From 64d7b5536641f84813239f1a249f9f570007fb28 Mon Sep 17 00:00:00 2001 From: halx99 Date: Fri, 31 Dec 2021 11:00:35 +0800 Subject: [PATCH] Update ci branch name --- .appveyor.yml | 42 + .github/workflows/android-ci.yml | 11 +- .github/workflows/clang-format.yml | 8 +- .github/workflows/genbindings-ci.yml | 36 - .github/workflows/ios-ci.yml | 11 +- .github/workflows/linux-ci.yml | 12 +- .github/workflows/osx-ci.yml | 11 +- .github/workflows/pr-ci.yml | 31 +- .github/workflows/windows-ci.yml | 4 +- README.md | 15 +- README_CN.md | 12 +- cocos/2d/CCActionTiledGrid.cpp | 2 +- cocos/2d/CCActionTween.cpp | 4 +- cocos/2d/CCActionTween.h | 6 +- cocos/2d/CCAnimation.cpp | 2 +- cocos/2d/CCAnimation.h | 2 +- cocos/2d/CCAnimationCache.cpp | 14 +- cocos/2d/CCAnimationCache.h | 12 +- cocos/2d/CCAtlasNode.cpp | 6 +- cocos/2d/CCAtlasNode.h | 4 +- cocos/2d/CCAutoPolygon.cpp | 4 +- cocos/2d/CCAutoPolygon.h | 8 +- cocos/2d/CCCameraBackgroundBrush.cpp | 24 +- cocos/2d/CCCameraBackgroundBrush.h | 24 +- cocos/2d/CCComponent.h | 4 +- cocos/2d/CCComponentContainer.cpp | 6 +- cocos/2d/CCComponentContainer.h | 6 +- cocos/2d/CCFastTMXLayer.cpp | 2 +- cocos/2d/CCFastTMXLayer.h | 6 +- cocos/2d/CCFastTMXTiledMap.cpp | 14 +- cocos/2d/CCFastTMXTiledMap.h | 16 +- cocos/2d/CCFontAtlas.cpp | 4 +- cocos/2d/CCFontAtlas.h | 2 +- cocos/2d/CCFontAtlasCache.cpp | 32 +- cocos/2d/CCFontAtlasCache.h | 20 +- cocos/2d/CCFontCharMap.cpp | 4 +- cocos/2d/CCFontCharMap.h | 4 +- cocos/2d/CCFontFNT.cpp | 30 +- cocos/2d/CCFontFNT.h | 25 +- cocos/2d/CCFontFreeType.cpp | 2 +- cocos/2d/CCFontFreeType.h | 4 +- cocos/2d/CCLabel.cpp | 55 +- cocos/2d/CCLabel.h | 64 +- cocos/2d/CCLabelAtlas.cpp | 26 +- cocos/2d/CCLabelAtlas.h | 18 +- cocos/2d/CCLabelTextFormatter.cpp | 10 +- cocos/2d/CCMenu.cpp | 2 +- cocos/2d/CCMenu.h | 2 +- cocos/2d/CCMenuItem.cpp | 54 +- cocos/2d/CCMenuItem.h | 54 +- cocos/2d/CCMotionStreak.cpp | 8 +- cocos/2d/CCMotionStreak.h | 4 +- cocos/2d/CCNode.cpp | 44 +- cocos/2d/CCNode.h | 36 +- cocos/2d/CCParallaxNode.cpp | 2 +- cocos/2d/CCParallaxNode.h | 2 +- cocos/2d/CCParticleBatchNode.cpp | 10 +- cocos/2d/CCParticleBatchNode.h | 10 +- cocos/2d/CCParticleSystem.cpp | 17 +- cocos/2d/CCParticleSystem.h | 8 +- cocos/2d/CCParticleSystemQuad.cpp | 2 +- cocos/2d/CCParticleSystemQuad.h | 2 +- cocos/2d/CCPlistSpriteSheetLoader.cpp | 112 +- cocos/2d/CCPlistSpriteSheetLoader.h | 16 +- cocos/2d/CCRenderTexture.cpp | 22 +- cocos/2d/CCRenderTexture.h | 23 +- cocos/2d/CCScene.h | 2 +- cocos/2d/CCSprite.cpp | 22 +- cocos/2d/CCSprite.h | 22 +- cocos/2d/CCSpriteBatchNode.cpp | 6 +- cocos/2d/CCSpriteBatchNode.h | 6 +- cocos/2d/CCSpriteFrame.cpp | 8 +- cocos/2d/CCSpriteFrame.h | 8 +- cocos/2d/CCSpriteFrameCache.cpp | 46 +- cocos/2d/CCSpriteFrameCache.h | 57 +- cocos/2d/CCSpriteSheetLoader.h | 28 +- cocos/2d/CCTMXObjectGroup.cpp | 4 +- cocos/2d/CCTMXObjectGroup.h | 8 +- cocos/2d/CCTMXXMLParser.cpp | 33 +- cocos/2d/CCTMXXMLParser.h | 24 +- cocos/2d/CCTextFieldTTF.cpp | 30 +- cocos/2d/CCTextFieldTTF.h | 28 +- cocos/2d/CCTileMapAtlas.cpp | 6 +- cocos/2d/CCTileMapAtlas.h | 6 +- cocos/3d/CCAnimate3D.cpp | 16 +- cocos/3d/CCAnimation3D.cpp | 20 +- cocos/3d/CCAnimation3D.h | 16 +- cocos/3d/CCBillBoard.cpp | 4 +- cocos/3d/CCBillBoard.h | 4 +- cocos/3d/CCBundle3D.cpp | 50 +- cocos/3d/CCBundle3D.h | 30 +- cocos/3d/CCBundle3DData.h | 14 +- cocos/3d/CCMesh.cpp | 8 +- cocos/3d/CCMesh.h | 10 +- cocos/3d/CCMeshSkin.cpp | 2 +- cocos/3d/CCMeshSkin.h | 4 +- cocos/3d/CCMeshVertexIndexData.cpp | 4 +- cocos/3d/CCMeshVertexIndexData.h | 8 +- cocos/3d/CCMotionStreak3D.cpp | 4 +- cocos/3d/CCMotionStreak3D.h | 8 +- cocos/3d/CCObjLoader.cpp | 8 +- cocos/3d/CCObjLoader.h | 6 +- cocos/3d/CCSkeleton3D.cpp | 6 +- cocos/3d/CCSkeleton3D.h | 8 +- cocos/3d/CCSkybox.cpp | 24 +- cocos/3d/CCSkybox.h | 24 +- cocos/3d/CCSprite3D.cpp | 38 +- cocos/3d/CCSprite3D.h | 41 +- cocos/3d/CCSprite3DMaterial.cpp | 8 +- cocos/3d/CCSprite3DMaterial.h | 10 +- cocos/3d/CCTerrain.cpp | 26 +- cocos/3d/CCTerrain.h | 20 +- cocos/3d/CCVertexAttribBinding.cpp | 9 +- cocos/3d/CCVertexAttribBinding.h | 6 +- cocos/CMakeLists.txt | 28 +- cocos/adxe.cpp | 2 +- cocos/audio/include/AudioDecoder.h | 2 +- cocos/audio/include/AudioDecoderEXT.h | 2 +- cocos/audio/include/AudioDecoderManager.h | 2 +- cocos/audio/include/AudioDecoderMp3.h | 2 +- cocos/audio/include/AudioDecoderOgg.h | 2 +- cocos/audio/include/AudioDecoderWav.h | 2 +- cocos/audio/include/AudioEngine.h | 16 +- cocos/audio/include/AudioEngineImpl.h | 10 +- cocos/audio/include/AudioPlayer.h | 2 +- cocos/audio/src/AudioDecoderEXT.mm | 333 +- cocos/audio/src/AudioDecoderManager.cpp | 2 +- cocos/audio/src/AudioDecoderMp3.cpp | 2 +- cocos/audio/src/AudioDecoderOgg.cpp | 2 +- cocos/audio/src/AudioDecoderWav.cpp | 4 +- cocos/audio/src/AudioEngine.cpp | 22 +- cocos/audio/src/AudioEngineImpl.mm | 351 +- cocos/base/CCAutoreleasePool.cpp | 2 +- cocos/base/CCAutoreleasePool.h | 2 +- cocos/base/CCConfiguration.cpp | 14 +- cocos/base/CCConfiguration.h | 8 +- cocos/base/CCConsole.cpp | 120 +- cocos/base/CCConsole.h | 106 +- cocos/base/CCController-android.cpp | 14 +- cocos/base/CCController-apple.mm | 482 ++- cocos/base/CCController-linux-win32.cpp | 12 +- cocos/base/CCController.h | 2 +- cocos/base/CCEventCustom.cpp | 3 +- cocos/base/CCEventCustom.h | 4 +- cocos/base/CCEventDispatcher.cpp | 27 +- cocos/base/CCEventDispatcher.h | 24 +- cocos/base/CCEventListener.cpp | 2 +- cocos/base/CCEventListener.h | 4 +- cocos/base/CCEventListenerCustom.cpp | 4 +- cocos/base/CCEventListenerCustom.h | 4 +- cocos/base/CCIMEDelegate.h | 2 +- cocos/base/CCIMEDispatcher.cpp | 2 +- cocos/base/CCIMEDispatcher.h | 2 +- cocos/base/CCMap.h | 72 +- cocos/base/CCNS.cpp | 22 +- cocos/base/CCNS.h | 6 +- cocos/base/CCNinePatchImageParser.cpp | 2 +- cocos/base/CCNinePatchImageParser.h | 2 +- cocos/base/CCProperties.cpp | 22 +- cocos/base/CCProperties.h | 8 +- cocos/base/CCProtocols.h | 2 +- cocos/base/CCScheduler.cpp | 10 +- cocos/base/CCScheduler.h | 12 +- cocos/base/CCScriptSupport.h | 2 +- cocos/base/CCUserDefault.cpp | 12 +- cocos/base/CCUserDefault.h | 14 +- cocos/base/CCValue.cpp | 6 +- cocos/base/CCValue.h | 13 +- cocos/base/ObjectFactory.cpp | 12 +- cocos/base/ObjectFactory.h | 8 +- cocos/base/ZipUtils.cpp | 41 +- cocos/base/ZipUtils.h | 18 +- cocos/base/ccUTF8.cpp | 16 +- cocos/base/ccUTF8.h | 10 +- cocos/base/ccUtils.cpp | 10 +- cocos/base/ccUtils.h | 10 +- cocos/base/hlookup.h | 64 - cocos/math/CCMathBase.h | 6 +- cocos/navmesh/CCNavMesh.cpp | 4 +- cocos/navmesh/CCNavMesh.h | 4 +- cocos/navmesh/CCNavMeshAgent.cpp | 2 +- cocos/navmesh/CCNavMeshAgent.h | 2 +- cocos/navmesh/CCNavMeshObstacle.cpp | 2 +- cocos/navmesh/CCNavMeshObstacle.h | 2 +- cocos/network/CCDownloader-curl.cpp | 8 +- cocos/network/CCDownloader.cpp | 26 +- cocos/network/CCDownloader.h | 27 +- cocos/network/CCIDownloaderImpl.h | 2 +- cocos/network/HttpClient.cpp | 16 +- cocos/network/HttpClient.h | 10 +- cocos/network/HttpCookie.cpp | 6 +- cocos/network/HttpCookie.h | 4 +- cocos/network/HttpRequest.h | 6 +- cocos/network/HttpResponse.h | 2 +- cocos/network/Uri.cpp | 6 +- cocos/network/Uri.h | 24 +- cocos/physics3d/CCPhysicsSprite3D.cpp | 4 +- cocos/physics3d/CCPhysicsSprite3D.h | 4 +- cocos/platform/CCApplicationProtocol.h | 2 +- cocos/platform/CCFileStream.h | 2 +- cocos/platform/CCFileUtils.cpp | 864 +++-- cocos/platform/CCFileUtils.h | 137 +- cocos/platform/CCGLView.cpp | 4 +- cocos/platform/CCGLView.h | 8 +- cocos/platform/CCImage.cpp | 12 +- cocos/platform/CCImage.h | 10 +- cocos/platform/CCPlatformMacros.h | 1 - cocos/platform/CCPosixFileStream.cpp | 4 +- cocos/platform/CCPosixFileStream.h | 4 +- cocos/platform/CCSAXParser.cpp | 2 +- cocos/platform/CCSAXParser.h | 2 +- cocos/platform/CMakeLists.txt | 8 - .../android/CCApplication-android.cpp | 4 +- .../platform/android/CCApplication-android.h | 2 +- cocos/platform/android/CCDevice-android.cpp | 2 +- .../platform/android/CCFileUtils-android.cpp | 43 +- cocos/platform/android/CCFileUtils-android.h | 14 +- .../platform/android/CCGLViewImpl-android.cpp | 10 +- cocos/platform/android/CCGLViewImpl-android.h | 10 +- cocos/platform/android/CMakeLists.txt | 26 + .../platform/android/javaactivity-android.cpp | 5 +- .../Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp | 2 +- .../Java_org_cocos2dx_lib_Cocos2dxHelper.cpp | 7 +- ...Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp | 2 +- cocos/platform/android/jni/JniHelper.cpp | 11 +- cocos/platform/android/jni/JniHelper.h | 121 +- cocos/platform/apple/CCDevice-apple.mm | 83 +- cocos/platform/apple/CCFileUtils-apple.h | 16 +- cocos/platform/apple/CCFileUtils-apple.mm | 126 +- .../platform/desktop/CCGLViewImpl-desktop.cpp | 47 +- cocos/platform/desktop/CCGLViewImpl-desktop.h | 20 +- cocos/platform/ios/CCApplication-ios.h | 2 +- cocos/platform/ios/CCApplication-ios.mm | 54 +- cocos/platform/ios/CCCommon-ios.mm | 19 +- cocos/platform/ios/CCDevice-ios.mm | 513 ++- cocos/platform/ios/CCDirectorCaller-ios.mm | 66 +- cocos/platform/ios/CCEAGLView-ios.mm | 631 ++-- cocos/platform/ios/CCES2Renderer-ios.h | 2 +- cocos/platform/ios/CCES2Renderer-ios.m | 2 +- cocos/platform/ios/CCESRenderer-ios.h | 2 +- cocos/platform/ios/CCGLViewImpl-ios.h | 10 +- cocos/platform/ios/CCGLViewImpl-ios.mm | 119 +- cocos/platform/ios/CCImage-ios.mm | 74 +- cocos/platform/ios/CCInputView-ios.mm | 137 +- cocos/platform/linux/CCApplication-linux.cpp | 6 +- cocos/platform/linux/CCApplication-linux.h | 6 +- cocos/platform/linux/CCFileUtils-linux.cpp | 16 +- cocos/platform/linux/CCFileUtils-linux.h | 2 +- cocos/platform/mac/CCApplication-mac.h | 6 +- cocos/platform/mac/CCApplication-mac.mm | 89 +- cocos/platform/mac/CCCommon-mac.mm | 12 +- cocos/platform/mac/CCDevice-mac.mm | 418 ++- cocos/platform/mac/CCGLViewImpl-mac.h | 18 +- cocos/platform/mac/CCGLViewImpl-mac.mm | 598 ++-- cocos/platform/win32/CCApplication-win32.cpp | 8 +- cocos/platform/win32/CCApplication-win32.h | 10 +- cocos/platform/win32/CCFileUtils-win32.cpp | 186 +- cocos/platform/win32/CCFileUtils-win32.h | 47 +- cocos/renderer/CCMaterial.cpp | 12 +- cocos/renderer/CCMaterial.h | 10 +- cocos/renderer/CCPass.h | 4 +- cocos/renderer/CCRenderState.cpp | 22 +- cocos/renderer/CCRenderState.h | 2 +- cocos/renderer/CCTechnique.cpp | 2 +- cocos/renderer/CCTechnique.h | 2 +- cocos/renderer/CCTexture2D.cpp | 4 +- cocos/renderer/CCTexture2D.h | 2 +- cocos/renderer/CCTextureAtlas.cpp | 6 +- cocos/renderer/CCTextureAtlas.h | 4 +- cocos/renderer/CCTextureCache.cpp | 58 +- cocos/renderer/CCTextureCache.h | 30 +- cocos/renderer/CCTextureCube.cpp | 26 +- cocos/renderer/CCTextureCube.h | 24 +- cocos/renderer/backend/Device.h | 4 +- cocos/renderer/backend/Program.cpp | 2 +- cocos/renderer/backend/Program.h | 14 +- cocos/renderer/backend/ProgramState.cpp | 6 +- cocos/renderer/backend/ProgramState.h | 16 +- cocos/renderer/backend/ShaderCache.cpp | 8 +- cocos/renderer/backend/ShaderCache.h | 6 +- cocos/renderer/backend/VertexLayout.cpp | 8 +- cocos/renderer/backend/VertexLayout.h | 8 +- cocos/renderer/backend/metal/BufferMTL.mm | 12 +- cocos/renderer/backend/metal/BufferManager.mm | 2 +- .../backend/metal/CommandBufferMTL.mm | 476 ++- .../backend/metal/DepthStencilStateMTL.mm | 168 +- cocos/renderer/backend/metal/DeviceInfoMTL.mm | 652 ++-- cocos/renderer/backend/metal/DeviceMTL.h | 4 +- cocos/renderer/backend/metal/DeviceMTL.mm | 44 +- cocos/renderer/backend/metal/ProgramMTL.h | 11 +- cocos/renderer/backend/metal/ProgramMTL.mm | 104 +- .../backend/metal/RenderPipelineMTL.mm | 363 +- .../renderer/backend/metal/RenderTargetMTL.mm | 122 +- .../renderer/backend/metal/ShaderModuleMTL.h | 14 +- .../renderer/backend/metal/ShaderModuleMTL.mm | 154 +- cocos/renderer/backend/metal/TextureMTL.mm | 277 +- cocos/renderer/backend/metal/UtilsMTL.mm | 182 +- cocos/renderer/backend/opengl/DeviceGL.cpp | 4 +- cocos/renderer/backend/opengl/DeviceGL.h | 4 +- .../renderer/backend/opengl/DeviceInfoGL.cpp | 2 +- cocos/renderer/backend/opengl/DeviceInfoGL.h | 2 +- cocos/renderer/backend/opengl/ProgramGL.cpp | 20 +- cocos/renderer/backend/opengl/ProgramGL.h | 15 +- .../backend/opengl/ShaderModuleGL.cpp | 8 +- .../renderer/backend/opengl/ShaderModuleGL.h | 4 +- cocos/renderer/shaders/label_sdf.frag | 52 - cocos/ui/CMakeLists.txt | 29 +- cocos/ui/UIAbstractCheckButton.cpp | 30 +- cocos/ui/UIAbstractCheckButton.h | 30 +- cocos/ui/UIButton.cpp | 36 +- cocos/ui/UIButton.h | 38 +- cocos/ui/UICheckBox.cpp | 12 +- cocos/ui/UICheckBox.h | 14 +- cocos/ui/UIEditBox/Mac/CCUIEditBoxMac.mm | 254 +- cocos/ui/UIEditBox/UIEditBox.cpp | 28 +- cocos/ui/UIEditBox/UIEditBox.h | 36 +- cocos/ui/UIEditBox/UIEditBoxImpl-android.cpp | 10 +- cocos/ui/UIEditBox/UIEditBoxImpl-common.cpp | 6 +- cocos/ui/UIEditBox/UIEditBoxImpl-common.h | 6 +- cocos/ui/UIEditBox/UIEditBoxImpl-ios.mm | 124 +- cocos/ui/UIEditBox/UIEditBoxImpl-mac.mm | 117 +- cocos/ui/UIEditBox/iOS/CCUIEditBoxIOS.mm | 410 ++- .../UIEditBox/iOS/CCUIMultilineTextField.mm | 80 +- .../UIEditBox/iOS/CCUISingleLineTextField.mm | 32 +- .../iOS/UITextField+CCUITextInput.mm | 54 +- .../UIEditBox/iOS/UITextView+CCUITextInput.mm | 66 +- cocos/ui/UIHelper.cpp | 10 +- cocos/ui/UIHelper.h | 4 +- cocos/ui/UIImageView.cpp | 6 +- cocos/ui/UIImageView.h | 6 +- cocos/ui/UILayout.cpp | 4 +- cocos/ui/UILayout.h | 4 +- cocos/ui/UILayoutManager.cpp | 2 +- cocos/ui/UILayoutParameter.cpp | 8 +- cocos/ui/UILayoutParameter.h | 8 +- cocos/ui/UIListView.cpp | 2 +- cocos/ui/UIListView.h | 2 +- cocos/ui/UILoadingBar.cpp | 6 +- cocos/ui/UILoadingBar.h | 6 +- cocos/ui/UIPageView.cpp | 2 +- cocos/ui/UIPageView.h | 2 +- cocos/ui/UIPageViewIndicator.cpp | 2 +- cocos/ui/UIPageViewIndicator.h | 3 +- cocos/ui/UIRadioButton.cpp | 12 +- cocos/ui/UIRadioButton.h | 14 +- cocos/ui/UIRichText.cpp | 97 +- cocos/ui/UIRichText.h | 82 +- cocos/ui/UIScale9Sprite.cpp | 24 +- cocos/ui/UIScale9Sprite.h | 24 +- cocos/ui/UIScrollView.cpp | 4 +- cocos/ui/UIScrollView.h | 4 +- cocos/ui/UISlider.cpp | 20 +- cocos/ui/UISlider.h | 22 +- cocos/ui/UITabControl.cpp | 32 +- cocos/ui/UITabControl.h | 26 +- cocos/ui/UIText.cpp | 10 +- cocos/ui/UIText.h | 10 +- cocos/ui/UITextAtlas.cpp | 14 +- cocos/ui/UITextAtlas.h | 14 +- cocos/ui/UITextBMFont.cpp | 8 +- cocos/ui/UITextBMFont.h | 8 +- cocos/ui/UITextField.cpp | 24 +- cocos/ui/UITextField.h | 20 +- cocos/ui/UITextFieldEx.cpp | 30 +- cocos/ui/UITextFieldEx.h | 22 +- cocos/ui/UIVideoPlayer-android.cpp | 12 +- cocos/ui/UIVideoPlayer-ios.mm | 263 +- cocos/ui/UIVideoPlayer.h | 8 +- cocos/ui/UIWebView/UIWebView-inl.h | 22 +- cocos/ui/UIWebView/UIWebView.h | 32 +- cocos/ui/UIWebView/UIWebView.mm | 8 +- cocos/ui/UIWebView/UIWebViewImpl-android.cpp | 50 +- cocos/ui/UIWebView/UIWebViewImpl-android.h | 28 +- cocos/ui/UIWebView/UIWebViewImpl-ios.h | 20 +- cocos/ui/UIWebView/UIWebViewImpl-ios.mm | 412 +-- cocos/ui/UIWebView/UIWebViewImpl-win32.cpp | 112 +- cocos/ui/UIWebView/UIWebViewImpl-win32.h | 18 +- cocos/ui/UIWidget.h | 8 +- extensions/DragonBones/CCArmatureDisplay.cpp | 9 +- extensions/DragonBones/CCArmatureDisplay.h | 11 +- extensions/DragonBones/CCFactory.cpp | 16 +- extensions/DragonBones/CCFactory.h | 26 +- .../DragonBones/animation/Animation.cpp | 34 +- extensions/DragonBones/animation/Animation.h | 34 +- .../DragonBones/animation/AnimationState.cpp | 20 +- .../DragonBones/animation/AnimationState.h | 12 +- extensions/DragonBones/armature/Armature.cpp | 8 +- extensions/DragonBones/armature/Armature.h | 10 +- extensions/DragonBones/armature/Bone.h | 4 +- extensions/DragonBones/armature/Constraint.h | 4 +- extensions/DragonBones/armature/Slot.h | 4 +- extensions/DragonBones/core/DragonBones.h | 9 +- .../DragonBones/event/IEventDispatcher.h | 10 +- .../DragonBones/factory/BaseFactory.cpp | 52 +- extensions/DragonBones/factory/BaseFactory.h | 62 +- .../DragonBones/model/AnimationConfig.cpp | 14 +- .../DragonBones/model/AnimationConfig.h | 8 +- extensions/DragonBones/model/AnimationData.h | 22 +- extensions/DragonBones/model/ArmatureData.cpp | 8 +- extensions/DragonBones/model/ArmatureData.h | 28 +- .../DragonBones/model/DragonBonesData.h | 7 +- extensions/DragonBones/model/SkinData.cpp | 6 +- extensions/DragonBones/model/SkinData.h | 13 +- .../DragonBones/model/TextureAtlasData.h | 6 +- extensions/DragonBones/parser/DataParser.cpp | 26 +- extensions/DragonBones/parser/DataParser.h | 14 +- .../DragonBones/parser/JSONDataParser.h | 18 +- .../CCControlExtension/CCControlButton.cpp | 16 +- .../GUI/CCControlExtension/CCControlButton.h | 18 +- .../CCControlExtension/CCControlSwitch.cpp | 4 +- extensions/GUI/CCScrollView/CCScrollView.cpp | 4 +- extensions/GUI/CCScrollView/CCScrollView.h | 4 +- extensions/ImGuiEXT/CCImGuiEXT.cpp | 24 +- extensions/ImGuiEXT/CCImGuiEXT.h | 18 +- extensions/ImGuiEXT/imgui/imconfig.h | 48 +- extensions/ImGuiEXT/imgui/imgui.cpp | 4 +- extensions/ImGuiEXT/imgui/imgui.h | 6 +- extensions/ImGuiEXT/imgui/imgui_demo.cpp | 2 +- extensions/ImGuiEXT/imgui/imgui_draw.cpp | 2 +- extensions/ImGuiEXT/imgui/imgui_tables.cpp | 2 +- extensions/ImGuiEXT/imgui/imgui_widgets.cpp | 2 +- extensions/Particle3D/CCParticle3DRender.cpp | 6 +- extensions/Particle3D/CCParticle3DRender.h | 6 +- extensions/Particle3D/PU/CCPUAffector.cpp | 10 +- extensions/Particle3D/PU/CCPUAffector.h | 12 +- .../Particle3D/PU/CCPUAffectorManager.cpp | 4 +- .../Particle3D/PU/CCPUAffectorManager.h | 4 +- extensions/Particle3D/PU/CCPUBeamRender.cpp | 2 +- extensions/Particle3D/PU/CCPUBeamRender.h | 2 +- extensions/Particle3D/PU/CCPUBehaviour.h | 4 +- .../Particle3D/PU/CCPUBehaviourManager.cpp | 4 +- .../Particle3D/PU/CCPUBehaviourManager.h | 4 +- .../Particle3D/PU/CCPUBillboardChain.cpp | 6 +- extensions/Particle3D/PU/CCPUBillboardChain.h | 16 +- .../PU/CCPUDoAffectorEventHandler.h | 4 +- .../PU/CCPUDoEnableComponentEventHandler.h | 4 +- .../CCPUDoPlacementParticleEventHandler.cpp | 2 +- .../PU/CCPUDoPlacementParticleEventHandler.h | 4 +- extensions/Particle3D/PU/CCPUEmitter.cpp | 2 +- extensions/Particle3D/PU/CCPUEmitter.h | 12 +- .../Particle3D/PU/CCPUEmitterManager.cpp | 4 +- extensions/Particle3D/PU/CCPUEmitterManager.h | 4 +- extensions/Particle3D/PU/CCPUEventHandler.h | 8 +- .../Particle3D/PU/CCPUEventHandlerManager.cpp | 4 +- .../Particle3D/PU/CCPUEventHandlerManager.h | 4 +- extensions/Particle3D/PU/CCPULineEmitter.cpp | 2 +- .../Particle3D/PU/CCPUMaterialManager.cpp | 35 +- .../Particle3D/PU/CCPUMaterialManager.h | 6 +- .../Particle3D/PU/CCPUMeshSurfaceEmitter.cpp | 19 +- .../Particle3D/PU/CCPUMeshSurfaceEmitter.h | 6 +- extensions/Particle3D/PU/CCPUObserver.cpp | 4 +- extensions/Particle3D/PU/CCPUObserver.h | 12 +- .../Particle3D/PU/CCPUObserverManager.cpp | 4 +- .../Particle3D/PU/CCPUObserverManager.h | 4 +- .../Particle3D/PU/CCPUParticleSystem3D.cpp | 66 +- .../Particle3D/PU/CCPUParticleSystem3D.h | 22 +- .../PU/CCPUParticleSystem3DTranslator.cpp | 5 +- extensions/Particle3D/PU/CCPURender.cpp | 25 +- extensions/Particle3D/PU/CCPURender.h | 14 +- extensions/Particle3D/PU/CCPURibbonTrail.cpp | 4 +- extensions/Particle3D/PU/CCPURibbonTrail.h | 12 +- .../Particle3D/PU/CCPURibbonTrailRender.cpp | 6 +- .../Particle3D/PU/CCPURibbonTrailRender.h | 2 +- .../Particle3D/PU/CCPUScriptCompiler.cpp | 30 +- extensions/Particle3D/PU/CCPUScriptCompiler.h | 18 +- extensions/Particle3D/PU/CCPUScriptLexer.cpp | 6 +- extensions/Particle3D/PU/CCPUScriptLexer.h | 4 +- .../Particle3D/PU/CCPUScriptTranslator.cpp | 8 +- .../Particle3D/PU/CCPUScriptTranslator.h | 10 +- extensions/Particle3D/PU/CCPUSlaveEmitter.cpp | 8 +- extensions/Particle3D/PU/CCPUSlaveEmitter.h | 8 +- .../Particle3D/PU/CCPUVertexEmitter.cpp | 6 +- extensions/Particle3D/PU/CCPUVertexEmitter.h | 4 +- extensions/assets-manager/AssetsManager.cpp | 10 +- extensions/assets-manager/AssetsManager.h | 2 +- extensions/assets-manager/AssetsManagerEx.cpp | 70 +- extensions/assets-manager/AssetsManagerEx.h | 53 +- .../assets-manager/CCEventAssetsManagerEx.cpp | 6 +- .../assets-manager/CCEventAssetsManagerEx.h | 14 +- extensions/assets-manager/Manifest.cpp | 60 +- extensions/assets-manager/Manifest.h | 43 +- .../ActionTimeline/CCActionTimeline.cpp | 8 +- .../ActionTimeline/CCActionTimeline.h | 16 +- .../ActionTimeline/CCActionTimelineCache.cpp | 35 +- .../ActionTimeline/CCActionTimelineCache.h | 28 +- .../cocostudio/ActionTimeline/CCBoneNode.cpp | 24 +- .../cocostudio/ActionTimeline/CCBoneNode.h | 6 +- .../cocostudio/ActionTimeline/CCFrame.cpp | 2 +- .../cocostudio/ActionTimeline/CCFrame.h | 12 +- .../ActionTimeline/CCSkeletonNode.cpp | 12 +- .../ActionTimeline/CCSkeletonNode.h | 14 +- .../cocostudio/ActionTimeline/CSLoader.cpp | 122 +- .../cocostudio/ActionTimeline/CSLoader.h | 50 +- extensions/cocostudio/CCActionNode.cpp | 15 +- extensions/cocostudio/CCActionNode.h | 8 +- extensions/cocostudio/CCActionObject.cpp | 10 +- extensions/cocostudio/CCActionObject.h | 8 +- extensions/cocostudio/CCArmature.cpp | 18 +- extensions/cocostudio/CCArmature.h | 22 +- extensions/cocostudio/CCArmatureAnimation.cpp | 14 +- extensions/cocostudio/CCArmatureAnimation.h | 21 +- .../cocostudio/CCArmatureDataManager.cpp | 68 +- extensions/cocostudio/CCArmatureDataManager.h | 58 +- extensions/cocostudio/CCBatchNode.cpp | 2 +- extensions/cocostudio/CCBatchNode.h | 4 +- extensions/cocostudio/CCBone.cpp | 8 +- extensions/cocostudio/CCBone.h | 8 +- extensions/cocostudio/CCComAttribute.cpp | 36 +- extensions/cocostudio/CCComAttribute.h | 18 +- extensions/cocostudio/CCComExtensionData.h | 4 +- extensions/cocostudio/CCComRender.cpp | 2 +- extensions/cocostudio/CCComRender.h | 4 +- extensions/cocostudio/CCDataReaderHelper.cpp | 48 +- extensions/cocostudio/CCDataReaderHelper.h | 14 +- extensions/cocostudio/CCDatas.cpp | 16 +- extensions/cocostudio/CCDatas.h | 16 +- extensions/cocostudio/CCDisplayManager.cpp | 4 +- extensions/cocostudio/CCDisplayManager.h | 4 +- extensions/cocostudio/CCSGUIReader.cpp | 34 +- extensions/cocostudio/CCSGUIReader.h | 30 +- extensions/cocostudio/CCSSceneReader.cpp | 10 +- extensions/cocostudio/CCSSceneReader.h | 10 +- extensions/cocostudio/CCSkin.cpp | 10 +- extensions/cocostudio/CCSkin.h | 12 +- .../cocostudio/CCSpriteFrameCacheHelper.cpp | 8 +- .../cocostudio/CCSpriteFrameCacheHelper.h | 12 +- extensions/cocostudio/CocosStudioExport.h | 2 - .../cocostudio/FlatBuffersSerialize.cpp | 24 +- extensions/cocostudio/FlatBuffersSerialize.h | 23 +- .../cocostudio/SpineSkeletonDataCache.h | 4 +- extensions/cocostudio/TriggerMng.cpp | 2 +- extensions/cocostudio/TriggerMng.h | 4 +- .../WidgetCallBackHandlerProtocol.cpp | 6 +- .../WidgetCallBackHandlerProtocol.h | 6 +- .../ArmatureNodeReader/ArmatureNodeReader.cpp | 6 +- .../ArmatureNodeReader/ArmatureNodeReader.h | 4 +- .../ImageViewReader/ImageViewReader.cpp | 2 +- .../WidgetReader/NodeReaderProtocol.cpp | 16 +- .../WidgetReader/NodeReaderProtocol.h | 6 +- .../TextAtlasReader/TextAtlasReader.cpp | 4 +- .../TextBMFontReader/TextBMFontReader.cpp | 4 +- .../TextFieldReader/TextFieldReader.cpp | 6 +- .../WidgetReader/TextReader/TextReader.cpp | 8 +- .../cocostudio/WidgetReader/WidgetReader.cpp | 29 +- .../cocostudio/WidgetReader/WidgetReader.h | 12 +- extensions/fairygui/GTextInput.cpp | 2 +- extensions/fairygui/GTextInput.h | 2 +- extensions/fairygui/ScrollPane.cpp | 4 +- extensions/fairygui/UIPackage.cpp | 12 +- extensions/fairygui/UIPackage.h | 4 +- extensions/fairygui/display/FUIContainer.cpp | 10 - extensions/fairygui/display/FUIContainer.h | 1 - extensions/fairygui/display/FUILabel.cpp | 2 +- extensions/fairygui/display/FUILabel.h | 2 +- extensions/fairygui/display/FUIRichText.cpp | 2 +- .../auto/lua_cocos2dx_3d_auto.cpp | 192 +- .../auto/lua_cocos2dx_audioengine_auto.cpp | 32 +- .../lua-bindings/auto/lua_cocos2dx_auto.cpp | 1944 +++++------ .../lua-bindings/auto/lua_cocos2dx_auto.hpp | 4 - .../auto/lua_cocos2dx_backend_auto.cpp | 54 +- .../auto/lua_cocos2dx_controller_auto.cpp | 4 +- .../auto/lua_cocos2dx_csloader_auto.cpp | 36 +- .../auto/lua_cocos2dx_extension_auto.cpp | 136 +- .../auto/lua_cocos2dx_navmesh_auto.cpp | 16 +- .../auto/lua_cocos2dx_physics_auto.cpp | 64 +- .../auto/lua_cocos2dx_studio_auto.cpp | 370 +-- .../auto/lua_cocos2dx_ui_auto.cpp | 1384 ++++---- .../auto/lua_cocos2dx_video_auto.cpp | 16 +- .../auto/lua_cocos2dx_webview_auto.cpp | 32 +- .../lua-bindings/manual/CCComponentLua.cpp | 36 +- .../lua-bindings/manual/CCComponentLua.h | 6 +- .../lua-bindings/manual/CCLuaEngine.cpp | 4 +- .../lua-bindings/manual/CCLuaEngine.h | 2 +- .../lua-bindings/manual/CCLuaStack.cpp | 14 +- .../lua-bindings/manual/CCLuaStack.h | 2 +- .../lua-bindings/manual/CCLuaValue.cpp | 6 +- .../lua-bindings/manual/CCLuaValue.h | 8 +- .../manual/LuaBasicConversions.cpp | 65 +- .../lua-bindings/manual/LuaBasicConversions.h | 18 +- .../lua_cocos2dx_audioengine_manual.cpp | 4 +- .../manual/cocos2d/lua_cocos2dx_manual.cpp | 12 +- .../manual/cocos2d/lua_cocos2dx_manual.hpp | 2 +- .../manual/cocostudio/CustomGUIReader.cpp | 4 +- .../manual/cocostudio/CustomGUIReader.h | 2 +- .../lua_cocos2dx_coco_studio_manual.cpp | 29 +- .../lua_cocos2dx_coco_studio_manual.hpp | 4 +- .../manual/network/lua_downloader.cpp | 35 +- .../manual/network/lua_xml_http_request.cpp | 13 +- .../manual/platform/ios/CCLuaObjcBridge.mm | 177 +- .../manual/ui/lua_cocos2dx_webview_manual.cpp | 32 +- templates/cpp-template-default/CMakeLists.txt | 7 +- .../Classes/AppDelegate.cpp | 62 +- .../Classes/AppDelegate.h | 15 +- .../Classes/HelloWorldScene.cpp | 6 +- .../Classes/HelloWorldScene.h | 8 +- .../proj.android/app/jni/hellocpp/main.cpp | 18 +- .../proj.ios_mac/ios/AppController.h | 10 +- .../proj.ios_mac/ios/AppController.mm | 87 +- .../proj.ios_mac/ios/RootViewController.h | 4 +- .../proj.ios_mac/ios/RootViewController.mm | 60 +- .../proj.ios_mac/mac/main.cpp | 10 +- .../cpp-template-default/proj.linux/main.cpp | 10 +- .../cpp-template-default/proj.win32/main.cpp | 13 +- .../cpp-template-default/proj.win32/main.h | 12 +- .../proj.win32/resource.h | 28 +- templates/lua-template-default/CMakeLists.txt | 7 +- .../runtime-src/Classes/AppDelegate.cpp | 34 +- .../runtime-src/Classes/AppDelegate.h | 8 +- .../proj.android/app/jni/hellolua/main.cpp | 18 +- .../proj.ios_mac/ios/AppController.h | 10 +- .../proj.ios_mac/ios/AppController.mm | 85 +- .../proj.ios_mac/ios/RootViewController.h | 4 +- .../proj.ios_mac/ios/RootViewController.mm | 60 +- .../runtime-src/proj.ios_mac/mac/main.cpp | 3 +- .../runtime-src/proj.linux/main.cpp | 10 +- .../runtime-src/proj.win32/main.cpp | 13 +- .../frameworks/runtime-src/proj.win32/main.h | 11 +- tests/cpp-tests/CMakeLists.txt | 8 +- .../ActionManagerTest/ActionManagerTest.cpp | 147 +- .../ActionManagerTest/ActionManagerTest.h | 21 +- .../ActionsEaseTest/ActionsEaseTest.cpp | 663 ++-- .../Classes/ActionsEaseTest/ActionsEaseTest.h | 12 +- .../ActionsProgressTest.cpp | 112 +- .../ActionsProgressTest/ActionsProgressTest.h | 2 +- .../Classes/ActionsTest/ActionsTest.cpp | 1241 +++---- .../Classes/ActionsTest/ActionsTest.h | 46 +- tests/cpp-tests/Classes/AppDelegate.cpp | 41 +- tests/cpp-tests/Classes/AppDelegate.h | 9 +- tests/cpp-tests/Classes/BaseTest.cpp | 149 +- tests/cpp-tests/Classes/BaseTest.h | 77 +- .../Classes/BillBoardTest/BillBoardTest.cpp | 179 +- .../Classes/BillBoardTest/BillBoardTest.h | 29 +- .../cpp-tests/Classes/Box2DTest/Box2dTest.cpp | 91 +- tests/cpp-tests/Classes/Box2DTest/Box2dTest.h | 11 +- .../Classes/Box2DTestBed/Box2DTestBed.cpp | 275 +- .../Classes/Box2DTestBed/Box2DTestBed.h | 73 +- tests/cpp-tests/Classes/Box2DTestBed/Test.cpp | 709 ++-- .../Classes/Box2DTestBed/tests/add_pair.cpp | 72 +- .../Box2DTestBed/tests/apply_force.cpp | 264 +- .../Classes/Box2DTestBed/tests/body_types.cpp | 209 +- .../Classes/Box2DTestBed/tests/box_stack.cpp | 220 +- .../Classes/Box2DTestBed/tests/breakable.cpp | 202 +- .../Classes/Box2DTestBed/tests/bridge.cpp | 156 +- .../Box2DTestBed/tests/bullet_test.cpp | 165 +- .../Classes/Box2DTestBed/tests/cantilever.cpp | 290 +- .../Classes/Box2DTestBed/tests/car.cpp | 404 +-- .../Classes/Box2DTestBed/tests/chain.cpp | 93 +- .../Box2DTestBed/tests/chain_problem.cpp | 15 +- .../tests/character_collision.cpp | 370 ++- .../Box2DTestBed/tests/circle_stack.cpp | 88 +- .../tests/collision_filtering.cpp | 219 +- .../tests/collision_processing.cpp | 250 +- .../Box2DTestBed/tests/compound_shapes.cpp | 307 +- .../Classes/Box2DTestBed/tests/confined.cpp | 225 +- .../Box2DTestBed/tests/continuous_test.cpp | 210 +- .../Box2DTestBed/tests/convex_hull.cpp | 128 +- .../Box2DTestBed/tests/conveyor_belt.cpp | 109 +- .../Box2DTestBed/tests/distance_joint.cpp | 149 +- .../Box2DTestBed/tests/distance_test.cpp | 169 +- .../Classes/Box2DTestBed/tests/dominos.cpp | 302 +- .../Box2DTestBed/tests/dump_loader.cpp | 81 +- .../Box2DTestBed/tests/dynamic_tree.cpp | 545 +-- .../Box2DTestBed/tests/edge_shapes.cpp | 349 +- .../Classes/Box2DTestBed/tests/edge_test.cpp | 381 ++- .../Classes/Box2DTestBed/tests/friction.cpp | 146 +- .../Classes/Box2DTestBed/tests/gear_joint.cpp | 245 +- .../Classes/Box2DTestBed/tests/heavy1.cpp | 48 +- .../Classes/Box2DTestBed/tests/heavy2.cpp | 70 +- .../Box2DTestBed/tests/mobile_balanced.cpp | 118 +- .../Box2DTestBed/tests/mobile_unbalanced.cpp | 114 +- .../Box2DTestBed/tests/motor_joint.cpp | 133 +- .../Classes/Box2DTestBed/tests/pinball.cpp | 223 +- .../Classes/Box2DTestBed/tests/platformer.cpp | 147 +- .../Box2DTestBed/tests/polygon_collision.cpp | 150 +- .../Box2DTestBed/tests/polygon_shapes.cpp | 368 ++- .../Box2DTestBed/tests/prismatic_joint.cpp | 134 +- .../Box2DTestBed/tests/pulley_joint.cpp | 98 +- .../Classes/Box2DTestBed/tests/pyramid.cpp | 97 +- .../Classes/Box2DTestBed/tests/ray_cast.cpp | 624 ++-- .../Box2DTestBed/tests/restitution.cpp | 70 +- .../Box2DTestBed/tests/revolute_joint.cpp | 205 +- .../Classes/Box2DTestBed/tests/rope.cpp | 404 +-- .../Classes/Box2DTestBed/tests/sensor.cpp | 250 +- .../Classes/Box2DTestBed/tests/settings.h | 103 +- .../Classes/Box2DTestBed/tests/shape_cast.cpp | 260 +- .../Box2DTestBed/tests/shape_editing.cpp | 127 +- .../Classes/Box2DTestBed/tests/skier.cpp | 210 +- .../Box2DTestBed/tests/slider_crank_1.cpp | 145 +- .../Box2DTestBed/tests/slider_crank_2.cpp | 204 +- .../Classes/Box2DTestBed/tests/test.h | 182 +- .../Box2DTestBed/tests/theo_jansen.cpp | 371 ++- .../Classes/Box2DTestBed/tests/tiles.cpp | 206 +- .../Box2DTestBed/tests/time_of_impact.cpp | 137 +- .../Classes/Box2DTestBed/tests/tumbler.cpp | 118 +- .../Classes/Box2DTestBed/tests/web.cpp | 325 +- .../Box2DTestBed/tests/wheel_joint.cpp | 143 +- .../Box2DTestBed/tests/wrecking_ball.cpp | 208 +- tests/cpp-tests/Classes/BugsTest/Bug-1159.cpp | 23 +- tests/cpp-tests/Classes/BugsTest/Bug-1159.h | 12 +- tests/cpp-tests/Classes/BugsTest/Bug-1174.cpp | 116 +- tests/cpp-tests/Classes/BugsTest/Bug-1174.h | 12 +- .../cpp-tests/Classes/BugsTest/Bug-12847.cpp | 29 +- tests/cpp-tests/Classes/BugsTest/Bug-12847.h | 17 +- .../cpp-tests/Classes/BugsTest/Bug-14327.cpp | 23 +- tests/cpp-tests/Classes/BugsTest/Bug-14327.h | 21 +- .../cpp-tests/Classes/BugsTest/Bug-15594.cpp | 23 +- tests/cpp-tests/Classes/BugsTest/Bug-15594.h | 10 +- .../cpp-tests/Classes/BugsTest/Bug-15776.cpp | 12 +- tests/cpp-tests/Classes/BugsTest/Bug-15776.h | 9 +- tests/cpp-tests/Classes/BugsTest/Bug-350.cpp | 14 +- tests/cpp-tests/Classes/BugsTest/Bug-350.h | 12 +- tests/cpp-tests/Classes/BugsTest/Bug-422.cpp | 25 +- tests/cpp-tests/Classes/BugsTest/Bug-422.h | 12 +- .../Classes/BugsTest/Bug-458/Bug-458.cpp | 28 +- .../Classes/BugsTest/Bug-458/Bug-458.h | 10 +- .../Bug-458/QuestionContainerSprite.cpp | 43 +- .../Bug-458/QuestionContainerSprite.h | 12 +- tests/cpp-tests/Classes/BugsTest/Bug-624.cpp | 39 +- tests/cpp-tests/Classes/BugsTest/Bug-624.h | 14 +- tests/cpp-tests/Classes/BugsTest/Bug-886.cpp | 12 +- tests/cpp-tests/Classes/BugsTest/Bug-886.h | 12 +- tests/cpp-tests/Classes/BugsTest/Bug-899.cpp | 10 +- tests/cpp-tests/Classes/BugsTest/Bug-899.h | 12 +- tests/cpp-tests/Classes/BugsTest/Bug-914.cpp | 34 +- tests/cpp-tests/Classes/BugsTest/Bug-914.h | 12 +- .../Classes/BugsTest/Bug-CCDrawNode.cpp | 10 +- .../Classes/BugsTest/Bug-CCDrawNode.h | 10 +- .../cpp-tests/Classes/BugsTest/Bug-Child.cpp | 75 +- tests/cpp-tests/Classes/BugsTest/Bug-Child.h | 25 +- tests/cpp-tests/Classes/BugsTest/BugsTest.cpp | 14 +- tests/cpp-tests/Classes/BugsTest/BugsTest.h | 10 +- .../Classes/Camera3DTest/Camera3DTest.cpp | 1140 +++---- .../Classes/Camera3DTest/Camera3DTest.h | 197 +- .../Classes/ChipmunkTest/ChipmunkTest.cpp | 119 +- .../Classes/ChipmunkTest/ChipmunkTest.h | 12 +- .../ChipmunkTestBed/ChipmunkTestBed.cpp | 1302 ++++---- .../Classes/ChipmunkTestBed/ChipmunkTestBed.h | 386 +-- .../Classes/ChipmunkTestBed/demo/Bench.c | 910 +++-- .../Classes/ChipmunkTestBed/demo/Buoyancy.c | 337 +- .../Classes/ChipmunkTestBed/demo/Chains.c | 211 +- .../ChipmunkTestBed/demo/ChipmunkDemo.h | 81 +- .../ChipmunkTestBed/demo/ContactGraph.c | 309 +- .../Classes/ChipmunkTestBed/demo/Convex.c | 154 +- .../Classes/ChipmunkTestBed/demo/Crane.c | 242 +- .../Classes/ChipmunkTestBed/demo/Example.c | 28 +- .../Classes/ChipmunkTestBed/demo/Joints.c | 490 +-- .../Classes/ChipmunkTestBed/demo/LogoSmash.c | 226 +- .../Classes/ChipmunkTestBed/demo/OneWay.c | 153 +- .../Classes/ChipmunkTestBed/demo/Planet.c | 161 +- .../Classes/ChipmunkTestBed/demo/Player.c | 217 +- .../Classes/ChipmunkTestBed/demo/Plink.c | 183 +- .../Classes/ChipmunkTestBed/demo/Pump.c | 273 +- .../ChipmunkTestBed/demo/PyramidStack.c | 22 +- .../ChipmunkTestBed/demo/PyramidTopple.c | 129 +- .../Classes/ChipmunkTestBed/demo/Query.c | 220 +- .../Classes/ChipmunkTestBed/demo/Shatter.c | 114 +- .../Classes/ChipmunkTestBed/demo/Slice.c | 284 +- .../Classes/ChipmunkTestBed/demo/Springies.c | 210 +- .../Classes/ChipmunkTestBed/demo/Sticky.c | 283 +- .../Classes/ChipmunkTestBed/demo/Tank.c | 188 +- .../Classes/ChipmunkTestBed/demo/TheoJansen.c | 229 +- .../Classes/ChipmunkTestBed/demo/Tumble.c | 197 +- .../Classes/ChipmunkTestBed/demo/Unicycle.c | 260 +- .../ClickAndMoveTest/ClickAndMoveTest.cpp | 57 +- .../ClickAndMoveTest/ClickAndMoveTest.h | 8 +- .../ClippingNodeTest/ClippingNodeTest.cpp | 397 +-- .../ClippingNodeTest/ClippingNodeTest.h | 54 +- .../ConfigurationTest/ConfigurationTest.cpp | 57 +- .../ConfigurationTest/ConfigurationTest.h | 12 +- .../Classes/ConsoleTest/ConsoleTest.cpp | 94 +- .../Classes/ConsoleTest/ConsoleTest.h | 6 +- tests/cpp-tests/Classes/CurlTest/CurlTest.cpp | 82 +- tests/cpp-tests/Classes/CurlTest/CurlTest.h | 12 +- .../CurrentLanguageTest.cpp | 19 +- .../CurrentLanguageTest/CurrentLanguageTest.h | 10 +- .../DataVisitorTest/DataVisitorTest.cpp | 70 +- .../Classes/DataVisitorTest/DataVisitorTest.h | 14 +- .../DrawPrimitivesTest/DrawPrimitivesTest.cpp | 213 +- .../DrawPrimitivesTest/DrawPrimitivesTest.h | 11 +- .../EffectsAdvancedTest.cpp | 201 +- .../EffectsAdvancedTest/EffectsAdvancedTest.h | 12 +- .../Classes/EffectsTest/EffectsTest.cpp | 196 +- .../Classes/EffectsTest/EffectsTest.h | 42 +- .../AssetsManagerExTest.cpp | 184 +- .../AssetsManagerExTest/AssetsManagerExTest.h | 12 +- .../Classes/ExtensionsTest/ExtensionsTest.cpp | 12 +- .../Classes/ExtensionsTest/ExtensionsTest.h | 8 +- .../TableViewTest/CustomTableViewCell.cpp | 34 +- .../TableViewTest/CustomTableViewCell.h | 11 +- .../TableViewTest/TableViewTestScene.cpp | 48 +- .../TableViewTest/TableViewTestScene.h | 32 +- .../Classes/FileUtilsTest/FileUtilsTest.cpp | 390 +-- .../Classes/FileUtilsTest/FileUtilsTest.h | 24 +- tests/cpp-tests/Classes/FontTest/FontTest.cpp | 284 +- tests/cpp-tests/Classes/FontTest/FontTest.h | 34 +- .../Classes/ImGuiEXTTest/ImGuiEXTTest.cpp | 17 +- .../Classes/ImGuiEXTTest/ImGuiEXTTest.h | 2 +- .../cpp-tests/Classes/InputTest/MouseTest.cpp | 70 +- tests/cpp-tests/Classes/InputTest/MouseTest.h | 19 +- .../Classes/IntervalTest/IntervalTest.cpp | 112 +- .../Classes/IntervalTest/IntervalTest.h | 22 +- tests/cpp-tests/Classes/JNITest/JNITest.cpp | 33 +- tests/cpp-tests/Classes/JNITest/JNITest.h | 14 +- .../Classes/LabelTest/LabelTestNew.cpp | 1284 +++---- .../Classes/LabelTest/LabelTestNew.h | 98 +- .../cpp-tests/Classes/LayerTest/LayerTest.cpp | 680 ++-- tests/cpp-tests/Classes/LayerTest/LayerTest.h | 33 +- .../cpp-tests/Classes/LightTest/LightTest.cpp | 135 +- tests/cpp-tests/Classes/LightTest/LightTest.h | 11 +- .../MaterialSystemTest/MaterialSystemTest.cpp | 161 +- .../MaterialSystemTest/MaterialSystemTest.h | 23 +- tests/cpp-tests/Classes/MenuTest/MenuTest.cpp | 435 +-- tests/cpp-tests/Classes/MenuTest/MenuTest.h | 20 +- .../MotionStreakTest/MotionStreakTest.cpp | 118 +- .../MotionStreakTest/MotionStreakTest.h | 20 +- .../Classes/MultiTouchTest/MultiTouchTest.cpp | 65 +- .../Classes/MultiTouchTest/MultiTouchTest.h | 16 +- .../Classes/NavMeshTest/NavMeshTest.cpp | 145 +- .../Classes/NavMeshTest/NavMeshTest.h | 65 +- .../DownloaderTest/DownloaderTest.cpp | 155 +- .../HttpClientTest/HttpClientTest.cpp | 189 +- .../HttpClientTest/HttpClientTest.h | 50 +- .../Classes/NetworkTest/NetworkTest.cpp | 11 +- .../Classes/NetworkTest/NetworkTest.h | 8 +- .../NewAudioEngineTest/NewAudioEngineTest.cpp | 830 +++-- .../NewAudioEngineTest/NewAudioEngineTest.h | 89 +- .../NewEventDispatcherTest.cpp | 908 ++--- .../NewEventDispatcherTest.h | 45 +- .../NewRendererTest/NewRendererTest.cpp | 454 +-- .../Classes/NewRendererTest/NewRendererTest.h | 90 +- tests/cpp-tests/Classes/NodeTest/NodeTest.cpp | 620 ++-- tests/cpp-tests/Classes/NodeTest/NodeTest.h | 11 +- .../Classes/OpenURLTest/OpenURLTest.cpp | 12 +- .../Classes/OpenURLTest/OpenURLTest.h | 13 +- .../Classes/ParallaxTest/ParallaxTest.cpp | 169 +- .../Classes/ParallaxTest/ParallaxTest.h | 28 +- .../Classes/Particle3DTest/Particle3DTest.cpp | 184 +- .../Classes/Particle3DTest/Particle3DTest.h | 40 +- .../Classes/ParticleTest/ParticleTest.cpp | 456 +-- .../Classes/ParticleTest/ParticleTest.h | 24 +- .../Classes/Physics3DTest/Physics3DTest.cpp | 313 +- .../Classes/Physics3DTest/Physics3DTest.h | 60 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 1502 +++++---- .../Classes/PhysicsTest/PhysicsTest.h | 103 +- .../ReleasePoolTest/ReleasePoolTest.cpp | 47 +- .../Classes/ReleasePoolTest/ReleasePoolTest.h | 12 +- .../RenderTextureTest/RenderTextureTest.cpp | 484 ++- .../RenderTextureTest/RenderTextureTest.h | 59 +- .../RotateWorldTest/RotateWorldTest.cpp | 104 +- .../Classes/RotateWorldTest/RotateWorldTest.h | 8 +- .../Classes/Scene3DTest/Scene3DTest.cpp | 495 +-- .../Classes/Scene3DTest/Scene3DTest.h | 8 +- .../cpp-tests/Classes/SceneTest/SceneTest.cpp | 97 +- tests/cpp-tests/Classes/SceneTest/SceneTest.h | 17 +- .../Classes/SchedulerTest/SchedulerTest.cpp | 434 +-- .../Classes/SchedulerTest/SchedulerTest.h | 81 +- .../Classes/ShaderTest/ShaderTest.cpp | 348 +- .../cpp-tests/Classes/ShaderTest/ShaderTest.h | 58 +- .../Classes/ShaderTest/ShaderTest.vsh.h | 19 +- .../Classes/ShaderTest/ShaderTest2.cpp | 283 +- .../Classes/ShaderTest/ShaderTest2.h | 26 +- .../Classes/ShaderTest/shaderTest.psh.h | 857 ++--- .../cpp-tests/Classes/SpineTest/SpineTest.cpp | 197 +- tests/cpp-tests/Classes/SpineTest/SpineTest.h | 54 +- .../Classes/Sprite3DTest/DrawNode3D.cpp | 92 +- .../Classes/Sprite3DTest/DrawNode3D.h | 94 +- .../Classes/Sprite3DTest/Sprite3DTest.cpp | 654 ++-- .../Classes/Sprite3DTest/Sprite3DTest.h | 237 +- .../SpriteFrameCacheTest.cpp | 163 +- .../SpriteFrameCacheTest.h | 32 +- .../SpritePolygonTest/SpritePolygonTest.cpp | 503 ++- .../SpritePolygonTest/SpritePolygonTest.h | 45 +- .../Classes/SpriteTest/SpriteTest.cpp | 2941 +++++++++-------- .../cpp-tests/Classes/SpriteTest/SpriteTest.h | 66 +- .../Classes/TerrainTest/TerrainTest.cpp | 262 +- .../Classes/TerrainTest/TerrainTest.h | 46 +- .../Classes/TextInputTest/TextInputTest.cpp | 156 +- .../Classes/TextInputTest/TextInputTest.h | 38 +- .../Classes/Texture2dTest/Texture2dTest.cpp | 825 ++--- .../Classes/Texture2dTest/Texture2dTest.h | 39 +- .../TextureCacheTest/TextureCacheTest.cpp | 140 +- .../TextureCacheTest/TextureCacheTest.h | 18 +- .../TextureAtlasEncryptionTest.cpp | 34 +- .../TextureAtlasEncryptionTest.h | 10 +- .../Classes/TileMapTest/TileMapTest2.cpp | 593 ++-- .../Classes/TileMapTest/TileMapTest2.h | 27 +- tests/cpp-tests/Classes/TouchesTest/Ball.cpp | 63 +- tests/cpp-tests/Classes/TouchesTest/Ball.h | 18 +- .../cpp-tests/Classes/TouchesTest/Paddle.cpp | 66 +- tests/cpp-tests/Classes/TouchesTest/Paddle.h | 15 +- .../Classes/TouchesTest/TouchesTest.cpp | 111 +- .../Classes/TouchesTest/TouchesTest.h | 24 +- .../TransitionsTest/TransitionsTest.cpp | 135 +- .../Classes/TransitionsTest/TransitionsTest.h | 9 +- .../CocoStudioGUITest/CocosGUIScene.cpp | 79 +- .../UITest/CocoStudioGUITest/CocosGUIScene.h | 8 +- .../UIButtonTest/UIButtonTest.cpp | 737 +++-- .../UIButtonTest/UIButtonTest.h | 23 +- .../UICheckBoxTest/UICheckBoxTest.cpp | 156 +- .../UICheckBoxTest/UICheckBoxTest.h | 15 +- .../CocoStudioGUITest/UIEditBoxTest.cpp | 269 +- .../UITest/CocoStudioGUITest/UIEditBoxTest.h | 35 +- .../UIFocusTest/UIFocusTest.cpp | 352 +- .../UIFocusTest/UIFocusTest.h | 24 +- .../UIImageViewTest/UIImageViewTest.cpp | 186 +- .../UIImageViewTest/UIImageViewTest.h | 11 +- .../UILayoutTest/UILayoutTest.cpp | 616 ++-- .../UILayoutTest/UILayoutTest.h | 31 +- .../UIListViewTest/UIListViewTest.cpp | 596 ++-- .../UIListViewTest/UIListViewTest.h | 52 +- .../UILoadingBarTest/UILoadingBarTest.cpp | 318 +- .../UILoadingBarTest/UILoadingBarTest.h | 34 +- .../UIPageViewTest/UIPageViewTest.cpp | 737 +++-- .../UIPageViewTest/UIPageViewTest.h | 40 +- .../UIRadioButtonTest/UIRadioButtonTest.cpp | 196 +- .../UIRadioButtonTest/UIRadioButtonTest.h | 31 +- .../UIRichTextTest/UIRichTextTest.cpp | 619 ++-- .../UIRichTextTest/UIRichTextTest.h | 22 +- .../CocoStudioGUITest/UIScale9SpriteTest.cpp | 936 +++--- .../CocoStudioGUITest/UIScale9SpriteTest.h | 70 +- .../UITest/CocoStudioGUITest/UIScene.cpp | 40 +- .../UITest/CocoStudioGUITest/UIScene.h | 10 +- .../CocoStudioGUITest/UISceneManager.cpp | 9 +- .../UITest/CocoStudioGUITest/UISceneManager.h | 8 +- .../UIScrollViewTest/UIScrollViewTest.cpp | 587 ++-- .../UIScrollViewTest/UIScrollViewTest.h | 45 +- .../UISliderTest/UISliderTest.cpp | 240 +- .../UISliderTest/UISliderTest.h | 21 +- .../UITabControlTest/UITabControlTest.cpp | 40 +- .../UITabControlTest/UITabControlTest.h | 5 +- .../UITextAtlasTest/UITextAtlasTest.cpp | 41 +- .../UITextAtlasTest/UITextAtlasTest.h | 14 +- .../UITextBMFontTest/UITextBMFontTest.cpp | 27 +- .../UITextBMFontTest/UITextBMFontTest.h | 9 +- .../UITextFieldTest/UITextFieldTest.cpp | 675 ++-- .../UITextFieldTest/UITextFieldTest.h | 31 +- .../UITextTest/UITextTest.cpp | 160 +- .../CocoStudioGUITest/UITextTest/UITextTest.h | 10 +- .../UIVideoPlayerTest/UIVideoPlayerTest.cpp | 237 +- .../UIVideoPlayerTest/UIVideoPlayerTest.h | 35 +- .../UIWebViewTest/UIWebViewTest.cpp | 201 +- .../UIWebViewTest/UIWebViewTest.h | 22 +- .../UIWidgetAddNodeTest.cpp | 28 +- .../UIWidgetAddNodeTest/UIWidgetAddNodeTest.h | 8 +- tests/cpp-tests/Classes/UITest/UITest.cpp | 15 +- tests/cpp-tests/Classes/UITest/UITest.h | 10 +- tests/cpp-tests/Classes/UnitTest/RefPtrTest.h | 13 +- tests/cpp-tests/Classes/UnitTest/UnitTest.cpp | 528 +-- tests/cpp-tests/Classes/UnitTest/UnitTest.h | 11 +- .../UserDefaultTest/UserDefaultTest.cpp | 145 +- .../Classes/UserDefaultTest/UserDefaultTest.h | 10 +- tests/cpp-tests/Classes/VRTest/VRTest.cpp | 10 +- tests/cpp-tests/Classes/VRTest/VRTest.h | 3 +- .../Classes/VibrateTest/VibrateTest.cpp | 416 ++- .../Classes/VibrateTest/VibrateTest.h | 20 +- tests/cpp-tests/Classes/VisibleRect.cpp | 19 +- tests/cpp-tests/Classes/VisibleRect.h | 9 +- .../Classes/WindowTest/WindowTest.cpp | 44 +- .../cpp-tests/Classes/WindowTest/WindowTest.h | 13 +- tests/cpp-tests/Classes/ZipTest/ZipTests.cpp | 91 +- tests/cpp-tests/Classes/ZipTest/ZipTests.h | 1 + .../Classes/ZwoptexTest/ZwoptexTest.cpp | 66 +- .../Classes/ZwoptexTest/ZwoptexTest.h | 14 +- tests/cpp-tests/Classes/controller.cpp | 214 +- tests/cpp-tests/Classes/controller.h | 13 +- tests/cpp-tests/Classes/testBasic.h | 27 +- tests/cpp-tests/Classes/testResource.h | 86 +- tests/cpp-tests/Classes/tests.h | 33 +- tests/cpp-tests/proj.android/app/jni/main.cpp | 18 +- .../proj.ios/Classes/RootViewController.h | 2 + .../proj.ios/Classes/RootViewController.mm | 35 +- .../proj.ios/Classes/testsAppDelegate.h | 5 +- .../proj.ios/Classes/testsAppDelegate.mm | 83 +- tests/cpp-tests/proj.linux/main.cpp | 10 +- tests/cpp-tests/proj.mac/main.cpp | 10 +- tests/cpp-tests/proj.win32/main.cpp | 13 +- tests/cpp-tests/proj.win32/main.h | 12 +- tests/fairygui-tests/CMakeLists.txt | 8 +- tests/lua-tests/project/CMakeLists.txt | 7 +- .../lua-tests/project/Classes/AppDelegate.cpp | 24 +- tests/lua-tests/project/Classes/AppDelegate.h | 11 +- .../Classes/lua_assetsmanager_test_sample.cpp | 56 +- .../Classes/lua_assetsmanager_test_sample.h | 13 +- .../project/Classes/lua_test_bindings.cpp | 427 ++- .../project/Classes/lua_test_bindings.h | 10 +- .../project/proj.android/app/jni/main.cpp | 18 +- .../project/proj.ios_mac/ios/AppController.h | 13 +- .../project/proj.ios_mac/ios/AppController.mm | 83 +- .../proj.ios_mac/ios/LuaObjectCBridgeTest.h | 24 +- .../proj.ios_mac/ios/LuaObjectCBridgeTest.mm | 37 +- .../proj.ios_mac/ios/RootViewController.h | 10 +- .../proj.ios_mac/ios/RootViewController.mm | 43 +- .../proj.ios_mac/mac/LuaObjectCBridgeTest.h | 24 +- .../proj.ios_mac/mac/LuaObjectCBridgeTest.mm | 37 +- .../project/proj.ios_mac/mac/main.cpp | 10 +- tests/lua-tests/project/proj.linux/main.cpp | 10 +- tests/lua-tests/project/proj.win32/main.cpp | 13 +- tests/lua-tests/project/proj.win32/main.h | 12 +- tests/lua-tests/project/proj.win32/resource.h | 28 +- tools/appveyor-scripts/before-build.ps1 | 51 + tools/appveyor-scripts/build.ps1 | 124 + tools/appveyor-scripts/git_retry.py | 165 + .../setup_android.py | 0 tools/bindings-generator/generator.py | 52 +- .../targets/lua/conversions.yaml | 14 +- tools/bindings-generator/test/test.ini | 2 +- tools/console/README.md | 13 + tools/console/config.json | 6 + tools/console/download-bin.py | 308 ++ tools/jenkins-scripts/configs/autotest.py | 10 + .../configs/cocos-2dx-develop-android.py | 21 + .../configs/cocos-2dx-develop-base-repo.py | 22 + .../configs/cocos-2dx-develop-ios.py | 20 + .../configs/cocos-2dx-develop-win32.py | 24 + .../configs/cocos-2dx-doxygen.py | 24 + ...-2dx-pull-request-build-comment-trigger.py | 8 + .../cocos-2dx-pull-request-build-trigger.py | 8 + .../configs/cocos-2dx-pull-request-build.py | 32 + .../configs/cocos2d-console-test.py | 12 + .../configs/cocostudiox-base-repo.py | 8 + .../configs/cocostudiox-daily-build.py | 30 + .../configs/jenkins-job-watchdog.py | 2 + .../configs/manual-update-jenkins-scripts.py | 2 + tools/jenkins-scripts/daily-build.py | 148 + .../do-pull-request-builder.py | 114 + .../master-scripts/autotest.py | 182 + .../master-scripts/ci-dailybuild-android.py | 168 + .../master-scripts/ci-release-test.py | 188 ++ .../master-scripts/cocos-console-test.py | 379 +++ .../cocos2dx-libsize-tracking.py | 88 + .../master-scripts/emptytest-post-build.py | 32 + .../master-scripts/emptytest.py | 354 ++ .../master-scripts/github-pr-watchdog.py | 72 + .../master-scripts/job-comment-trigger.py | 136 + .../master-scripts/job-trigger.py | 125 + .../master-scripts/post-build.py | 72 + .../master-scripts/watchdog.py | 114 + tools/jenkins-scripts/pull-request-builder.py | 149 + .../slave-scripts/framework/android-build.sh | 5 + .../slave-scripts/framework/mac-build.sh | 5 + .../slave-scripts/framework/win32-build.bat | 2 + .../jenkins-scripts/slave-scripts/gen_jsb.py | 16 + .../slave-scripts/runtime/android-build.sh | 12 + .../slave-scripts/runtime/ios-build.sh | 25 + .../slave-scripts/runtime/linux-build.sh | 13 + .../slave-scripts/runtime/mac-build.sh | 19 + .../slave-scripts/runtime/win32-cpp.bat | 2 + .../slave-scripts/runtime/win32-js.bat | 2 + .../slave-scripts/runtime/win32-lua.bat | 2 + .../runtime/windows-universal-cpp.bat | 2 + .../runtime/windows-universal-js.bat | 2 + .../runtime/windows-universal-lua.bat | 2 + .../slave-scripts/templates/android-build.sh | 12 + .../slave-scripts/templates/ios-build.sh | 25 + .../slave-scripts/templates/linux-build.sh | 13 + .../slave-scripts/templates/mac-build.sh | 25 + .../slave-scripts/templates/win32-cpp.bat | 2 + .../slave-scripts/templates/win32-js.bat | 2 + .../slave-scripts/templates/win32-lua.bat | 2 + .../templates/windows-universal-cpp.bat | 2 + .../templates/windows-universal-js.bat | 2 + .../templates/windows-universal-lua.bat | 2 + .../slave-scripts/tests/android-build.sh | 5 + .../slave-scripts/tests/ios-build.sh | 7 + .../slave-scripts/tests/linux-build.sh | 12 + .../slave-scripts/tests/mac-build.sh | 22 + .../slave-scripts/tests/tizen-build.sh | 26 + .../slave-scripts/tests/win32-build.bat | 2 + .../slave-scripts/tests/windows-universal.bat | 2 + tools/jenkins-scripts/utils/create-job.py | 32 + .../utils/create-template-project.py | 19 + tools/jenkins-scripts/utils/reboot.py | 73 + tools/jenkins-scripts/utils/upload_apk.sh | 9 + tools/tolua/cocos2dx.ini | 4 +- tools/tolua/cocos2dx_3d.ini | 4 +- tools/tolua/cocos2dx_audioengine.ini | 4 +- tools/tolua/cocos2dx_backend.ini | 6 +- tools/tolua/cocos2dx_controller.ini | 4 +- tools/tolua/cocos2dx_csloader.ini | 4 +- tools/tolua/cocos2dx_extension.ini | 4 +- tools/tolua/cocos2dx_navmesh.ini | 4 +- tools/tolua/cocos2dx_physics.ini | 4 +- tools/tolua/cocos2dx_physics3d.ini | 4 +- tools/tolua/cocos2dx_spine.ini | 4 +- tools/tolua/cocos2dx_studio.ini | 4 +- tools/tolua/cocos2dx_ui.ini | 4 +- tools/tolua/cocos2dx_video.ini | 4 +- tools/tolua/cocos2dx_webview.ini | 4 +- tools/tolua/genbindings.py | 2 +- tools/travis-scripts/before-install.sh | 141 + .../config.gitignore | 0 .../for-each-file-in-dir.sh | 0 .../generate-template-files.py | 0 tools/travis-scripts/run-script.sh | 339 ++ tools/unix-ci/before-install.sh | 93 - tools/unix-ci/run-script.sh | 106 - tools/win-ci/genbindings.ps1 | 37 - tools/{win-ci => windows-ci}/build.ps1 | 0 1098 files changed, 46409 insertions(+), 42237 deletions(-) create mode 100644 .appveyor.yml delete mode 100644 .github/workflows/genbindings-ci.yml delete mode 100644 cocos/base/hlookup.h create mode 100644 cocos/platform/android/CMakeLists.txt delete mode 100644 cocos/renderer/shaders/label_sdf.frag create mode 100644 tools/appveyor-scripts/before-build.ps1 create mode 100644 tools/appveyor-scripts/build.ps1 create mode 100644 tools/appveyor-scripts/git_retry.py rename tools/{unix-ci => appveyor-scripts}/setup_android.py (100%) create mode 100644 tools/console/config.json create mode 100644 tools/console/download-bin.py create mode 100644 tools/jenkins-scripts/configs/autotest.py create mode 100644 tools/jenkins-scripts/configs/cocos-2dx-develop-android.py create mode 100644 tools/jenkins-scripts/configs/cocos-2dx-develop-base-repo.py create mode 100644 tools/jenkins-scripts/configs/cocos-2dx-develop-ios.py create mode 100644 tools/jenkins-scripts/configs/cocos-2dx-develop-win32.py create mode 100644 tools/jenkins-scripts/configs/cocos-2dx-doxygen.py create mode 100644 tools/jenkins-scripts/configs/cocos-2dx-pull-request-build-comment-trigger.py create mode 100644 tools/jenkins-scripts/configs/cocos-2dx-pull-request-build-trigger.py create mode 100644 tools/jenkins-scripts/configs/cocos-2dx-pull-request-build.py create mode 100644 tools/jenkins-scripts/configs/cocos2d-console-test.py create mode 100644 tools/jenkins-scripts/configs/cocostudiox-base-repo.py create mode 100644 tools/jenkins-scripts/configs/cocostudiox-daily-build.py create mode 100644 tools/jenkins-scripts/configs/jenkins-job-watchdog.py create mode 100644 tools/jenkins-scripts/configs/manual-update-jenkins-scripts.py create mode 100644 tools/jenkins-scripts/daily-build.py create mode 100644 tools/jenkins-scripts/do-pull-request-builder.py create mode 100644 tools/jenkins-scripts/master-scripts/autotest.py create mode 100644 tools/jenkins-scripts/master-scripts/ci-dailybuild-android.py create mode 100644 tools/jenkins-scripts/master-scripts/ci-release-test.py create mode 100644 tools/jenkins-scripts/master-scripts/cocos-console-test.py create mode 100644 tools/jenkins-scripts/master-scripts/cocos2dx-libsize-tracking.py create mode 100644 tools/jenkins-scripts/master-scripts/emptytest-post-build.py create mode 100644 tools/jenkins-scripts/master-scripts/emptytest.py create mode 100644 tools/jenkins-scripts/master-scripts/github-pr-watchdog.py create mode 100644 tools/jenkins-scripts/master-scripts/job-comment-trigger.py create mode 100644 tools/jenkins-scripts/master-scripts/job-trigger.py create mode 100644 tools/jenkins-scripts/master-scripts/post-build.py create mode 100644 tools/jenkins-scripts/master-scripts/watchdog.py create mode 100644 tools/jenkins-scripts/pull-request-builder.py create mode 100644 tools/jenkins-scripts/slave-scripts/framework/android-build.sh create mode 100644 tools/jenkins-scripts/slave-scripts/framework/mac-build.sh create mode 100644 tools/jenkins-scripts/slave-scripts/framework/win32-build.bat create mode 100644 tools/jenkins-scripts/slave-scripts/gen_jsb.py create mode 100644 tools/jenkins-scripts/slave-scripts/runtime/android-build.sh create mode 100644 tools/jenkins-scripts/slave-scripts/runtime/ios-build.sh create mode 100644 tools/jenkins-scripts/slave-scripts/runtime/linux-build.sh create mode 100644 tools/jenkins-scripts/slave-scripts/runtime/mac-build.sh create mode 100644 tools/jenkins-scripts/slave-scripts/runtime/win32-cpp.bat create mode 100644 tools/jenkins-scripts/slave-scripts/runtime/win32-js.bat create mode 100644 tools/jenkins-scripts/slave-scripts/runtime/win32-lua.bat create mode 100644 tools/jenkins-scripts/slave-scripts/runtime/windows-universal-cpp.bat create mode 100644 tools/jenkins-scripts/slave-scripts/runtime/windows-universal-js.bat create mode 100644 tools/jenkins-scripts/slave-scripts/runtime/windows-universal-lua.bat create mode 100644 tools/jenkins-scripts/slave-scripts/templates/android-build.sh create mode 100644 tools/jenkins-scripts/slave-scripts/templates/ios-build.sh create mode 100644 tools/jenkins-scripts/slave-scripts/templates/linux-build.sh create mode 100644 tools/jenkins-scripts/slave-scripts/templates/mac-build.sh create mode 100644 tools/jenkins-scripts/slave-scripts/templates/win32-cpp.bat create mode 100644 tools/jenkins-scripts/slave-scripts/templates/win32-js.bat create mode 100644 tools/jenkins-scripts/slave-scripts/templates/win32-lua.bat create mode 100644 tools/jenkins-scripts/slave-scripts/templates/windows-universal-cpp.bat create mode 100644 tools/jenkins-scripts/slave-scripts/templates/windows-universal-js.bat create mode 100644 tools/jenkins-scripts/slave-scripts/templates/windows-universal-lua.bat create mode 100644 tools/jenkins-scripts/slave-scripts/tests/android-build.sh create mode 100644 tools/jenkins-scripts/slave-scripts/tests/ios-build.sh create mode 100644 tools/jenkins-scripts/slave-scripts/tests/linux-build.sh create mode 100644 tools/jenkins-scripts/slave-scripts/tests/mac-build.sh create mode 100644 tools/jenkins-scripts/slave-scripts/tests/tizen-build.sh create mode 100644 tools/jenkins-scripts/slave-scripts/tests/win32-build.bat create mode 100644 tools/jenkins-scripts/slave-scripts/tests/windows-universal.bat create mode 100644 tools/jenkins-scripts/utils/create-job.py create mode 100644 tools/jenkins-scripts/utils/create-template-project.py create mode 100644 tools/jenkins-scripts/utils/reboot.py create mode 100644 tools/jenkins-scripts/utils/upload_apk.sh create mode 100644 tools/travis-scripts/before-install.sh rename tools/{unix-ci => travis-scripts}/config.gitignore (100%) rename tools/{unix-ci => travis-scripts}/for-each-file-in-dir.sh (100%) rename tools/{unix-ci => travis-scripts}/generate-template-files.py (100%) create mode 100644 tools/travis-scripts/run-script.sh delete mode 100644 tools/unix-ci/before-install.sh delete mode 100644 tools/unix-ci/run-script.sh delete mode 100644 tools/win-ci/genbindings.ps1 rename tools/{win-ci => windows-ci}/build.ps1 (100%) diff --git a/.appveyor.yml b/.appveyor.yml new file mode 100644 index 0000000000..08b58326bd --- /dev/null +++ b/.appveyor.yml @@ -0,0 +1,42 @@ +version: 1.0.{build} +skip_tags: true +skip_branch_with_pr: true +image: + - Visual Studio 2019 +environment: + PYTHON: "C:\\Python27" + PYTHON_VERSION: "2.7.13" + PYTHON_ARCH: "32" + matrix: + - build_type: windows32_cmake_test +# - build_type: android_cpp_tests +# - build_type: android_lua_tests +# - build_type: android_cocos_new_test +# - build_type: android_cpp_empty_test +# - build_type: android_gen_libs + + +platform: + - x86 + +configuration: + - Release + +before_build: + - ps: ./tools/appveyor-scripts/before-build.ps1 + +build_script: + - ps: ./tools/appveyor-scripts/build.ps1 + +branches: + except: + - v1 + - v2 + - v4-develop + - v3-doc + - v3.11_backup + - v35-for-tizen + +clone_depth: 50 + +test: off diff --git a/.github/workflows/android-ci.yml b/.github/workflows/android-ci.yml index 30e2da959a..25724fa4df 100644 --- a/.github/workflows/android-ci.yml +++ b/.github/workflows/android-ci.yml @@ -4,7 +4,7 @@ on: push: branches: - dev - - main + - release paths: - cmake/**/* - cocos/**/* @@ -16,9 +16,12 @@ on: env: # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) - GH_OS_NAME: linux + TRAVIS_OS_NAME: linux BUILD_TARGET: android + # Simple let github action to build all (TODO: optimize in the future) + TRAVIS_PULL_REQUEST: true BUILD_TYPE: Release + GITHUB_CI: true PYENV_VERSION: 2.7.18 jobs: @@ -48,8 +51,8 @@ jobs: - name: Create Build Environment # Some projects don't allow in-source building, so create a separate build directory # We'll use this as our working directory for all - run: tools/unix-ci/before-install.sh + run: tools/travis-scripts/before-install.sh - name: Build # Execute the build. You can specify a specific target with "--target " - run: tools/unix-ci/run-script.sh + run: tools/travis-scripts/run-script.sh diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 007d1e0325..51ce1bc9a5 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -7,7 +7,7 @@ on: # actions run ID description: 'Commit clang-format changes?' # Default value if no value is explicitly provided - default: 'false' + default: false # Input has to be provided for the workflow to run required: false @@ -21,9 +21,9 @@ jobs: - name: Run clang-format lint uses: DoozyX/clang-format-lint-action@v0.13 with: - source: './cocos ./extensions ./tests ./templates' - exclude: './thidrparty ./extensions/fairygui ./extensions/scripting/lua-bindings/auto ./extensions/spine ./tests/fairygui-tests' - extensions: 'h,cpp,c,mm' + source: './cocos ./extensions' + exclude: './thidrparty ./extensions/fairygui ./extensions/scripting/lua-bindings/auto ./extensions/spine' + extensions: 'h,cpp,c' clangFormatVersion: 13 inplace: True - name: Commit clang-format changes diff --git a/.github/workflows/genbindings-ci.yml b/.github/workflows/genbindings-ci.yml deleted file mode 100644 index 9e2857817b..0000000000 --- a/.github/workflows/genbindings-ci.yml +++ /dev/null @@ -1,36 +0,0 @@ -name: genbindings - -on: - push: - branches: - - dev - - main - paths: - - cocos/**/* - - extensions/**/* - - .github/workflows/genbindings-ci.yml - -jobs: - build: - if: ${{ !startsWith(github.event.commits[0].message, 'Merge pull request') }} - # The CMake configure and build commands are platform agnostic and should work equally - # well on Windows or Mac. You can convert this to a matrix build if you need - # cross-platform coverage. - # See: https://docs.github.com/en/actions/configuring-and-managing-workflows/configuring-a-workflow#configuring-a-build-matrix - runs-on: windows-latest - - steps: - - uses: actions/checkout@v2 - with: - submodules: 'recursive' - lfs: 'true' - - - name: Setup Python - uses: actions/setup-python@v2 - - - uses: ilammy/msvc-dev-cmd@v1.9.0 - with: - arch: ${{ env.BUILD_ARCH }} - - - name: Build - run: tools\win-ci\genbindings.ps1 diff --git a/.github/workflows/ios-ci.yml b/.github/workflows/ios-ci.yml index ed204106b8..eeb83f9abe 100644 --- a/.github/workflows/ios-ci.yml +++ b/.github/workflows/ios-ci.yml @@ -4,7 +4,7 @@ on: push: branches: - dev - - main + - release paths: - cmake/**/* - cocos/**/* @@ -16,9 +16,12 @@ on: env: # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) - GH_OS_NAME: osx + TRAVIS_OS_NAME: osx BUILD_TARGET: ios + # Simple let github action to build all (TODO: optimize in the future) + TRAVIS_PULL_REQUEST: true BUILD_TYPE: Release + GITHUB_CI: true jobs: build: @@ -38,8 +41,8 @@ jobs: - name: Create Build Environment # Some projects don't allow in-source building, so create a separate build directory # We'll use this as our working directory for all - run: tools/unix-ci/before-install.sh + run: tools/travis-scripts/before-install.sh - name: Build # Execute the build. You can specify a specific target with "--target " - run: tools/unix-ci/run-script.sh + run: tools/travis-scripts/run-script.sh diff --git a/.github/workflows/linux-ci.yml b/.github/workflows/linux-ci.yml index 086aecbe20..9e46ebf844 100644 --- a/.github/workflows/linux-ci.yml +++ b/.github/workflows/linux-ci.yml @@ -4,7 +4,7 @@ on: push: branches: - dev - - main + - release paths: - cmake/**/* - cocos/**/* @@ -16,10 +16,12 @@ on: env: # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) - GH_OS_NAME: linux + TRAVIS_OS_NAME: linux BUILD_TARGET: linux + # Simple let github action to build all (TODO: optimize in the future) + TRAVIS_PULL_REQUEST: true BUILD_TYPE: Release - PYENV_VERSION: 2.7.18 + GITHUB_CI: true jobs: build: @@ -39,8 +41,8 @@ jobs: - name: Create Build Environment # Some projects don't allow in-source building, so create a separate build directory # We'll use this as our working directory for all subsequent commands - run: tools/unix-ci/before-install.sh + run: tools/travis-scripts/before-install.sh - name: Build # Execute the build. You can specify a specific target with "--target " - run: tools/unix-ci/run-script.sh + run: tools/travis-scripts/run-script.sh diff --git a/.github/workflows/osx-ci.yml b/.github/workflows/osx-ci.yml index 8c925befa2..05d6352ce9 100644 --- a/.github/workflows/osx-ci.yml +++ b/.github/workflows/osx-ci.yml @@ -4,7 +4,7 @@ on: push: branches: - dev - - main + - release paths: - cmake/**/* - cocos/**/* @@ -16,9 +16,12 @@ on: env: # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) - GH_OS_NAME: osx + TRAVIS_OS_NAME: osx BUILD_TARGET: osx + # Simple let github action to build all (TODO: optimize in the future) + TRAVIS_PULL_REQUEST: true BUILD_TYPE: Release + GITHUB_CI: true jobs: build: @@ -38,8 +41,8 @@ jobs: - name: Create Build Environment # Some projects don't allow in-source building, so create a separate build directory # We'll use this as our working directory for all - run: tools/unix-ci/before-install.sh + run: tools/travis-scripts/before-install.sh - name: Build # Execute the build. You can specify a specific target with "--target " - run: tools/unix-ci/run-script.sh + run: tools/travis-scripts/run-script.sh diff --git a/.github/workflows/pr-ci.yml b/.github/workflows/pr-ci.yml index 23cc0f8019..2a27801cac 100644 --- a/.github/workflows/pr-ci.yml +++ b/.github/workflows/pr-ci.yml @@ -8,7 +8,9 @@ on: env: # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) BUILD_TYPE: Release - PYENV_VERSION: 2.7.18 + # Simple let github action to build all (TODO: optimize in the future) + TRAVIS_PULL_REQUEST: true + GITHUB_CI: true jobs: build-windows: @@ -29,13 +31,13 @@ jobs: - name: Setup Python uses: actions/setup-python@v2 - name: Build - run: tools\win-ci\build.ps1 $env:BUILD_ARCH + run: tools\windows-ci\build.ps1 $env:BUILD_ARCH build-linux: name: build-linux runs-on: ubuntu-latest env: - GH_OS_NAME: linux + TRAVIS_OS_NAME: linux BUILD_TARGET: linux steps: - uses: actions/checkout@v2 @@ -44,8 +46,8 @@ jobs: lfs: 'true' - name: Build run: | - tools/unix-ci/before-install.sh - tools/unix-ci/run-script.sh + tools/travis-scripts/before-install.sh + tools/travis-scripts/run-script.sh build-android: name: build-android @@ -57,8 +59,9 @@ jobs: - arm64-v8a - x86 env: - GH_OS_NAME: linux + TRAVIS_OS_NAME: linux BUILD_TARGET: android + PYENV_VERSION: 2.7.18 BUILD_ARCH: ${{ matrix.arch }} steps: - uses: actions/checkout@v2 @@ -67,14 +70,14 @@ jobs: lfs: 'true' - name: Build run: | - tools/unix-ci/before-install.sh - tools/unix-ci/run-script.sh + tools/travis-scripts/before-install.sh + tools/travis-scripts/run-script.sh build-osx: name: build-osx runs-on: macos-latest env: - GH_OS_NAME: osx + TRAVIS_OS_NAME: osx BUILD_TARGET: osx steps: - uses: actions/checkout@v2 @@ -83,14 +86,14 @@ jobs: lfs: 'true' - name: Build run: | - tools/unix-ci/before-install.sh - tools/unix-ci/run-script.sh + tools/travis-scripts/before-install.sh + tools/travis-scripts/run-script.sh build-ios: name: build-ios runs-on: macos-latest env: - GH_OS_NAME: osx + TRAVIS_OS_NAME: osx BUILD_TARGET: ios steps: - uses: actions/checkout@v2 @@ -99,5 +102,5 @@ jobs: lfs: 'true' - name: Build run: | - tools/unix-ci/before-install.sh - tools/unix-ci/run-script.sh + tools/travis-scripts/before-install.sh + tools/travis-scripts/run-script.sh diff --git a/.github/workflows/windows-ci.yml b/.github/workflows/windows-ci.yml index 0abb5b8b8a..70df7df982 100644 --- a/.github/workflows/windows-ci.yml +++ b/.github/workflows/windows-ci.yml @@ -4,7 +4,7 @@ on: push: branches: - dev - - main + - release paths: - cmake/**/* - cocos/**/* @@ -44,4 +44,4 @@ jobs: arch: ${{ env.BUILD_ARCH }} - name: Build - run: tools\win-ci\build.ps1 $env:BUILD_ARCH + run: tools\windows-ci\build.ps1 $env:BUILD_ARCH diff --git a/README.md b/README.md index b27f735bfb..c85f86c333 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,7 @@ # adxe - -[![dev](https://img.shields.io/badge/v1.0.0-beta5-yellow.svg)](https://github.com/adxeproject/adxe/releases) -[![LICENSE](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/adxeproject/adxe/blob/master/LICENSE) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/1c5628dea478449ea0c6e1b0e30c3be9)](https://app.codacy.com/gh/adxeproject/adxe?utm_source=github.com&utm_medium=referral&utm_content=adxeproject/adxe&utm_campaign=Badge_Grade_Settings) -[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-blue.svg)](https://github.com/adxeproject/adxe/pulls) +[![dev](https://img.shields.io/badge/v1.0.0-beta4-yellow.svg)](https://github.com/adxeproject/adxe/releases) +[![LICENSE](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/adxeproject/adxe/blob/master/LICENSE) [![Windows Build Status](https://github.com/adxeproject/adxe/actions/workflows/windows-ci.yml/badge.svg)](https://github.com/adxeproject/adxe/actions/workflows/windows-ci.yml) [![Android Build Status](https://github.com/adxeproject/adxe/workflows/android/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Aandroid) @@ -11,7 +9,7 @@ [![Linux Build Status](https://github.com/adxeproject/adxe/workflows/linux/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Alinux) [![macOS Build Status](https://github.com/adxeproject/adxe/workflows/osx/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Aosx) -**This is another more radical fork of *Cocos2d-x-4.0*, use OpenAL for all platforms, single texture multi GPU texture handler, C++ 17 and some more (see 'Highlight Features' for more info).** +**This is another more radical fork of *Cocos2d-x-4.0*, use OpenAL for all platforms, single texture multi GPU texture handler, C++ 14/17 and some more (see 'Highlight Features' for more info).** ### View code with vscode online: - [![github1s](https://img.shields.io/badge/github1s-green.svg)](https://github1s.com/adxeproject/adxe) @@ -21,9 +19,10 @@ **[简体中文](README_CN.md)** ### Purpose Summary -* C++ 17 +* C++ 14/17 * Focus on native game dev (quick starting, easy to use, fast) * Bugfixes ASAP +* Usefull PRs from **you** are welcome (review/merge ASAP) ### Highlight Features * Windows x64 build support @@ -37,7 +36,7 @@ * Implement all .wav formats supported by ```OpenAL Soft```, such as MS-ADPCM, ADPCM, ... * Use modern GL loader ```Glad``` * Google [angle](https://github.com/google/angle) renderer backend support -* C++ 17 standard +* C++ 14 standard * IOS SDK 9.0 as minimal deployment * Use fast pugixml * Use [curl](https://github.com/curl/curl) for transferring data with URL syntax @@ -137,7 +136,7 @@ https://github.com/adxeproject/adxe/discussions/411 - @aismann - @weiwest -### Fully changes since cocos2d-x-4.0 +### Fullly changes since cocos2d-x-4.0 - [HIGHLIGHT] Implement Windows WebView using WebView2 Edge Chromium, thanks to @rh101 - [HIGHLIGHT] Windows x64 build support diff --git a/README_CN.md b/README_CN.md index 8784b18e74..d52c00e6a8 100644 --- a/README_CN.md +++ b/README_CN.md @@ -1,9 +1,8 @@ # adxe -[![dev](https://img.shields.io/badge/v1.0.0-beta5-yellow.svg)](https://github.com/adxeproject/adxe/releases) -[![LICENSE](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/adxeproject/adxe/blob/master/LICENSE) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/1c5628dea478449ea0c6e1b0e30c3be9)](https://app.codacy.com/gh/adxeproject/adxe?utm_source=github.com&utm_medium=referral&utm_content=adxeproject/adxe&utm_campaign=Badge_Grade_Settings) -[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-blue.svg)](https://github.com/adxeproject/adxe/pulls) +[![dev](https://img.shields.io/badge/v1.0.0-beta4-yellow.svg)](https://github.com/adxeproject/adxe/releases) +[![LICENSE](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/adxeproject/adxe/blob/master/LICENSE) [![Windows Build Status](https://github.com/adxeproject/adxe/actions/workflows/windows-ci.yml/badge.svg)](https://github.com/adxeproject/adxe/actions/workflows/windows-ci.yml) [![Android Build Status](https://github.com/adxeproject/adxe/workflows/android/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Aandroid) @@ -12,15 +11,16 @@ [![macOS Build Status](https://github.com/adxeproject/adxe/workflows/osx/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Aosx) -**这是另外一个基于 *Cocos2d-x-4.0* 持续维护的分支, 全平台基于OpenAL, c++17...** +**这是另外一个基于 *Cocos2d-x-4.0* 持续维护的分支, 全平台基于OpenAL, c++14/17...** **[English](README.md)** ### 宗旨: -* C++17 +* C++14/17 * Focus on native game dev only * Fix bugs ASAP * Review PR ASAP +* Excellent PRs from any guys are welcome, we will review & merge ASAP ### 主要特性: * Windows x64编译支持 @@ -33,7 +33,7 @@ * AudioEngine实现wav所有 ```openal-soft``` 支持的封装格式, 例如MS-ADPCM, ADPCM等 * 使用现代化的GL加载器glad代替glew * 增加google angle渲染后端支持 -* C++最低标准要求: C++17 +* 设置默认C++标准为C++14 * 设置ios下最低目标平台为ios9.0 * 使用更快的xml解析库pugixml代替tinyxml2 * Downloader全平台统一实现,均基于curl diff --git a/cocos/2d/CCActionTiledGrid.cpp b/cocos/2d/CCActionTiledGrid.cpp index 74665cd9b4..85558d98e3 100644 --- a/cocos/2d/CCActionTiledGrid.cpp +++ b/cocos/2d/CCActionTiledGrid.cpp @@ -247,7 +247,7 @@ Vec2 ShuffleTiles::getDelta(const Vec2& pos) const pos2.x = (float)(_tilesOrder[idx] / (int)_gridSize.height); pos2.y = (float)(_tilesOrder[idx] % (int)_gridSize.height); - return Vec2(static_cast((int)(pos2.x - pos.width)), static_cast((int)(pos2.y - pos.height))); + return Vec2((int)(pos2.x - pos.width), (int)(pos2.y - pos.height)); } void ShuffleTiles::placeTile(const Vec2& pos, Tile* t) diff --git a/cocos/2d/CCActionTween.cpp b/cocos/2d/CCActionTween.cpp index 68b84f63ba..37f93ffae1 100644 --- a/cocos/2d/CCActionTween.cpp +++ b/cocos/2d/CCActionTween.cpp @@ -29,7 +29,7 @@ THE SOFTWARE. NS_CC_BEGIN -ActionTween* ActionTween::create(float duration, std::string_view key, float from, float to) +ActionTween* ActionTween::create(float duration, const std::string& key, float from, float to) { ActionTween* ret = new ActionTween(); if (ret->initWithDuration(duration, key, from, to)) @@ -42,7 +42,7 @@ ActionTween* ActionTween::create(float duration, std::string_view key, float fro return nullptr; } -bool ActionTween::initWithDuration(float duration, std::string_view key, float from, float to) +bool ActionTween::initWithDuration(float duration, const std::string& key, float from, float to) { if (ActionInterval::initWithDuration(duration)) { diff --git a/cocos/2d/CCActionTween.h b/cocos/2d/CCActionTween.h index c0d1b7454f..4890f07a93 100644 --- a/cocos/2d/CCActionTween.h +++ b/cocos/2d/CCActionTween.h @@ -59,7 +59,7 @@ public: @param value The new value of the specified key. @param key The key of property which should be updated. */ - virtual void updateTweenAction(float value, std::string_view key) = 0; + virtual void updateTweenAction(float value, const std::string& key) = 0; }; /** ActionTween @@ -93,7 +93,7 @@ public: * @param to The value of the specified property when the action end. * @return If the creation success, return a pointer of ActionTween; otherwise, return nil. */ - static ActionTween* create(float duration, std::string_view key, float from, float to); + static ActionTween* create(float duration, const std::string& key, float from, float to); // Overrides void startWithTarget(Node* target) override; @@ -111,7 +111,7 @@ public: * @return If the initialization success, return true; otherwise, return false. */ bool - initWithDuration(float duration, std::string_view key, float from, float to); + initWithDuration(float duration, const std::string& key, float from, float to); protected: std::string _key; diff --git a/cocos/2d/CCAnimation.cpp b/cocos/2d/CCAnimation.cpp index 7f08879645..7909c0e9a3 100644 --- a/cocos/2d/CCAnimation.cpp +++ b/cocos/2d/CCAnimation.cpp @@ -165,7 +165,7 @@ void Animation::addSpriteFrame(SpriteFrame* spriteFrame) _totalDelayUnits++; } -void Animation::addSpriteFrameWithFile(std::string_view filename) +void Animation::addSpriteFrameWithFile(const std::string& filename) { Texture2D* texture = Director::getInstance()->getTextureCache()->addImage(filename); Rect rect = Rect::ZERO; diff --git a/cocos/2d/CCAnimation.h b/cocos/2d/CCAnimation.h index b9b266c617..1a312fc3f7 100644 --- a/cocos/2d/CCAnimation.h +++ b/cocos/2d/CCAnimation.h @@ -199,7 +199,7 @@ public: * Added to facilitate the migration from v0.8 to v0.9. * @param filename The path of SpriteFrame. */ - void addSpriteFrameWithFile(std::string_view filename); + void addSpriteFrameWithFile(const std::string& filename); /** Adds a frame with a texture and a rect. Internally it will create a SpriteFrame and it will add it. * The frame will be added with one "delay unit". diff --git a/cocos/2d/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp index eefbf411d7..6c3f62eecb 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -63,12 +63,12 @@ AnimationCache::~AnimationCache() CCLOGINFO("deallocing AnimationCache: %p", this); } -void AnimationCache::addAnimation(Animation* animation, std::string_view name) +void AnimationCache::addAnimation(Animation* animation, const std::string& name) { - _animations.insert(std::string{name}, animation); + _animations.insert(name, animation); } -void AnimationCache::removeAnimation(std::string_view name) +void AnimationCache::removeAnimation(const std::string& name) { if (name.empty()) return; @@ -76,7 +76,7 @@ void AnimationCache::removeAnimation(std::string_view name) _animations.erase(name); } -Animation* AnimationCache::getAnimation(std::string_view name) +Animation* AnimationCache::getAnimation(const std::string& name) { return _animations.at(name); } @@ -205,7 +205,7 @@ void AnimationCache::parseVersion2(const ValueMap& animations) } } -void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary, std::string_view plist) +void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary, const std::string& plist) { auto anisItr = dictionary.find("animations"); if (anisItr == dictionary.end()) @@ -245,7 +245,7 @@ void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary, std } /** Read an NSDictionary from a plist file and parse it automatically for animations */ -void AnimationCache::addAnimationsWithFile(std::string_view plist) +void AnimationCache::addAnimationsWithFile(const std::string& plist) { CCASSERT(!plist.empty(), "Invalid texture file name"); if (plist.empty()) @@ -259,7 +259,7 @@ void AnimationCache::addAnimationsWithFile(std::string_view plist) CCASSERT(!dict.empty(), "CCAnimationCache: File could not be found"); if (dict.empty()) { - log("AnimationCache::addAnimationsWithFile error:%s not exist!", plist.data()); + log("AnimationCache::addAnimationsWithFile error:%s not exist!", plist.c_str()); } addAnimationsWithDictionary(dict, plist); diff --git a/cocos/2d/CCAnimationCache.h b/cocos/2d/CCAnimationCache.h index 35ae26a737..0c41b66454 100644 --- a/cocos/2d/CCAnimationCache.h +++ b/cocos/2d/CCAnimationCache.h @@ -81,13 +81,13 @@ public: * @param animation An animation. * @param name The name of animation. */ - void addAnimation(Animation* animation, std::string_view name); + void addAnimation(Animation* animation, const std::string& name); /** Deletes a Animation from the cache. * * @param name The name of animation. */ - void removeAnimation(std::string_view name); + void removeAnimation(const std::string& name); /** Returns a Animation that was previously added. * If the name is not found it will return nil. @@ -95,7 +95,7 @@ public: * * @return A Animation that was previously added. If the name is not found it will return nil. */ - Animation* getAnimation(std::string_view name); + Animation* getAnimation(const std::string& name); /** Adds an animation from an NSDictionary. * Make sure that the frames were previously loaded in the SpriteFrameCache. @@ -104,7 +104,7 @@ public: * @since v1.1 @js NA */ - void addAnimationsWithDictionary(const ValueMap& dictionary, std::string_view plist); + void addAnimationsWithDictionary(const ValueMap& dictionary, const std::string& plist); /** Adds an animation from a plist file. * Make sure that the frames were previously loaded in the SpriteFrameCache. @@ -113,14 +113,14 @@ public: * @lua addAnimations * @param plist An animation from a plist file. */ - void addAnimationsWithFile(std::string_view plist); + void addAnimationsWithFile(const std::string& plist); private: void parseVersion1(const ValueMap& animations); void parseVersion2(const ValueMap& animations); private: - StringMap _animations; + Map _animations; static AnimationCache* s_sharedAnimationCache; }; diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index 6f38d89350..d1448ebdb4 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -47,7 +47,7 @@ AtlasNode::~AtlasNode() CC_SAFE_RELEASE(_textureAtlas); } -AtlasNode* AtlasNode::create(std::string_view tile, int tileWidth, int tileHeight, int itemsToRender) +AtlasNode* AtlasNode::create(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender) { AtlasNode* ret = new AtlasNode(); if (ret->initWithTileFile(tile, tileWidth, tileHeight, itemsToRender)) @@ -59,7 +59,7 @@ AtlasNode* AtlasNode::create(std::string_view tile, int tileWidth, int tileHeigh return nullptr; } -bool AtlasNode::initWithTileFile(std::string_view tile, int tileWidth, int tileHeight, int itemsToRender) +bool AtlasNode::initWithTileFile(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender) { CCASSERT(!tile.empty(), "file size should not be empty"); Texture2D* texture = _director->getTextureCache()->addImage(tile); @@ -222,7 +222,7 @@ void AtlasNode::setIgnoreContentScaleFactor(bool ignoreContentScaleFactor) auto label = dynamic_cast(this); if (label) { - Vec2 s = Vec2(static_cast(label->getString().size() * _itemWidth), static_cast(_itemHeight)); + Vec2 s = Vec2(label->getString().size() * _itemWidth, _itemHeight); this->setContentSize(s); } } diff --git a/cocos/2d/CCAtlasNode.h b/cocos/2d/CCAtlasNode.h index 63125c6d33..e35c14942d 100644 --- a/cocos/2d/CCAtlasNode.h +++ b/cocos/2d/CCAtlasNode.h @@ -57,7 +57,7 @@ public: * @param tileHeight The height of the item. * @param itemsToRender The quantity of items to render. */ - static AtlasNode* create(std::string_view filename, int tileWidth, int tileHeight, int itemsToRender); + static AtlasNode* create(const std::string& filename, int tileWidth, int tileHeight, int itemsToRender); /** updates the Atlas (indexed vertex array). * Shall be overridden in subclasses. @@ -106,7 +106,7 @@ public: /** Initializes an AtlasNode with an Atlas file the width and height of each item and the quantity of items to * render*/ - bool initWithTileFile(std::string_view tile, int tileWidth, int tileHeight, int itemsToRender); + bool initWithTileFile(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender); /** Initializes an AtlasNode with a texture the width and height of each item measured in points and the quantity * of items to render*/ diff --git a/cocos/2d/CCAutoPolygon.cpp b/cocos/2d/CCAutoPolygon.cpp index 6cec415131..6becd122ec 100644 --- a/cocos/2d/CCAutoPolygon.cpp +++ b/cocos/2d/CCAutoPolygon.cpp @@ -168,7 +168,7 @@ float PolygonInfo::getArea() const return area; } -AutoPolygon::AutoPolygon(std::string_view filename) +AutoPolygon::AutoPolygon(const std::string& filename) : _image(nullptr), _data(nullptr), _filename(""), _width(0), _height(0), _scaleFactor(0) { _filename = filename; @@ -714,7 +714,7 @@ PolygonInfo AutoPolygon::generateTriangles(const Rect& rect, float epsilon, floa return ret; } -PolygonInfo AutoPolygon::generatePolygon(std::string_view filename, const Rect& rect, float epsilon, float threshold) +PolygonInfo AutoPolygon::generatePolygon(const std::string& filename, const Rect& rect, float epsilon, float threshold) { AutoPolygon ap(filename); return ap.generateTriangles(rect, epsilon, threshold); diff --git a/cocos/2d/CCAutoPolygon.h b/cocos/2d/CCAutoPolygon.h index 676c6bd03b..1552ab99af 100644 --- a/cocos/2d/CCAutoPolygon.h +++ b/cocos/2d/CCAutoPolygon.h @@ -117,8 +117,8 @@ public: const Rect& getRect() const { return _rect; } void setRect(const Rect& rect) { _rect = rect; } - std::string_view getFilename() const { return _filename; } - void setFilename(std::string_view filename) { _filename = filename; } + const std::string& getFilename() const { return _filename; } + void setFilename(const std::string& filename) { _filename = filename; } // FIXME: this should be a property, not a public ivar TrianglesCommand::Triangles triangles; @@ -147,7 +147,7 @@ public: * @param filename a path to image file, e.g., "scene1/monster.png". * @return an AutoPolygon object; */ - AutoPolygon(std::string_view filename); + AutoPolygon(const std::string& filename); /** * Destructor of AutoPolygon. @@ -254,7 +254,7 @@ public: * auto sp = Sprite::create(AutoPolygon::generatePolygon("grossini.png")); * @endcode */ - static PolygonInfo generatePolygon(std::string_view filename, + static PolygonInfo generatePolygon(const std::string& filename, const Rect& rect = Rect::ZERO, float epsilon = 2.0f, float threshold = 0.05f); diff --git a/cocos/2d/CCCameraBackgroundBrush.cpp b/cocos/2d/CCCameraBackgroundBrush.cpp index f983bfa87f..442ca25bcb 100644 --- a/cocos/2d/CCCameraBackgroundBrush.cpp +++ b/cocos/2d/CCCameraBackgroundBrush.cpp @@ -71,12 +71,12 @@ CameraBackgroundDepthBrush* CameraBackgroundBrush::createDepthBrush(float depth) return CameraBackgroundDepthBrush::create(depth); } -CameraBackgroundSkyBoxBrush* CameraBackgroundBrush::createSkyboxBrush(std::string_view positive_x, - std::string_view negative_x, - std::string_view positive_y, - std::string_view negative_y, - std::string_view positive_z, - std::string_view negative_z) +CameraBackgroundSkyBoxBrush* CameraBackgroundBrush::createSkyboxBrush(const std::string& positive_x, + const std::string& negative_x, + const std::string& positive_y, + const std::string& negative_y, + const std::string& positive_z, + const std::string& negative_z) { return CameraBackgroundSkyBoxBrush::create(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z); } @@ -303,12 +303,12 @@ CameraBackgroundSkyBoxBrush::~CameraBackgroundSkyBoxBrush() #endif } -CameraBackgroundSkyBoxBrush* CameraBackgroundSkyBoxBrush::create(std::string_view positive_x, - std::string_view negative_x, - std::string_view positive_y, - std::string_view negative_y, - std::string_view positive_z, - std::string_view negative_z) +CameraBackgroundSkyBoxBrush* CameraBackgroundSkyBoxBrush::create(const std::string& positive_x, + const std::string& negative_x, + const std::string& positive_y, + const std::string& negative_y, + const std::string& positive_z, + const std::string& negative_z) { CameraBackgroundSkyBoxBrush* ret = nullptr; diff --git a/cocos/2d/CCCameraBackgroundBrush.h b/cocos/2d/CCCameraBackgroundBrush.h index 630b1a87e3..1f884cff85 100644 --- a/cocos/2d/CCCameraBackgroundBrush.h +++ b/cocos/2d/CCCameraBackgroundBrush.h @@ -105,12 +105,12 @@ public: @param negative_z texture for the rear side of the texture cube face. @return A new brush inited with given parameters. */ - static CameraBackgroundSkyBoxBrush* createSkyboxBrush(std::string_view positive_x, - std::string_view negative_x, - std::string_view positive_y, - std::string_view negative_y, - std::string_view positive_z, - std::string_view negative_z); + static CameraBackgroundSkyBoxBrush* createSkyboxBrush(const std::string& positive_x, + const std::string& negative_x, + const std::string& positive_y, + const std::string& negative_y, + const std::string& positive_z, + const std::string& negative_z); /** * draw the background */ @@ -253,12 +253,12 @@ public: @param negative_z texture for the rear side of the texture cube face. @return A new brush inited with given parameters. */ - static CameraBackgroundSkyBoxBrush* create(std::string_view positive_x, - std::string_view negative_x, - std::string_view positive_y, - std::string_view negative_y, - std::string_view positive_z, - std::string_view negative_z); + static CameraBackgroundSkyBoxBrush* create(const std::string& positive_x, + const std::string& negative_x, + const std::string& positive_y, + const std::string& negative_y, + const std::string& positive_z, + const std::string& negative_z); /** Creates a Skybox brush with 6 textures. */ diff --git a/cocos/2d/CCComponent.h b/cocos/2d/CCComponent.h index 6fa5ff0859..d780a665e6 100644 --- a/cocos/2d/CCComponent.h +++ b/cocos/2d/CCComponent.h @@ -60,8 +60,8 @@ public: bool isEnabled() const { return _enabled; } virtual void setEnabled(bool enabled); - std::string_view getName() const { return _name; } - virtual void setName(std::string_view name) { _name = name; } + const std::string& getName() const { return _name; } + virtual void setName(const std::string& name) { _name = name; } Node* getOwner() const { return _owner; } virtual void setOwner(Node* owner); diff --git a/cocos/2d/CCComponentContainer.cpp b/cocos/2d/CCComponentContainer.cpp index 456fcb8783..92f5788415 100644 --- a/cocos/2d/CCComponentContainer.cpp +++ b/cocos/2d/CCComponentContainer.cpp @@ -33,7 +33,7 @@ ComponentContainer::ComponentContainer(Node* node) : _owner(node) {} ComponentContainer::~ComponentContainer() {} -Component* ComponentContainer::get(std::string_view name) const +Component* ComponentContainer::get(const std::string& name) const { Component* ret = nullptr; @@ -60,7 +60,7 @@ bool ComponentContainer::add(Component* com) CCASSERT(false, "ComponentContainer already have this kind of component"); break; } - hlookup::set_item(_componentMap, componentName, com); //_componentMap[componentName] = com; + _componentMap[componentName] = com; com->retain(); com->setOwner(_owner); com->onAdd(); @@ -70,7 +70,7 @@ bool ComponentContainer::add(Component* com) return ret; } -bool ComponentContainer::remove(std::string_view componentName) +bool ComponentContainer::remove(const std::string& componentName) { bool ret = false; do diff --git a/cocos/2d/CCComponentContainer.h b/cocos/2d/CCComponentContainer.h index bdc08df759..caba0e1a24 100644 --- a/cocos/2d/CCComponentContainer.h +++ b/cocos/2d/CCComponentContainer.h @@ -54,10 +54,10 @@ public: /** * @js getComponent */ - Component* get(std::string_view name) const; + Component* get(const std::string& name) const; bool add(Component* com); - bool remove(std::string_view name); + bool remove(const std::string& name); bool remove(Component* com); void removeAll(); void visit(float delta); @@ -68,7 +68,7 @@ public: bool isEmpty() const { return _componentMap.empty(); } private: - hlookup::string_map _componentMap; + std::unordered_map _componentMap; Node* _owner; friend class Node; diff --git a/cocos/2d/CCFastTMXLayer.cpp b/cocos/2d/CCFastTMXLayer.cpp index 566eae8223..c3f82291a9 100644 --- a/cocos/2d/CCFastTMXLayer.cpp +++ b/cocos/2d/CCFastTMXLayer.cpp @@ -799,7 +799,7 @@ void FastTMXLayer::removeChild(Node* node, bool cleanup) } // TMXLayer - Properties -Value FastTMXLayer::getProperty(std::string_view propertyName) const +Value FastTMXLayer::getProperty(const std::string& propertyName) const { auto propItr = _properties.find(propertyName); if (propItr != _properties.end()) diff --git a/cocos/2d/CCFastTMXLayer.h b/cocos/2d/CCFastTMXLayer.h index 0da9a39e8d..0c69484ed8 100644 --- a/cocos/2d/CCFastTMXLayer.h +++ b/cocos/2d/CCFastTMXLayer.h @@ -152,7 +152,7 @@ public: * @param propertyName The value for the specific property name. * @return The value for the specific property name. */ - Value getProperty(std::string_view propertyName) const; + Value getProperty(const std::string& propertyName) const; /** Creates the tiles. */ void setupTiles(); @@ -161,13 +161,13 @@ public: * * @return The tile layer name. */ - std::string_view getLayerName() { return _layerName; } + const std::string& getLayerName() { return _layerName; } /** Set the tile layer name. * * @param layerName The new layer name. */ - void setLayerName(std::string_view layerName) { _layerName = layerName; } + void setLayerName(const std::string& layerName) { _layerName = layerName; } /** Gets the size of the layer in tiles. * diff --git a/cocos/2d/CCFastTMXTiledMap.cpp b/cocos/2d/CCFastTMXTiledMap.cpp index d06d483a7c..b17ff6328f 100644 --- a/cocos/2d/CCFastTMXTiledMap.cpp +++ b/cocos/2d/CCFastTMXTiledMap.cpp @@ -33,7 +33,7 @@ NS_CC_BEGIN // implementation FastTMXTiledMap -FastTMXTiledMap* FastTMXTiledMap::create(std::string_view tmxFile) +FastTMXTiledMap* FastTMXTiledMap::create(const std::string& tmxFile) { FastTMXTiledMap* ret = new FastTMXTiledMap(); if (ret->initWithTMXFile(tmxFile)) @@ -45,7 +45,7 @@ FastTMXTiledMap* FastTMXTiledMap::create(std::string_view tmxFile) return nullptr; } -FastTMXTiledMap* FastTMXTiledMap::createWithXML(std::string_view tmxString, std::string_view resourcePath) +FastTMXTiledMap* FastTMXTiledMap::createWithXML(const std::string& tmxString, const std::string& resourcePath) { FastTMXTiledMap* ret = new FastTMXTiledMap(); if (ret->initWithXML(tmxString, resourcePath)) @@ -57,7 +57,7 @@ FastTMXTiledMap* FastTMXTiledMap::createWithXML(std::string_view tmxString, std: return nullptr; } -bool FastTMXTiledMap::initWithTMXFile(std::string_view tmxFile) +bool FastTMXTiledMap::initWithTMXFile(const std::string& tmxFile) { CCASSERT(tmxFile.size() > 0, "FastTMXTiledMap: tmx file should not be empty"); @@ -77,7 +77,7 @@ bool FastTMXTiledMap::initWithTMXFile(std::string_view tmxFile) return true; } -bool FastTMXTiledMap::initWithXML(std::string_view tmxString, std::string_view resourcePath) +bool FastTMXTiledMap::initWithXML(const std::string& tmxString, const std::string& resourcePath) { setContentSize(Vec2::ZERO); @@ -194,7 +194,7 @@ void FastTMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo) } // public -FastTMXLayer* FastTMXTiledMap::getLayer(std::string_view layerName) const +FastTMXLayer* FastTMXTiledMap::getLayer(const std::string& layerName) const { CCASSERT(!layerName.empty(), "Invalid layer name!"); @@ -214,7 +214,7 @@ FastTMXLayer* FastTMXTiledMap::getLayer(std::string_view layerName) const return nullptr; } -TMXObjectGroup* FastTMXTiledMap::getObjectGroup(std::string_view groupName) const +TMXObjectGroup* FastTMXTiledMap::getObjectGroup(const std::string& groupName) const { CCASSERT(!groupName.empty(), "Invalid group name!"); @@ -233,7 +233,7 @@ TMXObjectGroup* FastTMXTiledMap::getObjectGroup(std::string_view groupName) cons return nullptr; } -Value FastTMXTiledMap::getProperty(std::string_view propertyName) const +Value FastTMXTiledMap::getProperty(const std::string& propertyName) const { auto propsItr = _properties.find(propertyName); if (propsItr != _properties.end()) diff --git a/cocos/2d/CCFastTMXTiledMap.h b/cocos/2d/CCFastTMXTiledMap.h index 9790ea746b..da7a0273ac 100644 --- a/cocos/2d/CCFastTMXTiledMap.h +++ b/cocos/2d/CCFastTMXTiledMap.h @@ -101,7 +101,7 @@ public: * * @return An autorelease object. */ - static FastTMXTiledMap* create(std::string_view tmxFile); + static FastTMXTiledMap* create(const std::string& tmxFile); /** Initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources. * @@ -109,25 +109,25 @@ public: * @param resourcePath A path to TMX resources. * @return An autorelease object. */ - static FastTMXTiledMap* createWithXML(std::string_view tmxString, std::string_view resourcePath); + static FastTMXTiledMap* createWithXML(const std::string& tmxString, const std::string& resourcePath); /** Return the FastTMXLayer for the specific layer. * * @return Return the FastTMXLayer for the specific layer. */ - FastTMXLayer* getLayer(std::string_view layerName) const; + FastTMXLayer* getLayer(const std::string& layerName) const; /** Return the TMXObjectGroup for the specific group. * * @return Return the TMXObjectGroup for the specific group. */ - TMXObjectGroup* getObjectGroup(std::string_view groupName) const; + TMXObjectGroup* getObjectGroup(const std::string& groupName) const; /** Return the value for the specific property name. * * @return Return the value for the specific property name. */ - Value getProperty(std::string_view propertyName) const; + Value getProperty(const std::string& propertyName) const; /** Return properties dictionary for tile GID. * @@ -207,7 +207,7 @@ public: int getLayerCount() const { return _layerCount; } - std::string_view getResourceFile() const { return _tmxFile; } + const std::string& getResourceFile() const { return _tmxFile; } CC_CONSTRUCTOR_ACCESS : /** @@ -221,10 +221,10 @@ public: virtual ~FastTMXTiledMap(); /** initializes a TMX Tiled Map with a TMX file */ - bool initWithTMXFile(std::string_view tmxFile); + bool initWithTMXFile(const std::string& tmxFile); /** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ - bool initWithXML(std::string_view tmxString, std::string_view resourcePath); + bool initWithXML(const std::string& tmxString, const std::string& resourcePath); protected: FastTMXLayer* parseLayer(TMXLayerInfo* layerInfo, TMXMapInfo* mapInfo); diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index fc1aabd928..df0db9bc02 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -520,9 +520,9 @@ void FontAtlas::setLineHeight(float newHeight) _lineHeight = newHeight; } -std::string_view FontAtlas::getFontName() const +std::string FontAtlas::getFontName() const { - std::string_view fontName = _fontFreeType ? _fontFreeType->getFontName() : ""sv; + std::string fontName = _fontFreeType ? _fontFreeType->getFontName() : ""; if (fontName.empty()) return fontName; auto idx = fontName.rfind('/'); diff --git a/cocos/2d/CCFontAtlas.h b/cocos/2d/CCFontAtlas.h index 16bcfc72a8..384aecb254 100644 --- a/cocos/2d/CCFontAtlas.h +++ b/cocos/2d/CCFontAtlas.h @@ -86,7 +86,7 @@ public: float getLineHeight() const { return _lineHeight; } void setLineHeight(float newHeight); - std::string_view getFontName() const; + std::string getFontName() const; Texture2D* getTexture(int slot); const Font* getFont() const { return _font; } diff --git a/cocos/2d/CCFontAtlasCache.cpp b/cocos/2d/CCFontAtlasCache.cpp index 4ab9771720..d9df5ab566 100644 --- a/cocos/2d/CCFontAtlasCache.cpp +++ b/cocos/2d/CCFontAtlasCache.cpp @@ -36,7 +36,7 @@ NS_CC_BEGIN -hlookup::string_map FontAtlasCache::_atlasMap; +std::unordered_map FontAtlasCache::_atlasMap; #define ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE 255 void FontAtlasCache::purgeCachedData() @@ -80,7 +80,8 @@ FontAtlas* FontAtlasCache::getFontAtlasTTF(const _ttfConfig* config) auto tempAtlas = font->newFontAtlas(); if (tempAtlas) { - return _atlasMap.emplace(atlasName, tempAtlas).first->second; + _atlasMap[atlasName] = tempAtlas; + return _atlasMap[atlasName]; } } } @@ -90,17 +91,16 @@ FontAtlas* FontAtlasCache::getFontAtlasTTF(const _ttfConfig* config) return nullptr; } -FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName) +FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName) { return getFontAtlasFNT(fontFileName, Rect::ZERO, false); } -FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName, std::string_view subTextureKey) +FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName, const std::string& subTextureKey) { const auto realFontFilename = FileUtils::getInstance()->getNewFilename( fontFileName); // resolves real file path, to prevent storing multiple atlases for the same file. - std::string atlasName{subTextureKey}; - atlasName.append(" ", 1).append(realFontFilename); + std::string atlasName = subTextureKey + " " + realFontFilename; const auto it = _atlasMap.find(atlasName); if (it == _atlasMap.end()) @@ -123,7 +123,7 @@ FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName, std::s return nullptr; } -FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName, const Rect& imageRect, bool imageRotated) +FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName, const Rect& imageRect, bool imageRotated) { const auto realFontFilename = FileUtils::getInstance()->getNewFilename( fontFileName); // resolves real file path, to prevent storing multiple atlases for the same file. @@ -153,14 +153,14 @@ FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName, const return nullptr; } -FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName, const Vec2& imageOffset) +FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName, const Vec2& imageOffset) { return getFontAtlasFNT(fontFileName, Rect(imageOffset.x, imageOffset.y, 0, 0), false); } -FontAtlas* FontAtlasCache::getFontAtlasCharMap(std::string_view plistFile) +FontAtlas* FontAtlasCache::getFontAtlasCharMap(const std::string& plistFile) { - std::string_view atlasName = plistFile; + const std::string& atlasName = plistFile; auto it = _atlasMap.find(atlasName); if (it == _atlasMap.end()) @@ -172,8 +172,8 @@ FontAtlas* FontAtlasCache::getFontAtlasCharMap(std::string_view plistFile) auto tempAtlas = font->newFontAtlas(); if (tempAtlas) { - hlookup::set_item(_atlasMap, atlasName, tempAtlas); // _atlasMap[atlasName] = tempAtlas; - return tempAtlas; + _atlasMap[atlasName] = tempAtlas; + return _atlasMap[atlasName]; } } } @@ -210,7 +210,7 @@ FontAtlas* FontAtlasCache::getFontAtlasCharMap(Texture2D* texture, int itemWidth return nullptr; } -FontAtlas* FontAtlasCache::getFontAtlasCharMap(std::string_view charMapFile, +FontAtlas* FontAtlasCache::getFontAtlasCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) @@ -263,7 +263,7 @@ bool FontAtlasCache::releaseFontAtlas(FontAtlas* atlas) return false; } -void FontAtlasCache::reloadFontAtlasFNT(std::string_view fontFileName, const Rect& imageRect, bool imageRotated) +void FontAtlasCache::reloadFontAtlasFNT(const std::string& fontFileName, const Rect& imageRect, bool imageRotated) { char keyPrefix[ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE]; snprintf(keyPrefix, ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE, "%.2f %.2f ", imageRect.origin.x, imageRect.origin.y); @@ -288,12 +288,12 @@ void FontAtlasCache::reloadFontAtlasFNT(std::string_view fontFileName, const Rec } } -void FontAtlasCache::reloadFontAtlasFNT(std::string_view fontFileName, const Vec2& imageOffset) +void FontAtlasCache::reloadFontAtlasFNT(const std::string& fontFileName, const Vec2& imageOffset) { reloadFontAtlasFNT(fontFileName, Rect(imageOffset.x, imageOffset.y, 0, 0), false); } -void FontAtlasCache::unloadFontAtlasTTF(std::string_view fontFileName) +void FontAtlasCache::unloadFontAtlasTTF(const std::string& fontFileName) { auto item = _atlasMap.begin(); while (item != _atlasMap.end()) diff --git a/cocos/2d/CCFontAtlasCache.h b/cocos/2d/CCFontAtlasCache.h index f02e41ad22..d995d2a92f 100644 --- a/cocos/2d/CCFontAtlasCache.h +++ b/cocos/2d/CCFontAtlasCache.h @@ -43,17 +43,17 @@ class CC_DLL FontAtlasCache public: static FontAtlas* getFontAtlasTTF(const _ttfConfig* config); - static FontAtlas* getFontAtlasFNT(std::string_view fontFileName); - static FontAtlas* getFontAtlasFNT(std::string_view fontFileName, std::string_view subTextureKey); - static FontAtlas* getFontAtlasFNT(std::string_view fontFileName, const Rect& imageRect, bool imageRotated); - CC_DEPRECATED_ATTRIBUTE static FontAtlas* getFontAtlasFNT(std::string_view fontFileName, const Vec2& imageOffset); + static FontAtlas* getFontAtlasFNT(const std::string& fontFileName); + static FontAtlas* getFontAtlasFNT(const std::string& fontFileName, const std::string& subTextureKey); + static FontAtlas* getFontAtlasFNT(const std::string& fontFileName, const Rect& imageRect, bool imageRotated); + CC_DEPRECATED_ATTRIBUTE static FontAtlas* getFontAtlasFNT(const std::string& fontFileName, const Vec2& imageOffset); - static FontAtlas* getFontAtlasCharMap(std::string_view charMapFile, + static FontAtlas* getFontAtlasCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); static FontAtlas* getFontAtlasCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); - static FontAtlas* getFontAtlasCharMap(std::string_view plistFile); + static FontAtlas* getFontAtlasCharMap(const std::string& plistFile); static bool releaseFontAtlas(FontAtlas* atlas); @@ -66,19 +66,19 @@ public: CAUTION : All component use this font texture should be reset font name, though the file name is same! otherwise, it will cause program crash! */ - static void reloadFontAtlasFNT(std::string_view fontFileName, const Rect& imageRect, bool imageRotated); + static void reloadFontAtlasFNT(const std::string& fontFileName, const Rect& imageRect, bool imageRotated); - CC_DEPRECATED_ATTRIBUTE static void reloadFontAtlasFNT(std::string_view fontFileName, + CC_DEPRECATED_ATTRIBUTE static void reloadFontAtlasFNT(const std::string& fontFileName, const Vec2& imageOffset = Vec2::ZERO); /** Unload all texture atlas texture create by special file name. CAUTION : All component use this font texture should be reset font name, though the file name is same! otherwise, it will cause program crash! */ - static void unloadFontAtlasTTF(std::string_view fontFileName); + static void unloadFontAtlasTTF(const std::string& fontFileName); private: - static hlookup::string_map _atlasMap; + static std::unordered_map _atlasMap; }; NS_CC_END diff --git a/cocos/2d/CCFontCharMap.cpp b/cocos/2d/CCFontCharMap.cpp index 8eb4986c83..c8625143b9 100644 --- a/cocos/2d/CCFontCharMap.cpp +++ b/cocos/2d/CCFontCharMap.cpp @@ -33,7 +33,7 @@ NS_CC_BEGIN -FontCharMap* FontCharMap::create(std::string_view plistFile) +FontCharMap* FontCharMap::create(const std::string& plistFile) { std::string pathStr = FileUtils::getInstance()->fullPathForFilename(plistFile); std::string relPathStr = pathStr.substr(0, pathStr.find_last_of('/')) + "/"; @@ -64,7 +64,7 @@ FontCharMap* FontCharMap::create(std::string_view plistFile) return tempFont; } -FontCharMap* FontCharMap::create(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap) +FontCharMap* FontCharMap::create(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) { Texture2D* tempTexture = Director::getInstance()->getTextureCache()->addImage(charMapFile); diff --git a/cocos/2d/CCFontCharMap.h b/cocos/2d/CCFontCharMap.h index 436290471d..1c57657196 100644 --- a/cocos/2d/CCFontCharMap.h +++ b/cocos/2d/CCFontCharMap.h @@ -38,9 +38,9 @@ class Texture2D; class FontCharMap : public Font { public: - static FontCharMap* create(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap); + static FontCharMap* create(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); static FontCharMap* create(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); - static FontCharMap* create(std::string_view plistFile); + static FontCharMap* create(const std::string& plistFile); virtual int* getHorizontalKerningForTextUTF32(const std::u32string& text, int& outNumLetters) const override; virtual FontAtlas* newFontAtlas() override; diff --git a/cocos/2d/CCFontFNT.cpp b/cocos/2d/CCFontFNT.cpp index 87fa76440d..d3b252a4b2 100644 --- a/cocos/2d/CCFontFNT.cpp +++ b/cocos/2d/CCFontFNT.cpp @@ -56,15 +56,15 @@ struct _FontDefHashElement; // // FNTConfig Cache - free functions // -static StringMap* s_configurations = nullptr; +static Map* s_configurations = nullptr; -BMFontConfiguration* FNTConfigLoadFile(std::string_view fntFile) +BMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile) { BMFontConfiguration* ret = nullptr; if (s_configurations == nullptr) { - s_configurations = new StringMap(); + s_configurations = new Map(); } ret = s_configurations->at(fntFile); @@ -84,7 +84,7 @@ BMFontConfiguration* FNTConfigLoadFile(std::string_view fntFile) // BitmapFontConfiguration // -BMFontConfiguration* BMFontConfiguration::create(std::string_view FNTfile) +BMFontConfiguration* BMFontConfiguration::create(const std::string& FNTfile) { BMFontConfiguration* ret = new BMFontConfiguration(); if (ret->initWithFNTfile(FNTfile)) @@ -96,7 +96,7 @@ BMFontConfiguration* BMFontConfiguration::create(std::string_view FNTfile) return nullptr; } -bool BMFontConfiguration::initWithFNTfile(std::string_view FNTfile) +bool BMFontConfiguration::initWithFNTfile(const std::string& FNTfile) { _characterSet = this->parseConfigFile(FNTfile); @@ -141,7 +141,7 @@ void BMFontConfiguration::purgeFontDefDictionary() _fontDefDictionary.clear(); } -std::set* BMFontConfiguration::parseConfigFile(std::string_view controlFile) +std::set* BMFontConfiguration::parseConfigFile(const std::string& controlFile) { std::string data = FileUtils::getInstance()->getStringFromFile(controlFile); if (data.empty()) @@ -156,7 +156,7 @@ std::set* BMFontConfiguration::parseConfigFile(std::string_view co } if (data[0] == 0) { - CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.data()); + CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.c_str()); return nullptr; } auto contents = data.c_str(); @@ -223,7 +223,7 @@ std::set* BMFontConfiguration::parseConfigFile(std::string_view co std::set* BMFontConfiguration::parseBinaryConfigFile(unsigned char* pData, uint32_t size, - std::string_view controlFile) + const std::string& controlFile) { /* based on http://www.angelcode.com/products/bmfont/doc/file_format.html file format */ @@ -399,7 +399,7 @@ std::set* BMFontConfiguration::parseBinaryConfigFile(unsigned char return validCharsString; } -void BMFontConfiguration::parseImageFileName(const char* line, std::string_view fntFile) +void BMFontConfiguration::parseImageFileName(const char* line, const std::string& fntFile) { ////////////////////////////////////////////////////////////////////////// // line to parse: @@ -528,7 +528,7 @@ void BMFontConfiguration::parseKerningEntry(const char* line) _kerningDictionary[key] = amount; } -FontFNT* FontFNT::create(std::string_view fntFilePath, const Rect& imageRect, bool imageRotated) +FontFNT* FontFNT::create(const std::string& fntFilePath, const Rect& imageRect, bool imageRotated) { const auto newConf = FNTConfigLoadFile(fntFilePath); if (!newConf) @@ -545,7 +545,7 @@ FontFNT* FontFNT::create(std::string_view fntFilePath, const Rect& imageRect, bo return tempFont; } -FontFNT* FontFNT::create(std::string_view fntFilePath, std::string_view subTextureKey) +FontFNT* FontFNT::create(const std::string& fntFilePath, const std::string& subTextureKey) { const auto newConf = FNTConfigLoadFile(fntFilePath); if (!newConf) @@ -567,7 +567,7 @@ FontFNT* FontFNT::create(std::string_view fntFilePath, std::string_view subTextu return tempFont; } -FontFNT* FontFNT::create(std::string_view fntFilePath) +FontFNT* FontFNT::create(const std::string& fntFilePath) { const auto newConf = FNTConfigLoadFile(fntFilePath); if (!newConf) @@ -590,7 +590,7 @@ FontFNT* FontFNT::create(std::string_view fntFilePath) return tempFont; } -FontFNT* FontFNT::create(std::string_view fntFilePath, const Vec2& imageOffset) +FontFNT* FontFNT::create(const std::string& fntFilePath, const Vec2& imageOffset) { return create(fntFilePath, Rect(imageOffset.x, imageOffset.y, 0, 0), false); } @@ -762,11 +762,11 @@ FontAtlas* FontFNT::newFontAtlas() return tempAtlas; } -void FontFNT::reloadBMFontResource(std::string_view fntFilePath) +void FontFNT::reloadBMFontResource(const std::string& fntFilePath) { if (s_configurations == nullptr) { - s_configurations = new StringMap(); + s_configurations = new Map(); } BMFontConfiguration* ret = s_configurations->at(fntFilePath); diff --git a/cocos/2d/CCFontFNT.h b/cocos/2d/CCFontFNT.h index a255920330..3e6cb364a6 100644 --- a/cocos/2d/CCFontFNT.h +++ b/cocos/2d/CCFontFNT.h @@ -115,27 +115,27 @@ public: std::string description() const; /** allocates a BMFontConfiguration with a FNT file */ - static BMFontConfiguration* create(std::string_view FNTfile); + static BMFontConfiguration* create(const std::string& FNTfile); /** initializes a BitmapFontConfiguration with a FNT file */ - bool initWithFNTfile(std::string_view FNTfile); + bool initWithFNTfile(const std::string& FNTfile); - std::string_view getAtlasName() { return _atlasName; } - void setAtlasName(std::string_view atlasName) { _atlasName = atlasName; } + const std::string& getAtlasName() { return _atlasName; } + void setAtlasName(const std::string& atlasName) { _atlasName = atlasName; } std::set* getCharacterSet() const; protected: - virtual std::set* parseConfigFile(std::string_view controlFile); + virtual std::set* parseConfigFile(const std::string& controlFile); virtual std::set* parseBinaryConfigFile(unsigned char* pData, uint32_t size, - std::string_view controlFile); + const std::string& controlFile); private: unsigned int parseCharacterDefinition(const char* line); void parseInfoArguments(const char* line); void parseCommonArguments(const char* line); - void parseImageFileName(const char* line, std::string_view fntFile); + void parseImageFileName(const char* line, const std::string& fntFile); void parseKerningEntry(const char* line); void purgeKerningDictionary(); void purgeFontDefDictionary(); @@ -145,11 +145,12 @@ class CC_DLL FontFNT : public Font { public: - static FontFNT* create(std::string_view fntFilePath, const Rect& imageRect, bool imageRotated); - static FontFNT* create(std::string_view fntFilePath, std::string_view subTextureKey); - static FontFNT* create(std::string_view fntFilePath); + static FontFNT* create(const std::string& fntFilePath, const Rect& imageRect, bool imageRotated); + static FontFNT* create(const std::string& fntFilePath, const std::string& subTextureKey); + static FontFNT* create(const std::string& fntFilePath); - CC_DEPRECATED_ATTRIBUTE static FontFNT* create(std::string_view fntFilePath, const Vec2& imageOffset = Vec2::ZERO); + CC_DEPRECATED_ATTRIBUTE static FontFNT* create(const std::string& fntFilePath, + const Vec2& imageOffset = Vec2::ZERO); /** Purges the cached data. Removes from memory the cached configurations and the atlas name dictionary. @@ -163,7 +164,7 @@ public: int getOriginalFontSize() const; - static void reloadBMFontResource(std::string_view fntFilePath); + static void reloadBMFontResource(const std::string& fntFilePath); protected: FontFNT(BMFontConfiguration* theContfig, const Rect& imageRect, bool imageRotated); diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index c038926bc7..4a93709cb1 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -653,7 +653,7 @@ std::string_view FontFreeType::getGlyphCollection() const return glyphCollection; } -void FontFreeType::releaseFont(std::string_view fontName) +void FontFreeType::releaseFont(const std::string& fontName) { auto item = s_cacheFontData.begin(); while (s_cacheFontData.end() != item) diff --git a/cocos/2d/CCFontFreeType.h b/cocos/2d/CCFontFreeType.h index 505812e87c..177571476b 100644 --- a/cocos/2d/CCFontFreeType.h +++ b/cocos/2d/CCFontFreeType.h @@ -101,12 +101,12 @@ public: int getFontAscender() const; const char* getFontFamily() const; - std::string_view getFontName() const { return _fontName; } + const std::string& getFontName() const { return _fontName; } virtual FontAtlas* newFontAtlas() override; virtual int getFontMaxHeight() const override { return _lineHeight; } - static void releaseFont(std::string_view fontName); + static void releaseFont(const std::string& fontName); static FT_Library getFTLibrary(); diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index e7f8a81943..a184fa67d3 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -240,8 +240,8 @@ Label* Label::create() return ret; } -Label* Label::createWithSystemFont(std::string_view text, - std::string_view font, +Label* Label::createWithSystemFont(const std::string& text, + const std::string& font, float fontSize, const Vec2& dimensions /* = Vec2::ZERO */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, @@ -259,8 +259,8 @@ Label* Label::createWithSystemFont(std::string_view text, return ret; } -Label* Label::createWithTTF(std::string_view text, - std::string_view fontFile, +Label* Label::createWithTTF(const std::string& text, + const std::string& fontFile, float fontSize, const Vec2& dimensions /* = Vec2::ZERO */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, @@ -279,7 +279,7 @@ Label* Label::createWithTTF(std::string_view text, } Label* Label::createWithTTF(const TTFConfig& ttfConfig, - std::string_view text, + const std::string& text, TextHAlignment hAlignment /* = TextHAlignment::CENTER */, int maxLineWidth /* = 0 */) { @@ -295,8 +295,8 @@ Label* Label::createWithTTF(const TTFConfig& ttfConfig, return nullptr; } -Label* Label::createWithBMFont(std::string_view bmfontPath, - std::string_view text, +Label* Label::createWithBMFont(const std::string& bmfontPath, + const std::string& text, const TextHAlignment& hAlignment, int maxLineWidth) { @@ -315,8 +315,8 @@ Label* Label::createWithBMFont(std::string_view bmfontPath, return nullptr; } -Label* Label::createWithBMFont(std::string_view bmfontPath, - std::string_view text, +Label* Label::createWithBMFont(const std::string& bmfontPath, + const std::string& text, const TextHAlignment& hAlignment, int maxLineWidth, const Rect& imageRect, @@ -337,11 +337,11 @@ Label* Label::createWithBMFont(std::string_view bmfontPath, return nullptr; } -Label* Label::createWithBMFont(std::string_view bmfontPath, - std::string_view text, +Label* Label::createWithBMFont(const std::string& bmfontPath, + const std::string& text, const TextHAlignment& hAlignment, int maxLineWidth, - std::string_view subTextureKey) + const std::string& subTextureKey) { auto ret = new Label(hAlignment); @@ -358,8 +358,8 @@ Label* Label::createWithBMFont(std::string_view bmfontPath, return nullptr; } -Label* Label::createWithBMFont(std::string_view bmfontPath, - std::string_view text, +Label* Label::createWithBMFont(const std::string& bmfontPath, + const std::string& text, const TextHAlignment& hAlignment, int maxLineWidth, const Vec2& imageOffset) @@ -368,7 +368,7 @@ Label* Label::createWithBMFont(std::string_view bmfontPath, false); } -Label* Label::createWithCharMap(std::string_view plistFile) +Label* Label::createWithCharMap(const std::string& plistFile) { auto ret = new Label(); @@ -396,7 +396,7 @@ Label* Label::createWithCharMap(Texture2D* texture, int itemWidth, int itemHeigh return nullptr; } -Label* Label::createWithCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap) +Label* Label::createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) { auto ret = new Label(); @@ -410,7 +410,7 @@ Label* Label::createWithCharMap(std::string_view charMapFile, int itemWidth, int return nullptr; } -bool Label::setCharMap(std::string_view plistFile) +bool Label::setCharMap(const std::string& plistFile) { auto newAtlas = FontAtlasCache::getFontAtlasCharMap(plistFile); @@ -426,8 +426,8 @@ bool Label::setCharMap(std::string_view plistFile) return true; } -bool Label::initWithTTF(std::string_view text, - std::string_view fontFilePath, +bool Label::initWithTTF(const std::string& text, + const std::string& fontFilePath, float fontSize, const Vec2& dimensions, TextHAlignment /*hAlignment*/, @@ -447,7 +447,7 @@ bool Label::initWithTTF(std::string_view text, } bool Label::initWithTTF(const TTFConfig& ttfConfig, - std::string_view text, + const std::string& text, TextHAlignment /*hAlignment*/, int maxLineWidth) { @@ -476,7 +476,7 @@ bool Label::setCharMap(Texture2D* texture, int itemWidth, int itemHeight, int st return true; } -bool Label::setCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap) +bool Label::setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) { auto newAtlas = FontAtlasCache::getFontAtlasCharMap(charMapFile, itemWidth, itemHeight, startCharMap); @@ -841,7 +841,7 @@ bool Label::setTTFConfig(const TTFConfig& ttfConfig) return setTTFConfigInternal(ttfConfig); } -bool Label::setBMFontFilePath(std::string_view bmfontFilePath, float fontSize) +bool Label::setBMFontFilePath(const std::string& bmfontFilePath, float fontSize) { FontAtlas* newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath); @@ -875,7 +875,10 @@ bool Label::setBMFontFilePath(std::string_view bmfontFilePath, float fontSize) return true; } -bool Label::setBMFontFilePath(std::string_view bmfontFilePath, const Rect& imageRect, bool imageRotated, float fontSize) +bool Label::setBMFontFilePath(const std::string& bmfontFilePath, + const Rect& imageRect, + bool imageRotated, + float fontSize) { FontAtlas* newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath, imageRect, imageRotated); @@ -911,7 +914,7 @@ bool Label::setBMFontFilePath(std::string_view bmfontFilePath, const Rect& image return true; } -bool Label::setBMFontFilePath(std::string_view bmfontFilePath, std::string_view subTextureKey, float fontSize) +bool Label::setBMFontFilePath(const std::string& bmfontFilePath, const std::string& subTextureKey, float fontSize) { FontAtlas* newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath, subTextureKey); @@ -946,7 +949,7 @@ bool Label::setBMFontFilePath(std::string_view bmfontFilePath, std::string_view return true; } -bool Label::setBMFontFilePath(std::string_view bmfontFilePath, const Vec2& imageOffset, float fontSize) +bool Label::setBMFontFilePath(const std::string& bmfontFilePath, const Vec2& imageOffset, float fontSize) { return setBMFontFilePath(bmfontFilePath, Rect(imageOffset.x, imageOffset.y, 0, 0), false); } @@ -2102,7 +2105,7 @@ void Label::drawSelf(bool visibleByCamera, Renderer* renderer, uint32_t flags) } } -void Label::setSystemFontName(std::string_view systemFont) +void Label::setSystemFontName(const std::string& systemFont) { if (systemFont != _systemFont) { diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index fa3e5e57e8..66d4669cd8 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -166,8 +166,8 @@ public: * * @return An automatically released Label object. */ - static Label* createWithSystemFont(std::string_view text, - std::string_view font, + static Label* createWithSystemFont(const std::string& text, + const std::string& font, float fontSize, const Vec2& dimensions = Vec2::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT, @@ -185,8 +185,8 @@ public: * * @return An automatically released Label object. */ - static Label* createWithTTF(std::string_view text, - std::string_view fontFilePath, + static Label* createWithTTF(const std::string& text, + const std::string& fontFilePath, float fontSize, const Vec2& dimensions = Vec2::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT, @@ -204,7 +204,7 @@ public: * @see TTFConfig setTTFConfig setMaxLineWidth */ static Label* createWithTTF(const TTFConfig& ttfConfig, - std::string_view text, + const std::string& text, TextHAlignment hAlignment = TextHAlignment::LEFT, int maxLineWidth = 0); @@ -219,8 +219,8 @@ public: * @return An automatically released Label object. * @see setBMFontFilePath setMaxLineWidth */ - static Label* createWithBMFont(std::string_view bmfontPath, - std::string_view text, + static Label* createWithBMFont(const std::string& bmfontPath, + const std::string& text, const TextHAlignment& hAlignment = TextHAlignment::LEFT, int maxLineWidth = 0); @@ -237,8 +237,8 @@ public: * @return An automatically released Label object. * @see setBMFontFilePath setMaxLineWidth */ - static Label* createWithBMFont(std::string_view bmfontPath, - std::string_view text, + static Label* createWithBMFont(const std::string& bmfontPath, + const std::string& text, const TextHAlignment& hAlignment, int maxLineWidth, const Rect& imageRect, @@ -256,11 +256,11 @@ public: * @return An automatically released Label object. * @see setBMFontFilePath setMaxLineWidth */ - static Label* createWithBMFont(std::string_view bmfontPath, - std::string_view text, + static Label* createWithBMFont(const std::string& bmfontPath, + const std::string& text, const TextHAlignment& hAlignment, int maxLineWidth, - std::string_view subTextureKey); + const std::string& subTextureKey); /** * Allocates and initializes a Label, with a bitmap font file. @@ -274,8 +274,8 @@ public: * @return An automatically released Label object. * @see setBMFontFilePath setMaxLineWidth */ - CC_DEPRECATED_ATTRIBUTE static Label* createWithBMFont(std::string_view bmfontPath, - std::string_view text, + CC_DEPRECATED_ATTRIBUTE static Label* createWithBMFont(const std::string& bmfontPath, + const std::string& text, const TextHAlignment& hAlignment, int maxLineWidth, const Vec2& imageOffset); @@ -290,7 +290,7 @@ public: * * @return An automatically released Label object. */ - static Label* createWithCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap); + static Label* createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); /** * Allocates and initializes a Label, with char map configuration. @@ -311,7 +311,7 @@ public: * * @return An automatically released Label object. */ - static Label* createWithCharMap(std::string_view plistFile); + static Label* createWithCharMap(const std::string& plistFile); // end of creators group /// @} @@ -332,31 +332,33 @@ public: virtual const TTFConfig& getTTFConfig() const { return _fontConfig; } /** Sets a new bitmap font to Label */ - virtual bool setBMFontFilePath(std::string_view bmfontFilePath, float fontSize = 0); + virtual bool setBMFontFilePath(const std::string& bmfontFilePath, float fontSize = 0); /** Sets a new bitmap font to Label */ - virtual bool setBMFontFilePath(std::string_view bmfontFilePath, + virtual bool setBMFontFilePath(const std::string& bmfontFilePath, const Rect& imageRect, bool imageRotated, float fontSize = 0); /** Sets a new bitmap font to Label */ - virtual bool setBMFontFilePath(std::string_view bmfontFilePath, std::string_view subTextureKey, float fontSize = 0); + virtual bool setBMFontFilePath(const std::string& bmfontFilePath, + const std::string& subTextureKey, + float fontSize = 0); /** Sets a new bitmap font to Label */ - CC_DEPRECATED_ATTRIBUTE virtual bool setBMFontFilePath(std::string_view bmfontFilePath, + CC_DEPRECATED_ATTRIBUTE virtual bool setBMFontFilePath(const std::string& bmfontFilePath, const Vec2& imageOffset, float fontSize = 0); /** Returns the bitmap font used by the Label.*/ - std::string_view getBMFontFilePath() const { return _bmFontPath; } + const std::string& getBMFontFilePath() const { return _bmFontPath; } /** * Sets a new char map configuration to Label. * - * @see `createWithCharMap(std::string_view,int,int,int)` + * @see `createWithCharMap(const std::string&,int,int,int)` */ - virtual bool setCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap); + virtual bool setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); /** * Sets a new char map configuration to Label. @@ -368,9 +370,9 @@ public: /** * Sets a new char map configuration to Label. * - * @see `createWithCharMap(std::string_view)` + * @see `createWithCharMap(const std::string&)` */ - virtual bool setCharMap(std::string_view plistFile); + virtual bool setCharMap(const std::string& plistFile); /** * Sets a new system font to Label. @@ -378,10 +380,10 @@ public: * @param font A font file or a font family name. * @warning */ - virtual void setSystemFontName(std::string_view font); + virtual void setSystemFontName(const std::string& font); /** Returns the system font used by the Label.*/ - virtual std::string_view getSystemFontName() const { return _systemFont; } + virtual const std::string& getSystemFontName() const { return _systemFont; } /* Sets the system font size of Label.*/ virtual void setSystemFontSize(float fontSize); @@ -401,7 +403,7 @@ public: virtual void setString(std::string_view text) override; /** Return the text the Label is currently displaying.*/ - virtual std::string_view getString() const override { return _utf8Text; } + virtual const std::string& getString() const override { return _utf8Text; } /** * Return the number of lines of text. @@ -714,15 +716,15 @@ public: */ virtual ~Label(); - bool initWithTTF(std::string_view text, - std::string_view fontFilePath, + bool initWithTTF(const std::string& text, + const std::string& fontFilePath, float fontSize, const Vec2& dimensions = Vec2::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT, TextVAlignment vAlignment = TextVAlignment::TOP); bool initWithTTF(const TTFConfig& ttfConfig, - std::string_view text, + const std::string& text, TextHAlignment hAlignment = TextHAlignment::LEFT, int maxLineWidth = 0); diff --git a/cocos/2d/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp index 5179b6ff06..4b45ff28bd 100644 --- a/cocos/2d/CCLabelAtlas.cpp +++ b/cocos/2d/CCLabelAtlas.cpp @@ -40,8 +40,8 @@ NS_CC_BEGIN // CCLabelAtlas - Creation & Init -LabelAtlas* LabelAtlas::create(std::string_view string, - std::string_view charMapFile, +LabelAtlas* LabelAtlas::create(const std::string& string, + const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) @@ -56,8 +56,8 @@ LabelAtlas* LabelAtlas::create(std::string_view string, return nullptr; } -bool LabelAtlas::initWithString(std::string_view string, - std::string_view charMapFile, +bool LabelAtlas::initWithString(const std::string& string, + const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) @@ -66,7 +66,7 @@ bool LabelAtlas::initWithString(std::string_view string, return initWithString(string, texture, itemWidth, itemHeight, startCharMap); } -bool LabelAtlas::initWithString(std::string_view string, +bool LabelAtlas::initWithString(const std::string& string, Texture2D* texture, int itemWidth, int itemHeight, @@ -81,7 +81,7 @@ bool LabelAtlas::initWithString(std::string_view string, return false; } -LabelAtlas* LabelAtlas::create(std::string_view string, std::string_view fntFile) +LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& fntFile) { LabelAtlas* ret = new LabelAtlas(); @@ -97,7 +97,7 @@ LabelAtlas* LabelAtlas::create(std::string_view string, std::string_view fntFile return ret; } -LabelAtlas* LabelAtlas::create(std::string_view string, +LabelAtlas* LabelAtlas::create(const std::string& string, Texture2D* texture, int itemWidth, int itemHeight, @@ -117,7 +117,7 @@ LabelAtlas* LabelAtlas::create(std::string_view string, return ret; } -bool LabelAtlas::initWithString(std::string_view theString, std::string_view fntFile) +bool LabelAtlas::initWithString(const std::string& theString, const std::string& fntFile) { std::string pathStr = FileUtils::getInstance()->fullPathForFilename(fntFile); std::string relPathStr = pathStr.substr(0, pathStr.find_last_of('/')) + "/"; @@ -128,8 +128,8 @@ bool LabelAtlas::initWithString(std::string_view theString, std::string_view fnt std::string textureFilename = relPathStr + dict["textureFilename"].asString(); - unsigned int width = static_cast(dict["itemWidth"].asInt() / CC_CONTENT_SCALE_FACTOR()); - unsigned int height = static_cast(dict["itemHeight"].asInt() / CC_CONTENT_SCALE_FACTOR()); + unsigned int width = dict["itemWidth"].asInt() / CC_CONTENT_SCALE_FACTOR(); + unsigned int height = dict["itemHeight"].asInt() / CC_CONTENT_SCALE_FACTOR(); unsigned int startChar = dict["firstChar"].asInt(); this->initWithString(theString, textureFilename, width, height, startChar); @@ -156,8 +156,8 @@ void LabelAtlas::updateAtlasValues() float itemHeightInPixels = _itemHeight * CC_CONTENT_SCALE_FACTOR(); if (_ignoreContentScaleFactor) { - itemWidthInPixels = static_cast(_itemWidth); - itemHeightInPixels = static_cast(_itemHeight); + itemWidthInPixels = _itemWidth; + itemHeightInPixels = _itemHeight; } CCASSERT(n <= _textureAtlas->getCapacity(), "updateAtlasValues: Invalid String length"); @@ -239,7 +239,7 @@ void LabelAtlas::setString(std::string_view label) _quadsToDraw = len; } -std::string_view LabelAtlas::getString() const +const std::string& LabelAtlas::getString() const { return _string; } diff --git a/cocos/2d/CCLabelAtlas.h b/cocos/2d/CCLabelAtlas.h index 1965e75f32..b1f10ca9a9 100644 --- a/cocos/2d/CCLabelAtlas.h +++ b/cocos/2d/CCLabelAtlas.h @@ -58,8 +58,8 @@ class CC_DLL LabelAtlas : public AtlasNode, public LabelProtocol public: /** Creates the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the * starting char of the atlas. */ - static LabelAtlas* create(std::string_view string, - std::string_view charMapFile, + static LabelAtlas* create(const std::string& string, + const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); @@ -68,13 +68,13 @@ public: * Creates the LabelAtlas with a string and a configuration file. * @since v2.0 */ - static LabelAtlas* create(std::string_view string, std::string_view fntFile); + static LabelAtlas* create(const std::string& string, const std::string& fntFile); /** * Creates the LabelAtlas with a string, a texture, the width and height of each element and the starting char of * the atlas. */ - static LabelAtlas* create(std::string_view string, + static LabelAtlas* create(const std::string& string, Texture2D* texture, int itemWidth, int itemHeight, @@ -82,8 +82,8 @@ public: /** Initializes the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and * the starting char of the atlas. */ - bool initWithString(std::string_view string, - std::string_view charMapFile, + bool initWithString(const std::string& string, + const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); @@ -92,14 +92,14 @@ public: * Initializes the LabelAtlas with a string and a configuration file. * @since v2.0 */ - bool initWithString(std::string_view string, std::string_view fntFile); + bool initWithString(const std::string& string, const std::string& fntFile); /** Initializes the LabelAtlas with a string, a texture, the width and height in points of each element and the * starting char of the atlas */ - bool initWithString(std::string_view string, Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); + bool initWithString(const std::string& string, Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); virtual void setString(std::string_view label) override; - virtual std::string_view getString() const override; + virtual const std::string& getString() const override; virtual void updateAtlasValues() override; /** diff --git a/cocos/2d/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp index 2a28d7686f..a357c06ede 100644 --- a/cocos/2d/CCLabelTextFormatter.cpp +++ b/cocos/2d/CCLabelTextFormatter.cpp @@ -109,7 +109,7 @@ int Label::getFirstWordLen(const std::u32string& utf32Text, int startIndex, int break; } - nextLetterX += static_cast(letterDef.xAdvance * _bmfontScale + _additionalKerning); + nextLetterX += letterDef.xAdvance * _bmfontScale + _additionalKerning; len++; } @@ -139,9 +139,9 @@ void Label::updateBMFontScale() auto font = _fontAtlas->getFont(); if (_currentLabelType == LabelType::BMFONT) { - FontFNT* bmFont = (FontFNT*)font; - auto originalFontSize = bmFont->getOriginalFontSize(); - _bmfontScale = _bmFontSize * CC_CONTENT_SCALE_FACTOR() / originalFontSize; + FontFNT* bmFont = (FontFNT*)font; + float originalFontSize = bmFont->getOriginalFontSize(); + _bmfontScale = _bmFontSize * CC_CONTENT_SCALE_FACTOR() / originalFontSize; } else { @@ -242,7 +242,7 @@ bool Label::multilineTextWrap(const std::function(_horizontalKernings[letterIndex + 1]); + newLetterWidth = _horizontalKernings[letterIndex + 1]; newLetterWidth += letterDef.xAdvance * _bmfontScale + _additionalKerning; nextLetterX += newLetterWidth; diff --git a/cocos/2d/CCMenu.cpp b/cocos/2d/CCMenu.cpp index d24e015291..bbd8808cc6 100644 --- a/cocos/2d/CCMenu.cpp +++ b/cocos/2d/CCMenu.cpp @@ -175,7 +175,7 @@ void Menu::addChild(Node* child, int zOrder, int tag) Layer::addChild(child, zOrder, tag); } -void Menu::addChild(Node* child, int zOrder, std::string_view name) +void Menu::addChild(Node* child, int zOrder, const std::string& name) { CCASSERT(dynamic_cast(child) != nullptr, "Menu only supports MenuItem objects as children"); Layer::addChild(child, zOrder, name); diff --git a/cocos/2d/CCMenu.h b/cocos/2d/CCMenu.h index 37d86df332..560c75c8e5 100644 --- a/cocos/2d/CCMenu.h +++ b/cocos/2d/CCMenu.h @@ -148,7 +148,7 @@ public: virtual void addChild(Node* child) override; virtual void addChild(Node* child, int zOrder) override; virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, std::string_view name) override; + virtual void addChild(Node* child, int zOrder, const std::string& name) override; virtual void onEnter() override; virtual void onExit() override; diff --git a/cocos/2d/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index fb797cc864..83927a12d2 100644 --- a/cocos/2d/CCMenuItem.cpp +++ b/cocos/2d/CCMenuItem.cpp @@ -180,13 +180,13 @@ bool MenuItemLabel::initWithLabel(Node* label, const ccMenuCallback& callback) MenuItemLabel::~MenuItemLabel() {} -void MenuItemLabel::setString(std::string_view label) +void MenuItemLabel::setString(const std::string& label) { dynamic_cast(_label)->setString(label); this->setContentSize(_label->getContentSize()); } -std::string_view MenuItemLabel::getString() const +std::string MenuItemLabel::getString() const { auto label = dynamic_cast(_label); return label->getString(); @@ -259,8 +259,8 @@ void MenuItemLabel::setEnabled(bool enabled) // CCMenuItemAtlasFont // -MenuItemAtlasFont* MenuItemAtlasFont::create(std::string_view value, - std::string_view charMapFile, +MenuItemAtlasFont* MenuItemAtlasFont::create(const std::string& value, + const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap) @@ -269,8 +269,8 @@ MenuItemAtlasFont* MenuItemAtlasFont::create(std::string_view value, (const ccMenuCallback&)nullptr); } -MenuItemAtlasFont* MenuItemAtlasFont::create(std::string_view value, - std::string_view charMapFile, +MenuItemAtlasFont* MenuItemAtlasFont::create(const std::string& value, + const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap, @@ -282,8 +282,8 @@ MenuItemAtlasFont* MenuItemAtlasFont::create(std::string_view value, return ret; } -bool MenuItemAtlasFont::initWithString(std::string_view value, - std::string_view charMapFile, +bool MenuItemAtlasFont::initWithString(const std::string& value, + const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap, @@ -312,7 +312,7 @@ int MenuItemFont::getFontSize() return _globalFontSize; } -void MenuItemFont::setFontName(std::string_view name) +void MenuItemFont::setFontName(const std::string& name) { if (_globalFontNameRelease) { @@ -322,12 +322,12 @@ void MenuItemFont::setFontName(std::string_view name) _globalFontNameRelease = true; } -std::string_view MenuItemFont::getFontName() +const std::string& MenuItemFont::getFontName() { return _globalFontName; } -MenuItemFont* MenuItemFont::create(std::string_view value, const ccMenuCallback& callback) +MenuItemFont* MenuItemFont::create(const std::string& value, const ccMenuCallback& callback) { MenuItemFont* ret = new MenuItemFont(); ret->initWithString(value, callback); @@ -335,7 +335,7 @@ MenuItemFont* MenuItemFont::create(std::string_view value, const ccMenuCallback& return ret; } -MenuItemFont* MenuItemFont::create(std::string_view value) +MenuItemFont* MenuItemFont::create(const std::string& value) { MenuItemFont* ret = new MenuItemFont(); ret->initWithString(value, (const ccMenuCallback&)nullptr); @@ -350,7 +350,7 @@ MenuItemFont::~MenuItemFont() CCLOGINFO("In the destructor of MenuItemFont (%p).", this); } -bool MenuItemFont::initWithString(std::string_view value, const ccMenuCallback& callback) +bool MenuItemFont::initWithString(const std::string& value, const ccMenuCallback& callback) { CCASSERT(!value.empty(), "Value length must be greater than 0"); @@ -377,14 +377,14 @@ int MenuItemFont::getFontSizeObj() const return _fontSize; } -void MenuItemFont::setFontNameObj(std::string_view name) +void MenuItemFont::setFontNameObj(const std::string& name) { _fontName = name; dynamic_cast(_label)->setSystemFontName(_fontName); this->setContentSize(dynamic_cast(_label)->getContentSize()); } -std::string_view MenuItemFont::getFontNameObj() const +const std::string& MenuItemFont::getFontNameObj() const { return _fontName; } @@ -600,21 +600,21 @@ bool MenuItemImage::init() return initWithNormalImage("", "", "", (const ccMenuCallback&)nullptr); } -MenuItemImage* MenuItemImage::create(std::string_view normalImage, std::string_view selectedImage) +MenuItemImage* MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage) { return MenuItemImage::create(normalImage, selectedImage, "", (const ccMenuCallback&)nullptr); } -MenuItemImage* MenuItemImage::create(std::string_view normalImage, - std::string_view selectedImage, +MenuItemImage* MenuItemImage::create(const std::string& normalImage, + const std::string& selectedImage, const ccMenuCallback& callback) { return MenuItemImage::create(normalImage, selectedImage, "", callback); } -MenuItemImage* MenuItemImage::create(std::string_view normalImage, - std::string_view selectedImage, - std::string_view disabledImage, +MenuItemImage* MenuItemImage::create(const std::string& normalImage, + const std::string& selectedImage, + const std::string& disabledImage, const ccMenuCallback& callback) { MenuItemImage* ret = new MenuItemImage(); @@ -627,9 +627,9 @@ MenuItemImage* MenuItemImage::create(std::string_view normalImage, return nullptr; } -MenuItemImage* MenuItemImage::create(std::string_view normalImage, - std::string_view selectedImage, - std::string_view disabledImage) +MenuItemImage* MenuItemImage::create(const std::string& normalImage, + const std::string& selectedImage, + const std::string& disabledImage) { MenuItemImage* ret = new MenuItemImage(); if (ret->initWithNormalImage(normalImage, selectedImage, disabledImage, (const ccMenuCallback&)nullptr)) @@ -641,9 +641,9 @@ MenuItemImage* MenuItemImage::create(std::string_view normalImage, return nullptr; } -bool MenuItemImage::initWithNormalImage(std::string_view normalImage, - std::string_view selectedImage, - std::string_view disabledImage, +bool MenuItemImage::initWithNormalImage(const std::string& normalImage, + const std::string& selectedImage, + const std::string& disabledImage, const ccMenuCallback& callback) { Node* normalSprite = nullptr; diff --git a/cocos/2d/CCMenuItem.h b/cocos/2d/CCMenuItem.h index 20639746c9..a36b65aaf6 100644 --- a/cocos/2d/CCMenuItem.h +++ b/cocos/2d/CCMenuItem.h @@ -137,10 +137,10 @@ public: static MenuItemLabel* create(Node* label); /** Sets a new string to the inner label. */ - void setString(std::string_view label); + void setString(const std::string& label); /** Get the inner string of the inner label. */ - std::string_view getString() const; + std::string getString() const; /** Gets the color that will be used when the item is disabled. */ const Color3B& getDisabledColor() const { return _disabledColor; } @@ -196,14 +196,14 @@ class CC_DLL MenuItemAtlasFont : public MenuItemLabel { public: /** Creates a menu item from a string and atlas with a target/selector. */ - static MenuItemAtlasFont* create(std::string_view value, - std::string_view charMapFile, + static MenuItemAtlasFont* create(const std::string& value, + const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap); /** Creates a menu item from a string and atlas. Use it with MenuItemToggle. */ - static MenuItemAtlasFont* create(std::string_view value, - std::string_view charMapFile, + static MenuItemAtlasFont* create(const std::string& value, + const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap, @@ -222,8 +222,8 @@ public: virtual ~MenuItemAtlasFont() {} /** Initializes a menu item from a string and atlas with a target/selector. */ - bool initWithString(std::string_view value, - std::string_view charMapFile, + bool initWithString(const std::string& value, + const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap, @@ -240,18 +240,18 @@ class CC_DLL MenuItemFont : public MenuItemLabel { public: /** Creates a menu item from a string without target/selector. To be used with MenuItemToggle. */ - static MenuItemFont* create(std::string_view value = ""); + static MenuItemFont* create(const std::string& value = ""); /** Creates a menu item from a string with a target/selector. */ - static MenuItemFont* create(std::string_view value, const ccMenuCallback& callback); + static MenuItemFont* create(const std::string& value, const ccMenuCallback& callback); /** Set default font size. */ static void setFontSize(int size); /** Get default font size. */ static int getFontSize(); /** Set the default font name. */ - static void setFontName(std::string_view name); + static void setFontName(const std::string& name); /** Get the default font name. */ - static std::string_view getFontName(); + static const std::string& getFontName(); /** Set font size. * c++ can not overload static and non-static member functions with the same parameter types. @@ -274,13 +274,13 @@ public: * @js setFontName * @js NA */ - void setFontNameObj(std::string_view name); + void setFontNameObj(const std::string& name); /** Returns the name of the Font. * @js getFontNameObj * @js NA */ - std::string_view getFontNameObj() const; + const std::string& getFontNameObj() const; CC_CONSTRUCTOR_ACCESS : /** @@ -294,7 +294,7 @@ public: virtual ~MenuItemFont(); /** Initializes a menu item from a string with a target/selector. */ - bool initWithString(std::string_view value, const ccMenuCallback& callback); + bool initWithString(const std::string& value, const ccMenuCallback& callback); protected: int _fontSize; @@ -392,19 +392,19 @@ public: /** Creates an MenuItemImage. */ static MenuItemImage* create(); /** Creates a menu item with a normal and selected image.*/ - static MenuItemImage* create(std::string_view normalImage, std::string_view selectedImage); + static MenuItemImage* create(const std::string& normalImage, const std::string& selectedImage); /** Creates a menu item with a normal,selected and disabled image.*/ - static MenuItemImage* create(std::string_view normalImage, - std::string_view selectedImage, - std::string_view disabledImage); + static MenuItemImage* create(const std::string& normalImage, + const std::string& selectedImage, + const std::string& disabledImage); /** Creates a menu item with a normal and selected image with a callable object. */ - static MenuItemImage* create(std::string_view normalImage, - std::string_view selectedImage, + static MenuItemImage* create(const std::string& normalImage, + const std::string& selectedImage, const ccMenuCallback& callback); /** Creates a menu item with a normal,selected and disabled image with a callable object. */ - static MenuItemImage* create(std::string_view normalImage, - std::string_view selectedImage, - std::string_view disabledImage, + static MenuItemImage* create(const std::string& normalImage, + const std::string& selectedImage, + const std::string& disabledImage, const ccMenuCallback& callback); /** Sets the sprite frame for the normal image. */ @@ -429,9 +429,9 @@ public: bool init(); /** Initializes a menu item with a normal, selected and disabled image with a callable object. */ - bool initWithNormalImage(std::string_view normalImage, - std::string_view selectedImage, - std::string_view disabledImage, + bool initWithNormalImage(const std::string& normalImage, + const std::string& selectedImage, + const std::string& disabledImage, const ccMenuCallback& callback); private: diff --git a/cocos/2d/CCMotionStreak.cpp b/cocos/2d/CCMotionStreak.cpp index 1535875ef6..d92839e954 100644 --- a/cocos/2d/CCMotionStreak.cpp +++ b/cocos/2d/CCMotionStreak.cpp @@ -52,7 +52,11 @@ MotionStreak::~MotionStreak() CC_SAFE_FREE(_texCoords); } -MotionStreak* MotionStreak::create(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path) +MotionStreak* MotionStreak::create(float fade, + float minSeg, + float stroke, + const Color3B& color, + const std::string& path) { MotionStreak* ret = new MotionStreak(); if (ret->initWithFade(fade, minSeg, stroke, color, path)) @@ -78,7 +82,7 @@ MotionStreak* MotionStreak::create(float fade, float minSeg, float stroke, const return nullptr; } -bool MotionStreak::initWithFade(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path) +bool MotionStreak::initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path) { CCASSERT(!path.empty(), "Invalid filename"); diff --git a/cocos/2d/CCMotionStreak.h b/cocos/2d/CCMotionStreak.h index 7ce1ca2c74..07ab945dd5 100644 --- a/cocos/2d/CCMotionStreak.h +++ b/cocos/2d/CCMotionStreak.h @@ -59,7 +59,7 @@ public: float minSeg, float strokeWidth, const Color3B& strokeColor, - std::string_view imagePath); + const std::string& imagePath); /** Creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture. * * @param timeToFade The fade time, in seconds. @@ -163,7 +163,7 @@ public: /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture filename */ - bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path); + bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path); /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture */ bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture); diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 49fa7a83f1..aa068ac8fd 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -56,7 +56,7 @@ THE SOFTWARE. /* * 4.5x faster than std::hash in release mode */ -#define CC_HASH_NODE_NAME(name) (!name.empty() ? XXH3_64bits(name.data(), name.length()) : 0) +#define CC_HASH_NODE_NAME(name) (!name.empty() ? XXH3_64bits(name.c_str(), name.length()) : 0) NS_CC_BEGIN @@ -695,12 +695,12 @@ void Node::setTag(int tag) _tag = tag; } -std::string_view Node::getName() const +const std::string& Node::getName() const { return _name; } -void Node::setName(std::string_view name) +void Node::setName(const std::string& name) { updateParentChildrenIndexer(name); _name = name; @@ -717,7 +717,7 @@ void Node::updateParentChildrenIndexer(int tag) } } -void Node::updateParentChildrenIndexer(std::string_view name) +void Node::updateParentChildrenIndexer(const std::string& name) { uint64_t newHash = CC_HASH_NODE_NAME(name); auto parentChildrenIndexer = getParentChildrenIndexer(); @@ -817,7 +817,7 @@ Node* Node::getChildByTag(int tag) const return nullptr; } -Node* Node::getChildByName(std::string_view name) const +Node* Node::getChildByName(const std::string& name) const { // CCASSERT(!name.empty(), "Invalid name"); auto hash = CC_HASH_NODE_NAME(name); @@ -837,7 +837,7 @@ Node* Node::getChildByName(std::string_view name) const return nullptr; } -void Node::enumerateChildren(std::string_view name, std::function callback) const +void Node::enumerateChildren(const std::string& name, std::function callback) const { CCASSERT(!name.empty(), "Invalid name"); CCASSERT(callback != nullptr, "Invalid callback function"); @@ -865,7 +865,7 @@ void Node::enumerateChildren(std::string_view name, std::function c } // Remove '//', '/..' if exist - auto newName = name.substr(subStrStartPos, subStrlength); + std::string newName = name.substr(subStrStartPos, subStrlength); const Node* target = this; @@ -886,15 +886,15 @@ void Node::enumerateChildren(std::string_view name, std::function c else { // name is xxx - target->doEnumerate(std::string{newName}, callback); + target->doEnumerate(newName, callback); } } -bool Node::doEnumerateRecursive(const Node* node, std::string_view name, std::function callback) const +bool Node::doEnumerateRecursive(const Node* node, const std::string& name, std::function callback) const { bool ret = false; - if (node->doEnumerate(std::string{name}, callback)) + if (node->doEnumerate(name, callback)) { // search itself ret = true; @@ -966,7 +966,7 @@ void Node::addChild(Node* child, int localZOrder, int tag) addChildHelper(child, localZOrder, tag, "", true); } -void Node::addChild(Node* child, int localZOrder, std::string_view name) +void Node::addChild(Node* child, int localZOrder, const std::string& name) { CCASSERT(child != nullptr, "Argument must be non-nil"); CCASSERT(child->_parent == nullptr, "child already added. It can't be added again"); @@ -974,7 +974,7 @@ void Node::addChild(Node* child, int localZOrder, std::string_view name) addChildHelper(child, localZOrder, INVALID_TAG, name, false); } -void Node::addChildHelper(Node* child, int localZOrder, int tag, std::string_view name, bool setTag) +void Node::addChildHelper(Node* child, int localZOrder, int tag, const std::string& name, bool setTag) { auto assertNotSelfChild([this, child]() -> bool { for (Node* parent(getParent()); parent != nullptr; parent = parent->getParent()) @@ -1088,7 +1088,7 @@ void Node::removeChildByTag(int tag, bool cleanup /* = true */) } } -void Node::removeChildByName(std::string_view name, bool cleanup) +void Node::removeChildByName(const std::string& name, bool cleanup) { CCASSERT(!name.empty(), "Invalid name"); @@ -1096,7 +1096,7 @@ void Node::removeChildByName(std::string_view name, bool cleanup) if (child == nullptr) { - CCLOG("cocos2d: removeChildByName(name = %s): child not found!", name.data()); + CCLOG("cocos2d: removeChildByName(name = %s): child not found!", name.c_str()); } else { @@ -1490,7 +1490,7 @@ bool Node::isScheduled(SEL_SCHEDULE selector) const return _scheduler->isScheduled(selector, this); } -bool Node::isScheduled(std::string_view key) const +bool Node::isScheduled(const std::string& key) const { return _scheduler->isScheduled(key, this); } @@ -1547,12 +1547,12 @@ void Node::schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, _scheduler->schedule(selector, this, interval, repeat, delay, !_running); } -void Node::schedule(const std::function& callback, std::string_view key) +void Node::schedule(const std::function& callback, const std::string& key) { _scheduler->schedule(callback, this, 0, !_running, key); } -void Node::schedule(const std::function& callback, float interval, std::string_view key) +void Node::schedule(const std::function& callback, float interval, const std::string& key) { _scheduler->schedule(callback, this, interval, !_running, key); } @@ -1561,7 +1561,7 @@ void Node::schedule(const std::function& callback, float interval, unsigned int repeat, float delay, - std::string_view key) + const std::string& key) { _scheduler->schedule(callback, this, interval, repeat, delay, !_running, key); } @@ -1571,7 +1571,7 @@ void Node::scheduleOnce(SEL_SCHEDULE selector, float delay) this->schedule(selector, 0.0f, 0, delay); } -void Node::scheduleOnce(const std::function& callback, float delay, std::string_view key) +void Node::scheduleOnce(const std::function& callback, float delay, const std::string& key) { _scheduler->schedule(callback, this, 0, 0, delay, !_running, key); } @@ -1585,7 +1585,7 @@ void Node::unschedule(SEL_SCHEDULE selector) _scheduler->unschedule(selector, this); } -void Node::unschedule(std::string_view key) +void Node::unschedule(const std::string& key) { _scheduler->unschedule(key, this); } @@ -1923,7 +1923,7 @@ void Node::updateTransform() // MARK: components -Component* Node::getComponent(std::string_view name) +Component* Node::getComponent(const std::string& name) { if (_componentContainer) return _componentContainer->get(name); @@ -1943,7 +1943,7 @@ bool Node::addComponent(Component* component) return _componentContainer->add(component); } -bool Node::removeComponent(std::string_view name) +bool Node::removeComponent(const std::string& name) { if (_componentContainer) return _componentContainer->remove(name); diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 9ebc5b5f67..01bd103303 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -762,7 +762,7 @@ public: * @param name A string to identify the node easily. Please refer to `setName(int)`. * */ - virtual void addChild(Node* child, int localZOrder, std::string_view name); + virtual void addChild(Node* child, int localZOrder, const std::string& name); /** * Gets a child from the container with its tag. * @@ -796,7 +796,7 @@ public: * * @since v3.2 */ - virtual Node* getChildByName(std::string_view name) const; + virtual Node* getChildByName(const std::string& name) const; /** * Gets a child from the container with its name that can be cast to Type T. * @@ -805,7 +805,7 @@ public: * @return a Node with the given name that can be cast to Type T. */ template - T getChildByName(std::string_view name) const + T getChildByName(const std::string& name) const { return static_cast(getChildByName(name)); } @@ -835,7 +835,7 @@ public: * * @since v3.2 */ - virtual void enumerateChildren(std::string_view name, std::function callback) const; + virtual void enumerateChildren(const std::string& name, std::function callback) const; /** * Returns the array of the node's children. * @@ -909,7 +909,7 @@ public: * @param name A string that identifies a child node. * @param cleanup True if all running actions and callbacks on the child node will be cleanup, false otherwise. */ - virtual void removeChildByName(std::string_view name, bool cleanup = true); + virtual void removeChildByName(const std::string& name, bool cleanup = true); /** * Removes all children from the container with a cleanup. * @@ -989,13 +989,13 @@ public: * * @since v3.2 */ - virtual std::string_view getName() const; + virtual const std::string& getName() const; /** Changes the name that is used to identify the node easily. * @param name A string that identifies the node. * * @since v3.2 */ - virtual void setName(std::string_view name); + virtual void setName(const std::string& name); /** * Returns a custom user data pointer. @@ -1306,7 +1306,7 @@ public: * @js NA * @lua NA */ - bool isScheduled(std::string_view key) const; + bool isScheduled(const std::string& key) const; /** * Schedules the "update" method. @@ -1385,7 +1385,7 @@ public: * @param key The key of the lambda function. To be used if you want to unschedule it. * @lua NA */ - void scheduleOnce(const std::function& callback, float delay, std::string_view key); + void scheduleOnce(const std::function& callback, float delay, const std::string& key); /** * Schedules a custom selector, the scheduled selector will be ticked every frame. @@ -1403,7 +1403,7 @@ public: * @param key The key of the lambda function. To be used if you want to unschedule it. * @lua NA */ - void schedule(const std::function& callback, std::string_view key); + void schedule(const std::function& callback, const std::string& key); /** * Schedules a lambda function. The scheduled lambda function will be called every "interval" seconds @@ -1413,7 +1413,7 @@ public: * @param key The key of the lambda function. To be used if you want to unschedule it * @lua NA */ - void schedule(const std::function& callback, float interval, std::string_view key); + void schedule(const std::function& callback, float interval, const std::string& key); /** * Schedules a lambda function. @@ -1430,7 +1430,7 @@ public: float interval, unsigned int repeat, float delay, - std::string_view key); + const std::string& key); /** * Unschedules a custom selector. @@ -1447,7 +1447,7 @@ public: * @param key The key of the lambda function to be unscheduled. * @lua NA */ - void unschedule(std::string_view key); + void unschedule(const std::string& key); /** * Unschedule all scheduled selectors and lambda functions: custom selectors, and the 'update' selector and lambda @@ -1633,7 +1633,7 @@ public: * @param name A given name of component. * @return The Component by name. */ - Component* getComponent(std::string_view name); + Component* getComponent(const std::string& name); /** * Adds a component. @@ -1649,7 +1649,7 @@ public: * @param name A given name of component. * @return True if removed success. */ - virtual bool removeComponent(std::string_view name); + virtual bool removeComponent(const std::string& name); /** * Removes a component by its pointer. @@ -1854,7 +1854,7 @@ protected: virtual void updateColor() {} bool doEnumerate(std::string name, std::function callback) const; - bool doEnumerateRecursive(const Node* node, std::string_view name, std::function callback) const; + bool doEnumerateRecursive(const Node* node, const std::string& name, std::function callback) const; // check whether this camera mask is visible by the current visiting camera bool isVisitableByVisitingCamera() const; @@ -1865,10 +1865,10 @@ protected: void updateRotation3D(); void updateParentChildrenIndexer(int tag); - void updateParentChildrenIndexer(std::string_view name); + void updateParentChildrenIndexer(const std::string& name); private: - void addChildHelper(Node* child, int localZOrder, int tag, std::string_view name, bool setTag); + void addChildHelper(Node* child, int localZOrder, int tag, const std::string& name, bool setTag); NodeIndexerMap_t* getParentChildrenIndexer(); diff --git a/cocos/2d/CCParallaxNode.cpp b/cocos/2d/CCParallaxNode.cpp index a2c04f4ec2..7282e416a4 100644 --- a/cocos/2d/CCParallaxNode.cpp +++ b/cocos/2d/CCParallaxNode.cpp @@ -91,7 +91,7 @@ void ParallaxNode::addChild(Node* /*child*/, int /*zOrder*/, int /*tag*/) CCASSERT(0, "ParallaxNode: use addChild:z:parallaxRatio:positionOffset instead"); } -void ParallaxNode::addChild(Node* /*child*/, int /*zOrder*/, std::string_view /*name*/) +void ParallaxNode::addChild(Node* /*child*/, int /*zOrder*/, const std::string& /*name*/) { CCASSERT(0, "ParallaxNode: use addChild:z:parallaxRatio:positionOffset instead"); } diff --git a/cocos/2d/CCParallaxNode.h b/cocos/2d/CCParallaxNode.h index 409717a0e9..577069ec82 100644 --- a/cocos/2d/CCParallaxNode.h +++ b/cocos/2d/CCParallaxNode.h @@ -83,7 +83,7 @@ public: // Overrides // virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, std::string_view name) override; + virtual void addChild(Node* child, int zOrder, const std::string& name) override; virtual void removeChild(Node* child, bool cleanup) override; virtual void removeAllChildrenWithCleanup(bool cleanup) override; virtual void visit(Renderer* renderer, const Mat4& parentTransform, uint32_t parentFlags) override; diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index e9f8edabb1..e91e27c5f6 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -108,7 +108,7 @@ ParticleBatchNode* ParticleBatchNode::createWithTexture(Texture2D* tex, int capa * creation with File Image */ -ParticleBatchNode* ParticleBatchNode::create(std::string_view imageFile, int capacity /* = kParticleDefaultCapacity*/) +ParticleBatchNode* ParticleBatchNode::create(const std::string& imageFile, int capacity /* = kParticleDefaultCapacity*/) { ParticleBatchNode* p = new ParticleBatchNode(); if (p->initWithFile(imageFile, capacity)) @@ -140,7 +140,7 @@ bool ParticleBatchNode::initWithTexture(Texture2D* tex, int capacity) /* * init with FileImage */ -bool ParticleBatchNode::initWithFile(std::string_view fileImage, int capacity) +bool ParticleBatchNode::initWithFile(const std::string& fileImage, int capacity) { Texture2D* tex = _director->getTextureCache()->addImage(fileImage); return initWithTexture(tex, capacity); @@ -193,7 +193,7 @@ void ParticleBatchNode::addChild(Node* aChild, int zOrder, int tag) addChildByTagOrName(child, zOrder, tag, "", true); } -void ParticleBatchNode::addChild(Node* aChild, int zOrder, std::string_view name) +void ParticleBatchNode::addChild(Node* aChild, int zOrder, const std::string& name) { CCASSERT(aChild != nullptr, "Argument must be non-nullptr"); CCASSERT(dynamic_cast(aChild) != nullptr, @@ -208,7 +208,7 @@ void ParticleBatchNode::addChild(Node* aChild, int zOrder, std::string_view name void ParticleBatchNode::addChildByTagOrName(ParticleSystem* child, int zOrder, int tag, - std::string_view name, + const std::string& name, bool setTag) { // If this is the 1st children, then copy blending function @@ -251,7 +251,7 @@ void ParticleBatchNode::addChildByTagOrName(ParticleSystem* child, // faster // FIXME: or possibly using vertexZ for reordering, that would be fastest // this helper is almost equivalent to Node's addChild, but doesn't make use of the lazy sorting -int ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag, std::string_view name, bool setTag) +int ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag, const std::string& name, bool setTag) { CCASSERT(child != nullptr, "Argument must be non-nil"); CCASSERT(child->getParent() == nullptr, "child already added. It can't be added again"); diff --git a/cocos/2d/CCParticleBatchNode.h b/cocos/2d/CCParticleBatchNode.h index 6ad5991e53..442416209d 100644 --- a/cocos/2d/CCParticleBatchNode.h +++ b/cocos/2d/CCParticleBatchNode.h @@ -87,7 +87,7 @@ public: * @param capacity A capacity of particles. * @return An autoreleased ParticleBatchNode object. */ - static ParticleBatchNode* create(std::string_view fileImage, int capacity = kParticleDefaultCapacity); + static ParticleBatchNode* create(const std::string& fileImage, int capacity = kParticleDefaultCapacity); /** Inserts a child into the ParticleBatchNode. * @@ -127,7 +127,7 @@ public: using Node::addChild; virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, std::string_view name) override; + virtual void addChild(Node* child, int zOrder, const std::string& name) override; virtual void removeChild(Node* child, bool cleanup) override; virtual void reorderChild(Node* child, int zOrder) override; virtual void draw(Renderer* renderer, const Mat4& transform, uint32_t flags) override; @@ -163,15 +163,15 @@ public: /** initializes the particle system with the name of a file on disk (for a list of supported formats look at the * Texture2D class), a capacity of particles */ - bool initWithFile(std::string_view fileImage, int capacity); + bool initWithFile(const std::string& fileImage, int capacity); private: void updateAllAtlasIndexes(); void increaseAtlasCapacityTo(ssize_t quantity); int searchNewPositionInChildrenForZ(int z); void getCurrentIndex(int* oldIndex, int* newIndex, Node* child, int z); - int addChildHelper(ParticleSystem* child, int z, int aTag, std::string_view name, bool setTag); - void addChildByTagOrName(ParticleSystem* child, int z, int tag, std::string_view name, bool setTag); + int addChildHelper(ParticleSystem* child, int z, int aTag, const std::string& name, bool setTag); + void addChildByTagOrName(ParticleSystem* child, int z, int tag, const std::string& name, bool setTag); void updateBlendFunc(); void updateProgramStateTexture(); diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index b2820844ed..8a40ac94f1 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -191,6 +191,11 @@ void ParticleData::release() Vector ParticleSystem::__allInstances; float ParticleSystem::__totalParticleCountFactor = 1.0f; +inline static const cocos2d::Value& optValue(const ValueMap& dictionary, const std::string& key) +{ + return dictionary.find(key) != dictionary.cend() ? dictionary.at(key) : cocos2d::Value::Null; +} + ParticleSystem::ParticleSystem() : _isBlendAdditive(false) , _isAutoRemoveOnFinish(false) @@ -245,7 +250,7 @@ ParticleSystem::ParticleSystem() } // implementation ParticleSystem -ParticleSystem* ParticleSystem::create(std::string_view plistFile) +ParticleSystem* ParticleSystem::create(const std::string& plistFile) { ParticleSystem* ret = new ParticleSystem(); if (ret->initWithFile(plistFile)) @@ -285,7 +290,7 @@ bool ParticleSystem::init() return initWithTotalParticles(150); } -bool ParticleSystem::initWithFile(std::string_view plistFile) +bool ParticleSystem::initWithFile(const std::string& plistFile) { bool ret = false; _plistFile = FileUtils::getInstance()->fullPathForFilename(plistFile); @@ -294,7 +299,7 @@ bool ParticleSystem::initWithFile(std::string_view plistFile) CCASSERT(!dict.empty(), "Particles: file not found"); // FIXME: compute path from a path, should define a function somewhere to do it - auto listFilePath = plistFile; + string listFilePath = plistFile; if (listFilePath.find('/') != string::npos) { listFilePath = listFilePath.substr(0, listFilePath.rfind('/') + 1); @@ -313,7 +318,7 @@ bool ParticleSystem::initWithDictionary(const ValueMap& dictionary) return initWithDictionary(dictionary, ""); } -bool ParticleSystem::initWithDictionary(const ValueMap& dictionary, std::string_view dirname) +bool ParticleSystem::initWithDictionary(const ValueMap& dictionary, const std::string& dirname) { bool ret = false; unsigned char* buffer = nullptr; @@ -482,12 +487,12 @@ bool ParticleSystem::initWithDictionary(const ValueMap& dictionary, std::string_ if (!dirname.empty() && textureDir != dirname) { textureName = textureName.substr(rPos + 1); - textureName.insert(0, dirname); // textureName = dirname + textureName; + textureName = dirname + textureName; } } else if (!dirname.empty() && !textureName.empty()) { - textureName.insert(0, dirname); // textureName = dirname + textureName; + textureName = dirname + textureName; } Texture2D* tex = nullptr; diff --git a/cocos/2d/CCParticleSystem.h b/cocos/2d/CCParticleSystem.h index 6e9dcff08c..558cf87111 100644 --- a/cocos/2d/CCParticleSystem.h +++ b/cocos/2d/CCParticleSystem.h @@ -237,7 +237,7 @@ public: * @param plistFile Particle plist file name. * @return An autoreleased ParticleSystem object. */ - static ParticleSystem* create(std::string_view plistFile); + static ParticleSystem* create(const std::string& plistFile); /** Create a system with a fixed number of particles. * @@ -761,7 +761,7 @@ public: */ virtual const BlendFunc& getBlendFunc() const override; - std::string_view getResourceFile() const { return _plistFile; } + const std::string& getResourceFile() const { return _plistFile; } /// @{ /// @name implement Playable Protocol @@ -793,7 +793,7 @@ public: http://particledesigner.71squared.com/ @since v0.99.3 */ - bool initWithFile(std::string_view plistFile); + bool initWithFile(const std::string& plistFile); /** initializes a QuadParticleSystem from a Dictionary. @since v0.99.3 @@ -803,7 +803,7 @@ public: /** initializes a particle system from a NSDictionary and the path from where to load the png @since v2.1 */ - bool initWithDictionary(const ValueMap& dictionary, std::string_view dirname); + bool initWithDictionary(const ValueMap& dictionary, const std::string& dirname); //! Initializes a system with a fixed number of particles virtual bool initWithTotalParticles(int numberOfParticles); diff --git a/cocos/2d/CCParticleSystemQuad.cpp b/cocos/2d/CCParticleSystemQuad.cpp index 0c87d08083..17e1b7de46 100644 --- a/cocos/2d/CCParticleSystemQuad.cpp +++ b/cocos/2d/CCParticleSystemQuad.cpp @@ -91,7 +91,7 @@ ParticleSystemQuad::~ParticleSystemQuad() // implementation ParticleSystemQuad -ParticleSystemQuad* ParticleSystemQuad::create(std::string_view filename) +ParticleSystemQuad* ParticleSystemQuad::create(const std::string& filename) { ParticleSystemQuad* ret = new ParticleSystemQuad(); if (ret->initWithFile(filename)) diff --git a/cocos/2d/CCParticleSystemQuad.h b/cocos/2d/CCParticleSystemQuad.h index 65229bd27f..5ab1210352 100644 --- a/cocos/2d/CCParticleSystemQuad.h +++ b/cocos/2d/CCParticleSystemQuad.h @@ -75,7 +75,7 @@ public: * @param filename Particle plist file name. * @return An autoreleased ParticleSystemQuad object. */ - static ParticleSystemQuad* create(std::string_view filename); + static ParticleSystemQuad* create(const std::string& filename); /** Creates a Particle Emitter with a dictionary. * * @param dictionary Particle dictionary. diff --git a/cocos/2d/CCPlistSpriteSheetLoader.cpp b/cocos/2d/CCPlistSpriteSheetLoader.cpp index 1406327d30..93a2a975e7 100644 --- a/cocos/2d/CCPlistSpriteSheetLoader.cpp +++ b/cocos/2d/CCPlistSpriteSheetLoader.cpp @@ -18,7 +18,7 @@ using namespace std; NS_CC_BEGIN -void PlistSpriteSheetLoader::load(std::string_view filePath, SpriteFrameCache& cache) +void PlistSpriteSheetLoader::load(const std::string& filePath, SpriteFrameCache& cache) { CCASSERT(!filePath.empty(), "plist filename should not be nullptr"); @@ -26,7 +26,7 @@ void PlistSpriteSheetLoader::load(std::string_view filePath, SpriteFrameCache& c if (fullPath.empty()) { // return if plist file doesn't exist - CCLOG("cocos2d: SpriteFrameCache: can not find %s", filePath.data()); + CCLOG("cocos2d: SpriteFrameCache: can not find %s", filePath.c_str()); return; } @@ -66,7 +66,7 @@ void PlistSpriteSheetLoader::load(std::string_view filePath, SpriteFrameCache& c addSpriteFramesWithDictionary(dict, texturePath, filePath, cache); } -void PlistSpriteSheetLoader::load(std::string_view filePath, Texture2D* texture, SpriteFrameCache& cache) +void PlistSpriteSheetLoader::load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache) { const auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); @@ -74,7 +74,9 @@ void PlistSpriteSheetLoader::load(std::string_view filePath, Texture2D* texture, addSpriteFramesWithDictionary(dict, texture, filePath, cache); } -void PlistSpriteSheetLoader::load(std::string_view filePath, std::string_view textureFileName, SpriteFrameCache& cache) +void PlistSpriteSheetLoader::load(const std::string& filePath, + const std::string& textureFileName, + SpriteFrameCache& cache) { CCASSERT(!textureFileName.empty(), "texture name should not be null"); const auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); @@ -96,7 +98,7 @@ void PlistSpriteSheetLoader::load(const Data& content, Texture2D* texture, Sprit addSpriteFramesWithDictionary(dict, texture, "by#addSpriteFramesWithFileContent()", cache); } -void PlistSpriteSheetLoader::reload(std::string_view filePath, SpriteFrameCache& cache) +void PlistSpriteSheetLoader::reload(const std::string& filePath, SpriteFrameCache& cache) { const auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); @@ -149,7 +151,7 @@ void PlistSpriteSheetLoader::reload(std::string_view filePath, SpriteFrameCache& void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, Texture2D* texture, - std::string_view plist, + const std::string& plist, SpriteFrameCache& cache) { /* @@ -176,15 +178,15 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, Vec2 textureSize; // get the format - auto metaItr = dictionary.find("metadata"sv); + auto metaItr = dictionary.find("metadata"); if (metaItr != dictionary.end()) { auto& metadataDict = metaItr->second.asValueMap(); - format = optValue(metadataDict, "format"sv).asInt(); + format = metadataDict["format"].asInt(); - if (metadataDict.find("size"sv) != metadataDict.end()) + if (metadataDict.find("size") != metadataDict.end()) { - textureSize = SizeFromString(optValue(metadataDict, "size"sv).asString()); + textureSize = SizeFromString(metadataDict["size"].asString()); } } @@ -208,14 +210,14 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, if (format == 0) { - auto x = optValue(frameDict, "x"sv).asFloat(); - auto y = optValue(frameDict, "y"sv).asFloat(); - auto w = optValue(frameDict, "width"sv).asFloat(); - auto h = optValue(frameDict, "height"sv).asFloat(); - auto ox = optValue(frameDict, "offsetX"sv).asFloat(); - auto oy = optValue(frameDict, "offsetY"sv).asFloat(); - auto ow = optValue(frameDict, "originalWidth"sv).asInt(); - auto oh = optValue(frameDict, "originalHeight"sv).asInt(); + auto x = frameDict["x"].asFloat(); + auto y = frameDict["y"].asFloat(); + auto w = frameDict["width"].asFloat(); + auto h = frameDict["height"].asFloat(); + auto ox = frameDict["offsetX"].asFloat(); + auto oy = frameDict["offsetY"].asFloat(); + auto ow = frameDict["originalWidth"].asInt(); + auto oh = frameDict["originalHeight"].asInt(); // check ow/oh if (!ow || !oh) { @@ -232,17 +234,17 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, } else if (format == 1 || format == 2) { - auto frame = RectFromString(optValue(frameDict, "frame"sv).asString()); + auto frame = RectFromString(frameDict["frame"].asString()); auto rotated = false; // rotation if (format == 2) { - rotated = optValue(frameDict, "rotated"sv).asBool(); + rotated = frameDict["rotated"].asBool(); } - auto offset = PointFromString(optValue(frameDict, "offset"sv).asString()); - auto sourceSize = SizeFromString(optValue(frameDict, "sourceSize"sv).asString()); + auto offset = PointFromString(frameDict["offset"].asString()); + auto sourceSize = SizeFromString(frameDict["sourceSize"].asString()); // create frame spriteFrame = SpriteFrame::createWithTexture(texture, frame, rotated, offset, sourceSize); @@ -250,14 +252,14 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, else if (format == 3) { // get values - auto spriteSize = SizeFromString(optValue(frameDict, "spriteSize"sv).asString()); - auto spriteOffset = PointFromString(optValue(frameDict, "spriteOffset"sv).asString()); - auto spriteSourceSize = SizeFromString(optValue(frameDict, "spriteSourceSize"sv).asString()); - auto textureRect = RectFromString(optValue(frameDict, "textureRect"sv).asString()); - auto textureRotated = optValue(frameDict, "textureRotated"sv).asBool(); + auto spriteSize = SizeFromString(frameDict["spriteSize"].asString()); + auto spriteOffset = PointFromString(frameDict["spriteOffset"].asString()); + auto spriteSourceSize = SizeFromString(frameDict["spriteSourceSize"].asString()); + auto textureRect = RectFromString(frameDict["textureRect"].asString()); + auto textureRotated = frameDict["textureRotated"].asBool(); // get aliases - auto& aliases = optValue(frameDict, "aliases"sv).asValueVector(); + auto& aliases = frameDict["aliases"].asValueVector(); for (const auto& value : aliases) { @@ -280,9 +282,9 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, if (frameDict.find("vertices") != frameDict.end()) { using cocos2d::utils::parseIntegerList; - auto vertices = parseIntegerList(optValue(frameDict, "vertices"sv).asString()); - auto verticesUV = parseIntegerList(optValue(frameDict, "verticesUV"sv).asString()); - auto indices = parseIntegerList(optValue(frameDict, "triangles"sv).asString()); + auto vertices = parseIntegerList(frameDict["vertices"].asString()); + auto verticesUV = parseIntegerList(frameDict["verticesUV"].asString()); + auto indices = parseIntegerList(frameDict["triangles"].asString()); PolygonInfo info; initializePolygonInfo(textureSize, spriteSourceSize, vertices, verticesUV, indices, info); @@ -290,7 +292,7 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, } if (frameDict.find("anchor") != frameDict.end()) { - spriteFrame->setAnchorPoint(PointFromString(optValue(frameDict, "anchor"sv).asString())); + spriteFrame->setAnchorPoint(PointFromString(frameDict["anchor"].asString())); } } @@ -321,8 +323,8 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, } void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dict, - std::string_view texturePath, - std::string_view plist, + const std::string& texturePath, + const std::string& plist, SpriteFrameCache& cache) { std::string pixelFormatName; @@ -376,7 +378,7 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dict, void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict, Texture2D* texture, - std::string_view plist, + const std::string& plist, SpriteFrameCache& cache) { auto& framesDict = dict["frames"].asValueMap(); @@ -399,8 +401,8 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict, for (auto& iter : framesDict) { - const ValueMap& frameDict = iter.second.asValueMap(); - std::string_view spriteFrameName = iter.first; + ValueMap& frameDict = iter.second.asValueMap(); + std::string spriteFrameName = iter.first; cache.eraseFrame(spriteFrameName); @@ -409,14 +411,14 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict, if (format == 0) { - const auto x = optValue(frameDict, "x"sv).asFloat(); - const auto y = optValue(frameDict, "y"sv).asFloat(); - const auto w = optValue(frameDict, "width"sv).asFloat(); - const auto h = optValue(frameDict, "height"sv).asFloat(); - const auto ox = optValue(frameDict, "offsetX"sv).asFloat(); - const auto oy = optValue(frameDict, "offsetY"sv).asFloat(); - auto ow = optValue(frameDict, "originalWidth"sv).asInt(); - auto oh = optValue(frameDict, "originalHeight"sv).asInt(); + const auto x = frameDict["x"].asFloat(); + const auto y = frameDict["y"].asFloat(); + const auto w = frameDict["width"].asFloat(); + const auto h = frameDict["height"].asFloat(); + const auto ox = frameDict["offsetX"].asFloat(); + const auto oy = frameDict["offsetY"].asFloat(); + auto ow = frameDict["originalWidth"].asInt(); + auto oh = frameDict["originalHeight"].asInt(); // check ow/oh if (!ow || !oh) { @@ -433,17 +435,17 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict, } else if (format == 1 || format == 2) { - auto frame = RectFromString(optValue(frameDict, "frame"sv).asString()); + auto frame = RectFromString(frameDict["frame"].asString()); auto rotated = false; // rotation if (format == 2) { - rotated = optValue(frameDict, "rotated"sv).asBool(); + rotated = frameDict["rotated"].asBool(); } - auto offset = PointFromString(optValue(frameDict, "offset"sv).asString()); - auto sourceSize = SizeFromString(optValue(frameDict, "sourceSize"sv).asString()); + auto offset = PointFromString(frameDict["offset"].asString()); + auto sourceSize = SizeFromString(frameDict["sourceSize"].asString()); // create frame spriteFrame = SpriteFrame::createWithTexture(texture, frame, rotated, offset, sourceSize); @@ -451,14 +453,14 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict, else if (format == 3) { // get values - const auto spriteSize = SizeFromString(optValue(frameDict, "spriteSize"sv).asString()); - auto spriteOffset = PointFromString(optValue(frameDict, "spriteOffset"sv).asString()); - auto spriteSourceSize = SizeFromString(optValue(frameDict, "spriteSourceSize"sv).asString()); - const auto textureRect = RectFromString(optValue(frameDict, "textureRect"sv).asString()); - const auto textureRotated = optValue(frameDict, "textureRotated"sv).asBool(); + const auto spriteSize = SizeFromString(frameDict["spriteSize"].asString()); + auto spriteOffset = PointFromString(frameDict["spriteOffset"].asString()); + auto spriteSourceSize = SizeFromString(frameDict["spriteSourceSize"].asString()); + const auto textureRect = RectFromString(frameDict["textureRect"].asString()); + const auto textureRotated = frameDict["textureRotated"].asBool(); // get aliases - const ValueVector& aliases = optValue(frameDict, "aliases"sv).asValueVector(); + ValueVector& aliases = frameDict["aliases"].asValueVector(); for (const auto& value : aliases) { diff --git a/cocos/2d/CCPlistSpriteSheetLoader.h b/cocos/2d/CCPlistSpriteSheetLoader.h index 6f36caad0b..79aa405400 100644 --- a/cocos/2d/CCPlistSpriteSheetLoader.h +++ b/cocos/2d/CCPlistSpriteSheetLoader.h @@ -14,30 +14,30 @@ public: static constexpr uint32_t FORMAT = SpriteSheetFormat::PLIST; uint32_t getFormat() override { return FORMAT; } - void load(std::string_view filePath, SpriteFrameCache& cache) override; - void load(std::string_view filePath, Texture2D* texture, SpriteFrameCache& cache) override; - void load(std::string_view filePath, std::string_view textureFileName, SpriteFrameCache& cache) override; + void load(const std::string& filePath, SpriteFrameCache& cache) override; + void load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache) override; + void load(const std::string& filePath, const std::string& textureFileName, SpriteFrameCache& cache) override; void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) override; - void reload(std::string_view filePath, SpriteFrameCache& cache) override; + void reload(const std::string& filePath, SpriteFrameCache& cache) override; protected: /*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames. */ void addSpriteFramesWithDictionary(ValueMap& dictionary, Texture2D* texture, - std::string_view plist, + const std::string& plist, SpriteFrameCache& cache); /*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames. */ void addSpriteFramesWithDictionary(ValueMap& dict, - std::string_view texturePath, - std::string_view plist, + const std::string& texturePath, + const std::string& plist, SpriteFrameCache& cache); void reloadSpriteFramesWithDictionary(ValueMap& dict, Texture2D* texture, - std::string_view plist, + const std::string& plist, SpriteFrameCache& cache); }; diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index 7525359dbf..067237e12e 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -357,7 +357,9 @@ void RenderTexture::visit(Renderer* renderer, const Mat4& parentTransform, uint3 // setOrderOfArrival(0); } -bool RenderTexture::saveToFileAsNonPMA(std::string_view filename, bool isRGBA, SaveFileCallbackType callback) +bool RenderTexture::saveToFileAsNonPMA(const std::string& filename, + bool isRGBA, + std::function callback) { std::string basename(filename); std::transform(basename.begin(), basename.end(), basename.begin(), ::tolower); @@ -380,7 +382,9 @@ bool RenderTexture::saveToFileAsNonPMA(std::string_view filename, bool isRGBA, S return saveToFileAsNonPMA(filename, Image::Format::JPG, false, callback); } -bool RenderTexture::saveToFile(std::string_view filename, bool isRGBA, SaveFileCallbackType callback) +bool RenderTexture::saveToFile(const std::string& filename, + bool isRGBA, + std::function callback) { std::string basename(filename); std::transform(basename.begin(), basename.end(), basename.begin(), ::tolower); @@ -403,10 +407,10 @@ bool RenderTexture::saveToFile(std::string_view filename, bool isRGBA, SaveFileC return saveToFile(filename, Image::Format::JPG, false, callback); } -bool RenderTexture::saveToFileAsNonPMA(std::string_view fileName, +bool RenderTexture::saveToFileAsNonPMA(const std::string& fileName, Image::Format format, bool isRGBA, - SaveFileCallbackType callback) + std::function callback) { CCASSERT(format == Image::Format::JPG || format == Image::Format::PNG, "the image can only be saved as JPG or PNG format"); @@ -415,7 +419,7 @@ bool RenderTexture::saveToFileAsNonPMA(std::string_view fileName, _saveFileCallback = callback; - std::string fullpath = FileUtils::getInstance()->getWritablePath().append(fileName); + std::string fullpath = FileUtils::getInstance()->getWritablePath() + fileName; _saveToFileCommand.init(_globalZOrder); _saveToFileCommand.func = CC_CALLBACK_0(RenderTexture::onSaveToFile, this, fullpath, isRGBA, true); @@ -423,10 +427,10 @@ bool RenderTexture::saveToFileAsNonPMA(std::string_view fileName, return true; } -bool RenderTexture::saveToFile(std::string_view fileName, +bool RenderTexture::saveToFile(const std::string& fileName, Image::Format format, bool isRGBA, - std::function callback) + std::function callback) { CCASSERT(format == Image::Format::JPG || format == Image::Format::PNG, "the image can only be saved as JPG or PNG format"); @@ -435,7 +439,7 @@ bool RenderTexture::saveToFile(std::string_view fileName, _saveFileCallback = callback; - std::string fullpath = FileUtils::getInstance()->getWritablePath().append(fileName); + std::string fullpath = FileUtils::getInstance()->getWritablePath() + fileName; _saveToFileCommand.init(_globalZOrder); _saveToFileCommand.func = CC_CALLBACK_0(RenderTexture::onSaveToFile, this, fullpath, isRGBA, false); @@ -443,7 +447,7 @@ bool RenderTexture::saveToFile(std::string_view fileName, return true; } -void RenderTexture::onSaveToFile(std::string_view filename, bool isRGBA, bool forceNonPMA) +void RenderTexture::onSaveToFile(const std::string& filename, bool isRGBA, bool forceNonPMA) { auto callbackFunc = [&, filename, isRGBA, forceNonPMA](RefPtr image) { if (image) diff --git a/cocos/2d/CCRenderTexture.h b/cocos/2d/CCRenderTexture.h index b43e9c380b..0fdfb5f543 100644 --- a/cocos/2d/CCRenderTexture.h +++ b/cocos/2d/CCRenderTexture.h @@ -61,7 +61,6 @@ class EventCustom; class CC_DLL RenderTexture : public Node { public: - using SaveFileCallbackType = std::function; /** Initializes a RenderTexture object with width and height in Points and a pixel format( only RGB and RGBA formats * are valid ) and depthStencil format. * @@ -172,7 +171,9 @@ public: * @param callback When the file is save finished,it will callback this function. * @return Returns true if the operation is successful. */ - bool saveToFileAsNonPMA(std::string_view filename, bool isRGBA = true, SaveFileCallbackType = nullptr); + bool saveToFileAsNonPMA(const std::string& filename, + bool isRGBA = true, + std::function callback = nullptr); /** Saves the texture into a file using JPEG format. The file will be saved in the Documents folder. * Returns true if the operation is successful. @@ -182,7 +183,9 @@ public: * @param callback When the file is save finished,it will callback this function. * @return Returns true if the operation is successful. */ - bool saveToFile(std::string_view filename, bool isRGBA = true, SaveFileCallbackType = nullptr); + bool saveToFile(const std::string& filename, + bool isRGBA = true, + std::function callback = nullptr); /** saves the texture into a file in non-PMA. The format could be JPG or PNG. The file will be saved in the Documents folder. Returns true if the operation is successful. @@ -198,10 +201,10 @@ public: * @param callback When the file is save finished,it will callback this function. * @return Returns true if the operation is successful. */ - bool saveToFileAsNonPMA(std::string_view fileName, + bool saveToFileAsNonPMA(const std::string& fileName, Image::Format format, bool isRGBA, - SaveFileCallbackType callback); + std::function callback); /** saves the texture into a file. The format could be JPG or PNG. The file will be saved in the Documents folder. Returns true if the operation is successful. @@ -217,10 +220,10 @@ public: * @param callback When the file is save finished,it will callback this function. * @return Returns true if the operation is successful. */ - bool saveToFile(std::string_view filename, + bool saveToFile(const std::string& filename, Image::Format format, - bool isRGBA = true, - SaveFileCallbackType callback = nullptr); + bool isRGBA = true, + std::function callback = nullptr); /** Listen "come to background" message, and save render texture. * It only has effect on Android. @@ -364,7 +367,7 @@ protected: void onEnd(); void clearColorAttachment(); - void onSaveToFile(std::string_view fileName, bool isRGBA = true, bool forceNonPMA = false); + void onSaveToFile(const std::string& fileName, bool isRGBA = true, bool forceNonPMA = false); bool _keepMatrix = false; Rect _rtTextureRect; @@ -408,7 +411,7 @@ protected: and the command and callback will be executed twice. */ CallbackCommand _saveToFileCommand; - std::function _saveFileCallback = nullptr; + std::function _saveFileCallback = nullptr; Mat4 _oldTransMatrix, _oldProjMatrix; Mat4 _transformMatrix, _projectionMatrix; diff --git a/cocos/2d/CCScene.h b/cocos/2d/CCScene.h index 2eed035aec..96890c12df 100644 --- a/cocos/2d/CCScene.h +++ b/cocos/2d/CCScene.h @@ -142,7 +142,7 @@ protected: std::vector _cameras; // weak ref to Camera Camera* _defaultCamera = nullptr; // weak ref, default camera created by scene, _cameras[0], Caution that the // default camera can not be added to _cameras before onEnter is called - bool _cameraOrderDirty = true; // order is dirty, need sort + bool _cameraOrderDirty = true; // order is dirty, need sort EventListenerCustom* _event; std::vector _lights; diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index 2a97c4f247..f5e87fcd73 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -72,7 +72,7 @@ Sprite* Sprite::createWithTexture(Texture2D* texture, const Rect& rect, bool rot return nullptr; } -Sprite* Sprite::create(std::string_view filename) +Sprite* Sprite::create(const std::string& filename) { Sprite* sprite = new Sprite(); if (sprite->initWithFile(filename)) @@ -96,7 +96,7 @@ Sprite* Sprite::create(const PolygonInfo& info) return nullptr; } -Sprite* Sprite::create(std::string_view filename, const Rect& rect) +Sprite* Sprite::create(const std::string& filename, const Rect& rect) { Sprite* sprite = new Sprite(); if (sprite->initWithFile(filename, rect)) @@ -120,13 +120,13 @@ Sprite* Sprite::createWithSpriteFrame(SpriteFrame* spriteFrame) return nullptr; } -Sprite* Sprite::createWithSpriteFrameName(std::string_view spriteFrameName) +Sprite* Sprite::createWithSpriteFrameName(const std::string& spriteFrameName) { SpriteFrame* frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); #if COCOS2D_DEBUG > 0 char msg[256] = {0}; - sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName.data()); + sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName.c_str()); CCASSERT(frame != nullptr, msg); #endif @@ -167,7 +167,7 @@ bool Sprite::initWithTexture(Texture2D* texture, const Rect& rect) return initWithTexture(texture, rect, false); } -bool Sprite::initWithFile(std::string_view filename) +bool Sprite::initWithFile(const std::string& filename) { if (filename.empty()) { @@ -191,7 +191,7 @@ bool Sprite::initWithFile(std::string_view filename) return false; } -bool Sprite::initWithFile(std::string_view filename, const Rect& rect) +bool Sprite::initWithFile(const std::string& filename, const Rect& rect) { CCASSERT(!filename.empty(), "Invalid filename"); if (filename.empty()) @@ -209,7 +209,7 @@ bool Sprite::initWithFile(std::string_view filename, const Rect& rect) return false; } -bool Sprite::initWithSpriteFrameName(std::string_view spriteFrameName) +bool Sprite::initWithSpriteFrameName(const std::string& spriteFrameName) { CCASSERT(!spriteFrameName.empty(), "Invalid spriteFrameName"); if (spriteFrameName.empty()) @@ -332,7 +332,7 @@ static unsigned char cc_2x2_white_image[] = { #define CC_2x2_WHITE_IMAGE_KEY "/cc_2x2_white_image" // MARK: texture -void Sprite::setTexture(std::string_view filename) +void Sprite::setTexture(const std::string& filename) { Texture2D* texture = _director->getTextureCache()->addImage(filename); setTexture(texture); @@ -1132,7 +1132,7 @@ void Sprite::addChild(Node* child, int zOrder, int tag) Node::addChild(child, zOrder, tag); } -void Sprite::addChild(Node* child, int zOrder, std::string_view name) +void Sprite::addChild(Node* child, int zOrder, const std::string& name) { CCASSERT(child != nullptr, "Argument must be non-nullptr"); if (child == nullptr) @@ -1539,7 +1539,7 @@ bool Sprite::isOpacityModifyRGB() const // MARK: Frames -void Sprite::setSpriteFrame(std::string_view spriteFrameName) +void Sprite::setSpriteFrame(const std::string& spriteFrameName) { CCASSERT(!spriteFrameName.empty(), "spriteFrameName must not be empty"); if (spriteFrameName.empty()) @@ -1590,7 +1590,7 @@ void Sprite::setSpriteFrame(SpriteFrame* spriteFrame) setCenterRect(spriteFrame->getCenterRect()); } -void Sprite::setDisplayFrameWithAnimationName(std::string_view animationName, unsigned int frameIndex) +void Sprite::setDisplayFrameWithAnimationName(const std::string& animationName, unsigned int frameIndex) { CCASSERT(!animationName.empty(), "CCSprite#setDisplayFrameWithAnimationName. animationName must not be nullptr"); if (animationName.empty()) diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index d993a6fef2..e81f18064e 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -129,7 +129,7 @@ public: * @param filename A path to image file, e.g., "scene1/monster.png". * @return An autoreleased sprite object. */ - static Sprite* create(std::string_view filename); + static Sprite* create(const std::string& filename); /** * Creates a polygon sprite with a polygon info. @@ -149,7 +149,7 @@ public: * @param rect A subrect of the image file. * @return An autoreleased sprite object. */ - static Sprite* create(std::string_view filename, const Rect& rect); + static Sprite* create(const std::string& filename, const Rect& rect); /** * Creates a sprite with a Texture2D object. @@ -191,7 +191,7 @@ public: * @param spriteFrameName The name of sprite frame. * @return An autoreleased sprite object. */ - static Sprite* createWithSpriteFrameName(std::string_view spriteFrameName); + static Sprite* createWithSpriteFrameName(const std::string& spriteFrameName); // end of creators group /// @} @@ -233,7 +233,7 @@ public: * @memberof Sprite * It will call `setTextureRect()` with the texture's content size. */ - virtual void setTexture(std::string_view filename); + virtual void setTexture(const std::string& filename); /** @overload * @@ -304,7 +304,7 @@ public: /** @{ * Sets a new SpriteFrame to the Sprite. */ - virtual void setSpriteFrame(std::string_view spriteFrameName); + virtual void setSpriteFrame(const std::string& spriteFrameName); virtual void setSpriteFrame(SpriteFrame* newFrame); /** @} */ @@ -326,7 +326,7 @@ public: * Changes the display frame with animation name and index. * The animation name will be get from the AnimationCache. */ - virtual void setDisplayFrameWithAnimationName(std::string_view animationName, unsigned int frameIndex); + virtual void setDisplayFrameWithAnimationName(const std::string& animationName, unsigned int frameIndex); /// @} /// @{ @@ -370,7 +370,7 @@ public: virtual void reorderChild(Node* child, int zOrder) override; using Node::addChild; virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, std::string_view name) override; + virtual void addChild(Node* child, int zOrder, const std::string& name) override; virtual void sortAllChildren() override; virtual void setScale(float scale) override; virtual void setPositionZ(float positionZ) override; @@ -513,7 +513,7 @@ public: /// @} int getResourceType() const { return _fileType; } - std::string_view getResourceName() const { return _fileName; } + const std::string& getResourceName() const { return _fileName; } CC_CONSTRUCTOR_ACCESS : /** @@ -588,7 +588,7 @@ public: * @param spriteFrameName A key string that can fetched a valid SpriteFrame from SpriteFrameCache. * @return True if the sprite is initialized properly, false otherwise. */ - virtual bool initWithSpriteFrameName(std::string_view spriteFrameName); + virtual bool initWithSpriteFrameName(const std::string& spriteFrameName); /** * Initializes a sprite with an image filename. @@ -601,7 +601,7 @@ public: * @return True if the sprite is initialized properly, false otherwise. * @lua init */ - virtual bool initWithFile(std::string_view filename); + virtual bool initWithFile(const std::string& filename); /** * Initializes a sprite with an image filename, and a rect. @@ -615,7 +615,7 @@ public: * @return True if the sprite is initialized properly, false otherwise. * @lua init */ - virtual bool initWithFile(std::string_view filename, const Rect& rect); + virtual bool initWithFile(const std::string& filename, const Rect& rect); virtual void setVertexLayout(); diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 4888ac8b5f..c2c809c518 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -64,7 +64,7 @@ SpriteBatchNode* SpriteBatchNode::createWithTexture(Texture2D* tex, ssize_t capa * creation with File Image */ -SpriteBatchNode* SpriteBatchNode::create(std::string_view fileImage, ssize_t capacity /* = DEFAULT_CAPACITY*/) +SpriteBatchNode* SpriteBatchNode::create(const std::string& fileImage, ssize_t capacity /* = DEFAULT_CAPACITY*/) { SpriteBatchNode* batchNode = new SpriteBatchNode(); if (batchNode->initWithFile(fileImage, capacity)) @@ -168,7 +168,7 @@ bool SpriteBatchNode::init() /* * init with FileImage */ -bool SpriteBatchNode::initWithFile(std::string_view fileImage, ssize_t capacity /* = DEFAULT_CAPACITY*/) +bool SpriteBatchNode::initWithFile(const std::string& fileImage, ssize_t capacity /* = DEFAULT_CAPACITY*/) { Texture2D* texture2D = _director->getTextureCache()->addImage(fileImage); return initWithTexture(texture2D, capacity); @@ -236,7 +236,7 @@ void SpriteBatchNode::addChild(Node* child, int zOrder, int tag) appendChild(sprite); } -void SpriteBatchNode::addChild(Node* child, int zOrder, std::string_view name) +void SpriteBatchNode::addChild(Node* child, int zOrder, const std::string& name) { CCASSERT(child != nullptr, "child should not be null"); CCASSERT(dynamic_cast(child) != nullptr, "CCSpriteBatchNode only supports Sprites as children"); diff --git a/cocos/2d/CCSpriteBatchNode.h b/cocos/2d/CCSpriteBatchNode.h index cb68aed0f4..3d99cdfa52 100644 --- a/cocos/2d/CCSpriteBatchNode.h +++ b/cocos/2d/CCSpriteBatchNode.h @@ -84,7 +84,7 @@ public: * @param capacity The capacity of children. * @return Return an autorelease object. */ - static SpriteBatchNode* create(std::string_view fileImage, ssize_t capacity = DEFAULT_CAPACITY); + static SpriteBatchNode* create(const std::string& fileImage, ssize_t capacity = DEFAULT_CAPACITY); /** Returns the TextureAtlas object. * @@ -195,7 +195,7 @@ public: using Node::addChild; virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, std::string_view name) override; + virtual void addChild(Node* child, int zOrder, const std::string& name) override; virtual void reorderChild(Node* child, int zOrder) override; virtual void removeChild(Node* child, bool cleanup) override; @@ -250,7 +250,7 @@ public: * @js init * @lua init */ - bool initWithFile(std::string_view fileImage, ssize_t capacity = DEFAULT_CAPACITY); + bool initWithFile(const std::string& fileImage, ssize_t capacity = DEFAULT_CAPACITY); bool init() override; protected: diff --git a/cocos/2d/CCSpriteFrame.cpp b/cocos/2d/CCSpriteFrame.cpp index 6ef46c7e67..7fa6769020 100644 --- a/cocos/2d/CCSpriteFrame.cpp +++ b/cocos/2d/CCSpriteFrame.cpp @@ -35,7 +35,7 @@ NS_CC_BEGIN // implementation of SpriteFrame -SpriteFrame* SpriteFrame::create(std::string_view filename, const Rect& rect) +SpriteFrame* SpriteFrame::create(const std::string& filename, const Rect& rect) { SpriteFrame* spriteFrame = new SpriteFrame(); spriteFrame->initWithTextureFilename(filename, rect); @@ -70,7 +70,7 @@ SpriteFrame* SpriteFrame::createWithTexture(Texture2D* texture, return nullptr; } -SpriteFrame* SpriteFrame::create(std::string_view filename, +SpriteFrame* SpriteFrame::create(const std::string& filename, const Rect& rect, bool rotated, const Vec2& offset, @@ -94,7 +94,7 @@ bool SpriteFrame::initWithTexture(Texture2D* texture, const Rect& rect) return initWithTexture(texture, rectInPixels, false, Vec2::ZERO, rectInPixels.size); } -bool SpriteFrame::initWithTextureFilename(std::string_view filename, const Rect& rect) +bool SpriteFrame::initWithTextureFilename(const std::string& filename, const Rect& rect) { Rect rectInPixels = CC_RECT_POINTS_TO_PIXELS(rect); return initWithTextureFilename(filename, rectInPixels, false, Vec2::ZERO, rectInPixels.size); @@ -126,7 +126,7 @@ bool SpriteFrame::initWithTexture(Texture2D* texture, return true; } -bool SpriteFrame::initWithTextureFilename(std::string_view filename, +bool SpriteFrame::initWithTextureFilename(const std::string& filename, const Rect& rect, bool rotated, const Vec2& offset, diff --git a/cocos/2d/CCSpriteFrame.h b/cocos/2d/CCSpriteFrame.h index 5f17fc1280..32e93be8ee 100644 --- a/cocos/2d/CCSpriteFrame.h +++ b/cocos/2d/CCSpriteFrame.h @@ -66,7 +66,7 @@ public: * @param rect A specified rect. * @return An autoreleased SpriteFrame object. */ - static SpriteFrame* create(std::string_view filename, const Rect& rect); + static SpriteFrame* create(const std::string& filename, const Rect& rect); /** Create a SpriteFrame with a texture filename, rect, rotated, offset and originalSize in pixels. The originalSize is the size in pixels of the frame before being trimmed. @@ -78,7 +78,7 @@ public: * @param originalSize A specified original size. * @return An autoreleased SpriteFrame object. */ - static SpriteFrame* create(std::string_view filename, + static SpriteFrame* create(const std::string& filename, const Rect& rect, bool rotated, const Vec2& offset, @@ -279,7 +279,7 @@ public: /** Initializes a SpriteFrame with a texture filename, rect in points; It is assumed that the frame was not trimmed. */ - bool initWithTextureFilename(std::string_view filename, const Rect& rect); + bool initWithTextureFilename(const std::string& filename, const Rect& rect); /** Initializes a SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels. The originalSize is the size in points of the frame before being trimmed. @@ -295,7 +295,7 @@ public: @since v1.1 */ - bool initWithTextureFilename(std::string_view filename, + bool initWithTextureFilename(const std::string& filename, const Rect& rect, bool rotated, const Vec2& offset, diff --git a/cocos/2d/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp index 6c4fc158a6..db7b977458 100644 --- a/cocos/2d/CCSpriteFrameCache.cpp +++ b/cocos/2d/CCSpriteFrameCache.cpp @@ -75,8 +75,8 @@ bool SpriteFrameCache::init() SpriteFrameCache::~SpriteFrameCache() {} -void SpriteFrameCache::addSpriteFramesWithFile(std::string_view spriteSheetFileName, - std::string_view textureFileName, +void SpriteFrameCache::addSpriteFramesWithFile(const std::string& spriteSheetFileName, + const std::string& textureFileName, uint32_t spriteSheetFormat) { auto* loader = getSpriteSheetLoader(spriteSheetFormat); @@ -86,7 +86,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(std::string_view spriteSheetFileN } } -void SpriteFrameCache::addSpriteFramesWithFile(std::string_view spriteSheetFileName, +void SpriteFrameCache::addSpriteFramesWithFile(const std::string& spriteSheetFileName, Texture2D* texture, uint32_t spriteSheetFormat) { @@ -97,7 +97,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(std::string_view spriteSheetFileN } } -void SpriteFrameCache::addSpriteFramesWithFile(std::string_view spriteSheetFileName, uint32_t spriteSheetFormat) +void SpriteFrameCache::addSpriteFramesWithFile(const std::string& spriteSheetFileName, uint32_t spriteSheetFormat) { auto* loader = getSpriteSheetLoader(spriteSheetFormat); if (loader) @@ -117,12 +117,12 @@ void SpriteFrameCache::addSpriteFramesWithFileContent(const Data& content, } } -bool SpriteFrameCache::isSpriteFramesWithFileLoaded(std::string_view plist) const +bool SpriteFrameCache::isSpriteFramesWithFileLoaded(const std::string& plist) const { return isSpriteSheetInUse(plist) && isPlistFull(plist); } -void SpriteFrameCache::addSpriteFrame(SpriteFrame* frame, std::string_view frameName) +void SpriteFrameCache::addSpriteFrame(SpriteFrame* frame, const std::string& frameName) { CCASSERT(frame, "frame should not be nil"); @@ -169,7 +169,7 @@ void SpriteFrameCache::removeUnusedSpriteFrames() } } -void SpriteFrameCache::removeSpriteFrameByName(std::string_view name) +void SpriteFrameCache::removeSpriteFrameByName(const std::string& name) { // explicit nil handling if (name.empty()) @@ -178,7 +178,7 @@ void SpriteFrameCache::removeSpriteFrameByName(std::string_view name) eraseFrame(name); } -void SpriteFrameCache::removeSpriteFramesFromFile(std::string_view atlasPath) +void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& atlasPath) { // const auto fullPath = FileUtils::getInstance()->fullPathForFilename(plist); // auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); @@ -193,7 +193,7 @@ void SpriteFrameCache::removeSpriteFramesFromFile(std::string_view atlasPath) removeSpriteSheet(atlasPath); } -void SpriteFrameCache::removeSpriteFramesFromFileContent(std::string_view plist_content) +void SpriteFrameCache::removeSpriteFramesFromFileContent(const std::string& plist_content) { auto dict = FileUtils::getInstance()->getValueMapFromData(plist_content.data(), static_cast(plist_content.size())); @@ -241,17 +241,17 @@ void SpriteFrameCache::removeSpriteFramesFromTexture(Texture2D* texture) eraseFrames(keysToRemove); } -SpriteFrame* SpriteFrameCache::getSpriteFrameByName(std::string_view name) +SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const std::string& name) { auto* frame = findFrame(name); if (!frame) { - CCLOG("cocos2d: SpriteFrameCache: Frame '%s' isn't found", name.data()); + CCLOG("cocos2d: SpriteFrameCache: Frame '%s' isn't found", name.c_str()); } return frame; } -bool SpriteFrameCache::reloadTexture(std::string_view spriteSheetFileName) +bool SpriteFrameCache::reloadTexture(const std::string& spriteSheetFileName) { CCASSERT(!spriteSheetFileName.empty(), "plist filename should not be nullptr"); @@ -283,18 +283,16 @@ bool SpriteFrameCache::reloadTexture(std::string_view spriteSheetFileName) } void SpriteFrameCache::insertFrame(const std::shared_ptr& spriteSheet, - std::string_view frameName, + const std::string& frameName, SpriteFrame* spriteFrame) { - spriteSheet->frames.emplace(frameName); + spriteSheet->frames.insert(frameName); _spriteFrames.insert(frameName, spriteFrame); // add SpriteFrame - _spriteSheets[spriteSheet->path] = spriteSheet; - hlookup::set_item(_spriteFrameToSpriteSheetMap, frameName, - spriteSheet); // _spriteFrameToSpriteSheetMap[frameName] = spriteSheet; // insert - // index frameName->plist + _spriteSheets[spriteSheet->path] = spriteSheet; + _spriteFrameToSpriteSheetMap[frameName] = spriteSheet; // insert index frameName->plist } -bool SpriteFrameCache::eraseFrame(std::string_view frameName) +bool SpriteFrameCache::eraseFrame(const std::string& frameName) { _spriteFrames.erase(frameName); // drop SpriteFrame const auto itFrame = _spriteFrameToSpriteSheetMap.find(frameName); @@ -332,7 +330,7 @@ bool SpriteFrameCache::eraseFrames(const std::vector& frames) return ret; } -bool SpriteFrameCache::removeSpriteSheet(std::string_view spriteSheetFileName) +bool SpriteFrameCache::removeSpriteSheet(const std::string& spriteSheetFileName) { auto it = _spriteSheets.find(spriteSheetFileName); if (it == _spriteSheets.end()) @@ -358,18 +356,18 @@ void SpriteFrameCache::clear() _spriteFrames.clear(); } -bool SpriteFrameCache::hasFrame(std::string_view frame) const +bool SpriteFrameCache::hasFrame(const std::string& frame) const { return _spriteFrameToSpriteSheetMap.find(frame) != _spriteFrameToSpriteSheetMap.end(); } -bool SpriteFrameCache::isSpriteSheetInUse(std::string_view spriteSheetFileName) const +bool SpriteFrameCache::isSpriteSheetInUse(const std::string& spriteSheetFileName) const { const auto spriteSheetItr = _spriteSheets.find(spriteSheetFileName); return spriteSheetItr != _spriteSheets.end() && !spriteSheetItr->second->frames.empty(); } -SpriteFrame* SpriteFrameCache::findFrame(std::string_view frame) +SpriteFrame* SpriteFrameCache::findFrame(const std::string& frame) { return _spriteFrames.at(frame); } @@ -379,7 +377,7 @@ void SpriteFrameCache::addSpriteFrameCapInset(SpriteFrame* spriteFrame, const Re texture->addSpriteFrameCapInset(spriteFrame, capInsets); } -StringMap& SpriteFrameCache::getSpriteFrames() +Map& SpriteFrameCache::getSpriteFrames() { return _spriteFrames; } diff --git a/cocos/2d/CCSpriteFrameCache.h b/cocos/2d/CCSpriteFrameCache.h index 78db1c5bff..3009a6bd85 100644 --- a/cocos/2d/CCSpriteFrameCache.h +++ b/cocos/2d/CCSpriteFrameCache.h @@ -117,7 +117,7 @@ public: /** Adds multiple Sprite Frames from a plist file. * A texture will be loaded automatically. The texture name will composed by replacing the .plist suffix with .png. - * If you want to use another texture, you should use the addSpriteFramesWithFile(std::string_view plist, const + * If you want to use another texture, you should use the addSpriteFramesWithFile(const std::string& plist, const * std::string& textureFileName) method. * @js addSpriteFrames * @lua addSpriteFrames @@ -125,7 +125,7 @@ public: * @param spriteSheetFileName file name. * @param spriteSheetFormat */ - void addSpriteFramesWithFile(std::string_view spriteSheetFileName, + void addSpriteFramesWithFile(const std::string& spriteSheetFileName, uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST); /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. @@ -137,8 +137,8 @@ public: * @param textureFileName Texture file name. * @param spriteSheetFormat */ - void addSpriteFramesWithFile(std::string_view spriteSheetFileName, - std::string_view textureFileName, + void addSpriteFramesWithFile(const std::string& spriteSheetFileName, + const std::string& textureFileName, uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST); /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. @@ -149,7 +149,7 @@ public: * @param texture Texture pointer. * @param spriteSheetFormat */ - void addSpriteFramesWithFile(std::string_view spriteSheetFileName, + void addSpriteFramesWithFile(const std::string& spriteSheetFileName, Texture2D* texture, uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST); @@ -172,7 +172,7 @@ public: * @param frame A certain sprite frame. * @param frameName The name of the sprite frame. */ - void addSpriteFrame(SpriteFrame* frame, std::string_view frameName); + void addSpriteFrame(SpriteFrame* frame, const std::string& frameName); /** Check if multiple Sprite Frames from a plist file have been loaded. * @js NA @@ -181,7 +181,7 @@ public: * @param plist Plist file name. * @return True if the file is loaded. */ - bool isSpriteFramesWithFileLoaded(std::string_view plist) const; + bool isSpriteFramesWithFileLoaded(const std::string& plist) const; /** Purges the dictionary of loaded sprite frames. * Call this method if you receive the "Memory Warning". @@ -202,7 +202,7 @@ public: * * @param name The name of the sprite frame that needs to removed. */ - void removeSpriteFrameByName(std::string_view name); + void removeSpriteFrameByName(const std::string& name); /** Removes multiple Sprite Frames from a plist file. * Sprite Frames stored in this file will be removed. @@ -211,7 +211,7 @@ public: * * @param plist The name of the plist that needs to removed. */ - void removeSpriteFramesFromFile(std::string_view plist); + void removeSpriteFramesFromFile(const std::string& plist); /** Removes multiple Sprite Frames from a plist file content. * Sprite Frames stored in this file will be removed. @@ -220,7 +220,7 @@ public: * @param plist_content The string of the plist content that needs to removed. * @js NA */ - void removeSpriteFramesFromFileContent(std::string_view plist_content); + void removeSpriteFramesFromFileContent(const std::string& plist_content); /** Removes all Sprite Frames associated with the specified textures. * It is convenient to call this method when a specific texture needs to be removed. @@ -239,22 +239,22 @@ public: * @param name A certain sprite frame name. * @return The sprite frame. */ - SpriteFrame* getSpriteFrameByName(std::string_view name); + SpriteFrame* getSpriteFrameByName(const std::string& name); - bool reloadTexture(std::string_view spriteSheetFileName); + bool reloadTexture(const std::string& spriteSheetFileName); - SpriteFrame* findFrame(std::string_view frame); + SpriteFrame* findFrame(const std::string& frame); /** Record SpriteFrame with plist and frame name, add frame name * and plist to index */ void insertFrame(const std::shared_ptr& spriteSheet, - std::string_view frameName, + const std::string& frameName, SpriteFrame* frameObj); /** Delete frame from cache, rebuild index */ - bool eraseFrame(std::string_view frameName); + bool eraseFrame(const std::string& frameName); void addSpriteFrameCapInset(SpriteFrame* spriteFrame, const Rect& capInsets, Texture2D* texture); @@ -277,35 +277,30 @@ protected: bool eraseFrames(const std::vector& frame); /** Delete frame from index and SpriteFrame is kept. */ - bool removeSpriteSheet(std::string_view spriteSheetFileName); + bool removeSpriteSheet(const std::string& spriteSheetFileName); /** Clear index and all SpriteFrames. */ void clear(); - inline bool hasFrame(std::string_view frame) const; - inline bool isSpriteSheetInUse(std::string_view spriteSheetFileName) const; + inline bool hasFrame(const std::string& frame) const; + inline bool isSpriteSheetInUse(const std::string& spriteSheetFileName) const; - inline StringMap& getSpriteFrames(); + inline Map& getSpriteFrames(); - void markPlistFull(std::string_view spriteSheetFileName, bool full) + void markPlistFull(const std::string& spriteSheetFileName, bool full) { - // _spriteSheets[spriteSheetFileName]->full = full; - auto it = _spriteSheets.find(spriteSheetFileName); - if (it != _spriteSheets.end()) - { - it.value()->full = full; - } + _spriteSheets[spriteSheetFileName]->full = full; } - bool isPlistFull(std::string_view spriteSheetFileName) const + bool isPlistFull(const std::string& spriteSheetFileName) const { - auto it = _spriteSheets.find(spriteSheetFileName); + auto&& it = _spriteSheets.find(spriteSheetFileName); return it == _spriteSheets.end() ? false : it->second->full; } private: - StringMap _spriteFrames; - hlookup::string_map> _spriteSheets; - hlookup::string_map> _spriteFrameToSpriteSheetMap; + Map _spriteFrames; + std::unordered_map> _spriteSheets; + std::unordered_map> _spriteFrameToSpriteSheetMap; std::map> _spriteSheetLoaders; }; diff --git a/cocos/2d/CCSpriteSheetLoader.h b/cocos/2d/CCSpriteSheetLoader.h index d4a236ee9d..80d93632d5 100644 --- a/cocos/2d/CCSpriteSheetLoader.h +++ b/cocos/2d/CCSpriteSheetLoader.h @@ -65,20 +65,20 @@ class SpriteSheet public: std::string path; uint32_t format; - hlookup::string_set frames; + std::set frames; bool full = false; }; class ISpriteSheetLoader { public: - virtual ~ISpriteSheetLoader() = default; - virtual uint32_t getFormat() = 0; - virtual void load(std::string_view filePath, SpriteFrameCache& cache) = 0; - virtual void load(std::string_view filePath, Texture2D* texture, SpriteFrameCache& cache) = 0; - virtual void load(std::string_view filePath, std::string_view textureFileName, SpriteFrameCache& cache) = 0; - virtual void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) = 0; - virtual void reload(std::string_view filePath, SpriteFrameCache& cache) = 0; + virtual ~ISpriteSheetLoader() = default; + virtual uint32_t getFormat() = 0; + virtual void load(const std::string& filePath, SpriteFrameCache& cache) = 0; + virtual void load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache) = 0; + virtual void load(const std::string& filePath, const std::string& textureFileName, SpriteFrameCache& cache) = 0; + virtual void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) = 0; + virtual void reload(const std::string& filePath, SpriteFrameCache& cache) = 0; }; class SpriteSheetLoader : public ISpriteSheetLoader @@ -92,12 +92,12 @@ public: const std::vector& triangleIndices, PolygonInfo& polygonInfo); - uint32_t getFormat() override = 0; - void load(std::string_view filePath, SpriteFrameCache& cache) override = 0; - void load(std::string_view filePath, Texture2D* texture, SpriteFrameCache& cache) override = 0; - void load(std::string_view filePath, std::string_view textureFileName, SpriteFrameCache& cache) override = 0; - void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) override = 0; - void reload(std::string_view filePath, SpriteFrameCache& cache) override = 0; + uint32_t getFormat() override = 0; + void load(const std::string& filePath, SpriteFrameCache& cache) override = 0; + void load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache) override = 0; + void load(const std::string& filePath, const std::string& textureFileName, SpriteFrameCache& cache) override = 0; + void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) override = 0; + void reload(const std::string& filePath, SpriteFrameCache& cache) override = 0; }; // end of _2d group diff --git a/cocos/2d/CCTMXObjectGroup.cpp b/cocos/2d/CCTMXObjectGroup.cpp index 99042b01b3..7196acad9b 100644 --- a/cocos/2d/CCTMXObjectGroup.cpp +++ b/cocos/2d/CCTMXObjectGroup.cpp @@ -40,7 +40,7 @@ TMXObjectGroup::~TMXObjectGroup() CCLOGINFO("deallocing TMXObjectGroup: %p", this); } -ValueMap TMXObjectGroup::getObject(std::string_view objectName) const +ValueMap TMXObjectGroup::getObject(const std::string& objectName) const { if (!_objects.empty()) { @@ -59,7 +59,7 @@ ValueMap TMXObjectGroup::getObject(std::string_view objectName) const return ValueMap(); } -Value TMXObjectGroup::getProperty(std::string_view propertyName) const +Value TMXObjectGroup::getProperty(const std::string& propertyName) const { if (_properties.find(propertyName) != _properties.end()) return _properties.at(propertyName); diff --git a/cocos/2d/CCTMXObjectGroup.h b/cocos/2d/CCTMXObjectGroup.h index 5a012fc180..d7df9de64b 100644 --- a/cocos/2d/CCTMXObjectGroup.h +++ b/cocos/2d/CCTMXObjectGroup.h @@ -60,13 +60,13 @@ public: * * @return The group name. */ - std::string_view getGroupName() const { return _groupName; } + const std::string& getGroupName() const { return _groupName; } /** Set the group name. * * @param groupName A string,it is used to set the group name. */ - void setGroupName(std::string_view groupName) { _groupName = groupName; } + void setGroupName(const std::string& groupName) { _groupName = groupName; } /** Return the value for the specific property name. * @@ -74,14 +74,14 @@ public: * @return Return the value for the specific property name. * @js NA */ - Value getProperty(std::string_view propertyName) const; + Value getProperty(const std::string& propertyName) const; /** Return the dictionary for the specific object name. * It will return the 1st object found on the array for the given name. * * @return Return the dictionary for the specific object name. */ - ValueMap getObject(std::string_view objectName) const; + ValueMap getObject(const std::string& objectName) const; /** Gets the offset position of child objects. * diff --git a/cocos/2d/CCTMXXMLParser.cpp b/cocos/2d/CCTMXXMLParser.cpp index e8d33801d8..6916188548 100644 --- a/cocos/2d/CCTMXXMLParser.cpp +++ b/cocos/2d/CCTMXXMLParser.cpp @@ -92,7 +92,7 @@ Rect TMXTilesetInfo::getRectForGID(uint32_t gid) // implementation TMXMapInfo -TMXMapInfo* TMXMapInfo::create(std::string_view tmxFile) +TMXMapInfo* TMXMapInfo::create(const std::string& tmxFile) { TMXMapInfo* ret = new TMXMapInfo(); if (ret->initWithTMXFile(tmxFile)) @@ -104,7 +104,7 @@ TMXMapInfo* TMXMapInfo::create(std::string_view tmxFile) return nullptr; } -TMXMapInfo* TMXMapInfo::createWithXML(std::string_view tmxString, std::string_view resourcePath) +TMXMapInfo* TMXMapInfo::createWithXML(const std::string& tmxString, const std::string& resourcePath) { TMXMapInfo* ret = new TMXMapInfo(); if (ret->initWithXML(tmxString, resourcePath)) @@ -116,7 +116,7 @@ TMXMapInfo* TMXMapInfo::createWithXML(std::string_view tmxString, std::string_vi return nullptr; } -void TMXMapInfo::internalInit(std::string_view tmxFileName, std::string_view resourcePath) +void TMXMapInfo::internalInit(const std::string& tmxFileName, const std::string& resourcePath) { if (!tmxFileName.empty()) { @@ -138,13 +138,13 @@ void TMXMapInfo::internalInit(std::string_view tmxFileName, std::string_view res _currentFirstGID = -1; } -bool TMXMapInfo::initWithXML(std::string_view tmxString, std::string_view resourcePath) +bool TMXMapInfo::initWithXML(const std::string& tmxString, const std::string& resourcePath) { internalInit("", resourcePath); return parseXMLString(tmxString); } -bool TMXMapInfo::initWithTMXFile(std::string_view tmxFile) +bool TMXMapInfo::initWithTMXFile(const std::string& tmxFile) { internalInit(tmxFile, ""); return parseXMLFile(_TMXFileName); @@ -171,7 +171,7 @@ TMXMapInfo::~TMXMapInfo() CCLOGINFO("deallocing TMXMapInfo: %p", this); } -bool TMXMapInfo::parseXMLString(std::string_view xmlString) +bool TMXMapInfo::parseXMLString(const std::string& xmlString) { size_t len = xmlString.size(); if (len <= 0) @@ -186,10 +186,10 @@ bool TMXMapInfo::parseXMLString(std::string_view xmlString) parser.setDelegator(this); - return parser.parse(xmlString.data(), len); + return parser.parse(xmlString.c_str(), len); } -bool TMXMapInfo::parseXMLFile(std::string_view xmlFilename) +bool TMXMapInfo::parseXMLFile(const std::string& xmlFilename) { SAXParser parser; @@ -265,7 +265,7 @@ void TMXMapInfo::startElement(void* /*ctx*/, const char* name, const char** atts tmxMapInfo->setStaggerIndex(TMXStaggerIndex_Even); } - auto hexSideLength = attributeDict["hexsidelength"].asInt(); + float hexSideLength = attributeDict["hexsidelength"].asFloat(); tmxMapInfo->setHexSideLength(hexSideLength); Vec2 s; @@ -348,7 +348,7 @@ void TMXMapInfo::startElement(void* /*ctx*/, const char* name, const char** atts TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); Vec2 layerSize = layer->_layerSize; uint32_t gid = static_cast(attributeDict["gid"].asUnsignedInt()); - int tilesAmount = static_cast(layerSize.width * layerSize.height); + int tilesAmount = layerSize.width * layerSize.height; if (_xmlTileIndex < tilesAmount) { @@ -443,7 +443,7 @@ void TMXMapInfo::startElement(void* /*ctx*/, const char* name, const char** atts TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); Vec2 layerSize = layer->_layerSize; - int tilesAmount = static_cast(layerSize.width * layerSize.height); + int tilesAmount = layerSize.width * layerSize.height; uint32_t* tiles = (uint32_t*)malloc(tilesAmount * sizeof(uint32_t)); // set all value to 0 @@ -688,10 +688,10 @@ void TMXMapInfo::endElement(void* /*ctx*/, const char* name) TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); - auto currentString = tmxMapInfo->getCurrentString(); + std::string currentString = tmxMapInfo->getCurrentString(); unsigned char* buffer; auto len = - base64Decode((unsigned char*)currentString.data(), (unsigned int)currentString.length(), &buffer); + base64Decode((unsigned char*)currentString.c_str(), (unsigned int)currentString.length(), &buffer); if (!buffer) { CCLOG("cocos2d: TiledMap: decode data error"); @@ -733,11 +733,10 @@ void TMXMapInfo::endElement(void* /*ctx*/, const char* name) TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); tmxMapInfo->setStoringCharacters(false); - auto currentString = tmxMapInfo->getCurrentString(); + std::string currentString = tmxMapInfo->getCurrentString(); vector gidTokens; - std::stringstream filestr; - filestr << currentString; + istringstream filestr(currentString); string sRow; while (getline(filestr, sRow, '\n')) { @@ -811,7 +810,7 @@ void TMXMapInfo::textHandler(void* /*ctx*/, const char* ch, size_t len) if (tmxMapInfo->isStoringCharacters()) { - std::string currentString{tmxMapInfo->getCurrentString()}; + std::string currentString = tmxMapInfo->getCurrentString(); currentString += text; tmxMapInfo->setCurrentString(currentString); } diff --git a/cocos/2d/CCTMXXMLParser.h b/cocos/2d/CCTMXXMLParser.h index 1ec2a821f4..20f780526c 100644 --- a/cocos/2d/CCTMXXMLParser.h +++ b/cocos/2d/CCTMXXMLParser.h @@ -250,9 +250,9 @@ class CC_DLL TMXMapInfo : public Ref, public SAXDelegator { public: /** creates a TMX Format with a tmx file */ - static TMXMapInfo* create(std::string_view tmxFile); + static TMXMapInfo* create(const std::string& tmxFile); /** creates a TMX Format with an XML string and a TMX resource path */ - static TMXMapInfo* createWithXML(std::string_view tmxString, std::string_view resourcePath); + static TMXMapInfo* createWithXML(const std::string& tmxString, const std::string& resourcePath); /** * @js ctor @@ -265,13 +265,13 @@ public: virtual ~TMXMapInfo(); /** initializes a TMX format with a tmx file */ - bool initWithTMXFile(std::string_view tmxFile); + bool initWithTMXFile(const std::string& tmxFile); /** initializes a TMX format with an XML string and a TMX resource path */ - bool initWithXML(std::string_view tmxString, std::string_view resourcePath); + bool initWithXML(const std::string& tmxString, const std::string& resourcePath); /** initializes parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file */ - bool parseXMLFile(std::string_view xmlFilename); + bool parseXMLFile(const std::string& xmlFilename); /* initializes parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string */ - bool parseXMLString(std::string_view xmlString); + bool parseXMLString(const std::string& xmlString); ValueMapIntKey& getTileProperties() { return _tileProperties; }; void setTileProperties(const ValueMapIntKey& tileProperties) { _tileProperties = tileProperties; } @@ -353,14 +353,14 @@ public: */ void textHandler(void* ctx, const char* ch, size_t len) override; - std::string_view getCurrentString() const { return _currentString; } - void setCurrentString(std::string_view currentString) { _currentString = currentString; } - std::string_view getTMXFileName() const { return _TMXFileName; } - void setTMXFileName(std::string_view fileName) { _TMXFileName = fileName; } - std::string_view getExternalTilesetFileName() const { return _externalTilesetFilename; } + const std::string& getCurrentString() const { return _currentString; } + void setCurrentString(const std::string& currentString) { _currentString = currentString; } + const std::string& getTMXFileName() const { return _TMXFileName; } + void setTMXFileName(const std::string& fileName) { _TMXFileName = fileName; } + const std::string& getExternalTilesetFileName() const { return _externalTilesetFilename; } protected: - void internalInit(std::string_view tmxFileName, std::string_view resourcePath); + void internalInit(const std::string& tmxFileName, const std::string& resourcePath); /// map orientation int _orientation; diff --git a/cocos/2d/CCTextFieldTTF.cpp b/cocos/2d/CCTextFieldTTF.cpp index a134395fb9..8ccdaace71 100644 --- a/cocos/2d/CCTextFieldTTF.cpp +++ b/cocos/2d/CCTextFieldTTF.cpp @@ -109,10 +109,10 @@ TextFieldTTF::~TextFieldTTF() {} // static constructor ////////////////////////////////////////////////////////////////////////// -TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(std::string_view placeholder, +TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, const Vec2& dimensions, TextHAlignment alignment, - std::string_view fontName, + const std::string& fontName, float fontSize) { TextFieldTTF* ret = new TextFieldTTF(); @@ -129,8 +129,8 @@ TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(std::string_view placeholde return nullptr; } -TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(std::string_view placeholder, - std::string_view fontName, +TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, + const std::string& fontName, float fontSize) { TextFieldTTF* ret = new TextFieldTTF(); @@ -151,10 +151,10 @@ TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(std::string_view placeholde // initialize ////////////////////////////////////////////////////////////////////////// -bool TextFieldTTF::initWithPlaceHolder(std::string_view placeholder, +bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, const Vec2& dimensions, TextHAlignment alignment, - std::string_view fontName, + const std::string& fontName, float fontSize) { setDimensions(dimensions.width, dimensions.height); @@ -162,7 +162,7 @@ bool TextFieldTTF::initWithPlaceHolder(std::string_view placeholder, return initWithPlaceHolder(placeholder, fontName, fontSize); } -bool TextFieldTTF::initWithPlaceHolder(std::string_view placeholder, std::string_view fontName, float fontSize) +bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize) { _placeHolder = placeholder; @@ -366,7 +366,7 @@ void TextFieldTTF::deleteBackward() } } -std::string_view TextFieldTTF::getContentText() +const std::string& TextFieldTTF::getContentText() { return _inputText; } @@ -573,9 +573,9 @@ void TextFieldTTF::setString(std::string_view text) _charCount = charCount; } -void TextFieldTTF::appendString(std::string_view text) +void TextFieldTTF::appendString(const std::string& text) { - insertText(text.data(), text.length()); + insertText(text.c_str(), text.length()); } void TextFieldTTF::makeStringSupportCursor(std::string& displayText) @@ -677,13 +677,13 @@ void TextFieldTTF::controlKey(EventKeyboard::KeyCode keyCode) } } -std::string_view TextFieldTTF::getString() const +const std::string& TextFieldTTF::getString() const { return _inputText; } // place holder text property -void TextFieldTTF::setPlaceHolder(std::string_view text) +void TextFieldTTF::setPlaceHolder(const std::string& text) { _placeHolder = text; if (_inputText.empty() && !_isAttachWithIME) @@ -693,7 +693,7 @@ void TextFieldTTF::setPlaceHolder(std::string_view text) } } -std::string_view TextFieldTTF::getPlaceHolder() const +const std::string& TextFieldTTF::getPlaceHolder() const { return _placeHolder; } @@ -733,7 +733,7 @@ void TextFieldTTF::setSecureTextEntry(bool value) } } -void TextFieldTTF::setPasswordTextStyle(std::string_view text) +void TextFieldTTF::setPasswordTextStyle(const std::string& text) { if (text.length() < 1) { @@ -747,7 +747,7 @@ void TextFieldTTF::setPasswordTextStyle(std::string_view text) } } -std::string_view TextFieldTTF::getPasswordTextStyle() const +const std::string& TextFieldTTF::getPasswordTextStyle() const { return _passwordStyleText; } diff --git a/cocos/2d/CCTextFieldTTF.h b/cocos/2d/CCTextFieldTTF.h index b9276ffb4a..4eee6e0f86 100644 --- a/cocos/2d/CCTextFieldTTF.h +++ b/cocos/2d/CCTextFieldTTF.h @@ -98,28 +98,28 @@ public: /** Creates a TextFieldTTF from a fontname, alignment, dimension and font size. * @js NA */ - static TextFieldTTF* textFieldWithPlaceHolder(std::string_view placeholder, + static TextFieldTTF* textFieldWithPlaceHolder(const std::string& placeholder, const Vec2& dimensions, TextHAlignment alignment, - std::string_view fontName, + const std::string& fontName, float fontSize); /** Creates a TextFieldTTF from a fontname and font size. * @js NA */ - static TextFieldTTF* textFieldWithPlaceHolder(std::string_view placeholder, - std::string_view fontName, + static TextFieldTTF* textFieldWithPlaceHolder(const std::string& placeholder, + const std::string& fontName, float fontSize); /** Initializes the TextFieldTTF with a font name, alignment, dimension and font size. */ - bool initWithPlaceHolder(std::string_view placeholder, + bool initWithPlaceHolder(const std::string& placeholder, const Vec2& dimensions, TextHAlignment alignment, - std::string_view fontName, + const std::string& fontName, float fontSize); /** Initializes the TextFieldTTF with a font name and font size. */ - bool initWithPlaceHolder(std::string_view placeholder, std::string_view fontName, float fontSize); + bool initWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize); /** *@brief Open keyboard and receive input text. @@ -183,26 +183,26 @@ public: * Append to input text of TextField. *@param text The append text of TextField. */ - virtual void appendString(std::string_view text); + virtual void appendString(const std::string& text); /** * Query the input text of TextField. *@return Get the input text of TextField. */ - virtual std::string_view getString() const override; + virtual const std::string& getString() const override; /** * Change placeholder text. * place holder text displayed when there is no text in the text field. *@param text The placeholder string. */ - virtual void setPlaceHolder(std::string_view text); + virtual void setPlaceHolder(const std::string& text); /** * Query the placeholder string. *@return The placeholder string. */ - virtual std::string_view getPlaceHolder() const; + virtual const std::string& getPlaceHolder() const; /** * Set enable secure text entry representation. @@ -211,8 +211,8 @@ public: * @js NA */ virtual void setSecureTextEntry(bool value); - virtual void setPasswordTextStyle(std::string_view text); - std::string_view getPasswordTextStyle() const; + virtual void setPasswordTextStyle(const std::string& text); + const std::string& getPasswordTextStyle() const; /** * Query whether the currently display mode is secure text entry or not. @@ -260,7 +260,7 @@ protected: virtual void didDetachWithIME() override; virtual void insertText(const char* text, size_t len) override; virtual void deleteBackward() override; - virtual std::string_view getContentText() override; + virtual const std::string& getContentText() override; virtual void controlKey(EventKeyboard::KeyCode keyCode) override; TextFieldDelegate* _delegate; diff --git a/cocos/2d/CCTileMapAtlas.cpp b/cocos/2d/CCTileMapAtlas.cpp index f0ca242ed4..987d598f7e 100644 --- a/cocos/2d/CCTileMapAtlas.cpp +++ b/cocos/2d/CCTileMapAtlas.cpp @@ -36,7 +36,7 @@ NS_CC_BEGIN // implementation TileMapAtlas -TileMapAtlas* TileMapAtlas::create(std::string_view tile, std::string_view mapFile, int tileWidth, int tileHeight) +TileMapAtlas* TileMapAtlas::create(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight) { TileMapAtlas* ret = new TileMapAtlas(); if (ret->initWithTileFile(tile, mapFile, tileWidth, tileHeight)) @@ -48,7 +48,7 @@ TileMapAtlas* TileMapAtlas::create(std::string_view tile, std::string_view mapFi return nullptr; } -bool TileMapAtlas::initWithTileFile(std::string_view tile, std::string_view mapFile, int tileWidth, int tileHeight) +bool TileMapAtlas::initWithTileFile(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight) { this->loadTGAfile(mapFile); this->calculateItemsToRender(); @@ -100,7 +100,7 @@ void TileMapAtlas::calculateItemsToRender() } } -void TileMapAtlas::loadTGAfile(std::string_view file) +void TileMapAtlas::loadTGAfile(const std::string& file) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(file); diff --git a/cocos/2d/CCTileMapAtlas.h b/cocos/2d/CCTileMapAtlas.h index b5adc261e2..711f9e1399 100644 --- a/cocos/2d/CCTileMapAtlas.h +++ b/cocos/2d/CCTileMapAtlas.h @@ -59,7 +59,7 @@ public: /** creates a TileMap with a tile file (atlas) with a map file and the width and height of each tile in points. The tile file will be loaded using the TextureMgr. */ - static TileMapAtlas* create(std::string_view tile, std::string_view mapFile, int tileWidth, int tileHeight); + static TileMapAtlas* create(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight); /** * @js ctor */ @@ -73,7 +73,7 @@ public: /** initializes a TileMap with a tile file (atlas) with a map file and the width and height of each tile in points. The file will be loaded using the TextureMgr. */ - bool initWithTileFile(std::string_view tile, std::string_view mapFile, int tileWidth, int tileHeight); + bool initWithTileFile(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight); /** * Returns a tile from position x,y. *For the moment only channel R is used @@ -100,7 +100,7 @@ public: void setTGAInfo(struct sImageTGA* TGAInfo) { _TGAInfo = TGAInfo; } protected: - void loadTGAfile(std::string_view file); + void loadTGAfile(const std::string& file); void calculateItemsToRender(); void updateAtlasValueAt(const Vec2& pos, const Color3B& value, int index); void updateAtlasValues(); diff --git a/cocos/3d/CCAnimate3D.cpp b/cocos/3d/CCAnimate3D.cpp index a192bbd1bf..7ad77b1ce5 100644 --- a/cocos/3d/CCAnimate3D.cpp +++ b/cocos/3d/CCAnimate3D.cpp @@ -128,9 +128,9 @@ Animate3D* Animate3D::reverse() const return animate; } -Node* findChildByNameRecursively(Node* node, std::string_view childName) +Node* findChildByNameRecursively(Node* node, const std::string& childName) { - std::string_view name = node->getName(); + const std::string& name = node->getName(); if (name == childName) return node; @@ -162,11 +162,11 @@ void Animate3D::startWithTarget(Node* target) { if (_animation) { - auto& boneCurves = _animation->getBoneCurves(); + const std::unordered_map& boneCurves = _animation->getBoneCurves(); for (const auto& iter : boneCurves) { - std::string_view boneName = iter.first; - auto skin = sprite->getSkeleton(); + const std::string& boneName = iter.first; + auto skin = sprite->getSkeleton(); if (skin) { auto bone = skin->getBoneByName(boneName); @@ -200,11 +200,11 @@ void Animate3D::startWithTarget(Node* target) } else { - auto& boneCurves = _animation->getBoneCurves(); + const std::unordered_map& boneCurves = _animation->getBoneCurves(); for (const auto& iter : boneCurves) { - std::string_view boneName = iter.first; - Node* node = nullptr; + const std::string& boneName = iter.first; + Node* node = nullptr; if (target->getName() == boneName) node = target; else diff --git a/cocos/3d/CCAnimation3D.cpp b/cocos/3d/CCAnimation3D.cpp index 7407b21887..7657842afd 100644 --- a/cocos/3d/CCAnimation3D.cpp +++ b/cocos/3d/CCAnimation3D.cpp @@ -29,11 +29,11 @@ NS_CC_BEGIN -Animation3D* Animation3D::create(std::string_view fileName, std::string_view animationName) +Animation3D* Animation3D::create(const std::string& fileName, const std::string& animationName) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName); - fullPath.append("#").append(animationName); - auto animation = Animation3DCache::getInstance()->getAnimation(fullPath); + std::string key = fullPath + "#" + animationName; + auto animation = Animation3DCache::getInstance()->getAnimation(key); if (animation != nullptr) return animation; @@ -50,7 +50,7 @@ Animation3D* Animation3D::create(std::string_view fileName, std::string_view ani return animation; } -bool Animation3D::initWithFile(std::string_view filename, std::string_view animationName) +bool Animation3D::initWithFile(const std::string& filename, const std::string& animationName) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename); @@ -59,8 +59,8 @@ bool Animation3D::initWithFile(std::string_view filename, std::string_view anima Animation3DData animationdata; if (bundle->load(fullPath) && bundle->loadAnimationData(animationName, &animationdata) && init(animationdata)) { - fullPath.append("#").append(animationName); - Animation3DCache::getInstance()->addAnimation(fullPath, this); + std::string key = fullPath + "#" + animationName; + Animation3DCache::getInstance()->addAnimation(key, this); Bundle3D::destroyBundle(bundle); return true; } @@ -70,7 +70,7 @@ bool Animation3D::initWithFile(std::string_view filename, std::string_view anima return false; } -Animation3D::Curve* Animation3D::getBoneCurveByName(std::string_view name) const +Animation3D::Curve* Animation3D::getBoneCurveByName(const std::string& name) const { auto it = _boneCurves.find(name); if (it != _boneCurves.end()) @@ -199,7 +199,7 @@ void Animation3DCache::destroyInstance() CC_SAFE_DELETE(_cacheInstance); } -Animation3D* Animation3DCache::getAnimation(std::string_view key) +Animation3D* Animation3DCache::getAnimation(const std::string& key) { auto it = _animations.find(key); if (it != _animations.end()) @@ -207,14 +207,14 @@ Animation3D* Animation3DCache::getAnimation(std::string_view key) return nullptr; } -void Animation3DCache::addAnimation(std::string_view key, Animation3D* animation) +void Animation3DCache::addAnimation(const std::string& key, Animation3D* animation) { const auto& it = _animations.find(key); if (it != _animations.end()) { return; // already have this key } - _animations.emplace(key, animation); //_animations[key] = animation; + _animations[key] = animation; animation->retain(); } diff --git a/cocos/3d/CCAnimation3D.h b/cocos/3d/CCAnimation3D.h index 64b1302d83..80f528ae27 100644 --- a/cocos/3d/CCAnimation3D.h +++ b/cocos/3d/CCAnimation3D.h @@ -69,7 +69,7 @@ public: }; /**read all animation or only the animation with given animationName? animationName == "" read the first.*/ - static Animation3D* create(std::string_view filename, std::string_view animationName = ""); + static Animation3D* create(const std::string& filename, const std::string& animationName = ""); /**get duration*/ float getDuration() const { return _duration; } @@ -79,10 +79,10 @@ public: * * @lua NA */ - Curve* getBoneCurveByName(std::string_view name) const; + Curve* getBoneCurveByName(const std::string& name) const; /**get the bone Curves set*/ - const hlookup::string_map& getBoneCurves() const { return _boneCurves; } + const std::unordered_map& getBoneCurves() const { return _boneCurves; } CC_CONSTRUCTOR_ACCESS : Animation3D(); virtual ~Animation3D(); @@ -90,10 +90,10 @@ public: bool init(const Animation3DData& data); /**init Animation3D with file name and animation name*/ - bool initWithFile(std::string_view filename, std::string_view animationName); + bool initWithFile(const std::string& filename, const std::string& animationName); protected: - hlookup::string_map _boneCurves; // bone curves map, key bone name, value AnimationCurve + std::unordered_map _boneCurves; // bone curves map, key bone name, value AnimationCurve float _duration; // animation duration }; @@ -109,10 +109,10 @@ public: static void destroyInstance(); /**get animation by key*/ - Animation3D* getAnimation(std::string_view key); + Animation3D* getAnimation(const std::string& key); /**add animation to cache*/ - void addAnimation(std::string_view key, Animation3D* animation); + void addAnimation(const std::string& key, Animation3D* animation); /**remove all animation*/ void removeAllAnimations(); @@ -125,7 +125,7 @@ protected: static Animation3DCache* _cacheInstance; // cache instance - hlookup::string_map _animations; // cached animations + std::unordered_map _animations; // cached animations }; // end of 3d group diff --git a/cocos/3d/CCBillBoard.cpp b/cocos/3d/CCBillBoard.cpp index 5eaba2dbb0..427d262a4c 100644 --- a/cocos/3d/CCBillBoard.cpp +++ b/cocos/3d/CCBillBoard.cpp @@ -53,7 +53,7 @@ BillBoard* BillBoard::createWithTexture(Texture2D* texture, Mode mode) return nullptr; } -BillBoard* BillBoard::create(std::string_view filename, Mode mode) +BillBoard* BillBoard::create(const std::string& filename, Mode mode) { BillBoard* billboard = new BillBoard(); if (billboard->initWithFile(filename)) @@ -66,7 +66,7 @@ BillBoard* BillBoard::create(std::string_view filename, Mode mode) return nullptr; } -BillBoard* BillBoard::create(std::string_view filename, const Rect& rect, Mode mode) +BillBoard* BillBoard::create(const std::string& filename, const Rect& rect, Mode mode) { BillBoard* billboard = new BillBoard(); if (billboard->initWithFile(filename, rect)) diff --git a/cocos/3d/CCBillBoard.h b/cocos/3d/CCBillBoard.h index 2f32370235..4eef5d257a 100644 --- a/cocos/3d/CCBillBoard.h +++ b/cocos/3d/CCBillBoard.h @@ -63,7 +63,7 @@ public: * @param filename A path to image file, e.g., "scene1/monster.png" * @return An autoreleased BillBoard object. */ - static BillBoard* create(std::string_view filename, Mode mode = Mode::VIEW_POINT_ORIENTED); + static BillBoard* create(const std::string& filename, Mode mode = Mode::VIEW_POINT_ORIENTED); /** * Creates a BillBoard with an image filename and a rect. @@ -72,7 +72,7 @@ public: * @param rect A subrect of the image file * @return An autoreleased BillBoard object */ - static BillBoard* create(std::string_view filename, const Rect& rect, Mode mode = Mode::VIEW_POINT_ORIENTED); + static BillBoard* create(const std::string& filename, const Rect& rect, Mode mode = Mode::VIEW_POINT_ORIENTED); /** * Creates a BillBoard with a Texture2D object. diff --git a/cocos/3d/CCBundle3D.cpp b/cocos/3d/CCBundle3D.cpp index 2f18d15daa..d735f5f39d 100644 --- a/cocos/3d/CCBundle3D.cpp +++ b/cocos/3d/CCBundle3D.cpp @@ -169,7 +169,7 @@ void Bundle3D::clear() } } -bool Bundle3D::load(std::string_view path) +bool Bundle3D::load(const std::string& path) { if (path.empty()) return false; @@ -193,7 +193,7 @@ bool Bundle3D::load(std::string_view path) } else { - CCLOG("warning: %s is invalid file formate", path.data()); + CCLOG("warning: %s is invalid file formate", path.c_str()); } ret ? (_path = path) : (_path = ""); @@ -204,7 +204,7 @@ bool Bundle3D::load(std::string_view path) bool Bundle3D::loadObj(MeshDatas& meshdatas, MaterialDatas& materialdatas, NodeDatas& nodedatas, - std::string_view fullPath, + const std::string& fullPath, const char* mtl_basepath) { meshdatas.resetData(); @@ -219,7 +219,7 @@ bool Bundle3D::loadObj(MeshDatas& meshdatas, std::vector shapes; std::vector materials; - auto ret = tinyobj::LoadObj(shapes, materials, fullPath.data(), mtlPath.c_str()); + auto ret = tinyobj::LoadObj(shapes, materials, fullPath.c_str(), mtlPath.c_str()); if (ret.empty()) { // fill data @@ -329,11 +329,11 @@ bool Bundle3D::loadObj(MeshDatas& meshdatas, return true; } - CCLOG("warning: load %s file error: %s", fullPath.data(), ret.c_str()); + CCLOG("warning: load %s file error: %s", fullPath.c_str(), ret.c_str()); return false; } -bool Bundle3D::loadSkinData(std::string_view /*id*/, SkinData* skindata) +bool Bundle3D::loadSkinData(const std::string& /*id*/, SkinData* skindata) { skindata->resetData(); @@ -347,7 +347,7 @@ bool Bundle3D::loadSkinData(std::string_view /*id*/, SkinData* skindata) } } -bool Bundle3D::loadAnimationData(std::string_view id, Animation3DData* animationdata) +bool Bundle3D::loadAnimationData(const std::string& id, Animation3DData* animationdata) { animationdata->resetData(); @@ -1062,7 +1062,7 @@ bool Bundle3D::loadMaterialsJson(MaterialDatas& materialdatas) } return true; } -bool Bundle3D::loadJson(std::string_view path) +bool Bundle3D::loadJson(const std::string& path) { clear(); @@ -1084,7 +1084,7 @@ bool Bundle3D::loadJson(std::string_view path) return true; } -bool Bundle3D::loadBinary(std::string_view path) +bool Bundle3D::loadBinary(const std::string& path) { clear(); @@ -1094,7 +1094,7 @@ bool Bundle3D::loadBinary(std::string_view path) if (_binaryBuffer.isNull()) { clear(); - CCLOG("warning: Failed to read file: %s", path.data()); + CCLOG("warning: Failed to read file: %s", path.c_str()); return false; } @@ -1107,7 +1107,7 @@ bool Bundle3D::loadBinary(std::string_view path) if (_binaryReader.read(sig, 1, 4) != 4 || memcmp(sig, identifier, 4) != 0) { clear(); - CCLOG("warning: Invalid identifier: %s", path.data()); + CCLOG("warning: Invalid identifier: %s", path.c_str()); return false; } @@ -1127,7 +1127,7 @@ bool Bundle3D::loadBinary(std::string_view path) if (_binaryReader.read(&_referenceCount, 4, 1) != 1) { clear(); - CCLOG("warning: Failed to read ref table size '%s'.", path.data()); + CCLOG("warning: Failed to read ref table size '%s'.", path.c_str()); return false; } @@ -1141,7 +1141,7 @@ bool Bundle3D::loadBinary(std::string_view path) _binaryReader.read(&_references[i].offset, 4, 1) != 1) { clear(); - CCLOG("warning: Failed to read ref number %u for bundle '%s'.", i, path.data()); + CCLOG("warning: Failed to read ref number %u for bundle '%s'.", i, path.c_str()); CC_SAFE_DELETE_ARRAY(_references); return false; } @@ -1460,7 +1460,7 @@ bool loadMaterialDataJson_0_2(MaterialData* /*materialdata*/) return true; } -bool Bundle3D::loadAnimationDataJson(std::string_view id, Animation3DData* animationdata) +bool Bundle3D::loadAnimationDataJson(const std::string& id, Animation3DData* animationdata) { std::string anim = ""; if (_version == "1.2" || _version == "0.2") @@ -1549,7 +1549,7 @@ bool Bundle3D::loadAnimationDataJson(std::string_view id, Animation3DData* anima return true; } -bool Bundle3D::loadAnimationDataBinary(std::string_view id, Animation3DData* animationdata) +bool Bundle3D::loadAnimationDataBinary(const std::string& id, Animation3DData* animationdata) { if (_version == "0.1" || _version == "0.2" || _version == "0.3" || _version == "0.4") @@ -1560,9 +1560,9 @@ bool Bundle3D::loadAnimationDataBinary(std::string_view id, Animation3DData* ani else { // if id is not a null string, we need to add a suffix of "animation" for seeding. - std::string id_{id}; - if (!id.empty()) - id_.append("animation"); + std::string id_ = id; + if (id != "") + id_ = id + "animation"; if (!seekToFirstType(BUNDLE_TYPE_ANIMATIONS, id_)) return false; @@ -1998,7 +1998,7 @@ NodeData* Bundle3D::parseNodesRecursivelyBinary(bool& skeleton, bool singleSprit return nodedata; } -backend::VertexFormat Bundle3D::parseGLDataType(std::string_view str, int size) +backend::VertexFormat Bundle3D::parseGLDataType(const std::string& str, int size) { backend::VertexFormat ret = backend::VertexFormat::INT; if (str == "GL_BYTE") @@ -2097,7 +2097,7 @@ backend::VertexFormat Bundle3D::parseGLDataType(std::string_view str, int size) return ret; } -backend::SamplerAddressMode Bundle3D::parseSamplerAddressMode(std::string_view str) +backend::SamplerAddressMode Bundle3D::parseSamplerAddressMode(const std::string& str) { if (str == "REPEAT") @@ -2115,7 +2115,7 @@ backend::SamplerAddressMode Bundle3D::parseSamplerAddressMode(std::string_view s } } -NTextureData::Usage Bundle3D::parseGLTextureType(std::string_view str) +NTextureData::Usage Bundle3D::parseGLTextureType(const std::string& str) { if (str == "AMBIENT") { @@ -2163,7 +2163,7 @@ NTextureData::Usage Bundle3D::parseGLTextureType(std::string_view str) return NTextureData::Usage::Unknown; } } -shaderinfos::VertexKey Bundle3D::parseGLProgramAttribute(std::string_view str) +shaderinfos::VertexKey Bundle3D::parseGLProgramAttribute(const std::string& str) { if (str == "VERTEX_ATTRIB_POSITION") { @@ -2233,14 +2233,14 @@ shaderinfos::VertexKey Bundle3D::parseGLProgramAttribute(std::string_view str) } } -void Bundle3D::getModelRelativePath(std::string_view path) +void Bundle3D::getModelRelativePath(const std::string& path) { ssize_t index = path.find_last_of('/'); std::string fullModelPath; _modelPath = path.substr(0, index + 1); } -Reference* Bundle3D::seekToFirstType(unsigned int type, std::string_view id) +Reference* Bundle3D::seekToFirstType(unsigned int type, const std::string& id) { // for each Reference for (unsigned int i = 0; i < _referenceCount; ++i) @@ -2266,7 +2266,7 @@ Reference* Bundle3D::seekToFirstType(unsigned int type, std::string_view id) return nullptr; } -std::vector Bundle3D::getTrianglesList(std::string_view path) +std::vector Bundle3D::getTrianglesList(const std::string& path) { std::vector trianglesList; diff --git a/cocos/3d/CCBundle3D.h b/cocos/3d/CCBundle3D.h index 6fb3d760a1..1a92eeb20d 100644 --- a/cocos/3d/CCBundle3D.h +++ b/cocos/3d/CCBundle3D.h @@ -64,32 +64,32 @@ public: * get define data type * @param str The type in string */ - static backend::VertexFormat parseGLDataType(std::string_view str, int size); + static backend::VertexFormat parseGLDataType(const std::string& str, int size); /** * get define data type * @param str The type in string */ - static backend::SamplerAddressMode parseSamplerAddressMode(std::string_view str); + static backend::SamplerAddressMode parseSamplerAddressMode(const std::string& str); /** * load a file. You must load a file first, then call loadMeshData, loadSkinData, and so on * @param path File to be loaded * @return result of load */ - virtual bool load(std::string_view path); + virtual bool load(const std::string& path); /** * load skin data from bundle * @param id The ID of the skin, load the first Skin in the bundle if it is empty */ - virtual bool loadSkinData(std::string_view id, SkinData* skindata); + virtual bool loadSkinData(const std::string& id, SkinData* skindata); /** * load material data from bundle * @param id The ID of the animation, load the first animation in the bundle if it is empty */ - virtual bool loadAnimationData(std::string_view id, Animation3DData* animationdata); + virtual bool loadAnimationData(const std::string& id, Animation3DData* animationdata); // since 3.3, to support reskin virtual bool loadMeshDatas(MeshDatas& meshdatas); @@ -102,21 +102,21 @@ public: * load triangle list * @param path the file path to load */ - static std::vector getTrianglesList(std::string_view path); + static std::vector getTrianglesList(const std::string& path); // load .obj file static bool loadObj(MeshDatas& meshdatas, MaterialDatas& materialdatas, NodeDatas& nodedatas, - std::string_view fullPath, + const std::string& fullPath, const char* mtl_basepath = nullptr); // calculate aabb static AABB calculateAABB(const std::vector& vertex, int stride, const std::vector& index); protected: - bool loadJson(std::string_view path); - bool loadBinary(std::string_view path); + bool loadJson(const std::string& path); + bool loadBinary(const std::string& path); bool loadMeshDatasJson(MeshDatas& meshdatas); bool loadMeshDataJson_0_1(MeshDatas& meshdatas); bool loadMeshDataJson_0_2(MeshDatas& meshdatas); @@ -137,8 +137,8 @@ protected: bool loadMaterialDataJson(MaterialData* materialdata); bool loadMaterialDataJson_0_1(MaterialData* materialdata); bool loadMaterialDataJson_0_2(MaterialData* materialdata); - bool loadAnimationDataJson(std::string_view id, Animation3DData* animationdata); - bool loadAnimationDataBinary(std::string_view id, Animation3DData* animationdata); + bool loadAnimationDataJson(const std::string& id, Animation3DData* animationdata); + bool loadAnimationDataBinary(const std::string& id, Animation3DData* animationdata); /** * load nodes of json @@ -156,26 +156,26 @@ protected: * get define data type * @param str The type in string */ - NTextureData::Usage parseGLTextureType(std::string_view str); + NTextureData::Usage parseGLTextureType(const std::string& str); /** * get vertex attribute type * @param str The type in string */ - shaderinfos::VertexKey parseGLProgramAttribute(std::string_view str); + shaderinfos::VertexKey parseGLProgramAttribute(const std::string& str); /* * get model path * @param str Full path of model file */ - void getModelRelativePath(std::string_view path); + void getModelRelativePath(const std::string& path); /* * set the read position in buffer to the target type * @param The data type * @param The data id */ - Reference* seekToFirstType(unsigned int type, std::string_view id = ""); + Reference* seekToFirstType(unsigned int type, const std::string& id = ""); CC_CONSTRUCTOR_ACCESS : Bundle3D(); virtual ~Bundle3D(); diff --git a/cocos/3d/CCBundle3DData.h b/cocos/3d/CCBundle3DData.h index 2538209458..2f54bdfcf2 100644 --- a/cocos/3d/CCBundle3DData.h +++ b/cocos/3d/CCBundle3DData.h @@ -220,21 +220,21 @@ struct SkinData rootBoneIndex = -1; } - void addSkinBoneNames(std::string_view name) + void addSkinBoneNames(const std::string& name) { auto it = std::find(skinBoneNames.begin(), skinBoneNames.end(), name); if (it == skinBoneNames.end()) - skinBoneNames.push_back(std::string{name}); + skinBoneNames.push_back(name); } - void addNodeBoneNames(std::string_view name) + void addNodeBoneNames(const std::string& name) { auto it = std::find(nodeBoneNames.begin(), nodeBoneNames.end(), name); if (it == nodeBoneNames.end()) - nodeBoneNames.push_back(std::string{name}); + nodeBoneNames.push_back(name); } - int getSkinBoneNameIndex(std::string_view name) const + int getSkinBoneNameIndex(const std::string& name) const { int i = 0; for (const auto& iter : skinBoneNames) @@ -246,7 +246,7 @@ struct SkinData return -1; } - int getBoneNameIndex(std::string_view name) const + int getBoneNameIndex(const std::string& name) const { int i = 0; for (const auto& iter : skinBoneNames) @@ -323,7 +323,7 @@ struct MaterialDatas { std::vector materials; void resetData() { materials.clear(); } - const NMaterialData* getMaterialData(std::string_view materialid) const + const NMaterialData* getMaterialData(const std::string& materialid) const { for (const auto& it : materials) { diff --git a/cocos/3d/CCMesh.cpp b/cocos/3d/CCMesh.cpp index 3a24788499..92a9434da0 100644 --- a/cocos/3d/CCMesh.cpp +++ b/cocos/3d/CCMesh.cpp @@ -228,7 +228,7 @@ Mesh* Mesh::create(const std::vector& vertices, return create("", indexData); } -Mesh* Mesh::create(std::string_view name, MeshIndexData* indexData, MeshSkin* skin) +Mesh* Mesh::create(const std::string& name, MeshIndexData* indexData, MeshSkin* skin) { auto state = new Mesh(); state->autorelease(); @@ -255,7 +255,7 @@ bool Mesh::isVisible() const return _visible; } -void Mesh::setTexture(std::string_view texPath) +void Mesh::setTexture(const std::string& texPath) { _texFile = texPath; auto tex = Director::getInstance()->getTextureCache()->addImage(texPath); @@ -307,7 +307,7 @@ void Mesh::setTexture(Texture2D* tex, NTextureData::Usage usage, bool cacheFileN } } -void Mesh::setTexture(std::string_view texPath, NTextureData::Usage usage) +void Mesh::setTexture(const std::string& texPath, NTextureData::Usage usage) { auto tex = Director::getInstance()->getTextureCache()->addImage(texPath); setTexture(tex, usage); @@ -350,7 +350,7 @@ void Mesh::setMaterial(Material* material) if (_material->getTechnique()->getName().compare(technique->getName()) == 0) { auto program = pass->getProgramState()->getProgram(); - auto attributes = program->getActiveAttributes(); + auto& attributes = program->getActiveAttributes(); auto meshVertexData = _meshIndexData->getMeshVertexData(); auto attributeCount = meshVertexData->getMeshVertexAttribCount(); CCASSERT(attributes.size() <= attributeCount, "missing attribute data"); diff --git a/cocos/3d/CCMesh.h b/cocos/3d/CCMesh.h index 3f8490edca..bbd9610b7a 100644 --- a/cocos/3d/CCMesh.h +++ b/cocos/3d/CCMesh.h @@ -83,7 +83,7 @@ public: * create mesh * @lua NA */ - static Mesh* create(std::string_view name, MeshIndexData* indexData, MeshSkin* skin = nullptr); + static Mesh* create(const std::string& name, MeshIndexData* indexData, MeshSkin* skin = nullptr); /** * get vertex buffer @@ -109,7 +109,7 @@ public: * call setTexture(texPath, NTextureData::Usage::Diffuse) * @param texPath texture path */ - void setTexture(std::string_view texPath); + void setTexture(const std::string& texPath); /** * set texture (diffuse), which is responsible for the main appearance. It is also means main texture, you can also * call setTexture(texPath, NTextureData::Usage::Diffuse) @@ -128,7 +128,7 @@ public: * @param texPath texture path * @param usage Usage of this texture */ - void setTexture(std::string_view texPath, NTextureData::Usage usage); + void setTexture(const std::string& texPath, NTextureData::Usage usage); /** * Get texture (diffuse), which is responsible for the main appearance. It is also means main texture, you can also * call getTexture(NTextureData::Usage::Diffuse) @@ -168,7 +168,7 @@ public: backend::ProgramState* getProgramState() const; /**name getter */ - std::string_view getName() const { return _name; } + const std::string& getName() const { return _name; } void setBlendFunc(const BlendFunc& blendFunc); const BlendFunc& getBlendFunc() const; @@ -225,7 +225,7 @@ public: /**Mesh index data setter*/ void setMeshIndexData(MeshIndexData* indexdata); /**name setter*/ - void setName(std::string_view name) { _name = name; } + void setName(const std::string& name) { _name = name; } /** * calculate the AABB of the mesh diff --git a/cocos/3d/CCMeshSkin.cpp b/cocos/3d/CCMeshSkin.cpp index 868aa50e08..903ff6cc7b 100644 --- a/cocos/3d/CCMeshSkin.cpp +++ b/cocos/3d/CCMeshSkin.cpp @@ -75,7 +75,7 @@ Bone3D* MeshSkin::getBoneByIndex(unsigned int index) const return nullptr; } -Bone3D* MeshSkin::getBoneByName(std::string_view id) const +Bone3D* MeshSkin::getBoneByName(const std::string& id) const { // search from skin bones for (const auto& it : _skinBones) diff --git a/cocos/3d/CCMeshSkin.h b/cocos/3d/CCMeshSkin.h index 3533f11337..13df178572 100644 --- a/cocos/3d/CCMeshSkin.h +++ b/cocos/3d/CCMeshSkin.h @@ -54,7 +54,7 @@ class CC_DLL MeshSkin : public Ref public: /**create a new meshskin if do not want to share meshskin*/ - static MeshSkin* create(Skeleton3D* skeleton, std::string_view filename, std::string_view name); + static MeshSkin* create(Skeleton3D* skeleton, const std::string& filename, const std::string& name); static MeshSkin* create(Skeleton3D* skeleton, const std::vector& boneNames, @@ -65,7 +65,7 @@ public: /**get bone*/ Bone3D* getBoneByIndex(unsigned int index) const; - Bone3D* getBoneByName(std::string_view id) const; + Bone3D* getBoneByName(const std::string& id) const; /**get bone index*/ int getBoneIndex(Bone3D* bone) const; diff --git a/cocos/3d/CCMeshVertexIndexData.cpp b/cocos/3d/CCMeshVertexIndexData.cpp index 3e0544022d..0f4c730859 100644 --- a/cocos/3d/CCMeshVertexIndexData.cpp +++ b/cocos/3d/CCMeshVertexIndexData.cpp @@ -49,7 +49,7 @@ using namespace std; NS_CC_BEGIN ///////////////////////////////////////////////////////////////////////////////////////////////////////////// -MeshIndexData* MeshIndexData::create(std::string_view id, +MeshIndexData* MeshIndexData::create(const std::string& id, MeshVertexData* vertexData, backend::Buffer* indexbuffer, const AABB& aabb) @@ -160,7 +160,7 @@ MeshVertexData* MeshVertexData::create(const MeshData& meshdata) return vertexdata; } -MeshIndexData* MeshVertexData::getMeshIndexDataById(std::string_view id) const +MeshIndexData* MeshVertexData::getMeshIndexDataById(const std::string& id) const { for (auto it : _indexs) { diff --git a/cocos/3d/CCMeshVertexIndexData.h b/cocos/3d/CCMeshVertexIndexData.h index ef68b9455c..a65a9ab641 100644 --- a/cocos/3d/CCMeshVertexIndexData.h +++ b/cocos/3d/CCMeshVertexIndexData.h @@ -55,7 +55,7 @@ class CC_DLL MeshIndexData : public Ref { public: /** create */ - static MeshIndexData* create(std::string_view id, + static MeshIndexData* create(const std::string& id, MeshVertexData* vertexData, backend::Buffer* indexbuffer, const AABB& aabb); @@ -74,8 +74,8 @@ public: const AABB& getAABB() const { return _aabb; } /** id setter and getter */ - void setId(std::string_view id) { _id = id; } - std::string_view getId() const { return _id; } + void setId(const std::string& id) { _id = id; } + const std::string& getId() const { return _id; } /**primitive type setter & getter*/ MeshCommand::PrimitiveType getPrimitiveType() const { return _primitiveType; } @@ -128,7 +128,7 @@ public: /** get index data by index */ MeshIndexData* getMeshIndexDataByIndex(int index) const { return _indexs.at(index); } /** get index data by id */ - MeshIndexData* getMeshIndexDataById(std::string_view id) const; + MeshIndexData* getMeshIndexDataById(const std::string& id) const; ssize_t getSizePerVertex() const { return _sizePerVertex; } diff --git a/cocos/3d/CCMotionStreak3D.cpp b/cocos/3d/CCMotionStreak3D.cpp index 6337c9fd66..e7ca8d32df 100644 --- a/cocos/3d/CCMotionStreak3D.cpp +++ b/cocos/3d/CCMotionStreak3D.cpp @@ -61,7 +61,7 @@ MotionStreak3D* MotionStreak3D::create(float fade, float minSeg, float stroke, const Color3B& color, - std::string_view path) + const std::string& path) { MotionStreak3D* ret = new MotionStreak3D(); if (ret && ret->initWithFade(fade, minSeg, stroke, color, path)) @@ -87,7 +87,7 @@ MotionStreak3D* MotionStreak3D::create(float fade, float minSeg, float stroke, c return nullptr; } -bool MotionStreak3D::initWithFade(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path) +bool MotionStreak3D::initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path) { CCASSERT(!path.empty(), "Invalid filename"); diff --git a/cocos/3d/CCMotionStreak3D.h b/cocos/3d/CCMotionStreak3D.h index dc7e072e3c..6b020a02cd 100644 --- a/cocos/3d/CCMotionStreak3D.h +++ b/cocos/3d/CCMotionStreak3D.h @@ -57,7 +57,11 @@ public: * @param path The texture file name of stoke. * @return An autoreleased MotionStreak3D object. */ - static MotionStreak3D* create(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path); + static MotionStreak3D* create(float fade, + float minSeg, + float stroke, + const Color3B& color, + const std::string& path); /** Creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture. * * @param fade The fade time, in seconds. @@ -160,7 +164,7 @@ public: /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture filename */ - bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path); + bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path); /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture */ bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture); diff --git a/cocos/3d/CCObjLoader.cpp b/cocos/3d/CCObjLoader.cpp index b3f0935f86..4d78b5d475 100644 --- a/cocos/3d/CCObjLoader.cpp +++ b/cocos/3d/CCObjLoader.cpp @@ -395,7 +395,7 @@ static bool exportFaceGroupToShape(shape_t& shape, const std::vector& in_texcoords, const std::vector>& faceGroup, const int material_id, - std::string_view name, + const std::string& name, bool clearCache) { if (faceGroup.empty()) @@ -517,7 +517,7 @@ std::string LoadMtl(std::map& material_map, char namebuf[TINYOBJ_SSCANF_BUFFER_SIZE]; token += 7; #ifdef _MSC_VER - sscanf_s(token, "%s", namebuf, static_cast(_countof(namebuf))); + sscanf_s(token, "%s", namebuf, _countof(namebuf)); #else sscanf(token, "%s", namebuf); #endif @@ -681,7 +681,7 @@ std::string LoadMtl(std::map& material_map, return err.str(); } -std::string MaterialFileReader::operator()(std::string_view matId, +std::string MaterialFileReader::operator()(const std::string& matId, std::vector& materials, std::map& matMap) { @@ -689,7 +689,7 @@ std::string MaterialFileReader::operator()(std::string_view matId, if (!m_mtlBasePath.empty()) { - filepath.append(m_mtlBasePath).append(matId); + filepath = std::string(m_mtlBasePath) + matId; } else { diff --git a/cocos/3d/CCObjLoader.h b/cocos/3d/CCObjLoader.h index af64222dc3..ef0dde2912 100644 --- a/cocos/3d/CCObjLoader.h +++ b/cocos/3d/CCObjLoader.h @@ -75,7 +75,7 @@ public: MaterialReader() {} virtual ~MaterialReader() {} - virtual std::string operator()(std::string_view matId, + virtual std::string operator()(const std::string& matId, std::vector& materials, std::map& matMap) = 0; }; @@ -83,9 +83,9 @@ public: class MaterialFileReader : public MaterialReader { public: - MaterialFileReader(std::string_view mtl_basepath) : m_mtlBasePath(mtl_basepath) {} + MaterialFileReader(const std::string& mtl_basepath) : m_mtlBasePath(mtl_basepath) {} virtual ~MaterialFileReader() {} - virtual std::string operator()(std::string_view matId, + virtual std::string operator()(const std::string& matId, std::vector& materials, std::map& matMap); diff --git a/cocos/3d/CCSkeleton3D.cpp b/cocos/3d/CCSkeleton3D.cpp index 7aa8d6a386..4bf8763fba 100644 --- a/cocos/3d/CCSkeleton3D.cpp +++ b/cocos/3d/CCSkeleton3D.cpp @@ -136,7 +136,7 @@ void Bone3D::clearBoneBlendState() /** * Creates C3DBone. */ -Bone3D* Bone3D::create(std::string_view id) +Bone3D* Bone3D::create(const std::string& id) { auto bone = new Bone3D(id); bone->autorelease(); @@ -185,7 +185,7 @@ void Bone3D::removeAllChildBone() _children.clear(); } -Bone3D::Bone3D(std::string_view id) : _name(id), _parent(nullptr), _worldDirty(true) {} +Bone3D::Bone3D(const std::string& id) : _name(id), _parent(nullptr), _worldDirty(true) {} Bone3D::~Bone3D() { @@ -279,7 +279,7 @@ Bone3D* Skeleton3D::getBoneByIndex(unsigned int index) const return nullptr; } -Bone3D* Skeleton3D::getBoneByName(std::string_view id) const +Bone3D* Skeleton3D::getBoneByName(const std::string& id) const { // search from bones for (auto it : _bones) diff --git a/cocos/3d/CCSkeleton3D.h b/cocos/3d/CCSkeleton3D.h index bd13a8a959..e63a06050c 100644 --- a/cocos/3d/CCSkeleton3D.h +++ b/cocos/3d/CCSkeleton3D.h @@ -61,7 +61,7 @@ public: const Mat4& getWorldMat(); /**get bone name*/ - std::string_view getName() const { return _name; } + const std::string& getName() const { return _name; } /** * set animation value @@ -78,7 +78,7 @@ public: /** * Creates C3DBone. */ - static Bone3D* create(std::string_view id); + static Bone3D* create(const std::string& id); /** * Sets the inverse bind pose matrix. @@ -139,7 +139,7 @@ protected: /** * Constructor. */ - Bone3D(std::string_view id); + Bone3D(const std::string& id); /** * Destructor. @@ -190,7 +190,7 @@ public: /**get bone*/ Bone3D* getBoneByIndex(unsigned int index) const; - Bone3D* getBoneByName(std::string_view id) const; + Bone3D* getBoneByName(const std::string& id) const; /**get & set root bone*/ ssize_t getRootCount() const; diff --git a/cocos/3d/CCSkybox.cpp b/cocos/3d/CCSkybox.cpp index 7e9d1fc2e8..e21c9770f8 100644 --- a/cocos/3d/CCSkybox.cpp +++ b/cocos/3d/CCSkybox.cpp @@ -41,12 +41,12 @@ Skybox::~Skybox() _texture->release(); } -Skybox* Skybox::create(std::string_view positive_x, - std::string_view negative_x, - std::string_view positive_y, - std::string_view negative_y, - std::string_view positive_z, - std::string_view negative_z) +Skybox* Skybox::create(const std::string& positive_x, + const std::string& negative_x, + const std::string& positive_y, + const std::string& negative_y, + const std::string& positive_z, + const std::string& negative_z) { auto ret = new Skybox(); ret->init(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z); @@ -90,12 +90,12 @@ bool Skybox::init() return true; } -bool Skybox::init(std::string_view positive_x, - std::string_view negative_x, - std::string_view positive_y, - std::string_view negative_y, - std::string_view positive_z, - std::string_view negative_z) +bool Skybox::init(const std::string& positive_x, + const std::string& negative_x, + const std::string& positive_y, + const std::string& negative_y, + const std::string& positive_z, + const std::string& negative_z) { auto texture = TextureCube::create(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z); if (texture == nullptr) diff --git a/cocos/3d/CCSkybox.h b/cocos/3d/CCSkybox.h index 40560f2978..644da64463 100644 --- a/cocos/3d/CCSkybox.h +++ b/cocos/3d/CCSkybox.h @@ -58,12 +58,12 @@ public: @param negative_z texture for the rear side of the texture cube face. @return A new skybox inited with given parameters. */ - static Skybox* create(std::string_view positive_x, - std::string_view negative_x, - std::string_view positive_y, - std::string_view negative_y, - std::string_view positive_z, - std::string_view negative_z); + static Skybox* create(const std::string& positive_x, + const std::string& negative_x, + const std::string& positive_y, + const std::string& negative_y, + const std::string& positive_z, + const std::string& negative_z); /**texture getter and setter*/ void setTexture(TextureCube*); @@ -93,12 +93,12 @@ public: /** * initialize with texture path */ - bool init(std::string_view positive_x, - std::string_view negative_x, - std::string_view positive_y, - std::string_view negative_y, - std::string_view positive_z, - std::string_view negative_z); + bool init(const std::string& positive_x, + const std::string& negative_x, + const std::string& positive_y, + const std::string& negative_y, + const std::string& positive_z, + const std::string& negative_z); protected: /** diff --git a/cocos/3d/CCSprite3D.cpp b/cocos/3d/CCSprite3D.cpp index f4d2e8cb68..3dcdf8e65a 100644 --- a/cocos/3d/CCSprite3D.cpp +++ b/cocos/3d/CCSprite3D.cpp @@ -63,7 +63,7 @@ Sprite3D* Sprite3D::create() return nullptr; } -Sprite3D* Sprite3D::create(std::string_view modelPath) +Sprite3D* Sprite3D::create(const std::string& modelPath) { CCASSERT(modelPath.length() >= 4, "invalid filename for Sprite3D"); @@ -77,7 +77,7 @@ Sprite3D* Sprite3D::create(std::string_view modelPath) CC_SAFE_DELETE(sprite); return nullptr; } -Sprite3D* Sprite3D::create(std::string_view modelPath, std::string_view texturePath) +Sprite3D* Sprite3D::create(const std::string& modelPath, const std::string& texturePath) { auto sprite = create(modelPath); if (sprite) @@ -88,15 +88,15 @@ Sprite3D* Sprite3D::create(std::string_view modelPath, std::string_view textureP return sprite; } -void Sprite3D::createAsync(std::string_view modelPath, +void Sprite3D::createAsync(const std::string& modelPath, const std::function& callback, void* callbackparam) { createAsync(modelPath, "", callback, callbackparam); } -void Sprite3D::createAsync(std::string_view modelPath, - std::string_view texturePath, +void Sprite3D::createAsync(const std::string& modelPath, + const std::string& texturePath, const std::function& callback, void* callbackparam) { @@ -197,7 +197,7 @@ AABB Sprite3D::getAABBRecursivelyImp(Node* node) return aabb; } -bool Sprite3D::loadFromCache(std::string_view path) +bool Sprite3D::loadFromCache(const std::string& path) { auto spritedata = Sprite3DCache::getInstance()->getSpriteData(path); if (spritedata) @@ -238,7 +238,7 @@ bool Sprite3D::loadFromCache(std::string_view path) return false; } -bool Sprite3D::loadFromFile(std::string_view path, +bool Sprite3D::loadFromFile(const std::string& path, NodeDatas* nodedatas, MeshDatas* meshdatas, MaterialDatas* materialdatas) @@ -296,7 +296,7 @@ bool Sprite3D::init() return false; } -bool Sprite3D::initWithFile(std::string_view path) +bool Sprite3D::initWithFile(const std::string& path) { _aabbDirty = true; _meshes.clear(); @@ -654,7 +654,7 @@ void Sprite3D::createNode(NodeData* nodedata, Node* root, const MaterialDatas& m } } -MeshIndexData* Sprite3D::getMeshIndexData(std::string_view indexId) const +MeshIndexData* Sprite3D::getMeshIndexData(const std::string& indexId) const { for (auto it : _meshVertexDatas) { @@ -672,7 +672,7 @@ void Sprite3D::addMesh(Mesh* mesh) _meshes.pushBack(mesh); } -void Sprite3D::setTexture(std::string_view texFile) +void Sprite3D::setTexture(const std::string& texFile) { auto tex = _director->getTextureCache()->addImage(texFile); setTexture(tex); @@ -685,7 +685,7 @@ void Sprite3D::setTexture(Texture2D* texture) mesh->setTexture(texture); } } -AttachNode* Sprite3D::getAttachNode(std::string_view boneName) +AttachNode* Sprite3D::getAttachNode(const std::string& boneName) { auto it = _attachments.find(boneName); if (it != _attachments.end()) @@ -698,7 +698,7 @@ AttachNode* Sprite3D::getAttachNode(std::string_view boneName) { auto attachNode = AttachNode::create(bone); addChild(attachNode); - _attachments.emplace(boneName, attachNode); // _attachments[boneName] = attachNode; + _attachments[boneName] = attachNode; return attachNode; } } @@ -706,7 +706,7 @@ AttachNode* Sprite3D::getAttachNode(std::string_view boneName) return nullptr; } -void Sprite3D::removeAttachNode(std::string_view boneName) +void Sprite3D::removeAttachNode(const std::string& boneName) { auto it = _attachments.find(boneName); if (it != _attachments.end()) @@ -918,7 +918,7 @@ Mesh* Sprite3D::getMeshByIndex(int index) const } /**get Mesh by Name */ -Mesh* Sprite3D::getMeshByName(std::string_view name) const +Mesh* Sprite3D::getMeshByName(const std::string& name) const { for (const auto& it : _meshes) { @@ -928,7 +928,7 @@ Mesh* Sprite3D::getMeshByName(std::string_view name) const return nullptr; } -std::vector Sprite3D::getMeshArrayByName(std::string_view name) const +std::vector Sprite3D::getMeshArrayByName(const std::string& name) const { std::vector meshes; for (const auto& it : _meshes) @@ -973,7 +973,7 @@ void Sprite3DCache::destroyInstance() } } -Sprite3DCache::Sprite3DData* Sprite3DCache::getSpriteData(std::string_view key) const +Sprite3DCache::Sprite3DData* Sprite3DCache::getSpriteData(const std::string& key) const { auto it = _spriteDatas.find(key); if (it != _spriteDatas.end()) @@ -981,18 +981,18 @@ Sprite3DCache::Sprite3DData* Sprite3DCache::getSpriteData(std::string_view key) return nullptr; } -bool Sprite3DCache::addSprite3DData(std::string_view key, Sprite3DCache::Sprite3DData* spritedata) +bool Sprite3DCache::addSprite3DData(const std::string& key, Sprite3DCache::Sprite3DData* spritedata) { auto it = _spriteDatas.find(key); if (it == _spriteDatas.end()) { - _spriteDatas.emplace(key, spritedata); // _spriteDatas[key] = spritedata; + _spriteDatas[key] = spritedata; return true; } return false; } -void Sprite3DCache::removeSprite3DData(std::string_view key) +void Sprite3DCache::removeSprite3DData(const std::string& key) { auto it = _spriteDatas.find(key); if (it != _spriteDatas.end()) diff --git a/cocos/3d/CCSprite3D.h b/cocos/3d/CCSprite3D.h index d038ce60b7..477b6968ce 100644 --- a/cocos/3d/CCSprite3D.h +++ b/cocos/3d/CCSprite3D.h @@ -62,10 +62,10 @@ public: static Sprite3D* create(); /** creates a Sprite3D*/ - static Sprite3D* create(std::string_view modelPath); + static Sprite3D* create(const std::string& modelPath); // creates a Sprite3D. It only supports one texture, and overrides the internal texture with 'texturePath' - static Sprite3D* create(std::string_view modelPath, std::string_view texturePath); + static Sprite3D* create(const std::string& modelPath, const std::string& texturePath); /** create 3d sprite asynchronously * If the 3d model was previously loaded, it will create a new 3d sprite and the callback will be called at once. @@ -76,31 +76,31 @@ public: * @param callback callback after loading * @param callbackparam user defined parameter for the callback */ - static void createAsync(std::string_view modelPath, + static void createAsync(const std::string& modelPath, const std::function& callback, void* callbackparam); - static void createAsync(std::string_view modelPath, - std::string_view texturePath, + static void createAsync(const std::string& modelPath, + const std::string& texturePath, const std::function& callback, void* callbackparam); /**set diffuse texture, set the first if multiple textures exist*/ - void setTexture(std::string_view texFile); + void setTexture(const std::string& texFile); void setTexture(Texture2D* texture); /**get Mesh by index*/ Mesh* getMeshByIndex(int index) const; /**get Mesh by Name, it returns the first one if there are more than one mesh with the same name */ - Mesh* getMeshByName(std::string_view name) const; + Mesh* getMeshByName(const std::string& name) const; /** * get mesh array by name, returns all meshes with the given name * * @lua NA */ - std::vector getMeshArrayByName(std::string_view name) const; + std::vector getMeshArrayByName(const std::string& name) const; /**get mesh*/ Mesh* getMesh() const; @@ -111,10 +111,10 @@ public: Skeleton3D* getSkeleton() const { return _skeleton; } /**get AttachNode by bone name, return nullptr if not exist*/ - AttachNode* getAttachNode(std::string_view boneName); + AttachNode* getAttachNode(const std::string& boneName); /**remove attach node*/ - void removeAttachNode(std::string_view boneName); + void removeAttachNode(const std::string& boneName); /**remove all attach nodes*/ void removeAllAttachNode(); @@ -214,16 +214,19 @@ public: virtual bool init() override; - bool initWithFile(std::string_view path); + bool initWithFile(const std::string& path); bool initFrom(const NodeDatas& nodedatas, const MeshDatas& meshdatas, const MaterialDatas& materialdatas); /**load sprite3d from cache, return true if succeed, false otherwise*/ - bool loadFromCache(std::string_view path); + bool loadFromCache(const std::string& path); /** load file and set it to meshedatas, nodedatas and materialdatas, obj file .mtl file should be at the same * directory if exist */ - bool loadFromFile(std::string_view path, NodeDatas* nodedatas, MeshDatas* meshdatas, MaterialDatas* materialdatas); + bool loadFromFile(const std::string& path, + NodeDatas* nodedatas, + MeshDatas* meshdatas, + MaterialDatas* materialdatas); /** * Visits this Sprite3D's children and draw them recursively. @@ -239,7 +242,7 @@ public: Sprite3D* createSprite3DNode(NodeData* nodedata, ModelData* modeldata, const MaterialDatas& materialdatas); /**get MeshIndexData by Id*/ - MeshIndexData* getMeshIndexData(std::string_view indexId) const; + MeshIndexData* getMeshIndexData(const std::string& indexId) const; void addMesh(Mesh* mesh); @@ -254,7 +257,7 @@ protected: Vector _meshVertexDatas; - hlookup::string_map _attachments; + std::unordered_map _attachments; BlendFunc _blend; @@ -316,17 +319,17 @@ public: * * @lua NA */ - Sprite3DData* getSpriteData(std::string_view key) const; + Sprite3DData* getSpriteData(const std::string& key) const; /** * add the SpriteData into Sprite3D by given the specified key * * @lua NA */ - bool addSprite3DData(std::string_view key, Sprite3DData* spritedata); + bool addSprite3DData(const std::string& key, Sprite3DData* spritedata); /**remove the SpriteData from Sprite3D by given the specified key*/ - void removeSprite3DData(std::string_view key); + void removeSprite3DData(const std::string& key); /**remove all the SpriteData from Sprite3D*/ void removeAllSprite3DData(); @@ -336,7 +339,7 @@ public: protected: static Sprite3DCache* _cacheInstance; - hlookup::string_map _spriteDatas; // cached sprite data + std::unordered_map _spriteDatas; // cached sprite data }; // end of 3d group diff --git a/cocos/3d/CCSprite3DMaterial.cpp b/cocos/3d/CCSprite3DMaterial.cpp index 1c109af5bb..5be1ec6974 100644 --- a/cocos/3d/CCSprite3DMaterial.cpp +++ b/cocos/3d/CCSprite3DMaterial.cpp @@ -238,7 +238,7 @@ Sprite3DMaterial* Sprite3DMaterial::createBuiltInMaterial(MaterialType type, boo return nullptr; } -Sprite3DMaterial* Sprite3DMaterial::createWithFilename(std::string_view path) +Sprite3DMaterial* Sprite3DMaterial::createWithFilename(const std::string& path) { auto validfilename = FileUtils::getInstance()->fullPathForFilename(path); if (!validfilename.empty()) @@ -311,19 +311,19 @@ void Sprite3DMaterialCache::destroyInstance() } } -bool Sprite3DMaterialCache::addSprite3DMaterial(std::string_view key, Texture2D* texture) +bool Sprite3DMaterialCache::addSprite3DMaterial(const std::string& key, Texture2D* texture) { auto itr = _materials.find(key); if (itr == _materials.end()) { CC_SAFE_RETAIN(texture); - _materials.emplace(key, texture); + _materials[key] = texture; return true; } return false; } -Texture2D* Sprite3DMaterialCache::getSprite3DMaterial(std::string_view key) +Texture2D* Sprite3DMaterialCache::getSprite3DMaterial(const std::string& key) { auto itr = _materials.find(key); if (itr != _materials.end()) diff --git a/cocos/3d/CCSprite3DMaterial.h b/cocos/3d/CCSprite3DMaterial.h index 2162627f72..1a128d0218 100644 --- a/cocos/3d/CCSprite3DMaterial.h +++ b/cocos/3d/CCSprite3DMaterial.h @@ -87,7 +87,7 @@ public: * @param path Path of material file * @return Created material */ - static Sprite3DMaterial* createWithFilename(std::string_view path); + static Sprite3DMaterial* createWithFilename(const std::string& path); /** * Create material with GLProgramState @@ -162,10 +162,10 @@ public: static void destroyInstance(); /**add to cache*/ - bool addSprite3DMaterial(std::string_view key, Texture2D* tex); + bool addSprite3DMaterial(const std::string& key, Texture2D* tex); /**get material from cache*/ - Texture2D* getSprite3DMaterial(std::string_view key); + Texture2D* getSprite3DMaterial(const std::string& key); /**remove all spritematerial*/ void removeAllSprite3DMaterial(); @@ -178,8 +178,8 @@ public: ~Sprite3DMaterialCache(); protected: - static Sprite3DMaterialCache* _cacheInstance; // instance - hlookup::string_map _materials; // cached material + static Sprite3DMaterialCache* _cacheInstance; // instance + std::unordered_map _materials; // cached material }; // end of 3d group diff --git a/cocos/3d/CCTerrain.cpp b/cocos/3d/CCTerrain.cpp index 19e0f00561..cc3bea4f6c 100644 --- a/cocos/3d/CCTerrain.cpp +++ b/cocos/3d/CCTerrain.cpp @@ -83,7 +83,7 @@ bool Terrain::initWithTerrainData(TerrainData& parameter, CrackFixedType fixedTy return initResult; } -void cocos2d::Terrain::setLightMap(std::string_view fileName) +void cocos2d::Terrain::setLightMap(const std::string& fileName) { CC_SAFE_RELEASE(_lightMap); auto image = new Image(); @@ -197,7 +197,7 @@ void Terrain::draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, } } -bool Terrain::initHeightMap(std::string_view heightMap) +bool Terrain::initHeightMap(const std::string& heightMap) { _heightMapImage = new Image(); _heightMapImage->initWithImageFile(heightMap); @@ -343,7 +343,7 @@ float Terrain::getHeight(float x, float z, Vec3* normal) const normal->z = d - a; normal->normalize(); //(*normal) = (1-u)*(1-v)*getNormal(i,j)+ (1-u)*v*getNormal(i,j+1) + u*(1-v)*getNormal(i+1,j)+ - // u*v*getNormal(i+1,j+1); + //u*v*getNormal(i+1,j+1); } float result = (1 - u) * (1 - v) * getImageHeight(i, j) * getScaleY() + (1 - u) * v * getImageHeight(i, j + 1) * getScaleY() + @@ -611,7 +611,7 @@ cocos2d::Vec2 Terrain::convertToTerrainSpace(const Vec2& worldSpaceXZ) const return Vec2(image_x, image_y); } -void Terrain::resetHeightMap(std::string_view heightMap) +void Terrain::resetHeightMap(const std::string& heightMap) { _heightMapImage->release(); _vertices.clear(); @@ -1154,8 +1154,8 @@ void Terrain::Chunk::updateIndicesLOD() } memcpy(_neighborOldLOD, currentNeighborLOD, sizeof(currentNeighborLOD)); _oldLod = _currentLod; - int gridY = static_cast(_size.height); - int gridX = static_cast(_size.width); + int gridY = _size.height; + int gridX = _size.width; int step = 1 << _currentLod; if ((_left && _left->_currentLod > _currentLod) || (_right && _right->_currentLod > _currentLod) || @@ -1644,8 +1644,8 @@ Terrain::QuadTree::~QuadTree() delete _br; } -Terrain::TerrainData::TerrainData(std::string_view heightMapsrc, - std::string_view textureSrc, +Terrain::TerrainData::TerrainData(const std::string& heightMapsrc, + const std::string& textureSrc, const Vec2& chunksize, float height, float scale) @@ -1659,8 +1659,8 @@ Terrain::TerrainData::TerrainData(std::string_view heightMapsrc, _skirtHeightRatio = 1; } -Terrain::TerrainData::TerrainData(std::string_view heightMapsrc, - std::string_view alphamap, +Terrain::TerrainData::TerrainData(const std::string& heightMapsrc, + const std::string& alphamap, const DetailMap& detail1, const DetailMap& detail2, const DetailMap& detail3, @@ -1682,8 +1682,8 @@ Terrain::TerrainData::TerrainData(std::string_view heightMapsrc, _skirtHeightRatio = 1; } -Terrain::TerrainData::TerrainData(std::string_view heightMapsrc, - std::string_view alphamap, +Terrain::TerrainData::TerrainData(const std::string& heightMapsrc, + const std::string& alphamap, const DetailMap& detail1, const DetailMap& detail2, const DetailMap& detail3, @@ -1729,7 +1729,7 @@ Terrain::ChunkIndices::~ChunkIndices() CC_SAFE_RELEASE_NULL(_indexBuffer); } -Terrain::DetailMap::DetailMap(std::string_view detailMapPath, float size /*= 35*/) +Terrain::DetailMap::DetailMap(const std::string& detailMapPath, float size /*= 35*/) { this->_detailMapSrc = detailMapPath; this->_detailMapSize = size; diff --git a/cocos/3d/CCTerrain.h b/cocos/3d/CCTerrain.h index e05a5721b2..25ebc401c9 100644 --- a/cocos/3d/CCTerrain.h +++ b/cocos/3d/CCTerrain.h @@ -108,7 +108,7 @@ public: { /*Constructors*/ DetailMap(); - DetailMap(std::string_view detailMapSrc, float size = 35); + DetailMap(const std::string& detailMapSrc, float size = 35); /*detail Image source file path*/ std::string _detailMapSrc; /*detailMapSize determine how many tiles that Terrain represent*/ @@ -136,14 +136,14 @@ public: /**empty constructor*/ TerrainData(); /**constructor, this constructor construct a simple terrain which only have 1 detailmap*/ - TerrainData(std::string_view heightMapsrc, - std::string_view textureSrc, + TerrainData(const std::string& heightMapsrc, + const std::string& textureSrc, const Vec2& chunksize = Vec2(32, 32), float mapHeight = 2, float mapScale = 0.1); /**constructor, this constructor construct a terrain which have 4 detailmaps, 1 alpha map*/ - TerrainData(std::string_view heightMapsrc, - std::string_view alphamap, + TerrainData(const std::string& heightMapsrc, + const std::string& alphamap, const DetailMap& detail1, const DetailMap& detail2, const DetailMap& detail3, @@ -152,8 +152,8 @@ public: float mapHeight = 2, float mapScale = 0.1); /**constructor, this constructor construct a terrain which have 3 detailmaps, 1 alpha map*/ - TerrainData(std::string_view heightMapsrc, - std::string_view alphamap, + TerrainData(const std::string& heightMapsrc, + const std::string& alphamap, const DetailMap& detail1, const DetailMap& detail2, const DetailMap& detail3, @@ -337,7 +337,7 @@ private: public: /** set light map texture */ - void setLightMap(std::string_view fileName); + void setLightMap(const std::string& fileName); /** set directional light for the terrain @@ -349,7 +349,7 @@ public: /**initialize all Properties which terrain need */ bool initProperties(); /**initialize heightMap data */ - bool initHeightMap(std::string_view heightMap); + bool initHeightMap(const std::string& heightMap); /**initialize alphaMap ,detailMaps textures*/ bool initTextures(); /**create entry*/ @@ -429,7 +429,7 @@ public: /** * reset the heightmap data. */ - void resetHeightMap(std::string_view heightMap); + void resetHeightMap(const std::string& heightMap); /** * get the terrain's minimal height. diff --git a/cocos/3d/CCVertexAttribBinding.cpp b/cocos/3d/CCVertexAttribBinding.cpp index f7325edb7e..9aa5e165b7 100644 --- a/cocos/3d/CCVertexAttribBinding.cpp +++ b/cocos/3d/CCVertexAttribBinding.cpp @@ -122,8 +122,9 @@ void VertexAttribBinding::parseAttributes() _attributes.clear(); _vertexAttribsFlags = 0; - auto program = _programState->getProgram(); - _attributes = program->getActiveAttributes(); + auto program = _programState->getProgram(); + auto& attributes = program->getActiveAttributes(); + _attributes = attributes; } bool VertexAttribBinding::hasAttribute(const shaderinfos::VertexKey& key) const @@ -132,7 +133,7 @@ bool VertexAttribBinding::hasAttribute(const shaderinfos::VertexKey& key) const return _attributes.find(name) != _attributes.end(); } -backend::AttributeBindInfo* VertexAttribBinding::getVertexAttribValue(std::string_view name) +backend::AttributeBindInfo* VertexAttribBinding::getVertexAttribValue(const std::string& name) { const auto itr = _attributes.find(name); if (itr != _attributes.end()) @@ -140,7 +141,7 @@ backend::AttributeBindInfo* VertexAttribBinding::getVertexAttribValue(std::strin return nullptr; } -void VertexAttribBinding::setVertexAttribPointer(std::string_view name, +void VertexAttribBinding::setVertexAttribPointer(const std::string& name, backend::VertexFormat type, bool normalized, int offset, diff --git a/cocos/3d/CCVertexAttribBinding.h b/cocos/3d/CCVertexAttribBinding.h index e923782625..20879586c0 100644 --- a/cocos/3d/CCVertexAttribBinding.h +++ b/cocos/3d/CCVertexAttribBinding.h @@ -107,18 +107,18 @@ private: VertexAttribBinding& operator=(const VertexAttribBinding&); bool init(MeshIndexData* meshIndexData, Pass* pass, MeshCommand*); - void setVertexAttribPointer(std::string_view name, + void setVertexAttribPointer(const std::string& name, backend::VertexFormat type, bool normalized, int offset, int flag); - backend::AttributeBindInfo* getVertexAttribValue(std::string_view name); + backend::AttributeBindInfo* getVertexAttribValue(const std::string& name); void parseAttributes(); MeshIndexData* _meshIndexData; backend::ProgramState* _programState; std::shared_ptr _vertexLayout = std::make_shared(); - hlookup::string_map _attributes; + std::unordered_map _attributes; uint32_t _vertexAttribsFlags; }; diff --git a/cocos/CMakeLists.txt b/cocos/CMakeLists.txt index a25fe697da..389e4295a8 100644 --- a/cocos/CMakeLists.txt +++ b/cocos/CMakeLists.txt @@ -40,10 +40,6 @@ if (NOT DEFINED CC_COMPAT_GL) set(CC_COMPAT_GL FALSE CACHE INTERNAL "Enabling CC_COMPAT_GL" ) endif() -if (NOT DEFINED ADXE_ENABLE_WEBVIEW2) - set(ADXE_ENABLE_WEBVIEW2 TRUE CACHE INTERNAL "Enabling windows webview2" ) -endif() - project(adxe_libs) if(XCODE) @@ -165,20 +161,17 @@ if(WINDOWS) # compile c as c++. needed for precompiled header set_source_files_properties(${COCOS_SPINE_SRC} base/ccFPSImages.c PROPERTIES LANGUAGE CXX) - if(ADXE_ENABLE_WEBVIEW2) - find_program(NUGET_EXE NAMES nuget - PATHS ${ADXE_ROOT_PATH}/tools/external/nuget) - - if(NOT NUGET_EXE) - message("NUGET.EXE not found.") - message(FATAL_ERROR "Please run setup.py again to download NUGET.EXE, and run CMake again.") - endif() - - exec_program(${NUGET_EXE} - ARGS install "Microsoft.Web.WebView2" -Version 1.0.992.28 -ExcludeVersion -OutputDirectory ${CMAKE_BINARY_DIR}/packages) - target_link_libraries(${ADXE_CORE_LIB} ${CMAKE_BINARY_DIR}/packages/Microsoft.Web.WebView2/build/native/Microsoft.Web.WebView2.targets) - target_compile_definitions(${ADXE_CORE_LIB} PUBLIC ADXE_HAVE_WEBVIEW2) + find_program(NUGET_EXE NAMES nuget + PATHS ${ADXE_ROOT_PATH}/tools/external/nuget) + + if(NOT NUGET_EXE) + message("NUGET.EXE not found.") + message(FATAL_ERROR "Please run setup.py again to download NUGET.EXE, and run CMake again.") endif() + + exec_program(${NUGET_EXE} + ARGS install "Microsoft.Web.WebView2" -Version 1.0.992.28 -ExcludeVersion -OutputDirectory ${CMAKE_BINARY_DIR}/packages) + target_link_libraries(${ADXE_CORE_LIB} ${CMAKE_BINARY_DIR}/packages/Microsoft.Web.WebView2/build/native/Microsoft.Web.WebView2.targets) endif() # engine extensions @@ -186,7 +179,6 @@ add_subdirectory(${ADXE_ROOT_PATH}/extensions ${ENGINE_BINARY_PATH}/extensions) if(MSVC_IDE) target_sources(${ADXE_CORE_LIB} PRIVATE ../thirdparty/yasio/yasio.natvis) - target_sources(${ADXE_CORE_LIB} PRIVATE ../thirdparty/robin-map/tsl-robin-map.natvis) endif() # copy all thirdparty libraries to ${CMAKE_BINARY_DIR}/lib/$ diff --git a/cocos/adxe.cpp b/cocos/adxe.cpp index 559aea4e0a..1dc63f4fb6 100644 --- a/cocos/adxe.cpp +++ b/cocos/adxe.cpp @@ -33,7 +33,7 @@ NS_CC_BEGIN CC_DLL const char* adxeVersion() { - return "adxe-1.0.0b5"; + return "adxe-1.0.0b4"; } NS_CC_END diff --git a/cocos/audio/include/AudioDecoder.h b/cocos/audio/include/AudioDecoder.h index 780ddc2933..1e1a27043d 100644 --- a/cocos/audio/include/AudioDecoder.h +++ b/cocos/audio/include/AudioDecoder.h @@ -60,7 +60,7 @@ public: * @brief Opens an audio file specified by a file path. * @return true if succeed, otherwise false. */ - virtual bool open(std::string_view path) = 0; + virtual bool open(const std::string& path) = 0; /** * @brief Checks whether decoder has opened file successfully. diff --git a/cocos/audio/include/AudioDecoderEXT.h b/cocos/audio/include/AudioDecoderEXT.h index f6eea0dbd2..d8d598c8ae 100644 --- a/cocos/audio/include/AudioDecoderEXT.h +++ b/cocos/audio/include/AudioDecoderEXT.h @@ -49,7 +49,7 @@ public: * @brief Opens an audio file specified by a file path. * @return true if succeed, otherwise false. */ - bool open(std::string_view path) override; + bool open(const std::string& path) override; /** * @brief Closes opened audio file. diff --git a/cocos/audio/include/AudioDecoderManager.h b/cocos/audio/include/AudioDecoderManager.h index 3075bf10d9..fe5c2d1ed9 100644 --- a/cocos/audio/include/AudioDecoderManager.h +++ b/cocos/audio/include/AudioDecoderManager.h @@ -37,7 +37,7 @@ class AudioDecoderManager public: static bool init(); static void destroy(); - static AudioDecoder* createDecoder(std::string_view path); + static AudioDecoder* createDecoder(const std::string& path); static void destroyDecoder(AudioDecoder* decoder); }; diff --git a/cocos/audio/include/AudioDecoderMp3.h b/cocos/audio/include/AudioDecoderMp3.h index 9731157397..a8be6fbeb3 100644 --- a/cocos/audio/include/AudioDecoderMp3.h +++ b/cocos/audio/include/AudioDecoderMp3.h @@ -52,7 +52,7 @@ public: * @brief Opens an audio file specified by a file path. * @return true if succeed, otherwise false. */ - bool open(std::string_view path) override; + bool open(const std::string& path) override; /** * @brief Closes opened audio file. diff --git a/cocos/audio/include/AudioDecoderOgg.h b/cocos/audio/include/AudioDecoderOgg.h index 18d86ebced..0ca447b680 100644 --- a/cocos/audio/include/AudioDecoderOgg.h +++ b/cocos/audio/include/AudioDecoderOgg.h @@ -44,7 +44,7 @@ public: * @brief Opens an audio file specified by a file path. * @return true if succeed, otherwise false. */ - bool open(std::string_view path) override; + bool open(const std::string& path) override; /** * @brief Closes opened audio file. diff --git a/cocos/audio/include/AudioDecoderWav.h b/cocos/audio/include/AudioDecoderWav.h index 8e9e101dd2..5986449463 100644 --- a/cocos/audio/include/AudioDecoderWav.h +++ b/cocos/audio/include/AudioDecoderWav.h @@ -128,7 +128,7 @@ public: * @brief Opens an audio file specified by a file path. * @return true if succeed, otherwise false. */ - bool open(std::string_view path) override; + bool open(const std::string& path) override; /** * @brief The helper function for convert frames to bytes diff --git a/cocos/audio/include/AudioEngine.h b/cocos/audio/include/AudioEngine.h index 2d864b78ee..ee89635def 100644 --- a/cocos/audio/include/AudioEngine.h +++ b/cocos/audio/include/AudioEngine.h @@ -126,7 +126,7 @@ public: * * @see `AudioProfile` */ - static AUDIO_ID play2d(std::string_view filePath, + static AUDIO_ID play2d(const std::string& filePath, bool loop = false, float volume = 1.0f, const AudioProfile* profile = nullptr); @@ -232,7 +232,7 @@ public: * @param audioID An audioID returned by the play2d function. * @param callback */ - static void setFinishCallback(AUDIO_ID audioID, const std::function& callback); + static void setFinishCallback(AUDIO_ID audioID, const std::function& callback); /** * Gets the maximum number of simultaneous audio instance of AudioEngine. @@ -253,7 +253,7 @@ public: * @warning This can lead to stop related audio first. * @param filePath Audio file path. */ - static void uncache(std::string_view filePath); + static void uncache(const std::string& filePath); /** * Uncache all audio data from internal buffer. @@ -276,20 +276,20 @@ public: * @param profileName A name of audio profile. * @return The audio profile. */ - static AudioProfile* getProfile(std::string_view profileName); + static AudioProfile* getProfile(const std::string& profileName); /** * Preload audio file. * @param filePath The file path of an audio. */ - static void preload(std::string_view filePath) { preload(filePath, nullptr); } + static void preload(const std::string& filePath) { preload(filePath, nullptr); } /** * Preload audio file. * @param filePath The file path of an audio. * @param callback A callback which will be called after loading is finished. */ - static void preload(std::string_view filePath, std::function callback); + static void preload(const std::string& filePath, std::function callback); /** * Gets playing audio count. @@ -346,10 +346,10 @@ protected: static std::unordered_map _audioIDInfoMap; // audio file path,audio IDs - static hlookup::string_map> _audioPathIDMap; + static std::unordered_map> _audioPathIDMap; // profileName,ProfileHelper - static hlookup::string_map _audioPathProfileHelperMap; + static std::unordered_map _audioPathProfileHelperMap; static unsigned int _maxInstances; diff --git a/cocos/audio/include/AudioEngineImpl.h b/cocos/audio/include/AudioEngineImpl.h index eb1c4c9610..cbb5c7284a 100644 --- a/cocos/audio/include/AudioEngineImpl.h +++ b/cocos/audio/include/AudioEngineImpl.h @@ -49,7 +49,7 @@ public: ~AudioEngineImpl(); bool init(); - AUDIO_ID play2d(std::string_view fileFullPath, bool loop, float volume); + AUDIO_ID play2d(const std::string& fileFullPath, bool loop, float volume); void setVolume(AUDIO_ID audioID, float volume); void setLoop(AUDIO_ID audioID, bool loop); bool pause(AUDIO_ID audioID); @@ -59,11 +59,11 @@ public: float getDuration(AUDIO_ID audioID); float getCurrentTime(AUDIO_ID audioID); bool setCurrentTime(AUDIO_ID audioID, float time); - void setFinishCallback(AUDIO_ID audioID, const std::function& callback); + void setFinishCallback(AUDIO_ID audioID, const std::function& callback); - void uncache(std::string_view filePath); + void uncache(const std::string& filePath); void uncacheAll(); - AudioCache* preload(std::string_view filePath, std::function callback); + AudioCache* preload(const std::string& filePath, std::function callback); void update(float dt); private: @@ -81,7 +81,7 @@ private: std::queue _unusedSourcesPool; // filePath,bufferInfo - hlookup::string_map> _audioCaches; + std::unordered_map _audioCaches; // audioID,AudioInfo std::unordered_map _audioPlayers; diff --git a/cocos/audio/include/AudioPlayer.h b/cocos/audio/include/AudioPlayer.h index 81512b98d9..e114c5ea81 100644 --- a/cocos/audio/include/AudioPlayer.h +++ b/cocos/audio/include/AudioPlayer.h @@ -72,7 +72,7 @@ protected: float _volume; bool _loop; - std::function _finishCallbak; + std::function _finishCallbak; bool _isDestroyed; bool _removeByAudioEngine; diff --git a/cocos/audio/src/AudioDecoderEXT.mm b/cocos/audio/src/AudioDecoderEXT.mm index eb7f9ceaa4..d310eb38e8 100644 --- a/cocos/audio/src/AudioDecoderEXT.mm +++ b/cocos/audio/src/AudioDecoderEXT.mm @@ -32,194 +32,183 @@ #define LOG_TAG "AudioDecoder" -namespace cocos2d -{ +namespace cocos2d { -AudioDecoderEXT::AudioDecoderEXT() : _extRef(nullptr), _fileStream(nullptr), _streamSize(0), _audioFileId(nullptr) -{ - memset(&_outputFormat, 0, sizeof(_outputFormat)); -} - -AudioDecoderEXT::~AudioDecoderEXT() -{ - closeInternal(); -} - -bool AudioDecoderEXT::open(std::string_view fullPath) -{ - bool ret = false; - CFURLRef fileURL = nil; - do + AudioDecoderEXT::AudioDecoderEXT() + : _extRef(nullptr), _fileStream(nullptr), _streamSize(0), _audioFileId(nullptr) { - BREAK_IF_ERR_LOG(fullPath.empty(), "Invalid path!"); + memset(&_outputFormat, 0, sizeof(_outputFormat)); + } - _fileStream = cocos2d::FileUtils::getInstance()->openFileStream(fullPath, FileStream::Mode::READ); - BREAK_IF_ERR_LOG(_fileStream == nullptr, "FileUtils::openFileStream FAILED for file: %s", fullPath.data()); - if (_fileStream) + AudioDecoderEXT::~AudioDecoderEXT() + { + closeInternal(); + } + + bool AudioDecoderEXT::open(const std::string& fullPath) + { + bool ret = false; + CFURLRef fileURL = nil; + do { - _streamSize = _fileStream->size(); // cache the stream size + BREAK_IF_ERR_LOG(fullPath.empty(), "Invalid path!"); + + _fileStream = cocos2d::FileUtils::getInstance()->openFileStream(fullPath, FileStream::Mode::READ); + BREAK_IF_ERR_LOG(_fileStream == nullptr, "FileUtils::openFileStream FAILED for file: %s", fullPath.c_str()); + if (_fileStream) + { + _streamSize = _fileStream->size(); // cache the stream size + } + + OSStatus status = AudioFileOpenWithCallbacks(this, &AudioDecoderEXT::readCallback, nullptr, &AudioDecoderEXT::getSizeCallback, nullptr, 0, &_audioFileId); + BREAK_IF_ERR_LOG(status != noErr, "AudioFileOpenWithCallbacks FAILED, Error = %d", (int)status); + + status = ExtAudioFileWrapAudioFileID(_audioFileId, false, &_extRef); + BREAK_IF_ERR_LOG(status != noErr, "ExtAudioFileWrapAudioFileID FAILED, Error = %d", (int)status); + + BREAK_IF_ERR_LOG(status != noErr, "ExtAudioFileOpenURL FAILED, Error = %d", (int)status); + + AudioStreamBasicDescription fileFormat; + UInt32 propertySize = sizeof(fileFormat); + + // Get the audio data format + status = ExtAudioFileGetProperty(_extRef, kExtAudioFileProperty_FileDataFormat, &propertySize, &fileFormat); + BREAK_IF_ERR_LOG(status != noErr, "ExtAudioFileGetProperty(kExtAudioFileProperty_FileDataFormat) FAILED, Error = %d", (int)status); + BREAK_IF_ERR_LOG(fileFormat.mChannelsPerFrame > 2, "Unsupported Format, channel count is greater than stereo!"); + + // Set the client format to 16 bit signed integer (native-endian) data + // Maintain the channel count and sample rate of the original source format + _outputFormat.mSampleRate = fileFormat.mSampleRate; + _outputFormat.mChannelsPerFrame = fileFormat.mChannelsPerFrame; + _outputFormat.mFormatID = kAudioFormatLinearPCM; + _outputFormat.mFramesPerPacket = 1; + _outputFormat.mBitsPerChannel = 16; + _outputFormat.mFormatFlags = kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked | kAudioFormatFlagIsSignedInteger; + + _sampleRate = _outputFormat.mSampleRate; + _channelCount = _outputFormat.mChannelsPerFrame; + _bytesPerBlock = 2 * _outputFormat.mChannelsPerFrame; + + _outputFormat.mBytesPerPacket = _bytesPerBlock; + _outputFormat.mBytesPerFrame = _bytesPerBlock; + + status = ExtAudioFileSetProperty(_extRef, kExtAudioFileProperty_ClientDataFormat, sizeof(_outputFormat), &_outputFormat); + BREAK_IF_ERR_LOG(status != noErr, "ExtAudioFileSetProperty FAILED, Error = %d", (int)status); + + // Get the total frame count + SInt64 totalFrames = 0; + propertySize = sizeof(totalFrames); + status = ExtAudioFileGetProperty(_extRef, kExtAudioFileProperty_FileLengthFrames, &propertySize, &totalFrames); + BREAK_IF_ERR_LOG(status != noErr, "ExtAudioFileGetProperty(kExtAudioFileProperty_FileLengthFrames) FAILED, Error = %d",(int)status); + BREAK_IF_ERR_LOG(totalFrames <= 0, "Total frames is 0, it's an invalid audio file: %s", fullPath.c_str()); + _totalFrames = static_cast(totalFrames); + _isOpened = true; + + ret = true; + } while (false); + + if (fileURL != nil) + CFRelease(fileURL); + + if (!ret) + { + close(); } - OSStatus status = AudioFileOpenWithCallbacks(this, &AudioDecoderEXT::readCallback, nullptr, - &AudioDecoderEXT::getSizeCallback, nullptr, 0, &_audioFileId); - BREAK_IF_ERR_LOG(status != noErr, "AudioFileOpenWithCallbacks FAILED, Error = %d", (int)status); - - status = ExtAudioFileWrapAudioFileID(_audioFileId, false, &_extRef); - BREAK_IF_ERR_LOG(status != noErr, "ExtAudioFileWrapAudioFileID FAILED, Error = %d", (int)status); - - BREAK_IF_ERR_LOG(status != noErr, "ExtAudioFileOpenURL FAILED, Error = %d", (int)status); - - AudioStreamBasicDescription fileFormat; - UInt32 propertySize = sizeof(fileFormat); - - // Get the audio data format - status = ExtAudioFileGetProperty(_extRef, kExtAudioFileProperty_FileDataFormat, &propertySize, &fileFormat); - BREAK_IF_ERR_LOG(status != noErr, - "ExtAudioFileGetProperty(kExtAudioFileProperty_FileDataFormat) FAILED, Error = %d", - (int)status); - BREAK_IF_ERR_LOG(fileFormat.mChannelsPerFrame > 2, "Unsupported Format, channel count is greater than stereo!"); - - // Set the client format to 16 bit signed integer (native-endian) data - // Maintain the channel count and sample rate of the original source format - _outputFormat.mSampleRate = fileFormat.mSampleRate; - _outputFormat.mChannelsPerFrame = fileFormat.mChannelsPerFrame; - _outputFormat.mFormatID = kAudioFormatLinearPCM; - _outputFormat.mFramesPerPacket = 1; - _outputFormat.mBitsPerChannel = 16; - _outputFormat.mFormatFlags = - kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked | kAudioFormatFlagIsSignedInteger; - - _sampleRate = _outputFormat.mSampleRate; - _channelCount = _outputFormat.mChannelsPerFrame; - _bytesPerBlock = 2 * _outputFormat.mChannelsPerFrame; - - _outputFormat.mBytesPerPacket = _bytesPerBlock; - _outputFormat.mBytesPerFrame = _bytesPerBlock; - - status = ExtAudioFileSetProperty(_extRef, kExtAudioFileProperty_ClientDataFormat, sizeof(_outputFormat), - &_outputFormat); - BREAK_IF_ERR_LOG(status != noErr, "ExtAudioFileSetProperty FAILED, Error = %d", (int)status); - - // Get the total frame count - SInt64 totalFrames = 0; - propertySize = sizeof(totalFrames); - status = ExtAudioFileGetProperty(_extRef, kExtAudioFileProperty_FileLengthFrames, &propertySize, &totalFrames); - BREAK_IF_ERR_LOG(status != noErr, - "ExtAudioFileGetProperty(kExtAudioFileProperty_FileLengthFrames) FAILED, Error = %d", - (int)status); - BREAK_IF_ERR_LOG(totalFrames <= 0, "Total frames is 0, it's an invalid audio file: %s", fullPath.data()); - _totalFrames = static_cast(totalFrames); - _isOpened = true; - - ret = true; - } while (false); - - if (fileURL != nil) - CFRelease(fileURL); - - if (!ret) - { - close(); + return ret; } - return ret; -} - -void AudioDecoderEXT::close() -{ - closeInternal(); -} - -uint32_t AudioDecoderEXT::read(uint32_t framesToRead, char* pcmBuf) -{ - uint32_t ret = 0; - do + void AudioDecoderEXT::close() { - BREAK_IF_ERR_LOG(!isOpened(), "decoder isn't openned"); - BREAK_IF_ERR_LOG(framesToRead == INVALID_FRAME_INDEX, "frameToRead is INVALID_FRAME_INDEX"); - BREAK_IF_ERR_LOG(framesToRead == 0, "frameToRead is 0"); - BREAK_IF_ERR_LOG(pcmBuf == nullptr, "pcmBuf is nullptr"); - - AudioBufferList bufferList; - bufferList.mNumberBuffers = 1; - bufferList.mBuffers[0].mDataByteSize = framesToRead * _bytesPerBlock; - bufferList.mBuffers[0].mNumberChannels = _outputFormat.mChannelsPerFrame; - bufferList.mBuffers[0].mData = pcmBuf; - - UInt32 frames = framesToRead; - OSStatus status = ExtAudioFileRead(_extRef, &frames, &bufferList); - BREAK_IF(status != noErr); - ret = frames; - } while (false); - - return ret; -} - -bool AudioDecoderEXT::seek(uint32_t frameOffset) -{ - bool ret = false; - do - { - BREAK_IF_ERR_LOG(!isOpened(), "decoder isn't openned"); - BREAK_IF_ERR_LOG(frameOffset == INVALID_FRAME_INDEX, "frameIndex is INVALID_FRAME_INDEX"); - - OSStatus status = ExtAudioFileSeek(_extRef, frameOffset); - BREAK_IF(status != noErr); - ret = true; - } while (false); - return ret; -} - -void AudioDecoderEXT::closeInternal() -{ - if (_extRef != nullptr) - { - ExtAudioFileDispose(_extRef); - AudioFileClose(_audioFileId); - _extRef = nullptr; - _audioFileId = nullptr; - _fileStream = nullptr; - } -} - -OSStatus AudioDecoderEXT::readCallback(void* inClientData, - SInt64 inPosition, - UInt32 requestCount, - void* buffer, - UInt32* actualCount) -{ - if (!inClientData) - { - return kAudioFileNotOpenError; + closeInternal(); } - auto* audioDecoder = (AudioDecoderEXT*)inClientData; - auto* fileStream = audioDecoder->_fileStream.get(); - auto currPos = (SInt64)fileStream->tell(); - auto posDiff = inPosition - currPos; - if (posDiff != 0) + uint32_t AudioDecoderEXT::read(uint32_t framesToRead, char* pcmBuf) { - if (fileStream->seek(posDiff, SEEK_CUR) < 0) + uint32_t ret = 0; + do { - return kAudioFilePositionError; + BREAK_IF_ERR_LOG(!isOpened(), "decoder isn't openned"); + BREAK_IF_ERR_LOG(framesToRead == INVALID_FRAME_INDEX, "frameToRead is INVALID_FRAME_INDEX"); + BREAK_IF_ERR_LOG(framesToRead == 0, "frameToRead is 0"); + BREAK_IF_ERR_LOG(pcmBuf == nullptr, "pcmBuf is nullptr"); + + AudioBufferList bufferList; + bufferList.mNumberBuffers = 1; + bufferList.mBuffers[0].mDataByteSize = framesToRead * _bytesPerBlock; + bufferList.mBuffers[0].mNumberChannels = _outputFormat.mChannelsPerFrame; + bufferList.mBuffers[0].mData = pcmBuf; + + UInt32 frames = framesToRead; + OSStatus status = ExtAudioFileRead(_extRef, &frames, &bufferList); + BREAK_IF(status != noErr); + ret = frames; + } while (false); + + return ret; + } + + bool AudioDecoderEXT::seek(uint32_t frameOffset) + { + bool ret = false; + do + { + BREAK_IF_ERR_LOG(!isOpened(), "decoder isn't openned"); + BREAK_IF_ERR_LOG(frameOffset == INVALID_FRAME_INDEX, "frameIndex is INVALID_FRAME_INDEX"); + + OSStatus status = ExtAudioFileSeek(_extRef, frameOffset); + BREAK_IF(status != noErr); + ret = true; + } while(false); + return ret; + } + + void AudioDecoderEXT::closeInternal() + { + if (_extRef != nullptr) + { + ExtAudioFileDispose(_extRef); + AudioFileClose(_audioFileId); + _extRef = nullptr; + _audioFileId = nullptr; + _fileStream = nullptr; } } - const auto count = fileStream->read(buffer, requestCount); - - if (count < 0) + OSStatus AudioDecoderEXT::readCallback(void *inClientData, SInt64 inPosition, UInt32 requestCount, void *buffer, UInt32 *actualCount) { - return kAudioFileEndOfFileError; + if (!inClientData) + { + return kAudioFileNotOpenError; + } + + auto* audioDecoder = (AudioDecoderEXT*)inClientData; + auto* fileStream = audioDecoder->_fileStream.get(); + auto currPos = (SInt64)fileStream->tell(); + auto posDiff = inPosition - currPos; + if (posDiff != 0) + { + if (fileStream->seek(posDiff, SEEK_CUR) < 0) + { + return kAudioFilePositionError; + } + } + + const auto count = fileStream->read(buffer, requestCount); + + if (count < 0) + { + return kAudioFileEndOfFileError; + } + + *actualCount = count; + + return noErr; } - *actualCount = count; - - return noErr; -} - -SInt64 AudioDecoderEXT::getSizeCallback(void* inClientData) -{ - auto* audioDecoder = (AudioDecoderEXT*)inClientData; - return audioDecoder->_streamSize; -} -} // namespace cocos2d { + SInt64 AudioDecoderEXT::getSizeCallback(void *inClientData) + { + auto* audioDecoder = (AudioDecoderEXT*)inClientData; + return audioDecoder->_streamSize; + } +} // namespace cocos2d { diff --git a/cocos/audio/src/AudioDecoderManager.cpp b/cocos/audio/src/AudioDecoderManager.cpp index 879d893a63..fc0730e1c4 100644 --- a/cocos/audio/src/AudioDecoderManager.cpp +++ b/cocos/audio/src/AudioDecoderManager.cpp @@ -60,7 +60,7 @@ void AudioDecoderManager::destroy() #endif } -AudioDecoder* AudioDecoderManager::createDecoder(std::string_view path) +AudioDecoder* AudioDecoderManager::createDecoder(const std::string& path) { cxx17::string_view svPath(path); if (cxx20::ic::ends_with(svPath, ".ogg")) diff --git a/cocos/audio/src/AudioDecoderMp3.cpp b/cocos/audio/src/AudioDecoderMp3.cpp index b02cecc2a1..a1c8c2cc5a 100644 --- a/cocos/audio/src/AudioDecoderMp3.cpp +++ b/cocos/audio/src/AudioDecoderMp3.cpp @@ -126,7 +126,7 @@ AudioDecoderMp3::~AudioDecoderMp3() close(); } -bool AudioDecoderMp3::open(std::string_view fullPath) +bool AudioDecoderMp3::open(const std::string& fullPath) { #if !CC_USE_MPG123 do diff --git a/cocos/audio/src/AudioDecoderOgg.cpp b/cocos/audio/src/AudioDecoderOgg.cpp index bad5a4f6f4..15c4cc9ce8 100644 --- a/cocos/audio/src/AudioDecoderOgg.cpp +++ b/cocos/audio/src/AudioDecoderOgg.cpp @@ -70,7 +70,7 @@ AudioDecoderOgg::~AudioDecoderOgg() close(); } -bool AudioDecoderOgg::open(std::string_view fullPath) +bool AudioDecoderOgg::open(const std::string& fullPath) { auto fs = FileUtils::getInstance()->openFileStream(fullPath, FileStream::Mode::READ).release(); if (!fs) diff --git a/cocos/audio/src/AudioDecoderWav.cpp b/cocos/audio/src/AudioDecoderWav.cpp index 3d6be1e0fe..28366caed4 100644 --- a/cocos/audio/src/AudioDecoderWav.cpp +++ b/cocos/audio/src/AudioDecoderWav.cpp @@ -78,7 +78,7 @@ static bool wav_scan_chunk(WAV_FILE* wavf, uint32_t chunkID, void* header, void* } return false; } -static bool wav_open(std::string_view fullPath, WAV_FILE* wavf) +static bool wav_open(const std::string& fullPath, WAV_FILE* wavf) { wavf->Stream = FileUtils::getInstance()->openFileStream(fullPath, FileStream::Mode::READ); if (!wavf->Stream) @@ -192,7 +192,7 @@ AudioDecoderWav::~AudioDecoderWav() close(); } -bool AudioDecoderWav::open(std::string_view fullPath) +bool AudioDecoderWav::open(const std::string& fullPath) { if (wav_open(fullPath, &_wavf)) { diff --git a/cocos/audio/src/AudioEngine.cpp b/cocos/audio/src/AudioEngine.cpp index 8590394e97..a59ac5b9a9 100644 --- a/cocos/audio/src/AudioEngine.cpp +++ b/cocos/audio/src/AudioEngine.cpp @@ -47,9 +47,9 @@ const int AudioEngine::INVALID_AUDIO_ID = -1; const float AudioEngine::TIME_UNKNOWN = -1.0f; // audio file path,audio IDs -hlookup::string_map> AudioEngine::_audioPathIDMap; +std::unordered_map> AudioEngine::_audioPathIDMap; // profileName,ProfileHelper -hlookup::string_map AudioEngine::_audioPathProfileHelperMap; +std::unordered_map AudioEngine::_audioPathProfileHelperMap; unsigned int AudioEngine::_maxInstances = MAX_AUDIOINSTANCES; AudioEngine::ProfileHelper* AudioEngine::_defaultProfileHelper = nullptr; std::unordered_map AudioEngine::_audioIDInfoMap; @@ -172,7 +172,7 @@ bool AudioEngine::lazyInit() return true; } -AUDIO_ID AudioEngine::play2d(std::string_view filePath, bool loop, float volume, const AudioProfile* profile) +AUDIO_ID AudioEngine::play2d(const std::string& filePath, bool loop, float volume, const AudioProfile* profile) { AUDIO_ID ret = AudioEngine::INVALID_AUDIO_ID; @@ -203,7 +203,7 @@ AUDIO_ID AudioEngine::play2d(std::string_view filePath, bool loop, float volume, if (_audioIDInfoMap.size() >= _maxInstances) { - log("Fail to play %s cause by limited max instance of AudioEngine", filePath.data()); + log("Fail to play %s cause by limited max instance of AudioEngine", filePath.c_str()); break; } if (profileHelper) @@ -211,7 +211,7 @@ AUDIO_ID AudioEngine::play2d(std::string_view filePath, bool loop, float volume, if (profileHelper->profile.maxInstances != 0 && profileHelper->audioIDs.size() >= profileHelper->profile.maxInstances) { - log("Fail to play %s cause by limited max instance of AudioProfile", filePath.data()); + log("Fail to play %s cause by limited max instance of AudioProfile", filePath.c_str()); break; } if (profileHelper->profile.minDelay > TIME_DELAY_PRECISION) @@ -220,7 +220,7 @@ AUDIO_ID AudioEngine::play2d(std::string_view filePath, bool loop, float volume, if (profileHelper->lastPlayTime > TIME_DELAY_PRECISION && currTime - profileHelper->lastPlayTime <= profileHelper->profile.minDelay) { - log("Fail to play %s cause by limited minimum delay", filePath.data()); + log("Fail to play %s cause by limited minimum delay", filePath.c_str()); break; } } @@ -238,7 +238,7 @@ AUDIO_ID AudioEngine::play2d(std::string_view filePath, bool loop, float volume, ret = _audioEngineImpl->play2d(filePath, loop, volume); if (ret != INVALID_AUDIO_ID) { - _audioPathIDMap[filePath.data()].push_back(ret); + _audioPathIDMap[filePath].push_back(ret); auto it = _audioPathIDMap.find(filePath); auto& audioRef = _audioIDInfoMap[ret]; @@ -380,7 +380,7 @@ void AudioEngine::stopAll() _audioIDInfoMap.clear(); } -void AudioEngine::uncache(std::string_view filePath) +void AudioEngine::uncache(const std::string& filePath) { if (!_audioEngineImpl) { @@ -463,7 +463,7 @@ float AudioEngine::getCurrentTime(AUDIO_ID audioID) return 0.0f; } -void AudioEngine::setFinishCallback(AUDIO_ID audioID, const std::function& callback) +void AudioEngine::setFinishCallback(AUDIO_ID audioID, const std::function& callback) { auto it = _audioIDInfoMap.find(audioID); if (it != _audioIDInfoMap.end()) @@ -539,7 +539,7 @@ AudioProfile* AudioEngine::getDefaultProfile() return &_defaultProfileHelper->profile; } -AudioProfile* AudioEngine::getProfile(std::string_view name) +AudioProfile* AudioEngine::getProfile(const std::string& name) { auto it = _audioPathProfileHelperMap.find(name); if (it != _audioPathProfileHelperMap.end()) @@ -552,7 +552,7 @@ AudioProfile* AudioEngine::getProfile(std::string_view name) } } -void AudioEngine::preload(std::string_view filePath, std::function callback) +void AudioEngine::preload(const std::string& filePath, std::function callback) { if (!isEnabled()) { diff --git a/cocos/audio/src/AudioEngineImpl.mm b/cocos/audio/src/AudioEngineImpl.mm index f4aca8818f..f51ed483fc 100644 --- a/cocos/audio/src/AudioEngineImpl.mm +++ b/cocos/audio/src/AudioEngineImpl.mm @@ -32,7 +32,7 @@ #include "audio/include/AudioDecoderManager.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC -# import +#import #endif #include "audio/include/AudioEngine.h" @@ -42,33 +42,31 @@ #include "base/ccUtils.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS -# import +#import #endif using namespace cocos2d; -static ALCdevice* s_ALDevice = nullptr; -static ALCcontext* s_ALContext = nullptr; +static ALCdevice* s_ALDevice = nullptr; +static ALCcontext* s_ALContext = nullptr; static AudioEngineImpl* s_instance = nullptr; -static void ccALPauseDevice() -{ +static void ccALPauseDevice() { ALOGD("%s", "===> ccALPauseDevice"); #if CC_USE_ALSOFT alcDevicePauseSOFT(s_ALDevice); #else - if (alcGetCurrentContext()) + if(alcGetCurrentContext()) alcMakeContextCurrent(nullptr); #endif } -static void ccALResumeDevice() -{ +static void ccALResumeDevice() { ALOGD("%s", "===> ccALResumeDevice"); #if CC_USE_ALSOFT alcDeviceResumeSOFT(s_ALDevice); #else - if (alcGetCurrentContext()) + if(alcGetCurrentContext()) alcMakeContextCurrent(nullptr); alcMakeContextCurrent(s_ALContext); #endif @@ -77,14 +75,8 @@ static void ccALResumeDevice() #if defined(__APPLE__) typedef ALvoid (*alSourceNotificationProc)(ALuint sid, ALuint notificationID, ALvoid* userData); -typedef ALenum (*alSourceAddNotificationProcPtr)(ALuint sid, - ALuint notificationID, - alSourceNotificationProc notifyProc, - ALvoid* userData); -static ALenum alSourceAddNotificationExt(ALuint sid, - ALuint notificationID, - alSourceNotificationProc notifyProc, - ALvoid* userData) +typedef ALenum (*alSourceAddNotificationProcPtr)(ALuint sid, ALuint notificationID, alSourceNotificationProc notifyProc, ALvoid* userData); +static ALenum alSourceAddNotificationExt(ALuint sid, ALuint notificationID, alSourceNotificationProc notifyProc, ALvoid* userData) { static alSourceAddNotificationProcPtr proc = nullptr; @@ -100,48 +92,42 @@ static ALenum alSourceAddNotificationExt(ALuint sid, return AL_INVALID_VALUE; } -# if CC_TARGET_PLATFORM == CC_PLATFORM_IOS -@interface AudioEngineSessionHandler : NSObject { +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS +@interface AudioEngineSessionHandler : NSObject +{ } -- (id)init; -- (void)handleInterruption:(NSNotification*)notification; +-(id) init; +-(void)handleInterruption:(NSNotification*)notification; @end @implementation AudioEngineSessionHandler -- (id)init +-(id) init { if (self = [super init]) { int deviceVer = [[[UIDevice currentDevice] systemVersion] intValue]; ALOGD("===> The device version: %d", deviceVer); - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(handleInterruption:) - name:AVAudioSessionInterruptionNotification - object:[AVAudioSession sharedInstance]]; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(handleInterruption:) - name:UIApplicationDidBecomeActiveNotification - object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(handleInterruption:) - name:UIApplicationWillResignActiveNotification - object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:UIApplicationDidBecomeActiveNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:UIApplicationWillResignActiveNotification object:nil]; - BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil]; + BOOL success = [[AVAudioSession sharedInstance] + setCategory: AVAudioSessionCategoryAmbient + error: nil]; if (!success) ALOGE("Fail to set audio session."); } return self; } -- (void)handleInterruption:(NSNotification*)notification +-(void)handleInterruption:(NSNotification*)notification { static bool isAudioSessionInterrupted = false; - static bool resumeOnBecomingActive = false; - static bool pauseOnResignActive = false; + static bool resumeOnBecomingActive = false; + static bool pauseOnResignActive = false; if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification]) { @@ -152,15 +138,13 @@ static ALenum alSourceAddNotificationExt(ALuint sid, if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) { - ALOGD("AVAudioSessionInterruptionTypeBegan, application != UIApplicationStateActive, " - "alcMakeContextCurrent(nullptr)"); + ALOGD("AVAudioSessionInterruptionTypeBegan, application != UIApplicationStateActive, alcMakeContextCurrent(nullptr)"); } else { - ALOGD("AVAudioSessionInterruptionTypeBegan, application == UIApplicationStateActive, " - "pauseOnResignActive = true"); + ALOGD("AVAudioSessionInterruptionTypeBegan, application == UIApplicationStateActive, pauseOnResignActive = true"); } - + // We always pause device when interruption began ccALPauseDevice(); } @@ -170,9 +154,8 @@ static ALenum alSourceAddNotificationExt(ALuint sid, if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) { - ALOGD("AVAudioSessionInterruptionTypeEnded, application == UIApplicationStateActive, " - "alcMakeContextCurrent(s_ALContext)"); - NSError* error = nil; + ALOGD("AVAudioSessionInterruptionTypeEnded, application == UIApplicationStateActive, alcMakeContextCurrent(s_ALContext)"); + NSError *error = nil; [[AVAudioSession sharedInstance] setActive:YES error:&error]; ccALResumeDevice(); if (Director::getInstance()->isPaused()) @@ -183,8 +166,7 @@ static ALenum alSourceAddNotificationExt(ALuint sid, } else { - ALOGD("AVAudioSessionInterruptionTypeEnded, application != UIApplicationStateActive, " - "resumeOnBecomingActive = true"); + ALOGD("AVAudioSessionInterruptionTypeEnded, application != UIApplicationStateActive, resumeOnBecomingActive = true"); resumeOnBecomingActive = true; } } @@ -206,15 +188,14 @@ static ALenum alSourceAddNotificationExt(ALuint sid, { resumeOnBecomingActive = false; ALOGD("UIApplicationDidBecomeActiveNotification, alcMakeContextCurrent(s_ALContext)"); - NSError* error = nil; - BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error]; - if (!success) - { + NSError *error = nil; + BOOL success = [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: &error]; + if (!success) { ALOGE("Fail to set audio session."); return; } [[AVAudioSession sharedInstance] setActive:YES error:&error]; - + ccALResumeDevice(); } else if (isAudioSessionInterrupted) @@ -224,20 +205,18 @@ static ALenum alSourceAddNotificationExt(ALuint sid, } } -- (void)dealloc +-(void) dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionInterruptionNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil]; - [[NSNotificationCenter defaultCenter] removeObserver:self - name:UIApplicationWillResignActiveNotification - object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil]; [super dealloc]; } @end static id s_AudioEngineSessionHandler = nullptr; -# endif +#endif ALvoid AudioEngineImpl::myAlSourceNotificationCallback(ALuint sid, ALuint notificationID, ALvoid* userData) { @@ -260,7 +239,10 @@ ALvoid AudioEngineImpl::myAlSourceNotificationCallback(ALuint sid, ALuint notifi #endif -AudioEngineImpl::AudioEngineImpl() : _scheduled(false), _currentAudioID(0), _scheduler(nullptr) +AudioEngineImpl::AudioEngineImpl() +: _scheduled(false) +, _currentAudioID(0) +, _scheduler(nullptr) { s_instance = this; } @@ -272,8 +254,7 @@ AudioEngineImpl::~AudioEngineImpl() _scheduler->unschedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this); } - if (s_ALContext) - { + if (s_ALContext) { alDeleteSources(MAX_AUDIOINSTANCES, _alSources); _audioCaches.clear(); @@ -283,8 +264,7 @@ AudioEngineImpl::~AudioEngineImpl() s_ALContext = nullptr; } - if (s_ALDevice) - { + if (s_ALDevice) { alcCloseDevice(s_ALDevice); s_ALDevice = nullptr; } @@ -300,34 +280,30 @@ AudioEngineImpl::~AudioEngineImpl() bool AudioEngineImpl::init() { bool ret = false; - do - { + do{ #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS s_AudioEngineSessionHandler = [[AudioEngineSessionHandler alloc] init]; #endif s_ALDevice = alcOpenDevice(nullptr); - if (s_ALDevice) - { + if (s_ALDevice) { alGetError(); s_ALContext = alcCreateContext(s_ALDevice, nullptr); alcMakeContextCurrent(s_ALContext); alGenSources(MAX_AUDIOINSTANCES, _alSources); auto alError = alGetError(); - if (alError != AL_NO_ERROR) + if(alError != AL_NO_ERROR) { ALOGE("%s:generating sources failed! error = %x\n", __FUNCTION__, alError); break; } - for (int i = 0; i < MAX_AUDIOINSTANCES; ++i) - { + for (int i = 0; i < MAX_AUDIOINSTANCES; ++i) { _unusedSourcesPool.push(_alSources[i]); #if defined(__APPLE__) - alSourceAddNotificationExt(_alSources[i], AL_BUFFERS_PROCESSED, myAlSourceNotificationCallback, - nullptr); + alSourceAddNotificationExt(_alSources[i], AL_BUFFERS_PROCESSED, myAlSourceNotificationCallback, nullptr); #endif } @@ -392,30 +368,28 @@ bool AudioEngineImpl::init() #endif // ================ Workaround end ================ // - _scheduler = Director::getInstance()->getScheduler(); - ret = AudioDecoderManager::init(); - const char* vender = alGetString(AL_VENDOR); + _scheduler = Director::getInstance()->getScheduler(); + ret = AudioDecoderManager::init(); + const char* vender = alGetString(AL_VENDOR); const char* version = alGetString(AL_VERSION); ALOGI("OpenAL was initialized successfully, vender:%s, version:%s", vender, version); } - } while (false); + }while (false); return ret; } -AudioCache* AudioEngineImpl::preload(std::string_view filePath, std::function callback) +AudioCache* AudioEngineImpl::preload(const std::string& filePath, std::function callback) { AudioCache* audioCache = nullptr; auto it = _audioCaches.find(filePath); - if (it == _audioCaches.end()) - { - audioCache = new AudioCache(); // hlookup_second(it); - _audioCaches.emplace(filePath, std::unique_ptr(audioCache)); + if (it == _audioCaches.end()) { + audioCache = &_audioCaches[filePath]; audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath); - unsigned int cacheId = audioCache->_id; - auto isCacheDestroyed = audioCache->_isDestroyed; - AudioEngine::addTask([audioCache, cacheId, isCacheDestroyed]() { + unsigned int cacheId = audioCache->_id; + auto isCacheDestroyed = audioCache->_isDestroyed; + AudioEngine::addTask([audioCache, cacheId, isCacheDestroyed](){ if (*isCacheDestroyed) { ALOGV("AudioCache (id=%u) was destroyed, no need to launch readDataTask.", cacheId); @@ -425,9 +399,8 @@ AudioCache* AudioEngineImpl::preload(std::string_view filePath, std::functionreadDataTask(cacheId); }); } - else - { - audioCache = it->second.get(); + else { + audioCache = &it->second; } if (audioCache && callback) @@ -437,10 +410,9 @@ AudioCache* AudioEngineImpl::preload(std::string_view filePath, std::function_alSource = alSource; - player->_loop = loop; - player->_volume = volume; + player->_loop = loop; + player->_volume = volume; auto audioCache = preload(filePath, nullptr); - if (audioCache == nullptr) - { + if (audioCache == nullptr) { delete player; return AudioEngine::INVALID_AUDIO_ID; } @@ -472,7 +442,7 @@ AUDIO_ID AudioEngineImpl::play2d(std::string_view filePath, bool loop, float vol _audioPlayers.emplace(++_currentAudioID, player); _threadMutex.unlock(); - audioCache->addPlayCallback(std::bind(&AudioEngineImpl::_play2d, this, audioCache, _currentAudioID)); + audioCache->addPlayCallback(std::bind(&AudioEngineImpl::_play2d,this,audioCache,_currentAudioID)); if (!_scheduled) { @@ -483,7 +453,7 @@ AUDIO_ID AudioEngineImpl::play2d(std::string_view filePath, bool loop, float vol return _currentAudioID; } -void AudioEngineImpl::_play2d(AudioCache* cache, AUDIO_ID audioID) +void AudioEngineImpl::_play2d(AudioCache *cache, AUDIO_ID audioID) { std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); @@ -491,14 +461,13 @@ void AudioEngineImpl::_play2d(AudioCache* cache, AUDIO_ID audioID) return; auto player = iter->second; - // Note: It maybe in sub thread or main thread :( + //Note: It maybe in sub thread or main thread :( if (!*cache->_isDestroyed && cache->_state == AudioCache::State::READY) { - if (player->play2d()) - { - _scheduler->performFunctionInCocosThread([audioID]() { - if (AudioEngine::_audioIDInfoMap.find(audioID) != AudioEngine::_audioIDInfoMap.end()) - { + if (player->play2d()) { + _scheduler->performFunctionInCocosThread([audioID](){ + + if (AudioEngine::_audioIDInfoMap.find(audioID) != AudioEngine::_audioIDInfoMap.end()) { AudioEngine::_audioIDInfoMap[audioID].state = AudioEngine::AudioState::PLAYING; } }); @@ -523,25 +492,23 @@ ALuint AudioEngineImpl::findValidSource() return sourceId; } -void AudioEngineImpl::setVolume(AUDIO_ID audioID, float volume) +void AudioEngineImpl::setVolume(AUDIO_ID audioID,float volume) { std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if (iter == _audioPlayers.end()) + if(iter == _audioPlayers.end()) return; - + auto player = iter->second; lck.unlock(); - + player->_volume = volume; - if (player->_ready) - { + if (player->_ready) { alSourcef(player->_alSource, AL_GAIN, volume); auto error = alGetError(); - if (error != AL_NO_ERROR) - { + if (error != AL_NO_ERROR) { ALOGE("%s: audio id = " AUDIO_ID_PRID ", error = %x", __FUNCTION__, audioID, error); } } @@ -551,39 +518,30 @@ void AudioEngineImpl::setLoop(AUDIO_ID audioID, bool loop) { std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if (iter == _audioPlayers.end()) + if(iter == _audioPlayers.end()) return; - + auto player = iter->second; lck.unlock(); - - if (player->_ready) - { - if (player->_streamingSource) - { + + if (player->_ready) { + if (player->_streamingSource) { player->setLoop(loop); - } - else - { - if (loop) - { + } else { + if (loop) { alSourcei(player->_alSource, AL_LOOPING, AL_TRUE); - } - else - { + } else { alSourcei(player->_alSource, AL_LOOPING, AL_FALSE); } auto error = alGetError(); - if (error != AL_NO_ERROR) - { + if (error != AL_NO_ERROR) { ALOGE("%s: audio id = " AUDIO_ID_PRID ", error = %x", __FUNCTION__, audioID, error); } } } - else - { + else { player->_loop = loop; } } @@ -592,19 +550,18 @@ bool AudioEngineImpl::pause(AUDIO_ID audioID) { std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if (iter == _audioPlayers.end()) + if(iter == _audioPlayers.end()) return false; - + auto player = iter->second; - + lck.unlock(); - + bool ret = true; alSourcePause(player->_alSource); auto error = alGetError(); - if (error != AL_NO_ERROR) - { + if (error != AL_NO_ERROR) { ret = false; ALOGE("%s: audio id = " AUDIO_ID_PRID ", error = %x\n", __FUNCTION__, audioID, error); } @@ -617,17 +574,16 @@ bool AudioEngineImpl::resume(AUDIO_ID audioID) bool ret = true; std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if (iter == _audioPlayers.end()) + if(iter == _audioPlayers.end()) return false; - + auto player = iter->second; lck.unlock(); - + alSourcePlay(player->_alSource); auto error = alGetError(); - if (error != AL_NO_ERROR) - { + if (error != AL_NO_ERROR) { ret = false; ALOGE("%s: audio id = " AUDIO_ID_PRID ", error = %x\n", __FUNCTION__, audioID, error); } @@ -639,30 +595,29 @@ void AudioEngineImpl::stop(AUDIO_ID audioID) { std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if (iter == _audioPlayers.end()) + if(iter == _audioPlayers.end()) return; - + auto player = iter->second; player->destroy(); - // Call '_updatePlayersState' method to cleanup immediately since the schedule may be cancelled without any - // notification. + // Call '_updatePlayersState' method to cleanup immediately since the schedule may be cancelled without any notification. _updatePlayers(true); } void AudioEngineImpl::stopAll() { std::lock_guard lck(_threadMutex); - for (auto&& player : _audioPlayers) + for(auto&& player : _audioPlayers) { player.second->destroy(); } - // Note: Don't set the flag to false here, it should be set in 'update' function. + //Note: Don't set the flag to false here, it should be set in 'update' function. // Otherwise, the state got from alSourceState may be wrong - // for(int index = 0; index < MAX_AUDIOINSTANCES; ++index) - // { - // _alSourceUsed[_alSources[index]] = false; - // } +// for(int index = 0; index < MAX_AUDIOINSTANCES; ++index) +// { +// _alSourceUsed[_alSources[index]] = false; +// } // Call '_updatePlayers' method to cleanup immediately since the schedule may be cancelled without any notification. _updatePlayers(true); @@ -672,11 +627,9 @@ float AudioEngineImpl::getDuration(AUDIO_ID audioID) { std::lock_guard lck(_threadMutex); auto it = _audioPlayers.find(audioID); - if (it != _audioPlayers.end()) - { + if (it != _audioPlayers.end()) { auto player = it->second; - if (player->_ready) - { + if (player->_ready) { return player->_audioCache->_duration; } } @@ -686,25 +639,21 @@ float AudioEngineImpl::getDuration(AUDIO_ID audioID) float AudioEngineImpl::getCurrentTime(AUDIO_ID audioID) { std::unique_lock lck(_threadMutex); - auto it = _audioPlayers.find(audioID); + auto it = _audioPlayers.find(audioID); if (it == _audioPlayers.end()) return 0.0f; - float ret = 0.0f; + float ret = 0.0f; auto player = it->second; - if (player->_ready) - { - if (player->_streamingSource) - { + if (player->_ready) { + if (player->_streamingSource) { ret = player->getTime(); } - else - { + else { alGetSourcef(player->_alSource, AL_SEC_OFFSET, &ret); auto error = alGetError(); - if (error != AL_NO_ERROR) - { + if (error != AL_NO_ERROR) { ALOGE("%s, audio id:" AUDIO_ID_PRID ",error code:%x", __FUNCTION__, audioID, error); } } @@ -718,28 +667,23 @@ bool AudioEngineImpl::setCurrentTime(AUDIO_ID audioID, float time) bool ret = false; std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if (iter == _audioPlayers.end()) + if(iter == _audioPlayers.end()) return false; - + auto player = iter->second; - do - { - if (!player->_ready) - { + do { + if (!player->_ready) { break; } - if (player->_streamingSource) - { + if (player->_streamingSource) { ret = player->setTime(time); break; } - else - { + else { if (player->_audioCache->_framesRead != player->_audioCache->_totalFrames && - (time * player->_audioCache->_sampleRate) > player->_audioCache->_framesRead) - { + (time * player->_audioCache->_sampleRate) > player->_audioCache->_framesRead) { ALOGE("%s: audio id = " AUDIO_ID_PRID, __FUNCTION__, audioID); break; } @@ -747,8 +691,7 @@ bool AudioEngineImpl::setCurrentTime(AUDIO_ID audioID, float time) alSourcef(player->_alSource, AL_SEC_OFFSET, time); auto error = alGetError(); - if (error != AL_NO_ERROR) - { + if (error != AL_NO_ERROR) { ALOGE("%s: audio id = " AUDIO_ID_PRID ", error = %x", __FUNCTION__, audioID, error); } ret = true; @@ -758,17 +701,16 @@ bool AudioEngineImpl::setCurrentTime(AUDIO_ID audioID, float time) return ret; } -void AudioEngineImpl::setFinishCallback(AUDIO_ID audioID, - const std::function& callback) +void AudioEngineImpl::setFinishCallback(AUDIO_ID audioID, const std::function &callback) { std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if (iter == _audioPlayers.end()) + if(iter == _audioPlayers.end()) return; - + auto player = iter->second; lck.unlock(); - + player->_finishCallbak = callback; } @@ -784,49 +726,45 @@ void AudioEngineImpl::_updatePlayers(bool forStop) AudioPlayer* player; ALuint alSource; - // ALOGV("AudioPlayer count: %d", (int)_audioPlayers.size()); - for (auto it = _audioPlayers.begin(); it != _audioPlayers.end();) - { - audioID = it->first; - player = it->second; +// ALOGV("AudioPlayer count: %d", (int)_audioPlayers.size()); + for (auto it = _audioPlayers.begin(); it != _audioPlayers.end(); ) { + audioID = it->first; + player = it->second; alSource = player->_alSource; if (player->_removeByAudioEngine) { AudioEngine::remove(audioID); - + it = _audioPlayers.erase(it); delete player; _unusedSourcesPool.push(alSource); } - else if (player->_ready && player->isFinished()) - { + else if (player->_ready && player->isFinished()) { std::string filePath; - if (player->_finishCallbak) - { + if (player->_finishCallbak) { auto& audioInfo = AudioEngine::_audioIDInfoMap[audioID]; - filePath = audioInfo.filePath; + filePath = audioInfo.filePath; } AudioEngine::remove(audioID); - + it = _audioPlayers.erase(it); - if (player->_finishCallbak) - { + if (player->_finishCallbak) { /// ###IMPORTANT: don't call immidiately, because at callback, user-end may play a new audio /// cause _audioPlayers' iterator goan to invalid. - _finishCallbacks.push_back([finishCallback = std::move(player->_finishCallbak), audioID, - filePath = std::move(filePath)]() { finishCallback(audioID, filePath); }); + _finishCallbacks.push_back([finishCallback = std::move(player->_finishCallbak), audioID, filePath = std::move(filePath)](){ + finishCallback(audioID, filePath); + }); } // clear cache when audio player finsihed properly player->setCache(nullptr); delete player; _unusedSourcesPool.push(alSource); } - else - { + else{ ++it; } } @@ -848,8 +786,7 @@ void AudioEngineImpl::_updatePlayers(bool forStop) _unscheduleUpdate(); } -void AudioEngineImpl::_unscheduleUpdate() -{ +void AudioEngineImpl::_unscheduleUpdate() { if (_scheduled) { _scheduled = false; @@ -857,7 +794,7 @@ void AudioEngineImpl::_unscheduleUpdate() } } -void AudioEngineImpl::uncache(std::string_view filePath) +void AudioEngineImpl::uncache(const std::string &filePath) { _audioCaches.erase(filePath); } diff --git a/cocos/base/CCAutoreleasePool.cpp b/cocos/base/CCAutoreleasePool.cpp index 3027fee8a0..9be2e9cdf0 100644 --- a/cocos/base/CCAutoreleasePool.cpp +++ b/cocos/base/CCAutoreleasePool.cpp @@ -38,7 +38,7 @@ AutoreleasePool::AutoreleasePool() PoolManager::getInstance()->push(this); } -AutoreleasePool::AutoreleasePool(std::string_view name) +AutoreleasePool::AutoreleasePool(const std::string& name) : _name(name) #if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) , _isClearing(false) diff --git a/cocos/base/CCAutoreleasePool.h b/cocos/base/CCAutoreleasePool.h index d2a8341ade..fde07e39de 100644 --- a/cocos/base/CCAutoreleasePool.h +++ b/cocos/base/CCAutoreleasePool.h @@ -58,7 +58,7 @@ public: * * @param name The name of created autorelease pool. */ - AutoreleasePool(std::string_view name); + AutoreleasePool(const std::string& name); /** * @js NA diff --git a/cocos/base/CCConfiguration.cpp b/cocos/base/CCConfiguration.cpp index 1979f0225c..0d623209a9 100644 --- a/cocos/base/CCConfiguration.cpp +++ b/cocos/base/CCConfiguration.cpp @@ -186,7 +186,7 @@ void Configuration::destroyInstance() CC_SAFE_RELEASE_NULL(s_sharedConfiguration); } -bool Configuration::checkForGLExtension(std::string_view searchName) const +bool Configuration::checkForGLExtension(const std::string& searchName) const { return _glExtensions.find(searchName) != std::string::npos; } @@ -315,7 +315,7 @@ Animate3DQuality Configuration::getAnimate3DQuality() const // // generic getters for properties // -const Value& Configuration::getValue(std::string_view key, const Value& defaultValue) const +const Value& Configuration::getValue(const std::string& key, const Value& defaultValue) const { auto iter = _valueDict.find(key); if (iter != _valueDict.cend()) @@ -324,15 +324,15 @@ const Value& Configuration::getValue(std::string_view key, const Value& defaultV return defaultValue; } -void Configuration::setValue(std::string_view key, const Value& value) +void Configuration::setValue(const std::string& key, const Value& value) { - hlookup::set_item(_valueDict, key, value); // _valueDict[key] = value; + _valueDict[key] = value; } // // load file // -void Configuration::loadConfigFile(std::string_view filename) +void Configuration::loadConfigFile(const std::string& filename) { ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(filename); CCASSERT(!dict.empty(), "cannot create dictionary"); @@ -360,14 +360,14 @@ void Configuration::loadConfigFile(std::string_view filename) if (!validMetadata) { - CCLOG("Invalid config format for file: %s", filename.data()); + CCLOG("Invalid config format for file: %s", filename.c_str()); return; } auto dataIter = dict.find("data"); if (dataIter == dict.cend() || dataIter->second.getType() != Value::Type::MAP) { - CCLOG("Expected 'data' dict, but not found. Config file: %s", filename.data()); + CCLOG("Expected 'data' dict, but not found. Config file: %s", filename.c_str()); return; } diff --git a/cocos/base/CCConfiguration.h b/cocos/base/CCConfiguration.h index aefcefbede..9761135884 100644 --- a/cocos/base/CCConfiguration.h +++ b/cocos/base/CCConfiguration.h @@ -205,7 +205,7 @@ public: * @param searchName A given search name. * @return Is true if an OpenGL is supported. */ - bool checkForGLExtension(std::string_view searchName) const; + bool checkForGLExtension(const std::string& searchName) const; /** Initialize method. * @@ -219,14 +219,14 @@ public: * @param defaultValue if not find the value, return the defaultValue. * @return */ - const Value& getValue(std::string_view key, const Value& defaultValue = Value::Null) const; + const Value& getValue(const std::string& key, const Value& defaultValue = Value::Null) const; /** Sets a new key/value pair in the configuration dictionary. * * @param key A given key. * @param value A given value. */ - void setValue(std::string_view key, const Value& value); + void setValue(const std::string& key, const Value& value); /** Returns the Configuration info. * @@ -243,7 +243,7 @@ public: * * @param filename Config file name. */ - void loadConfigFile(std::string_view filename); + void loadConfigFile(const std::string& filename); static const char* CONFIG_FILE_LOADED; diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 60c03d7aa6..c0953cb9e5 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -204,10 +204,9 @@ std::string& Console::Utility::trim(std::string& s) return Console::Utility::ltrim(Console::Utility::rtrim(s)); } -std::vector& Console::Utility::split(std::string_view s, char delim, std::vector& elems) +std::vector& Console::Utility::split(const std::string& s, char delim, std::vector& elems) { - std::stringstream ss; - ss << s; + std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { @@ -216,7 +215,7 @@ std::vector& Console::Utility::split(std::string_view s, char delim return elems; } -std::vector Console::Utility::split(std::string_view s, char delim) +std::vector Console::Utility::split(const std::string& s, char delim) { std::vector elems; Console::Utility::split(s, delim, elems); @@ -224,14 +223,13 @@ std::vector Console::Utility::split(std::string_view s, char delim) } // isFloat taken from http://stackoverflow.com/questions/447206/c-isfloat-function -bool Console::Utility::isFloat(std::string_view myString) +bool Console::Utility::isFloat(const std::string& myString) { - std::stringstream ss; - ss << myString; + std::istringstream iss(myString); float f; - ss >> std::noskipws >> f; // noskipws considers leading whitespace invalid + iss >> std::noskipws >> f; // noskipws considers leading whitespace invalid // Check the entire string was consumed and if either failbit or badbit is set - return ss.eof() && !ss.fail(); + return iss.eof() && !iss.fail(); } ssize_t Console::Utility::sendToConsole(int fd, const void* buffer, size_t length, int flags) @@ -277,12 +275,12 @@ void Console::Utility::sendPrompt(int fd) send(fd, prompt, strlen(prompt), 0); } -void Console::Utility::setPrompt(std::string_view prompt) +void Console::Utility::setPrompt(const std::string& prompt) { _prompt = prompt; } -std::string_view Console::Utility::getPrompt() +const std::string& Console::Utility::getPrompt() { return _prompt; } @@ -293,10 +291,11 @@ std::string_view Console::Utility::getPrompt() Console::Command::Command() : _callback(nullptr) {} -Console::Command::Command(std::string_view name, std::string_view help) : _name(name), _help(help), _callback(nullptr) +Console::Command::Command(const std::string& name, const std::string& help) + : _name(name), _help(help), _callback(nullptr) {} -Console::Command::Command(std::string_view name, std::string_view help, const Callback& callback) +Console::Command::Command(const std::string& name, const std::string& help, const Callback& callback) : _name(name), _help(help), _callback(callback) {} @@ -379,7 +378,7 @@ void Console::Command::addSubCommand(const Command& subCmd) _subCommands[subCmd._name] = cmd; } -const Console::Command* Console::Command::getSubCommand(std::string_view subCmdName) const +const Console::Command* Console::Command::getSubCommand(const std::string& subCmdName) const { auto it = _subCommands.find(subCmdName); if (it != _subCommands.end()) @@ -390,7 +389,7 @@ const Console::Command* Console::Command::getSubCommand(std::string_view subCmdN return nullptr; } -void Console::Command::delSubCommand(std::string_view subCmdName) +void Console::Command::delSubCommand(const std::string& subCmdName) { auto iter = _subCommands.find(subCmdName); if (iter != _subCommands.end()) @@ -400,7 +399,7 @@ void Console::Command::delSubCommand(std::string_view subCmdName) } } -void Console::Command::commandHelp(int fd, std::string_view /*args*/) +void Console::Command::commandHelp(int fd, const std::string& /*args*/) { if (!_help.empty()) { @@ -413,7 +412,7 @@ void Console::Command::commandHelp(int fd, std::string_view /*args*/) } } -void Console::Command::commandGeneric(int fd, std::string_view args) +void Console::Command::commandGeneric(int fd, const std::string& args) { // The first argument (including the empty) std::string key(args); @@ -622,10 +621,10 @@ void Console::addCommand(const Command& cmd) delete iter->second; _commands.erase(iter); } - _commands.emplace(cmd.getName(), newCommand); // _commands[cmd.getName()] = newCommand; + _commands[cmd.getName()] = newCommand; } -void Console::addSubCommand(std::string_view cmdName, const Command& subCmd) +void Console::addSubCommand(const std::string& cmdName, const Command& subCmd) { auto it = _commands.find(cmdName); if (it != _commands.end()) @@ -640,7 +639,7 @@ void Console::addSubCommand(Command& cmd, const Command& subCmd) cmd.addSubCommand(subCmd); } -const Console::Command* Console::getCommand(std::string_view cmdName) +const Console::Command* Console::getCommand(const std::string& cmdName) { auto it = _commands.find(cmdName); if (it != _commands.end()) @@ -651,7 +650,7 @@ const Console::Command* Console::getCommand(std::string_view cmdName) return nullptr; } -const Console::Command* Console::getSubCommand(std::string_view cmdName, std::string_view subCmdName) +const Console::Command* Console::getSubCommand(const std::string& cmdName, const std::string& subCmdName) { auto it = _commands.find(cmdName); if (it != _commands.end()) @@ -662,12 +661,12 @@ const Console::Command* Console::getSubCommand(std::string_view cmdName, std::st return nullptr; } -const Console::Command* Console::getSubCommand(const Command& cmd, std::string_view subCmdName) +const Console::Command* Console::getSubCommand(const Command& cmd, const std::string& subCmdName) { return cmd.getSubCommand(subCmdName); } -void Console::delCommand(std::string_view cmdName) +void Console::delCommand(const std::string& cmdName) { auto it = _commands.find(cmdName); if (it != _commands.end()) @@ -677,7 +676,7 @@ void Console::delCommand(std::string_view cmdName) } } -void Console::delSubCommand(std::string_view cmdName, std::string_view subCmdName) +void Console::delSubCommand(const std::string& cmdName, const std::string& subCmdName) { auto it = _commands.find(cmdName); if (it != _commands.end()) @@ -687,7 +686,7 @@ void Console::delSubCommand(std::string_view cmdName, std::string_view subCmdNam } } -void Console::delSubCommand(Command& cmd, std::string_view subCmdName) +void Console::delSubCommand(Command& cmd, const std::string& subCmdName) { cmd.delSubCommand(subCmdName); } @@ -702,7 +701,7 @@ void Console::log(const char* buf) } } -void Console::setBindAddress(std::string_view address) +void Console::setBindAddress(const std::string& address) { _bindAddress = address; } @@ -974,7 +973,7 @@ bool Console::parseCommand(socket_native_type fd) return true; } -void Console::performCommand(socket_native_type fd, std::string_view command) +void Console::performCommand(socket_native_type fd, const std::string& command) { std::vector args = Console::Utility::split(command, ' '); if (args.empty()) @@ -999,7 +998,7 @@ void Console::performCommand(socket_native_type fd, std::string_view command) } else { - throw std::runtime_error(std::string{"Unknown command "}.append(command).append(". Type 'help' for options\n")); + throw std::runtime_error("Unknown command " + command + ". Type 'help' for options\n"); } } @@ -1163,7 +1162,7 @@ void Console::createCommandVersion() // commands // -void Console::commandAllocator(socket_native_type fd, std::string_view /*args*/) +void Console::commandAllocator(socket_native_type fd, const std::string& /*args*/) { #if CC_ENABLE_ALLOCATOR_DIAGNOSTICS auto info = allocator::AllocatorDiagnostics::instance()->diagnostics(); @@ -1174,7 +1173,7 @@ void Console::commandAllocator(socket_native_type fd, std::string_view /*args*/) #endif } -void Console::commandConfig(socket_native_type fd, std::string_view /*args*/) +void Console::commandConfig(socket_native_type fd, const std::string& /*args*/) { Scheduler* sched = Director::getInstance()->getScheduler(); sched->performFunctionInCocosThread([=]() { @@ -1183,49 +1182,49 @@ void Console::commandConfig(socket_native_type fd, std::string_view /*args*/) }); } -void Console::commandDebugMsg(socket_native_type fd, std::string_view /*args*/) +void Console::commandDebugMsg(socket_native_type fd, const std::string& /*args*/) { Console::Utility::mydprintf(fd, "Debug message is: %s\n", _sendDebugStrings ? "on" : "off"); } -void Console::commandDebugMsgSubCommandOnOff(socket_native_type /*fd*/, std::string_view args) +void Console::commandDebugMsgSubCommandOnOff(socket_native_type /*fd*/, const std::string& args) { _sendDebugStrings = (args.compare("on") == 0); } -void Console::commandDirectorSubCommandPause(socket_native_type /*fd*/, std::string_view /*args*/) +void Console::commandDirectorSubCommandPause(socket_native_type /*fd*/, const std::string& /*args*/) { auto director = Director::getInstance(); Scheduler* sched = director->getScheduler(); sched->performFunctionInCocosThread([]() { Director::getInstance()->pause(); }); } -void Console::commandDirectorSubCommandResume(socket_native_type /*fd*/, std::string_view /*args*/) +void Console::commandDirectorSubCommandResume(socket_native_type /*fd*/, const std::string& /*args*/) { auto director = Director::getInstance(); director->resume(); } -void Console::commandDirectorSubCommandStop(socket_native_type /*fd*/, std::string_view /*args*/) +void Console::commandDirectorSubCommandStop(socket_native_type /*fd*/, const std::string& /*args*/) { auto director = Director::getInstance(); Scheduler* sched = director->getScheduler(); sched->performFunctionInCocosThread([]() { Director::getInstance()->stopAnimation(); }); } -void Console::commandDirectorSubCommandStart(socket_native_type /*fd*/, std::string_view /*args*/) +void Console::commandDirectorSubCommandStart(socket_native_type /*fd*/, const std::string& /*args*/) { auto director = Director::getInstance(); director->startAnimation(); } -void Console::commandDirectorSubCommandEnd(socket_native_type /*fd*/, std::string_view /*args*/) +void Console::commandDirectorSubCommandEnd(socket_native_type /*fd*/, const std::string& /*args*/) { auto director = Director::getInstance(); director->end(); } -void Console::commandExit(socket_native_type fd, std::string_view /*args*/) +void Console::commandExit(socket_native_type fd, const std::string& /*args*/) { FD_CLR(fd, &_read_set); _fds.erase(std::remove(_fds.begin(), _fds.end(), fd), _fds.end()); @@ -1236,23 +1235,23 @@ void Console::commandExit(socket_native_type fd, std::string_view /*args*/) #endif } -void Console::commandFileUtils(socket_native_type fd, std::string_view /*args*/) +void Console::commandFileUtils(socket_native_type fd, const std::string& /*args*/) { Scheduler* sched = Director::getInstance()->getScheduler(); sched->performFunctionInCocosThread(std::bind(&Console::printFileUtils, this, fd)); } -void Console::commandFileUtilsSubCommandFlush(socket_native_type /*fd*/, std::string_view /*args*/) +void Console::commandFileUtilsSubCommandFlush(socket_native_type /*fd*/, const std::string& /*args*/) { FileUtils::getInstance()->purgeCachedEntries(); } -void Console::commandFps(socket_native_type fd, std::string_view /*args*/) +void Console::commandFps(socket_native_type fd, const std::string& /*args*/) { Console::Utility::mydprintf(fd, "FPS is: %s\n", Director::getInstance()->isDisplayStats() ? "on" : "off"); } -void Console::commandFpsSubCommandOnOff(socket_native_type /*fd*/, std::string_view args) +void Console::commandFpsSubCommandOnOff(socket_native_type /*fd*/, const std::string& args) { bool state = (args.compare("on") == 0); Director* dir = Director::getInstance(); @@ -1260,12 +1259,12 @@ void Console::commandFpsSubCommandOnOff(socket_native_type /*fd*/, std::string_v sched->performFunctionInCocosThread(std::bind(&Director::setDisplayStats, dir, state)); } -void Console::commandHelp(socket_native_type fd, std::string_view /*args*/) +void Console::commandHelp(socket_native_type fd, const std::string& /*args*/) { sendHelp(fd, _commands, "\nAvailable commands:\n"); } -void Console::commandProjection(socket_native_type fd, std::string_view /*args*/) +void Console::commandProjection(socket_native_type fd, const std::string& /*args*/) { auto director = Director::getInstance(); char buf[20]; @@ -1289,26 +1288,25 @@ void Console::commandProjection(socket_native_type fd, std::string_view /*args*/ Console::Utility::mydprintf(fd, "Current projection: %s\n", buf); } -void Console::commandProjectionSubCommand2d(socket_native_type /*fd*/, std::string_view /*args*/) +void Console::commandProjectionSubCommand2d(socket_native_type /*fd*/, const std::string& /*args*/) { auto director = Director::getInstance(); Scheduler* sched = director->getScheduler(); sched->performFunctionInCocosThread([=]() { director->setProjection(Director::Projection::_2D); }); } -void Console::commandProjectionSubCommand3d(socket_native_type /*fd*/, std::string_view /*args*/) +void Console::commandProjectionSubCommand3d(socket_native_type /*fd*/, const std::string& /*args*/) { auto director = Director::getInstance(); Scheduler* sched = director->getScheduler(); sched->performFunctionInCocosThread([=]() { director->setProjection(Director::Projection::_3D); }); } -void Console::commandResolution(socket_native_type /*fd*/, std::string_view args) +void Console::commandResolution(socket_native_type /*fd*/, const std::string& args) { int policy; float width, height; - std::stringstream stream; - stream << args; + std::istringstream stream(args); stream >> width >> height >> policy; Scheduler* sched = Director::getInstance()->getScheduler(); @@ -1318,7 +1316,7 @@ void Console::commandResolution(socket_native_type /*fd*/, std::string_view args }); } -void Console::commandResolutionSubCommandEmpty(socket_native_type fd, std::string_view /*args*/) +void Console::commandResolutionSubCommandEmpty(socket_native_type fd, const std::string& /*args*/) { auto director = Director::getInstance(); Vec2 points = director->getWinSize(); @@ -1342,13 +1340,13 @@ void Console::commandResolutionSubCommandEmpty(socket_native_type fd, std::strin (int)visibleRect.origin.y, (int)visibleRect.size.width, (int)visibleRect.size.height); } -void Console::commandSceneGraph(socket_native_type fd, std::string_view /*args*/) +void Console::commandSceneGraph(socket_native_type fd, const std::string& /*args*/) { Scheduler* sched = Director::getInstance()->getScheduler(); sched->performFunctionInCocosThread(std::bind(&Console::printSceneGraphBoot, this, fd)); } -void Console::commandTextures(socket_native_type fd, std::string_view /*args*/) +void Console::commandTextures(socket_native_type fd, const std::string& /*args*/) { Scheduler* sched = Director::getInstance()->getScheduler(); sched->performFunctionInCocosThread([=]() { @@ -1358,13 +1356,13 @@ void Console::commandTextures(socket_native_type fd, std::string_view /*args*/) }); } -void Console::commandTexturesSubCommandFlush(socket_native_type /*fd*/, std::string_view /*args*/) +void Console::commandTexturesSubCommandFlush(socket_native_type /*fd*/, const std::string& /*args*/) { Scheduler* sched = Director::getInstance()->getScheduler(); sched->performFunctionInCocosThread([]() { Director::getInstance()->getTextureCache()->removeAllTextures(); }); } -void Console::commandTouchSubCommandTap(socket_native_type fd, std::string_view args) +void Console::commandTouchSubCommandTap(socket_native_type fd, const std::string& args) { auto argv = Console::Utility::split(args, ' '); @@ -1389,7 +1387,7 @@ void Console::commandTouchSubCommandTap(socket_native_type fd, std::string_view } } -void Console::commandTouchSubCommandSwipe(socket_native_type fd, std::string_view args) +void Console::commandTouchSubCommandSwipe(socket_native_type fd, const std::string& args) { auto argv = Console::Utility::split(args, ' '); @@ -1560,7 +1558,7 @@ void Console::commandUpload(socket_native_type fd) } } -void Console::commandVersion(socket_native_type fd, std::string_view /*args*/) +void Console::commandVersion(socket_native_type fd, const std::string& /*args*/) { Console::Utility::mydprintf(fd, "%s\n", adxeVersion()); } @@ -1620,7 +1618,9 @@ void Console::printFileUtils(socket_native_type fd) Console::Utility::sendPrompt(fd); } -void Console::sendHelp(socket_native_type fd, const hlookup::string_map& commands, const char* msg) +void Console::sendHelp(socket_native_type fd, + const std::unordered_map& commands, + const char* msg) { Console::Utility::sendToConsole(fd, msg, strlen(msg)); for (auto& it : commands) @@ -1629,14 +1629,14 @@ void Console::sendHelp(socket_native_type fd, const hlookup::string_mapgetHelp().empty()) continue; - Console::Utility::mydprintf(fd, "\t%s", command->getName().data()); - ssize_t tabs = command->getName().length() / 8; + Console::Utility::mydprintf(fd, "\t%s", command->getName().c_str()); + ssize_t tabs = strlen(command->getName().c_str()) / 8; tabs = 3 - tabs; for (int j = 0; j < tabs; j++) { Console::Utility::mydprintf(fd, "\t"); } - Console::Utility::mydprintf(fd, "%s\n", command->getHelp().data()); + Console::Utility::mydprintf(fd, "%s\n", command->getHelp().c_str()); } } diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h index 07882085c6..20f5aa54f4 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -82,11 +82,11 @@ public: static std::string& trim(std::string& s); // split - static std::vector& split(std::string_view s, char delim, std::vector& elems); - static std::vector split(std::string_view s, char delim); + static std::vector& split(const std::string& s, char delim, std::vector& elems); + static std::vector split(const std::string& s, char delim); /** Checks myString is a floating-point type. */ - static bool isFloat(std::string_view myString); + static bool isFloat(const std::string& myString); /** send a message to console */ static ssize_t sendToConsole(int fd, const void* buffer, size_t length, int flags = 0); @@ -98,10 +98,10 @@ public: static void sendPrompt(int fd); /** set a new string for the prompt. */ - static void setPrompt(std::string_view prompt); + static void setPrompt(const std::string& prompt); /** get the prompt string. */ - static std::string_view getPrompt(); + static const std::string& getPrompt(); private: static std::string _prompt; /*!< prompt */ @@ -111,11 +111,11 @@ public: class CC_DLL Command { public: - using Callback = std::function; + using Callback = std::function; /** Constructor */ Command(); - Command(std::string_view name, std::string_view help); - Command(std::string_view name, std::string_view help, const Callback& callback); + Command(const std::string& name, const std::string& help); + Command(const std::string& name, const std::string& help, const Callback& callback); /** Copy constructor */ Command(const Command& o); @@ -139,29 +139,29 @@ public: void addSubCommand(const Command& subCmd); /** get sub command */ - const Command* getSubCommand(std::string_view subCmdName) const; + const Command* getSubCommand(const std::string& subCmdName) const; /** delete sub command */ - void delSubCommand(std::string_view subCmdName); + void delSubCommand(const std::string& subCmdName); /** help command handler */ - void commandHelp(int fd, std::string_view args); + void commandHelp(int fd, const std::string& args); /** generic command handler */ - void commandGeneric(int fd, std::string_view args); + void commandGeneric(int fd, const std::string& args); /** Gets the name of the current command */ - std::string_view getName() const { return _name; } + const std::string& getName() const { return _name; } /** Gets the help information of the current command */ - std::string_view getHelp() const { return _help; } + const std::string& getHelp() const { return _help; } private: std::string _name; std::string _help; Callback _callback; - hlookup::string_map _subCommands; + std::unordered_map _subCommands; }; /** Constructor */ @@ -181,18 +181,18 @@ public: /** add custom command */ void addCommand(const Command& cmd); - void addSubCommand(std::string_view cmdName, const Command& subCmd); + void addSubCommand(const std::string& cmdName, const Command& subCmd); void addSubCommand(Command& cmd, const Command& subCmd); /** get custom command */ - const Command* getCommand(std::string_view cmdName); - const Command* getSubCommand(std::string_view cmdName, std::string_view subCmdName); - const Command* getSubCommand(const Command& cmd, std::string_view subCmdName); + const Command* getCommand(const std::string& cmdName); + const Command* getSubCommand(const std::string& cmdName, const std::string& subCmdName); + const Command* getSubCommand(const Command& cmd, const std::string& subCmdName); /** delete custom command */ - void delCommand(std::string_view cmdName); - void delSubCommand(std::string_view cmdName, std::string_view subCmdName); - void delSubCommand(Command& cmd, std::string_view subCmdName); + void delCommand(const std::string& cmdName); + void delSubCommand(const std::string& cmdName, const std::string& subCmdName); + void delSubCommand(Command& cmd, const std::string& subCmdName); /** log something in the console */ void log(const char* buf); @@ -202,7 +202,7 @@ public: * * @address : 127.0.0.1 */ - void setBindAddress(std::string_view address); + void setBindAddress(const std::string& address); /** Checks whether the server for console is bound with ipv6 address */ bool isIpv6Server() const; @@ -218,7 +218,7 @@ protected: ssize_t readline(socket_native_type fd, char* buf, size_t maxlen); ssize_t readBytes(socket_native_type fd, char* buffer, size_t maxlen, bool* more); bool parseCommand(socket_native_type fd); - void performCommand(socket_native_type fd, std::string_view command); + void performCommand(socket_native_type fd, const std::string& command); void addClient(); @@ -240,33 +240,33 @@ protected: void createCommandVersion(); // Add commands here - void commandAllocator(socket_native_type fd, std::string_view args); - void commandConfig(socket_native_type fd, std::string_view args); - void commandDebugMsg(socket_native_type fd, std::string_view args); - void commandDebugMsgSubCommandOnOff(socket_native_type fd, std::string_view args); - void commandDirectorSubCommandPause(socket_native_type fd, std::string_view args); - void commandDirectorSubCommandResume(socket_native_type fd, std::string_view args); - void commandDirectorSubCommandStop(socket_native_type fd, std::string_view args); - void commandDirectorSubCommandStart(socket_native_type fd, std::string_view args); - void commandDirectorSubCommandEnd(socket_native_type fd, std::string_view args); - void commandExit(socket_native_type fd, std::string_view args); - void commandFileUtils(socket_native_type fd, std::string_view args); - void commandFileUtilsSubCommandFlush(socket_native_type fd, std::string_view args); - void commandFps(socket_native_type fd, std::string_view args); - void commandFpsSubCommandOnOff(socket_native_type fd, std::string_view args); - void commandHelp(socket_native_type fd, std::string_view args); - void commandProjection(socket_native_type fd, std::string_view args); - void commandProjectionSubCommand2d(socket_native_type fd, std::string_view args); - void commandProjectionSubCommand3d(socket_native_type fd, std::string_view args); - void commandResolution(socket_native_type fd, std::string_view args); - void commandResolutionSubCommandEmpty(socket_native_type fd, std::string_view args); - void commandSceneGraph(socket_native_type fd, std::string_view args); - void commandTextures(socket_native_type fd, std::string_view args); - void commandTexturesSubCommandFlush(socket_native_type fd, std::string_view args); - void commandTouchSubCommandTap(socket_native_type fd, std::string_view args); - void commandTouchSubCommandSwipe(socket_native_type fd, std::string_view args); + void commandAllocator(socket_native_type fd, const std::string& args); + void commandConfig(socket_native_type fd, const std::string& args); + void commandDebugMsg(socket_native_type fd, const std::string& args); + void commandDebugMsgSubCommandOnOff(socket_native_type fd, const std::string& args); + void commandDirectorSubCommandPause(socket_native_type fd, const std::string& args); + void commandDirectorSubCommandResume(socket_native_type fd, const std::string& args); + void commandDirectorSubCommandStop(socket_native_type fd, const std::string& args); + void commandDirectorSubCommandStart(socket_native_type fd, const std::string& args); + void commandDirectorSubCommandEnd(socket_native_type fd, const std::string& args); + void commandExit(socket_native_type fd, const std::string& args); + void commandFileUtils(socket_native_type fd, const std::string& args); + void commandFileUtilsSubCommandFlush(socket_native_type fd, const std::string& args); + void commandFps(socket_native_type fd, const std::string& args); + void commandFpsSubCommandOnOff(socket_native_type fd, const std::string& args); + void commandHelp(socket_native_type fd, const std::string& args); + void commandProjection(socket_native_type fd, const std::string& args); + void commandProjectionSubCommand2d(socket_native_type fd, const std::string& args); + void commandProjectionSubCommand3d(socket_native_type fd, const std::string& args); + void commandResolution(socket_native_type fd, const std::string& args); + void commandResolutionSubCommandEmpty(socket_native_type fd, const std::string& args); + void commandSceneGraph(socket_native_type fd, const std::string& args); + void commandTextures(socket_native_type fd, const std::string& args); + void commandTexturesSubCommandFlush(socket_native_type fd, const std::string& args); + void commandTouchSubCommandTap(socket_native_type fd, const std::string& args); + void commandTouchSubCommandSwipe(socket_native_type fd, const std::string& args); void commandUpload(socket_native_type fd); - void commandVersion(socket_native_type fd, std::string_view args); + void commandVersion(socket_native_type fd, const std::string& args); // file descriptor: socket, console, etc. socket_native_type _listenfd; socket_native_type _maxfd; @@ -279,7 +279,7 @@ protected: bool _endThread; bool _isIpv6Server; - hlookup::string_map _commands; + std::unordered_map _commands; // strings generated by cocos2d sent to the remote console bool _sendDebugStrings; @@ -299,7 +299,9 @@ private: void printFileUtils(socket_native_type fd); /** send help message to console */ - static void sendHelp(socket_native_type fd, const hlookup::string_map& commands, const char* msg); + static void sendHelp(socket_native_type fd, + const std::unordered_map& commands, + const char* msg); }; NS_CC_END diff --git a/cocos/base/CCController-android.cpp b/cocos/base/CCController-android.cpp index d7084d06cc..564735b5c9 100644 --- a/cocos/base/CCController-android.cpp +++ b/cocos/base/CCController-android.cpp @@ -40,7 +40,7 @@ class ControllerImpl public: ControllerImpl(Controller* controller) : _controller(controller) {} - static std::vector::iterator findController(std::string_view deviceName, int deviceId) + static std::vector::iterator findController(const std::string& deviceName, int deviceId) { auto iter = std::find_if( Controller::s_allController.begin(), Controller::s_allController.end(), [&](Controller* controller) { @@ -50,10 +50,10 @@ public: return iter; } - static void onConnected(std::string_view deviceName, int deviceId) + static void onConnected(const std::string& deviceName, int deviceId) { // Check whether the controller is already connected. - CCLOG("onConnected %s,%d", deviceName.data(), deviceId); + CCLOG("onConnected %s,%d", deviceName.c_str(), deviceId); auto iter = findController(deviceName, deviceId); if (iter != Controller::s_allController.end()) @@ -68,9 +68,9 @@ public: controller->onConnected(); } - static void onDisconnected(std::string_view deviceName, int deviceId) + static void onDisconnected(const std::string& deviceName, int deviceId) { - CCLOG("onDisconnected %s,%d", deviceName.data(), deviceId); + CCLOG("onDisconnected %s,%d", deviceName.c_str(), deviceId); auto iter = findController(deviceName, deviceId); if (iter == Controller::s_allController.end()) @@ -83,7 +83,7 @@ public: Controller::s_allController.erase(iter); } - static void onButtonEvent(std::string_view deviceName, + static void onButtonEvent(const std::string& deviceName, int deviceId, int keyCode, bool isPressed, @@ -101,7 +101,7 @@ public: (*iter)->onButtonEvent(keyCode, isPressed, value, isAnalog); } - static void onAxisEvent(std::string_view deviceName, int deviceId, int axisCode, float value, bool isAnalog) + static void onAxisEvent(const std::string& deviceName, int deviceId, int axisCode, float value, bool isAnalog) { auto iter = findController(deviceName, deviceId); if (iter == Controller::s_allController.end()) diff --git a/cocos/base/CCController-apple.mm b/cocos/base/CCController-apple.mm index 0140a148ff..349ab4188c 100644 --- a/cocos/base/CCController-apple.mm +++ b/cocos/base/CCController-apple.mm @@ -2,19 +2,19 @@ Copyright (c) 2014 cocos2d-x.org Copyright (c) 2014-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -28,35 +28,36 @@ #include "platform/CCPlatformConfig.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -# include "base/ccMacros.h" -# include "base/CCEventDispatcher.h" -# include "base/CCEventController.h" -# include "base/CCEventListenerController.h" -# include "base/CCDirector.h" -# include "2d/CCLabel.h" +#include "base/ccMacros.h" +#include "base/CCEventDispatcher.h" +#include "base/CCEventController.h" +#include "base/CCEventListenerController.h" +#include "base/CCDirector.h" +#include "2d/CCLabel.h" -# import +#import typedef void (^GCControllerConnectionBlock)(GCController* controller); typedef void (^GCControllerDisconnectionBlock)(GCController* controller); -@interface GCControllerConnectionEventHandler : NSObject { +@interface GCControllerConnectionEventHandler : NSObject +{ } -@property(copy) GCControllerConnectionBlock _connectionBlock; -@property(copy) GCControllerDisconnectionBlock _disconnectionBlock; +@property (copy) GCControllerConnectionBlock _connectionBlock; +@property (copy) GCControllerDisconnectionBlock _disconnectionBlock; -+ (GCControllerConnectionEventHandler*)getInstance; -+ (void)destroyInstance; ++(GCControllerConnectionEventHandler*) getInstance; ++(void) destroyInstance; @end @implementation GCControllerConnectionEventHandler + static GCControllerConnectionEventHandler* __instance = nil; -+ (GCControllerConnectionEventHandler*)getInstance -{ - ++(GCControllerConnectionEventHandler*) getInstance { + if (__instance == nil) { __instance = [[GCControllerConnectionEventHandler alloc] init]; @@ -64,8 +65,7 @@ static GCControllerConnectionEventHandler* __instance = nil; return __instance; } -+ (void)destroyInstance -{ ++(void) destroyInstance { if (__instance) { [__instance release]; @@ -73,44 +73,33 @@ static GCControllerConnectionEventHandler* __instance = nil; } } -- (void)observerConnection:(GCControllerConnectionBlock)connectBlock - disconnection:(GCControllerDisconnectionBlock)disconnectBlock -{ - self._connectionBlock = connectBlock; +-(void) observerConnection: (GCControllerConnectionBlock) connectBlock disconnection: (GCControllerDisconnectionBlock) disconnectBlock { + self._connectionBlock = connectBlock; self._disconnectionBlock = disconnectBlock; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(onControllerConnected:) - name:GCControllerDidConnectNotification - object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(onControllerDisconnected:) - name:GCControllerDidDisconnectNotification - object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onControllerConnected:) name:GCControllerDidConnectNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onControllerDisconnected:) name:GCControllerDidDisconnectNotification object:nil]; } -- (void)dealloc -{ +-(void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; // Have to reset 'copy' property to nil value to avoid memory leak. - self._connectionBlock = nil; + self._connectionBlock = nil; self._disconnectionBlock = nil; [super dealloc]; } -- (void)onControllerConnected:(NSNotification*)connectedNotification -{ - GCController* controller = (GCController*)[connectedNotification object]; - +-(void) onControllerConnected :(NSNotification *)connectedNotification { + GCController *controller =(GCController *)[connectedNotification object]; + self._connectionBlock(controller); } -- (void)onControllerDisconnected:(NSNotification*)connectedNotification -{ - - GCController* controller = (GCController*)[connectedNotification object]; +-(void) onControllerDisconnected :(NSNotification *)connectedNotification { + + GCController *controller =(GCController *)[connectedNotification object]; self._disconnectionBlock(controller); } @@ -121,64 +110,67 @@ NS_CC_BEGIN class ControllerImpl { public: - ControllerImpl(Controller* controller) : _controller(controller), _gcController(nil) {} - + ControllerImpl(Controller* controller) + : _controller(controller) + , _gcController(nil) + { + + } + Controller* _controller; GCController* _gcController; }; void Controller::startDiscoveryController() { - if (NSClassFromString(@"GCController") == nil) - { + if (NSClassFromString(@"GCController") == nil) { return; } - [GCController startWirelessControllerDiscoveryWithCompletionHandler:nil]; - - [[GCControllerConnectionEventHandler getInstance] - observerConnection:^(GCController* gcController) { - auto controller = new Controller(); - controller->_impl->_gcController = gcController; - controller->_deviceName = [gcController.vendorName UTF8String]; - - s_allController.push_back(controller); - - controller->registerListeners(); - controller->getDeviceName(); - - controller->onConnected(); + [GCController startWirelessControllerDiscoveryWithCompletionHandler: nil]; + + [[GCControllerConnectionEventHandler getInstance] observerConnection: ^(GCController* gcController) { + + auto controller = new Controller(); + controller->_impl->_gcController = gcController; + controller->_deviceName = [gcController.vendorName UTF8String]; + + s_allController.push_back(controller); + + controller->registerListeners(); + controller->getDeviceName(); + + controller->onConnected(); + + } disconnection: ^(GCController* gcController) { + auto iter = std::find_if(s_allController.begin(), s_allController.end(), [gcController](Controller* c){ return c->_impl->_gcController == gcController; }); + + if(iter == s_allController.end()) + { + log("disconnect:Could not find the controller"); + return; } - disconnection:^(GCController* gcController) { - auto iter = std::find_if(s_allController.begin(), s_allController.end(), - [gcController](Controller* c) { return c->_impl->_gcController == gcController; }); - - if (iter == s_allController.end()) - { - log("disconnect:Could not find the controller"); - return; - } - - (*iter)->onDisconnected(); - s_allController.erase(iter); - }]; + + (*iter)->onDisconnected(); + s_allController.erase(iter); + + }]; } void Controller::stopDiscoveryController() { - if (NSClassFromString(@"GCController") == nil) - { + if (NSClassFromString(@"GCController") == nil) { return; } [GCController stopWirelessControllerDiscovery]; } Controller::Controller() - : _deviceId(0) - , _controllerTag(TAG_UNSET) - , _impl(new ControllerImpl(this)) - , _connectEvent(nullptr) - , _keyEvent(nullptr) - , _axisEvent(nullptr) +: _deviceId(0) +, _controllerTag(TAG_UNSET) +, _impl(new ControllerImpl(this)) +, _connectEvent(nullptr) +, _keyEvent(nullptr) +, _axisEvent(nullptr) { init(); } @@ -186,7 +178,7 @@ Controller::Controller() Controller::~Controller() { delete _impl; - + delete _connectEvent; delete _keyEvent; delete _axisEvent; @@ -196,184 +188,164 @@ void Controller::registerListeners() { if (_impl->_gcController.extendedGamepad != nil) { - _impl->_gcController.extendedGamepad.dpad.up.valueChangedHandler = - ^(GCControllerButtonInput* button, float value, BOOL pressed) { - onButtonEvent(Key::BUTTON_DPAD_UP, pressed, value, button.isAnalog); - }; - - _impl->_gcController.extendedGamepad.dpad.down.valueChangedHandler = - ^(GCControllerButtonInput* button, float value, BOOL pressed) { - onButtonEvent(Key::BUTTON_DPAD_DOWN, pressed, value, button.isAnalog); - }; - - _impl->_gcController.extendedGamepad.dpad.left.valueChangedHandler = - ^(GCControllerButtonInput* button, float value, BOOL pressed) { - onButtonEvent(Key::BUTTON_DPAD_LEFT, pressed, value, button.isAnalog); - }; - - _impl->_gcController.extendedGamepad.dpad.right.valueChangedHandler = - ^(GCControllerButtonInput* button, float value, BOOL pressed) { - onButtonEvent(Key::BUTTON_DPAD_RIGHT, pressed, value, button.isAnalog); - }; - - _impl->_gcController.extendedGamepad.leftThumbstick.xAxis.valueChangedHandler = - ^(GCControllerAxisInput* axis, float value) { - onAxisEvent(Key::JOYSTICK_LEFT_X, value, axis.isAnalog); - }; - - _impl->_gcController.extendedGamepad.leftThumbstick.yAxis.valueChangedHandler = - ^(GCControllerAxisInput* axis, float value) { - onAxisEvent(Key::JOYSTICK_LEFT_Y, -value, axis.isAnalog); - }; - - _impl->_gcController.extendedGamepad.rightThumbstick.xAxis.valueChangedHandler = - ^(GCControllerAxisInput* axis, float value) { - onAxisEvent(Key::JOYSTICK_RIGHT_X, value, axis.isAnalog); - }; - - _impl->_gcController.extendedGamepad.rightThumbstick.yAxis.valueChangedHandler = - ^(GCControllerAxisInput* axis, float value) { - onAxisEvent(Key::JOYSTICK_RIGHT_Y, -value, axis.isAnalog); - }; - - _impl->_gcController.extendedGamepad.valueChangedHandler = ^(GCExtendedGamepad* gamepad, - GCControllerElement* element) { - if (element == gamepad.buttonA) - { - onButtonEvent(Key::BUTTON_A, gamepad.buttonA.isPressed, gamepad.buttonA.value, gamepad.buttonA.isAnalog); - } - else if (element == gamepad.buttonB) - { - onButtonEvent(Key::BUTTON_B, gamepad.buttonB.isPressed, gamepad.buttonB.value, gamepad.buttonB.isAnalog); - } - else if (element == gamepad.buttonX) - { - onButtonEvent(Key::BUTTON_X, gamepad.buttonX.isPressed, gamepad.buttonX.value, gamepad.buttonX.isAnalog); - } - else if (element == gamepad.buttonY) - { - onButtonEvent(Key::BUTTON_Y, gamepad.buttonY.isPressed, gamepad.buttonY.value, gamepad.buttonY.isAnalog); - } - else if (element == gamepad.leftShoulder) - { - onButtonEvent(Key::BUTTON_LEFT_SHOULDER, gamepad.leftShoulder.isPressed, gamepad.leftShoulder.value, - gamepad.leftShoulder.isAnalog); - } - else if (element == gamepad.rightShoulder) - { - onButtonEvent(Key::BUTTON_RIGHT_SHOULDER, gamepad.rightShoulder.isPressed, gamepad.rightShoulder.value, - gamepad.rightShoulder.isAnalog); - } - else if (element == gamepad.leftTrigger) - { - onAxisEvent(Key::AXIS_LEFT_TRIGGER, gamepad.leftTrigger.value, gamepad.leftTrigger.isAnalog); - } - else if (element == gamepad.rightTrigger) - { - onAxisEvent(Key::AXIS_RIGHT_TRIGGER, gamepad.rightTrigger.value, gamepad.rightTrigger.isAnalog); - } + _impl->_gcController.extendedGamepad.dpad.up.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ + onButtonEvent(Key::BUTTON_DPAD_UP, pressed, value, button.isAnalog); + }; + + _impl->_gcController.extendedGamepad.dpad.down.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ + onButtonEvent(Key::BUTTON_DPAD_DOWN, pressed, value, button.isAnalog); + }; + + _impl->_gcController.extendedGamepad.dpad.left.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ + onButtonEvent(Key::BUTTON_DPAD_LEFT, pressed, value, button.isAnalog); + }; + + _impl->_gcController.extendedGamepad.dpad.right.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ + onButtonEvent(Key::BUTTON_DPAD_RIGHT, pressed, value, button.isAnalog); + }; + + _impl->_gcController.extendedGamepad.leftThumbstick.xAxis.valueChangedHandler = ^(GCControllerAxisInput *axis, float value){ + onAxisEvent(Key::JOYSTICK_LEFT_X, value, axis.isAnalog); + }; + + _impl->_gcController.extendedGamepad.leftThumbstick.yAxis.valueChangedHandler = ^(GCControllerAxisInput *axis, float value){ + onAxisEvent(Key::JOYSTICK_LEFT_Y, -value, axis.isAnalog); + }; + + _impl->_gcController.extendedGamepad.rightThumbstick.xAxis.valueChangedHandler = ^(GCControllerAxisInput *axis, float value){ + onAxisEvent(Key::JOYSTICK_RIGHT_X, value, axis.isAnalog); + }; + + _impl->_gcController.extendedGamepad.rightThumbstick.yAxis.valueChangedHandler = ^(GCControllerAxisInput *axis, float value){ + onAxisEvent(Key::JOYSTICK_RIGHT_Y, -value, axis.isAnalog); + }; + + _impl->_gcController.extendedGamepad.valueChangedHandler = ^(GCExtendedGamepad *gamepad, GCControllerElement *element){ + if (element == gamepad.buttonA) + { + onButtonEvent(Key::BUTTON_A, gamepad.buttonA.isPressed, gamepad.buttonA.value, gamepad.buttonA.isAnalog); + } + else if (element == gamepad.buttonB) + { + onButtonEvent(Key::BUTTON_B, gamepad.buttonB.isPressed, gamepad.buttonB.value, gamepad.buttonB.isAnalog); + } + else if (element == gamepad.buttonX) + { + onButtonEvent(Key::BUTTON_X, gamepad.buttonX.isPressed, gamepad.buttonX.value, gamepad.buttonX.isAnalog); + } + else if (element == gamepad.buttonY) + { + onButtonEvent(Key::BUTTON_Y, gamepad.buttonY.isPressed, gamepad.buttonY.value, gamepad.buttonY.isAnalog); + } + else if (element == gamepad.leftShoulder) + { + onButtonEvent(Key::BUTTON_LEFT_SHOULDER, gamepad.leftShoulder.isPressed, gamepad.leftShoulder.value, gamepad.leftShoulder.isAnalog); + } + else if (element == gamepad.rightShoulder) + { + onButtonEvent(Key::BUTTON_RIGHT_SHOULDER, gamepad.rightShoulder.isPressed, gamepad.rightShoulder.value, gamepad.rightShoulder.isAnalog); + } + else if (element == gamepad.leftTrigger) + { + onAxisEvent(Key::AXIS_LEFT_TRIGGER, gamepad.leftTrigger.value, gamepad.leftTrigger.isAnalog); + } + else if (element == gamepad.rightTrigger) + { + onAxisEvent(Key::AXIS_RIGHT_TRIGGER, gamepad.rightTrigger.value, gamepad.rightTrigger.isAnalog); + } }; } else if (_impl->_gcController.gamepad != nil) { - _impl->_gcController.gamepad.dpad.up.valueChangedHandler = - ^(GCControllerButtonInput* button, float value, BOOL pressed) { - onButtonEvent(Key::BUTTON_DPAD_UP, pressed, value, button.isAnalog); - }; - - _impl->_gcController.gamepad.dpad.down.valueChangedHandler = - ^(GCControllerButtonInput* button, float value, BOOL pressed) { - onButtonEvent(Key::BUTTON_DPAD_DOWN, pressed, value, button.isAnalog); - }; - - _impl->_gcController.gamepad.dpad.left.valueChangedHandler = - ^(GCControllerButtonInput* button, float value, BOOL pressed) { - onButtonEvent(Key::BUTTON_DPAD_LEFT, pressed, value, button.isAnalog); - }; - - _impl->_gcController.gamepad.dpad.right.valueChangedHandler = - ^(GCControllerButtonInput* button, float value, BOOL pressed) { - onButtonEvent(Key::BUTTON_DPAD_RIGHT, pressed, value, button.isAnalog); - }; - - _impl->_gcController.gamepad.valueChangedHandler = ^(GCGamepad* gamepad, GCControllerElement* element) { - if (element == gamepad.buttonA) - { - onButtonEvent(Key::BUTTON_A, gamepad.buttonA.isPressed, gamepad.buttonA.value, gamepad.buttonA.isAnalog); - } - else if (element == gamepad.buttonB) - { - onButtonEvent(Key::BUTTON_B, gamepad.buttonB.isPressed, gamepad.buttonB.value, gamepad.buttonB.isAnalog); - } - else if (element == gamepad.buttonX) - { - onButtonEvent(Key::BUTTON_X, gamepad.buttonX.isPressed, gamepad.buttonX.value, gamepad.buttonX.isAnalog); - } - else if (element == gamepad.buttonY) - { - onButtonEvent(Key::BUTTON_Y, gamepad.buttonY.isPressed, gamepad.buttonY.value, gamepad.buttonY.isAnalog); - } - else if (element == gamepad.leftShoulder) - { - onButtonEvent(Key::BUTTON_LEFT_SHOULDER, gamepad.leftShoulder.isPressed, gamepad.leftShoulder.value, - gamepad.leftShoulder.isAnalog); - } - else if (element == gamepad.rightShoulder) - { - onButtonEvent(Key::BUTTON_RIGHT_SHOULDER, gamepad.rightShoulder.isPressed, gamepad.rightShoulder.value, - gamepad.rightShoulder.isAnalog); - } + _impl->_gcController.gamepad.dpad.up.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ + onButtonEvent(Key::BUTTON_DPAD_UP, pressed, value, button.isAnalog); + }; + + _impl->_gcController.gamepad.dpad.down.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ + onButtonEvent(Key::BUTTON_DPAD_DOWN, pressed, value, button.isAnalog); + }; + + _impl->_gcController.gamepad.dpad.left.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ + onButtonEvent(Key::BUTTON_DPAD_LEFT, pressed, value, button.isAnalog); + }; + + _impl->_gcController.gamepad.dpad.right.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ + onButtonEvent(Key::BUTTON_DPAD_RIGHT, pressed, value, button.isAnalog); + }; + + _impl->_gcController.gamepad.valueChangedHandler = ^(GCGamepad *gamepad, GCControllerElement *element){ + + if (element == gamepad.buttonA) + { + onButtonEvent(Key::BUTTON_A, gamepad.buttonA.isPressed, gamepad.buttonA.value, gamepad.buttonA.isAnalog); + } + else if (element == gamepad.buttonB) + { + onButtonEvent(Key::BUTTON_B, gamepad.buttonB.isPressed, gamepad.buttonB.value, gamepad.buttonB.isAnalog); + } + else if (element == gamepad.buttonX) + { + onButtonEvent(Key::BUTTON_X, gamepad.buttonX.isPressed, gamepad.buttonX.value, gamepad.buttonX.isAnalog); + } + else if (element == gamepad.buttonY) + { + onButtonEvent(Key::BUTTON_Y, gamepad.buttonY.isPressed, gamepad.buttonY.value, gamepad.buttonY.isAnalog); + } + else if (element == gamepad.leftShoulder) + { + onButtonEvent(Key::BUTTON_LEFT_SHOULDER, gamepad.leftShoulder.isPressed, gamepad.leftShoulder.value, gamepad.leftShoulder.isAnalog); + } + else if (element == gamepad.rightShoulder) + { + onButtonEvent(Key::BUTTON_RIGHT_SHOULDER, gamepad.rightShoulder.isPressed, gamepad.rightShoulder.value, gamepad.rightShoulder.isAnalog); + } }; } -# if defined(CC_TARGET_OS_TVOS) +#if defined(CC_TARGET_OS_TVOS) else if (_impl->_gcController.microGamepad != nil) { - _impl->_gcController.microGamepad.dpad.up.valueChangedHandler = - ^(GCControllerButtonInput* button, float value, BOOL pressed) { - onButtonEvent(Key::BUTTON_DPAD_UP, pressed, value, button.isAnalog); - }; - - _impl->_gcController.microGamepad.dpad.down.valueChangedHandler = - ^(GCControllerButtonInput* button, float value, BOOL pressed) { - onButtonEvent(Key::BUTTON_DPAD_DOWN, pressed, value, button.isAnalog); - }; - - _impl->_gcController.microGamepad.dpad.left.valueChangedHandler = - ^(GCControllerButtonInput* button, float value, BOOL pressed) { - onButtonEvent(Key::BUTTON_DPAD_LEFT, pressed, value, button.isAnalog); - }; - - _impl->_gcController.microGamepad.dpad.right.valueChangedHandler = - ^(GCControllerButtonInput* button, float value, BOOL pressed) { - onButtonEvent(Key::BUTTON_DPAD_RIGHT, pressed, value, button.isAnalog); - }; - - _impl->_gcController.microGamepad.valueChangedHandler = ^(GCMicroGamepad* gamepad, - GCControllerElement* element) { - if (element == gamepad.buttonA) - { - onButtonEvent(Key::BUTTON_A, gamepad.buttonA.isPressed, gamepad.buttonA.value, gamepad.buttonA.isAnalog); - } - else if (element == gamepad.buttonX) - { - onButtonEvent(Key::BUTTON_X, gamepad.buttonX.isPressed, gamepad.buttonX.value, gamepad.buttonX.isAnalog); - } + _impl->_gcController.microGamepad.dpad.up.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ + onButtonEvent(Key::BUTTON_DPAD_UP, pressed, value, button.isAnalog); + }; + + _impl->_gcController.microGamepad.dpad.down.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ + onButtonEvent(Key::BUTTON_DPAD_DOWN, pressed, value, button.isAnalog); + }; + + _impl->_gcController.microGamepad.dpad.left.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ + onButtonEvent(Key::BUTTON_DPAD_LEFT, pressed, value, button.isAnalog); + }; + + _impl->_gcController.microGamepad.dpad.right.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ + onButtonEvent(Key::BUTTON_DPAD_RIGHT, pressed, value, button.isAnalog); + }; + + _impl->_gcController.microGamepad.valueChangedHandler = ^(GCMicroGamepad *gamepad, GCControllerElement *element){ + + if (element == gamepad.buttonA) + { + onButtonEvent(Key::BUTTON_A, gamepad.buttonA.isPressed, gamepad.buttonA.value, gamepad.buttonA.isAnalog); + } + else if (element == gamepad.buttonX) + { + onButtonEvent(Key::BUTTON_X, gamepad.buttonX.isPressed, gamepad.buttonX.value, gamepad.buttonX.isAnalog); + } }; } -# endif - - _impl->_gcController.controllerPausedHandler = ^(GCController* gcCon) { - auto iter = std::find_if(s_allController.begin(), s_allController.end(), - [gcCon](Controller* c) { return c->_impl->_gcController == gcCon; }); - - if (iter == s_allController.end()) - { - log("Could not find the controller"); - return; - } - - onButtonEvent(Key::BUTTON_PAUSE, true, 1.0f, false); - onButtonEvent(Key::BUTTON_PAUSE, false, 0.0f, false); +#endif + + _impl->_gcController.controllerPausedHandler = ^(GCController* gcCon){ + + auto iter = std::find_if(s_allController.begin(), s_allController.end(), [gcCon](Controller* c){ return c->_impl->_gcController == gcCon; }); + + if(iter == s_allController.end()) + { + log("Could not find the controller"); + return; + } + + onButtonEvent(Key::BUTTON_PAUSE, true, 1.0f, false); + onButtonEvent(Key::BUTTON_PAUSE, false, 0.0f, false); }; } @@ -382,8 +354,10 @@ bool Controller::isConnected() const return _impl->_gcController.isAttachedToDevice == YES; } -void Controller::receiveExternalKeyEvent(int externalKeyCode, bool receive) {} +void Controller::receiveExternalKeyEvent(int externalKeyCode,bool receive) +{ +} NS_CC_END -#endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) +#endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) diff --git a/cocos/base/CCController-linux-win32.cpp b/cocos/base/CCController-linux-win32.cpp index f99e23b641..cca3d2ee2c 100644 --- a/cocos/base/CCController-linux-win32.cpp +++ b/cocos/base/CCController-linux-win32.cpp @@ -4203,7 +4203,7 @@ public: return iter; } - static void onConnected(std::string_view deviceName, int deviceId) + static void onConnected(const std::string& deviceName, int deviceId) { // Check whether the controller is already registered auto iter = findController(deviceId); @@ -4222,7 +4222,7 @@ public: if (deviceName.compare(it.first) == 0) { // Found controller profile. Attach it to the controller: - CCLOG("ControllerImpl: Found input profile for controller: %s", deviceName.data()); + CCLOG("ControllerImpl: Found input profile for controller: %s", deviceName.c_str()); controller->_buttonInputMap = it.second.first; controller->_axisInputMap = it.second.second; @@ -4241,7 +4241,7 @@ public: CCLOG( "ControllerImpl: Could not find a button input mapping for controller \"%s\", and keyCode " "\"%d\". This keyCode will not match any from Controller::Key", - controller->getDeviceName().data(), i); + controller->getDeviceName().c_str(), i); } } @@ -4255,7 +4255,7 @@ public: CCLOG( "ControllerImpl: Could not find an axis input mapping for controller \"%s\", and keyCode " "\"%d\". This keyCode will not match any from Controller::Key", - controller->getDeviceName().data(), i); + controller->getDeviceName().c_str(), i); } } # endif @@ -4268,12 +4268,12 @@ public: # ifdef COCOS2D_DEBUG if (controller->_buttonInputMap.empty()) { - CCLOG("ControllerImpl: Could not find a button input map for controller: %s", deviceName.data()); + CCLOG("ControllerImpl: Could not find a button input map for controller: %s", deviceName.c_str()); } if (controller->_axisInputMap.empty()) { - CCLOG("ControllerImpl: Could not find an axis input map for controller: %s", deviceName.data()); + CCLOG("ControllerImpl: Could not find an axis input map for controller: %s", deviceName.c_str()); } # endif diff --git a/cocos/base/CCController.h b/cocos/base/CCController.h index f6c3bc70f4..646195def4 100644 --- a/cocos/base/CCController.h +++ b/cocos/base/CCController.h @@ -153,7 +153,7 @@ public: /** * Gets the name of this Controller object. */ - std::string_view getDeviceName() const { return _deviceName; } + const std::string& getDeviceName() const { return _deviceName; } /** * Gets the Controller id. diff --git a/cocos/base/CCEventCustom.cpp b/cocos/base/CCEventCustom.cpp index 2d3cb05fd2..025252f7a7 100644 --- a/cocos/base/CCEventCustom.cpp +++ b/cocos/base/CCEventCustom.cpp @@ -28,6 +28,7 @@ NS_CC_BEGIN -EventCustom::EventCustom(std::string_view eventName) : Event(Type::CUSTOM), _userData(nullptr), _eventName(eventName) {} +EventCustom::EventCustom(const std::string& eventName) : Event(Type::CUSTOM), _userData(nullptr), _eventName(eventName) +{} NS_CC_END diff --git a/cocos/base/CCEventCustom.h b/cocos/base/CCEventCustom.h index e7a03091c7..ae14031001 100644 --- a/cocos/base/CCEventCustom.h +++ b/cocos/base/CCEventCustom.h @@ -47,7 +47,7 @@ public: * @param eventName A given name of the custom event. * @js ctor */ - EventCustom(std::string_view eventName); + EventCustom(const std::string& eventName); /** Sets user data. * @@ -65,7 +65,7 @@ public: * * @return The name of the event. */ - std::string_view getEventName() const { return _eventName; } + const std::string& getEventName() const { return _eventName; } protected: void* _userData; ///< User data diff --git a/cocos/base/CCEventDispatcher.cpp b/cocos/base/CCEventDispatcher.cpp index 41eae69d1e..7a18512e66 100644 --- a/cocos/base/CCEventDispatcher.cpp +++ b/cocos/base/CCEventDispatcher.cpp @@ -451,9 +451,9 @@ void EventDispatcher::addEventListener(EventListener* listener) void EventDispatcher::forceAddEventListener(EventListener* listener) { - EventListenerVector* listeners = nullptr; - auto listenerID = listener->getListenerID(); - auto itr = _listenerMap.find(listenerID); + EventListenerVector* listeners = nullptr; + EventListener::ListenerID listenerID = listener->getListenerID(); + auto itr = _listenerMap.find(listenerID); if (itr == _listenerMap.end()) { @@ -579,7 +579,7 @@ void EventDispatcher::addEventListenerWithFixedPriority(EventListener* listener, addEventListener(listener); } -EventListenerCustom* EventDispatcher::addCustomEventListener(std::string_view eventName, +EventListenerCustom* EventDispatcher::addCustomEventListener(const std::string& eventName, const std::function& callback) { EventListenerCustom* listener = EventListenerCustom::create(eventName, callback); @@ -931,14 +931,14 @@ void EventDispatcher::dispatchEvent(Event* event) updateListeners(event); } -void EventDispatcher::dispatchCustomEvent(std::string_view eventName, void* optionalUserData) +void EventDispatcher::dispatchCustomEvent(const std::string& eventName, void* optionalUserData) { EventCustom ev(eventName); ev.setUserData(optionalUserData); dispatchEvent(&ev); } -bool EventDispatcher::hasEventListener(std::string_view listenerID) const +bool EventDispatcher::hasEventListener(const EventListener::ListenerID& listenerID) const { return getListeners(listenerID) != nullptr; } @@ -1268,7 +1268,7 @@ void EventDispatcher::updateDirtyFlagForSceneGraph() } } -void EventDispatcher::sortEventListeners(std::string_view listenerID) +void EventDispatcher::sortEventListeners(const EventListener::ListenerID& listenerID) { DirtyFlag dirtyFlag = DirtyFlag::NONE; @@ -1303,7 +1303,8 @@ void EventDispatcher::sortEventListeners(std::string_view listenerID) } } -void EventDispatcher::sortEventListenersOfSceneGraphPriority(std::string_view listenerID, Node* rootNode) +void EventDispatcher::sortEventListenersOfSceneGraphPriority(const EventListener::ListenerID& listenerID, + Node* rootNode) { auto listeners = getListeners(listenerID); @@ -1336,7 +1337,7 @@ void EventDispatcher::sortEventListenersOfSceneGraphPriority(std::string_view li #endif } -void EventDispatcher::sortEventListenersOfFixedPriority(std::string_view listenerID) +void EventDispatcher::sortEventListenersOfFixedPriority(const EventListener::ListenerID& listenerID) { auto listeners = getListeners(listenerID); @@ -1373,7 +1374,7 @@ void EventDispatcher::sortEventListenersOfFixedPriority(std::string_view listene #endif } -EventDispatcher::EventListenerVector* EventDispatcher::getListeners(std::string_view listenerID) const +EventDispatcher::EventListenerVector* EventDispatcher::getListeners(const EventListener::ListenerID& listenerID) const { auto iter = _listenerMap.find(listenerID); if (iter != _listenerMap.end()) @@ -1384,7 +1385,7 @@ EventDispatcher::EventListenerVector* EventDispatcher::getListeners(std::string_ return nullptr; } -void EventDispatcher::removeEventListenersForListenerID(std::string_view listenerID) +void EventDispatcher::removeEventListenersForListenerID(const EventListener::ListenerID& listenerID) { auto listenerItemIter = _listenerMap.find(listenerID); if (listenerItemIter != _listenerMap.end()) @@ -1478,7 +1479,7 @@ void EventDispatcher::removeEventListenersForType(EventListener::Type listenerTy } } -void EventDispatcher::removeCustomEventListeners(std::string_view customEventName) +void EventDispatcher::removeCustomEventListeners(const std::string& customEventName) { removeEventListenersForListenerID(customEventName); } @@ -1538,7 +1539,7 @@ void EventDispatcher::setDirtyForNode(Node* node) } } -void EventDispatcher::setDirty(std::string_view listenerID, DirtyFlag flag) +void EventDispatcher::setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag) { auto iter = _priorityDirtyFlagMap.find(listenerID); if (iter == _priorityDirtyFlagMap.end()) diff --git a/cocos/base/CCEventDispatcher.h b/cocos/base/CCEventDispatcher.h index 9c01a79663..2523f7ff2b 100644 --- a/cocos/base/CCEventDispatcher.h +++ b/cocos/base/CCEventDispatcher.h @@ -87,7 +87,7 @@ public: * @param callback A given callback method that associated the event name. * @return the generated event. Needed in order to remove the event from the dispatcher */ - EventListenerCustom* addCustomEventListener(std::string_view eventName, + EventListenerCustom* addCustomEventListener(const std::string& eventName, const std::function& callback); ///////////////////////////////////////////// @@ -117,7 +117,7 @@ public: * * @param customEventName A given event listener name which needs to be removed. */ - void removeCustomEventListeners(std::string_view customEventName); + void removeCustomEventListeners(const std::string& customEventName); /** Removes all listeners. */ @@ -177,7 +177,7 @@ public: * @param eventName The name of the event which needs to be dispatched. * @param optionalUserData The optional user data, it's a void*, the default value is nullptr. */ - void dispatchCustomEvent(std::string_view eventName, void* optionalUserData = nullptr); + void dispatchCustomEvent(const std::string& eventName, void* optionalUserData = nullptr); /** Query whether the specified event listener id has been added. * @@ -185,7 +185,7 @@ public: * * @return True if dispatching events is exist */ - bool hasEventListener(std::string_view listenerID) const; + bool hasEventListener(const EventListener::ListenerID& listenerID) const; ///////////////////////////////////////////// @@ -252,22 +252,22 @@ protected: void forceAddEventListener(EventListener* listener); /** Gets event the listener list for the event listener type. */ - EventListenerVector* getListeners(std::string_view listenerID) const; + EventListenerVector* getListeners(const EventListener::ListenerID& listenerID) const; /** Update dirty flag */ void updateDirtyFlagForSceneGraph(); /** Removes all listeners with the same event listener ID */ - void removeEventListenersForListenerID(std::string_view listenerID); + void removeEventListenersForListenerID(const EventListener::ListenerID& listenerID); /** Sort event listener */ - void sortEventListeners(std::string_view listenerID); + void sortEventListeners(const EventListener::ListenerID& listenerID); /** Sorts the listeners of specified type by scene graph priority */ - void sortEventListenersOfSceneGraphPriority(std::string_view listenerID, Node* rootNode); + void sortEventListenersOfSceneGraphPriority(const EventListener::ListenerID& listenerID, Node* rootNode); /** Sorts the listeners of specified type by fixed priority */ - void sortEventListenersOfFixedPriority(std::string_view listenerID); + void sortEventListenersOfFixedPriority(const EventListener::ListenerID& listenerID); /** Updates all listeners * 1) Removes all listener items that have been marked as 'removed' when dispatching event. @@ -311,7 +311,7 @@ protected: }; /** Sets the dirty flag for a specified listener ID */ - void setDirty(std::string_view listenerID, DirtyFlag flag); + void setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag); /** Walks though scene graph to get the draw order for each node, it's called before sorting event listener with * scene graph priority */ @@ -321,10 +321,10 @@ protected: void cleanToRemovedListeners(); /** Listeners map */ - hlookup::string_map _listenerMap; + std::unordered_map _listenerMap; /** The map of dirty flag */ - hlookup::string_map _priorityDirtyFlagMap; + std::unordered_map _priorityDirtyFlagMap; /** The map of node and event listeners */ std::unordered_map*> _nodeListenersMap; diff --git a/cocos/base/CCEventListener.cpp b/cocos/base/CCEventListener.cpp index d2e9e29c88..5da92081a7 100644 --- a/cocos/base/CCEventListener.cpp +++ b/cocos/base/CCEventListener.cpp @@ -35,7 +35,7 @@ EventListener::~EventListener() CCLOGINFO("In the destructor of EventListener. %p", this); } -bool EventListener::init(Type t, std::string_view listenerID, const std::function& callback) +bool EventListener::init(Type t, const ListenerID& listenerID, const std::function& callback) { _onEvent = callback; _type = t; diff --git a/cocos/base/CCEventListener.h b/cocos/base/CCEventListener.h index 6eb1f728ed..3f8a64631d 100644 --- a/cocos/base/CCEventListener.h +++ b/cocos/base/CCEventListener.h @@ -79,7 +79,7 @@ public: * Initializes event with type and callback function * @js NA */ - bool init(Type t, std::string_view listenerID, const std::function& callback); + bool init(Type t, const ListenerID& listenerID, const std::function& callback); public: /** Destructor. @@ -143,7 +143,7 @@ protected: /** Gets the listener ID of this listener * When event is being dispatched, listener ID is used as key for searching listeners according to event type. */ - std::string_view getListenerID() const { return _listenerID; } + const ListenerID& getListenerID() const { return _listenerID; } /** Sets the fixed priority for this listener * @note This method is only used for `fixed priority listeners`, it needs to access a non-zero value. diff --git a/cocos/base/CCEventListenerCustom.cpp b/cocos/base/CCEventListenerCustom.cpp index 299d6724fc..6ccfe80712 100644 --- a/cocos/base/CCEventListenerCustom.cpp +++ b/cocos/base/CCEventListenerCustom.cpp @@ -30,7 +30,7 @@ NS_CC_BEGIN EventListenerCustom::EventListenerCustom() : _onCustomEvent(nullptr) {} -EventListenerCustom* EventListenerCustom::create(std::string_view eventName, +EventListenerCustom* EventListenerCustom::create(const std::string& eventName, const std::function& callback) { EventListenerCustom* ret = new EventListenerCustom(); @@ -45,7 +45,7 @@ EventListenerCustom* EventListenerCustom::create(std::string_view eventName, return ret; } -bool EventListenerCustom::init(std::string_view listenerId, const std::function& callback) +bool EventListenerCustom::init(const ListenerID& listenerId, const std::function& callback) { bool ret = false; diff --git a/cocos/base/CCEventListenerCustom.h b/cocos/base/CCEventListenerCustom.h index ea68f2302e..b982162491 100644 --- a/cocos/base/CCEventListenerCustom.h +++ b/cocos/base/CCEventListenerCustom.h @@ -66,7 +66,7 @@ public: * @param callback The callback function when the specified event was emitted. * @return An autoreleased EventListenerCustom object. */ - static EventListenerCustom* create(std::string_view eventName, const std::function& callback); + static EventListenerCustom* create(const std::string& eventName, const std::function& callback); /// Overrides virtual bool checkAvailable() override; @@ -77,7 +77,7 @@ public: EventListenerCustom(); /** Initializes event with type and callback function */ - bool init(std::string_view listenerId, const std::function& callback); + bool init(const ListenerID& listenerId, const std::function& callback); protected: std::function _onCustomEvent; diff --git a/cocos/base/CCIMEDelegate.h b/cocos/base/CCIMEDelegate.h index 276c0d5d24..9c9c63574c 100644 --- a/cocos/base/CCIMEDelegate.h +++ b/cocos/base/CCIMEDelegate.h @@ -137,7 +137,7 @@ protected: * @js NA * @lua NA */ - virtual std::string_view getContentText() { return STD_STRING_EMPTY; } + virtual const std::string& getContentText() { return STD_STRING_EMPTY; } ////////////////////////////////////////////////////////////////////////// // keyboard show/hide notification diff --git a/cocos/base/CCIMEDispatcher.cpp b/cocos/base/CCIMEDispatcher.cpp index 7444466678..ccd59f96dc 100644 --- a/cocos/base/CCIMEDispatcher.cpp +++ b/cocos/base/CCIMEDispatcher.cpp @@ -247,7 +247,7 @@ void IMEDispatcher::dispatchControlKey(EventKeyboard::KeyCode keyCode) } while (0); } -std::string_view IMEDispatcher::getContentText() +const std::string& IMEDispatcher::getContentText() { if (_impl && _impl->_delegateWithIme) { diff --git a/cocos/base/CCIMEDispatcher.h b/cocos/base/CCIMEDispatcher.h index 4ab9b6f5b4..5040b9d324 100644 --- a/cocos/base/CCIMEDispatcher.h +++ b/cocos/base/CCIMEDispatcher.h @@ -76,7 +76,7 @@ public: * @brief Get the content text from IMEDelegate, retrieved previously from IME. * @lua NA */ - std::string_view getContentText(); + const std::string& getContentText(); ////////////////////////////////////////////////////////////////////////// // dispatch keyboard notification diff --git a/cocos/base/CCMap.h b/cocos/base/CCMap.h index af45abeacf..8bfd817dfa 100644 --- a/cocos/base/CCMap.h +++ b/cocos/base/CCMap.h @@ -27,7 +27,6 @@ #define __CCMAP_H__ #define USE_STD_UNORDERED_MAP 1 -#define USE_ROBIN_MAP 1 #include "base/ccMacros.h" #include "base/CCRef.h" @@ -52,12 +51,12 @@ NS_CC_BEGIN * @js NA * @lua NA */ -template , typename E = std::equal_to> +template class Map { public: #if USE_STD_UNORDERED_MAP - typedef tsl::robin_map RefMap; + typedef std::unordered_map RefMap; #else typedef std::map RefMap; #endif @@ -87,14 +86,14 @@ public: const_iterator cend() const { return _data.cend(); } /** Default constructor */ - Map() : _data() + Map() : _data() { static_assert(std::is_convertible::value, "Invalid Type for cocos2d::Map!"); CCLOGINFO("In the default constructor of Map!"); } /** Constructor with capacity. */ - explicit Map(ssize_t capacity) : _data() + explicit Map(ssize_t capacity) : _data() { static_assert(std::is_convertible::value, "Invalid Type for cocos2d::Map!"); CCLOGINFO("In the constructor with capacity of Map!"); @@ -102,7 +101,7 @@ public: } /** Copy constructor. */ - Map(const Map& other) + Map(const Map& other) { static_assert(std::is_convertible::value, "Invalid Type for cocos2d::Map!"); CCLOGINFO("In the copy constructor of Map!"); @@ -111,7 +110,7 @@ public: } /** Move constructor. */ - Map(Map&& other) + Map(Map&& other) { static_assert(std::is_convertible::value, "Invalid Type for cocos2d::Map!"); CCLOGINFO("In the move constructor of Map!"); @@ -122,7 +121,7 @@ public: * Destructor. * It will release all objects in map. */ - ~Map() + ~Map() { CCLOGINFO("In the destructor of Map!"); clear(); @@ -149,7 +148,7 @@ public: /** Returns the number of elements in bucket n. */ ssize_t bucketSize(ssize_t n) const { -#if USE_STD_UNORDERED_MAP && !defined(USE_ROBIN_MAP) +#if USE_STD_UNORDERED_MAP return _data.bucket_size(n); #else return 0; @@ -159,7 +158,7 @@ public: /** Returns the bucket number where the element with key k is located. */ ssize_t bucket(const K& k) const { -#if USE_STD_UNORDERED_MAP && !defined(USE_ROBIN_MAP) +#if USE_STD_UNORDERED_MAP return _data.bucket(k); #else return 0; @@ -224,8 +223,7 @@ public: * Member type K is the keys for the elements in the container. defined in Map as an alias of its first * template parameter (Key). */ - template - const V at(const K2& key) const + const V at(const K& key) const { auto iter = _data.find(key); if (iter != _data.end()) @@ -233,8 +231,7 @@ public: return nullptr; } - template - V at(const K2& key) + V at(const K& key) { auto iter = _data.find(key); if (iter != _data.end()) @@ -250,17 +247,9 @@ public: * Member type 'K' is the type of the keys for the elements in the container, * defined in Map as an alias of its first template parameter (Key). */ - template - const_iterator find(const K2& key) const - { - return _data.find(key); - } + const_iterator find(const K& key) const { return _data.find(key); } - template - iterator find(const K2& key) - { - return _data.find(key); - } + iterator find(const K& key) { return _data.find(key); } /** * Inserts new elements in the map. @@ -270,8 +259,7 @@ public: * @param key The key to be inserted. * @param object The object to be inserted. */ - template - void insert(const K2& key, V object) + void insert(const K& key, V object) { CCASSERT(object != nullptr, "Object is nullptr!"); object->retain(); @@ -292,13 +280,6 @@ public: return _data.erase(position); } - iterator erase(iterator position) - { - CCASSERT(position != _data.cend(), "Invalid iterator!"); - position->second->release(); - return _data.erase(position); - } - /** * Removes an element with an iterator from the Map container. * @@ -306,20 +287,7 @@ public: * Member type 'K' is the type of the keys for the elements in the container, * defined in Map as an alias of its first template parameter (Key). */ - // size_t erase(const K& k) - //{ - // auto iter = _data.find(k); - // if (iter != _data.end()) - // { - // iter->second->release(); - // _data.erase(iter); - // return 1; - // } - // return 0; - // } - - template - size_t erase(const _K2& k) + size_t erase(const K& k) { auto iter = _data.find(k); if (iter != _data.end()) @@ -336,8 +304,7 @@ public: * * @param keys Keys of elements to be erased. */ - template - void erase(const std::vector<_K2>& keys) + void erase(const std::vector& keys) { for (const auto& key : keys) { @@ -402,7 +369,7 @@ public: // } /** Copy assignment operator. */ - Map& operator=(const Map& other) + Map& operator=(const Map& other) { if (this != &other) { @@ -415,7 +382,7 @@ public: } /** Move assignment operator. */ - Map& operator=(Map&& other) + Map& operator=(Map&& other) { if (this != &other) { @@ -439,9 +406,6 @@ protected: RefMap _data; }; -template -using StringMap = Map; - NS_CC_END // end group /// @} diff --git a/cocos/base/CCNS.cpp b/cocos/base/CCNS.cpp index 17d4165860..2ebd2ff5a6 100644 --- a/cocos/base/CCNS.cpp +++ b/cocos/base/CCNS.cpp @@ -38,7 +38,7 @@ NS_CC_BEGIN typedef std::vector strArray; // string toolkit -static inline void split(std::string_view src, std::string_view token, strArray& vect) +static inline void split(const std::string& src, const std::string& token, strArray& vect) { size_t nend = 0; size_t nbegin = 0; @@ -47,9 +47,9 @@ static inline void split(std::string_view src, std::string_view token, strArray& { nend = src.find(token, nbegin); if (nend == std::string::npos) - vect.push_back(std::string{src.substr(nbegin, src.length() - nbegin)}); + vect.push_back(src.substr(nbegin, src.length() - nbegin)); else - vect.push_back(std::string{src.substr(nbegin, nend - nbegin)}); + vect.push_back(src.substr(nbegin, nend - nbegin)); nbegin = nend + tokenSize; } } @@ -58,7 +58,7 @@ static inline void split(std::string_view src, std::string_view token, strArray& // if the form is right,the string will be split into the parameter strs; // or the parameter strs will be empty. // if the form is right return true,else return false. -static bool splitWithForm(std::string_view content, strArray& strs) +static bool splitWithForm(const std::string& content, strArray& strs) { bool bRet = false; @@ -74,7 +74,7 @@ static bool splitWithForm(std::string_view content, strArray& strs) // '}' is before '{' CC_BREAK_IF(nPosLeft > nPosRight); - auto pointStr = content.substr(nPosLeft + 1, nPosRight - nPosLeft - 1); + const std::string pointStr = content.substr(nPosLeft + 1, nPosRight - nPosLeft - 1); // nothing between '{' and '}' CC_BREAK_IF(pointStr.empty()); @@ -98,14 +98,14 @@ static bool splitWithForm(std::string_view content, strArray& strs) // implement the functions -Rect RectFromString(std::string_view str) +Rect RectFromString(const std::string& str) { Rect result = Rect::ZERO; do { CC_BREAK_IF(str.empty()); - auto content = str; + std::string content = str; // find the first '{' and the third '}' size_t nPosLeft = content.find('{'); @@ -127,8 +127,8 @@ Rect RectFromString(std::string_view str) CC_BREAK_IF(nPointEnd == std::string::npos); // get the point string and size string - auto pointStr = content.substr(0, nPointEnd); - auto sizeStr = content.substr(nPointEnd + 1, content.length() - nPointEnd); + const std::string pointStr = content.substr(0, nPointEnd); + const std::string sizeStr = content.substr(nPointEnd + 1, content.length() - nPointEnd); // split the string with ',' strArray pointInfo; @@ -147,7 +147,7 @@ Rect RectFromString(std::string_view str) return result; } -Vec2 PointFromString(std::string_view str) +Vec2 PointFromString(const std::string& str) { Vec2 ret; @@ -165,7 +165,7 @@ Vec2 PointFromString(std::string_view str) return ret; } -Vec2 SizeFromString(std::string_view pszContent) +Vec2 SizeFromString(const std::string& pszContent) { Vec2 ret = Vec2::ZERO; diff --git a/cocos/base/CCNS.h b/cocos/base/CCNS.h index c08b799992..730fd94faa 100644 --- a/cocos/base/CCNS.h +++ b/cocos/base/CCNS.h @@ -46,7 +46,7 @@ NS_CC_BEGIN * @return A Core Graphics structure that represents a rectangle. * If the string is not well-formed, the function returns Rect::ZERO. */ -Rect CC_DLL RectFromString(std::string_view str); +Rect CC_DLL RectFromString(const std::string& str); /** * @brief Returns a Core Graphics point structure corresponding to the data in a given string. @@ -58,7 +58,7 @@ Rect CC_DLL RectFromString(std::string_view str); * @return A Core Graphics structure that represents a point. * If the string is not well-formed, the function returns Vec2::ZERO. */ -Vec2 CC_DLL PointFromString(std::string_view str); +Vec2 CC_DLL PointFromString(const std::string& str); /** * @brief Returns a Core Graphics size structure corresponding to the data in a given string. @@ -70,7 +70,7 @@ Vec2 CC_DLL PointFromString(std::string_view str); * @return A Core Graphics structure that represents a size. * If the string is not well-formed, the function returns Vec2::ZERO. */ -Vec2 CC_DLL SizeFromString(std::string_view str); +Vec2 CC_DLL SizeFromString(const std::string& str); // end of data_structure group /** @} */ diff --git a/cocos/base/CCNinePatchImageParser.cpp b/cocos/base/CCNinePatchImageParser.cpp index 5d23b2041f..ab71f14fdd 100644 --- a/cocos/base/CCNinePatchImageParser.cpp +++ b/cocos/base/CCNinePatchImageParser.cpp @@ -179,7 +179,7 @@ void NinePatchImageParser::setSpriteFrameInfo(Image* image, const cocos2d::Rect& this->_isRotated = rotated; } -bool NinePatchImageParser::isNinePatchImage(std::string_view filepath) +bool NinePatchImageParser::isNinePatchImage(const std::string& filepath) { size_t length = filepath.length(); if (length < 7) diff --git a/cocos/base/CCNinePatchImageParser.h b/cocos/base/CCNinePatchImageParser.h index b16c6be593..c695e10b85 100644 --- a/cocos/base/CCNinePatchImageParser.h +++ b/cocos/base/CCNinePatchImageParser.h @@ -51,7 +51,7 @@ public: * * @return If the filename contains ".9.png", then return true, otherwise false. */ - static bool isNinePatchImage(std::string_view filename); + static bool isNinePatchImage(const std::string& filename); /** * Default constructor. diff --git a/cocos/base/CCProperties.cpp b/cocos/base/CCProperties.cpp index 4709844f7a..a518a91d7f 100644 --- a/cocos/base/CCProperties.cpp +++ b/cocos/base/CCProperties.cpp @@ -38,7 +38,7 @@ USING_NS_CC; // Utility functions (shared with SceneLoader). /** @script{ignore} */ -void calculateNamespacePath(std::string_view urlString, +void calculateNamespacePath(const std::string& urlString, std::string& fileString, std::vector& namespacePath); /** @script{ignore} */ @@ -79,7 +79,7 @@ Properties::Properties(Data* data, ssize_t* dataIdx) Properties::Properties(Data* data, ssize_t* dataIdx, - std::string_view name, + const std::string& name, const char* id, const char* parentID, Properties* parent) @@ -97,7 +97,7 @@ Properties::Properties(Data* data, rewind(); } -Properties* Properties::createNonRefCounted(std::string_view url) +Properties* Properties::createNonRefCounted(const std::string& url) { if (url.empty()) { @@ -106,7 +106,7 @@ Properties* Properties::createNonRefCounted(std::string_view url) } // Calculate the file and full namespace path from the specified url. - auto& urlString = url; + std::string urlString = url; std::string fileString; std::vector namespacePath; calculateNamespacePath(urlString, fileString, namespacePath); @@ -122,7 +122,7 @@ Properties* Properties::createNonRefCounted(std::string_view url) Properties* p = getPropertiesFromNamespacePath(properties, namespacePath); if (!p) { - CCLOGWARN("Failed to load properties from url '%s'.", url.data()); + CCLOGWARN("Failed to load properties from url '%s'.", url.c_str()); CC_SAFE_DELETE(properties); return nullptr; } @@ -1093,7 +1093,7 @@ void Properties::setDirectoryPath(const std::string* path) } } -void Properties::setDirectoryPath(std::string_view path) +void Properties::setDirectoryPath(const std::string& path) { if (_dirPath == NULL) { @@ -1105,7 +1105,7 @@ void Properties::setDirectoryPath(std::string_view path) } } -void calculateNamespacePath(std::string_view urlString, +void calculateNamespacePath(const std::string& urlString, std::string& fileString, std::vector& namespacePath) { @@ -1114,14 +1114,14 @@ void calculateNamespacePath(std::string_view urlString, size_t loc = urlString.rfind('#'); if (loc != std::string::npos) { - fileString = urlString.substr(0, loc); - auto namespacePathString = urlString.substr(loc + 1); + fileString = urlString.substr(0, loc); + std::string namespacePathString = urlString.substr(loc + 1); while ((loc = namespacePathString.find('/')) != std::string::npos) { - namespacePath.push_back(std::string{namespacePathString.substr(0, loc)}); + namespacePath.push_back(namespacePathString.substr(0, loc)); namespacePathString = namespacePathString.substr(loc + 1); } - namespacePath.push_back(std::string{namespacePathString}); + namespacePath.push_back(namespacePathString); } else { diff --git a/cocos/base/CCProperties.h b/cocos/base/CCProperties.h index 14ddc7eeb3..97c123802c 100644 --- a/cocos/base/CCProperties.h +++ b/cocos/base/CCProperties.h @@ -183,7 +183,7 @@ public: * @return The created Properties or NULL if there was an error. * @script{create} */ - static Properties* createNonRefCounted(std::string_view url); + static Properties* createNonRefCounted(const std::string& url); /** * Destructor. @@ -533,7 +533,7 @@ private: { std::string name; std::string value; - Property(std::string_view aname, std::string_view avalue) : name(aname), value(avalue) {} + Property(const std::string& aname, const std::string& avalue) : name(aname), value(avalue) {} }; /** @@ -554,7 +554,7 @@ private: */ Properties(Data* data, ssize_t* dataIdx, - std::string_view name, + const std::string& name, const char* id, const char* parentID, Properties* parent); @@ -578,7 +578,7 @@ private: Properties* clone(); void setDirectoryPath(const std::string* path); - void setDirectoryPath(std::string_view path); + void setDirectoryPath(const std::string& path); /** * Reads the next character from the Data. Returns EOF if the end of the Data is reached. diff --git a/cocos/base/CCProtocols.h b/cocos/base/CCProtocols.h index a5e3a138ef..99708d8fc1 100644 --- a/cocos/base/CCProtocols.h +++ b/cocos/base/CCProtocols.h @@ -250,7 +250,7 @@ public: * @js NA * @lua NA */ - virtual std::string_view getString() const = 0; + virtual const std::string& getString() const = 0; }; /** diff --git a/cocos/base/CCScheduler.cpp b/cocos/base/CCScheduler.cpp index 7709d94687..029a12f1b6 100644 --- a/cocos/base/CCScheduler.cpp +++ b/cocos/base/CCScheduler.cpp @@ -188,7 +188,7 @@ TimerTargetCallback::TimerTargetCallback() : _target(nullptr), _callback(nullptr bool TimerTargetCallback::initWithCallback(Scheduler* scheduler, const ccSchedulerFunc& callback, void* target, - std::string_view key, + const std::string& key, float seconds, unsigned int repeat, float delay) @@ -283,7 +283,7 @@ void Scheduler::schedule(const ccSchedulerFunc& callback, void* target, float interval, bool paused, - std::string_view key) + const std::string& key) { this->schedule(callback, target, interval, CC_REPEAT_FOREVER, 0.0f, paused, key); } @@ -294,7 +294,7 @@ void Scheduler::schedule(const ccSchedulerFunc& callback, unsigned int repeat, float delay, bool paused, - std::string_view key) + const std::string& key) { CCASSERT(target, "Argument target must be non-nullptr"); CCASSERT(!key.empty(), "key should not be empty!"); @@ -344,7 +344,7 @@ void Scheduler::schedule(const ccSchedulerFunc& callback, timer->release(); } -void Scheduler::unschedule(std::string_view key, void* target) +void Scheduler::unschedule(const std::string& key, void* target) { // explicit handle nil arguments when removing an object if (target == nullptr || key.empty()) @@ -513,7 +513,7 @@ void Scheduler::schedulePerFrame(const ccSchedulerFunc& callback, void* target, } } -bool Scheduler::isScheduled(std::string_view key, const void* target) const +bool Scheduler::isScheduled(const std::string& key, const void* target) const { CCASSERT(!key.empty(), "Argument key must not be empty"); CCASSERT(target, "Argument target must be non-nullptr"); diff --git a/cocos/base/CCScheduler.h b/cocos/base/CCScheduler.h index 2dfe4283c4..5cf609f375 100644 --- a/cocos/base/CCScheduler.h +++ b/cocos/base/CCScheduler.h @@ -109,13 +109,13 @@ public: bool initWithCallback(Scheduler* scheduler, const ccSchedulerFunc& callback, void* target, - std::string_view key, + const std::string& key, float seconds, unsigned int repeat, float delay); const ccSchedulerFunc& getCallback() const { return _callback; } - std::string_view getKey() const { return _key; } + const std::string& getKey() const { return _key; } virtual void trigger(float dt) override; virtual void cancel() override; @@ -252,7 +252,7 @@ public: unsigned int repeat, float delay, bool paused, - std::string_view key); + const std::string& key); /** The scheduled method will be called every 'interval' seconds for ever. @param callback The callback function. @@ -263,7 +263,7 @@ public: @param key The key to identify the callback function, because there is not way to identify a std::function<>. @since v3.0 */ - void schedule(const ccSchedulerFunc& callback, void* target, float interval, bool paused, std::string_view key); + void schedule(const ccSchedulerFunc& callback, void* target, float interval, bool paused, const std::string& key); /** The scheduled method will be called every `interval` seconds. If paused is true, then it won't be called until it is resumed. @@ -329,7 +329,7 @@ public: @param target The target to be unscheduled. @since v3.0 */ - void unschedule(std::string_view key, void* target); + void unschedule(const std::string& key, void* target); /** Unschedules a selector for a given target. If you want to unschedule the "update", use `unscheduleUpdate()`. @@ -386,7 +386,7 @@ public: @return True if the specified callback is invoked, false if not. @since v3.0.0 */ - bool isScheduled(std::string_view key, const void* target) const; + bool isScheduled(const std::string& key, const void* target) const; /** Checks whether a selector for a given target is scheduled. @param selector The selector to be checked. diff --git a/cocos/base/CCScriptSupport.h b/cocos/base/CCScriptSupport.h index 6613b152da..318eec1da0 100644 --- a/cocos/base/CCScriptSupport.h +++ b/cocos/base/CCScriptSupport.h @@ -756,7 +756,7 @@ public: * @lua NA * @js NA */ - virtual bool parseConfig(ConfigType type, std::string_view str) = 0; + virtual bool parseConfig(ConfigType type, const std::string& str) = 0; /** Root a Reference. It tells the Garbage Collector that the associated Scripting object should not be collected diff --git a/cocos/base/CCUserDefault.cpp b/cocos/base/CCUserDefault.cpp index d241ca88a4..e3b243fe9c 100644 --- a/cocos/base/CCUserDefault.cpp +++ b/cocos/base/CCUserDefault.cpp @@ -211,12 +211,12 @@ double UserDefault::getDoubleForKey(const char* pKey, double defaultValue) return defaultValue; } -std::string_view UserDefault::getStringForKey(const char* pKey) +std::string UserDefault::getStringForKey(const char* pKey) { return getStringForKey(pKey, ""); } -std::string_view UserDefault::getStringForKey(const char* pKey, std::string_view defaultValue) +std::string UserDefault::getStringForKey(const char* pKey, const std::string& defaultValue) { auto pValue = getValueForKey(pKey); if (pValue) @@ -225,7 +225,7 @@ std::string_view UserDefault::getStringForKey(const char* pKey, std::string_view return defaultValue; } -const std::string* UserDefault::getValueForKey(std::string_view key) +const std::string* UserDefault::getValueForKey(const std::string& key) { // do lazyInit at here to make sure _encryptEnabled works well, lazyInit(); @@ -294,7 +294,7 @@ void UserDefault::setDoubleForKey(const char* pKey, double value) setStringForKey(pKey, tmp); } -void UserDefault::setStringForKey(const char* pKey, std::string_view value) +void UserDefault::setStringForKey(const char* pKey, const std::string& value) { // ignore empty key if (!pKey || !*pKey) @@ -338,7 +338,7 @@ void UserDefault::setStringForKey(const char* pKey, std::string_view value) #endif } -void UserDefault::setValueForKey(std::string_view key, std::string_view value) +void UserDefault::setValueForKey(const std::string& key, const std::string& value) { // do lazyInit at here to make sure _encryptEnabled works well lazyInit(); @@ -346,7 +346,7 @@ void UserDefault::setValueForKey(std::string_view key, std::string_view value) updateValueForKey(key, value); } -void UserDefault::updateValueForKey(std::string_view key, std::string_view value) +void UserDefault::updateValueForKey(const std::string& key, const std::string& value) { auto it = _values.find(key); if (it != _values.end()) diff --git a/cocos/base/CCUserDefault.h b/cocos/base/CCUserDefault.h index cf5de7f394..6f10045045 100644 --- a/cocos/base/CCUserDefault.h +++ b/cocos/base/CCUserDefault.h @@ -149,7 +149,7 @@ public: * @return String value of the key. * @js NA */ - std::string_view getStringForKey(const char* key); + std::string getStringForKey(const char* key); /** * Get string value by key, if the key doesn't exist, will return passed default value. @@ -158,7 +158,7 @@ public: * @return String value of the key. * @js NA */ - virtual std::string_view getStringForKey(const char* key, std::string_view defaultValue); + virtual std::string getStringForKey(const char* key, const std::string& defaultValue); // set value methods @@ -203,7 +203,7 @@ public: * @param value A string value to set to the key. * @js NA */ - virtual void setStringForKey(const char* key, std::string_view value); + virtual void setStringForKey(const char* key, const std::string& value); /** * Since we reimplement UserDefault with file mapping io, @@ -265,16 +265,16 @@ protected: void closeFileMapping(); // The low level API of all getXXXForKey - const std::string* getValueForKey(std::string_view key); + const std::string* getValueForKey(const std::string& key); // The low level API of all setXXXForKey - void setValueForKey(std::string_view key, std::string_view value); + void setValueForKey(const std::string& key, const std::string& value); // Update value without lazyInit - void updateValueForKey(std::string_view key, std::string_view value); + void updateValueForKey(const std::string& key, const std::string& value); protected: - hlookup::string_map _values; + std::unordered_map _values; static UserDefault* _userDefault; std::string _filePath; diff --git a/cocos/base/CCValue.cpp b/cocos/base/CCValue.cpp index 225d8976ba..8045669764 100644 --- a/cocos/base/CCValue.cpp +++ b/cocos/base/CCValue.cpp @@ -92,7 +92,7 @@ Value::Value(const char* v) : _type(Type::STRING) _field.strVal = new std::string(v ? v : ""); } -Value::Value(std::string_view v) : _type(Type::STRING) +Value::Value(const std::string& v) : _type(Type::STRING) { _field.strVal = new std::string(v); } @@ -308,7 +308,7 @@ Value& Value::operator=(const char* v) return *this; } -Value& Value::operator=(std::string_view v) +Value& Value::operator=(const std::string& v) { reset(Type::STRING); *_field.strVal = v; @@ -769,7 +769,7 @@ std::string Value::asString() const return ret; } -std::string_view Value::asStringRef() const +const std::string& Value::asStringRef() const { if (_type == Type::STRING) return *_field.strVal; diff --git a/cocos/base/CCValue.h b/cocos/base/CCValue.h index 27c8c94fc1..47e511cf43 100644 --- a/cocos/base/CCValue.h +++ b/cocos/base/CCValue.h @@ -43,7 +43,7 @@ NS_CC_BEGIN class Value; typedef std::vector ValueVector; -typedef hlookup::string_map ValueMap; +typedef std::unordered_map ValueMap; typedef std::unordered_map ValueMapIntKey; CC_DLL extern const ValueVector ValueVectorNull; @@ -91,7 +91,7 @@ public: explicit Value(const char* v); /** Create a Value by a string. */ - explicit Value(std::string_view v); + explicit Value(const std::string& v); explicit Value(std::string&& v); @@ -142,7 +142,7 @@ public: /** Assignment operator, assign from char* to Value. */ Value& operator=(const char* v); /** Assignment operator, assign from string to Value. */ - Value& operator=(std::string_view v); + Value& operator=(const std::string& v); Value& operator=(std::string&& v); /** Assignment operator, assign from ValueVector to Value. */ @@ -193,7 +193,7 @@ public: std::string asString() const; /** Gets as a string value reference without conversion, if value type is not string will return "" */ - std::string_view asStringRef() const; + const std::string& asStringRef() const; /** Gets as a ValueVector reference. Will convert to ValueVector if possible, or will trigger assert error. */ ValueVector& asValueVector(); @@ -279,11 +279,6 @@ private: Type _type; }; -inline const cocos2d::Value& optValue(const ValueMap& dictionary, std::string_view key) -{ - return dictionary.find(key) != dictionary.cend() ? dictionary.at(key) : cocos2d::Value::Null; -} - /** @} */ NS_CC_END diff --git a/cocos/base/ObjectFactory.cpp b/cocos/base/ObjectFactory.cpp index d0920f7dff..065d70f049 100644 --- a/cocos/base/ObjectFactory.cpp +++ b/cocos/base/ObjectFactory.cpp @@ -30,12 +30,12 @@ NS_CC_BEGIN ObjectFactory::TInfo::TInfo() : _class(""), _fun(nullptr), _func(nullptr) {} -ObjectFactory::TInfo::TInfo(std::string_view type, Instance ins) : _class(type), _fun(ins), _func(nullptr) +ObjectFactory::TInfo::TInfo(const std::string& type, Instance ins) : _class(type), _fun(ins), _func(nullptr) { ObjectFactory::getInstance()->registerType(*this); } -ObjectFactory::TInfo::TInfo(std::string_view type, InstanceFunc ins) : _class(type), _fun(nullptr), _func(ins) +ObjectFactory::TInfo::TInfo(const std::string& type, InstanceFunc ins) : _class(type), _fun(nullptr), _func(ins) { ObjectFactory::getInstance()->registerType(*this); } @@ -85,16 +85,12 @@ void ObjectFactory::destroyInstance() CC_SAFE_DELETE(_sharedFactory); } -Ref* ObjectFactory::createObject(std::string_view name) +Ref* ObjectFactory::createObject(const std::string& name) { Ref* o = nullptr; do { - // const TInfo t = _typeMap[name.data]; - auto it = _typeMap.find(name); - if (it == _typeMap.end()) - break; - auto& t = it->second; + const TInfo t = _typeMap[name]; if (t._fun != nullptr) { o = t._fun(); diff --git a/cocos/base/ObjectFactory.h b/cocos/base/ObjectFactory.h index 0ee3ad46f7..e7499b08e0 100644 --- a/cocos/base/ObjectFactory.h +++ b/cocos/base/ObjectFactory.h @@ -42,8 +42,8 @@ public: struct CC_DLL TInfo { TInfo(); - TInfo(std::string_view type, Instance ins = nullptr); - TInfo(std::string_view type, InstanceFunc ins = nullptr); + TInfo(const std::string& type, Instance ins = nullptr); + TInfo(const std::string& type, InstanceFunc ins = nullptr); TInfo(const TInfo& t); ~TInfo(); TInfo& operator=(const TInfo& t); @@ -51,11 +51,11 @@ public: Instance _fun; InstanceFunc _func; }; - typedef hlookup::string_map FactoryMap; + typedef std::unordered_map FactoryMap; static ObjectFactory* getInstance(); static void destroyInstance(); - cocos2d::Ref* createObject(std::string_view name); + cocos2d::Ref* createObject(const std::string& name); void registerType(const TInfo& t); void removeAll(); diff --git a/cocos/base/ZipUtils.cpp b/cocos/base/ZipUtils.cpp index 3aea081ace..f5fa6beb31 100644 --- a/cocos/base/ZipUtils.cpp +++ b/cocos/base/ZipUtils.cpp @@ -658,7 +658,7 @@ struct ZipFilePrivate std::unique_ptr memfs; // std::unordered_map is faster if available on the platform - typedef hlookup::string_map FileListContainer; + typedef std::unordered_map FileListContainer; FileListContainer fileList; zlib_filefunc_def functionOverrides{}; @@ -683,10 +683,10 @@ ZipFile::ZipFile() : _data(new ZipFilePrivate()) _data->zipFile = nullptr; } -ZipFile::ZipFile(std::string_view zipFile, std::string_view filter) : _data(new ZipFilePrivate()) +ZipFile::ZipFile(const std::string& zipFile, const std::string& filter) : _data(new ZipFilePrivate()) { _data->zipFileName = zipFile; - _data->zipFile = unzOpen2(zipFile.data(), &_data->functionOverrides); + _data->zipFile = unzOpen2(zipFile.c_str(), &_data->functionOverrides); setFilter(filter); } @@ -700,7 +700,7 @@ ZipFile::~ZipFile() CC_SAFE_DELETE(_data); } -bool ZipFile::setFilter(std::string_view filter) +bool ZipFile::setFilter(const std::string& filter) { bool ret = false; do @@ -743,7 +743,7 @@ bool ZipFile::setFilter(std::string_view filter) return ret; } -bool ZipFile::fileExists(std::string_view fileName) const +bool ZipFile::fileExists(const std::string& fileName) const { bool ret = false; do @@ -756,7 +756,7 @@ bool ZipFile::fileExists(std::string_view fileName) const return ret; } -std::vector ZipFile::listFiles(std::string_view pathname) const +std::vector ZipFile::listFiles(const std::string& pathname) const { // filter files which `filename.startsWith(pathname)` @@ -766,23 +766,22 @@ std::vector ZipFile::listFiles(std::string_view pathname) const ZipFilePrivate::FileListContainer::const_iterator it = _data->fileList.begin(); ZipFilePrivate::FileListContainer::const_iterator end = _data->fileList.end(); // ensure pathname ends with `/` as a directory - std::string ensureDir; - std::string_view dirname = pathname[pathname.length() - 1] == '/' ? pathname : (ensureDir.append(pathname) += '/'); + std::string dirname = pathname[pathname.length() - 1] == '/' ? pathname : pathname + "/"; for (auto& item : _data->fileList) { - std::string_view filename = item.first; - if (cxx20::starts_with(filename, cxx17::string_view{dirname})) + const std::string& filename = item.first; + if (cxx20::starts_with(cxx17::string_view{filename}, cxx17::string_view{dirname})) { - std::string_view suffix{filename.substr(dirname.length())}; - auto pos = suffix.find('/'); + std::string suffix = filename.substr(dirname.length()); + auto pos = suffix.find('/'); if (pos == std::string::npos) { - fileSet.insert(std::string{suffix}); + fileSet.insert(suffix); } else { // fileSet.insert(parts[0] + "/"); - fileSet.insert(std::string{suffix.substr(0, pos + 1)}); + fileSet.insert(suffix.substr(0, pos + 1)); } } } @@ -790,7 +789,7 @@ std::vector ZipFile::listFiles(std::string_view pathname) const return std::vector{fileSet.begin(), fileSet.end()}; } -unsigned char* ZipFile::getFileData(std::string_view fileName, ssize_t* size) +unsigned char* ZipFile::getFileData(const std::string& fileName, ssize_t* size) { unsigned char* buffer = nullptr; if (size) @@ -801,7 +800,7 @@ unsigned char* ZipFile::getFileData(std::string_view fileName, ssize_t* size) CC_BREAK_IF(!_data->zipFile); CC_BREAK_IF(fileName.empty()); - auto it = _data->fileList.find(fileName); + ZipFilePrivate::FileListContainer::iterator it = _data->fileList.find(fileName); CC_BREAK_IF(it == _data->fileList.end()); ZipEntryInfo& fileInfo = it->second; @@ -829,7 +828,7 @@ unsigned char* ZipFile::getFileData(std::string_view fileName, ssize_t* size) return buffer; } -bool ZipFile::getFileData(std::string_view fileName, ResizableBuffer* buffer) +bool ZipFile::getFileData(const std::string& fileName, ResizableBuffer* buffer) { bool res = false; do @@ -916,7 +915,7 @@ bool ZipFile::initWithBuffer(const void* buffer, unsigned int size) return true; } -bool ZipFile::zfopen(std::string_view fileName, ZipFileStream* zfs) +bool ZipFile::zfopen(const std::string& fileName, ZipFileStream* zfs) { if (!zfs) return false; @@ -1006,7 +1005,7 @@ long long ZipFile::zfsize(ZipFileStream* zfs) return -1; } -unsigned char* ZipFile::getFileDataFromZip(std::string_view zipFilePath, std::string_view filename, ssize_t* size) +unsigned char* ZipFile::getFileDataFromZip(const std::string& zipFilePath, const std::string& filename, ssize_t* size) { unsigned char* buffer = nullptr; unzFile file = nullptr; @@ -1016,11 +1015,11 @@ unsigned char* ZipFile::getFileDataFromZip(std::string_view zipFilePath, std::st { CC_BREAK_IF(zipFilePath.empty()); - file = unzOpen(zipFilePath.data()); + file = unzOpen(zipFilePath.c_str()); CC_BREAK_IF(!file); // minizip 1.2.0 is same with other platforms - int ret = unzLocateFile(file, filename.data(), nullptr); + int ret = unzLocateFile(file, filename.c_str(), nullptr); CC_BREAK_IF(UNZ_OK != ret); diff --git a/cocos/base/ZipUtils.h b/cocos/base/ZipUtils.h index 8fb4e5b529..4a74a38fb2 100644 --- a/cocos/base/ZipUtils.h +++ b/cocos/base/ZipUtils.h @@ -250,7 +250,7 @@ public: * * @since v2.0.5 */ - ZipFile(std::string_view zipFile, std::string_view filter = std::string()); + ZipFile(const std::string& zipFile, const std::string& filter = std::string()); virtual ~ZipFile(); /** @@ -262,7 +262,7 @@ public: * * @since v2.0.5 */ - bool setFilter(std::string_view filter); + bool setFilter(const std::string& filter); /** * Check does a file exists or not in zip file @@ -272,7 +272,7 @@ public: * * @since v2.0.5 */ - bool fileExists(std::string_view fileName) const; + bool fileExists(const std::string& fileName) const; /** * Get files and folders in pathname @@ -280,7 +280,7 @@ public: * @param dirname * @return */ - std::vector listFiles(std::string_view pathname) const; + std::vector listFiles(const std::string& pathname) const; /** * Get resource file data from a zip file. @@ -291,7 +291,7 @@ public: * * @since v2.0.5 */ - unsigned char* getFileData(std::string_view fileName, ssize_t* size); + unsigned char* getFileData(const std::string& fileName, ssize_t* size); /** * Get resource file data from a zip file. @@ -299,7 +299,7 @@ public: * @param[out] buffer If the file read operation succeeds, if will contain the file data. * @return True if successful. */ - bool getFileData(std::string_view fileName, ResizableBuffer* buffer); + bool getFileData(const std::string& fileName, ResizableBuffer* buffer); std::string getFirstFilename(); std::string getNextFilename(); @@ -310,7 +310,7 @@ public: * zipFile Streaming support, !!!important, the file in zip must no compress level, otherwise * stream seek doesn't work. */ - bool zfopen(std::string_view fileName, ZipFileStream* zfs); + bool zfopen(const std::string& fileName, ZipFileStream* zfs); int zfread(ZipFileStream* zfs, void* buf, unsigned int size); int32_t zfseek(ZipFileStream* zfs, int32_t offset, int origin); void zfclose(ZipFileStream* zfs); @@ -325,7 +325,9 @@ public: * @warning Recall: you are responsible for calling free() on any Non-nullptr pointer returned. */ CC_DEPRECATED() - static unsigned char* getFileDataFromZip(std::string_view zipFilePath, std::string_view filename, ssize_t* size); + static unsigned char* getFileDataFromZip(const std::string& zipFilePath, + const std::string& filename, + ssize_t* size); private: /* Only used internal for createWithBuffer() */ diff --git a/cocos/base/ccUTF8.cpp b/cocos/base/ccUTF8.cpp index 2db5969e2b..1c993a6299 100644 --- a/cocos/base/ccUTF8.cpp +++ b/cocos/base/ccUTF8.cpp @@ -375,7 +375,7 @@ std::string getStringUTFCharsJNI(JNIEnv* env, jstring srcjStr, bool* ret) return utf8Str; } -jstring newStringUTFJNI(JNIEnv* env, std::string_view utf8Str, bool* ret) +jstring newStringUTFJNI(JNIEnv* env, const std::string& utf8Str, bool* ret) { std::u16string utf16Str; bool flag = cocos2d::StringUtils::UTF8ToUTF16(utf8Str, utf16Str); @@ -399,9 +399,9 @@ std::vector getChar16VectorFromUTF16String(const std::u16string& utf16 return std::vector(utf16.begin(), utf16.end()); } -int32_t getCharacterCountInUTF8String(std::string_view utf8) +int32_t getCharacterCountInUTF8String(const std::string& utf8) { - return getUTF8StringLength((const UTF8*)utf8.data()); + return getUTF8StringLength((const UTF8*)utf8.c_str()); } bool hasNonAsciiUTF8(const char* str, size_t len) @@ -455,7 +455,7 @@ bool isLegalUTF8String(const char* str, size_t len) StringUTF8::StringUTF8() {} -StringUTF8::StringUTF8(std::string_view newStr) +StringUTF8::StringUTF8(const std::string& newStr) { replace(newStr); } @@ -467,18 +467,18 @@ std::size_t StringUTF8::length() const return _str.size(); } -void StringUTF8::replace(std::string_view newStr) +void StringUTF8::replace(const std::string& newStr) { _str.clear(); if (!newStr.empty()) { - UTF8* sequenceUtf8 = (UTF8*)newStr.data(); + UTF8* sequenceUtf8 = (UTF8*)newStr.c_str(); int lengthString = getUTF8StringLength(sequenceUtf8); if (lengthString == 0) { - CCLOG("Bad utf-8 set string: %s", newStr.data()); + CCLOG("Bad utf-8 set string: %s", newStr.c_str()); return; } @@ -536,7 +536,7 @@ bool StringUTF8::deleteChar(std::size_t pos) } } -bool StringUTF8::insert(std::size_t pos, std::string_view insertStr) +bool StringUTF8::insert(std::size_t pos, const std::string& insertStr) { StringUTF8 utf8(insertStr); diff --git a/cocos/base/ccUTF8.h b/cocos/base/ccUTF8.h index a648372018..80626a4bc8 100644 --- a/cocos/base/ccUTF8.h +++ b/cocos/base/ccUTF8.h @@ -147,7 +147,7 @@ CC_DLL std::string getStringUTFCharsJNI(JNIEnv* env, jstring srcjStr, bool* ret * @param ret True if the conversion succeeds and the ret pointer isn't null * @returns the result of jstring,the jstring need to DeleteLocalRef(jstring); */ -CC_DLL jstring newStringUTFJNI(JNIEnv* env, std::string_view utf8Str, bool* ret = nullptr); +CC_DLL jstring newStringUTFJNI(JNIEnv* env, const std::string& utf8Str, bool* ret = nullptr); #endif /** @@ -199,7 +199,7 @@ CC_DLL bool isUnicodeNonBreaking(char32_t ch); * @param utf8 An UTF-8 encoded string. * @returns The length of the string in characters. */ -CC_DLL int32_t getCharacterCountInUTF8String(std::string_view utf8); +CC_DLL int32_t getCharacterCountInUTF8String(const std::string& utf8); /** * @brief Gets the index of the last character that is not equal to the character given. @@ -245,18 +245,18 @@ public: typedef std::vector CharUTF8Store; StringUTF8(); - StringUTF8(std::string_view newStr); + StringUTF8(const std::string& newStr); ~StringUTF8(); std::size_t length() const; - void replace(std::string_view newStr); + void replace(const std::string& newStr); std::string getAsCharSequence() const; std::string getAsCharSequence(std::size_t pos) const; std::string getAsCharSequence(std::size_t pos, std::size_t len) const; bool deleteChar(std::size_t pos); - bool insert(std::size_t pos, std::string_view insertStr); + bool insert(std::size_t pos, const std::string& insertStr); bool insert(std::size_t pos, const StringUTF8& insertStr); CharUTF8Store& getString() { return _str; } diff --git a/cocos/base/ccUtils.cpp b/cocos/base/ccUtils.cpp index c10a345f0b..a661939ab0 100644 --- a/cocos/base/ccUtils.cpp +++ b/cocos/base/ccUtils.cpp @@ -178,13 +178,13 @@ void captureNode(Node* startNode, std::function)> imageCallba } // [DEPRECATED] -void captureScreen(std::function afterCap, std::string_view filename) +void captureScreen(std::function afterCap, const std::string& filename) { std::string outfile; if (FileUtils::getInstance()->isAbsolutePath(filename)) outfile = filename; else - outfile = FileUtils::getInstance()->getWritablePath().append(filename); + outfile = FileUtils::getInstance()->getWritablePath() + filename; captureScreen([_afterCap = std::move(afterCap), _outfile = std::move(outfile)](RefPtr image) mutable { AsyncTaskPool::getInstance()->enqueue( @@ -199,7 +199,7 @@ void captureScreen(std::function afterCap, std::st }); } -std::vector findChildren(const Node& node, std::string_view name) +std::vector findChildren(const Node& node, const std::string& name) { std::vector vec; @@ -348,7 +348,7 @@ Sprite* createSpriteFromBase64(const char* base64String) return sprite; } -Node* findChild(Node* levelRoot, std::string_view name) +Node* findChild(Node* levelRoot, const std::string& name) { if (levelRoot == nullptr || name.empty()) return nullptr; @@ -389,7 +389,7 @@ Node* findChild(Node* levelRoot, int tag) return nullptr; } -std::string getFileMD5Hash(std::string_view filename) +std::string getFileMD5Hash(const std::string& filename) { Data data; FileUtils::getInstance()->getContents(filename, &data); diff --git a/cocos/base/ccUtils.h b/cocos/base/ccUtils.h index 8276c42355..9ea8fad56d 100644 --- a/cocos/base/ccUtils.h +++ b/cocos/base/ccUtils.h @@ -92,7 +92,7 @@ CC_DLL void captureNode(Node* startNode, std::function)> imag * etc.). * @since v4.0 */ -CC_DLL void captureScreen(std::function afterCap, std::string_view filename); +CC_DLL void captureScreen(std::function afterCap, const std::string& filename); /** Find children by name, it will return all child that has the same name. * It supports c++ 11 regular expression. It is a helper function of `Node::enumerateChildren()`. @@ -103,7 +103,7 @@ CC_DLL void captureScreen(std::function afterCap, * @return Array of Nodes that matches the name * @since v3.2 */ -CC_DLL std::vector findChildren(const Node& node, std::string_view name); +CC_DLL std::vector findChildren(const Node& node, const std::string& name); /** Same to ::atof, but strip the string, remain 7 numbers after '.' before call atof. * Why we need this? Because in android c++_static, atof ( and std::atof ) is unsupported for numbers have long decimal @@ -151,7 +151,7 @@ CC_DLL Sprite* createSpriteFromBase64(const char* base64String); * @return Returns found node or nullptr */ -CC_DLL Node* findChild(Node* levelRoot, std::string_view name); +CC_DLL Node* findChild(Node* levelRoot, const std::string& name); /** * Find a child by tag recursively @@ -166,7 +166,7 @@ CC_DLL Node* findChild(Node* levelRoot, int tag); * @return Returns found node or nullptr with specified type 'T' */ template -inline T findChild(Node* levelRoot, std::string_view name) +inline T findChild(Node* levelRoot, const std::string& name) { return dynamic_cast(findChild(levelRoot, name)); } @@ -187,7 +187,7 @@ inline T findChild(Node* levelRoot, int tag) * @param filename The file to calculate md5 hash. * @return The md5 hash for the file */ -CC_DLL std::string getFileMD5Hash(std::string_view filename); +CC_DLL std::string getFileMD5Hash(const std::string& filename); /** * Gets the md5 hash for the given buffer. diff --git a/cocos/base/hlookup.h b/cocos/base/hlookup.h deleted file mode 100644 index 6a66949333..0000000000 --- a/cocos/base/hlookup.h +++ /dev/null @@ -1,64 +0,0 @@ -// Heterogeneous lookup support on c++17 with robin_hash -// C++20 demo: Heterogeneous lookup for unordered containers (transparent hashing) -// https://en.cppreference.com/w/cpp/container/unordered_map/find -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include "tsl/robin_map.h" -#include "tsl/robin_set.h" - -using namespace std::string_literals; -using namespace std::string_view_literals; - -namespace hlookup -{ -struct string_hash -{ - using hash_type = std::hash; - using is_transparent = void; - - size_t operator()(const char* str) const { return hash_type{}(str); } - size_t operator()(std::string_view str) const { return hash_type{}(str); } - size_t operator()(const std::string& str) const { return hash_type{}(str); } -}; - -struct equal_to -{ - template - constexpr auto operator()(_Ty1&& _Left, _Ty2&& _Right) const - noexcept(noexcept(static_cast<_Ty1&&>(_Left) == static_cast<_Ty2&&>(_Right))) // strengthened - -> decltype(static_cast<_Ty1&&>(_Left) == static_cast<_Ty2&&>(_Right)) - { - return static_cast<_Ty1&&>(_Left) == static_cast<_Ty2&&>(_Right); - } - - using is_transparent = void; -}; - -template -using stl_string_map = std::map>; -using stl_string_set = std::set>; - -template -using string_map = tsl::robin_map; -using string_set = tsl::robin_set; - -template -inline auto set_item(_Cont& cont, std::string_view k, _Valty&& v) -{ - typename _Cont::iterator it = cont.find(k); - if (it != cont.end()) - it->second = std::forward<_Valty>(v); - else - it = cont.emplace(k, std::forward<_Valty>(v)).first; - return it; -} - -constexpr auto empty_sv = ""sv; - -} // namespace hlookup diff --git a/cocos/math/CCMathBase.h b/cocos/math/CCMathBase.h index 527be2f10e..36b6ff1a3a 100644 --- a/cocos/math/CCMathBase.h +++ b/cocos/math/CCMathBase.h @@ -53,9 +53,9 @@ //#define MATH_LOG2E 1.442695040888963387f //#define MATH_PI 3.14159265358979323846f //#define MATH_RANDOM_MINUS1_1() ((2.0f*((float)rand()/RAND_MAX))-1.0f) // Returns a random float between -1 -// and 1. #define MATH_RANDOM_0_1() ((float)rand()/RAND_MAX) // Returns a random float -// between 0 and 1. #define MATH_CLAMP(x, lo, hi) ((x < lo) ? lo : ((x > hi) ? hi : x)) #ifndef M_1_PI #define -// M_1_PI 0.31830988618379067154 +//and 1. #define MATH_RANDOM_0_1() ((float)rand()/RAND_MAX) // Returns a random float +//between 0 and 1. #define MATH_CLAMP(x, lo, hi) ((x < lo) ? lo : ((x > hi) ? hi : x)) #ifndef M_1_PI #define +//M_1_PI 0.31830988618379067154 #ifdef __cplusplus # define NS_CC_MATH_BEGIN \ diff --git a/cocos/navmesh/CCNavMesh.cpp b/cocos/navmesh/CCNavMesh.cpp index dacb3948fb..cd990f580f 100644 --- a/cocos/navmesh/CCNavMesh.cpp +++ b/cocos/navmesh/CCNavMesh.cpp @@ -90,7 +90,7 @@ static const int TILECACHESET_MAGIC = 'T' << 24 | 'S' << 16 | 'E' << 8 | 'T'; static const int TILECACHESET_VERSION = 2; // 1: fastlz, 2: lz4 static const int MAX_AGENTS = 128; -NavMesh* NavMesh::create(std::string_view navFilePath, std::string_view geomFilePath) +NavMesh* NavMesh::create(const std::string& navFilePath, const std::string& geomFilePath) { auto ref = new NavMesh(); if (ref->initWithFilePath(navFilePath, geomFilePath)) @@ -138,7 +138,7 @@ NavMesh::~NavMesh() _obstacleList.clear(); } -bool NavMesh::initWithFilePath(std::string_view navFilePath, std::string_view geomFilePath) +bool NavMesh::initWithFilePath(const std::string& navFilePath, const std::string& geomFilePath) { _navFilePath = navFilePath; _geomFilePath = geomFilePath; diff --git a/cocos/navmesh/CCNavMesh.h b/cocos/navmesh/CCNavMesh.h index 41ad2f8d6b..44aaaa1d03 100644 --- a/cocos/navmesh/CCNavMesh.h +++ b/cocos/navmesh/CCNavMesh.h @@ -60,7 +60,7 @@ public: @param navFilePath The NavMesh File path. @param geomFilePath The geometry File Path,include offmesh information,etc. */ - static NavMesh* create(std::string_view navFilePath, std::string_view geomFilePath); + static NavMesh* create(const std::string& navFilePath, const std::string& geomFilePath); /** update navmesh. */ void update(float dt); @@ -99,7 +99,7 @@ public: virtual ~NavMesh(); protected: - bool initWithFilePath(std::string_view navFilePath, std::string_view geomFilePath); + bool initWithFilePath(const std::string& navFilePath, const std::string& geomFilePath); bool read(); bool loadNavMeshFile(); bool loadGeomFile(); diff --git a/cocos/navmesh/CCNavMeshAgent.cpp b/cocos/navmesh/CCNavMeshAgent.cpp index f72ee758a2..920bd386d1 100644 --- a/cocos/navmesh/CCNavMeshAgent.cpp +++ b/cocos/navmesh/CCNavMeshAgent.cpp @@ -60,7 +60,7 @@ NavMeshAgent* NavMeshAgent::create(const NavMeshAgentParam& param) return nullptr; } -std::string_view NavMeshAgent::getNavMeshAgentComponentName() +const std::string& NavMeshAgent::getNavMeshAgentComponentName() { static std::string comName = "___NavMeshAgentComponent___"; return comName; diff --git a/cocos/navmesh/CCNavMeshAgent.h b/cocos/navmesh/CCNavMeshAgent.h index 9b532cfd4a..d92e541d61 100644 --- a/cocos/navmesh/CCNavMeshAgent.h +++ b/cocos/navmesh/CCNavMeshAgent.h @@ -97,7 +97,7 @@ public: @param param The parameters of agent. */ static NavMeshAgent* create(const NavMeshAgentParam& param); - static std::string_view getNavMeshAgentComponentName(); + static const std::string& getNavMeshAgentComponentName(); virtual void onEnter() override; virtual void onExit() override; diff --git a/cocos/navmesh/CCNavMeshObstacle.cpp b/cocos/navmesh/CCNavMeshObstacle.cpp index 81e9ec900f..61ad5d183a 100644 --- a/cocos/navmesh/CCNavMeshObstacle.cpp +++ b/cocos/navmesh/CCNavMeshObstacle.cpp @@ -45,7 +45,7 @@ NavMeshObstacle* NavMeshObstacle::create(float radius, float height) return nullptr; } -std::string_view NavMeshObstacle::getNavMeshObstacleComponentName() +const std::string& NavMeshObstacle::getNavMeshObstacleComponentName() { static std::string comName = "___NavMeshObstacleComponent___"; return comName; diff --git a/cocos/navmesh/CCNavMeshObstacle.h b/cocos/navmesh/CCNavMeshObstacle.h index b0a0ad32f3..0dc5677284 100644 --- a/cocos/navmesh/CCNavMeshObstacle.h +++ b/cocos/navmesh/CCNavMeshObstacle.h @@ -64,7 +64,7 @@ public: @param height The height of obstacle. */ static NavMeshObstacle* create(float radius, float height); - static std::string_view getNavMeshObstacleComponentName(); + static const std::string& getNavMeshObstacleComponentName(); virtual void onEnter() override; virtual void onExit() override; diff --git a/cocos/network/CCDownloader-curl.cpp b/cocos/network/CCDownloader-curl.cpp index 7a98042eb6..41e97da10b 100644 --- a/cocos/network/CCDownloader-curl.cpp +++ b/cocos/network/CCDownloader-curl.cpp @@ -106,7 +106,7 @@ public: DLLOG("Destruct DownloadTaskCURL %p", this); } - bool init(std::string_view filename, std::string_view tempSuffix) + bool init(const std::string& filename, const std::string& tempSuffix) { if (0 == filename.length()) { @@ -170,7 +170,7 @@ public: } // init md5 state - _checksumFileName = _tempFileName + ".chksum"; + _checksumFileName = filename + ".chksum"; _fsMd5 = FileUtils::getInstance()->openFileStream(_checksumFileName, FileStream::Mode::OVERLAPPED); _fsMd5->seek(0, SEEK_END); @@ -219,7 +219,7 @@ public: /* retval: 0. don't check, 1. check succeed, 2. check failed */ - int checkFileMd5(std::string_view requiredsum, std::string* outsum = nullptr) + int checkFileMd5(const std::string& requiredsum, std::string* outsum = nullptr) { int status = 0; if (!requiredsum.empty()) @@ -573,7 +573,7 @@ private: do { long httpResponseCode = 0; - rc = curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &httpResponseCode); + rc = curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &httpResponseCode); if (CURLE_OK != rc) { break; diff --git a/cocos/network/CCDownloader.cpp b/cocos/network/CCDownloader.cpp index 5c9e67a36a..14c337a1c2 100644 --- a/cocos/network/CCDownloader.cpp +++ b/cocos/network/CCDownloader.cpp @@ -39,17 +39,17 @@ DownloadTask::DownloadTask() DLLOG("Construct DownloadTask %p", this); } -DownloadTask::DownloadTask(std::string_view srcUrl, std::string_view identifier) +DownloadTask::DownloadTask(const std::string& srcUrl, const std::string& identifier) { this->requestURL = srcUrl; this->identifier = identifier; this->background = false; } -DownloadTask::DownloadTask(std::string_view srcUrl, - std::string_view storagePath, - std::string_view checksum, - std::string_view identifier, +DownloadTask::DownloadTask(const std::string& srcUrl, + const std::string& storagePath, + const std::string& checksum, + const std::string& identifier, bool background) { this->requestURL = srcUrl; @@ -87,7 +87,7 @@ Downloader::Downloader(const DownloaderHints& hints) }; _impl->onTaskFinish = [this](const DownloadTask& task, int errorCode, int errorCodeInternal, - std::string_view errorStr, std::vector& data) { + const std::string& errorStr, std::vector& data) { if (DownloadTask::ERROR_NO_ERROR != errorCode) { if (onTaskError) @@ -121,8 +121,8 @@ Downloader::~Downloader() DLLOG("Destruct Downloader %p", this); } -std::shared_ptr Downloader::createDownloadDataTask(std::string_view srcUrl, - std::string_view identifier /* = ""*/) +std::shared_ptr Downloader::createDownloadDataTask(const std::string& srcUrl, + const std::string& identifier /* = ""*/) { auto task = std::make_shared(srcUrl, identifier); @@ -143,10 +143,10 @@ std::shared_ptr Downloader::createDownloadDataTask(std::string_vie return task; } -std::shared_ptr Downloader::createDownloadFileTask(std::string_view srcUrl, - std::string_view storagePath, - std::string_view identifier, - std::string_view md5checksum, +std::shared_ptr Downloader::createDownloadFileTask(const std::string& srcUrl, + const std::string& storagePath, + const std::string& identifier, + const std::string& md5checksum, bool background) { auto task = std::make_shared(srcUrl, storagePath, md5checksum, identifier, background); @@ -167,7 +167,7 @@ std::shared_ptr Downloader::createDownloadFileTask(std::string_vie return task; } -// std::string Downloader::getFileNameFromUrl(std::string_view srcUrl) +// std::string Downloader::getFileNameFromUrl(const std::string& srcUrl) //{ // // Find file name and file extension // std::string filename; diff --git a/cocos/network/CCDownloader.h b/cocos/network/CCDownloader.h index c6e3379a40..164859bb73 100644 --- a/cocos/network/CCDownloader.h +++ b/cocos/network/CCDownloader.h @@ -72,11 +72,11 @@ public: } mutable progressInfo; DownloadTask(); - DownloadTask(std::string_view srcUrl, std::string_view identifier); - DownloadTask(std::string_view srcUrl, - std::string_view storagePath, - std::string_view checksum, // currently is MD5 - std::string_view identifier, + DownloadTask(const std::string& srcUrl, const std::string& identifier); + DownloadTask(const std::string& srcUrl, + const std::string& storagePath, + const std::string& checksum, // currently is MD5 + const std::string& identifier, bool background); virtual ~DownloadTask(); @@ -114,7 +114,7 @@ public: std::function onTaskProgress; - std::function + std::function onTaskError; void setOnFileTaskSuccess(const std::function& callback) @@ -129,18 +129,19 @@ public: void setOnTaskError( const std::function< - void(const DownloadTask& task, int errorCode, int errorCodeInternal, std::string_view errorStr)>& callback) + void(const DownloadTask& task, int errorCode, int errorCodeInternal, const std::string& errorStr)>& + callback) { onTaskError = callback; }; - std::shared_ptr createDownloadDataTask(std::string_view srcUrl, std::string_view identifier = ""); + std::shared_ptr createDownloadDataTask(const std::string& srcUrl, const std::string& identifier = ""); - std::shared_ptr createDownloadFileTask(std::string_view srcUrl, - std::string_view storagePath, - std::string_view identifier = "", - std::string_view checksum = "", - bool background = false); + std::shared_ptr createDownloadFileTask(const std::string& srcUrl, + const std::string& storagePath, + const std::string& identifier = "", + const std::string& checksum = "", + bool background = false); private: std::unique_ptr _impl; diff --git a/cocos/network/CCIDownloaderImpl.h b/cocos/network/CCIDownloaderImpl.h index ceefec26fe..71ffa79253 100644 --- a/cocos/network/CCIDownloaderImpl.h +++ b/cocos/network/CCIDownloaderImpl.h @@ -67,7 +67,7 @@ public: std::function& data)> onTaskFinish; diff --git a/cocos/network/HttpClient.cpp b/cocos/network/HttpClient.cpp index 6c54503bd7..0f2f78290e 100644 --- a/cocos/network/HttpClient.cpp +++ b/cocos/network/HttpClient.cpp @@ -104,7 +104,7 @@ void HttpClient::enableCookies(const char* cookieFile) _cookie->readFile(); } -void HttpClient::setSSLVerification(std::string_view caFile) +void HttpClient::setSSLVerification(const std::string& caFile) { std::lock_guard lock(_sslCaFileMutex); _sslCaFilename = caFile; @@ -167,9 +167,9 @@ void HttpClient::handleNetworkStatusChanged() _service->set_option(YOPT_S_DNS_DIRTY, 1); } -void HttpClient::setNameServers(std::string_view servers) +void HttpClient::setNameServers(const std::string& servers) { - _service->set_option(YOPT_S_DNS_LIST, servers.data()); + _service->set_option(YOPT_S_DNS_LIST, servers.c_str()); } yasio::io_service* HttpClient::getInternalService() @@ -208,7 +208,7 @@ int HttpClient::tryTakeAvailChannel() return -1; } -void HttpClient::processResponse(HttpResponse* response, std::string_view url) +void HttpClient::processResponse(HttpResponse* response, const std::string& url) { auto channelIndex = tryTakeAvailChannel(); response->retain(); @@ -221,7 +221,7 @@ void HttpClient::processResponse(HttpResponse* response, std::string_view url) auto& requestUri = response->getRequestUri(); auto channelHandle = _service->channel_at(channelIndex); channelHandle->ud_.ptr = response; - _service->set_option(YOPT_C_REMOTE_ENDPOINT, channelIndex, requestUri.getHost().data(), + _service->set_option(YOPT_C_REMOTE_ENDPOINT, channelIndex, requestUri.getHost().c_str(), (int)requestUri.getPort()); if (requestUri.isSecure()) _service->open(channelIndex, YCK_SSL_CLIENT); @@ -292,7 +292,7 @@ void HttpClient::handleNetworkEvent(yasio::io_event* event) obs.write_bytes(uri.getPath()); if (!usePostData) { - auto query = uri.getQuery(); + auto& query = uri.getQuery(); if (!query.empty()) { obs.write_byte('?'); @@ -530,13 +530,13 @@ int HttpClient::getTimeoutForRead() return _timeoutForRead; } -std::string_view HttpClient::getCookieFilename() +const std::string& HttpClient::getCookieFilename() { std::lock_guard lock(_cookieFileMutex); return _cookieFilename; } -std::string_view HttpClient::getSSLVerification() +const std::string& HttpClient::getSSLVerification() { std::lock_guard lock(_sslCaFileMutex); return _sslCaFilename; diff --git a/cocos/network/HttpClient.h b/cocos/network/HttpClient.h index 36a191fbf6..7d6fd1a7a6 100644 --- a/cocos/network/HttpClient.h +++ b/cocos/network/HttpClient.h @@ -89,21 +89,21 @@ public: * * @return the cookie filename */ - std::string_view getCookieFilename(); + const std::string& getCookieFilename(); /** * Set root certificate path for SSL verification. * * @param caFile a full path of root certificate.if it is empty, SSL verification is disabled. */ - void setSSLVerification(std::string_view caFile); + void setSSLVerification(const std::string& caFile); /** * Get the ssl CA filename * * @return the ssl CA filename */ - std::string_view getSSLVerification(); + const std::string& getSSLVerification(); /** * Send http request concurrently, non-blocking @@ -197,7 +197,7 @@ public: * Sets custom dns server list: * format: "xxx.xxx.xxx.xxx[:port],xxx.xxx.xxx.xxx[:port] */ - void setNameServers(std::string_view servers); + void setNameServers(const std::string& servers); yasio::io_service* getInternalService(); @@ -205,7 +205,7 @@ private: HttpClient(); virtual ~HttpClient(); - void processResponse(HttpResponse* response, std::string_view url); + void processResponse(HttpResponse* response, const std::string& url); int tryTakeAvailChannel(); diff --git a/cocos/network/HttpCookie.cpp b/cocos/network/HttpCookie.cpp index bfe76554e1..be22e571b1 100644 --- a/cocos/network/HttpCookie.cpp +++ b/cocos/network/HttpCookie.cpp @@ -151,11 +151,11 @@ std::string HttpCookie::checkAndGetFormatedMatchCookies(const Uri& uri) return ret; } -bool HttpCookie::updateOrAddCookie(std::string_view cookie, const Uri& uri) +bool HttpCookie::updateOrAddCookie(const std::string& cookie, const Uri& uri) { unsigned int count = 0; CookieInfo info; - xsbase::nzls::fast_split(cookie.data(), cookie.length(), ';', [&](const char* start, const char* end) { + xsbase::nzls::fast_split(cookie.c_str(), cookie.length(), ';', [&](const char* start, const char* end) { unsigned int count_ = 0; while (*start == ' ') ++start; // skip ws @@ -289,7 +289,7 @@ void HttpCookie::writeFile() fclose(out); } -void HttpCookie::setCookieFileName(std::string_view filename) +void HttpCookie::setCookieFileName(const std::string& filename) { _cookieFileName = filename; } diff --git a/cocos/network/HttpCookie.h b/cocos/network/HttpCookie.h index 4ba517d2d2..8e7d116cac 100644 --- a/cocos/network/HttpCookie.h +++ b/cocos/network/HttpCookie.h @@ -90,7 +90,7 @@ public: void readFile(); void writeFile(); - void setCookieFileName(std::string_view fileName); + void setCookieFileName(const std::string& fileName); const std::vector* getCookies() const; const CookieInfo* getMatchCookie(const Uri& uri) const; @@ -98,7 +98,7 @@ public: // Check match cookies for http request std::string checkAndGetFormatedMatchCookies(const Uri& uri); - bool updateOrAddCookie(std::string_view cookie, const Uri& uri); + bool updateOrAddCookie(const std::string& cookie, const Uri& uri); private: std::string _cookieFileName; diff --git a/cocos/network/HttpRequest.h b/cocos/network/HttpRequest.h index 10a5ad0072..2dee876f32 100644 --- a/cocos/network/HttpRequest.h +++ b/cocos/network/HttpRequest.h @@ -125,14 +125,14 @@ public: * * @param url the string object. */ - void setUrl(std::string_view url) { _url = url; } + void setUrl(const std::string& url) { _url = url; } /** * Get the url address of HttpRequest object. * * @return const char* the pointer of _url. */ - std::string_view getUrl() const { return _url; } + const std::string& getUrl() const { return _url; } /** * Set the request data of HttpRequest object. @@ -168,7 +168,7 @@ public: * * @param tag the string object. */ - void setTag(std::string_view tag) { _tag = tag; } + void setTag(const std::string& tag) { _tag = tag; } /** * Get the string tag to identify the request. diff --git a/cocos/network/HttpResponse.h b/cocos/network/HttpResponse.h index 68b3694df6..8909c36440 100644 --- a/cocos/network/HttpResponse.h +++ b/cocos/network/HttpResponse.h @@ -155,7 +155,7 @@ private: * @param value a string pointer that point to response data buffer. * @param n the defined size that the response data buffer would be copied. */ - bool prepareForProcess(std::string_view url) + bool prepareForProcess(const std::string& url) { /* Resets response status */ _finished = false; diff --git a/cocos/network/Uri.cpp b/cocos/network/Uri.cpp index 835738740b..665837fccc 100644 --- a/cocos/network/Uri.cpp +++ b/cocos/network/Uri.cpp @@ -143,7 +143,7 @@ bool Uri::operator==(const Uri& o) const _queryParams == o._queryParams); } -Uri Uri::parse(std::string_view str) +Uri Uri::parse(const std::string& str) { Uri uri; @@ -155,7 +155,7 @@ Uri Uri::parse(std::string_view str) return uri; } -bool Uri::doParse(std::string_view str) +bool Uri::doParse(const std::string& str) { static const std::regex uriRegex( "([a-zA-Z][a-zA-Z0-9+.-]*):" // scheme: @@ -182,7 +182,7 @@ bool Uri::doParse(std::string_view str) std::smatch match; if (UNLIKELY(!std::regex_match(copied.cbegin(), copied.cend(), match, uriRegex))) { - CCLOGERROR("Invalid URI: %s", str.data()); + CCLOGERROR("Invalid URI: %s", str.c_str()); return false; } diff --git a/cocos/network/Uri.h b/cocos/network/Uri.h index de32b98921..aa24b1d924 100644 --- a/cocos/network/Uri.h +++ b/cocos/network/Uri.h @@ -58,7 +58,7 @@ public: /** * Parse a Uri from a string. Throws std::invalid_argument on parse error. */ - static Uri parse(std::string_view str); + static Uri parse(const std::string& str); /** Default constructor */ Uri(); @@ -85,18 +85,18 @@ public: bool isSecure() const { return _isSecure; } /** Gets the scheme name for this URI. */ - std::string_view getScheme() const { return _scheme; } + const std::string& getScheme() const { return _scheme; } /** Gets the user name with the specified URI. */ - std::string_view getUserName() const { return _username; } + const std::string& getUserName() const { return _username; } /** Gets the password with the specified URI. */ - std::string_view getPassword() const { return _password; } + const std::string& getPassword() const { return _password; } /** * Get host part of URI. If host is an IPv6 address, square brackets will be * returned, for example: "[::1]". */ - std::string_view getHost() const { return _host; } + const std::string& getHost() const { return _host; } /** * Get host part of URI. If host is an IPv6 address, square brackets will not * be returned, for exmaple "::1"; otherwise it returns the same thing as @@ -106,29 +106,29 @@ public: * or API that connects to that host/port; e.g. getaddrinfo() only understands * IPv6 host without square brackets */ - std::string_view getHostName() const { return _hostName; } + const std::string& getHostName() const { return _hostName; } /** Gets the port number of the URI. */ uint16_t getPort() const { return _port; } /** Gets the path part of the URI. */ - std::string_view getPath() const { return _path; } + const std::string& getPath() const { return _path; } /// Gets the path, query and fragment parts of the URI. - std::string_view getPathEtc() const { return _pathEtc; } + const std::string& getPathEtc() const { return _pathEtc; } /** Gets the query part of the URI. */ - std::string_view getQuery() const { return _query; } + const std::string& getQuery() const { return _query; } /** Gets the fragment part of the URI */ - std::string_view getFragment() const { return _fragment; } + const std::string& getFragment() const { return _fragment; } /** Gets the authority part (userName, password, host and port) of the URI. * @note If the port number is a well-known port * number for the given scheme (e.g., 80 for http), it * is not included in the authority. */ - std::string_view getAuthority() const { return _authority; } + const std::string& getAuthority() const { return _authority; } /** Gets a string representation of the URI. */ std::string toString() const; @@ -159,7 +159,7 @@ public: void clear(); private: - bool doParse(std::string_view str); + bool doParse(const std::string& str); bool _isValid; bool _isSecure; diff --git a/cocos/physics3d/CCPhysicsSprite3D.cpp b/cocos/physics3d/CCPhysicsSprite3D.cpp index 26a0da9a7f..be3b008054 100644 --- a/cocos/physics3d/CCPhysicsSprite3D.cpp +++ b/cocos/physics3d/CCPhysicsSprite3D.cpp @@ -31,7 +31,7 @@ NS_CC_BEGIN -PhysicsSprite3D* PhysicsSprite3D::create(std::string_view modelPath, +PhysicsSprite3D* PhysicsSprite3D::create(const std::string& modelPath, Physics3DRigidBodyDes* rigidDes, const cocos2d::Vec3& translateInPhysics, const cocos2d::Quaternion& rotInPhsyics) @@ -50,7 +50,7 @@ PhysicsSprite3D* PhysicsSprite3D::create(std::string_view modelPath, return ret; } -PhysicsSprite3D* PhysicsSprite3D::createWithCollider(std::string_view modelPath, +PhysicsSprite3D* PhysicsSprite3D::createWithCollider(const std::string& modelPath, Physics3DColliderDes* colliderDes, const cocos2d::Vec3& translateInPhysics, const cocos2d::Quaternion& rotInPhsyics) diff --git a/cocos/physics3d/CCPhysicsSprite3D.h b/cocos/physics3d/CCPhysicsSprite3D.h index 7e94346f55..3a61876de4 100644 --- a/cocos/physics3d/CCPhysicsSprite3D.h +++ b/cocos/physics3d/CCPhysicsSprite3D.h @@ -48,13 +48,13 @@ class CC_DLL PhysicsSprite3D : public cocos2d::Sprite3D { public: /** creates a PhysicsSprite3D*/ - static PhysicsSprite3D* create(std::string_view modelPath, + static PhysicsSprite3D* create(const std::string& modelPath, Physics3DRigidBodyDes* rigidDes, const cocos2d::Vec3& translateInPhysics = cocos2d::Vec3::ZERO, const cocos2d::Quaternion& rotInPhsyics = cocos2d::Quaternion::ZERO); /** creates a PhysicsSprite3D as a collider*/ - static PhysicsSprite3D* createWithCollider(std::string_view modelPath, + static PhysicsSprite3D* createWithCollider(const std::string& modelPath, Physics3DColliderDes* colliderDes, const cocos2d::Vec3& translateInPhysics = cocos2d::Vec3::ZERO, const cocos2d::Quaternion& rotInPhsyics = cocos2d::Quaternion::ZERO); diff --git a/cocos/platform/CCApplicationProtocol.h b/cocos/platform/CCApplicationProtocol.h index cfb3b0ba04..7bb1e930fd 100644 --- a/cocos/platform/CCApplicationProtocol.h +++ b/cocos/platform/CCApplicationProtocol.h @@ -152,7 +152,7 @@ public: * @js NA * @lua NA */ - virtual bool openURL(std::string_view url) = 0; + virtual bool openURL(const std::string& url) = 0; }; // end of platform group diff --git a/cocos/platform/CCFileStream.h b/cocos/platform/CCFileStream.h index 74caba22bc..e44e74a512 100644 --- a/cocos/platform/CCFileStream.h +++ b/cocos/platform/CCFileStream.h @@ -28,7 +28,7 @@ public: * @param mode File open mode, being READ | WRITE | APPEND * @return true if successful, false if not */ - virtual bool open(std::string_view path, FileStream::Mode mode) = 0; + virtual bool open(const std::string& path, FileStream::Mode mode) = 0; /** * Close a file stream diff --git a/cocos/platform/CCFileUtils.cpp b/cocos/platform/CCFileUtils.cpp index 517cb2fc2e..06fd8061c8 100644 --- a/cocos/platform/CCFileUtils.cpp +++ b/cocos/platform/CCFileUtils.cpp @@ -29,7 +29,6 @@ THE SOFTWARE. #include #include -#include #include "base/CCData.h" #include "base/ccMacros.h" @@ -45,38 +44,9 @@ THE SOFTWARE. #endif #include -#if defined(_WIN32) -# include "ntcvt/ntcvt.hpp" -#endif - -#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS -# include "tinydir/tinydir.h" -#endif - #include "pugixml/pugixml.hpp" - #define DECLARE_GUARD (void)0 -#if CC_TARGET_PLATFORM != CC_PLATFORM_IOS && (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID || (defined(__NDK_MAJOR__) && __NDK_MAJOR__ >= 22) ) -# define ADXE_HAVE_STDFS 1 -# include -namespace stdfs = std::filesystem; -# if defined(_WIN32) -inline stdfs::path toFspath(const std::string_view& pathSV) -{ - return stdfs::path{ntcvt::from_chars(pathSV)}; -} -# else -inline stdfs::path toFspath(const std::string_view& pathSV) -{ - return stdfs::path{pathSV}; -} -# endif -#else -# include "tinydir/tinydir.h" -# define ADXE_HAVE_STDFS 0 -#endif - NS_CC_BEGIN // Implement DictMaker @@ -122,7 +92,7 @@ public: ~DictMaker() {} - ValueMap dictionaryWithContentsOfFile(std::string_view fileName) + ValueMap dictionaryWithContentsOfFile(const std::string& fileName) { _resultType = SAX_RESULT_DICT; SAXParser parser; @@ -146,7 +116,7 @@ public: return _rootDict; } - ValueVector arrayWithContentsOfFile(std::string_view fileName) + ValueVector arrayWithContentsOfFile(const std::string& fileName) { _resultType = SAX_RESULT_ARRAY; SAXParser parser; @@ -186,9 +156,9 @@ public: { // add a new dictionary into the pre dictionary CCASSERT(!_dictStack.empty(), "The state is wrong!"); - ValueMap* preDict = _dictStack.top(); - auto& curVal = hlookup::set_item(*preDict, _curKey, Value(ValueMap()))->second; - _curDict = &curVal.asValueMap(); + ValueMap* preDict = _dictStack.top(); + (*preDict)[_curKey] = Value(ValueMap()); + _curDict = &(*preDict)[_curKey].asValueMap(); } // record the dict state @@ -351,7 +321,7 @@ public: } }; -ValueMap FileUtils::getValueMapFromFile(std::string_view filename) const +ValueMap FileUtils::getValueMapFromFile(const std::string& filename) const { const std::string fullPath = fullPathForFilename(filename); DictMaker tMaker; @@ -364,7 +334,7 @@ ValueMap FileUtils::getValueMapFromData(const char* filedata, int filesize) cons return tMaker.dictionaryWithDataOfFile(filedata, filesize); } -ValueVector FileUtils::getValueVectorFromFile(std::string_view filename) const +ValueVector FileUtils::getValueVectorFromFile(const std::string& filename) const { const std::string fullPath = fullPathForFilename(filename); DictMaker tMaker; @@ -380,12 +350,12 @@ static void generateElementForDict(const ValueMap& dict, pugi::xml_node& innerDi /* * Use pugixml to write plist files */ -bool FileUtils::writeToFile(const ValueMap& dict, std::string_view fullPath) const +bool FileUtils::writeToFile(const ValueMap& dict, const std::string& fullPath) const { return writeValueMapToFile(dict, fullPath); } -bool FileUtils::writeValueMapToFile(const ValueMap& dict, std::string_view fullPath) const +bool FileUtils::writeValueMapToFile(const ValueMap& dict, const std::string& fullPath) const { pugi::xml_document doc; doc.load_string(R"( @@ -401,7 +371,7 @@ bool FileUtils::writeValueMapToFile(const ValueMap& dict, std::string_view fullP return writeStringToFile(ss.str(), fullPath); } -bool FileUtils::writeValueVectorToFile(const ValueVector& vecData, std::string_view fullPath) const +bool FileUtils::writeValueVectorToFile(const ValueVector& vecData, const std::string& fullPath) const { pugi::xml_document doc; doc.load_string(R"( @@ -490,37 +460,35 @@ FileUtils::FileUtils() : _writablePath("") {} FileUtils::~FileUtils() {} -bool FileUtils::writeStringToFile(std::string_view dataStr, std::string_view fullPath) const +bool FileUtils::writeStringToFile(const std::string& dataStr, const std::string& fullPath) const { - return FileUtils::writeBinaryToFile(dataStr.data(), dataStr.size(), fullPath); + return FileUtils::writeBinaryToFile(dataStr.c_str(), dataStr.size(), fullPath); } void FileUtils::writeStringToFile(std::string dataStr, - std::string_view fullPath, + const std::string& fullPath, std::function callback) const { performOperationOffthread( - [path = std::string{fullPath}](std::string_view dataStrIn) -> bool { - return FileUtils::getInstance()->writeStringToFile(dataStrIn, path); + [fullPath](const std::string& dataStrIn) -> bool { + return FileUtils::getInstance()->writeStringToFile(dataStrIn, fullPath); }, std::move(callback), std::move(dataStr)); } -bool FileUtils::writeDataToFile(const Data& data, std::string_view fullPath) const +bool FileUtils::writeDataToFile(const Data& data, const std::string& fullPath) const { return FileUtils::writeBinaryToFile(data.getBytes(), data.getSize(), fullPath); } -void FileUtils::writeDataToFile(Data data, std::string_view fullPath, std::function callback) const +void FileUtils::writeDataToFile(Data data, const std::string& fullPath, std::function callback) const { performOperationOffthread( - [path = std::string{fullPath}](const Data& dataIn) -> bool { - return FileUtils::getInstance()->writeDataToFile(dataIn, path); - }, + [fullPath](const Data& dataIn) -> bool { return FileUtils::getInstance()->writeDataToFile(dataIn, fullPath); }, std::move(callback), std::move(data)); } -bool FileUtils::writeBinaryToFile(const void* data, size_t dataSize, std::string_view fullPath) +bool FileUtils::writeBinaryToFile(const void* data, size_t dataSize, const std::string& fullPath) { CCASSERT(!fullPath.empty() && dataSize > 0, "Invalid parameters."); @@ -553,39 +521,38 @@ void FileUtils::purgeCachedEntries() _fullPathCacheDir.clear(); } -std::string FileUtils::getStringFromFile(std::string_view filename) const +std::string FileUtils::getStringFromFile(const std::string& filename) const { std::string s; getContents(filename, &s); return s; } -void FileUtils::getStringFromFile(std::string_view path, std::function callback) const +void FileUtils::getStringFromFile(const std::string& path, std::function callback) const { // Get the full path on the main thread, to avoid the issue that FileUtil's is not // thread safe, and accessing the fullPath cache and searching the search paths is not thread safe auto fullPath = fullPathForFilename(path); performOperationOffthread( - [path = std::string{fullPath}]() -> std::string { return FileUtils::getInstance()->getStringFromFile(path); }, + [fullPath]() -> std::string { return FileUtils::getInstance()->getStringFromFile(fullPath); }, std::move(callback)); } -Data FileUtils::getDataFromFile(std::string_view filename) const +Data FileUtils::getDataFromFile(const std::string& filename) const { Data d; getContents(filename, &d); return d; } -void FileUtils::getDataFromFile(std::string_view filename, std::function callback) const +void FileUtils::getDataFromFile(const std::string& filename, std::function callback) const { auto fullPath = fullPathForFilename(filename); - performOperationOffthread( - [path = std::string{fullPath}]() -> Data { return FileUtils::getInstance()->getDataFromFile(path); }, - std::move(callback)); + performOperationOffthread([fullPath]() -> Data { return FileUtils::getInstance()->getDataFromFile(fullPath); }, + std::move(callback)); } -FileUtils::Status FileUtils::getContents(std::string_view filename, ResizableBuffer* buffer) const +FileUtils::Status FileUtils::getContents(const std::string& filename, ResizableBuffer* buffer) const { if (filename.empty()) return Status::NotExists; @@ -623,28 +590,30 @@ FileUtils::Status FileUtils::getContents(std::string_view filename, ResizableBuf return Status::OK; } -void FileUtils::writeValueMapToFile(ValueMap dict, std::string_view fullPath, std::function callback) const +void FileUtils::writeValueMapToFile(ValueMap dict, + const std::string& fullPath, + std::function callback) const { performOperationOffthread( - [path = std::string{fullPath}](const ValueMap& dictIn) -> bool { - return FileUtils::getInstance()->writeValueMapToFile(dictIn, path); + [fullPath](const ValueMap& dictIn) -> bool { + return FileUtils::getInstance()->writeValueMapToFile(dictIn, fullPath); }, std::move(callback), std::move(dict)); } void FileUtils::writeValueVectorToFile(ValueVector vecData, - std::string_view fullPath, + const std::string& fullPath, std::function callback) const { performOperationOffthread( - [path = std::string{fullPath}](const ValueVector& vecDataIn) -> bool { - return FileUtils::getInstance()->writeValueVectorToFile(vecDataIn, path); + [fullPath](const ValueVector& vecDataIn) -> bool { + return FileUtils::getInstance()->writeValueVectorToFile(vecDataIn, fullPath); }, std::move(callback), std::move(vecData)); } -std::string FileUtils::getNewFilename(std::string_view filename) const +std::string FileUtils::getNewFilename(const std::string& filename) const { std::string newFileName; @@ -664,13 +633,13 @@ std::string FileUtils::getNewFilename(std::string_view filename) const return newFileName; } -std::string FileUtils::getPathForFilename(std::string_view filename, - std::string_view resolutionDirectory, - std::string_view searchPath) const +std::string FileUtils::getPathForFilename(const std::string& filename, + const std::string& resolutionDirectory, + const std::string& searchPath) const { - auto file = filename; - std::string_view file_path = hlookup::empty_sv; - size_t pos = filename.find_last_of('/'); + std::string file = filename; + std::string file_path = ""; + size_t pos = filename.find_last_of('/'); if (pos != std::string::npos) { file_path = filename.substr(0, pos + 1); @@ -678,7 +647,7 @@ std::string FileUtils::getPathForFilename(std::string_view filename, } // searchPath + file_path + resourceDirectory - std::string path{searchPath}; + std::string path = searchPath; path += file_path; path += resolutionDirectory; @@ -687,14 +656,14 @@ std::string FileUtils::getPathForFilename(std::string_view filename, return path; } -std::string FileUtils::getPathForDirectory(std::string_view dir, - std::string_view resolutionDiretory, - std::string_view searchPath) const +std::string FileUtils::getPathForDirectory(const std::string& dir, + const std::string& resolutionDiretory, + const std::string& searchPath) const { - return std::string{searchPath}.append(resolutionDiretory).append(dir); + return searchPath + resolutionDiretory + dir; } -std::string FileUtils::fullPathForFilename(std::string_view filename) const +std::string FileUtils::fullPathForFilename(const std::string& filename) const { DECLARE_GUARD; @@ -712,7 +681,7 @@ std::string FileUtils::fullPathForFilename(std::string_view filename) const */ if (isAbsolutePath(filename)) { - return std::string{filename}; + return filename; } // Already Cached ? @@ -744,14 +713,14 @@ std::string FileUtils::fullPathForFilename(std::string_view filename) const if (isPopupNotify()) { - CCLOG("cocos2d: fullPathForFilename: No file found at %s. Possible missing file.", filename.data()); + CCLOG("cocos2d: fullPathForFilename: No file found at %s. Possible missing file.", filename.c_str()); } // The file wasn't found, return empty string. - return std::string{}; + return ""; } -std::string FileUtils::fullPathForDirectory(std::string_view dir) const +std::string FileUtils::fullPathForDirectory(const std::string& dir) const { DECLARE_GUARD; @@ -762,7 +731,7 @@ std::string FileUtils::fullPathForDirectory(std::string_view dir) const if (isAbsolutePath(dir)) { - return std::string{dir}; + return dir; } // Already Cached ? @@ -771,7 +740,7 @@ std::string FileUtils::fullPathForDirectory(std::string_view dir) const { return cacheIter->second; } - std::string longdir{dir}; + std::string longdir = dir; std::string fullpath; if (longdir[longdir.length() - 1] != '/') @@ -797,16 +766,16 @@ std::string FileUtils::fullPathForDirectory(std::string_view dir) const if (isPopupNotify()) { - CCLOG("cocos2d: fullPathForDirectory: No directory found at %s. Possible missing directory.", dir.data()); + CCLOG("cocos2d: fullPathForDirectory: No directory found at %s. Possible missing directory.", dir.c_str()); } // The file wasn't found, return empty string. return ""; } -std::string FileUtils::fullPathFromRelativeFile(std::string_view filename, std::string_view relativeFile) const +std::string FileUtils::fullPathFromRelativeFile(const std::string& filename, const std::string& relativeFile) const { - return std::string{relativeFile.substr(0, relativeFile.rfind('/') + 1)}.append(getNewFilename(filename)); + return relativeFile.substr(0, relativeFile.rfind('/') + 1) + getNewFilename(filename); } void FileUtils::setSearchResolutionsOrder(const std::vector& searchResolutionsOrder) @@ -826,7 +795,7 @@ void FileUtils::setSearchResolutionsOrder(const std::vector& search for (const auto& iter : searchResolutionsOrder) { std::string resolutionDirectory = iter; - if (!existDefault && resolutionDirectory.empty()) + if (!existDefault && resolutionDirectory == "") { existDefault = true; } @@ -845,12 +814,12 @@ void FileUtils::setSearchResolutionsOrder(const std::vector& search } } -void FileUtils::addSearchResolutionsOrder(std::string_view order, const bool front) +void FileUtils::addSearchResolutionsOrder(const std::string& order, const bool front) { DECLARE_GUARD; - std::string resOrder{order}; + std::string resOrder = order; if (!resOrder.empty() && resOrder[resOrder.length() - 1] != '/') resOrder.push_back('/'); @@ -882,7 +851,7 @@ const std::vector FileUtils::getOriginalSearchPaths() const return _originalSearchPaths; } -void FileUtils::setWritablePath(std::string_view writablePath) +void FileUtils::setWritablePath(const std::string& writablePath) { DECLARE_GUARD; _writablePath = writablePath; @@ -894,7 +863,7 @@ const std::string FileUtils::getDefaultResourceRootPath() const return _defaultResRootPath; } -void FileUtils::setDefaultResourceRootPath(std::string_view path) +void FileUtils::setDefaultResourceRootPath(const std::string& path) { DECLARE_GUARD; if (_defaultResRootPath != path) @@ -950,14 +919,14 @@ void FileUtils::setSearchPaths(const std::vector& searchPaths) } } -void FileUtils::addSearchPath(std::string_view searchpath, const bool front) +void FileUtils::addSearchPath(const std::string& searchpath, const bool front) { DECLARE_GUARD; - std::string path; + std::string prefix; if (!isAbsolutePath(searchpath)) - path = _defaultResRootPath; + prefix = _defaultResRootPath; - path.append(searchpath); + std::string path = prefix + searchpath; if (!path.empty() && path[path.length() - 1] != '/') { path += "/"; @@ -965,13 +934,13 @@ void FileUtils::addSearchPath(std::string_view searchpath, const bool front) if (front) { - _originalSearchPaths.insert(_originalSearchPaths.begin(), std::string{searchpath}); - _searchPathArray.insert(_searchPathArray.begin(), std::move(path)); + _originalSearchPaths.insert(_originalSearchPaths.begin(), searchpath); + _searchPathArray.insert(_searchPathArray.begin(), path); } else { - _originalSearchPaths.push_back(std::string{searchpath}); - _searchPathArray.push_back(std::move(path)); + _originalSearchPaths.push_back(searchpath); + _searchPathArray.push_back(path); } } @@ -983,7 +952,7 @@ void FileUtils::setFilenameLookupDictionary(const ValueMap& filenameLookupDict) _filenameLookupDict = filenameLookupDict; } -void FileUtils::loadFilenameLookupDictionaryFromFile(std::string_view filename) +void FileUtils::loadFilenameLookupDictionaryFromFile(const std::string& filename) { const std::string fullPath = fullPathForFilename(filename); if (!fullPath.empty()) @@ -996,7 +965,7 @@ void FileUtils::loadFilenameLookupDictionaryFromFile(std::string_view filename) if (version != 1) { CCLOG("cocos2d: ERROR: Invalid filenameLookup dictionary version: %d. Filename: %s", version, - filename.data()); + filename.c_str()); return; } setFilenameLookupDictionary(dict["filenames"].asValueMap()); @@ -1004,12 +973,12 @@ void FileUtils::loadFilenameLookupDictionaryFromFile(std::string_view filename) } } -std::string FileUtils::getFullPathForFilenameWithinDirectory(std::string_view directory, - std::string_view filename) const +std::string FileUtils::getFullPathForFilenameWithinDirectory(const std::string& directory, + const std::string& filename) const { // get directory+filename, safely adding '/' as necessary - std::string ret{directory}; - if (!directory.empty() && directory[directory.size() - 1] != '/') + std::string ret = directory; + if (directory.size() && directory[directory.size() - 1] != '/') { ret += '/'; } @@ -1017,12 +986,12 @@ std::string FileUtils::getFullPathForFilenameWithinDirectory(std::string_view di // if the file doesn't exist, return an empty string if (!isFileExistInternal(ret)) { - ret.clear(); + ret = ""; } return ret; } -bool FileUtils::isFileExist(std::string_view filename) const +bool FileUtils::isFileExist(const std::string& filename) const { if (isAbsolutePath(filename)) { @@ -1038,20 +1007,19 @@ bool FileUtils::isFileExist(std::string_view filename) const } } -void FileUtils::isFileExist(std::string_view filename, std::function callback) const +void FileUtils::isFileExist(const std::string& filename, std::function callback) const { auto fullPath = fullPathForFilename(filename); - performOperationOffthread( - [path = std::string{fullPath}]() -> bool { return FileUtils::getInstance()->isFileExist(path); }, - std::move(callback)); + performOperationOffthread([fullPath]() -> bool { return FileUtils::getInstance()->isFileExist(fullPath); }, + std::move(callback)); } -bool FileUtils::isAbsolutePath(std::string_view path) const +bool FileUtils::isAbsolutePath(const std::string& path) const { return isAbsolutePathInternal(path); } -bool FileUtils::isAbsolutePathInternal(std::string_view path) +bool FileUtils::isAbsolutePathInternal(const std::string& path) { #if defined(_WIN32) // see also: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file?redirectedfrom=MSDN @@ -1066,7 +1034,7 @@ bool FileUtils::isAbsolutePathInternal(std::string_view path) #endif } -bool FileUtils::isDirectoryExist(std::string_view dirPath) const +bool FileUtils::isDirectoryExist(const std::string& dirPath) const { CCASSERT(!dirPath.empty(), "Invalid path"); @@ -1083,87 +1051,79 @@ bool FileUtils::isDirectoryExist(std::string_view dirPath) const } } -void FileUtils::isDirectoryExist(std::string_view fullPath, std::function callback) const +void FileUtils::isDirectoryExist(const std::string& fullPath, std::function callback) const { CCASSERT(isAbsolutePath(fullPath), "Async isDirectoryExist only accepts absolute file paths"); - performOperationOffthread( - [path = std::string{fullPath}]() -> bool { return FileUtils::getInstance()->isDirectoryExist(path); }, - std::move(callback)); -} - -void FileUtils::createDirectory(std::string_view dirPath, std::function callback) const -{ - performOperationOffthread( - [path = std::string{dirPath}]() -> bool { return FileUtils::getInstance()->createDirectory(path); }, - std::move(callback)); -} - -void FileUtils::removeDirectory(std::string_view dirPath, std::function callback) const -{ - performOperationOffthread( - [path = std::string{dirPath}]() -> bool { return FileUtils::getInstance()->removeDirectory(path); }, - std::move(callback)); -} - -void FileUtils::removeFile(std::string_view filepath, std::function callback) const -{ - auto fullPath = fullPathForFilename(filepath); - performOperationOffthread( - [path = std::string{fullPath}]() -> bool { return FileUtils::getInstance()->removeFile(path); }, - std::move(callback)); -} - -void FileUtils::renameFile(std::string_view path, - std::string_view oldname, - std::string_view name, - std::function callback) const -{ - performOperationOffthread( - [path = std::string{path}, oldname = std::string{oldname}, name = std::string{name}]() -> bool { - return FileUtils::getInstance()->renameFile(path, oldname, name); - }, - std::move(callback)); -} - -void FileUtils::renameFile(std::string_view oldfullpath, - std::string_view newfullpath, - std::function callback) const -{ - performOperationOffthread( - [oldpath = std::string{oldfullpath}, newpath = std::string{newfullpath}]() { - return FileUtils::getInstance()->renameFile(oldpath, newpath); - }, - std::move(callback)); -} - -void FileUtils::getFileSize(std::string_view filepath, std::function callback) const -{ - auto fullPath = fullPathForFilename(filepath); - performOperationOffthread([path = std::string{fullPath}]() { return FileUtils::getInstance()->getFileSize(path); }, + performOperationOffthread([fullPath]() -> bool { return FileUtils::getInstance()->isDirectoryExist(fullPath); }, std::move(callback)); } -void FileUtils::listFilesAsync(std::string_view dirPath, std::function)> callback) const +void FileUtils::createDirectory(const std::string& dirPath, std::function callback) const +{ + performOperationOffthread([dirPath]() -> bool { return FileUtils::getInstance()->createDirectory(dirPath); }, + std::move(callback)); +} + +void FileUtils::removeDirectory(const std::string& dirPath, std::function callback) const +{ + performOperationOffthread([dirPath]() -> bool { return FileUtils::getInstance()->removeDirectory(dirPath); }, + std::move(callback)); +} + +void FileUtils::removeFile(const std::string& filepath, std::function callback) const +{ + auto fullPath = fullPathForFilename(filepath); + performOperationOffthread([fullPath]() -> bool { return FileUtils::getInstance()->removeFile(fullPath); }, + std::move(callback)); +} + +void FileUtils::renameFile(const std::string& path, + const std::string& oldname, + const std::string& name, + std::function callback) const +{ + performOperationOffthread( + [path, oldname, name]() -> bool { return FileUtils::getInstance()->renameFile(path, oldname, name); }, + std::move(callback)); +} + +void FileUtils::renameFile(const std::string& oldfullpath, + const std::string& newfullpath, + std::function callback) const +{ + performOperationOffthread( + [oldfullpath, newfullpath]() { return FileUtils::getInstance()->renameFile(oldfullpath, newfullpath); }, + std::move(callback)); +} + +void FileUtils::getFileSize(const std::string& filepath, std::function callback) const +{ + auto fullPath = fullPathForFilename(filepath); + performOperationOffthread([fullPath]() { return FileUtils::getInstance()->getFileSize(fullPath); }, + std::move(callback)); +} + +void FileUtils::listFilesAsync(const std::string& dirPath, std::function)> callback) const { auto fullPath = fullPathForDirectory(dirPath); - performOperationOffthread([path = std::string{fullPath}]() { return FileUtils::getInstance()->listFiles(path); }, + performOperationOffthread([fullPath]() { return FileUtils::getInstance()->listFiles(fullPath); }, std::move(callback)); } -void FileUtils::listFilesRecursivelyAsync(std::string_view dirPath, +void FileUtils::listFilesRecursivelyAsync(const std::string& dirPath, std::function)> callback) const { auto fullPath = fullPathForDirectory(dirPath); performOperationOffthread( - [path = std::string{fullPath}]() { + [fullPath]() { std::vector retval; - FileUtils::getInstance()->listFilesRecursively(path, &retval); + FileUtils::getInstance()->listFilesRecursively(fullPath, &retval); return retval; }, std::move(callback)); } -std::unique_ptr FileUtils::openFileStream(std::string_view filePath, FileStream::Mode mode) +std::unique_ptr FileUtils::openFileStream(const std::string& filePath, FileStream::Mode mode) { PosixFileStream fs; @@ -1175,80 +1135,252 @@ std::unique_ptr FileUtils::openFileStream(std::string_view filePath, return nullptr; } -/* !!!Notes for c++fs - a. ios: require ios 13.0+ - b. android: require ndk-r22+ -*/ -#if ADXE_HAVE_STDFS -std::vector FileUtils::listFiles(std::string_view dirPath) const +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) +// windows os implement should override in platform specific FileUtiles class +bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const { - const auto fullPath = fullPathForDirectory(dirPath); - auto fsPath = toFspath(fullPath); - if (!stdfs::is_directory(fsPath)) - { - return {}; - } - std::vector files = {}; - for (const auto& entry : stdfs::directory_iterator(fsPath)) - { - const auto isDir = entry.is_directory(); - if (isDir || entry.is_regular_file()) - { -# if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) -# if defined(__cpp_lib_char8_t) - std::u8string u8path = entry.path().u8string(); - std::string pathStr = {u8path.begin(), u8path.end()}; -# else - std::string pathStr = entry.path().u8string(); -# endif - std::replace(pathStr.begin(), pathStr.end(), '\\', '/'); -# else - std::string pathStr = entry.path().string(); -# endif - if (isDir) - { - pathStr += '/'; - } - files.emplace_back(std::move(pathStr)); - } - } - return files; + CCASSERT(false, "FileUtils not support isDirectoryExistInternal"); + return false; } -void FileUtils::listFilesRecursively(std::string_view dirPath, std::vector* files) const +bool FileUtils::createDirectory(const std::string& path) const { - const auto fullPath = fullPathForDirectory(dirPath); - auto fsPath = toFspath(fullPath); - if (!stdfs::is_directory(fsPath)) - { - return; - } - for (const auto& entry : stdfs::recursive_directory_iterator(fsPath)) - { - const auto isDir = entry.is_directory(); - if (isDir || entry.is_regular_file()) - { -# if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) -# if defined(__cpp_lib_char8_t) - std::u8string u8path = entry.path().u8string(); - std::string pathStr = {u8path.begin(), u8path.end()}; -# else - std::string pathStr = entry.path().u8string(); -# endif - std::replace(pathStr.begin(), pathStr.end(), '\\', '/'); -# else - std::string pathStr = entry.path().string(); + CCASSERT(false, "FileUtils not support createDirectory"); + return false; +} + +bool FileUtils::removeDirectory(const std::string& path) const +{ + CCASSERT(false, "FileUtils not support removeDirectory"); + return false; +} + +bool FileUtils::removeFile(const std::string& path) const +{ + CCASSERT(false, "FileUtils not support removeFile"); + return false; +} + +bool FileUtils::renameFile(const std::string& oldfullpath, const std::string& newfullpath) const +{ + CCASSERT(false, "FileUtils not support renameFile"); + return false; +} + +bool FileUtils::renameFile(const std::string& path, const std::string& oldname, const std::string& name) const +{ + CCASSERT(false, "FileUtils not support renameFile"); + return false; +} + +int64_t FileUtils::getFileSize(const std::string& filepath) const +{ + CCASSERT(false, "getFileSize should be override by platform FileUtils"); + return 0; +} + +std::vector FileUtils::listFiles(const std::string& dirPath) const +{ + CCASSERT(false, "FileUtils not support listFiles"); + return std::vector(); +} + +void FileUtils::listFilesRecursively(const std::string& dirPath, std::vector* files) const +{ + CCASSERT(false, "FileUtils not support listFilesRecursively"); + return; +} + +#else +# include "tinydir/tinydir.h" +// default implements for unix like os +# include +# include +# include + +// android doesn't have ftw.h +# if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) +# include # endif - if (isDir) + +bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const +{ + struct stat st; + if (stat(dirPath.c_str(), &st) == 0) + { + return S_ISDIR(st.st_mode); + } + return false; +} + +bool FileUtils::createDirectory(const std::string& path) const +{ + CCASSERT(!path.empty(), "Invalid path"); + + if (isDirectoryExist(path)) + return true; + + // Split the path + size_t start = 0; + size_t found = path.find_first_of("/\\", start); + std::string subpath; + std::vector dirs; + + if (found != std::string::npos) + { + while (true) + { + subpath = path.substr(start, found - start + 1); + if (!subpath.empty()) + dirs.push_back(subpath); + start = found + 1; + found = path.find_first_of("/\\", start); + if (found == std::string::npos) { - pathStr += '/'; + if (start < path.length()) + { + dirs.push_back(path.substr(start)); + } + break; } - files->emplace_back(std::move(pathStr)); } } + + DIR* dir = NULL; + + // Create path recursively + subpath = ""; + for (const auto& iter : dirs) + { + subpath += iter; + dir = opendir(subpath.c_str()); + + if (!dir) + { + // directory doesn't exist, should create a new one + + int ret = mkdir(subpath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO); + if (ret != 0 && (errno != EEXIST)) + { + // current directory can not be created, sub directories can not be created too + // should return + return false; + } + } + else + { + // directory exists, should close opened dir + closedir(dir); + } + } + return true; } -#else -std::vector FileUtils::listFiles(std::string_view dirPath) const + +namespace +{ +# if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) +int unlink_cb(const char* fpath, const struct stat* sb, int typeflag, struct FTW* ftwbuf) +{ + int rv = remove(fpath); + + if (rv) + perror(fpath); + + return rv; +} +# endif +} // namespace + +bool FileUtils::removeDirectory(const std::string& path) const +{ +# if !defined(CC_TARGET_OS_TVOS) + +# if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) + if (nftw(path.c_str(), unlink_cb, 64, FTW_DEPTH | FTW_PHYS) == -1) + return false; + else + return true; +# else + std::string command = "rm -r "; + // Path may include space. + command += "\"" + path + "\""; + if (system(command.c_str()) >= 0) + return true; + else + return false; +# endif // (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) + +# else + return false; +# endif // !defined(CC_TARGET_OS_TVOS) +} + +bool FileUtils::removeFile(const std::string& path) const +{ + if (remove(path.c_str())) + { + return false; + } + else + { + return true; + } +} + +bool FileUtils::renameFile(const std::string& oldfullpath, const std::string& newfullpath) const +{ + CCASSERT(!oldfullpath.empty(), "Invalid path"); + CCASSERT(!newfullpath.empty(), "Invalid path"); + + int errorCode = rename(oldfullpath.c_str(), newfullpath.c_str()); + + if (0 != errorCode) + { + CCLOGERROR("Fail to rename file %s to %s !Error code is %d", oldfullpath.c_str(), newfullpath.c_str(), + errorCode); + return false; + } + return true; +} + +bool FileUtils::renameFile(const std::string& path, const std::string& oldname, const std::string& name) const +{ + CCASSERT(!path.empty(), "Invalid path"); + std::string oldPath = path + oldname; + std::string newPath = path + name; + + return this->renameFile(oldPath, newPath); +} + +int64_t FileUtils::getFileSize(const std::string& filepath) const +{ + CCASSERT(!filepath.empty(), "Invalid path"); + + std::string fullpath = filepath; + if (!isAbsolutePath(filepath)) + { + fullpath = fullPathForFilename(filepath); + if (fullpath.empty()) + return 0; + } + + struct stat info; + // Get data associated with "crt_stat.c": + int result = ::stat(fullpath.c_str(), &info); + + // Check if statistics are valid: + if (result != 0) + { + // Failed + return -1; + } + else + { + return info.st_size; + } +} + +std::vector FileUtils::listFiles(const std::string& dirPath) const { std::vector files; std::string fullpath = fullPathForDirectory(dirPath); @@ -1289,7 +1421,7 @@ std::vector FileUtils::listFiles(std::string_view dirPath) const return files; } -void FileUtils::listFilesRecursively(std::string_view dirPath, std::vector* files) const +void FileUtils::listFilesRecursively(const std::string& dirPath, std::vector* files) const { std::string fullpath = fullPathForDirectory(dirPath); if (isDirectoryExist(fullpath)) @@ -1333,244 +1465,6 @@ void FileUtils::listFilesRecursively(std::string_view dirPath, std::vector -# include -# include - -// android doesn't have ftw.h -# if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) -# include -# endif - -bool FileUtils::isDirectoryExistInternal(std::string_view dirPath) const -{ - struct stat st; - if (stat(dirPath.data(), &st) == 0) - { - return S_ISDIR(st.st_mode); - } - return false; -} - -bool FileUtils::createDirectory(std::string_view path) const -{ - CCASSERT(!path.empty(), "Invalid path"); - - if (isDirectoryExist(path)) - return true; - - // Split the path - size_t start = 0; - size_t found = path.find_first_of("/\\", start); - std::string_view subpath; - std::vector dirs; - - if (found != std::string::npos) - { - while (true) - { - subpath = path.substr(start, found - start + 1); - if (!subpath.empty()) - dirs.push_back(std::string{subpath}); - start = found + 1; - found = path.find_first_of("/\\", start); - if (found == std::string::npos) - { - if (start < path.length()) - { - dirs.push_back(std::string{path.substr(start)}); - } - break; - } - } - } - - DIR* dir = NULL; - - // Create path recursively - std::string strSubpath; - for (const auto& iter : dirs) - { - strSubpath += iter; - dir = opendir(strSubpath.c_str()); - - if (!dir) - { - // directory doesn't exist, should create a new one - - int ret = mkdir(strSubpath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO); - if (ret != 0 && (errno != EEXIST)) - { - // current directory can not be created, sub directories can not be created too - // should return - return false; - } - } - else - { - // directory exists, should close opened dir - closedir(dir); - } - } - return true; -} - -namespace -{ -# if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) -int unlink_cb(const char* fpath, const struct stat* sb, int typeflag, struct FTW* ftwbuf) -{ - int rv = remove(fpath); - - if (rv) - perror(fpath); - - return rv; -} -# endif -} // namespace - -bool FileUtils::removeDirectory(std::string_view path) const -{ -# if !defined(CC_TARGET_OS_TVOS) - -# if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) - if (nftw(path.data(), unlink_cb, 64, FTW_DEPTH | FTW_PHYS) == -1) - return false; - else - return true; -# else - std::string command = "rm -r \""s; - // Path may include space. - command.append(path).append("\"", 1); - if (system(command.c_str()) >= 0) - return true; - else - return false; -# endif // (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) - -# else - return false; -# endif // !defined(CC_TARGET_OS_TVOS) -} - -bool FileUtils::removeFile(std::string_view path) const -{ - if (remove(path.data())) - { - return false; - } - else - { - return true; - } -} - -bool FileUtils::renameFile(std::string_view oldfullpath, std::string_view newfullpath) const -{ - CCASSERT(!oldfullpath.empty(), "Invalid path"); - CCASSERT(!newfullpath.empty(), "Invalid path"); - - int errorCode = rename(oldfullpath.data(), newfullpath.data()); - - if (0 != errorCode) - { - CCLOGERROR("Fail to rename file %s to %s !Error code is %d", oldfullpath.data(), newfullpath.data(), errorCode); - return false; - } - return true; -} - -bool FileUtils::renameFile(std::string_view path, std::string_view oldname, std::string_view name) const -{ - CCASSERT(!path.empty(), "Invalid path"); - std::string oldPath{path}; - oldPath += oldname; - std::string newPath{path}; - newPath += name; - - return this->renameFile(oldPath, newPath); -} - -int64_t FileUtils::getFileSize(std::string_view filepath) const -{ - CCASSERT(!filepath.empty(), "Invalid path"); - - std::string_view path; - std::string fullpath; - if (!isAbsolutePath(filepath)) - { - fullpath = fullPathForFilename(filepath); - if (fullpath.empty()) - return 0; - path = fullpath; - } - else - path = filepath; - - struct stat info; - // Get data associated with "crt_stat.c": - int result = ::stat(path.data(), &info); - - // Check if statistics are valid: - if (result != 0) - { - // Failed - return -1; - } - else - { - return info.st_size; - } -} #endif @@ -1589,7 +1483,7 @@ bool FileUtils::isPopupNotify() const return s_popupNotify; } -std::string FileUtils::getFileExtension(std::string_view filePath) const +std::string FileUtils::getFileExtension(const std::string& filePath) const { std::string fileExtension; size_t pos = filePath.find_last_of('.'); @@ -1603,16 +1497,16 @@ std::string FileUtils::getFileExtension(std::string_view filePath) const return fileExtension; } -std::string FileUtils::getFileShortName(std::string_view filePath) +std::string FileUtils::getFileShortName(const std::string& filePath) { - // std::string fileExtension; + std::string fileExtension; size_t pos = filePath.find_last_of("/\\"); if (pos != std::string::npos) { - return std::string{filePath.substr(pos + 1)}; + return filePath.substr(pos + 1); } - return std::string{filePath}; + return filePath; } void FileUtils::valueMapCompact(ValueMap& /*valueMap*/) const {} diff --git a/cocos/platform/CCFileUtils.h b/cocos/platform/CCFileUtils.h index 0e82201e78..3376b9035d 100644 --- a/cocos/platform/CCFileUtils.h +++ b/cocos/platform/CCFileUtils.h @@ -157,7 +157,7 @@ public: /** * Gets string from a file. */ - virtual std::string getStringFromFile(std::string_view filename) const; + virtual std::string getStringFromFile(const std::string& filename) const; /** * Gets string from a file, async off the main cocos thread @@ -166,13 +166,13 @@ public: * @param callback Function that will be called when file is read. Will be called * on the main cocos thread. */ - virtual void getStringFromFile(std::string_view path, std::function callback) const; + virtual void getStringFromFile(const std::string& path, std::function callback) const; /** * Creates binary data from a file. * @return A data object. */ - virtual Data getDataFromFile(std::string_view filename) const; + virtual Data getDataFromFile(const std::string& filename) const; /** * Gets a binary data object from a file, async off the main cocos thread. @@ -181,7 +181,7 @@ public: * @param callback Function that will be called when file is read. Will be called * on the main cocos thread. */ - virtual void getDataFromFile(std::string_view filename, std::function callback) const; + virtual void getDataFromFile(const std::string& filename, std::function callback) const; enum class Status { @@ -255,12 +255,12 @@ public: template >::value>::type> - Status getContents(std::string_view filename, T* buffer) const + Status getContents(const std::string& filename, T* buffer) const { ResizableBufferAdapter buf(buffer); return getContents(filename, &buf); } - virtual Status getContents(std::string_view filename, ResizableBuffer* buffer) const; + virtual Status getContents(const std::string& filename, ResizableBuffer* buffer) const; /** Returns the fullpath for a given filename. @@ -310,7 +310,7 @@ public: @since v2.1 */ - virtual std::string fullPathForFilename(std::string_view filename) const; + virtual std::string fullPathForFilename(const std::string& filename) const; /** * Loads the filenameLookup dictionary from the contents of a filename. @@ -345,7 +345,7 @@ public: * @js loadFilenameLookup * @lua loadFilenameLookup */ - virtual void loadFilenameLookupDictionaryFromFile(std::string_view filename); + virtual void loadFilenameLookupDictionaryFromFile(const std::string& filename); /** * Sets the filenameLookup dictionary. @@ -365,7 +365,7 @@ public: * dictionary. ) * */ - virtual std::string fullPathFromRelativeFile(std::string_view filename, std::string_view relativeFile) const; + virtual std::string fullPathFromRelativeFile(const std::string& filename, const std::string& relativeFile) const; /** * Sets the array that contains the search order of the resources. @@ -384,7 +384,7 @@ public: * @see setSearchResolutionsOrder(), fullPathForFilename(). * @since v2.1 */ - virtual void addSearchResolutionsOrder(std::string_view order, const bool front = false); + virtual void addSearchResolutionsOrder(const std::string& order, const bool front = false); /** * Gets the array that contains the search order of the resources. @@ -424,14 +424,14 @@ public: /** * Set default resource root path. */ - void setDefaultResourceRootPath(std::string_view path); + void setDefaultResourceRootPath(const std::string& path); /** * Add search path. * * @since v2.1 */ - void addSearchPath(std::string_view path, const bool front = false); + void addSearchPath(const std::string& path, const bool front = false); /** * Gets the array of search paths. @@ -468,7 +468,7 @@ public: /** * Sets writable path. */ - virtual void setWritablePath(std::string_view writablePath); + virtual void setWritablePath(const std::string& writablePath); /** * Sets whether to pop-up a message box when failed to load an image. @@ -486,7 +486,7 @@ public: * @return ValueMap of the file contents. * @note This method is used internally. */ - virtual ValueMap getValueMapFromFile(std::string_view filename) const; + virtual ValueMap getValueMapFromFile(const std::string& filename) const; /** Converts the contents of a file to a ValueMap. * This method is used internally. @@ -500,7 +500,7 @@ public: *@param fullPath The full path to the file you want to save a string *@return bool */ - virtual bool writeToFile(const ValueMap& dict, std::string_view fullPath) const; + virtual bool writeToFile(const ValueMap& dict, const std::string& fullPath) const; /** * write a string into a file @@ -509,7 +509,7 @@ public: * @param fullPath The full path to the file you want to save a string * @return bool True if write success */ - virtual bool writeStringToFile(std::string_view dataStr, std::string_view fullPath) const; + virtual bool writeStringToFile(const std::string& dataStr, const std::string& fullPath) const; /** * Write a string to a file, done async off the main cocos thread @@ -525,7 +525,7 @@ public: * signifying if the write was successful. */ virtual void writeStringToFile(std::string dataStr, - std::string_view fullPath, + const std::string& fullPath, std::function callback) const; /** @@ -535,12 +535,12 @@ public: *@param fullPath The full path to the file you want to save a string *@return bool */ - virtual bool writeDataToFile(const Data& data, std::string_view fullPath) const; + virtual bool writeDataToFile(const Data& data, const std::string& fullPath) const; /** * save data to file */ - static bool writeBinaryToFile(const void* data, size_t dataSize, std::string_view fullPath); + static bool writeBinaryToFile(const void* data, size_t dataSize, const std::string& fullPath); /** * Write Data into a file, done async off the main cocos thread. @@ -556,7 +556,7 @@ public: * function will be executed on the main cocos thread. It will have on boolean argument * signifying if the write was successful. */ - virtual void writeDataToFile(Data data, std::string_view fullPath, std::function callback) const; + virtual void writeDataToFile(Data data, const std::string& fullPath, std::function callback) const; /** * write ValueMap into a plist file @@ -565,7 +565,7 @@ public: *@param fullPath The full path to the file you want to save a string *@return bool */ - virtual bool writeValueMapToFile(const ValueMap& dict, std::string_view fullPath) const; + virtual bool writeValueMapToFile(const ValueMap& dict, const std::string& fullPath) const; /** * Write a ValueMap into a file, done async off the main cocos thread. @@ -582,7 +582,7 @@ public: * signifying if the write was successful. */ virtual void writeValueMapToFile(ValueMap dict, - std::string_view fullPath, + const std::string& fullPath, std::function callback) const; /** @@ -592,7 +592,7 @@ public: *@param fullPath The full path to the file you want to save a string *@return bool */ - virtual bool writeValueVectorToFile(const ValueVector& vecData, std::string_view fullPath) const; + virtual bool writeValueVectorToFile(const ValueVector& vecData, const std::string& fullPath) const; /** * Write a ValueVector into a file, done async off the main cocos thread. @@ -609,12 +609,12 @@ public: * signifying if the write was successful. */ virtual void writeValueVectorToFile(ValueVector vecData, - std::string_view fullPath, + const std::string& fullPath, std::function callback) const; // Converts the contents of a file to a ValueVector. // This method is used internally. - virtual ValueVector getValueVectorFromFile(std::string_view filename) const; + virtual ValueVector getValueVectorFromFile(const std::string& filename) const; /** * Checks whether a file exists. @@ -623,7 +623,7 @@ public: * @param filename The path of the file, it could be a relative or absolute path. * @return True if the file exists, false if not. */ - virtual bool isFileExist(std::string_view filename) const; + virtual bool isFileExist(const std::string& filename) const; /** * Checks if a file exists, done async off the main cocos thread. @@ -635,7 +635,7 @@ public: * @param callback The function that will be called when the operation is complete. Will have one boolean * argument, true if the file exists, false otherwise. */ - virtual void isFileExist(std::string_view filename, std::function callback) const; + virtual void isFileExist(const std::string& filename, std::function callback) const; /** * Gets filename extension is a suffix (separated from the base filename by a dot) in lower case. @@ -643,14 +643,14 @@ public: * @param filePath The path of the file, it could be a relative or absolute path. * @return suffix for filename in lower case or empty if a dot not found. */ - virtual std::string getFileExtension(std::string_view filePath) const; + virtual std::string getFileExtension(const std::string& filePath) const; /** * Gets filename shotName * @param filePath The path of the file, it could be a relative or absolute path. * @return fileName.Extension without path */ - static std::string getFileShortName(std::string_view filePath); + static std::string getFileShortName(const std::string& filePath); /** * Checks whether the path is an absolute path. @@ -661,9 +661,9 @@ public: * @param path The path that needs to be checked. * @return True if it's an absolute path, false if not. */ - virtual bool isAbsolutePath(std::string_view path) const; + virtual bool isAbsolutePath(const std::string& path) const; - static bool isAbsolutePathInternal(std::string_view path); + static bool isAbsolutePathInternal(const std::string& path); /** * Checks whether the path is a directory. @@ -671,7 +671,7 @@ public: * @param dirPath The path of the directory, it could be a relative or an absolute path. * @return True if the directory exists, false if not. */ - virtual bool isDirectoryExist(std::string_view dirPath) const; + virtual bool isDirectoryExist(const std::string& dirPath) const; /** * Checks whether the absoulate path is a directory, async off of the main cocos thread. @@ -680,7 +680,7 @@ public: * @param callback that will accept a boolean, true if the file exists, false otherwise. * Callback will happen on the main cocos thread. */ - virtual void isDirectoryExist(std::string_view fullPath, std::function callback) const; + virtual void isDirectoryExist(const std::string& fullPath, std::function callback) const; /** * Creates a directory. @@ -688,7 +688,7 @@ public: * @param dirPath The path of the directory, it must be an absolute path. * @return True if the directory have been created successfully, false if not. */ - virtual bool createDirectory(std::string_view dirPath) const; + virtual bool createDirectory(const std::string& dirPath) const; /** * Create a directory, async off the main cocos thread. @@ -697,7 +697,7 @@ public: * @param callback The function that will be called when the operation is complete. Will have one boolean * argument, true if the directory was successfully, false otherwise. */ - virtual void createDirectory(std::string_view dirPath, std::function callback) const; + virtual void createDirectory(const std::string& dirPath, std::function callback) const; /** * Removes a directory. @@ -705,7 +705,7 @@ public: * @param dirPath The full path of the directory, it must be an absolute path. * @return True if the directory have been removed successfully, false if not. */ - virtual bool removeDirectory(std::string_view dirPath) const; + virtual bool removeDirectory(const std::string& dirPath) const; /** * Removes a directory, async off the main cocos thread. @@ -714,7 +714,7 @@ public: * @param callback The function that will be called when the operation is complete. Will have one boolean * argument, true if the directory was successfully removed, false otherwise. */ - virtual void removeDirectory(std::string_view dirPath, std::function callback) const; + virtual void removeDirectory(const std::string& dirPath, std::function callback) const; /** * Removes a file. @@ -722,7 +722,7 @@ public: * @param filepath The full path of the file, it must be an absolute path. * @return True if the file have been removed successfully, false if not. */ - virtual bool removeFile(std::string_view filepath) const; + virtual bool removeFile(const std::string& filepath) const; /** * Removes a file, async off the main cocos thread. @@ -731,7 +731,7 @@ public: * @param callback The function that will be called when the operation is complete. Will have one boolean * argument, true if the file was successfully removed, false otherwise. */ - virtual void removeFile(std::string_view filepath, std::function callback) const; + virtual void removeFile(const std::string& filepath, std::function callback) const; /** * Renames a file under the given directory. @@ -741,7 +741,7 @@ public: * @param name The new name of the file. * @return True if the file have been renamed successfully, false if not. */ - virtual bool renameFile(std::string_view path, std::string_view oldname, std::string_view name) const; + virtual bool renameFile(const std::string& path, const std::string& oldname, const std::string& name) const; /** * Renames a file under the given directory, async off the main cocos thread. @@ -752,9 +752,9 @@ public: * @param callback The function that will be called when the operation is complete. Will have one boolean * argument, true if the file was successfully renamed, false otherwise. */ - virtual void renameFile(std::string_view path, - std::string_view oldname, - std::string_view name, + virtual void renameFile(const std::string& path, + const std::string& oldname, + const std::string& name, std::function callback) const; /** @@ -764,7 +764,7 @@ public: * @param newfullpath The new fullpath of the file. Includes path and name. * @return True if the file have been renamed successfully, false if not. */ - virtual bool renameFile(std::string_view oldfullpath, std::string_view newfullpath) const; + virtual bool renameFile(const std::string& oldfullpath, const std::string& newfullpath) const; /** * Renames a file under the given directory, async off the main cocos thread. @@ -774,8 +774,8 @@ public: * @param callback The function that will be called when the operation is complete. Will have one boolean * argument, true if the file was successfully renamed, false otherwise. */ - virtual void renameFile(std::string_view oldfullpath, - std::string_view newfullpath, + virtual void renameFile(const std::string& oldfullpath, + const std::string& newfullpath, std::function callback) const; /** @@ -785,7 +785,7 @@ public: * @param filepath The path of the file, it could be a relative or absolute path. * @return The file size. */ - virtual int64_t getFileSize(std::string_view filepath) const; + virtual int64_t getFileSize(const std::string& filepath) const; /** * Retrieve the file size, async off the main cocos thread. @@ -795,7 +795,7 @@ public: * @param callback The function that will be called when the operation is complete. Will have one long * argument, the file size. */ - virtual void getFileSize(std::string_view filepath, std::function callback) const; + virtual void getFileSize(const std::string& filepath, std::function callback) const; /** * List all files in a directory. @@ -803,7 +803,7 @@ public: * @param dirPath The path of the directory, it could be a relative or an absolute path. * @return File paths in a string vector */ - virtual std::vector listFiles(std::string_view dirPath) const; + virtual std::vector listFiles(const std::string& dirPath) const; /** * List all files in a directory async, off of the main cocos thread. @@ -814,7 +814,8 @@ public: * @js NA * @lua NA */ - virtual void listFilesAsync(std::string_view dirPath, std::function)> callback) const; + virtual void listFilesAsync(const std::string& dirPath, + std::function)> callback) const; /** * List all files recursively in a directory. @@ -822,7 +823,7 @@ public: * @param dirPath The path of the directory, it could be a relative or an absolute path. * @return File paths in a string vector */ - virtual void listFilesRecursively(std::string_view dirPath, std::vector* files) const; + virtual void listFilesRecursively(const std::string& dirPath, std::vector* files) const; /** * List all files recursively in a directory, async off the main cocos thread. @@ -833,11 +834,11 @@ public: * @js NA * @lua NA */ - virtual void listFilesRecursivelyAsync(std::string_view dirPath, + virtual void listFilesRecursivelyAsync(const std::string& dirPath, std::function)> callback) const; /** Returns the full path cache. */ - const hlookup::string_map getFullPathCache() const { return _fullPathCache; } + const std::unordered_map getFullPathCache() const { return _fullPathCache; } /** * Gets the new filename from the filename lookup dictionary. @@ -846,21 +847,21 @@ public: * @return The new filename after searching in the filename lookup dictionary. * If the original filename wasn't in the dictionary, it will return the original filename. */ - virtual std::string getNewFilename(std::string_view filename) const; + virtual std::string getNewFilename(const std::string& filename) const; /** * Checks whether a file exists without considering search paths and resolution orders. * @param filename The file (with absolute path) to look up for * @return Returns true if the file found at the given absolute path, otherwise returns false */ - virtual bool isFileExistInternal(std::string_view filename) const = 0; + virtual bool isFileExistInternal(const std::string& filename) const = 0; /** * Checks whether a directory exists without considering search paths and resolution orders. * @param dirPath The directory (with absolute path) to look up for * @return Returns true if the directory found at the given absolute path, otherwise returns false */ - virtual bool isDirectoryExistInternal(std::string_view dirPath) const; + virtual bool isDirectoryExistInternal(const std::string& dirPath) const; /** * Open a FileStream based on the implementation provided in openFileStream or its overrides @@ -868,7 +869,7 @@ public: * @param mode The mode to open the file in, being READ | WRITE | APPEND * @return Returns a pointer to the file stream */ - virtual std::unique_ptr openFileStream(std::string_view filePath, FileStream::Mode mode); + virtual std::unique_ptr openFileStream(const std::string& filePath, FileStream::Mode mode); protected: /** @@ -896,13 +897,13 @@ protected: * @param searchPath The search path. * @return The full path of the file. It will return an empty string if the full path of the file doesn't exist. */ - virtual std::string getPathForFilename(std::string_view filename, - std::string_view resolutionDirectory, - std::string_view searchPath) const; + virtual std::string getPathForFilename(const std::string& filename, + const std::string& resolutionDirectory, + const std::string& searchPath) const; - virtual std::string getPathForDirectory(std::string_view dir, - std::string_view resolutionDiretory, - std::string_view searchPath) const; + virtual std::string getPathForDirectory(const std::string& dir, + const std::string& resolutionDiretory, + const std::string& searchPath) const; /** * Gets full path for the directory and the filename. @@ -914,14 +915,14 @@ protected: * @param filename The name of the file. * @return The full path of the file, if the file can't be found, it will return an empty string. */ - virtual std::string getFullPathForFilenameWithinDirectory(std::string_view directory, - std::string_view filename) const; + virtual std::string getFullPathForFilenameWithinDirectory(const std::string& directory, + const std::string& filename) const; /** * Returns the fullpath for a given dirname. * @since 3.17.1 */ - virtual std::string fullPathForDirectory(std::string_view dirname) const; + virtual std::string fullPathForDirectory(const std::string& dirname) const; /** * mutex used to protect fields. @@ -967,13 +968,13 @@ protected: * The full path cache for normal files. When a file is found, it will be added into this cache. * This variable is used for improving the performance of file search. */ - mutable hlookup::string_map _fullPathCache; + mutable std::unordered_map _fullPathCache; /** * The full path cache for directories. When a diretory is found, it will be added into this cache. * This variable is used for improving the performance of file search. */ - mutable hlookup::string_map _fullPathCacheDir; + mutable std::unordered_map _fullPathCacheDir; /** * Writable path. diff --git a/cocos/platform/CCGLView.cpp b/cocos/platform/CCGLView.cpp index 7ee97868af..5c8494362a 100644 --- a/cocos/platform/CCGLView.cpp +++ b/cocos/platform/CCGLView.cpp @@ -279,12 +279,12 @@ Rect GLView::getScissorRect() const return Rect(x, y, w, h); } -void GLView::setViewName(std::string_view viewname) +void GLView::setViewName(const std::string& viewname) { _viewName = viewname; } -std::string_view GLView::getViewName() const +const std::string& GLView::getViewName() const { return _viewName; } diff --git a/cocos/platform/CCGLView.h b/cocos/platform/CCGLView.h index f5bbc43547..6cd6c1568b 100644 --- a/cocos/platform/CCGLView.h +++ b/cocos/platform/CCGLView.h @@ -308,13 +308,13 @@ public: * * @param viewname A string will be set to the view as name. */ - virtual void setViewName(std::string_view viewname); + virtual void setViewName(const std::string& viewname); /** Get the view name. * * @return The view name. */ - std::string_view getViewName() const; + const std::string& getViewName() const; /** Touch events are handled by default; if you want to customize your handlers, please override this function. * @@ -367,14 +367,14 @@ public: * * @param filename A path to image file, e.g., "icons/cusom.png". */ - virtual void setIcon(std::string_view filename) const {}; + virtual void setIcon(const std::string& filename) const {}; /** Set window icon (implemented for windows and linux). * Best icon (based on size) will be auto selected. * * @param filelist The array contains icons. */ - virtual void setIcon(const std::vector& filelist) const {}; + virtual void setIcon(const std::vector& filelist) const {}; /** Set default window icon (implemented for windows and linux). * On windows it will use icon from .exe file (if included). diff --git a/cocos/platform/CCImage.cpp b/cocos/platform/CCImage.cpp index 7296355cae..6f2340a153 100644 --- a/cocos/platform/CCImage.cpp +++ b/cocos/platform/CCImage.cpp @@ -601,7 +601,7 @@ Image::~Image() } } -bool Image::initWithImageFile(std::string_view path) +bool Image::initWithImageFile(const std::string& path) { bool ret = false; _filePath = FileUtils::getInstance()->fullPathForFilename(path); @@ -618,7 +618,7 @@ bool Image::initWithImageFile(std::string_view path) return ret; } -bool Image::initWithImageFileThreadSafe(std::string_view fullpath) +bool Image::initWithImageFileThreadSafe(const std::string& fullpath) { bool ret = false; _filePath = fullpath; @@ -2193,7 +2193,7 @@ void Image::forwardPixels(uint8_t* data, ssize_t dataLen, int offset, bool ownDa } #if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) -bool Image::saveToFile(std::string_view filename, bool isToRGB) +bool Image::saveToFile(const std::string& filename, bool isToRGB) { // only support for backend::PixelFormat::RGB8 or backend::PixelFormat::RGBA8 uncompressed data if (isCompressed() || (_pixelFormat != backend::PixelFormat::RGB8 && _pixelFormat != backend::PixelFormat::RGBA8)) @@ -2216,13 +2216,13 @@ bool Image::saveToFile(std::string_view filename, bool isToRGB) } else { - CCLOG("cocos2d: Image: saveToFile no support file extension(only .png or .jpg) for file: %s", filename.data()); + CCLOG("cocos2d: Image: saveToFile no support file extension(only .png or .jpg) for file: %s", filename.c_str()); return false; } } #endif -bool Image::saveImageToPNG(std::string_view filePath, bool isToRGB) +bool Image::saveImageToPNG(const std::string& filePath, bool isToRGB) { #if CC_USE_PNG bool ret = false; @@ -2365,7 +2365,7 @@ bool Image::saveImageToPNG(std::string_view filePath, bool isToRGB) #endif // CC_USE_PNG } -bool Image::saveImageToJPG(std::string_view filePath) +bool Image::saveImageToJPG(const std::string& filePath) { #if CC_USE_JPEG bool ret = false; diff --git a/cocos/platform/CCImage.h b/cocos/platform/CCImage.h index ae1adc4ff3..3466dbe617 100644 --- a/cocos/platform/CCImage.h +++ b/cocos/platform/CCImage.h @@ -148,7 +148,7 @@ public: @param path the absolute file path. @return true if loaded correctly. */ - bool initWithImageFile(std::string_view path); + bool initWithImageFile(const std::string& path); /** @brief Load image from stream buffer. @@ -191,7 +191,7 @@ public: @param filePath the file's absolute path, including file suffix. @param isToRGB whether the image is saved as RGB format. */ - bool saveToFile(std::string_view filename, bool isToRGB = true); + bool saveToFile(const std::string& filename, bool isToRGB = true); void premultiplyAlpha(); void reversePremultipliedAlpha(); @@ -218,8 +218,8 @@ protected: // fast forward pixels to GPU if ownData void forwardPixels(uint8_t* data, ssize_t dataLen, int offset, bool ownData); - bool saveImageToPNG(std::string_view filePath, bool isToRGB = true); - bool saveImageToJPG(std::string_view filePath); + bool saveImageToPNG(const std::string& filePath, bool isToRGB = true); + bool saveImageToJPG(const std::string& filePath); protected: /** @@ -259,7 +259,7 @@ protected: @param imageType the type of image, currently only supporting two types. @return true if loaded correctly. */ - bool initWithImageFileThreadSafe(std::string_view fullpath); + bool initWithImageFileThreadSafe(const std::string& fullpath); Format detectFormat(const uint8_t* data, ssize_t dataLen); bool isPng(const uint8_t* data, ssize_t dataLen); diff --git a/cocos/platform/CCPlatformMacros.h b/cocos/platform/CCPlatformMacros.h index b8a6516c14..4f2a33e3e0 100644 --- a/cocos/platform/CCPlatformMacros.h +++ b/cocos/platform/CCPlatformMacros.h @@ -32,7 +32,6 @@ Copyright (c) 2021 Bytedance Inc. * Define some platform specific macros. */ #include "base/ccConfig.h" -#include "base/hlookup.h" #include "platform/CCPlatformConfig.h" #include "platform/CCPlatformDefine.h" diff --git a/cocos/platform/CCPosixFileStream.cpp b/cocos/platform/CCPosixFileStream.cpp index cdf1f76bee..6606cc594c 100644 --- a/cocos/platform/CCPosixFileStream.cpp +++ b/cocos/platform/CCPosixFileStream.cpp @@ -19,7 +19,7 @@ struct PXIoF long long (*size)(PXFileHandle& handle); }; -static int pfs_posix_open(std::string_view path, FileStream::Mode mode, PXFileHandle& handle) +static int pfs_posix_open(const std::string& path, FileStream::Mode mode, PXFileHandle& handle) { switch (mode) { @@ -127,7 +127,7 @@ PosixFileStream::~PosixFileStream() internalClose(); } -bool PosixFileStream::open(std::string_view path, FileStream::Mode mode) +bool PosixFileStream::open(const std::string& path, FileStream::Mode mode) { bool ok = false; #if CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID diff --git a/cocos/platform/CCPosixFileStream.h b/cocos/platform/CCPosixFileStream.h index 02b668a616..183f6d5dea 100644 --- a/cocos/platform/CCPosixFileStream.h +++ b/cocos/platform/CCPosixFileStream.h @@ -54,7 +54,7 @@ # define O_APPEND_FLAGS O_APPEND | O_CREAT | O_RDWR, S_IRWXU # define O_OVERLAP_FLAGS O_CREAT | O_RDWR, S_IRWXU -# define posix_open_cxx(path, ...) ::open(path.data(), ##__VA_ARGS__) +# define posix_open_cxx(path, ...) ::open(path.c_str(), ##__VA_ARGS__) # define posix_open ::open # define posix_close ::close # define posix_lseek ::lseek @@ -114,7 +114,7 @@ public: APPEND, }; - bool open(std::string_view path, FileStream::Mode mode) override; + bool open(const std::string& path, FileStream::Mode mode) override; int close() override; int seek(int64_t offset, int origin) override; diff --git a/cocos/platform/CCSAXParser.cpp b/cocos/platform/CCSAXParser.cpp index 7af489f71f..2629c6a856 100644 --- a/cocos/platform/CCSAXParser.cpp +++ b/cocos/platform/CCSAXParser.cpp @@ -108,7 +108,7 @@ bool SAXParser::parse(const char* xmlData, size_t dataLength) return false; } -bool SAXParser::parse(std::string_view filename) +bool SAXParser::parse(const std::string& filename) { bool ret = false; Data data = FileUtils::getInstance()->getDataFromFile(filename); diff --git a/cocos/platform/CCSAXParser.h b/cocos/platform/CCSAXParser.h index ecb4c7bbe5..7b948fc071 100644 --- a/cocos/platform/CCSAXParser.h +++ b/cocos/platform/CCSAXParser.h @@ -90,7 +90,7 @@ public: * @js NA * @lua NA */ - bool parse(std::string_view filename); + bool parse(const std::string& filename); /** * New API for performance. diff --git a/cocos/platform/CMakeLists.txt b/cocos/platform/CMakeLists.txt index 1b60199c7b..c91d63fdd5 100644 --- a/cocos/platform/CMakeLists.txt +++ b/cocos/platform/CMakeLists.txt @@ -30,14 +30,6 @@ if(ANDROID) platform/android/CCGLViewImpl-android.cpp platform/android/CCFileUtils-android.cpp platform/android/CCEnhanceAPI-android.cpp - platform/android/CCDevice-android.cpp - platform/android/javaactivity-android.cpp - platform/android/jni/JniHelper.cpp - platform/android/jni/TouchesJni.cpp - platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxAccelerometer.cpp - platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp - platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp - platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp ) elseif(WINDOWS) set(COCOS_PLATFORM_SPECIFIC_HEADER diff --git a/cocos/platform/android/CCApplication-android.cpp b/cocos/platform/android/CCApplication-android.cpp index 16927d40d5..08809fb6d7 100644 --- a/cocos/platform/android/CCApplication-android.cpp +++ b/cocos/platform/android/CCApplication-android.cpp @@ -43,7 +43,7 @@ extern "C" size_t __ctype_get_mb_cur_max(void) } #endif -static const char* helperClassName = "org.cocos2dx.lib.Cocos2dxHelper"; +static const std::string helperClassName = "org.cocos2dx.lib.Cocos2dxHelper"; NS_CC_BEGIN @@ -119,7 +119,7 @@ std::string Application::getVersion() return JniHelper::callStaticStringMethod(helperClassName, "getVersion"); } -bool Application::openURL(std::string_view url) +bool Application::openURL(const std::string& url) { return JniHelper::callStaticBooleanMethod(helperClassName, "openURL", url); } diff --git a/cocos/platform/android/CCApplication-android.h b/cocos/platform/android/CCApplication-android.h index 71f0e2146e..42cf2dc287 100644 --- a/cocos/platform/android/CCApplication-android.h +++ b/cocos/platform/android/CCApplication-android.h @@ -90,7 +90,7 @@ public: @param String with url to open. @return true if the resource located by the URL was successfully opened; otherwise false. */ - virtual bool openURL(std::string_view url) override; + virtual bool openURL(const std::string& url) override; /** @brief This function will be called when the application screen size is changed. diff --git a/cocos/platform/android/CCDevice-android.cpp b/cocos/platform/android/CCDevice-android.cpp index e5e994fc3a..ebfda66eb0 100644 --- a/cocos/platform/android/CCDevice-android.cpp +++ b/cocos/platform/android/CCDevice-android.cpp @@ -33,7 +33,7 @@ THE SOFTWARE. #include "platform/CCFileUtils.h" #include "yasio/cxx17/string_view.hpp" -static const char* helperClassName = "org.cocos2dx.lib.Cocos2dxHelper"; +static const std::string helperClassName = "org.cocos2dx.lib.Cocos2dxHelper"; NS_CC_BEGIN diff --git a/cocos/platform/android/CCFileUtils-android.cpp b/cocos/platform/android/CCFileUtils-android.cpp index e9ca5b5639..dabb0a4148 100644 --- a/cocos/platform/android/CCFileUtils-android.cpp +++ b/cocos/platform/android/CCFileUtils-android.cpp @@ -36,8 +36,6 @@ THE SOFTWARE. #include #include -#include "yasio/cxx17/string_view.hpp" - #define LOG_TAG "CCFileUtils-android.cpp" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) @@ -105,7 +103,7 @@ bool FileUtilsAndroid::init() return FileUtils::init(); } -std::string FileUtilsAndroid::getNewFilename(std::string_view filename) const +std::string FileUtilsAndroid::getNewFilename(const std::string& filename) const { std::string newFileName = FileUtils::getNewFilename(filename); // ../xxx do not fix this path @@ -158,7 +156,7 @@ std::string FileUtilsAndroid::getNewFilename(std::string_view filename) const return newFileName; } -bool FileUtilsAndroid::isFileExistInternal(std::string_view strFilePath) const +bool FileUtilsAndroid::isFileExistInternal(const std::string& strFilePath) const { DECLARE_GUARD; @@ -173,7 +171,7 @@ bool FileUtilsAndroid::isFileExistInternal(std::string_view strFilePath) const // Check whether file exists in apk. if (strFilePath[0] != '/') { - const char* s = strFilePath.data(); + const char* s = strFilePath.c_str(); // Found "assets/" at the beginning of the path and we don't want it if (strFilePath.find(_defaultResRootPath) == 0) @@ -200,30 +198,26 @@ bool FileUtilsAndroid::isFileExistInternal(std::string_view strFilePath) const else { struct stat st; - if (::stat(strFilePath.data(), &st) == 0) + if (::stat(strFilePath.c_str(), &st) == 0) bFound = S_ISREG(st.st_mode); } return bFound; } -bool FileUtilsAndroid::isDirectoryExistInternal(std::string_view dirPath) const +bool FileUtilsAndroid::isDirectoryExistInternal(const std::string& dirPath) const { if (dirPath.empty()) { return false; } - std::string_view path; - std::string dirPathCopy; - if (dirPath[dirPath.length() - 1] == '/') + std::string dirPathCopy = dirPath; + if (dirPathCopy[dirPathCopy.length() - 1] == '/') { - dirPathCopy.assign(dirPath.data(), dirPath.length() - 1); - path = dirPathCopy; + dirPathCopy.erase(dirPathCopy.length() - 1); } - else - path = dirPath; - const char* s = path.data(); + const char* s = dirPathCopy.c_str(); // find absolute path in flash memory if (s[0] == '/') @@ -260,7 +254,7 @@ bool FileUtilsAndroid::isDirectoryExistInternal(std::string_view dirPath) const return false; } -bool FileUtilsAndroid::isAbsolutePath(std::string_view strPath) const +bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath) const { DECLARE_GUARD; // On Android, there are two situations for full path. @@ -270,7 +264,7 @@ bool FileUtilsAndroid::isAbsolutePath(std::string_view strPath) const return (strPath[0] == '/' || strPath.find(_defaultResRootPath) == 0); } -int64_t FileUtilsAndroid::getFileSize(std::string_view filepath) const +int64_t FileUtilsAndroid::getFileSize(const std::string& filepath) const { DECLARE_GUARD; int64_t size = FileUtils::getFileSize(filepath); @@ -281,16 +275,13 @@ int64_t FileUtilsAndroid::getFileSize(std::string_view filepath) const if (FileUtilsAndroid::assetmanager) { - std::string_view path; - std::string relativePath; - if (cxx20::starts_with(filepath, _defaultResRootPath)) + string relativePath = filepath; + if (filepath.find(_defaultResRootPath) == 0) { - path = relativePath = filepath.substr(_defaultResRootPath.size()); + relativePath = filepath.substr(_defaultResRootPath.size()); } - else - path = filepath; - AAsset* asset = AAssetManager_open(FileUtilsAndroid::assetmanager, path.data(), AASSET_MODE_UNKNOWN); + AAsset* asset = AAssetManager_open(FileUtilsAndroid::assetmanager, relativePath.data(), AASSET_MODE_UNKNOWN); if (asset) { size = AAsset_getLength(asset); @@ -301,7 +292,7 @@ int64_t FileUtilsAndroid::getFileSize(std::string_view filepath) const return size; } -std::vector FileUtilsAndroid::listFiles(std::string_view dirPath) const +std::vector FileUtilsAndroid::listFiles(const std::string& dirPath) const { if (!dirPath.empty() && dirPath[0] == '/') @@ -356,7 +347,7 @@ std::vector FileUtilsAndroid::listFiles(std::string_view dirPath) c return fileList; } -FileUtils::Status FileUtilsAndroid::getContents(std::string_view filename, ResizableBuffer* buffer) const +FileUtils::Status FileUtilsAndroid::getContents(const std::string& filename, ResizableBuffer* buffer) const { static const std::string apkprefix("assets/"); if (filename.empty()) diff --git a/cocos/platform/android/CCFileUtils-android.h b/cocos/platform/android/CCFileUtils-android.h index fc3c6c8577..44ef3864fb 100644 --- a/cocos/platform/android/CCFileUtils-android.h +++ b/cocos/platform/android/CCFileUtils-android.h @@ -64,20 +64,20 @@ public: /* override functions */ bool init() override; - virtual std::string getNewFilename(std::string_view filename) const override; + virtual std::string getNewFilename(const std::string& filename) const override; - virtual FileUtils::Status getContents(std::string_view filename, ResizableBuffer* buffer) const override; + virtual FileUtils::Status getContents(const std::string& filename, ResizableBuffer* buffer) const override; virtual std::string getWritablePath() const override; std::string getNativeWritableAbsolutePath() const override; - virtual bool isAbsolutePath(std::string_view strPath) const override; + virtual bool isAbsolutePath(const std::string& strPath) const override; - virtual int64_t getFileSize(std::string_view filepath) const override; - virtual std::vector listFiles(std::string_view dirPath) const override; + virtual int64_t getFileSize(const std::string& filepath) const override; + virtual std::vector listFiles(const std::string& dirPath) const override; private: - virtual bool isFileExistInternal(std::string_view strFilePath) const override; - virtual bool isDirectoryExistInternal(std::string_view dirPath) const override; + virtual bool isFileExistInternal(const std::string& strFilePath) const override; + virtual bool isDirectoryExistInternal(const std::string& dirPath) const override; static AAssetManager* assetmanager; static ZipFile* obbfile; diff --git a/cocos/platform/android/CCGLViewImpl-android.cpp b/cocos/platform/android/CCGLViewImpl-android.cpp index 8a0ff6eb3c..b094714312 100644 --- a/cocos/platform/android/CCGLViewImpl-android.cpp +++ b/cocos/platform/android/CCGLViewImpl-android.cpp @@ -50,7 +50,7 @@ void initExtensions() NS_CC_BEGIN -GLViewImpl* GLViewImpl::createWithRect(std::string_view viewName, Rect rect, float frameZoomFactor) +GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor) { auto ret = new GLViewImpl; if (ret && ret->initWithRect(viewName, rect, frameZoomFactor)) @@ -62,7 +62,7 @@ GLViewImpl* GLViewImpl::createWithRect(std::string_view viewName, Rect rect, flo return nullptr; } -GLViewImpl* GLViewImpl::create(std::string_view viewName) +GLViewImpl* GLViewImpl::create(const std::string& viewName) { auto ret = new GLViewImpl; if (ret && ret->initWithFullScreen(viewName)) @@ -74,7 +74,7 @@ GLViewImpl* GLViewImpl::create(std::string_view viewName) return nullptr; } -GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName) +GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName) { auto ret = new GLViewImpl(); if (ret && ret->initWithFullScreen(viewName)) @@ -93,12 +93,12 @@ GLViewImpl::GLViewImpl() GLViewImpl::~GLViewImpl() {} -bool GLViewImpl::initWithRect(std::string_view viewName, Rect rect, float frameZoomFactor) +bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor) { return true; } -bool GLViewImpl::initWithFullScreen(std::string_view viewName) +bool GLViewImpl::initWithFullScreen(const std::string& viewName) { return true; } diff --git a/cocos/platform/android/CCGLViewImpl-android.h b/cocos/platform/android/CCGLViewImpl-android.h index fc42130964..0f7e2d539b 100644 --- a/cocos/platform/android/CCGLViewImpl-android.h +++ b/cocos/platform/android/CCGLViewImpl-android.h @@ -35,9 +35,9 @@ class CC_DLL GLViewImpl : public GLView { public: // static function - static GLViewImpl* create(std::string_view viewname); - static GLViewImpl* createWithRect(std::string_view viewName, Rect rect, float frameZoomFactor = 1.0f); - static GLViewImpl* createWithFullScreen(std::string_view viewName); + static GLViewImpl* create(const std::string& viewname); + static GLViewImpl* createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor = 1.0f); + static GLViewImpl* createWithFullScreen(const std::string& viewName); bool isOpenGLReady() override; void end() override; @@ -49,8 +49,8 @@ protected: GLViewImpl(); virtual ~GLViewImpl(); - bool initWithRect(std::string_view viewName, Rect rect, float frameZoomFactor); - bool initWithFullScreen(std::string_view viewName); + bool initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor); + bool initWithFullScreen(const std::string& viewName); }; NS_CC_END diff --git a/cocos/platform/android/CMakeLists.txt b/cocos/platform/android/CMakeLists.txt new file mode 100644 index 0000000000..fb10db45a1 --- /dev/null +++ b/cocos/platform/android/CMakeLists.txt @@ -0,0 +1,26 @@ +# need to whole-archive this lib +set(target_name cpp_android_spec) + +project(${target_name}) + +set(${target_name}_src + CCDevice-android.cpp + javaactivity-android.cpp + jni/JniHelper.cpp + jni/TouchesJni.cpp + jni/Java_org_cocos2dx_lib_Cocos2dxAccelerometer.cpp + jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp + jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp + jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp +) + +add_library(${target_name} STATIC + ${${target_name}_src} +) + +target_include_directories(${target_name} + PRIVATE .. + PRIVATE ../.. + PRIVATE ../../../thirdparty +) + diff --git a/cocos/platform/android/javaactivity-android.cpp b/cocos/platform/android/javaactivity-android.cpp index cceffd07fc..2865ba5942 100644 --- a/cocos/platform/android/javaactivity-android.cpp +++ b/cocos/platform/android/javaactivity-android.cpp @@ -1,9 +1,8 @@ /**************************************************************************** Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -Copyright (c) Bytedance Inc. -https://adxeproject.github.io/ +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 @@ -36,8 +35,6 @@ THE SOFTWARE. #include #include -#include "jni/jni.hpp" - #define LOG_TAG "main" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) diff --git a/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp b/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp index daad8b2d6d..f89188ceb4 100644 --- a/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp +++ b/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp @@ -31,7 +31,7 @@ THE SOFTWARE. #include "platform/CCFileUtils.h" #include "base/ccUTF8.h" -static const char* className = "org.cocos2dx.lib.Cocos2dxBitmap"; +static const std::string className = "org.cocos2dx.lib.Cocos2dxBitmap"; using namespace cocos2d; diff --git a/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp b/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp index 85bba0fe90..0592dc4044 100644 --- a/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp +++ b/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp @@ -37,7 +37,7 @@ THE SOFTWARE. #define LOG_TAG "Java_org_cocos2dx_lib_Cocos2dxHelper.cpp" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) -static const char* className = "org.cocos2dx.lib.Cocos2dxHelper"; +static const std::string className = "org.cocos2dx.lib.Cocos2dxHelper"; static EditTextCallback s_editTextCallback = nullptr; static void* s_ctx = nullptr; @@ -142,7 +142,8 @@ int getObbAssetFileDescriptorJNI(const char* path, int64_t* startOffset, int64_t JniMethodInfo methodInfo; int fd = 0; - if (JniHelper::getStaticMethodInfo(methodInfo, className, "getObbAssetFileDescriptor", "(Ljava/lang/String;)[J")) + if (JniHelper::getStaticMethodInfo(methodInfo, className.c_str(), "getObbAssetFileDescriptor", + "(Ljava/lang/String;)[J")) { jstring stringArg = methodInfo.env->NewStringUTF(path); jlongArray newArray = @@ -180,7 +181,7 @@ void conversionEncodingJNI(const char* src, int byteSize, const char* fromCharse { JniMethodInfo methodInfo; - if (JniHelper::getStaticMethodInfo(methodInfo, className, "conversionEncoding", + if (JniHelper::getStaticMethodInfo(methodInfo, className.c_str(), "conversionEncoding", "([BLjava/lang/String;Ljava/lang/String;)[B")) { jbyteArray strArray = methodInfo.env->NewByteArray(byteSize); diff --git a/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp b/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp index ec5960b569..bf9de1f55e 100644 --- a/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp +++ b/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp @@ -84,7 +84,7 @@ JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeDeleteBackwa JNIEXPORT jstring JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeGetContentText(JNIEnv* env, jclass) { - auto pszText = cocos2d::IMEDispatcher::sharedDispatcher()->getContentText(); + std::string pszText = cocos2d::IMEDispatcher::sharedDispatcher()->getContentText(); return cocos2d::StringUtils::newStringUTFJNI(env, pszText); } } diff --git a/cocos/platform/android/jni/JniHelper.cpp b/cocos/platform/android/jni/JniHelper.cpp index 66dbf8e90a..bddad033df 100644 --- a/cocos/platform/android/jni/JniHelper.cpp +++ b/cocos/platform/android/jni/JniHelper.cpp @@ -319,11 +319,6 @@ jstring JniHelper::convert(LocalRefMapType& localRefs, cocos2d::JniMethodInfo& t return ret; } -jstring JniHelper::convert(LocalRefMapType& localRefs, cocos2d::JniMethodInfo& t, std::string_view x) -{ - return convert(localRefs, t, x.data()); -} - jstring JniHelper::convert(LocalRefMapType& localRefs, cocos2d::JniMethodInfo& t, const std::string& x) { return convert(localRefs, t, x.c_str()); @@ -343,10 +338,10 @@ void JniHelper::deleteLocalRefs(JNIEnv* env, LocalRefMapType& localRefs) localRefs[env].clear(); } -void JniHelper::reportError(const char* className, const char* methodName, const char* signature) +void JniHelper::reportError(const std::string& className, const std::string& methodName, const std::string& signature) { - LOGE("Failed to find static java method. Class name: %s, method name: %s, signature: %s ", className, methodName, - signature); + LOGE("Failed to find static java method. Class name: %s, method name: %s, signature: %s ", className.c_str(), + methodName.c_str(), signature.c_str()); } } // namespace cocos2d diff --git a/cocos/platform/android/jni/JniHelper.h b/cocos/platform/android/jni/JniHelper.h index 60fa77e86d..1367b95c5a 100644 --- a/cocos/platform/android/jni/JniHelper.h +++ b/cocos/platform/android/jni/JniHelper.h @@ -2,9 +2,8 @@ Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -Copyright (c) 2021 Bytedance Inc. -https://adxeproject.github.io +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 @@ -32,34 +31,8 @@ THE SOFTWARE. #include #include #include -#include #include "platform/CCPlatformMacros.h" #include "math/Vec3.h" -#include "jni/jni.hpp" - -namespace jni -{ -template <> -struct TypeSignature -{ - constexpr auto operator()() const { return TypeSignature{}(); } -}; -template <> -struct TypeSignature -{ - constexpr auto operator()() const { return TypeSignature{}(); } -}; -template <> -struct TypeSignature -{ - constexpr auto operator()() const { return TypeSignature{}(); } -}; -template <> -struct TypeSignature -{ - constexpr auto operator()() const { return TypeSignature{}(); } -}; -} // namespace jni NS_CC_BEGIN @@ -101,11 +74,11 @@ public: @if no such method will log error */ template - static void callStaticVoidMethod(const char* className, const char* methodName, Ts&&... xs) + static void callStaticVoidMethod(const std::string& className, const std::string& methodName, Ts... xs) { cocos2d::JniMethodInfo t; - const char* signature = jni::TypeSignature...)>{}(); - if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, signature)) + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")V"; + if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; t.env->CallStaticVoidMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); @@ -123,12 +96,12 @@ public: @return value from Java static boolean method if there are proper JniMethodInfo; otherwise false. */ template - static bool callStaticBooleanMethod(const char* className, const char* methodName, Ts&&... xs) + static bool callStaticBooleanMethod(const std::string& className, const std::string& methodName, Ts... xs) { jboolean jret = JNI_FALSE; cocos2d::JniMethodInfo t; - const char* signature = jni::TypeSignature...)>{}(); - if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, signature)) + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")Z"; + if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; jret = t.env->CallStaticBooleanMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); @@ -147,12 +120,12 @@ public: @return value from Java static int method if there are proper JniMethodInfo; otherwise 0. */ template - static int callStaticIntMethod(const char* className, const char* methodName, Ts&&... xs) + static int callStaticIntMethod(const std::string& className, const std::string& methodName, Ts... xs) { jint ret = 0; cocos2d::JniMethodInfo t; - const char* signature = jni::TypeSignature...)>{}(); - if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, signature)) + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")I"; + if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; ret = t.env->CallStaticIntMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); @@ -171,12 +144,12 @@ public: @return value from Java static float method if there are proper JniMethodInfo; otherwise 0. */ template - static float callStaticFloatMethod(const char* className, const char* methodName, Ts&&... xs) + static float callStaticFloatMethod(const std::string& className, const std::string& methodName, Ts... xs) { jfloat ret = 0.0; cocos2d::JniMethodInfo t; - const char* signature = jni::TypeSignature...)>{}(); - if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, signature)) + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")F"; + if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; ret = t.env->CallStaticFloatMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); @@ -195,12 +168,12 @@ public: @return address of JniMethodInfo if there are proper JniMethodInfo; otherwise nullptr. */ template - static float* callStaticFloatArrayMethod(const char* className, const char* methodName, Ts&&... xs) + static float* callStaticFloatArrayMethod(const std::string& className, const std::string& methodName, Ts... xs) { static float ret[32]; cocos2d::JniMethodInfo t; - const char* signature = jni::TypeSignature(std::decay_t...)>{}(); - if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, signature)) + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")[F"; + if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; jfloatArray array = @@ -231,12 +204,12 @@ public: @return address of JniMethodInfo if there are proper JniMethodInfo; otherwise nullptr. */ template - static int* callStaticIntArrayMethod(const char* className, const char* methodName, Ts&&... xs) + static int* callStaticIntArrayMethod(const std::string& className, const std::string& methodName, Ts... xs) { static int ret[32]; cocos2d::JniMethodInfo t; - const char* signature = jni::TypeSignature(std::decay_t...)>{}(); - if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, signature)) + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")[I"; + if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; jintArray array = @@ -267,12 +240,12 @@ public: @return JniMethodInfo of Vec3 type if there are proper JniMethodInfo; otherwise Vec3(0, 0, 0). */ template - static Vec3 callStaticVec3Method(const char* className, const char* methodName, Ts&&... xs) + static Vec3 callStaticVec3Method(const std::string& className, const std::string& methodName, Ts... xs) { Vec3 ret; cocos2d::JniMethodInfo t; - const char* signature = jni::TypeSignature(std::decay_t...)>{}(); - if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, signature)) + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")[F"; + if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; jfloatArray array = @@ -301,12 +274,12 @@ public: @return value from Java static double method if there are proper JniMethodInfo; otherwise 0. */ template - static double callStaticDoubleMethod(const char* className, const char* methodName, Ts&&... xs) + static double callStaticDoubleMethod(const std::string& className, const std::string& methodName, Ts... xs) { jdouble ret = 0.0; cocos2d::JniMethodInfo t; - const char* signature = jni::TypeSignature...)>{}(); - if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, signature)) + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")D"; + if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; ret = t.env->CallStaticDoubleMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); @@ -325,13 +298,13 @@ public: @return JniMethodInfo of string type if there are proper JniMethodInfo; otherwise empty string. */ template - static std::string callStaticStringMethod(const char* className, const char* methodName, Ts&&... xs) + static std::string callStaticStringMethod(const std::string& className, const std::string& methodName, Ts... xs) { std::string ret; cocos2d::JniMethodInfo t; - const char* signature = jni::TypeSignature...)>{}(); - if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, signature)) + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")Ljava/lang/String;"; + if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; jstring jret = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); @@ -361,8 +334,6 @@ private: static jstring convert(LocalRefMapType& localRefs, cocos2d::JniMethodInfo& t, const char* x); - static jstring convert(LocalRefMapType& localRefs, cocos2d::JniMethodInfo& t, std::string_view x); - static jstring convert(LocalRefMapType& localRefs, cocos2d::JniMethodInfo& t, const std::string& x); inline static jint convert(LocalRefMapType&, cocos2d::JniMethodInfo&, int32_t value) @@ -406,7 +377,41 @@ private: static void deleteLocalRefs(JNIEnv* env, LocalRefMapType& localRefs); - static void reportError(const char* className, const char* methodName, const char* signature); + static std::string getJNISignature() { return ""; } + + static std::string getJNISignature(bool) { return "Z"; } + + static std::string getJNISignature(char) { return "C"; } + + static std::string getJNISignature(short) { return "S"; } + + static std::string getJNISignature(int) { return "I"; } + + static std::string getJNISignature(long) { return "J"; } + + static std::string getJNISignature(float) { return "F"; } + + static std::string getJNISignature(double) { return "D"; } + + static std::string getJNISignature(const char*) { return "Ljava/lang/String;"; } + + static std::string getJNISignature(const std::string&) { return "Ljava/lang/String;"; } + + template + static std::string getJNISignature(T x) + { + // This template should never be instantiated + static_assert(sizeof(x) == 0, "Unsupported argument type"); + return ""; + } + + template + static std::string getJNISignature(T x, Ts... xs) + { + return getJNISignature(x) + getJNISignature(xs...); + } + + static void reportError(const std::string& className, const std::string& methodName, const std::string& signature); }; NS_CC_END diff --git a/cocos/platform/apple/CCDevice-apple.mm b/cocos/platform/apple/CCDevice-apple.mm index fff35eb1bb..e4a72afd2f 100644 --- a/cocos/platform/apple/CCDevice-apple.mm +++ b/cocos/platform/apple/CCDevice-apple.mm @@ -2,19 +2,19 @@ Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -29,56 +29,51 @@ #if CC_TARGET_PLATFORM == CC_PLATFORM_MAC -# include -# include -# include +#include +#include +#include #elif CC_TARGET_PLATFORM == CC_PLATFORM_IOS -# import +#import #endif #include "base/ccTypes.h" #include "platform/apple/CCDevice-apple.h" -namespace FontUtils -{ -NSMutableParagraphStyle* _calculateParagraphStyle(bool enableWrap, int overflow) -{ - NSMutableParagraphStyle* paragraphStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; - paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; - return paragraphStyle; -} - -NSTextAlignment _calculateTextAlignment(cocos2d::Device::TextAlign align) -{ - unsigned uHoriFlag = (int)align & 0x0f; - NSTextAlignment nsAlign = (2 == uHoriFlag) ? NSTextAlignmentRight - : (3 == uHoriFlag) ? NSTextAlignmentCenter - : NSTextAlignmentLeft; - - return nsAlign; -} - -CGFloat _calculateTextDrawStartWidth(cocos2d::Device::TextAlign align, CGSize realDimensions, CGSize dimensions) -{ - CGFloat xPadding = 0; - unsigned uHoriFlag = (int)align & 0x0f; - switch (uHoriFlag) +namespace FontUtils { + NSMutableParagraphStyle* _calculateParagraphStyle(bool enableWrap, int overflow) { - // center - case 3: - xPadding = (dimensions.width - realDimensions.width) / 2.0f; - break; - // right - case 2: - xPadding = dimensions.width - realDimensions.width; - break; - default: - break; + NSMutableParagraphStyle* paragraphStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; + paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; + return paragraphStyle; + } + + NSTextAlignment _calculateTextAlignment(cocos2d::Device::TextAlign align) + { + unsigned uHoriFlag = (int)align & 0x0f; + NSTextAlignment nsAlign = (2 == uHoriFlag) ? NSTextAlignmentRight + : (3 == uHoriFlag) ? NSTextAlignmentCenter + : NSTextAlignmentLeft; + + return nsAlign; + } + + + + CGFloat _calculateTextDrawStartWidth(cocos2d::Device::TextAlign align, CGSize realDimensions, CGSize dimensions) + { + CGFloat xPadding = 0; + unsigned uHoriFlag = (int)align & 0x0f; + switch (uHoriFlag) { + //center + case 3: xPadding = (dimensions.width - realDimensions.width) / 2.0f; break; + //right + case 2: xPadding = dimensions.width - realDimensions.width; break; + default: break; + } + return xPadding; } - return xPadding; -} } diff --git a/cocos/platform/apple/CCFileUtils-apple.h b/cocos/platform/apple/CCFileUtils-apple.h index 14a3fb62e4..8eff83505a 100644 --- a/cocos/platform/apple/CCFileUtils-apple.h +++ b/cocos/platform/apple/CCFileUtils-apple.h @@ -51,21 +51,21 @@ public: /* override functions */ virtual std::string getWritablePath() const override; virtual std::string getNativeWritableAbsolutePath() const override; - virtual std::string getFullPathForFilenameWithinDirectory(std::string_view directory, - std::string_view filename) const override; + virtual std::string getFullPathForFilenameWithinDirectory(const std::string& directory, + const std::string& filename) const override; #if CC_FILEUTILS_APPLE_ENABLE_OBJC void setBundle(NSBundle* bundle); #endif - virtual bool createDirectory(std::string_view path) const override; - virtual std::string getPathForDirectory(std::string_view dir, - std::string_view resolutionDiretory, - std::string_view searchPath) const override; + virtual bool createDirectory(const std::string& path) const override; + virtual std::string getPathForDirectory(const std::string& dir, + const std::string& resolutionDiretory, + const std::string& searchPath) const override; private: - virtual bool isFileExistInternal(std::string_view filePath) const override; - virtual bool removeDirectory(std::string_view dirPath) const override; + virtual bool isFileExistInternal(const std::string& filePath) const override; + virtual bool removeDirectory(const std::string& dirPath) const override; struct IMPL; std::unique_ptr pimpl_; diff --git a/cocos/platform/apple/CCFileUtils-apple.mm b/cocos/platform/apple/CCFileUtils-apple.mm index 3c4717884c..75dabafb21 100644 --- a/cocos/platform/apple/CCFileUtils-apple.mm +++ b/cocos/platform/apple/CCFileUtils-apple.mm @@ -36,27 +36,29 @@ THE SOFTWARE. #include "base/CCDirector.h" #include "platform/CCFileUtils.h" -#define DECLARE_GUARD (void)0 // std::lock_guard mutexGuard(_mutex) +#define DECLARE_GUARD (void)0 // std::lock_guard mutexGuard(_mutex) NS_CC_BEGIN -struct FileUtilsApple::IMPL -{ - IMPL(NSBundle* bundle) : bundle_([NSBundle mainBundle]) {} - void setBundle(NSBundle* bundle) { bundle_ = bundle; } - NSBundle* getBundle() const { return bundle_; } - +struct FileUtilsApple::IMPL { + IMPL(NSBundle* bundle):bundle_([NSBundle mainBundle]) {} + void setBundle(NSBundle* bundle) { + bundle_ = bundle; + } + NSBundle* getBundle() const { + return bundle_; + } private: NSBundle* bundle_; }; -FileUtilsApple::FileUtilsApple() : pimpl_(new IMPL([NSBundle mainBundle])) {} +FileUtilsApple::FileUtilsApple() : pimpl_(new IMPL([NSBundle mainBundle])) { +} FileUtilsApple::~FileUtilsApple() = default; #if CC_FILEUTILS_APPLE_ENABLE_OBJC -void FileUtilsApple::setBundle(NSBundle* bundle) -{ +void FileUtilsApple::setBundle(NSBundle* bundle) { pimpl_->setBundle(bundle); } #endif @@ -70,16 +72,17 @@ FileUtils* FileUtils::getInstance() if (s_sharedFileUtils == nullptr) { s_sharedFileUtils = new FileUtilsApple(); - if (!s_sharedFileUtils->init()) + if(!s_sharedFileUtils->init()) { - delete s_sharedFileUtils; - s_sharedFileUtils = nullptr; - CCLOG("ERROR: Could not init CCFileUtilsApple"); + delete s_sharedFileUtils; + s_sharedFileUtils = nullptr; + CCLOG("ERROR: Could not init CCFileUtilsApple"); } } return s_sharedFileUtils; } + std::string FileUtilsApple::getWritablePath() const { DECLARE_GUARD; @@ -95,14 +98,14 @@ std::string FileUtilsApple::getNativeWritableAbsolutePath() const } // save to document folder - NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); - NSString* documentsDirectory = [paths objectAtIndex:0]; - std::string strRet = [documentsDirectory UTF8String]; + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *documentsDirectory = [paths objectAtIndex:0]; + std::string strRet = [documentsDirectory UTF8String]; strRet.append("/"); return strRet; } -bool FileUtilsApple::isFileExistInternal(std::string_view filePath) const +bool FileUtilsApple::isFileExistInternal(const std::string& filePath) const { if (filePath.empty()) { @@ -118,8 +121,8 @@ bool FileUtilsApple::isFileExistInternal(std::string_view filePath) const size_t pos = filePath.find_last_of("/"); if (pos != std::string::npos) { - file = filePath.substr(pos + 1); - path = filePath.substr(0, pos + 1); + file = filePath.substr(pos+1); + path = filePath.substr(0, pos+1); } else { @@ -127,18 +130,16 @@ bool FileUtilsApple::isFileExistInternal(std::string_view filePath) const } NSString* fullpath = [pimpl_->getBundle() pathForResource:[NSString stringWithUTF8String:file.c_str()] - ofType:nil - inDirectory:[NSString stringWithUTF8String:path.c_str()]]; - if (fullpath != nil) - { + ofType:nil + inDirectory:[NSString stringWithUTF8String:path.c_str()]]; + if (fullpath != nil) { ret = true; } } else { // Search path is an absolute path. - if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:filePath.data()]]) - { + if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:filePath.c_str()]]) { ret = true; } } @@ -146,18 +147,18 @@ bool FileUtilsApple::isFileExistInternal(std::string_view filePath) const return ret; } -static int unlink_cb(const char* fpath, const struct stat* sb, int typeflag, struct FTW* ftwbuf) +static int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) { auto ret = remove(fpath); if (ret) { - log("Fail to remove: %s ", fpath); + log("Fail to remove: %s ",fpath); } return ret; } -bool FileUtilsApple::removeDirectory(std::string_view path) const +bool FileUtilsApple::removeDirectory(const std::string& path) const { if (path.empty()) { @@ -165,89 +166,78 @@ bool FileUtilsApple::removeDirectory(std::string_view path) const return false; } - if (nftw(path.data(), unlink_cb, 64, FTW_DEPTH | FTW_PHYS)) + if (nftw(path.c_str(),unlink_cb, 64, FTW_DEPTH | FTW_PHYS)) return false; else return true; } -std::string FileUtilsApple::getPathForDirectory(std::string_view dir, - std::string_view resolutionDiretory, - std::string_view searchPath) const +std::string FileUtilsApple::getPathForDirectory(const std::string &dir, const std::string &resolutionDiretory, const std::string &searchPath) const { - std::string path{searchPath}; - path.append(resolutionDiretory).append(dir); - - if (!path.empty() && path[path.length() - 1] == '/') - { + auto path = searchPath + resolutionDiretory + dir; + + if(!path.empty() && path[path.length() -1] == '/') { path.erase(path.end() - 1); } - - if (path[0] == '/') + + if(path[0] == '/') { BOOL isDir = false; - if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:dir.data()] isDirectory:&isDir]) - { + if([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:dir.c_str()] + isDirectory:&isDir]) { return isDir ? path : ""; } } else { - NSString* fullpath = [pimpl_->getBundle() pathForResource:[NSString stringWithUTF8String:path.c_str()] + NSString *fullpath = [pimpl_->getBundle() pathForResource:[NSString stringWithUTF8String:path.c_str()] ofType:nil]; - if (fullpath != nil) - { + if(fullpath != nil) { return [fullpath UTF8String]; } } return ""; } -std::string FileUtilsApple::getFullPathForFilenameWithinDirectory(std::string_view directory, - std::string_view filename) const + +std::string FileUtilsApple::getFullPathForFilenameWithinDirectory(const std::string& directory, const std::string& filename) const { if (directory[0] != '/') { - NSString* fullpath = [pimpl_->getBundle() pathForResource:[NSString stringWithUTF8String:filename.data()] - ofType:nil - inDirectory:[NSString stringWithUTF8String:directory.data()]]; - if (fullpath != nil) - { + NSString* fullpath = [pimpl_->getBundle() pathForResource:[NSString stringWithUTF8String:filename.c_str()] + ofType:nil + inDirectory:[NSString stringWithUTF8String:directory.c_str()]]; + if (fullpath != nil) { return [fullpath UTF8String]; } } else { - std::string fullPath{directory}; - fullPath += filename; + std::string fullPath = directory+filename; // Search path is an absolute path. - if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:fullPath.c_str()]]) - { + if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:fullPath.c_str()]]) { return fullPath; } } return ""; } -bool FileUtilsApple::createDirectory(std::string_view path) const +bool FileUtilsApple::createDirectory(const std::string& path) const { CCASSERT(!path.empty(), "Invalid path"); - + if (isDirectoryExist(path)) return true; - + NSError* error; - - bool result = [s_fileManager createDirectoryAtPath:[NSString stringWithUTF8String:path.data()] - withIntermediateDirectories:YES - attributes:nil - error:&error]; - - if (!result && error != nil) + + bool result = [s_fileManager createDirectoryAtPath:[NSString stringWithUTF8String:path.c_str()] withIntermediateDirectories:YES attributes:nil error:&error]; + + if(!result && error != nil) { - CCLOGERROR("Fail to create directory \"%s\": %s", path.data(), [error.localizedDescription UTF8String]); + CCLOGERROR("Fail to create directory \"%s\": %s", path.c_str(), [error.localizedDescription UTF8String]); } - + return result; } diff --git a/cocos/platform/desktop/CCGLViewImpl-desktop.cpp b/cocos/platform/desktop/CCGLViewImpl-desktop.cpp index d3183da959..7f18509643 100644 --- a/cocos/platform/desktop/CCGLViewImpl-desktop.cpp +++ b/cocos/platform/desktop/CCGLViewImpl-desktop.cpp @@ -326,12 +326,12 @@ GLViewImpl::~GLViewImpl() #endif } -GLViewImpl* GLViewImpl::create(std::string_view viewName) +GLViewImpl* GLViewImpl::create(const std::string& viewName) { return GLViewImpl::create(viewName, false); } -GLViewImpl* GLViewImpl::create(std::string_view viewName, bool resizable) +GLViewImpl* GLViewImpl::create(const std::string& viewName, bool resizable) { auto ret = new GLViewImpl; if (ret->initWithRect(viewName, Rect(0, 0, 960, 640), 1.0f, resizable)) @@ -343,7 +343,7 @@ GLViewImpl* GLViewImpl::create(std::string_view viewName, bool resizable) return nullptr; } -GLViewImpl* GLViewImpl::createWithRect(std::string_view viewName, Rect rect, float frameZoomFactor, bool resizable) +GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable) { auto ret = new GLViewImpl; if (ret->initWithRect(viewName, rect, frameZoomFactor, resizable)) @@ -355,7 +355,7 @@ GLViewImpl* GLViewImpl::createWithRect(std::string_view viewName, Rect rect, flo return nullptr; } -GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName) +GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName) { auto ret = new GLViewImpl(); if (ret->initWithFullScreen(viewName)) @@ -367,7 +367,7 @@ GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName) return nullptr; } -GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName, +GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName, const GLFWvidmode& videoMode, GLFWmonitor* monitor) { @@ -381,7 +381,7 @@ GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName, return nullptr; } -bool GLViewImpl::initWithRect(std::string_view viewName, Rect rect, float frameZoomFactor, bool resizable) +bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable) { setViewName(viewName); @@ -509,7 +509,7 @@ bool GLViewImpl::initWithRect(std::string_view viewName, Rect rect, float frameZ return true; } -bool GLViewImpl::initWithFullScreen(std::string_view viewName) +bool GLViewImpl::initWithFullScreen(const std::string& viewName) { // Create fullscreen window on primary monitor at its current video mode. _monitor = glfwGetPrimaryMonitor(); @@ -520,7 +520,7 @@ bool GLViewImpl::initWithFullScreen(std::string_view viewName) return initWithRect(viewName, Rect(0, 0, (float)videoMode->width, (float)videoMode->height), 1.0f, false); } -bool GLViewImpl::initWithFullscreen(std::string_view viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor) +bool GLViewImpl::initWithFullscreen(const std::string& viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor) { // Create fullscreen on specified monitor at the specified video mode. _monitor = monitor; @@ -575,29 +575,30 @@ void GLViewImpl::pollEvents() void GLViewImpl::enableRetina(bool enabled) { // official v4 comment follow sources - // #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) - // _isRetinaEnabled = enabled; - // if (_isRetinaEnabled) - // { - // _retinaFactor = 1; - // } - // else - // { - // _retinaFactor = 2; - // } - // updateFrameSize(); - // #endif + // #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) + // _isRetinaEnabled = enabled; + // if (_isRetinaEnabled) + // { + // _retinaFactor = 1; + // } + // else + // { + // _retinaFactor = 2; + // } + // updateFrameSize(); + // #endif } void GLViewImpl::setIMEKeyboardState(bool /*bOpen*/) {} #if CC_ICON_SET_SUPPORT -void GLViewImpl::setIcon(std::string_view filename) const +void GLViewImpl::setIcon(const std::string& filename) const { - this->setIcon(std::vector{filename}); + std::vector vec = {filename}; + this->setIcon(vec); } -void GLViewImpl::setIcon(const std::vector& filelist) const +void GLViewImpl::setIcon(const std::vector& filelist) const { if (filelist.empty()) return; diff --git a/cocos/platform/desktop/CCGLViewImpl-desktop.h b/cocos/platform/desktop/CCGLViewImpl-desktop.h index 74c7d895fe..f46a0f0ec2 100644 --- a/cocos/platform/desktop/CCGLViewImpl-desktop.h +++ b/cocos/platform/desktop/CCGLViewImpl-desktop.h @@ -60,14 +60,14 @@ class CC_DLL GLViewImpl : public GLView friend class GLFWEventHandler; public: - static GLViewImpl* create(std::string_view viewName); - static GLViewImpl* create(std::string_view viewName, bool resizable); - static GLViewImpl* createWithRect(std::string_view viewName, + static GLViewImpl* create(const std::string& viewName); + static GLViewImpl* create(const std::string& viewName, bool resizable); + static GLViewImpl* createWithRect(const std::string& viewName, Rect size, float frameZoomFactor = 1.0f, bool resizable = false); - static GLViewImpl* createWithFullScreen(std::string_view viewName); - static GLViewImpl* createWithFullScreen(std::string_view viewName, + static GLViewImpl* createWithFullScreen(const std::string& viewName); + static GLViewImpl* createWithFullScreen(const std::string& viewName, const GLFWvidmode& videoMode, GLFWmonitor* monitor); @@ -121,8 +121,8 @@ public: virtual void setIMEKeyboardState(bool bOpen) override; #if CC_ICON_SET_SUPPORT - virtual void setIcon(std::string_view filename) const override; - virtual void setIcon(const std::vector& filelist) const override; + virtual void setIcon(const std::string& filename) const override; + virtual void setIcon(const std::vector& filelist) const override; virtual void setDefaultIcon() const override; #endif /* CC_ICON_SET_SUPPORT */ @@ -157,9 +157,9 @@ protected: GLViewImpl(bool initglfw = true); virtual ~GLViewImpl(); - bool initWithRect(std::string_view viewName, Rect rect, float frameZoomFactor, bool resizable); - bool initWithFullScreen(std::string_view viewName); - bool initWithFullscreen(std::string_view viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor); + bool initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable); + bool initWithFullScreen(const std::string& viewName); + bool initWithFullscreen(const std::string& viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor); bool loadGL(); diff --git a/cocos/platform/ios/CCApplication-ios.h b/cocos/platform/ios/CCApplication-ios.h index d87e7a79bc..bcced55ac1 100644 --- a/cocos/platform/ios/CCApplication-ios.h +++ b/cocos/platform/ios/CCApplication-ios.h @@ -87,7 +87,7 @@ public: @param String with url to open. @return true if the resource located by the URL was successfully opened; otherwise false. */ - virtual bool openURL(std::string_view url) override; + virtual bool openURL(const std::string& url) override; /** @brief This function will be called when the application screen size is changed. diff --git a/cocos/platform/ios/CCApplication-ios.mm b/cocos/platform/ios/CCApplication-ios.mm index 79d3576b03..fbf2827c29 100644 --- a/cocos/platform/ios/CCApplication-ios.mm +++ b/cocos/platform/ios/CCApplication-ios.mm @@ -37,7 +37,7 @@ Application* Application::sm_pSharedApplication = nullptr; Application::Application() { - CC_ASSERT(!sm_pSharedApplication); + CC_ASSERT(! sm_pSharedApplication); sm_pSharedApplication = this; } @@ -58,7 +58,7 @@ int Application::run() void Application::setAnimationInterval(float interval) { - [[CCDirectorCaller sharedDirectorCaller] setAnimationInterval:interval]; + [[CCDirectorCaller sharedDirectorCaller] setAnimationInterval: interval ]; } ///////////////////////////////////////////////////////////////////////////////////////////////// @@ -71,39 +71,39 @@ Application* Application::getInstance() return sm_pSharedApplication; } -const char* Application::getCurrentLanguageCode() +const char * Application::getCurrentLanguageCode() { - static char code[3] = {0}; - NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; - NSArray* languages = [defaults objectForKey:@"AppleLanguages"]; - NSString* currentLanguage = [languages objectAtIndex:0]; + static char code[3]={0}; + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + NSArray *languages = [defaults objectForKey:@"AppleLanguages"]; + NSString *currentLanguage = [languages objectAtIndex:0]; // get the current language code.(such as English is "en", Chinese is "zh" and so on) - NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; - NSString* languageCode = [temp objectForKey:NSLocaleLanguageCode]; + NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; + NSString * languageCode = [temp objectForKey:NSLocaleLanguageCode]; [languageCode getCString:code maxLength:3 encoding:NSASCIIStringEncoding]; - code[2] = '\0'; + code[2]='\0'; return code; } LanguageType Application::getCurrentLanguage() { // get the current language and country config - NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; - NSArray* languages = [defaults objectForKey:@"AppleLanguages"]; - NSString* currentLanguage = [languages objectAtIndex:0]; + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + NSArray *languages = [defaults objectForKey:@"AppleLanguages"]; + NSString *currentLanguage = [languages objectAtIndex:0]; // get the current language code.(such as English is "en", Chinese is "zh" and so on) - NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; - NSString* languageCode = [temp objectForKey:NSLocaleLanguageCode]; + NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; + NSString * languageCode = [temp objectForKey:NSLocaleLanguageCode]; return utils::getLanguageTypeByISO2([languageCode UTF8String]); + } Application::Platform Application::getTargetPlatform() { - if ([UIDevice.currentDevice userInterfaceIdiom] == - UIUserInterfaceIdiomPad) // idiom for iOS <= 3.2, otherwise: [UIDevice userInterfaceIdiom] is faster. + if ([UIDevice.currentDevice userInterfaceIdiom] == UIUserInterfaceIdiomPad) // idiom for iOS <= 3.2, otherwise: [UIDevice userInterfaceIdiom] is faster. { return Platform::OS_IPAD; } @@ -113,23 +113,21 @@ Application::Platform Application::getTargetPlatform() } } -std::string Application::getVersion() -{ +std::string Application::getVersion() { NSString* version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]; - if (version) - { + if (version) { return [version UTF8String]; } return ""; } -bool Application::openURL(std::string_view url) +bool Application::openURL(const std::string &url) { - NSString* msg = [NSString stringWithCString:url.data() encoding:NSUTF8StringEncoding]; - NSURL* nsUrl = [NSURL URLWithString:msg]; - + NSString* msg = [NSString stringWithCString:url.c_str() encoding:NSUTF8StringEncoding]; + NSURL* nsUrl = [NSURL URLWithString:msg]; + id application = [UIApplication sharedApplication]; - if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) + if ([application respondsToSelector:@selector(openURL:options:completionHandler:)] ) { [application openURL:nsUrl options:@{} completionHandler:nil]; } @@ -139,6 +137,8 @@ bool Application::openURL(std::string_view url) } } -void Application::applicationScreenSizeChanged(int newWidth, int newHeight) {} +void Application::applicationScreenSizeChanged(int newWidth, int newHeight) { + +} NS_CC_END diff --git a/cocos/platform/ios/CCCommon-ios.mm b/cocos/platform/ios/CCCommon-ios.mm index fb2a462e63..254978be54 100644 --- a/cocos/platform/ios/CCCommon-ios.mm +++ b/cocos/platform/ios/CCCommon-ios.mm @@ -36,30 +36,29 @@ NS_CC_BEGIN // ios no MessageBox, use log instead -void ccMessageBox(const char* msg, const char* title) +void ccMessageBox(const char * msg, const char * title) { // only enable it on iOS. // FIXME: Implement it for tvOS #if !defined(CC_TARGET_OS_TVOS) - NSString* tmpTitle = (title) ? [NSString stringWithUTF8String:title] : nil; - NSString* tmpMsg = (msg) ? [NSString stringWithUTF8String:msg] : nil; + NSString * tmpTitle = (title) ? [NSString stringWithUTF8String : title] : nil; + NSString * tmpMsg = (msg) ? [NSString stringWithUTF8String : msg] : nil; UIAlertController* alertController = [UIAlertController alertControllerWithTitle:tmpTitle - message:tmpMsg - preferredStyle:UIAlertControllerStyleAlert]; + message:tmpMsg + preferredStyle:UIAlertControllerStyleAlert]; - UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" - style:UIAlertActionStyleDefault - handler:^(UIAlertAction* action){ - }]; + UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault + handler:^(UIAlertAction * action) {}]; [alertController addAction:defaultAction]; auto rootViewController = [UIApplication sharedApplication].windows[0].rootViewController; [rootViewController presentViewController:alertController animated:YES completion:nil]; #endif + } -void LuaLog(const char* format) +void LuaLog(const char * format) { puts(format); } diff --git a/cocos/platform/ios/CCDevice-ios.mm b/cocos/platform/ios/CCDevice-ios.mm index ae01148a19..9b3036fbc8 100644 --- a/cocos/platform/ios/CCDevice-ios.mm +++ b/cocos/platform/ios/CCDevice-ios.mm @@ -34,30 +34,29 @@ // Accelerometer #if !defined(CC_TARGET_OS_TVOS) -# import +#import #endif -#import +#import #import // Vibrate #import const float MAX_MEASURE_HEIGHT = 10000; + static NSAttributedString* __attributedStringWithFontSize(NSMutableAttributedString* attributedString, CGFloat fontSize) { { [attributedString beginEditing]; - [attributedString enumerateAttribute:NSFontAttributeName - inRange:NSMakeRange(0, attributedString.length) - options:0 - usingBlock:^(id value, NSRange range, BOOL* stop) { - UIFont* font = value; - font = [font fontWithSize:fontSize]; + [attributedString enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, attributedString.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) { - [attributedString removeAttribute:NSFontAttributeName range:range]; - [attributedString addAttribute:NSFontAttributeName value:font range:range]; - }]; + UIFont* font = value; + font = [font fontWithSize:fontSize]; + + [attributedString removeAttribute:NSFontAttributeName range:range]; + [attributedString addAttribute:NSFontAttributeName value:font range:range]; + }]; [attributedString endEditing]; } @@ -70,116 +69,97 @@ static CGFloat _calculateTextDrawStartHeight(cocos2d::Device::TextAlign align, C float startH = 0; // vertical alignment unsigned int vAlignment = ((int)align >> 4) & 0x0F; - switch (vAlignment) - { - // bottom - case 2: - startH = dimensions.height - realDimensions.height; - break; - // top - case 1: - startH = 0; - break; - // center - case 3: - startH = (dimensions.height - realDimensions.height) / 2; - break; - default: - break; + switch (vAlignment) { + //bottom + case 2:startH = dimensions.height - realDimensions.height;break; + //top + case 1:startH = 0;break; + //center + case 3: startH = (dimensions.height - realDimensions.height) / 2;break; + default: + break; } return startH; } -static CGSize _calculateShrinkedSizeForString(NSAttributedString** str, +static CGSize _calculateShrinkedSizeForString(NSAttributedString **str, id font, CGSize constrainSize, bool enableWrap, int& newFontSize) { CGRect actualSize = CGRectMake(0, 0, constrainSize.width + 1, constrainSize.height + 1); - int fontSize = [font pointSize]; - fontSize = fontSize + 1; + int fontSize = [font pointSize]; + fontSize = fontSize + 1; - if (!enableWrap) - { - while (actualSize.size.width > constrainSize.width || actualSize.size.height > constrainSize.height) - { + if (!enableWrap) { + while (actualSize.size.width > constrainSize.width || + actualSize.size.height > constrainSize.height) { fontSize = fontSize - 1; - if (fontSize < 0) - { + if(fontSize < 0) { actualSize = CGRectMake(0, 0, 0, 0); break; } - NSMutableAttributedString* mutableString = [[*str mutableCopy] autorelease]; - *str = __attributedStringWithFontSize(mutableString, fontSize); + NSMutableAttributedString *mutableString = [[*str mutableCopy] autorelease]; + *str = __attributedStringWithFontSize(mutableString, fontSize); - CTFramesetterRef framesetter = - CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef) * str); + CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)*str); CGSize targetSize = CGSizeMake(MAX_MEASURE_HEIGHT, MAX_MEASURE_HEIGHT); - CGSize fitSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, [(*str) length]), - NULL, targetSize, NULL); + CGSize fitSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, [(*str) length]), NULL, targetSize, NULL); CFRelease(framesetter); - if (fitSize.width == 0 || fitSize.height == 0) - { + if (fitSize.width == 0 || fitSize.height == 0) { continue; } - + actualSize.size = fitSize; - - if (constrainSize.width <= 0) - { + + if (constrainSize.width <= 0) { constrainSize.width = fitSize.width; } - if (constrainSize.height <= 0) - { + if (constrainSize.height <= 0) { constrainSize.height = fitSize.height; } - if (fontSize <= 0) - { + if (fontSize <= 0) { break; } } + } - else - { - while (actualSize.size.height > constrainSize.height || actualSize.size.width > constrainSize.width) - { + else { + while (actualSize.size.height > constrainSize.height || + actualSize.size.width > constrainSize.width) { fontSize = fontSize - 1; - if (fontSize < 0) - { + if(fontSize < 0) { actualSize = CGRectMake(0, 0, 0, 0); break; } - - NSMutableAttributedString* mutableString = [[*str mutableCopy] autorelease]; - *str = __attributedStringWithFontSize(mutableString, fontSize); - + + NSMutableAttributedString *mutableString = [[*str mutableCopy] autorelease]; + *str = __attributedStringWithFontSize(mutableString, fontSize); + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake(constrainSize.width, MAX_MEASURE_HEIGHT) - options:(NSStringDrawingUsesLineFragmentOrigin)context:nil] - .size; + options:(NSStringDrawingUsesLineFragmentOrigin) + context:nil].size; - if (fitSize.width == 0 || fitSize.height == 0) - { + if (fitSize.width == 0 || fitSize.height == 0) { continue; } - + actualSize.size = fitSize; - - if (constrainSize.height <= 0) - { + + if (constrainSize.height <= 0) { constrainSize.height = fitSize.height; } - if (constrainSize.width <= 0) - { + if (constrainSize.width <= 0) { constrainSize.width = fitSize.width; } - if (fontSize <= 0) - { + if (fontSize <= 0) { break; } } + } newFontSize = fontSize; @@ -190,15 +170,16 @@ static CGSize _calculateShrinkedSizeForString(NSAttributedString** str, #define SENSOR_DELAY_GAME 0.02 #if !defined(CC_TARGET_OS_TVOS) -@interface CCAccelerometerDispatcher : NSObject { - cocos2d::Acceleration* _acceleration; - CMMotionManager* _motionManager; +@interface CCAccelerometerDispatcher : NSObject +{ + cocos2d::Acceleration *_acceleration; + CMMotionManager *_motionManager; } -+ (id)sharedAccelerometerDispatcher; -- (id)init; -- (void)setAccelerometerEnabled:(bool)isEnabled; -- (void)setAccelerometerInterval:(float)interval; ++ (id) sharedAccelerometerDispatcher; +- (id) init; +- (void) setAccelerometerEnabled: (bool) isEnabled; +- (void) setAccelerometerInterval:(float) interval; @end @@ -206,28 +187,26 @@ static CGSize _calculateShrinkedSizeForString(NSAttributedString** str, static CCAccelerometerDispatcher* s_pAccelerometerDispatcher; -+ (id)sharedAccelerometerDispatcher ++ (id) sharedAccelerometerDispatcher { - if (s_pAccelerometerDispatcher == nil) - { + if (s_pAccelerometerDispatcher == nil) { s_pAccelerometerDispatcher = [[self alloc] init]; } return s_pAccelerometerDispatcher; } -- (id)init +- (id) init { - if ((self = [super init])) - { - _acceleration = new cocos2d::Acceleration(); - _motionManager = [[CMMotionManager alloc] init]; + if( (self = [super init]) ) { + _acceleration = new cocos2d::Acceleration(); + _motionManager = [[CMMotionManager alloc] init]; _motionManager.accelerometerUpdateInterval = SENSOR_DELAY_GAME; } return self; } -- (void)dealloc +- (void) dealloc { s_pAccelerometerDispatcher = nullptr; delete _acceleration; @@ -235,14 +214,13 @@ static CCAccelerometerDispatcher* s_pAccelerometerDispatcher; [super dealloc]; } -- (void)setAccelerometerEnabled:(bool)isEnabled +- (void) setAccelerometerEnabled: (bool) isEnabled { if (isEnabled) { - [_motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] - withHandler:^(CMAccelerometerData* accelerometerData, NSError* error) { - [self accelerometer:accelerometerData]; - }]; + [_motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) { + [self accelerometer:accelerometerData]; + }]; } else { @@ -250,16 +228,16 @@ static CCAccelerometerDispatcher* s_pAccelerometerDispatcher; } } -- (void)setAccelerometerInterval:(float)interval +-(void) setAccelerometerInterval:(float)interval { _motionManager.accelerometerUpdateInterval = interval; } -- (void)accelerometer:(CMAccelerometerData*)accelerometerData +- (void)accelerometer:(CMAccelerometerData *)accelerometerData { - _acceleration->x = accelerometerData.acceleration.x; - _acceleration->y = accelerometerData.acceleration.y; - _acceleration->z = accelerometerData.acceleration.z; + _acceleration->x = accelerometerData.acceleration.x; + _acceleration->y = accelerometerData.acceleration.y; + _acceleration->z = accelerometerData.acceleration.z; _acceleration->timestamp = accelerometerData.timestamp; double tmp = _acceleration->x; @@ -273,28 +251,28 @@ static CCAccelerometerDispatcher* s_pAccelerometerDispatcher; // Fallback on earlier versions orientation = [[UIApplication sharedApplication] statusBarOrientation]; } - + switch (orientation) { - case UIInterfaceOrientationLandscapeRight: - _acceleration->x = -_acceleration->y; - _acceleration->y = tmp; - break; - - case UIInterfaceOrientationLandscapeLeft: - _acceleration->x = _acceleration->y; - _acceleration->y = -tmp; - break; - - case UIInterfaceOrientationPortraitUpsideDown: - _acceleration->x = -_acceleration->y; - _acceleration->y = -tmp; - break; - - case UIInterfaceOrientationPortrait: - break; - default: - NSAssert(false, @"unknown orientation"); + case UIInterfaceOrientationLandscapeRight: + _acceleration->x = -_acceleration->y; + _acceleration->y = tmp; + break; + + case UIInterfaceOrientationLandscapeLeft: + _acceleration->x = _acceleration->y; + _acceleration->y = -tmp; + break; + + case UIInterfaceOrientationPortraitUpsideDown: + _acceleration->x = -_acceleration->y; + _acceleration->y = -tmp; + break; + + case UIInterfaceOrientationPortrait: + break; + default: + NSAssert(false, @"unknown orientation"); } cocos2d::EventAcceleration event(*_acceleration); @@ -302,7 +280,8 @@ static CCAccelerometerDispatcher* s_pAccelerometerDispatcher; dispatcher->dispatchEvent(&event); } @end -#endif // !defined(CC_TARGET_OS_TVOS) +#endif // !defined(CC_TARGET_OS_TVOS) + // @@ -316,28 +295,23 @@ int Device::getDPI() { float scale = 1.0f; - if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) - { + if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { scale = [[UIScreen mainScreen] scale]; } UIUserInterfaceIdiom userInterfaceIdiom = [UIDevice.currentDevice userInterfaceIdiom]; - if (userInterfaceIdiom == UIUserInterfaceIdiomPad) - { + if (userInterfaceIdiom == UIUserInterfaceIdiomPad) { dpi = 132 * scale; - } - else if (userInterfaceIdiom == UIUserInterfaceIdiomPhone) - { + } else if (userInterfaceIdiom == UIUserInterfaceIdiomPhone) { dpi = 163 * scale; - } - else - { + } else { dpi = 160 * scale; } } return dpi; } + void Device::setAccelerometerEnabled(bool isEnabled) { #if !defined(CC_TARGET_OS_TVOS) @@ -356,74 +330,67 @@ typedef struct { unsigned int height; unsigned int width; - bool isPremultipliedAlpha; - bool hasShadow; - CGSize shadowOffset; - float shadowBlur; - float shadowOpacity; - bool hasStroke; - float strokeColorR; - float strokeColorG; - float strokeColorB; - float strokeColorA; - float strokeSize; - float tintColorR; - float tintColorG; - float tintColorB; - float tintColorA; + bool isPremultipliedAlpha; + bool hasShadow; + CGSize shadowOffset; + float shadowBlur; + float shadowOpacity; + bool hasStroke; + float strokeColorR; + float strokeColorG; + float strokeColorB; + float strokeColorA; + float strokeSize; + float tintColorR; + float tintColorG; + float tintColorB; + float tintColorA; - unsigned char* data; + unsigned char* data; } tImageInfo; -static CGSize _calculateStringSize(NSAttributedString* str, - id font, - CGSize* constrainSize, - bool enableWrap, - int overflow) +static CGSize _calculateStringSize(NSAttributedString *str, id font, CGSize *constrainSize, bool enableWrap, int overflow) { CGSize textRect = CGSizeZero; - textRect.width = constrainSize->width > 0 ? constrainSize->width : MAX_MEASURE_HEIGHT; - textRect.height = constrainSize->height > 0 ? constrainSize->height : MAX_MEASURE_HEIGHT; - - if (overflow == 1) - { - if (!enableWrap) - { - textRect.width = MAX_MEASURE_HEIGHT; + textRect.width = constrainSize->width > 0 ? constrainSize->width + : MAX_MEASURE_HEIGHT; + textRect.height = constrainSize->height > 0 ? constrainSize->height + : MAX_MEASURE_HEIGHT; + + if (overflow == 1) { + if(!enableWrap) { + textRect.width = MAX_MEASURE_HEIGHT; textRect.height = MAX_MEASURE_HEIGHT; - } - else - { + } else { textRect.height = MAX_MEASURE_HEIGHT; } } CGSize dim; dim = [str boundingRectWithSize:CGSizeMake(textRect.width, textRect.height) - options:(NSStringDrawingUsesLineFragmentOrigin)context:nil] - .size; + options:(NSStringDrawingUsesLineFragmentOrigin) + context:nil].size; - dim.width = ceilf(dim.width); + dim.width = ceilf(dim.width); dim.height = ceilf(dim.height); return dim; } -static id _createSystemFont(const char* fontName, int size) +static id _createSystemFont( const char * fontName, int size) { - NSString* fntName = [NSString stringWithUTF8String:fontName]; - // On iOS custom fonts must be listed beforehand in the App info.plist (in order to be usable) and referenced only - // the by the font family name itself when calling [UIFont fontWithName]. Therefore even if the developer adds - // 'SomeFont.ttf' or 'fonts/SomeFont.ttf' to the App .plist, the font must be referenced as 'SomeFont' when calling - // [UIFont fontWithName]. Hence we strip out the folder path components and the extension here in order to get just - // the font family name itself. This stripping step is required especially for references to user fonts stored in - // CCB files; CCB files appear to store the '.ttf' extensions when referring to custom fonts. + NSString * fntName = [NSString stringWithUTF8String:fontName]; + // On iOS custom fonts must be listed beforehand in the App info.plist (in order to be usable) and referenced only the by the font family name itself when + // calling [UIFont fontWithName]. Therefore even if the developer adds 'SomeFont.ttf' or 'fonts/SomeFont.ttf' to the App .plist, the font must + // be referenced as 'SomeFont' when calling [UIFont fontWithName]. Hence we strip out the folder path components and the extension here in order to get just + // the font family name itself. This stripping step is required especially for references to user fonts stored in CCB files; CCB files appear to store + // the '.ttf' extensions when referring to custom fonts. fntName = [[fntName lastPathComponent] stringByDeletingPathExtension]; - + // create the font id font = [UIFont fontWithName:fntName size:size]; - + if (!font) { font = [UIFont systemFontOfSize:size]; @@ -431,89 +398,86 @@ static id _createSystemFont(const char* fontName, int size) return font; } -static bool _initWithString(const char* text, - cocos2d::Device::TextAlign align, - const char* fontName, - int size, - tImageInfo* info, - bool enableWrap, - int overflow) +static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, const char * fontName, int size, tImageInfo* info, bool enableWrap, int overflow) { bool bRet = false; do { - CC_BREAK_IF(!text || !info); + CC_BREAK_IF(! text || ! info); id font = _createSystemFont(fontName, size); - - CC_BREAK_IF(!font); - - NSString* str = [NSString stringWithUTF8String:text]; + + CC_BREAK_IF(! font); + + NSString * str = [NSString stringWithUTF8String:text]; CC_BREAK_IF(!str); CGSize dimensions; - dimensions.width = info->width; - dimensions.height = info->height; + dimensions.width = info->width; + dimensions.height = info->height; - NSTextAlignment nsAlign = FontUtils::_calculateTextAlignment(align); + NSTextAlignment nsAlign = FontUtils::_calculateTextAlignment(align); NSMutableParagraphStyle* paragraphStyle = FontUtils::_calculateParagraphStyle(enableWrap, overflow); - paragraphStyle.alignment = nsAlign; + paragraphStyle.alignment = nsAlign; // measure text size with specified font and determine the rectangle to draw text in - UIColor* foregroundColor = [UIColor colorWithRed:info->tintColorR - green:info->tintColorG - blue:info->tintColorB - alpha:info->tintColorA]; + UIColor *foregroundColor = [UIColor colorWithRed:info->tintColorR + green:info->tintColorG + blue:info->tintColorB + alpha:info->tintColorA]; // adjust text rect according to overflow - NSMutableDictionary* tokenAttributesDict = [NSMutableDictionary - dictionaryWithObjectsAndKeys:foregroundColor, NSForegroundColorAttributeName, font, NSFontAttributeName, - paragraphStyle, NSParagraphStyleAttributeName, nil]; + NSMutableDictionary* tokenAttributesDict = [NSMutableDictionary dictionaryWithObjectsAndKeys: + foregroundColor,NSForegroundColorAttributeName, + font, NSFontAttributeName, + paragraphStyle, NSParagraphStyleAttributeName, nil]; - NSAttributedString* stringWithAttributes = - [[[NSAttributedString alloc] initWithString:str attributes:tokenAttributesDict] autorelease]; + NSAttributedString *stringWithAttributes =[[[NSAttributedString alloc] initWithString:str + attributes:tokenAttributesDict] autorelease]; int shrinkFontSize = size; CGSize realDimensions; - if (overflow == 2) - { - realDimensions = - _calculateShrinkedSizeForString(&stringWithAttributes, font, dimensions, enableWrap, shrinkFontSize); - } - else - { + if (overflow == 2) { + realDimensions = _calculateShrinkedSizeForString(&stringWithAttributes, font, dimensions, enableWrap, shrinkFontSize); + } else { realDimensions = _calculateStringSize(stringWithAttributes, font, &dimensions, enableWrap, overflow); } + CC_BREAK_IF(realDimensions.width <= 0 || realDimensions.height <= 0); - if (dimensions.width <= 0) - { + if (dimensions.width <= 0) { dimensions.width = realDimensions.width; } - if (dimensions.height <= 0) - { + if (dimensions.height <= 0) { dimensions.height = realDimensions.height; } // compute start point CGFloat yPadding = _calculateTextDrawStartHeight(align, realDimensions, dimensions); CGFloat xPadding = FontUtils::_calculateTextDrawStartWidth(align, realDimensions, dimensions); - + NSInteger POTWide = dimensions.width; NSInteger POTHigh = dimensions.height; + + CGRect textRect = CGRectMake(xPadding, yPadding, + realDimensions.width, realDimensions.height); - CGRect textRect = CGRectMake(xPadding, yPadding, realDimensions.width, realDimensions.height); NSUInteger textureSize = POTWide * POTHigh * 4; - unsigned char* data = (unsigned char*)malloc(sizeof(unsigned char) * textureSize); + unsigned char* data = (unsigned char*)malloc(sizeof(unsigned char) * textureSize); memset(data, 0, textureSize); // draw text - CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); - CGContextRef context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, POTWide * 4, colorSpace, - kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGContextRef context = CGBitmapContextCreate(data, + POTWide, + POTHigh, + 8, + POTWide * 4, + colorSpace, + kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); if (!context) { CGColorSpaceRelease(colorSpace); @@ -522,12 +486,16 @@ static bool _initWithString(const char* text, } // text color - CGContextSetRGBFillColor(context, info->tintColorR, info->tintColorG, info->tintColorB, info->tintColorA); + CGContextSetRGBFillColor(context, + info->tintColorR, + info->tintColorG, + info->tintColorB, + info->tintColorA); // move Y rendering to the top of the image CGContextTranslateCTM(context, 0.0f, POTHigh); - - // NOTE: NSString draws in UIKit referential i.e. renders upside-down compared to CGBitmapContext referential + + //NOTE: NSString draws in UIKit referential i.e. renders upside-down compared to CGBitmapContext referential CGContextScaleCTM(context, 1.0f, -1.0f); // store the current context UIGraphicsPushContext(context); @@ -538,30 +506,34 @@ static bool _initWithString(const char* text, CGContextBeginTransparencyLayerWithRect(context, textRect, NULL); - if (info->hasStroke) + + if ( info->hasStroke ) { CGContextSetTextDrawingMode(context, kCGTextStroke); - UIColor* strokeColor = [UIColor colorWithRed:info->strokeColorR - green:info->strokeColorG - blue:info->strokeColorB - alpha:info->strokeColorA]; + UIColor *strokeColor = [UIColor colorWithRed:info->strokeColorR + green:info->strokeColorG + blue:info->strokeColorB + alpha:info->strokeColorA]; - NSMutableDictionary* tokenAttributesDict2 = [NSMutableDictionary - dictionaryWithObjectsAndKeys:foregroundColor, NSForegroundColorAttributeName, font, NSFontAttributeName, - paragraphStyle, NSParagraphStyleAttributeName, nil]; - [tokenAttributesDict2 setObject:[NSNumber numberWithFloat:info->strokeSize / shrinkFontSize * 100] + + NSMutableDictionary* tokenAttributesDict2 = [NSMutableDictionary dictionaryWithObjectsAndKeys: + foregroundColor,NSForegroundColorAttributeName, + font, NSFontAttributeName, + paragraphStyle, NSParagraphStyleAttributeName, nil]; + [tokenAttributesDict2 setObject:[NSNumber numberWithFloat: info->strokeSize / shrinkFontSize * 100] forKey:NSStrokeWidthAttributeName]; - [tokenAttributesDict2 setObject:strokeColor forKey:NSStrokeColorAttributeName]; - - NSAttributedString* strokeString = - [[[NSAttributedString alloc] initWithString:str attributes:tokenAttributesDict2] autorelease]; - - if (overflow == 2) - { + [tokenAttributesDict2 setObject:strokeColor forKey:NSStrokeColorAttributeName]; + + NSAttributedString *strokeString =[[[NSAttributedString alloc] initWithString:str + attributes:tokenAttributesDict2] autorelease]; + + if(overflow == 2){ _calculateShrinkedSizeForString(&strokeString, font, dimensions, enableWrap, shrinkFontSize); } + [strokeString drawInRect:textRect]; + } CGContextSetTextDrawingMode(context, kCGTextFill); @@ -576,57 +548,51 @@ static bool _initWithString(const char* text, // release the context CGContextRelease(context); - + // output params info->data = data; info->isPremultipliedAlpha = true; info->width = static_cast(POTWide); info->height = static_cast(POTHigh); - bRet = true; + bRet = true; } while (0); return bRet; } -Data Device::getTextureDataForText(const char* text, - const FontDefinition& textDefinition, - TextAlign align, - int& width, - int& height, - bool& hasPremultipliedAlpha) + +Data Device::getTextureDataForText(const char * text, const FontDefinition& textDefinition, TextAlign align, int &width, int &height, bool& hasPremultipliedAlpha) { Data ret; - do - { - tImageInfo info = {0}; - info.width = textDefinition._dimensions.width; - info.height = textDefinition._dimensions.height; - info.hasShadow = textDefinition._shadow._shadowEnabled; - info.shadowOffset.width = textDefinition._shadow._shadowOffset.width; - info.shadowOffset.height = textDefinition._shadow._shadowOffset.height; - info.shadowBlur = textDefinition._shadow._shadowBlur; - info.shadowOpacity = textDefinition._shadow._shadowOpacity; - info.hasStroke = textDefinition._stroke._strokeEnabled; - info.strokeColorR = textDefinition._stroke._strokeColor.r / 255.0f; - info.strokeColorG = textDefinition._stroke._strokeColor.g / 255.0f; - info.strokeColorB = textDefinition._stroke._strokeColor.b / 255.0f; - info.strokeColorA = textDefinition._stroke._strokeAlpha / 255.0f; - info.strokeSize = textDefinition._stroke._strokeSize; - info.tintColorR = textDefinition._fontFillColor.r / 255.0f; - info.tintColorG = textDefinition._fontFillColor.g / 255.0f; - info.tintColorB = textDefinition._fontFillColor.b / 255.0f; - info.tintColorA = textDefinition._fontAlpha / 255.0f; + do { + tImageInfo info = {0}; + info.width = textDefinition._dimensions.width; + info.height = textDefinition._dimensions.height; + info.hasShadow = textDefinition._shadow._shadowEnabled; + info.shadowOffset.width = textDefinition._shadow._shadowOffset.width; + info.shadowOffset.height = textDefinition._shadow._shadowOffset.height; + info.shadowBlur = textDefinition._shadow._shadowBlur; + info.shadowOpacity = textDefinition._shadow._shadowOpacity; + info.hasStroke = textDefinition._stroke._strokeEnabled; + info.strokeColorR = textDefinition._stroke._strokeColor.r / 255.0f; + info.strokeColorG = textDefinition._stroke._strokeColor.g / 255.0f; + info.strokeColorB = textDefinition._stroke._strokeColor.b / 255.0f; + info.strokeColorA = textDefinition._stroke._strokeAlpha / 255.0f; + info.strokeSize = textDefinition._stroke._strokeSize; + info.tintColorR = textDefinition._fontFillColor.r / 255.0f; + info.tintColorG = textDefinition._fontFillColor.g / 255.0f; + info.tintColorB = textDefinition._fontFillColor.b / 255.0f; + info.tintColorA = textDefinition._fontAlpha / 255.0f; - if (!_initWithString(text, align, textDefinition._fontName.c_str(), textDefinition._fontSize, &info, - textDefinition._enableWrap, textDefinition._overflow)) + if (! _initWithString(text, align, textDefinition._fontName.c_str(), textDefinition._fontSize, &info, textDefinition._enableWrap, textDefinition._overflow)) { break; } height = info.height; - width = info.width; - ret.fastSet(info.data, width * height * 4); + width = info.width; + ret.fastSet(info.data,width * height * 4); hasPremultipliedAlpha = true; } while (0); @@ -639,23 +605,22 @@ void Device::setKeepScreenOn(bool value) } /*! - @brief Only works on iOS devices that support vibration (such as iPhone). Should only be used for important alerts. Use - risks rejection in iTunes Store. + @brief Only works on iOS devices that support vibration (such as iPhone). Should only be used for important alerts. Use risks rejection in iTunes Store. @param duration ignored for iOS */ void Device::vibrate(float duration) { // See http://stackoverflow.com/questions/4724980/making-the-iphone-vibrate // should vibrate no matter it is silient or not - if ([[UIDevice currentDevice].model isEqualToString:@"iPhone"]) + if([[UIDevice currentDevice].model isEqualToString:@"iPhone"]) { - AudioServicesPlaySystemSound(1352); // works ALWAYS as of this post + AudioServicesPlaySystemSound (1352); //works ALWAYS as of this post } else { // Not an iPhone, so doesn't have vibrate // play the less annoying tick noise or one of your own - AudioServicesPlayAlertSound(kSystemSoundID_Vibrate); + AudioServicesPlayAlertSound (kSystemSoundID_Vibrate); } } diff --git a/cocos/platform/ios/CCDirectorCaller-ios.mm b/cocos/platform/ios/CCDirectorCaller-ios.mm index 53c4e24973..6b34dd90f1 100644 --- a/cocos/platform/ios/CCDirectorCaller-ios.mm +++ b/cocos/platform/ios/CCDirectorCaller-ios.mm @@ -35,55 +35,50 @@ static id s_sharedDirectorCaller; -@interface NSObject (CADisplayLink) -+ (id)displayLinkWithTarget:(id)arg1 selector:(SEL)arg2; -- (void)addToRunLoop:(id)arg1 forMode:(id)arg2; -- (void)setFrameInterval:(NSInteger)interval; -- (void)invalidate; +@interface NSObject(CADisplayLink) ++(id) displayLinkWithTarget: (id)arg1 selector:(SEL)arg2; +-(void) addToRunLoop: (id)arg1 forMode: (id)arg2; +-(void) setFrameInterval: (NSInteger)interval; +-(void) invalidate; @end @implementation CCDirectorCaller @synthesize interval; -+ (id)sharedDirectorCaller ++(id) sharedDirectorCaller { if (s_sharedDirectorCaller == nil) { s_sharedDirectorCaller = [[CCDirectorCaller alloc] init]; } - + return s_sharedDirectorCaller; } -+ (void)destroy ++(void) destroy { [s_sharedDirectorCaller stopMainLoop]; [s_sharedDirectorCaller release]; s_sharedDirectorCaller = nil; } + - (instancetype)init { if (self = [super init]) { - isAppActive = [UIApplication sharedApplication].applicationState == UIApplicationStateActive; - NSNotificationCenter* nc = [NSNotificationCenter defaultCenter]; - [nc addObserver:self - selector:@selector(appDidBecomeActive) - name:UIApplicationDidBecomeActiveNotification - object:nil]; - [nc addObserver:self - selector:@selector(appDidBecomeInactive) - name:UIApplicationWillResignActiveNotification - object:nil]; - + isAppActive = [UIApplication sharedApplication].applicationState == UIApplicationStateActive; + NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; + [nc addObserver:self selector:@selector(appDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil]; + [nc addObserver:self selector:@selector(appDidBecomeInactive) name:UIApplicationWillResignActiveNotification object:nil]; + self.interval = 1; } return self; } -- (void)dealloc +-(void) dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; [displayLink release]; @@ -105,53 +100,52 @@ static id s_sharedDirectorCaller; isAppActive = NO; } -- (void)startMainLoop +-(void) startMainLoop { // Director::setAnimationInterval() is called, we should invalidate it first [self stopMainLoop]; - + displayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(doCaller:)]; - [displayLink setFrameInterval:self.interval]; + [displayLink setFrameInterval: self.interval]; [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; } -- (void)stopMainLoop +-(void) stopMainLoop { [displayLink invalidate]; displayLink = nil; } -- (void)setAnimationInterval:(double)intervalNew +-(void) setAnimationInterval:(double)intervalNew { // Director::setAnimationInterval() is called, we should invalidate it first [self stopMainLoop]; - + self.interval = 60.0 * intervalNew; - + displayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(doCaller:)]; - [displayLink setFrameInterval:self.interval]; + [displayLink setFrameInterval: self.interval]; [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; } - -- (void)doCaller:(id)sender + +-(void) doCaller: (id) sender { - if (isAppActive) - { + if (isAppActive) { cocos2d::Director* director = cocos2d::Director::getInstance(); #if defined(CC_USE_GLES) EAGLContext* cocos2dxContext = [(CCEAGLView*)director->getOpenGLView()->getEAGLView() context]; if (cocos2dxContext != [EAGLContext currentContext]) glFlush(); - - [EAGLContext setCurrentContext:cocos2dxContext]; + + [EAGLContext setCurrentContext: cocos2dxContext]; #endif CFTimeInterval dt = ((CADisplayLink*)displayLink).timestamp - lastDisplayTime; - lastDisplayTime = ((CADisplayLink*)displayLink).timestamp; + lastDisplayTime = ((CADisplayLink*)displayLink).timestamp; director->mainLoop(dt); } } -- (void)initLastDisplayTime +-(void)initLastDisplayTime { struct mach_timebase_info timeBaseInfo; mach_timebase_info(&timeBaseInfo); diff --git a/cocos/platform/ios/CCEAGLView-ios.mm b/cocos/platform/ios/CCEAGLView-ios.mm index ca1bccdadd..6cd9b6c270 100644 --- a/cocos/platform/ios/CCEAGLView-ios.mm +++ b/cocos/platform/ios/CCEAGLView-ios.mm @@ -70,21 +70,21 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. #import "platform/ios/CCInputView-ios.h" #if defined(CC_USE_METAL) -# import -# import "renderer/backend/metal/DeviceMTL.h" -# import "renderer/backend/metal/UtilsMTL.h" +#import +#import "renderer/backend/metal/DeviceMTL.h" +#import "renderer/backend/metal/UtilsMTL.h" #else -# import "platform/ios/CCGLViewImpl-ios.h" -# import "platform/ios/CCES2Renderer-ios.h" -# import "platform/ios/OpenGL_Internal-ios.h" +#import "platform/ios/CCGLViewImpl-ios.h" +#import "platform/ios/CCES2Renderer-ios.h" +#import "platform/ios/OpenGL_Internal-ios.h" #endif -// CLASS IMPLEMENTATIONS: +//CLASS IMPLEMENTATIONS: -#define IOS_MAX_TOUCHES_COUNT 10 +#define IOS_MAX_TOUCHES_COUNT 10 @interface CCEAGLView () -@property(nonatomic) CCInputView* textInputView; +@property (nonatomic) CCInputView* textInputView; @property(nonatomic, readwrite, assign) BOOL isKeyboardShown; @property(nonatomic, copy) NSNotification* keyboardShowNotification; @property(nonatomic, assign) CGRect originalRect; @@ -92,17 +92,17 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. @implementation CCEAGLView -@synthesize surfaceSize = size_; -@synthesize pixelFormat = pixelformat_, depthFormat = depthFormat_; +@synthesize surfaceSize=size_; +@synthesize pixelFormat=pixelformat_, depthFormat=depthFormat_; #if !defined(CC_USE_METAL) -@synthesize context = context_; +@synthesize context=context_; #endif -@synthesize multiSampling = multiSampling_; +@synthesize multiSampling=multiSampling_; @synthesize keyboardShowNotification = keyboardShowNotification_; @synthesize isKeyboardShown; @synthesize originalRect = originalRect_; -+ (Class)layerClass ++ (Class) layerClass { #if defined(CC_USE_METAL) return [CAMetalLayer class]; @@ -111,191 +111,153 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. #endif } -+ (id)viewWithFrame:(CGRect)frame ++ (id) viewWithFrame:(CGRect)frame { return [[[self alloc] initWithFrame:frame] autorelease]; } -+ (id)viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format ++ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format { - return [[[self alloc] initWithFrame:frame pixelFormat:format] autorelease]; + return [[[self alloc]initWithFrame:frame pixelFormat:format] autorelease]; } -+ (id)viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth ++ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth { - return [[[self alloc] initWithFrame:frame - pixelFormat:format - depthFormat:depth - preserveBackbuffer:NO - sharegroup:nil - multiSampling:NO - numberOfSamples:0] autorelease]; + return [[[self alloc] initWithFrame:frame pixelFormat:format depthFormat:depth preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0] autorelease]; } -+ (id)viewWithFrame:(CGRect)frame - pixelFormat:(NSString*)format - depthFormat:(GLuint)depth - preserveBackbuffer:(BOOL)retained - sharegroup:(EAGLSharegroup*)sharegroup - multiSampling:(BOOL)multisampling - numberOfSamples:(unsigned int)samples ++ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned int)samples { - return [[[self alloc] initWithFrame:frame - pixelFormat:format - depthFormat:depth - preserveBackbuffer:retained - sharegroup:sharegroup - multiSampling:multisampling - numberOfSamples:samples] autorelease]; + return [[[self alloc]initWithFrame:frame pixelFormat:format depthFormat:depth preserveBackbuffer:retained sharegroup:sharegroup multiSampling:multisampling numberOfSamples:samples] autorelease]; } -- (id)initWithFrame:(CGRect)frame +- (id) initWithFrame:(CGRect)frame { - return [self initWithFrame:frame - pixelFormat:kEAGLColorFormatRGB565 - depthFormat:0 - preserveBackbuffer:NO - sharegroup:nil - multiSampling:NO - numberOfSamples:0]; + return [self initWithFrame:frame pixelFormat:kEAGLColorFormatRGB565 depthFormat:0 preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0]; } -- (id)initWithFrame:(CGRect)frame pixelFormat:(NSString*)format +- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format { - return [self initWithFrame:frame - pixelFormat:format - depthFormat:0 - preserveBackbuffer:NO - sharegroup:nil - multiSampling:NO - numberOfSamples:0]; + return [self initWithFrame:frame pixelFormat:format depthFormat:0 preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0]; } -- (id)initWithFrame:(CGRect)frame - pixelFormat:(NSString*)format - depthFormat:(GLuint)depth - preserveBackbuffer:(BOOL)retained - sharegroup:(EAGLSharegroup*)sharegroup - multiSampling:(BOOL)sampling - numberOfSamples:(unsigned int)nSamples +- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)sampling numberOfSamples:(unsigned int)nSamples { - if ((self = [super initWithFrame:frame])) + if((self = [super initWithFrame:frame])) { self.textInputView = [[CCInputView alloc] initWithFrame:frame]; - originalRect_ = self.frame; + originalRect_ = self.frame; self.keyboardShowNotification = nil; if ([self respondsToSelector:@selector(setContentScaleFactor:)]) { self.contentScaleFactor = [[UIScreen mainScreen] scale]; } - + #if defined(CC_USE_METAL) id device = MTLCreateSystemDefaultDevice(); if (!device) { - CCLOG("Doesn't support metal."); - return nil; + CCLOG("Doesn't support metal."); + return nil; } - CAMetalLayer* metalLayer = (CAMetalLayer*)[self layer]; - metalLayer.device = device; - metalLayer.pixelFormat = MTLPixelFormatBGRA8Unorm; + CAMetalLayer* metalLayer = (CAMetalLayer*)[self layer]; + metalLayer.device = device; + metalLayer.pixelFormat = MTLPixelFormatBGRA8Unorm; metalLayer.framebufferOnly = YES; cocos2d::backend::DeviceMTL::setCAMetalLayer(metalLayer); #else - pixelformat_ = format; - depthFormat_ = depth; - multiSampling_ = sampling; - requestedSamples_ = nSamples; + pixelformat_ = format; + depthFormat_ = depth; + multiSampling_ = sampling; + requestedSamples_ = nSamples; preserveBackbuffer_ = retained; - if (![self setupSurfaceWithSharegroup:sharegroup]) - { + if( ! [self setupSurfaceWithSharegroup:sharegroup] ) { [self release]; return nil; } #endif } - + return self; } -- (id)initWithCoder:(NSCoder*)aDecoder +-(id) initWithCoder:(NSCoder *)aDecoder { - if ((self = [super initWithCoder:aDecoder])) + if ( (self = [super initWithCoder:aDecoder]) ) { self.textInputView = [[CCInputView alloc] initWithCoder:aDecoder]; #if defined(CC_USE_METAL) size_ = [self bounds].size; #else CAEAGLLayer* eaglLayer = (CAEAGLLayer*)[self layer]; - - pixelformat_ = kEAGLColorFormatRGB565; - depthFormat_ = 0; // GL_DEPTH_COMPONENT24_OES; - multiSampling_ = NO; + + pixelformat_ = kEAGLColorFormatRGB565; + depthFormat_ = 0; // GL_DEPTH_COMPONENT24_OES; + multiSampling_= NO; requestedSamples_ = 0; - size_ = [eaglLayer bounds].size; - - if (![self setupSurfaceWithSharegroup:nil]) - { + size_ = [eaglLayer bounds].size; + + if( ! [self setupSurfaceWithSharegroup:nil] ) { [self release]; return nil; } #endif } - + return self; } -- (int)getWidth +-(int) getWidth { CGSize bound = [self bounds].size; return (int)bound.width * self.contentScaleFactor; } -- (int)getHeight +-(int) getHeight { CGSize bound = [self bounds].size; return (int)bound.height * self.contentScaleFactor; } #if !defined(CC_USE_METAL) -- (BOOL)setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup +-(BOOL) setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup { - CAEAGLLayer* eaglLayer = (CAEAGLLayer*)self.layer; - + CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer; + eaglLayer.opaque = YES; - eaglLayer.drawableProperties = - [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:preserveBackbuffer_], - kEAGLDrawablePropertyRetainedBacking, pixelformat_, - kEAGLDrawablePropertyColorFormat, nil]; - + eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys: + [NSNumber numberWithBool:preserveBackbuffer_], kEAGLDrawablePropertyRetainedBacking, + pixelformat_, kEAGLDrawablePropertyColorFormat, nil]; + + renderer_ = [[CCES2Renderer alloc] initWithDepthFormat:depthFormat_ - withPixelFormat:[self convertPixelFormat:pixelformat_] - withSharegroup:sharegroup - withMultiSampling:multiSampling_ - withNumberOfSamples:requestedSamples_]; - + withPixelFormat:[self convertPixelFormat:pixelformat_] + withSharegroup:sharegroup + withMultiSampling:multiSampling_ + withNumberOfSamples:requestedSamples_]; + NSAssert(renderer_, @"OpenGL ES 2.O is required."); if (!renderer_) return NO; - + context_ = [renderer_ context]; - -# if GL_EXT_discard_framebuffer == 1 - discardFramebufferSupported_ = YES; -# else - discardFramebufferSupported_ = NO; -# endif - + + #if GL_EXT_discard_framebuffer == 1 + discardFramebufferSupported_ = YES; + #else + discardFramebufferSupported_ = NO; + #endif + CHECK_GL_ERROR(); - + return YES; } #endif -- (void)dealloc +- (void) dealloc { - [[NSNotificationCenter defaultCenter] removeObserver:self]; // remove keyboard notification + [[NSNotificationCenter defaultCenter] removeObserver:self]; // remove keyboard notification #if !defined(CC_USE_METAL) [renderer_ release]; #endif @@ -303,29 +265,29 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. [super dealloc]; } -- (void)layoutSubviews +- (void) layoutSubviews { if (!cocos2d::Director::getInstance()->isValid()) return; - + #if defined(CC_USE_METAL) size_ = [self bounds].size; size_.width *= self.contentScaleFactor; size_.height *= self.contentScaleFactor; - cocos2d::backend::UtilsMTL::resizeDefaultAttachmentTexture(size_.width, size_.height); + cocos2d::backend::UtilsMTL::resizeDefaultAttachmentTexture(size_.width, size_.height); #else [renderer_ resizeFromLayer:(CAEAGLLayer*)self.layer]; size_ = [renderer_ backingSize]; // Issue #914 #924 - // Director *director = [Director sharedDirector]; - // [director reshapeProjection:size_]; +// Director *director = [Director sharedDirector]; +// [director reshapeProjection:size_]; cocos2d::Size size; - size.width = size_.width; + size.width = size_.width; size.height = size_.height; - // cocos2d::Director::getInstance()->reshapeProjection(size); + //cocos2d::Director::getInstance()->reshapeProjection(size); #endif - + // Avoid flicker. Issue #350 if ([NSThread isMainThread]) { @@ -334,28 +296,29 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. } #if defined(CC_USE_METAL) -- (void)swapBuffers -{} +- (void) swapBuffers +{ +} #else -- (void)swapBuffers +- (void) swapBuffers { // IMPORTANT: - // - preconditions - // -> context_ MUST be the OpenGL context - // -> renderbuffer_ must be the RENDER BUFFER - -# ifdef __IPHONE_4_0 + // - preconditions + // -> context_ MUST be the OpenGL context + // -> renderbuffer_ must be the RENDER BUFFER +#ifdef __IPHONE_4_0 + if (multiSampling_) { /* Resolve from msaaFramebuffer to resolveFramebuffer */ - // glDisable(GL_SCISSOR_TEST); + //glDisable(GL_SCISSOR_TEST); glBindFramebuffer(GL_READ_FRAMEBUFFER_APPLE, [renderer_ msaaFrameBuffer]); glBindFramebuffer(GL_DRAW_FRAMEBUFFER_APPLE, [renderer_ defaultFrameBuffer]); glResolveMultisampleFramebufferAPPLE(); } - - if (discardFramebufferSupported_) + + if(discardFramebufferSupported_) { if (multiSampling_) { @@ -369,98 +332,97 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. GLenum attachments[] = {GL_COLOR_ATTACHMENT0}; glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 1, attachments); } - + glBindRenderbuffer(GL_RENDERBUFFER, [renderer_ colorRenderBuffer]); + } - + // not MSAA - else if (depthFormat_) - { - GLenum attachments[] = {GL_DEPTH_ATTACHMENT}; + else if (depthFormat_ ) { + GLenum attachments[] = { GL_DEPTH_ATTACHMENT}; glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments); } } + +#endif // __IPHONE_4_0 + + if(![context_ presentRenderbuffer:GL_RENDERBUFFER]) + { +// CCLOG(@"cocos2d: Failed to swap renderbuffer in %s\n", __FUNCTION__); + } -# endif // __IPHONE_4_0 - - if (![context_ presentRenderbuffer:GL_RENDERBUFFER]) - { - // CCLOG(@"cocos2d: Failed to swap renderbuffer in %s\n", __FUNCTION__); - } - -# if COCOS2D_DEBUG +#if COCOS2D_DEBUG CHECK_GL_ERROR(); -# endif - +#endif + // We can safely re-bind the framebuffer here, since this will be the // 1st instruction of the new main loop - if (multiSampling_) + if( multiSampling_ ) glBindFramebuffer(GL_FRAMEBUFFER, [renderer_ msaaFrameBuffer]); } -- (unsigned int)convertPixelFormat:(NSString*)pixelFormat +- (unsigned int) convertPixelFormat:(NSString*) pixelFormat { // define the pixel format GLenum pFormat; - - if ([pixelFormat isEqualToString:@"EAGLColorFormat565"]) + + + if([pixelFormat isEqualToString:@"EAGLColorFormat565"]) pFormat = GL_RGB565; else pFormat = GL_RGBA8_OES; - + return pFormat; } #endif #pragma mark CCEAGLView - Point conversion -- (CGPoint)convertPointFromViewToSurface:(CGPoint)point +- (CGPoint) convertPointFromViewToSurface:(CGPoint)point { CGRect bounds = [self bounds]; - + CGPoint ret; ret.x = (point.x - bounds.origin.x) / bounds.size.width * size_.width; - ret.y = (point.y - bounds.origin.y) / bounds.size.height * size_.height; - + ret.y = (point.y - bounds.origin.y) / bounds.size.height * size_.height; + return ret; } -- (CGRect)convertRectFromViewToSurface:(CGRect)rect +- (CGRect) convertRectFromViewToSurface:(CGRect)rect { CGRect bounds = [self bounds]; - + CGRect ret; - ret.origin.x = (rect.origin.x - bounds.origin.x) / bounds.size.width * size_.width; - ret.origin.y = (rect.origin.y - bounds.origin.y) / bounds.size.height * size_.height; - ret.size.width = rect.size.width / bounds.size.width * size_.width; + ret.origin.x = (rect.origin.x - bounds.origin.x) / bounds.size.width * size_.width; + ret.origin.y = (rect.origin.y - bounds.origin.y) / bounds.size.height * size_.height; + ret.size.width = rect.size.width / bounds.size.width * size_.width; ret.size.height = rect.size.height / bounds.size.height * size_.height; - + return ret; } // Pass the touches to the superview #pragma mark CCEAGLView - Touch Delegate -- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event +- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { if (self.isKeyboardShown) [self closeKeyboardOpenedByEditBox]; - + UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; - float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - + float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + int i = 0; - for (UITouch* touch in touches) - { - if (i >= IOS_MAX_TOUCHES_COUNT) - { + for (UITouch *touch in touches) { + if (i >= IOS_MAX_TOUCHES_COUNT) { CCLOG("warning: touches more than 10, should adjust IOS_MAX_TOUCHES_COUNT"); break; } ids[i] = touch; - xs[i] = [touch locationInView:[touch view]].x * self.contentScaleFactor; - ys[i] = [touch locationInView:[touch view]].y * self.contentScaleFactor; + xs[i] = [touch locationInView: [touch view]].x * self.contentScaleFactor; + ys[i] = [touch locationInView: [touch view]].y * self.contentScaleFactor; ++i; } @@ -468,30 +430,27 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. glview->handleTouchesBegin(i, (intptr_t*)ids, xs, ys); } -- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event +- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; - float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - float fs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - float ms[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - + float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + float fs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + float ms[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + int i = 0; - for (UITouch* touch in touches) - { - if (i >= IOS_MAX_TOUCHES_COUNT) - { + for (UITouch *touch in touches) { + if (i >= IOS_MAX_TOUCHES_COUNT) { CCLOG("warning: touches more than 10, should adjust IOS_MAX_TOUCHES_COUNT"); break; } ids[i] = touch; - xs[i] = [touch locationInView:[touch view]].x * self.contentScaleFactor; - ys[i] = [touch locationInView:[touch view]].y * self.contentScaleFactor; + xs[i] = [touch locationInView: [touch view]].x * self.contentScaleFactor; + ys[i] = [touch locationInView: [touch view]].y * self.contentScaleFactor; #if defined(__IPHONE_9_0) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0) // running on iOS 9.0 or higher version - if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0f) - { + if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0f) { fs[i] = touch.force; ms[i] = touch.maximumPossibleForce; } @@ -503,49 +462,45 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. glview->handleTouchesMove(i, (intptr_t*)ids, xs, ys, fs, ms); } -- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event +- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; - float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - + float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + int i = 0; - for (UITouch* touch in touches) - { - if (i >= IOS_MAX_TOUCHES_COUNT) - { + for (UITouch *touch in touches) { + if (i >= IOS_MAX_TOUCHES_COUNT) { CCLOG("warning: touches more than 10, should adjust IOS_MAX_TOUCHES_COUNT"); break; } ids[i] = touch; - xs[i] = [touch locationInView:[touch view]].x * self.contentScaleFactor; - ys[i] = [touch locationInView:[touch view]].y * self.contentScaleFactor; + xs[i] = [touch locationInView: [touch view]].x * self.contentScaleFactor; + ys[i] = [touch locationInView: [touch view]].y * self.contentScaleFactor; ++i; } auto glview = cocos2d::Director::getInstance()->getOpenGLView(); glview->handleTouchesEnd(i, (intptr_t*)ids, xs, ys); } - -- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event + +- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; - float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - + float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + int i = 0; - for (UITouch* touch in touches) - { - if (i >= IOS_MAX_TOUCHES_COUNT) - { + for (UITouch *touch in touches) { + if (i >= IOS_MAX_TOUCHES_COUNT) { CCLOG("warning: touches more than 10, should adjust IOS_MAX_TOUCHES_COUNT"); break; } - + ids[i] = touch; - xs[i] = [touch locationInView:[touch view]].x * self.contentScaleFactor; - ys[i] = [touch locationInView:[touch view]].y * self.contentScaleFactor; + xs[i] = [touch locationInView: [touch view]].x * self.contentScaleFactor; + ys[i] = [touch locationInView: [touch view]].y * self.contentScaleFactor; ++i; } @@ -553,90 +508,83 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. glview->handleTouchesCancel(i, (intptr_t*)ids, xs, ys); } -- (void)showKeyboard +- (void) showKeyboard { [self addSubview:self.textInputView]; [self.textInputView becomeFirstResponder]; } -- (void)hideKeyboard +- (void) hideKeyboard { [self.textInputView resignFirstResponder]; [self.textInputView removeFromSuperview]; } -- (void)doAnimationWhenKeyboardMoveWithDuration:(float)duration distance:(float)dis +-(void) doAnimationWhenKeyboardMoveWithDuration:(float) duration distance:(float) dis { [UIView beginAnimations:nil context:nullptr]; - [UIView setAnimationDelegate:self]; - [UIView setAnimationDuration:duration]; - [UIView setAnimationBeginsFromCurrentState:YES]; + [UIView setAnimationDelegate:self]; + [UIView setAnimationDuration:duration]; + [UIView setAnimationBeginsFromCurrentState:YES]; + + //NSLog(@"[animation] dis = %f, scale = %f \n", dis, cocos2d::GLView::getInstance()->getScaleY()); + + if (dis < 0.0f) dis = 0.0f; - // NSLog(@"[animation] dis = %f, scale = %f \n", dis, cocos2d::GLView::getInstance()->getScaleY()); + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + dis *= glview->getScaleY(); + + dis /= self.contentScaleFactor; - if (dis < 0.0f) - dis = 0.0f; - - auto glview = cocos2d::Director::getInstance()->getOpenGLView(); - dis *= glview->getScaleY(); - - dis /= self.contentScaleFactor; - -#if defined(CC_TARGET_OS_TVOS) - self.frame = CGRectMake(originalRect_.origin.x, originalRect_.origin.y - dis, originalRect_.size.width, - originalRect_.size.height); -#else - switch (getFixedOrientation([[UIApplication sharedApplication] statusBarOrientation])) - { - case UIInterfaceOrientationPortrait: - self.frame = CGRectMake(originalRect_.origin.x, originalRect_.origin.y - dis, originalRect_.size.width, - originalRect_.size.height); - break; - - case UIInterfaceOrientationPortraitUpsideDown: - self.frame = CGRectMake(originalRect_.origin.x, originalRect_.origin.y + dis, originalRect_.size.width, - originalRect_.size.height); - break; - - case UIInterfaceOrientationLandscapeLeft: - self.frame = CGRectMake(originalRect_.origin.x - dis, originalRect_.origin.y, originalRect_.size.width, - originalRect_.size.height); - break; - - case UIInterfaceOrientationLandscapeRight: - self.frame = CGRectMake(originalRect_.origin.x + dis, originalRect_.origin.y, originalRect_.size.width, - originalRect_.size.height); - break; - - default: - break; - } -#endif - - [UIView commitAnimations]; + #if defined(CC_TARGET_OS_TVOS) + self.frame = CGRectMake(originalRect_.origin.x, originalRect_.origin.y - dis, originalRect_.size.width, originalRect_.size.height); + #else + switch (getFixedOrientation([[UIApplication sharedApplication] statusBarOrientation])) + { + case UIInterfaceOrientationPortrait: + self.frame = CGRectMake(originalRect_.origin.x, originalRect_.origin.y - dis, originalRect_.size.width, originalRect_.size.height); + break; + + case UIInterfaceOrientationPortraitUpsideDown: + self.frame = CGRectMake(originalRect_.origin.x, originalRect_.origin.y + dis, originalRect_.size.width, originalRect_.size.height); + break; + + case UIInterfaceOrientationLandscapeLeft: + self.frame = CGRectMake(originalRect_.origin.x - dis, originalRect_.origin.y , originalRect_.size.width, originalRect_.size.height); + break; + + case UIInterfaceOrientationLandscapeRight: + self.frame = CGRectMake(originalRect_.origin.x + dis, originalRect_.origin.y , originalRect_.size.width, originalRect_.size.height); + break; + + default: + break; + } + #endif + + [UIView commitAnimations]; } -- (void)doAnimationWhenAnotherEditBeClicked +-(void) doAnimationWhenAnotherEditBeClicked { if (self.keyboardShowNotification != nil) { - [[NSNotificationCenter defaultCenter] postNotification:self.keyboardShowNotification]; + [[NSNotificationCenter defaultCenter]postNotification:self.keyboardShowNotification]; } } #pragma UIKeyboard notification #if !defined(CC_TARGET_OS_TVOS) -namespace -{ -UIInterfaceOrientation getFixedOrientation(UIInterfaceOrientation statusBarOrientation) -{ - if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) +namespace { + UIInterfaceOrientation getFixedOrientation(UIInterfaceOrientation statusBarOrientation) { - statusBarOrientation = UIInterfaceOrientationPortrait; + if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) + { + statusBarOrientation = UIInterfaceOrientationPortrait; + } + return statusBarOrientation; } - return statusBarOrientation; -} } #endif @@ -645,89 +593,87 @@ UIInterfaceOrientation getFixedOrientation(UIInterfaceOrientation statusBarOrien #if !defined(CC_TARGET_OS_TVOS) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUIKeyboardNotification:) - name:UIKeyboardWillShowNotification - object:nil]; + name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUIKeyboardNotification:) - name:UIKeyboardDidShowNotification - object:nil]; + name:UIKeyboardDidShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUIKeyboardNotification:) - name:UIKeyboardWillHideNotification - object:nil]; + name:UIKeyboardWillHideNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUIKeyboardNotification:) - name:UIKeyboardDidHideNotification - object:nil]; + name:UIKeyboardDidHideNotification object:nil]; #endif } -- (void)onUIKeyboardNotification:(NSNotification*)notif +- (void)onUIKeyboardNotification:(NSNotification *)notif { - NSString* type = notif.name; - + NSString * type = notif.name; + NSDictionary* info = [notif userInfo]; - CGRect begin = [self convertRect:[[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue] fromView:self]; - CGRect end = [self convertRect:[[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue] fromView:self]; + CGRect begin = [self convertRect: + [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue] + fromView:self]; + CGRect end = [self convertRect: + [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue] + fromView:self]; double aniDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; - + CGSize viewSize = self.frame.size; CGFloat tmp; switch (getFixedOrientation([[UIApplication sharedApplication] statusBarOrientation])) { - case UIInterfaceOrientationPortrait: - begin.origin.y = viewSize.height - begin.origin.y - begin.size.height; - end.origin.y = viewSize.height - end.origin.y - end.size.height; - break; - - case UIInterfaceOrientationPortraitUpsideDown: - begin.origin.x = viewSize.width - (begin.origin.x + begin.size.width); - end.origin.x = viewSize.width - (end.origin.x + end.size.width); - break; - - case UIInterfaceOrientationLandscapeLeft: - std::swap(begin.size.width, begin.size.height); - std::swap(end.size.width, end.size.height); - std::swap(viewSize.width, viewSize.height); - - tmp = begin.origin.x; - begin.origin.x = begin.origin.y; - begin.origin.y = viewSize.height - tmp - begin.size.height; - tmp = end.origin.x; - end.origin.x = end.origin.y; - end.origin.y = viewSize.height - tmp - end.size.height; - break; - - case UIInterfaceOrientationLandscapeRight: - std::swap(begin.size.width, begin.size.height); - std::swap(end.size.width, end.size.height); - std::swap(viewSize.width, viewSize.height); - - tmp = begin.origin.x; - begin.origin.x = begin.origin.y; - begin.origin.y = tmp; - tmp = end.origin.x; - end.origin.x = end.origin.y; - end.origin.y = tmp; - break; - - default: - break; + case UIInterfaceOrientationPortrait: + begin.origin.y = viewSize.height - begin.origin.y - begin.size.height; + end.origin.y = viewSize.height - end.origin.y - end.size.height; + break; + + case UIInterfaceOrientationPortraitUpsideDown: + begin.origin.x = viewSize.width - (begin.origin.x + begin.size.width); + end.origin.x = viewSize.width - (end.origin.x + end.size.width); + break; + + case UIInterfaceOrientationLandscapeLeft: + std::swap(begin.size.width, begin.size.height); + std::swap(end.size.width, end.size.height); + std::swap(viewSize.width, viewSize.height); + + tmp = begin.origin.x; + begin.origin.x = begin.origin.y; + begin.origin.y = viewSize.height - tmp - begin.size.height; + tmp = end.origin.x; + end.origin.x = end.origin.y; + end.origin.y = viewSize.height - tmp - end.size.height; + break; + + case UIInterfaceOrientationLandscapeRight: + std::swap(begin.size.width, begin.size.height); + std::swap(end.size.width, end.size.height); + std::swap(viewSize.width, viewSize.height); + + tmp = begin.origin.x; + begin.origin.x = begin.origin.y; + begin.origin.y = tmp; + tmp = end.origin.x; + end.origin.x = end.origin.y; + end.origin.y = tmp; + break; + + default: + break; } - auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); float scaleX = glview->getScaleX(); float scaleY = glview->getScaleY(); - + // Convert to pixel coordinate - begin = CGRectApplyAffineTransform( - begin, CGAffineTransformScale(CGAffineTransformIdentity, self.contentScaleFactor, self.contentScaleFactor)); - end = CGRectApplyAffineTransform( - end, CGAffineTransformScale(CGAffineTransformIdentity, self.contentScaleFactor, self.contentScaleFactor)); - + begin = CGRectApplyAffineTransform(begin, CGAffineTransformScale(CGAffineTransformIdentity, self.contentScaleFactor, self.contentScaleFactor)); + end = CGRectApplyAffineTransform(end, CGAffineTransformScale(CGAffineTransformIdentity, self.contentScaleFactor, self.contentScaleFactor)); + float offestY = glview->getViewPortRect().origin.y; if (offestY < 0.0f) { @@ -735,18 +681,23 @@ UIInterfaceOrientation getFixedOrientation(UIInterfaceOrientation statusBarOrien begin.size.height -= offestY; end.size.height -= offestY; } - + // Convert to design coordinate - begin = CGRectApplyAffineTransform(begin, - CGAffineTransformScale(CGAffineTransformIdentity, 1.0f / scaleX, 1.0f / scaleY)); - end = CGRectApplyAffineTransform(end, - CGAffineTransformScale(CGAffineTransformIdentity, 1.0f / scaleX, 1.0f / scaleY)); + begin = CGRectApplyAffineTransform(begin, CGAffineTransformScale(CGAffineTransformIdentity, 1.0f/scaleX, 1.0f/scaleY)); + end = CGRectApplyAffineTransform(end, CGAffineTransformScale(CGAffineTransformIdentity, 1.0f/scaleX, 1.0f/scaleY)); + cocos2d::IMEKeyboardNotificationInfo notiInfo; - notiInfo.begin = cocos2d::Rect(begin.origin.x, begin.origin.y, begin.size.width, begin.size.height); - notiInfo.end = cocos2d::Rect(end.origin.x, end.origin.y, end.size.width, end.size.height); + notiInfo.begin = cocos2d::Rect(begin.origin.x, + begin.origin.y, + begin.size.width, + begin.size.height); + notiInfo.end = cocos2d::Rect(end.origin.x, + end.origin.y, + end.size.width, + end.size.height); notiInfo.duration = (float)aniDuration; - + cocos2d::IMEDispatcher* dispatcher = cocos2d::IMEDispatcher::sharedDispatcher(); if (UIKeyboardWillShowNotification == type) { @@ -769,14 +720,14 @@ UIInterfaceOrientation getFixedOrientation(UIInterfaceOrientation statusBarOrien } // Close the keyboard opened by EditBox -- (void)closeKeyboardOpenedByEditBox +-(void) closeKeyboardOpenedByEditBox { - NSArray* subviews = self.subviews; - - for (UIView* view in subviews) + NSArray *subviews = self.subviews; + + for(UIView* view in subviews) { - if ([view isKindOfClass:NSClassFromString(@"UITextView")] || - [view isKindOfClass:NSClassFromString(@"UITextField")]) + if([view isKindOfClass:NSClassFromString(@"UITextView")] || + [view isKindOfClass:NSClassFromString(@"UITextField")]) { if ([view isFirstResponder]) { diff --git a/cocos/platform/ios/CCES2Renderer-ios.h b/cocos/platform/ios/CCES2Renderer-ios.h index 7aec434db7..d0ac908bb3 100644 --- a/cocos/platform/ios/CCES2Renderer-ios.h +++ b/cocos/platform/ios/CCES2Renderer-ios.h @@ -37,7 +37,7 @@ # import # import -//# import "platform/CCPlatformMacros.h" +# import "platform/CCPlatformMacros.h" @interface CCES2Renderer : NSObject { // The pixel dimensions of the CAEAGLLayer diff --git a/cocos/platform/ios/CCES2Renderer-ios.m b/cocos/platform/ios/CCES2Renderer-ios.m index fd49e8f1f4..c1f04ab98e 100644 --- a/cocos/platform/ios/CCES2Renderer-ios.m +++ b/cocos/platform/ios/CCES2Renderer-ios.m @@ -33,7 +33,7 @@ #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS #import "platform/ios/CCES2Renderer-ios.h" -// #import "platform/CCPlatformMacros.h" +#import "platform/CCPlatformMacros.h" #import "platform/ios/OpenGL_Internal-ios.h" #if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0 diff --git a/cocos/platform/ios/CCESRenderer-ios.h b/cocos/platform/ios/CCESRenderer-ios.h index c21fb928c5..7498b30991 100644 --- a/cocos/platform/ios/CCESRenderer-ios.h +++ b/cocos/platform/ios/CCESRenderer-ios.h @@ -32,7 +32,7 @@ #include "platform/CCPlatformConfig.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS -// # include "platform/CCPlatformMacros.h" +# include "platform/CCPlatformMacros.h" # import # import diff --git a/cocos/platform/ios/CCGLViewImpl-ios.h b/cocos/platform/ios/CCGLViewImpl-ios.h index f8ab60f75b..0aa8892865 100644 --- a/cocos/platform/ios/CCGLViewImpl-ios.h +++ b/cocos/platform/ios/CCGLViewImpl-ios.h @@ -40,13 +40,13 @@ public: static GLViewImpl* createWithEAGLView(void* eaGLView); /** creates a GLViewImpl with a title name in fullscreen mode */ - static GLViewImpl* create(std::string_view viewName); + static GLViewImpl* create(const std::string& viewName); /** creates a GLViewImpl with a title name, a rect and the zoom factor */ - static GLViewImpl* createWithRect(std::string_view viewName, const Rect& rect, float frameZoomFactor = 1.0f); + static GLViewImpl* createWithRect(const std::string& viewName, const Rect& rect, float frameZoomFactor = 1.0f); /** creates a GLViewImpl with a name in fullscreen mode */ - static GLViewImpl* createWithFullScreen(std::string_view viewName); + static GLViewImpl* createWithFullScreen(const std::string& viewName); static void convertAttrs(); static void* _pixelFormat; @@ -78,8 +78,8 @@ protected: virtual ~GLViewImpl(); bool initWithEAGLView(void* eaGLView); - bool initWithRect(std::string_view viewName, const Rect& rect, float frameZoomFactor); - bool initWithFullScreen(std::string_view viewName); + bool initWithRect(const std::string& viewName, const Rect& rect, float frameZoomFactor); + bool initWithFullScreen(const std::string& viewName); // the objective-c CCEAGLView instance void* _eaglview; diff --git a/cocos/platform/ios/CCGLViewImpl-ios.mm b/cocos/platform/ios/CCGLViewImpl-ios.mm index 594680a915..53a1e78194 100644 --- a/cocos/platform/ios/CCGLViewImpl-ios.mm +++ b/cocos/platform/ios/CCGLViewImpl-ios.mm @@ -33,15 +33,14 @@ NS_CC_BEGIN -void* GLViewImpl::_pixelFormat = kEAGLColorFormatRGB565; -int GLViewImpl::_depthFormat = GL_DEPTH_COMPONENT16; +void* GLViewImpl::_pixelFormat = kEAGLColorFormatRGB565; +int GLViewImpl::_depthFormat = GL_DEPTH_COMPONENT16; int GLViewImpl::_multisamplingCount = 0; -GLViewImpl* GLViewImpl::createWithEAGLView(void* eaglview) +GLViewImpl* GLViewImpl::createWithEAGLView(void *eaglview) { auto ret = new GLViewImpl; - if (ret->initWithEAGLView(eaglview)) - { + if(ret->initWithEAGLView(eaglview)) { ret->autorelease(); return ret; } @@ -49,11 +48,10 @@ GLViewImpl* GLViewImpl::createWithEAGLView(void* eaglview) return nullptr; } -GLViewImpl* GLViewImpl::create(std::string_view viewName) +GLViewImpl* GLViewImpl::create(const std::string& viewName) { auto ret = new GLViewImpl; - if (ret->initWithFullScreen(viewName)) - { + if(ret->initWithFullScreen(viewName)) { ret->autorelease(); return ret; } @@ -61,11 +59,10 @@ GLViewImpl* GLViewImpl::create(std::string_view viewName) return nullptr; } -GLViewImpl* GLViewImpl::createWithRect(std::string_view viewName, const Rect& rect, float frameZoomFactor) +GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, const Rect& rect, float frameZoomFactor) { auto ret = new GLViewImpl; - if (ret->initWithRect(viewName, rect, frameZoomFactor)) - { + if(ret->initWithRect(viewName, rect, frameZoomFactor)) { ret->autorelease(); return ret; } @@ -73,11 +70,10 @@ GLViewImpl* GLViewImpl::createWithRect(std::string_view viewName, const Rect& re return nullptr; } -GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName) +GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName) { auto ret = new GLViewImpl(); - if (ret->initWithFullScreen(viewName)) - { + if(ret->initWithFullScreen(viewName)) { ret->autorelease(); return ret; } @@ -87,68 +83,64 @@ GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName) void GLViewImpl::convertAttrs() { - if (_glContextAttrs.redBits == 8 && _glContextAttrs.greenBits == 8 && _glContextAttrs.blueBits == 8 && - _glContextAttrs.alphaBits == 8) + if(_glContextAttrs.redBits==8 && _glContextAttrs.greenBits==8 && _glContextAttrs.blueBits==8 && _glContextAttrs.alphaBits==8) { _pixelFormat = kEAGLColorFormatRGBA8; - } - else if (_glContextAttrs.redBits == 5 && _glContextAttrs.greenBits == 6 && _glContextAttrs.blueBits == 5 && - _glContextAttrs.alphaBits == 0) + } else if (_glContextAttrs.redBits==5 && _glContextAttrs.greenBits==6 && _glContextAttrs.blueBits==5 && _glContextAttrs.alphaBits==0) { _pixelFormat = kEAGLColorFormatRGB565; - } - else + } else { CCASSERT(0, "Unsupported render buffer pixel format. Using default"); } - if (_glContextAttrs.depthBits == 24 && _glContextAttrs.stencilBits == 8) + if(_glContextAttrs.depthBits==24 && _glContextAttrs.stencilBits==8) { _depthFormat = GL_DEPTH24_STENCIL8_OES; - } - else if (_glContextAttrs.depthBits == 0 && _glContextAttrs.stencilBits == 0) + } else if (_glContextAttrs.depthBits==0 && _glContextAttrs.stencilBits==0) { _depthFormat = 0; - } - else + } else { CCASSERT(0, "Unsupported format for depth and stencil buffers. Using default"); } - + _multisamplingCount = _glContextAttrs.multisamplingCount; } -GLViewImpl::GLViewImpl() {} +GLViewImpl::GLViewImpl() +{ +} GLViewImpl::~GLViewImpl() { - // CCEAGLView *glview = (CCEAGLView*) _eaglview; + //CCEAGLView *glview = (CCEAGLView*) _eaglview; //[glview release]; } -bool GLViewImpl::initWithEAGLView(void* eaglview) +bool GLViewImpl::initWithEAGLView(void *eaglview) { - _eaglview = eaglview; - CCEAGLView* glview = (CCEAGLView*)_eaglview; + _eaglview = eaglview; + CCEAGLView *glview = (CCEAGLView*) _eaglview; _screenSize.width = _designResolutionSize.width = [glview getWidth]; _screenSize.height = _designResolutionSize.height = [glview getHeight]; - // _scaleX = _scaleY = [glview contentScaleFactor]; +// _scaleX = _scaleY = [glview contentScaleFactor]; return true; } -bool GLViewImpl::initWithRect(std::string_view viewName, const Rect& rect, float frameZoomFactor) +bool GLViewImpl::initWithRect(const std::string& viewName, const Rect& rect, float frameZoomFactor) { CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height); convertAttrs(); - CCEAGLView* eaglview = [CCEAGLView viewWithFrame:r - pixelFormat:(NSString*)_pixelFormat - depthFormat:_depthFormat - preserveBackbuffer:NO - sharegroup:nil - multiSampling:NO - numberOfSamples:0]; + CCEAGLView *eaglview = [CCEAGLView viewWithFrame: r + pixelFormat: (NSString*)_pixelFormat + depthFormat: _depthFormat + preserveBackbuffer: NO + sharegroup: nil + multiSampling: NO + numberOfSamples: 0]; // Not available on tvOS #if !defined(CC_TARGET_OS_TVOS) @@ -157,20 +149,20 @@ bool GLViewImpl::initWithRect(std::string_view viewName, const Rect& rect, float _screenSize.width = _designResolutionSize.width = [eaglview getWidth]; _screenSize.height = _designResolutionSize.height = [eaglview getHeight]; - // _scaleX = _scaleY = [eaglview contentScaleFactor]; +// _scaleX = _scaleY = [eaglview contentScaleFactor]; _eaglview = eaglview; return true; } -bool GLViewImpl::initWithFullScreen(std::string_view viewName) +bool GLViewImpl::initWithFullScreen(const std::string& viewName) { CGRect rect = [[UIScreen mainScreen] bounds]; Rect r; - r.origin.x = rect.origin.x; - r.origin.y = rect.origin.y; - r.size.width = rect.size.width; + r.origin.x = rect.origin.x; + r.origin.y = rect.origin.y; + r.size.width = rect.size.width; r.size.height = rect.size.height; return initWithRect(viewName, r, 1); @@ -183,10 +175,10 @@ bool GLViewImpl::isOpenGLReady() bool GLViewImpl::setContentScaleFactor(float contentScaleFactor) { - CC_ASSERT(_resolutionPolicy == ResolutionPolicy::UNKNOWN); // cannot enable retina mode + CC_ASSERT(_resolutionPolicy == ResolutionPolicy::UNKNOWN); // cannot enable retina mode _scaleX = _scaleY = contentScaleFactor; - CCEAGLView* eaglview = (CCEAGLView*)_eaglview; + CCEAGLView *eaglview = (CCEAGLView*) _eaglview; [eaglview setNeedsLayout]; return true; @@ -194,11 +186,11 @@ bool GLViewImpl::setContentScaleFactor(float contentScaleFactor) float GLViewImpl::getContentScaleFactor() const { - CCEAGLView* eaglview = (CCEAGLView*)_eaglview; + CCEAGLView *eaglview = (CCEAGLView*) _eaglview; float scaleFactor = [eaglview contentScaleFactor]; - // CCASSERT(scaleFactor == _scaleX == _scaleY, "Logic error in GLView::getContentScaleFactor"); +// CCASSERT(scaleFactor == _scaleX == _scaleY, "Logic error in GLView::getContentScaleFactor"); return scaleFactor; } @@ -208,22 +200,23 @@ void GLViewImpl::end() [CCDirectorCaller destroy]; // destroy EAGLView - CCEAGLView* eaglview = (CCEAGLView*)_eaglview; + CCEAGLView *eaglview = (CCEAGLView*) _eaglview; [eaglview removeFromSuperview]; //[eaglview release]; release(); } + void GLViewImpl::swapBuffers() { - CCEAGLView* eaglview = (CCEAGLView*)_eaglview; + CCEAGLView *eaglview = (CCEAGLView*) _eaglview; [eaglview swapBuffers]; } void GLViewImpl::setIMEKeyboardState(bool open) { - CCEAGLView* eaglview = (CCEAGLView*)_eaglview; + CCEAGLView *eaglview = (CCEAGLView*) _eaglview; if (open) { @@ -237,16 +230,16 @@ void GLViewImpl::setIMEKeyboardState(bool open) Rect GLViewImpl::getSafeAreaRect() const { - CCEAGLView* eaglview = (CCEAGLView*)_eaglview; + CCEAGLView *eaglview = (CCEAGLView*) _eaglview; #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 float version = [[UIDevice currentDevice].systemVersion floatValue]; if (version >= 11.0f) { -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wpartial-availability" +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpartial-availability" UIEdgeInsets safeAreaInsets = eaglview.safeAreaInsets; -# pragma clang diagnostic pop +#pragma clang diagnostic pop // Multiply contentScaleFactor since safeAreaInsets return points. safeAreaInsets.left *= eaglview.contentScaleFactor; @@ -256,23 +249,23 @@ Rect GLViewImpl::getSafeAreaRect() const // Get leftBottom and rightTop point in UI coordinates Vec2 leftBottom = Vec2(safeAreaInsets.left, _screenSize.height - safeAreaInsets.bottom); - Vec2 rightTop = Vec2(_screenSize.width - safeAreaInsets.right, safeAreaInsets.top); + Vec2 rightTop = Vec2(_screenSize.width - safeAreaInsets.right, safeAreaInsets.top); // Convert a point from UI coordinates to which in design resolution coordinate. leftBottom.x = (leftBottom.x - _viewPortRect.origin.x) / _scaleX, leftBottom.y = (leftBottom.y - _viewPortRect.origin.y) / _scaleY; - rightTop.x = (rightTop.x - _viewPortRect.origin.x) / _scaleX, - rightTop.y = (rightTop.y - _viewPortRect.origin.y) / _scaleY; + rightTop.x = (rightTop.x - _viewPortRect.origin.x) / _scaleX, + rightTop.y = (rightTop.y - _viewPortRect.origin.y) / _scaleY; // Adjust points to make them inside design resolution leftBottom.x = MAX(leftBottom.x, 0); leftBottom.y = MIN(leftBottom.y, _designResolutionSize.height); - rightTop.x = MIN(rightTop.x, _designResolutionSize.width); - rightTop.y = MAX(rightTop.y, 0); + rightTop.x = MIN(rightTop.x, _designResolutionSize.width); + rightTop.y = MAX(rightTop.y, 0); // Convert to GL coordinates leftBottom = Director::getInstance()->convertToGL(leftBottom); - rightTop = Director::getInstance()->convertToGL(rightTop); + rightTop = Director::getInstance()->convertToGL(rightTop); return Rect(leftBottom.x, leftBottom.y, rightTop.x - leftBottom.x, rightTop.y - leftBottom.y); } diff --git a/cocos/platform/ios/CCImage-ios.mm b/cocos/platform/ios/CCImage-ios.mm index 372ed56fa1..b5b9387998 100644 --- a/cocos/platform/ios/CCImage-ios.mm +++ b/cocos/platform/ios/CCImage-ios.mm @@ -35,16 +35,15 @@ THE SOFTWARE. NS_CC_BEGIN -bool cocos2d::Image::saveToFile(std::string_view filename, bool isToRGB) +bool cocos2d::Image::saveToFile(const std::string& filename, bool isToRGB) { - // only support for backend::PixelFormat::RGB8 or backend::PixelFormat::RGBA8 uncompressed data + //only support for backend::PixelFormat::RGB8 or backend::PixelFormat::RGBA8 uncompressed data if (isCompressed() || (_pixelFormat != backend::PixelFormat::RGB8 && _pixelFormat != backend::PixelFormat::RGBA8)) { - CCLOG("cocos2d: Image: saveToFile is only support for backend::PixelFormat::RGB8 or " - "backend::PixelFormat::RGBA8 uncompressed data for now"); + CCLOG("cocos2d: Image: saveToFile is only support for backend::PixelFormat::RGB8 or backend::PixelFormat::RGBA8 uncompressed data for now"); return false; } - bool saveToPNG = false; + bool saveToPNG = false; bool needToCopyPixels = false; std::string basename(filename); @@ -53,65 +52,64 @@ bool cocos2d::Image::saveToFile(std::string_view filename, bool isToRGB) { saveToPNG = true; } - - int bitsPerComponent = 8; - int bitsPerPixel = hasAlpha() ? 32 : 24; - if ((!saveToPNG) || isToRGB) + + int bitsPerComponent = 8; + int bitsPerPixel = hasAlpha() ? 32 : 24; + if ((! saveToPNG) || isToRGB) { bitsPerPixel = 24; - } - - int bytesPerRow = (bitsPerPixel / 8) * _width; + } + + int bytesPerRow = (bitsPerPixel/8) * _width; int myDataLength = bytesPerRow * _height; - - unsigned char* pixels = _data; - + + unsigned char *pixels = _data; + // The data has alpha channel, and want to save it with an RGB png file, // or want to save as jpg, remove the alpha channel. if (hasAlpha() && bitsPerPixel == 24) { pixels = new unsigned char[myDataLength]; - + for (int i = 0; i < _height; ++i) { for (int j = 0; j < _width; ++j) { - pixels[(i * _width + j) * 3] = _data[(i * _width + j) * 4]; + pixels[(i * _width + j) * 3] = _data[(i * _width + j) * 4]; pixels[(i * _width + j) * 3 + 1] = _data[(i * _width + j) * 4 + 1]; pixels[(i * _width + j) * 3 + 2] = _data[(i * _width + j) * 4 + 2]; } } - + needToCopyPixels = true; } - + // make data provider with data. CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault; - if (saveToPNG && hasAlpha() && (!isToRGB)) + if (saveToPNG && hasAlpha() && (! isToRGB)) { bitmapInfo |= kCGImageAlphaLast; } - CGDataProviderRef provider = CGDataProviderCreateWithData(nullptr, pixels, myDataLength, nullptr); - CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); - CGImageRef iref = CGImageCreate(_width, _height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, - bitmapInfo, provider, nullptr, false, kCGRenderingIntentDefault); - - UIImage* image = [[UIImage alloc] initWithCGImage:iref]; - - CGImageRelease(iref); + CGDataProviderRef provider = CGDataProviderCreateWithData(nullptr, pixels, myDataLength, nullptr); + CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); + CGImageRef iref = CGImageCreate(_width, _height, + bitsPerComponent, bitsPerPixel, bytesPerRow, + colorSpaceRef, bitmapInfo, provider, + nullptr, false, + kCGRenderingIntentDefault); + + UIImage* image = [[UIImage alloc] initWithCGImage:iref]; + + CGImageRelease(iref); CGColorSpaceRelease(colorSpaceRef); CGDataProviderRelease(provider); // NOTE: Prevent memory leak. Requires ARC enabled. - @autoreleasepool - { - NSData* data; - if (saveToPNG) - { + @autoreleasepool { + NSData *data; + if (saveToPNG) { data = UIImagePNGRepresentation(image); - } - else - { + } else { data = UIImageJPEGRepresentation(image, 1.0f); } @@ -123,9 +121,9 @@ bool cocos2d::Image::saveToFile(std::string_view filename, bool isToRGB) if (needToCopyPixels) { - delete[] pixels; + delete [] pixels; } - + return true; } diff --git a/cocos/platform/ios/CCInputView-ios.mm b/cocos/platform/ios/CCInputView-ios.mm index aea326830e..8b131d54f5 100644 --- a/cocos/platform/ios/CCInputView-ios.mm +++ b/cocos/platform/ios/CCInputView-ios.mm @@ -41,31 +41,27 @@ THE SOFTWARE. @synthesize tokenizer; @synthesize autocorrectionType; -- (instancetype)initWithFrame:(CGRect)frame -{ - if (self = [super initWithFrame:frame]) - { - self.myMarkedText = nil; +- (instancetype) initWithFrame:(CGRect)frame { + if (self = [super initWithFrame:frame] ) { + self.myMarkedText = nil; self.autocorrectionType = UITextAutocorrectionTypeNo; } - + return self; } -- (void)dealloc -{ - [[NSNotificationCenter defaultCenter] removeObserver:self]; // remove keyboard notification +- (void) dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; // remove keyboard notification [self.myMarkedText release]; [self removeFromSuperview]; [super dealloc]; } -- (BOOL)canBecomeFirstResponder -{ +- (BOOL) canBecomeFirstResponder { return YES; } -- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event +- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self resignFirstResponder]; [self removeFromSuperview]; @@ -73,190 +69,159 @@ THE SOFTWARE. #pragma TextInput protocol -- (id)inputDelegate -{ +- (id)inputDelegate { return nil; } -- (void)setInputDelegate:(id)inputDelegate -{} +- (void)setInputDelegate:(id)inputDelegate { + +} -- (void)setSelectedTextRange:(UITextRange*)aSelectedTextRange -{ +- (void)setSelectedTextRange:(UITextRange *)aSelectedTextRange { CCLOG("UITextRange:setSelectedTextRange"); } -- (UITextRange*)selectedTextRange -{ +- (UITextRange *)selectedTextRange { return [[[UITextRange alloc] init] autorelease]; } -- (void)deleteBackward -{ - if (nil != self.myMarkedText) - { +- (void)deleteBackward { + if (nil != self.myMarkedText) { [self.myMarkedText release]; self.myMarkedText = nil; } cocos2d::IMEDispatcher::sharedDispatcher()->dispatchDeleteBackward(); } -- (void)insertText:(nonnull NSString*)text -{ - if (nil != self.myMarkedText) - { +- (void)insertText:(nonnull NSString *)text { + if (nil != self.myMarkedText) { [self.myMarkedText release]; self.myMarkedText = nil; } - const char* pszText = [text cStringUsingEncoding:NSUTF8StringEncoding]; + const char * pszText = [text cStringUsingEncoding:NSUTF8StringEncoding]; cocos2d::IMEDispatcher::sharedDispatcher()->dispatchInsertText(pszText, strlen(pszText)); } -- (NSWritingDirection)baseWritingDirectionForPosition:(nonnull UITextPosition*)position - inDirection:(UITextStorageDirection)direction -{ +- (NSWritingDirection)baseWritingDirectionForPosition:(nonnull UITextPosition *)position inDirection:(UITextStorageDirection)direction { CCLOG("baseWritingDirectionForPosition"); return NSWritingDirectionLeftToRight; } -- (CGRect)caretRectForPosition:(nonnull UITextPosition*)position -{ +- (CGRect)caretRectForPosition:(nonnull UITextPosition *)position { CCLOG("caretRectForPosition"); return CGRectZero; } -- (nullable UITextRange*)characterRangeAtPoint:(CGPoint)point -{ +- (nullable UITextRange *)characterRangeAtPoint:(CGPoint)point { CCLOG("characterRangeAtPoint"); return nil; } -- (nullable UITextRange*)characterRangeByExtendingPosition:(nonnull UITextPosition*)position - inDirection:(UITextLayoutDirection)direction -{ +- (nullable UITextRange *)characterRangeByExtendingPosition:(nonnull UITextPosition *)position inDirection:(UITextLayoutDirection)direction { CCLOG("characterRangeByExtendingPosition"); return nil; } -- (nullable UITextPosition*)closestPositionToPoint:(CGPoint)point -{ +- (nullable UITextPosition *)closestPositionToPoint:(CGPoint)point { CCLOG("closestPositionToPoint"); return nil; } -- (nullable UITextPosition*)closestPositionToPoint:(CGPoint)point withinRange:(nonnull UITextRange*)range -{ +- (nullable UITextPosition *)closestPositionToPoint:(CGPoint)point withinRange:(nonnull UITextRange *)range { CCLOG("closestPositionToPoint"); return nil; } -- (NSComparisonResult)comparePosition:(nonnull UITextPosition*)position toPosition:(nonnull UITextPosition*)other -{ +- (NSComparisonResult)comparePosition:(nonnull UITextPosition *)position toPosition:(nonnull UITextPosition *)other { CCLOG("comparePosition"); return (NSComparisonResult)0; } -- (CGRect)firstRectForRange:(nonnull UITextRange*)range -{ +- (CGRect)firstRectForRange:(nonnull UITextRange *)range { CCLOG("firstRectForRange"); return CGRectNull; } -- (NSInteger)offsetFromPosition:(nonnull UITextPosition*)from toPosition:(nonnull UITextPosition*)toPosition -{ +- (NSInteger)offsetFromPosition:(nonnull UITextPosition *)from toPosition:(nonnull UITextPosition *)toPosition { CCLOG("offsetFromPosition"); return 0; } -- (nullable UITextPosition*)positionFromPosition:(nonnull UITextPosition*)position - inDirection:(UITextLayoutDirection)direction - offset:(NSInteger)offset -{ +- (nullable UITextPosition *)positionFromPosition:(nonnull UITextPosition *)position inDirection:(UITextLayoutDirection)direction offset:(NSInteger)offset { CCLOG("positionFromPosition"); return nil; } -- (nullable UITextPosition*)positionFromPosition:(nonnull UITextPosition*)position offset:(NSInteger)offset -{ +- (nullable UITextPosition *)positionFromPosition:(nonnull UITextPosition *)position offset:(NSInteger)offset { CCLOG("positionFromPosition"); return nil; } -- (nullable UITextPosition*)positionWithinRange:(nonnull UITextRange*)range - farthestInDirection:(UITextLayoutDirection)direction -{ +- (nullable UITextPosition *)positionWithinRange:(nonnull UITextRange *)range farthestInDirection:(UITextLayoutDirection)direction { CCLOG("positionWithinRange"); return nil; } -- (void)replaceRange:(nonnull UITextRange*)range withText:(nonnull NSString*)text -{} +- (void)replaceRange:(nonnull UITextRange *)range withText:(nonnull NSString *)text { + +} -- (nonnull NSArray*)selectionRectsForRange:(nonnull UITextRange*)range -{ +- (nonnull NSArray *)selectionRectsForRange:(nonnull UITextRange *)range { CCLOG("selectionRectsForRange"); return nil; } -- (void)setBaseWritingDirection:(NSWritingDirection)writingDirection forRange:(nonnull UITextRange*)range -{} +- (void)setBaseWritingDirection:(NSWritingDirection)writingDirection forRange:(nonnull UITextRange *)range { + +} -- (void)setMarkedText:(nullable NSString*)markedText selectedRange:(NSRange)selectedRange -{ +- (void)setMarkedText:(nullable NSString *)markedText selectedRange:(NSRange)selectedRange { CCLOG("setMarkedText"); - if (markedText == self.myMarkedText) - { + if (markedText == self.myMarkedText) { return; } - if (nil != self.myMarkedText) - { + if (nil != self.myMarkedText) { [self.myMarkedText release]; } self.myMarkedText = markedText; [self.myMarkedText retain]; } -- (UITextRange*)markedTextRange +- (UITextRange *)markedTextRange { CCLOG("markedTextRange"); - if (nil != self.myMarkedText) - { + if (nil != self.myMarkedText) { return [[[UITextRange alloc] init] autorelease]; } - return nil; // Nil if no marked text. + return nil; // Nil if no marked text. } -- (nullable NSString*)textInRange:(nonnull UITextRange*)range -{ +- (nullable NSString *)textInRange:(nonnull UITextRange *)range { CCLOG("textInRange"); - if (nil != self.myMarkedText) - { + if (nil != self.myMarkedText) { return self.myMarkedText; } return nil; } -- (nullable UITextRange*)textRangeFromPosition:(nonnull UITextPosition*)fromPosition - toPosition:(nonnull UITextPosition*)toPosition -{ +- (nullable UITextRange *)textRangeFromPosition:(nonnull UITextPosition *)fromPosition toPosition:(nonnull UITextPosition *)toPosition { CCLOG("textRangeFromPosition"); return nil; } -- (void)unmarkText -{ +- (void)unmarkText { CCLOG("unmarkText"); if (nil == self.myMarkedText) { return; } - const char* pszText = [self.myMarkedText cStringUsingEncoding:NSUTF8StringEncoding]; + const char * pszText = [self.myMarkedText cStringUsingEncoding:NSUTF8StringEncoding]; cocos2d::IMEDispatcher::sharedDispatcher()->dispatchInsertText(pszText, strlen(pszText)); [self.myMarkedText release]; self.myMarkedText = nil; } -- (void)encodeWithCoder:(nonnull NSCoder*)coder -{} +- (void)encodeWithCoder:(nonnull NSCoder *)coder { +} @end diff --git a/cocos/platform/linux/CCApplication-linux.cpp b/cocos/platform/linux/CCApplication-linux.cpp index fa98b686a6..be903a2dab 100644 --- a/cocos/platform/linux/CCApplication-linux.cpp +++ b/cocos/platform/linux/CCApplication-linux.cpp @@ -110,7 +110,7 @@ void Application::setAnimationInterval(float interval) _animationInterval = interval * 1000.0f; } -void Application::setResourceRootPath(std::string_view rootResDir) +void Application::setResourceRootPath(const std::string& rootResDir) { _resourceRootPath = rootResDir; if (_resourceRootPath[_resourceRootPath.length() - 1] != '/') @@ -123,7 +123,7 @@ void Application::setResourceRootPath(std::string_view rootResDir) pFileUtils->setSearchPaths(searchPaths); } -std::string_view Application::getResourceRootPath() +const std::string& Application::getResourceRootPath() { return _resourceRootPath; } @@ -138,7 +138,7 @@ std::string Application::getVersion() return ""; } -bool Application::openURL(std::string_view url) +bool Application::openURL(const std::string& url) { std::string op = std::string("xdg-open '").append(url).append("'"); return system(op.c_str()) == 0; diff --git a/cocos/platform/linux/CCApplication-linux.h b/cocos/platform/linux/CCApplication-linux.h index 3d5c05e602..8f40f7ea00 100644 --- a/cocos/platform/linux/CCApplication-linux.h +++ b/cocos/platform/linux/CCApplication-linux.h @@ -84,19 +84,19 @@ public: @param String with url to open. @return true if the resource located by the URL was successfully opened; otherwise false. */ - virtual bool openURL(std::string_view url) override; + virtual bool openURL(const std::string& url) override; /** * Sets the Resource root path. * @deprecated Please use FileUtils::getInstance()->setSearchPaths() instead. */ - CC_DEPRECATED_ATTRIBUTE void setResourceRootPath(std::string_view rootResDir); + CC_DEPRECATED_ATTRIBUTE void setResourceRootPath(const std::string& rootResDir); /** * Gets the Resource root path. * @deprecated Please use FileUtils::getInstance()->getSearchPaths() instead. */ - CC_DEPRECATED_ATTRIBUTE std::string_view getResourceRootPath(); + CC_DEPRECATED_ATTRIBUTE const std::string& getResourceRootPath(); /** @brief Get target platform diff --git a/cocos/platform/linux/CCFileUtils-linux.cpp b/cocos/platform/linux/CCFileUtils-linux.cpp index 31ab5ada2e..0ec3a38d07 100644 --- a/cocos/platform/linux/CCFileUtils-linux.cpp +++ b/cocos/platform/linux/CCFileUtils-linux.cpp @@ -2,9 +2,8 @@ Copyright (c) 2011 Laschweinski Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -Copyright (c) 2021 Bytedance Inc. -https://adxeproject.github.io +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 @@ -116,23 +115,22 @@ std::string FileUtilsLinux::getNativeWritableAbsolutePath() const return _writablePath; } -bool FileUtilsLinux::isFileExistInternal(std::string_view path) const +bool FileUtilsLinux::isFileExistInternal(const std::string& strFilePath) const { DECLARE_GUARD; - if (path.empty()) + if (strFilePath.empty()) { return false; } - std::string strPath; - if (!isAbsolutePath(path)) + std::string strPath = strFilePath; + if (!isAbsolutePath(strPath)) { // Not absolute path, add the default root path at the beginning. - strPath.assign(_defaultResRootPath).append(path); - path = strPath; + strPath.insert(0, _defaultResRootPath); } struct stat sts; - return (stat(path.data(), &sts) == 0) && S_ISREG(sts.st_mode); + return (stat(strPath.c_str(), &sts) == 0) && S_ISREG(sts.st_mode); } NS_CC_END diff --git a/cocos/platform/linux/CCFileUtils-linux.h b/cocos/platform/linux/CCFileUtils-linux.h index 1dc54ec213..258ac96d99 100644 --- a/cocos/platform/linux/CCFileUtils-linux.h +++ b/cocos/platform/linux/CCFileUtils-linux.h @@ -56,7 +56,7 @@ public: std::string getNativeWritableAbsolutePath() const override; private: - virtual bool isFileExistInternal(std::string_view strFilePath) const override; + virtual bool isFileExistInternal(const std::string& strFilePath) const override; }; // end of platform group diff --git a/cocos/platform/mac/CCApplication-mac.h b/cocos/platform/mac/CCApplication-mac.h index fe6bbbff1a..9636b4af88 100644 --- a/cocos/platform/mac/CCApplication-mac.h +++ b/cocos/platform/mac/CCApplication-mac.h @@ -90,11 +90,11 @@ public: @param String with url to open. @return true if the resource located by the URL was successfully opened; otherwise false. */ - virtual bool openURL(std::string_view url) override; + virtual bool openURL(const std::string& url) override; - void setStartupScriptFilename(std::string_view startupScriptFile); + void setStartupScriptFilename(const std::string& startupScriptFile); - std::string_view getStartupScriptFilename(); + const std::string& getStartupScriptFilename(); protected: static Application* sm_pSharedApplication; diff --git a/cocos/platform/mac/CCApplication-mac.mm b/cocos/platform/mac/CCApplication-mac.mm index b4fd1dc684..8d8a92b313 100644 --- a/cocos/platform/mac/CCApplication-mac.mm +++ b/cocos/platform/mac/CCApplication-mac.mm @@ -40,17 +40,18 @@ static int32_t getCurrentMillSecond() { int32_t lLastTime = 0; struct timeval stCurrentTime; - - gettimeofday(&stCurrentTime, NULL); - lLastTime = stCurrentTime.tv_sec * 1000 + stCurrentTime.tv_usec * 0.001; // milliseconds + + gettimeofday(&stCurrentTime,NULL); + lLastTime = stCurrentTime.tv_sec*1000+stCurrentTime.tv_usec*0.001; // milliseconds return lLastTime; } Application* Application::sm_pSharedApplication = nullptr; -Application::Application() : _animationInterval(1.0f / 60.0f * 1000.0f) +Application::Application() +: _animationInterval(1.0f/60.0f*1000.0f) { - CCASSERT(!sm_pSharedApplication, "sm_pSharedApplication already exist"); + CCASSERT(! sm_pSharedApplication, "sm_pSharedApplication already exist"); sm_pSharedApplication = this; } @@ -63,53 +64,53 @@ Application::~Application() int Application::run() { initGLContextAttrs(); - if (!applicationDidFinishLaunching()) + if(!applicationDidFinishLaunching()) { return 1; } - + int32_t lastTime = 0L; - int32_t curTime = 0L; - + int32_t curTime = 0L; + auto director = Director::getInstance(); - auto glview = director->getOpenGLView(); - + auto glview = director->getOpenGLView(); + // Retain glview to avoid glview being released in the while loop glview->retain(); while (!glview->windowShouldClose()) { lastTime = getCurrentMillSecond(); - + director->mainLoop(); glview->pollEvents(); curTime = getCurrentMillSecond(); if (curTime - lastTime < _animationInterval) { - usleep(static_cast((_animationInterval - curTime + lastTime) * 1000)); + usleep(static_cast((_animationInterval - curTime + lastTime)*1000)); } } /* Only work on Desktop - * Director::mainLoop is really one frame logic - * when we want to close the window, we should call Director::end(); - * then call Director::mainLoop to do release of internal resources - */ + * Director::mainLoop is really one frame logic + * when we want to close the window, we should call Director::end(); + * then call Director::mainLoop to do release of internal resources + */ if (glview->isOpenGLReady()) { director->end(); director->mainLoop(); } - + glview->release(); - + return 0; } void Application::setAnimationInterval(float interval) { - _animationInterval = interval * 1000.0f; + _animationInterval = interval*1000.0f; } Application::Platform Application::getTargetPlatform() @@ -117,11 +118,9 @@ Application::Platform Application::getTargetPlatform() return Platform::OS_MAC; } -std::string Application::getVersion() -{ +std::string Application::getVersion() { NSString* version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]; - if (version) - { + if (version) { return [version UTF8String]; } return ""; @@ -137,49 +136,49 @@ Application* Application::getInstance() return sm_pSharedApplication; } -const char* Application::getCurrentLanguageCode() +const char * Application::getCurrentLanguageCode() { - static char code[3] = {0}; - NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; - NSArray* languages = [defaults objectForKey:@"AppleLanguages"]; - NSString* currentLanguage = [languages objectAtIndex:0]; - + static char code[3]={0}; + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + NSArray *languages = [defaults objectForKey:@"AppleLanguages"]; + NSString *currentLanguage = [languages objectAtIndex:0]; + // get the current language code.(such as English is "en", Chinese is "zh" and so on) - NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; - NSString* languageCode = [temp objectForKey:NSLocaleLanguageCode]; + NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; + NSString * languageCode = [temp objectForKey:NSLocaleLanguageCode]; [languageCode getCString:code maxLength:3 encoding:NSASCIIStringEncoding]; - code[2] = '\0'; + code[2]='\0'; return code; } LanguageType Application::getCurrentLanguage() { // get the current language and country config - NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; - NSArray* languages = [defaults objectForKey:@"AppleLanguages"]; - NSString* currentLanguage = [languages objectAtIndex:0]; - + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + NSArray *languages = [defaults objectForKey:@"AppleLanguages"]; + NSString *currentLanguage = [languages objectAtIndex:0]; + // get the current language code.(such as English is "en", Chinese is "zh" and so on) - NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; - NSString* languageCode = [temp objectForKey:NSLocaleLanguageCode]; - + NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; + NSString * languageCode = [temp objectForKey:NSLocaleLanguageCode]; + return utils::getLanguageTypeByISO2([languageCode UTF8String]); } -bool Application::openURL(std::string_view url) +bool Application::openURL(const std::string &url) { - NSString* msg = [NSString stringWithCString:url.data() encoding:NSUTF8StringEncoding]; - NSURL* nsUrl = [NSURL URLWithString:msg]; + NSString* msg = [NSString stringWithCString:url.c_str() encoding:NSUTF8StringEncoding]; + NSURL* nsUrl = [NSURL URLWithString:msg]; return [[NSWorkspace sharedWorkspace] openURL:nsUrl]; } -void Application::setStartupScriptFilename(std::string_view startupScriptFile) +void Application::setStartupScriptFilename(const std::string& startupScriptFile) { _startupScriptFilename = startupScriptFile; std::replace(_startupScriptFilename.begin(), _startupScriptFilename.end(), '\\', '/'); } -std::string_view Application::getStartupScriptFilename() +const std::string& Application::getStartupScriptFilename() { return _startupScriptFilename; } diff --git a/cocos/platform/mac/CCCommon-mac.mm b/cocos/platform/mac/CCCommon-mac.mm index 5e3be91e60..3ce527eb52 100644 --- a/cocos/platform/mac/CCCommon-mac.mm +++ b/cocos/platform/mac/CCCommon-mac.mm @@ -33,25 +33,25 @@ THE SOFTWARE. NS_CC_BEGIN -void LuaLog(const char* format) +void LuaLog(const char * format) { puts(format); } // ios no MessageBox, use log instead -void ccMessageBox(const char* msg, const char* title) +void ccMessageBox(const char * msg, const char * title) { - NSString* tmpTitle = (title) ? [NSString stringWithUTF8String:title] : nil; - NSString* tmpMsg = (msg) ? [NSString stringWithUTF8String:msg] : nil; + NSString * tmpTitle = (title) ? [NSString stringWithUTF8String : title] : nil; + NSString * tmpMsg = (msg) ? [NSString stringWithUTF8String : msg] : nil; - NSAlert* alert = [[[NSAlert alloc] init] autorelease]; + NSAlert *alert = [[[NSAlert alloc] init] autorelease]; [alert addButtonWithTitle:@"OK"]; [alert setMessageText:tmpMsg]; [alert setInformativeText:tmpTitle]; [alert setAlertStyle:NSAlertStyleWarning]; auto glview = Director::getInstance()->getOpenGLView(); - id window = glview->getCocoaWindow(); + id window = glview->getCocoaWindow(); [alert beginSheetModalForWindow:window completionHandler:nil]; } diff --git a/cocos/platform/mac/CCDevice-mac.mm b/cocos/platform/mac/CCDevice-mac.mm index cf1b1ae014..5a8b4e09c9 100644 --- a/cocos/platform/mac/CCDevice-mac.mm +++ b/cocos/platform/mac/CCDevice-mac.mm @@ -36,37 +36,41 @@ static NSAttributedString* __attributedStringWithFontSize(NSMutableAttributedStr { { [attributedString beginEditing]; - - [attributedString enumerateAttribute:NSFontAttributeName - inRange:NSMakeRange(0, attributedString.length) - options:0 - usingBlock:^(id value, NSRange range, BOOL* stop) { - NSFont* font = value; - font = [[NSFontManager sharedFontManager] convertFont:font toSize:fontSize]; - - [attributedString removeAttribute:NSFontAttributeName range:range]; - [attributedString addAttribute:NSFontAttributeName value:font range:range]; - }]; - + + [attributedString enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, attributedString.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) { + + NSFont* font = value; + font = [[NSFontManager sharedFontManager] convertFont:font toSize:fontSize]; + + [attributedString removeAttribute:NSFontAttributeName range:range]; + [attributedString addAttribute:NSFontAttributeName value:font range:range]; + }]; + [attributedString endEditing]; } - + return [[attributedString copy] autorelease]; } int Device::getDPI() { - NSScreen* screen = [NSScreen mainScreen]; - NSDictionary* description = [screen deviceDescription]; - NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue]; + NSScreen *screen = [NSScreen mainScreen]; + NSDictionary *description = [screen deviceDescription]; + NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue]; CGSize displayPhysicalSize = CGDisplayScreenSize([[description objectForKey:@"NSScreenNumber"] unsignedIntValue]); - + return ((displayPixelSize.width / displayPhysicalSize.width) * 25.4f); } -void Device::setAccelerometerEnabled(bool isEnabled) {} +void Device::setAccelerometerEnabled(bool isEnabled) +{ -void Device::setAccelerometerInterval(float interval) {} +} + +void Device::setAccelerometerInterval(float interval) +{ + +} typedef struct { @@ -77,359 +81,305 @@ typedef struct unsigned char* data; } tImageInfo; -static NSSize _calculateStringSize(NSAttributedString* str, - id font, - CGSize* constrainSize, - bool enableWrap, - int overflow) +static NSSize _calculateStringSize(NSAttributedString *str, id font, CGSize *constrainSize, bool enableWrap, int overflow) { NSSize textRect = NSZeroSize; - textRect.width = constrainSize->width > 0 ? constrainSize->width : CGFLOAT_MAX; - textRect.height = constrainSize->height > 0 ? constrainSize->height : CGFLOAT_MAX; - - if (overflow == 1) - { - if (!enableWrap) - { - textRect.width = CGFLOAT_MAX; + textRect.width = constrainSize->width > 0 ? constrainSize->width + : CGFLOAT_MAX; + textRect.height = constrainSize->height > 0 ? constrainSize->height + : CGFLOAT_MAX; + + if (overflow == 1) { + if (!enableWrap) { + textRect.width = CGFLOAT_MAX; textRect.height = CGFLOAT_MAX; - } - else - { + } else { textRect.height = CGFLOAT_MAX; } } - + NSSize dim; #ifdef __MAC_10_11 -# if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_11 - dim = [str boundingRectWithSize:textRect - options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin)context:nil] - .size; -# else - dim = [str boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin)] - .size; -# endif + #if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_11 + dim = [str boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin) context:nil].size; + #else + dim = [str boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin)].size; + #endif #else - dim = [str boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin)] - .size; + dim = [str boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin)].size; #endif - - dim.width = ceilf(dim.width); + + + dim.width = ceilf(dim.width); dim.height = ceilf(dim.height); return dim; } -static NSSize _calculateRealSizeForString(NSAttributedString** str, id font, NSSize constrainSize, bool enableWrap) +static NSSize _calculateRealSizeForString(NSAttributedString **str, id font, NSSize constrainSize, bool enableWrap) { CGRect actualSize = CGRectMake(0, 0, constrainSize.width + 1, constrainSize.height + 1); - int fontSize = [font pointSize]; - fontSize = fontSize + 1; + int fontSize = [font pointSize]; + fontSize = fontSize + 1; - if (!enableWrap) - { - while (actualSize.size.width > constrainSize.width || actualSize.size.height > constrainSize.height) - { + if (!enableWrap) { + while (actualSize.size.width > constrainSize.width || + actualSize.size.height > constrainSize.height) { fontSize = fontSize - 1; - if (fontSize < 0) - { + if (fontSize < 0) { actualSize = CGRectMake(0, 0, 0, 0); break; } - - NSMutableAttributedString* mutableString = [[*str mutableCopy] autorelease]; - *str = __attributedStringWithFontSize(mutableString, fontSize); + + NSMutableAttributedString *mutableString = [[*str mutableCopy] autorelease]; + *str = __attributedStringWithFontSize(mutableString, fontSize); #ifdef __MAC_10_11 -# if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_11 - CGSize fitSize = [*str boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) - options:NSStringDrawingUsesLineFragmentOrigin - context:nil] - .size; -# else - CGSize fitSize = [*str boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) - options:NSStringDrawingUsesLineFragmentOrigin] - .size; -# endif + #if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_11 + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size; + #else + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin].size; + #endif #else - CGSize fitSize = [*str boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) - options:NSStringDrawingUsesLineFragmentOrigin] - .size; + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin].size; #endif - if (fitSize.width == 0 || fitSize.height == 0) - continue; + if(fitSize.width == 0 || fitSize.height == 0) continue; actualSize.size = fitSize; - if (constrainSize.width <= 0) - { + if (constrainSize.width <= 0) { constrainSize.width = fitSize.width; } - if (constrainSize.height <= 0) - { + if (constrainSize.height <= 0){ constrainSize.height = fitSize.height; } - if (fontSize <= 0) - { + if(fontSize <= 0){ break; } } + } - else - { - while (actualSize.size.height > constrainSize.height || actualSize.size.width > constrainSize.width) - { + else { + while (actualSize.size.height > constrainSize.height + ||actualSize.size.width > constrainSize.width) { fontSize = fontSize - 1; - if (fontSize < 0) - { + if (fontSize < 0) { actualSize = CGRectMake(0, 0, 0, 0); break; } - - NSMutableAttributedString* mutableString = [[*str mutableCopy] autorelease]; - *str = __attributedStringWithFontSize(mutableString, fontSize); + + NSMutableAttributedString *mutableString = [[*str mutableCopy] autorelease]; + *str = __attributedStringWithFontSize(mutableString, fontSize); #ifdef __MAC_10_11 -# if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_11 - CGSize fitSize = [*str boundingRectWithSize:CGSizeMake(constrainSize.width, CGFLOAT_MAX) - options:NSStringDrawingUsesLineFragmentOrigin - context:nil] - .size; -# else - CGSize fitSize = [*str boundingRectWithSize:CGSizeMake(constrainSize.width, CGFLOAT_MAX) - options:NSStringDrawingUsesLineFragmentOrigin] - .size; -# endif + #if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_11 + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( constrainSize.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size; + #else + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( constrainSize.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin].size; + #endif #else - CGSize fitSize = [*str boundingRectWithSize:CGSizeMake(constrainSize.width, CGFLOAT_MAX) - options:NSStringDrawingUsesLineFragmentOrigin] - .size; + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( constrainSize.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin].size; #endif - - if (fitSize.width == 0 || fitSize.height == 0) - continue; + + if(fitSize.width == 0 || fitSize.height == 0) continue; actualSize.size = fitSize; - - if (constrainSize.width <= 0) - { + + if (constrainSize.width <= 0) { constrainSize.width = fitSize.width; } - if (constrainSize.height <= 0) - { + if (constrainSize.height <= 0){ constrainSize.height = fitSize.height; } - if (fontSize <= 0) - { + if(fontSize <= 0){ break; } } + } return CGSizeMake(actualSize.size.width, actualSize.size.height); } static NSFont* _createSystemFont(const char* fontName, int size) { - NSString* fntName = [NSString stringWithUTF8String:fontName]; - fntName = [[fntName lastPathComponent] stringByDeletingPathExtension]; - + NSString * fntName = [NSString stringWithUTF8String:fontName]; + fntName = [[fntName lastPathComponent] stringByDeletingPathExtension]; + // font - NSFont* font = [NSFont fontWithName:fntName size:size]; - - if (font == nil) - { + NSFont *font = [NSFont fontWithName:fntName size:size]; + + if (font == nil) { font = [NSFont systemFontOfSize:size]; } return font; } + static CGFloat _calculateTextDrawStartHeight(cocos2d::Device::TextAlign align, CGSize realDimensions, CGSize dimensions) { float startH = 0; // vertical alignment unsigned int vAlignment = ((int)align >> 4) & 0x0F; - switch (vAlignment) - { - // bottom - case 1: - startH = dimensions.height - realDimensions.height; - break; - // top - case 2: - startH = 0; - break; - // center - case 3: - startH = (dimensions.height - realDimensions.height) / 2; - break; - default: - break; + switch (vAlignment) { + //bottom + case 1:startH = dimensions.height - realDimensions.height;break; + //top + case 2:startH = 0;break; + //center + case 3: startH = (dimensions.height - realDimensions.height) / 2;break; + default: + break; } return startH; } -static bool _initWithString(const char* text, - Device::TextAlign align, - const char* fontName, - int size, - tImageInfo* info, - const Color3B* fontColor, - int fontAlpha, - bool enableWrap, - int overflow, - const FontStroke& stroke) +static bool _initWithString(const char * text, Device::TextAlign align, const char * fontName, int size, tImageInfo* info, const Color3B* fontColor, int fontAlpha, bool enableWrap, int overflow, const FontStroke &stroke) { bool ret = false; - + CCASSERT(text, "Invalid text"); CCASSERT(info, "Invalid info"); - - do - { - NSString* string = [NSString stringWithUTF8String:text]; + + do { + NSString * string = [NSString stringWithUTF8String:text]; CC_BREAK_IF(!string); - + id font = _createSystemFont(fontName, size); CC_BREAK_IF(!font); - + // color NSColor* foregroundColor; - if (fontColor) - { - foregroundColor = [NSColor colorWithDeviceRed:fontColor->r / 255.0 - green:fontColor->g / 255.0 - blue:fontColor->b / 255.0 - alpha:fontAlpha / 255.0]; - } - else - { + if (fontColor) { + foregroundColor = [NSColor colorWithDeviceRed:fontColor->r/255.0 + green:fontColor->g/255.0 + blue:fontColor->b/255.0 + alpha:fontAlpha/255.0]; + } else { foregroundColor = [NSColor whiteColor]; } - + // alignment - NSTextAlignment textAlign = FontUtils::_calculateTextAlignment(align); - NSMutableParagraphStyle* paragraphStyle = FontUtils::_calculateParagraphStyle(enableWrap, overflow); + NSTextAlignment textAlign = FontUtils::_calculateTextAlignment(align); + NSMutableParagraphStyle *paragraphStyle = FontUtils::_calculateParagraphStyle(enableWrap, overflow); [paragraphStyle setAlignment:textAlign]; - + // attribute - NSDictionary* tokenAttributesDict = [NSDictionary - dictionaryWithObjectsAndKeys:foregroundColor, NSForegroundColorAttributeName, font, NSFontAttributeName, - paragraphStyle, NSParagraphStyleAttributeName, nil]; - NSAttributedString* stringWithAttributes = - [[[NSAttributedString alloc] initWithString:string attributes:tokenAttributesDict] autorelease]; - + NSDictionary* tokenAttributesDict = [NSDictionary dictionaryWithObjectsAndKeys: + foregroundColor,NSForegroundColorAttributeName, + font, NSFontAttributeName, + paragraphStyle, NSParagraphStyleAttributeName, nil]; + NSAttributedString *stringWithAttributes =[[[NSAttributedString alloc] initWithString:string + attributes:tokenAttributesDict] autorelease]; + CGSize dimensions = CGSizeMake(info->width, info->height); NSSize realDimensions; - + if (overflow == 2) realDimensions = _calculateRealSizeForString(&stringWithAttributes, font, dimensions, enableWrap); else - realDimensions = _calculateStringSize(stringWithAttributes, font, &dimensions, enableWrap, overflow); + realDimensions = _calculateStringSize(stringWithAttributes, font, &dimensions, enableWrap, overflow); // Mac crashes if the width or height is 0 CC_BREAK_IF(realDimensions.width <= 0 || realDimensions.height <= 0); - - if (dimensions.width <= 0.f) + + if(dimensions.width <= 0.f) dimensions.width = realDimensions.width; if (dimensions.height <= 0.f) - dimensions.height = realDimensions.height; - - // Alignment + dimensions.height = realDimensions.height; + + //Alignment CGFloat xPadding = FontUtils::_calculateTextDrawStartWidth(align, realDimensions, dimensions); CGFloat yPadding = _calculateTextDrawStartHeight(align, realDimensions, dimensions); NSInteger POTWide = dimensions.width; NSInteger POTHigh = dimensions.height; - NSRect textRect = - NSMakeRect(xPadding, POTHigh - dimensions.height + yPadding, realDimensions.width, realDimensions.height); + NSRect textRect = NSMakeRect(xPadding, POTHigh - dimensions.height + yPadding, + realDimensions.width, realDimensions.height); - NSBitmapImageRep* offscreenRep = [[[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL - pixelsWide:POTWide - pixelsHigh:POTHigh - bitsPerSample:8 - samplesPerPixel:4 - hasAlpha:YES - isPlanar:NO - colorSpaceName:NSDeviceRGBColorSpace - bitmapFormat:0 - bytesPerRow:4 * POTWide - bitsPerPixel:32] autorelease]; + NSBitmapImageRep* offscreenRep = [[[NSBitmapImageRep alloc] + initWithBitmapDataPlanes:NULL + pixelsWide:POTWide + pixelsHigh:POTHigh + bitsPerSample:8 + samplesPerPixel:4 + hasAlpha:YES + isPlanar:NO + colorSpaceName:NSDeviceRGBColorSpace + bitmapFormat: 0 + bytesPerRow:4 * POTWide + bitsPerPixel:32] autorelease]; NSGraphicsContext* g = [NSGraphicsContext graphicsContextWithBitmapImageRep:offscreenRep]; [NSGraphicsContext saveGraphicsState]; [NSGraphicsContext setCurrentContext:g]; - - if (stroke._strokeSize > 0) - { - NSColor* strokeColor = [NSColor colorWithDeviceRed:stroke._strokeColor.r / 255.0 - green:stroke._strokeColor.g / 255.0 - blue:stroke._strokeColor.b / 255.0 - alpha:stroke._strokeAlpha / 255.0]; - NSNumber* strokeSize = [NSNumber numberWithFloat:stroke._strokeSize / size * 100.0]; - NSDictionary* tokenAttributesDict2 = [NSDictionary - dictionaryWithObjectsAndKeys:foregroundColor, NSForegroundColorAttributeName, font, NSFontAttributeName, - paragraphStyle, NSParagraphStyleAttributeName, strokeSize, - NSStrokeWidthAttributeName, strokeColor, NSStrokeColorAttributeName, nil]; - NSAttributedString* strokeString = - [[[NSAttributedString alloc] initWithString:string attributes:tokenAttributesDict2] autorelease]; + + if (stroke._strokeSize > 0) { + NSColor *strokeColor = [NSColor colorWithDeviceRed:stroke._strokeColor.r/255.0 + green:stroke._strokeColor.g/255.0 + blue:stroke._strokeColor.b/255.0 + alpha:stroke._strokeAlpha/255.0]; + NSNumber *strokeSize = [NSNumber numberWithFloat:stroke._strokeSize / size * 100.0]; + NSDictionary *tokenAttributesDict2 = [NSDictionary dictionaryWithObjectsAndKeys: + foregroundColor,NSForegroundColorAttributeName, + font, NSFontAttributeName, + paragraphStyle, NSParagraphStyleAttributeName, + strokeSize, NSStrokeWidthAttributeName, + strokeColor, NSStrokeColorAttributeName, + nil]; + NSAttributedString *strokeString = [[[NSAttributedString alloc] initWithString:string + attributes:tokenAttributesDict2] autorelease]; [strokeString drawInRect:textRect]; } - + [stringWithAttributes drawInRect:textRect]; [NSGraphicsContext restoreGraphicsState]; - auto data = (unsigned char*)[offscreenRep bitmapData]; // Use the same buffer to improve the performance. + auto data = (unsigned char*) [offscreenRep bitmapData]; //Use the same buffer to improve the performance. NSUInteger textureSize = POTWide * POTHigh * 4; - auto dataNew = (unsigned char*)malloc(sizeof(unsigned char) * textureSize); - if (dataNew) - { + auto dataNew = (unsigned char*)malloc(sizeof(unsigned char) * textureSize); + if (dataNew) { memcpy(dataNew, data, textureSize); // output params - info->width = static_cast(POTWide); - info->height = static_cast(POTHigh); - info->data = dataNew; - info->hasAlpha = true; + info->width = static_cast(POTWide); + info->height = static_cast(POTHigh); + info->data = dataNew; + info->hasAlpha = true; info->isPremultipliedAlpha = true; - ret = true; + ret = true; } } while (0); return ret; } -Data Device::getTextureDataForText(const char* text, - const FontDefinition& textDefinition, - TextAlign align, - int& width, - int& height, - bool& hasPremultipliedAlpha) +Data Device::getTextureDataForText(const char * text, const FontDefinition& textDefinition, TextAlign align, int &width, int &height, bool& hasPremultipliedAlpha) { Data ret; - do - { + do { tImageInfo info = {0}; - info.width = textDefinition._dimensions.width; - info.height = textDefinition._dimensions.height; + info.width = textDefinition._dimensions.width; + info.height = textDefinition._dimensions.height; - if (!_initWithString(text, align, textDefinition._fontName.c_str(), textDefinition._fontSize, &info, - &textDefinition._fontFillColor, textDefinition._fontAlpha, textDefinition._enableWrap, - textDefinition._overflow, textDefinition._stroke)) + if (! _initWithString(text, align, textDefinition._fontName.c_str(), textDefinition._fontSize, &info, &textDefinition._fontFillColor, textDefinition._fontAlpha, textDefinition._enableWrap, textDefinition._overflow, textDefinition._stroke)) { break; } height = (short)info.height; - width = (short)info.width; - ret.fastSet(info.data, width * height * 4); + width = (short)info.width; + ret.fastSet(info.data,width * height * 4); hasPremultipliedAlpha = true; } while (0); - + return ret; } -void Device::setKeepScreenOn(bool value) {} +void Device::setKeepScreenOn(bool value) +{ +} -void Device::vibrate(float duration) {} +void Device::vibrate(float duration) +{ +} NS_CC_END diff --git a/cocos/platform/mac/CCGLViewImpl-mac.h b/cocos/platform/mac/CCGLViewImpl-mac.h index 01317ae283..7c2d480dfa 100644 --- a/cocos/platform/mac/CCGLViewImpl-mac.h +++ b/cocos/platform/mac/CCGLViewImpl-mac.h @@ -58,14 +58,14 @@ class CC_DLL GLViewImpl : public GLView friend class GLFWEventHandler; public: - static GLViewImpl* create(std::string_view viewName); - static GLViewImpl* create(std::string_view viewName, bool resizable); - static GLViewImpl* createWithRect(std::string_view viewName, + static GLViewImpl* create(const std::string& viewName); + static GLViewImpl* create(const std::string& viewName, bool resizable); + static GLViewImpl* createWithRect(const std::string& viewName, Rect size, float frameZoomFactor = 1.0f, bool resizable = false); - static GLViewImpl* createWithFullScreen(std::string_view viewName); - static GLViewImpl* createWithFullScreen(std::string_view viewName, + static GLViewImpl* createWithFullScreen(const std::string& viewName); + static GLViewImpl* createWithFullScreen(const std::string& viewName, const GLFWvidmode& videoMode, GLFWmonitor* monitor); @@ -119,7 +119,7 @@ public: virtual void setIMEKeyboardState(bool bOpen) override; #if CC_ICON_SET_SUPPORT - virtual void setIcon(std::string_view filename) const override; + virtual void setIcon(const std::string& filename) const override; virtual void setIcon(const std::vector& filelist) const override; virtual void setDefaultIcon() const override; #endif /* CC_ICON_SET_SUPPORT */ @@ -149,9 +149,9 @@ protected: GLViewImpl(bool initglfw = true); virtual ~GLViewImpl(); - bool initWithRect(std::string_view viewName, Rect rect, float frameZoomFactor, bool resizable); - bool initWithFullScreen(std::string_view viewName); - bool initWithFullscreen(std::string_view viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor); + bool initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable); + bool initWithFullScreen(const std::string& viewName); + bool initWithFullscreen(const std::string& viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor); /* update frame layout when enter/exit full screen mode */ void updateWindowSize(); diff --git a/cocos/platform/mac/CCGLViewImpl-mac.mm b/cocos/platform/mac/CCGLViewImpl-mac.mm index dfd66ec28d..8d47ababc9 100644 --- a/cocos/platform/mac/CCGLViewImpl-mac.mm +++ b/cocos/platform/mac/CCGLViewImpl-mac.mm @@ -40,7 +40,7 @@ THE SOFTWARE. #include "base/ccUTF8.h" #include "2d/CCCamera.h" #if CC_ICON_SET_SUPPORT -# include "platform/CCImage.h" +#include "platform/CCImage.h" #endif /* CC_ICON_SET_SUPPORT */ #include "renderer/backend/metal/DeviceMTL.h" #include "renderer/CCRenderer.h" @@ -100,13 +100,16 @@ public: // _view->onGLFWframebufferSize(window, w, h); // } - static void onGLFWWindowSizeCallback(GLFWwindow* window, int width, int height) + static void onGLFWWindowSizeCallback(GLFWwindow *window, int width, int height) { if (_view) _view->onGLFWWindowSizeCallback(window, width, height); } - static void setGLViewImpl(GLViewImpl* view) { _view = view; } + static void setGLViewImpl(GLViewImpl* view) + { + _view = view; + } static void onGLFWWindowIconifyCallback(GLFWwindow* window, int iconified) { @@ -129,8 +132,8 @@ private: }; GLViewImpl* GLFWEventHandler::_view = nullptr; -const std::string GLViewImpl::EVENT_WINDOW_RESIZED = "glview_window_resized"; -const std::string GLViewImpl::EVENT_WINDOW_FOCUSED = "glview_window_focused"; +const std::string GLViewImpl::EVENT_WINDOW_RESIZED = "glview_window_resized"; +const std::string GLViewImpl::EVENT_WINDOW_FOCUSED = "glview_window_focused"; const std::string GLViewImpl::EVENT_WINDOW_UNFOCUSED = "glview_window_unfocused"; //////////////////////////////////////////////////// @@ -145,147 +148,149 @@ static std::unordered_map g_keyCodeMap; static keyCodeItem g_keyCodeStructArray[] = { /* The unknown key */ - {GLFW_KEY_UNKNOWN, EventKeyboard::KeyCode::KEY_NONE}, + { GLFW_KEY_UNKNOWN , EventKeyboard::KeyCode::KEY_NONE }, /* Printable keys */ - {GLFW_KEY_SPACE, EventKeyboard::KeyCode::KEY_SPACE}, - {GLFW_KEY_APOSTROPHE, EventKeyboard::KeyCode::KEY_APOSTROPHE}, - {GLFW_KEY_COMMA, EventKeyboard::KeyCode::KEY_COMMA}, - {GLFW_KEY_MINUS, EventKeyboard::KeyCode::KEY_MINUS}, - {GLFW_KEY_PERIOD, EventKeyboard::KeyCode::KEY_PERIOD}, - {GLFW_KEY_SLASH, EventKeyboard::KeyCode::KEY_SLASH}, - {GLFW_KEY_0, EventKeyboard::KeyCode::KEY_0}, - {GLFW_KEY_1, EventKeyboard::KeyCode::KEY_1}, - {GLFW_KEY_2, EventKeyboard::KeyCode::KEY_2}, - {GLFW_KEY_3, EventKeyboard::KeyCode::KEY_3}, - {GLFW_KEY_4, EventKeyboard::KeyCode::KEY_4}, - {GLFW_KEY_5, EventKeyboard::KeyCode::KEY_5}, - {GLFW_KEY_6, EventKeyboard::KeyCode::KEY_6}, - {GLFW_KEY_7, EventKeyboard::KeyCode::KEY_7}, - {GLFW_KEY_8, EventKeyboard::KeyCode::KEY_8}, - {GLFW_KEY_9, EventKeyboard::KeyCode::KEY_9}, - {GLFW_KEY_SEMICOLON, EventKeyboard::KeyCode::KEY_SEMICOLON}, - {GLFW_KEY_EQUAL, EventKeyboard::KeyCode::KEY_EQUAL}, - {GLFW_KEY_A, EventKeyboard::KeyCode::KEY_A}, - {GLFW_KEY_B, EventKeyboard::KeyCode::KEY_B}, - {GLFW_KEY_C, EventKeyboard::KeyCode::KEY_C}, - {GLFW_KEY_D, EventKeyboard::KeyCode::KEY_D}, - {GLFW_KEY_E, EventKeyboard::KeyCode::KEY_E}, - {GLFW_KEY_F, EventKeyboard::KeyCode::KEY_F}, - {GLFW_KEY_G, EventKeyboard::KeyCode::KEY_G}, - {GLFW_KEY_H, EventKeyboard::KeyCode::KEY_H}, - {GLFW_KEY_I, EventKeyboard::KeyCode::KEY_I}, - {GLFW_KEY_J, EventKeyboard::KeyCode::KEY_J}, - {GLFW_KEY_K, EventKeyboard::KeyCode::KEY_K}, - {GLFW_KEY_L, EventKeyboard::KeyCode::KEY_L}, - {GLFW_KEY_M, EventKeyboard::KeyCode::KEY_M}, - {GLFW_KEY_N, EventKeyboard::KeyCode::KEY_N}, - {GLFW_KEY_O, EventKeyboard::KeyCode::KEY_O}, - {GLFW_KEY_P, EventKeyboard::KeyCode::KEY_P}, - {GLFW_KEY_Q, EventKeyboard::KeyCode::KEY_Q}, - {GLFW_KEY_R, EventKeyboard::KeyCode::KEY_R}, - {GLFW_KEY_S, EventKeyboard::KeyCode::KEY_S}, - {GLFW_KEY_T, EventKeyboard::KeyCode::KEY_T}, - {GLFW_KEY_U, EventKeyboard::KeyCode::KEY_U}, - {GLFW_KEY_V, EventKeyboard::KeyCode::KEY_V}, - {GLFW_KEY_W, EventKeyboard::KeyCode::KEY_W}, - {GLFW_KEY_X, EventKeyboard::KeyCode::KEY_X}, - {GLFW_KEY_Y, EventKeyboard::KeyCode::KEY_Y}, - {GLFW_KEY_Z, EventKeyboard::KeyCode::KEY_Z}, - {GLFW_KEY_LEFT_BRACKET, EventKeyboard::KeyCode::KEY_LEFT_BRACKET}, - {GLFW_KEY_BACKSLASH, EventKeyboard::KeyCode::KEY_BACK_SLASH}, - {GLFW_KEY_RIGHT_BRACKET, EventKeyboard::KeyCode::KEY_RIGHT_BRACKET}, - {GLFW_KEY_GRAVE_ACCENT, EventKeyboard::KeyCode::KEY_GRAVE}, - {GLFW_KEY_WORLD_1, EventKeyboard::KeyCode::KEY_GRAVE}, - {GLFW_KEY_WORLD_2, EventKeyboard::KeyCode::KEY_NONE}, + { GLFW_KEY_SPACE , EventKeyboard::KeyCode::KEY_SPACE }, + { GLFW_KEY_APOSTROPHE , EventKeyboard::KeyCode::KEY_APOSTROPHE }, + { GLFW_KEY_COMMA , EventKeyboard::KeyCode::KEY_COMMA }, + { GLFW_KEY_MINUS , EventKeyboard::KeyCode::KEY_MINUS }, + { GLFW_KEY_PERIOD , EventKeyboard::KeyCode::KEY_PERIOD }, + { GLFW_KEY_SLASH , EventKeyboard::KeyCode::KEY_SLASH }, + { GLFW_KEY_0 , EventKeyboard::KeyCode::KEY_0 }, + { GLFW_KEY_1 , EventKeyboard::KeyCode::KEY_1 }, + { GLFW_KEY_2 , EventKeyboard::KeyCode::KEY_2 }, + { GLFW_KEY_3 , EventKeyboard::KeyCode::KEY_3 }, + { GLFW_KEY_4 , EventKeyboard::KeyCode::KEY_4 }, + { GLFW_KEY_5 , EventKeyboard::KeyCode::KEY_5 }, + { GLFW_KEY_6 , EventKeyboard::KeyCode::KEY_6 }, + { GLFW_KEY_7 , EventKeyboard::KeyCode::KEY_7 }, + { GLFW_KEY_8 , EventKeyboard::KeyCode::KEY_8 }, + { GLFW_KEY_9 , EventKeyboard::KeyCode::KEY_9 }, + { GLFW_KEY_SEMICOLON , EventKeyboard::KeyCode::KEY_SEMICOLON }, + { GLFW_KEY_EQUAL , EventKeyboard::KeyCode::KEY_EQUAL }, + { GLFW_KEY_A , EventKeyboard::KeyCode::KEY_A }, + { GLFW_KEY_B , EventKeyboard::KeyCode::KEY_B }, + { GLFW_KEY_C , EventKeyboard::KeyCode::KEY_C }, + { GLFW_KEY_D , EventKeyboard::KeyCode::KEY_D }, + { GLFW_KEY_E , EventKeyboard::KeyCode::KEY_E }, + { GLFW_KEY_F , EventKeyboard::KeyCode::KEY_F }, + { GLFW_KEY_G , EventKeyboard::KeyCode::KEY_G }, + { GLFW_KEY_H , EventKeyboard::KeyCode::KEY_H }, + { GLFW_KEY_I , EventKeyboard::KeyCode::KEY_I }, + { GLFW_KEY_J , EventKeyboard::KeyCode::KEY_J }, + { GLFW_KEY_K , EventKeyboard::KeyCode::KEY_K }, + { GLFW_KEY_L , EventKeyboard::KeyCode::KEY_L }, + { GLFW_KEY_M , EventKeyboard::KeyCode::KEY_M }, + { GLFW_KEY_N , EventKeyboard::KeyCode::KEY_N }, + { GLFW_KEY_O , EventKeyboard::KeyCode::KEY_O }, + { GLFW_KEY_P , EventKeyboard::KeyCode::KEY_P }, + { GLFW_KEY_Q , EventKeyboard::KeyCode::KEY_Q }, + { GLFW_KEY_R , EventKeyboard::KeyCode::KEY_R }, + { GLFW_KEY_S , EventKeyboard::KeyCode::KEY_S }, + { GLFW_KEY_T , EventKeyboard::KeyCode::KEY_T }, + { GLFW_KEY_U , EventKeyboard::KeyCode::KEY_U }, + { GLFW_KEY_V , EventKeyboard::KeyCode::KEY_V }, + { GLFW_KEY_W , EventKeyboard::KeyCode::KEY_W }, + { GLFW_KEY_X , EventKeyboard::KeyCode::KEY_X }, + { GLFW_KEY_Y , EventKeyboard::KeyCode::KEY_Y }, + { GLFW_KEY_Z , EventKeyboard::KeyCode::KEY_Z }, + { GLFW_KEY_LEFT_BRACKET , EventKeyboard::KeyCode::KEY_LEFT_BRACKET }, + { GLFW_KEY_BACKSLASH , EventKeyboard::KeyCode::KEY_BACK_SLASH }, + { GLFW_KEY_RIGHT_BRACKET , EventKeyboard::KeyCode::KEY_RIGHT_BRACKET }, + { GLFW_KEY_GRAVE_ACCENT , EventKeyboard::KeyCode::KEY_GRAVE }, + { GLFW_KEY_WORLD_1 , EventKeyboard::KeyCode::KEY_GRAVE }, + { GLFW_KEY_WORLD_2 , EventKeyboard::KeyCode::KEY_NONE }, /* Function keys */ - {GLFW_KEY_ESCAPE, EventKeyboard::KeyCode::KEY_ESCAPE}, - {GLFW_KEY_ENTER, EventKeyboard::KeyCode::KEY_ENTER}, - {GLFW_KEY_TAB, EventKeyboard::KeyCode::KEY_TAB}, - {GLFW_KEY_BACKSPACE, EventKeyboard::KeyCode::KEY_BACKSPACE}, - {GLFW_KEY_INSERT, EventKeyboard::KeyCode::KEY_INSERT}, - {GLFW_KEY_DELETE, EventKeyboard::KeyCode::KEY_DELETE}, - {GLFW_KEY_RIGHT, EventKeyboard::KeyCode::KEY_RIGHT_ARROW}, - {GLFW_KEY_LEFT, EventKeyboard::KeyCode::KEY_LEFT_ARROW}, - {GLFW_KEY_DOWN, EventKeyboard::KeyCode::KEY_DOWN_ARROW}, - {GLFW_KEY_UP, EventKeyboard::KeyCode::KEY_UP_ARROW}, - {GLFW_KEY_PAGE_UP, EventKeyboard::KeyCode::KEY_PG_UP}, - {GLFW_KEY_PAGE_DOWN, EventKeyboard::KeyCode::KEY_PG_DOWN}, - {GLFW_KEY_HOME, EventKeyboard::KeyCode::KEY_HOME}, - {GLFW_KEY_END, EventKeyboard::KeyCode::KEY_END}, - {GLFW_KEY_CAPS_LOCK, EventKeyboard::KeyCode::KEY_CAPS_LOCK}, - {GLFW_KEY_SCROLL_LOCK, EventKeyboard::KeyCode::KEY_SCROLL_LOCK}, - {GLFW_KEY_NUM_LOCK, EventKeyboard::KeyCode::KEY_NUM_LOCK}, - {GLFW_KEY_PRINT_SCREEN, EventKeyboard::KeyCode::KEY_PRINT}, - {GLFW_KEY_PAUSE, EventKeyboard::KeyCode::KEY_PAUSE}, - {GLFW_KEY_F1, EventKeyboard::KeyCode::KEY_F1}, - {GLFW_KEY_F2, EventKeyboard::KeyCode::KEY_F2}, - {GLFW_KEY_F3, EventKeyboard::KeyCode::KEY_F3}, - {GLFW_KEY_F4, EventKeyboard::KeyCode::KEY_F4}, - {GLFW_KEY_F5, EventKeyboard::KeyCode::KEY_F5}, - {GLFW_KEY_F6, EventKeyboard::KeyCode::KEY_F6}, - {GLFW_KEY_F7, EventKeyboard::KeyCode::KEY_F7}, - {GLFW_KEY_F8, EventKeyboard::KeyCode::KEY_F8}, - {GLFW_KEY_F9, EventKeyboard::KeyCode::KEY_F9}, - {GLFW_KEY_F10, EventKeyboard::KeyCode::KEY_F10}, - {GLFW_KEY_F11, EventKeyboard::KeyCode::KEY_F11}, - {GLFW_KEY_F12, EventKeyboard::KeyCode::KEY_F12}, - {GLFW_KEY_F13, EventKeyboard::KeyCode::KEY_NONE}, - {GLFW_KEY_F14, EventKeyboard::KeyCode::KEY_NONE}, - {GLFW_KEY_F15, EventKeyboard::KeyCode::KEY_NONE}, - {GLFW_KEY_F16, EventKeyboard::KeyCode::KEY_NONE}, - {GLFW_KEY_F17, EventKeyboard::KeyCode::KEY_NONE}, - {GLFW_KEY_F18, EventKeyboard::KeyCode::KEY_NONE}, - {GLFW_KEY_F19, EventKeyboard::KeyCode::KEY_NONE}, - {GLFW_KEY_F20, EventKeyboard::KeyCode::KEY_NONE}, - {GLFW_KEY_F21, EventKeyboard::KeyCode::KEY_NONE}, - {GLFW_KEY_F22, EventKeyboard::KeyCode::KEY_NONE}, - {GLFW_KEY_F23, EventKeyboard::KeyCode::KEY_NONE}, - {GLFW_KEY_F24, EventKeyboard::KeyCode::KEY_NONE}, - {GLFW_KEY_F25, EventKeyboard::KeyCode::KEY_NONE}, - {GLFW_KEY_KP_0, EventKeyboard::KeyCode::KEY_0}, - {GLFW_KEY_KP_1, EventKeyboard::KeyCode::KEY_1}, - {GLFW_KEY_KP_2, EventKeyboard::KeyCode::KEY_2}, - {GLFW_KEY_KP_3, EventKeyboard::KeyCode::KEY_3}, - {GLFW_KEY_KP_4, EventKeyboard::KeyCode::KEY_4}, - {GLFW_KEY_KP_5, EventKeyboard::KeyCode::KEY_5}, - {GLFW_KEY_KP_6, EventKeyboard::KeyCode::KEY_6}, - {GLFW_KEY_KP_7, EventKeyboard::KeyCode::KEY_7}, - {GLFW_KEY_KP_8, EventKeyboard::KeyCode::KEY_8}, - {GLFW_KEY_KP_9, EventKeyboard::KeyCode::KEY_9}, - {GLFW_KEY_KP_DECIMAL, EventKeyboard::KeyCode::KEY_PERIOD}, - {GLFW_KEY_KP_DIVIDE, EventKeyboard::KeyCode::KEY_KP_DIVIDE}, - {GLFW_KEY_KP_MULTIPLY, EventKeyboard::KeyCode::KEY_KP_MULTIPLY}, - {GLFW_KEY_KP_SUBTRACT, EventKeyboard::KeyCode::KEY_KP_MINUS}, - {GLFW_KEY_KP_ADD, EventKeyboard::KeyCode::KEY_KP_PLUS}, - {GLFW_KEY_KP_ENTER, EventKeyboard::KeyCode::KEY_KP_ENTER}, - {GLFW_KEY_KP_EQUAL, EventKeyboard::KeyCode::KEY_EQUAL}, - {GLFW_KEY_LEFT_SHIFT, EventKeyboard::KeyCode::KEY_LEFT_SHIFT}, - {GLFW_KEY_LEFT_CONTROL, EventKeyboard::KeyCode::KEY_LEFT_CTRL}, - {GLFW_KEY_LEFT_ALT, EventKeyboard::KeyCode::KEY_LEFT_ALT}, - {GLFW_KEY_LEFT_SUPER, EventKeyboard::KeyCode::KEY_HYPER}, - {GLFW_KEY_RIGHT_SHIFT, EventKeyboard::KeyCode::KEY_RIGHT_SHIFT}, - {GLFW_KEY_RIGHT_CONTROL, EventKeyboard::KeyCode::KEY_RIGHT_CTRL}, - {GLFW_KEY_RIGHT_ALT, EventKeyboard::KeyCode::KEY_RIGHT_ALT}, - {GLFW_KEY_RIGHT_SUPER, EventKeyboard::KeyCode::KEY_HYPER}, - {GLFW_KEY_MENU, EventKeyboard::KeyCode::KEY_MENU}, - {GLFW_KEY_LAST, EventKeyboard::KeyCode::KEY_NONE}}; + { GLFW_KEY_ESCAPE , EventKeyboard::KeyCode::KEY_ESCAPE }, + { GLFW_KEY_ENTER , EventKeyboard::KeyCode::KEY_ENTER }, + { GLFW_KEY_TAB , EventKeyboard::KeyCode::KEY_TAB }, + { GLFW_KEY_BACKSPACE , EventKeyboard::KeyCode::KEY_BACKSPACE }, + { GLFW_KEY_INSERT , EventKeyboard::KeyCode::KEY_INSERT }, + { GLFW_KEY_DELETE , EventKeyboard::KeyCode::KEY_DELETE }, + { GLFW_KEY_RIGHT , EventKeyboard::KeyCode::KEY_RIGHT_ARROW }, + { GLFW_KEY_LEFT , EventKeyboard::KeyCode::KEY_LEFT_ARROW }, + { GLFW_KEY_DOWN , EventKeyboard::KeyCode::KEY_DOWN_ARROW }, + { GLFW_KEY_UP , EventKeyboard::KeyCode::KEY_UP_ARROW }, + { GLFW_KEY_PAGE_UP , EventKeyboard::KeyCode::KEY_PG_UP }, + { GLFW_KEY_PAGE_DOWN , EventKeyboard::KeyCode::KEY_PG_DOWN }, + { GLFW_KEY_HOME , EventKeyboard::KeyCode::KEY_HOME }, + { GLFW_KEY_END , EventKeyboard::KeyCode::KEY_END }, + { GLFW_KEY_CAPS_LOCK , EventKeyboard::KeyCode::KEY_CAPS_LOCK }, + { GLFW_KEY_SCROLL_LOCK , EventKeyboard::KeyCode::KEY_SCROLL_LOCK }, + { GLFW_KEY_NUM_LOCK , EventKeyboard::KeyCode::KEY_NUM_LOCK }, + { GLFW_KEY_PRINT_SCREEN , EventKeyboard::KeyCode::KEY_PRINT }, + { GLFW_KEY_PAUSE , EventKeyboard::KeyCode::KEY_PAUSE }, + { GLFW_KEY_F1 , EventKeyboard::KeyCode::KEY_F1 }, + { GLFW_KEY_F2 , EventKeyboard::KeyCode::KEY_F2 }, + { GLFW_KEY_F3 , EventKeyboard::KeyCode::KEY_F3 }, + { GLFW_KEY_F4 , EventKeyboard::KeyCode::KEY_F4 }, + { GLFW_KEY_F5 , EventKeyboard::KeyCode::KEY_F5 }, + { GLFW_KEY_F6 , EventKeyboard::KeyCode::KEY_F6 }, + { GLFW_KEY_F7 , EventKeyboard::KeyCode::KEY_F7 }, + { GLFW_KEY_F8 , EventKeyboard::KeyCode::KEY_F8 }, + { GLFW_KEY_F9 , EventKeyboard::KeyCode::KEY_F9 }, + { GLFW_KEY_F10 , EventKeyboard::KeyCode::KEY_F10 }, + { GLFW_KEY_F11 , EventKeyboard::KeyCode::KEY_F11 }, + { GLFW_KEY_F12 , EventKeyboard::KeyCode::KEY_F12 }, + { GLFW_KEY_F13 , EventKeyboard::KeyCode::KEY_NONE }, + { GLFW_KEY_F14 , EventKeyboard::KeyCode::KEY_NONE }, + { GLFW_KEY_F15 , EventKeyboard::KeyCode::KEY_NONE }, + { GLFW_KEY_F16 , EventKeyboard::KeyCode::KEY_NONE }, + { GLFW_KEY_F17 , EventKeyboard::KeyCode::KEY_NONE }, + { GLFW_KEY_F18 , EventKeyboard::KeyCode::KEY_NONE }, + { GLFW_KEY_F19 , EventKeyboard::KeyCode::KEY_NONE }, + { GLFW_KEY_F20 , EventKeyboard::KeyCode::KEY_NONE }, + { GLFW_KEY_F21 , EventKeyboard::KeyCode::KEY_NONE }, + { GLFW_KEY_F22 , EventKeyboard::KeyCode::KEY_NONE }, + { GLFW_KEY_F23 , EventKeyboard::KeyCode::KEY_NONE }, + { GLFW_KEY_F24 , EventKeyboard::KeyCode::KEY_NONE }, + { GLFW_KEY_F25 , EventKeyboard::KeyCode::KEY_NONE }, + { GLFW_KEY_KP_0 , EventKeyboard::KeyCode::KEY_0 }, + { GLFW_KEY_KP_1 , EventKeyboard::KeyCode::KEY_1 }, + { GLFW_KEY_KP_2 , EventKeyboard::KeyCode::KEY_2 }, + { GLFW_KEY_KP_3 , EventKeyboard::KeyCode::KEY_3 }, + { GLFW_KEY_KP_4 , EventKeyboard::KeyCode::KEY_4 }, + { GLFW_KEY_KP_5 , EventKeyboard::KeyCode::KEY_5 }, + { GLFW_KEY_KP_6 , EventKeyboard::KeyCode::KEY_6 }, + { GLFW_KEY_KP_7 , EventKeyboard::KeyCode::KEY_7 }, + { GLFW_KEY_KP_8 , EventKeyboard::KeyCode::KEY_8 }, + { GLFW_KEY_KP_9 , EventKeyboard::KeyCode::KEY_9 }, + { GLFW_KEY_KP_DECIMAL , EventKeyboard::KeyCode::KEY_PERIOD }, + { GLFW_KEY_KP_DIVIDE , EventKeyboard::KeyCode::KEY_KP_DIVIDE }, + { GLFW_KEY_KP_MULTIPLY , EventKeyboard::KeyCode::KEY_KP_MULTIPLY }, + { GLFW_KEY_KP_SUBTRACT , EventKeyboard::KeyCode::KEY_KP_MINUS }, + { GLFW_KEY_KP_ADD , EventKeyboard::KeyCode::KEY_KP_PLUS }, + { GLFW_KEY_KP_ENTER , EventKeyboard::KeyCode::KEY_KP_ENTER }, + { GLFW_KEY_KP_EQUAL , EventKeyboard::KeyCode::KEY_EQUAL }, + { GLFW_KEY_LEFT_SHIFT , EventKeyboard::KeyCode::KEY_LEFT_SHIFT }, + { GLFW_KEY_LEFT_CONTROL , EventKeyboard::KeyCode::KEY_LEFT_CTRL }, + { GLFW_KEY_LEFT_ALT , EventKeyboard::KeyCode::KEY_LEFT_ALT }, + { GLFW_KEY_LEFT_SUPER , EventKeyboard::KeyCode::KEY_HYPER }, + { GLFW_KEY_RIGHT_SHIFT , EventKeyboard::KeyCode::KEY_RIGHT_SHIFT }, + { GLFW_KEY_RIGHT_CONTROL , EventKeyboard::KeyCode::KEY_RIGHT_CTRL }, + { GLFW_KEY_RIGHT_ALT , EventKeyboard::KeyCode::KEY_RIGHT_ALT }, + { GLFW_KEY_RIGHT_SUPER , EventKeyboard::KeyCode::KEY_HYPER }, + { GLFW_KEY_MENU , EventKeyboard::KeyCode::KEY_MENU }, + { GLFW_KEY_LAST , EventKeyboard::KeyCode::KEY_NONE } +}; ////////////////////////////////////////////////////////////////////////// // implement GLViewImpl ////////////////////////////////////////////////////////////////////////// + GLViewImpl::GLViewImpl(bool initglfw) - : _captured(false) - , _isInRetinaMonitor(false) - , _isRetinaEnabled(false) - , _retinaFactor(1) - , _frameZoomFactor(1.0f) - , _mainWindow(nullptr) - , _monitor(nullptr) - , _mouseX(0.0f) - , _mouseY(0.0f) +: _captured(false) +, _isInRetinaMonitor(false) +, _isRetinaEnabled(false) +, _retinaFactor(1) +, _frameZoomFactor(1.0f) +, _mainWindow(nullptr) +, _monitor(nullptr) +, _mouseX(0.0f) +, _mouseY(0.0f) { _viewName = "cocos2dx"; g_keyCodeMap.clear(); @@ -309,16 +314,15 @@ GLViewImpl::~GLViewImpl() glfwTerminate(); } -GLViewImpl* GLViewImpl::create(std::string_view viewName) +GLViewImpl* GLViewImpl::create(const std::string& viewName) { return GLViewImpl::create(viewName, false); } -GLViewImpl* GLViewImpl::create(std::string_view viewName, bool resizable) +GLViewImpl* GLViewImpl::create(const std::string& viewName, bool resizable) { auto ret = new GLViewImpl; - if (ret->initWithRect(viewName, Rect(0, 0, 960, 640), 1.0f, resizable)) - { + if(ret->initWithRect(viewName, Rect(0, 0, 960, 640), 1.0f, resizable)) { ret->autorelease(); return ret; } @@ -326,11 +330,10 @@ GLViewImpl* GLViewImpl::create(std::string_view viewName, bool resizable) return nullptr; } -GLViewImpl* GLViewImpl::createWithRect(std::string_view viewName, Rect rect, float frameZoomFactor, bool resizable) +GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable) { auto ret = new GLViewImpl; - if (ret->initWithRect(viewName, rect, frameZoomFactor, resizable)) - { + if(ret->initWithRect(viewName, rect, frameZoomFactor, resizable)) { ret->autorelease(); return ret; } @@ -338,11 +341,10 @@ GLViewImpl* GLViewImpl::createWithRect(std::string_view viewName, Rect rect, flo return nullptr; } -GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName) +GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName) { auto ret = new GLViewImpl(); - if (ret->initWithFullScreen(viewName)) - { + if(ret->initWithFullScreen(viewName)) { ret->autorelease(); return ret; } @@ -350,13 +352,10 @@ GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName) return nullptr; } -GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName, - const GLFWvidmode& videoMode, - GLFWmonitor* monitor) +GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName, const GLFWvidmode &videoMode, GLFWmonitor *monitor) { auto ret = new GLViewImpl(); - if (ret->initWithFullscreen(viewName, videoMode, monitor)) - { + if(ret->initWithFullscreen(viewName, videoMode, monitor)) { ret->autorelease(); return ret; } @@ -364,28 +363,28 @@ GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName, return nullptr; } -bool GLViewImpl::initWithRect(std::string_view viewName, Rect rect, float frameZoomFactor, bool resizable) +bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable) { setViewName(viewName); _frameZoomFactor = frameZoomFactor; - glfwWindowHint(GLFW_RESIZABLE, resizable ? GL_TRUE : GL_FALSE); - glfwWindowHint(GLFW_RED_BITS, _glContextAttrs.redBits); - glfwWindowHint(GLFW_GREEN_BITS, _glContextAttrs.greenBits); - glfwWindowHint(GLFW_BLUE_BITS, _glContextAttrs.blueBits); - glfwWindowHint(GLFW_ALPHA_BITS, _glContextAttrs.alphaBits); - glfwWindowHint(GLFW_DEPTH_BITS, _glContextAttrs.depthBits); - glfwWindowHint(GLFW_STENCIL_BITS, _glContextAttrs.stencilBits); - + glfwWindowHint(GLFW_RESIZABLE,resizable?GL_TRUE:GL_FALSE); + glfwWindowHint(GLFW_RED_BITS,_glContextAttrs.redBits); + glfwWindowHint(GLFW_GREEN_BITS,_glContextAttrs.greenBits); + glfwWindowHint(GLFW_BLUE_BITS,_glContextAttrs.blueBits); + glfwWindowHint(GLFW_ALPHA_BITS,_glContextAttrs.alphaBits); + glfwWindowHint(GLFW_DEPTH_BITS,_glContextAttrs.depthBits); + glfwWindowHint(GLFW_STENCIL_BITS,_glContextAttrs.stencilBits); + glfwWindowHint(GLFW_SAMPLES, _glContextAttrs.multisamplingCount); - + #if defined(CC_USE_METAL) // Don't create gl context. glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); #endif - int neededWidth = rect.size.width * _frameZoomFactor; + int neededWidth = rect.size.width * _frameZoomFactor; int neededHeight = rect.size.height * _frameZoomFactor; _mainWindow = glfwCreateWindow(neededWidth, neededHeight, _viewName.c_str(), _monitor, nullptr); @@ -402,12 +401,13 @@ bool GLViewImpl::initWithRect(std::string_view viewName, Rect rect, float frameZ ccMessageBox(message.c_str(), "Error launch application"); return false; } - + int fbWidth, fbHeight; glfwGetFramebufferSize(_mainWindow, &fbWidth, &fbHeight); - + + CGSize size; - size.width = static_cast(fbWidth); + size.width = static_cast(fbWidth); size.height = static_cast(fbHeight); #if defined(CC_USE_METAL) @@ -420,7 +420,7 @@ bool GLViewImpl::initWithRect(std::string_view viewName, Rect rect, float frameZ } NSView* contentView = [getCocoaWindow() contentView]; - [contentView setWantsLayer:YES]; + [contentView setWantsLayer: YES]; CAMetalLayer* layer = [CAMetalLayer layer]; [layer setDevice:device]; [layer setPixelFormat:MTLPixelFormatBGRA8Unorm]; @@ -431,15 +431,15 @@ bool GLViewImpl::initWithRect(std::string_view viewName, Rect rect, float frameZ #endif /* - * Note that the created window and context may differ from what you requested, - * as not all parameters and hints are - * [hard constraints](@ref window_hints_hard). This includes the size of the - * window, especially for full screen windows. To retrieve the actual - * attributes of the created window and context, use queries like @ref - * glfwGetWindowAttrib and @ref glfwGetWindowSize. - * - * see declaration glfwCreateWindow - */ + * Note that the created window and context may differ from what you requested, + * as not all parameters and hints are + * [hard constraints](@ref window_hints_hard). This includes the size of the + * window, especially for full screen windows. To retrieve the actual + * attributes of the created window and context, use queries like @ref + * glfwGetWindowAttrib and @ref glfwGetWindowSize. + * + * see declaration glfwCreateWindow + */ int realW = 0, realH = 0; glfwGetWindowSize(_mainWindow, &realW, &realH); if (realW != neededWidth) @@ -470,9 +470,9 @@ bool GLViewImpl::initWithRect(std::string_view viewName, Rect rect, float frameZ return true; } -bool GLViewImpl::initWithFullScreen(std::string_view viewName) +bool GLViewImpl::initWithFullScreen(const std::string& viewName) { - // Create fullscreen window on primary monitor at its current video mode. + //Create fullscreen window on primary monitor at its current video mode. _monitor = glfwGetPrimaryMonitor(); if (nullptr == _monitor) return false; @@ -481,21 +481,19 @@ bool GLViewImpl::initWithFullScreen(std::string_view viewName) return initWithRect(viewName, Rect(0, 0, (float)videoMode->width, (float)videoMode->height), 1.0f, false); } -bool GLViewImpl::initWithFullscreen(std::string_view viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor) +bool GLViewImpl::initWithFullscreen(const std::string &viewname, const GLFWvidmode &videoMode, GLFWmonitor *monitor) { - // Create fullscreen on specified monitor at the specified video mode. + //Create fullscreen on specified monitor at the specified video mode. _monitor = monitor; if (nullptr == _monitor) return false; - - // These are soft constraints. If the video mode is retrieved at runtime, the resulting window and context should - // match these exactly. If invalid attribs are passed (eg. from an outdated cache), window creation will NOT fail - // but the actual window/context may differ. + + //These are soft constraints. If the video mode is retrieved at runtime, the resulting window and context should match these exactly. If invalid attribs are passed (eg. from an outdated cache), window creation will NOT fail but the actual window/context may differ. glfwWindowHint(GLFW_REFRESH_RATE, videoMode.refreshRate); glfwWindowHint(GLFW_RED_BITS, videoMode.redBits); glfwWindowHint(GLFW_BLUE_BITS, videoMode.blueBits); glfwWindowHint(GLFW_GREEN_BITS, videoMode.greenBits); - + return initWithRect(viewname, Rect(0, 0, (float)videoMode.width, (float)videoMode.height), 1.0f, false); } @@ -506,9 +504,9 @@ bool GLViewImpl::isOpenGLReady() void GLViewImpl::end() { - if (_mainWindow) + if(_mainWindow) { - glfwSetWindowShouldClose(_mainWindow, 1); + glfwSetWindowShouldClose(_mainWindow,1); _mainWindow = nullptr; } // Release self. Otherwise, GLViewImpl could not be freed. @@ -518,14 +516,14 @@ void GLViewImpl::end() void GLViewImpl::swapBuffers() { #if defined(CC_USE_GL) - if (_mainWindow) + if(_mainWindow) glfwSwapBuffers(_mainWindow); #endif } bool GLViewImpl::windowShouldClose() { - if (_mainWindow) + if(_mainWindow) return glfwWindowShouldClose(_mainWindow) ? true : false; else return true; @@ -538,54 +536,49 @@ void GLViewImpl::pollEvents() void GLViewImpl::enableRetina(bool enabled) { - _isRetinaEnabled = enabled; - if (_isRetinaEnabled) - { - _retinaFactor = 1; - } - else - { - _retinaFactor = 2; - } - updateFrameSize(); + _isRetinaEnabled = enabled; + if (_isRetinaEnabled) + { + _retinaFactor = 1; + } + else + { + _retinaFactor = 2; + } + updateFrameSize(); } -void GLViewImpl::setIMEKeyboardState(bool /*bOpen*/) {} + +void GLViewImpl::setIMEKeyboardState(bool /*bOpen*/) +{ + +} #if CC_ICON_SET_SUPPORT -void GLViewImpl::setIcon(std::string_view filename) const -{ +void GLViewImpl::setIcon(const std::string& filename) const { std::vector vec = {filename}; this->setIcon(vec); } -void GLViewImpl::setIcon(const std::vector& filelist) const -{ - if (filelist.empty()) - return; +void GLViewImpl::setIcon(const std::vector& filelist) const { + if (filelist.empty()) return; std::vector icons; - for (auto const& filename : filelist) - { + for (auto const& filename: filelist) { Image* icon = new Image(); - if (icon->initWithImageFile(filename)) - { + if (icon->initWithImageFile(filename)) { icons.push_back(icon); - } - else - { + } else { CC_SAFE_DELETE(icon); } } - if (icons.empty()) - return; // No valid images + if (icons.empty()) return; // No valid images size_t iconsCount = icons.size(); - auto images = new GLFWimage[iconsCount]; - for (size_t i = 0; i < iconsCount; i++) - { - auto& image = images[i]; - auto& icon = icons[i]; - image.width = icon->getWidth(); + auto images = new GLFWimage[iconsCount]; + for (size_t i = 0; i < iconsCount; i++) { + auto& image = images[i]; + auto& icon = icons[i]; + image.width = icon->getWidth(); image.height = icon->getHeight(); image.pixels = icon->getData(); }; @@ -594,25 +587,23 @@ void GLViewImpl::setIcon(const std::vector& filelist) const glfwSetWindowIcon(window, iconsCount, images); CC_SAFE_DELETE_ARRAY(images); - for (auto& icon : icons) - { + for (auto& icon: icons) { CC_SAFE_DELETE(icon); } } -void GLViewImpl::setDefaultIcon() const -{ +void GLViewImpl::setDefaultIcon() const { GLFWwindow* window = this->getWindow(); glfwSetWindowIcon(window, 0, nullptr); } #endif /* CC_ICON_SET_SUPPORT */ -void GLViewImpl::setCursorVisible(bool isVisible) +void GLViewImpl::setCursorVisible( bool isVisible ) { - if (_mainWindow == NULL) + if( _mainWindow == NULL ) return; - - if (isVisible) + + if( isVisible ) glfwSetInputMode(_mainWindow, GLFW_CURSOR, GLFW_CURSOR_NORMAL); else glfwSetInputMode(_mainWindow, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); @@ -636,8 +627,7 @@ float GLViewImpl::getFrameZoomFactor() const return _frameZoomFactor; } -bool GLViewImpl::isFullscreen() const -{ +bool GLViewImpl::isFullscreen() const { return (_monitor != nullptr); } @@ -646,11 +636,9 @@ void GLViewImpl::setFullscreen() setFullscreen(-1, -1, -1); } -void GLViewImpl::setFullscreen(int w, int h, int refreshRate) -{ +void GLViewImpl::setFullscreen(int w, int h, int refreshRate) { auto monitor = glfwGetPrimaryMonitor(); - if (nullptr == monitor || monitor == _monitor) - { + if (nullptr == monitor || monitor == _monitor) { return; } this->setFullscreen(monitor, w, h, refreshRate); @@ -661,24 +649,20 @@ void GLViewImpl::setFullscreen(int monitorIndex) setFullscreen(monitorIndex, -1, -1, -1); } -void GLViewImpl::setFullscreen(int monitorIndex, int w, int h, int refreshRate) -{ - int count = 0; +void GLViewImpl::setFullscreen(int monitorIndex, int w, int h, int refreshRate) { + int count = 0; GLFWmonitor** monitors = glfwGetMonitors(&count); - if (monitorIndex < 0 || monitorIndex >= count) - { + if (monitorIndex < 0 || monitorIndex >= count) { return; } GLFWmonitor* monitor = monitors[monitorIndex]; - if (nullptr == monitor || _monitor == monitor) - { + if (nullptr == monitor || _monitor == monitor) { return; } this->setFullscreen(monitor, w, h, refreshRate); } -void GLViewImpl::setFullscreen(GLFWmonitor* monitor, int w, int h, int refreshRate) -{ +void GLViewImpl::setFullscreen(GLFWmonitor *monitor, int w, int h, int refreshRate) { _monitor = monitor; const GLFWvidmode* videoMode = glfwGetVideoMode(_monitor); @@ -694,14 +678,10 @@ void GLViewImpl::setFullscreen(GLFWmonitor* monitor, int w, int h, int refreshRa updateWindowSize(); } -void GLViewImpl::setWindowed(int width, int height) -{ - if (!this->isFullscreen()) - { +void GLViewImpl::setWindowed(int width, int height) { + if (!this->isFullscreen()) { this->setFrameSize((float)width, (float)height); - } - else - { + } else { const GLFWvidmode* videoMode = glfwGetVideoMode(_monitor); int xpos = 0, ypos = 0; glfwGetMonitorPos(_monitor, &xpos, &ypos); @@ -722,36 +702,31 @@ void GLViewImpl::updateWindowSize() { int w = 0, h = 0; glfwGetFramebufferSize(_mainWindow, &w, &h); - int frameWidth = w / _frameZoomFactor; + int frameWidth = w / _frameZoomFactor; int frameHeight = h / _frameZoomFactor; setFrameSize(frameWidth, frameHeight); updateDesignResolutionSize(); Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(GLViewImpl::EVENT_WINDOW_RESIZED, nullptr); } -int GLViewImpl::getMonitorCount() const -{ +int GLViewImpl::getMonitorCount() const { int count = 0; glfwGetMonitors(&count); return count; } -Size GLViewImpl::getMonitorSize() const -{ +Size GLViewImpl::getMonitorSize() const { GLFWmonitor* monitor = _monitor; - if (nullptr == monitor) - { + if (nullptr == monitor) { GLFWwindow* window = this->getWindow(); - monitor = glfwGetWindowMonitor(window); + monitor = glfwGetWindowMonitor(window); } - if (nullptr == monitor) - { + if (nullptr == monitor) { monitor = glfwGetPrimaryMonitor(); } - if (nullptr != monitor) - { + if (nullptr != monitor) { const GLFWvidmode* videoMode = glfwGetVideoMode(monitor); - Size size = Size((float)videoMode->width, (float)videoMode->height); + Size size = Size((float)videoMode->width, (float)videoMode->height); return size; } return Size::ZERO; @@ -777,8 +752,7 @@ void GLViewImpl::updateFrameSize() { _retinaFactor = 2; } - glfwSetWindowSize(_mainWindow, _screenSize.width / 2 * _retinaFactor * _frameZoomFactor, - _screenSize.height / 2 * _retinaFactor * _frameZoomFactor); + glfwSetWindowSize(_mainWindow, _screenSize.width/2 * _retinaFactor * _frameZoomFactor, _screenSize.height/2 * _retinaFactor * _frameZoomFactor); _isInRetinaMonitor = true; } @@ -788,8 +762,7 @@ void GLViewImpl::updateFrameSize() { _retinaFactor = 1; } - glfwSetWindowSize(_mainWindow, (int)(_screenSize.width * _retinaFactor * _frameZoomFactor), - (int)(_screenSize.height * _retinaFactor * _frameZoomFactor)); + glfwSetWindowSize(_mainWindow, (int)(_screenSize.width * _retinaFactor * _frameZoomFactor), (int)(_screenSize.height *_retinaFactor * _frameZoomFactor)); _isInRetinaMonitor = false; } @@ -802,26 +775,22 @@ void GLViewImpl::setFrameSize(float width, float height) updateFrameSize(); } -void GLViewImpl::setViewPortInPoints(float x, float y, float w, float h) +void GLViewImpl::setViewPortInPoints(float x , float y , float w , float h) { Viewport vp; - vp.x = (int)(x * _scaleX * _retinaFactor * _frameZoomFactor + - _viewPortRect.origin.x * _retinaFactor * _frameZoomFactor); - vp.y = (int)(y * _scaleY * _retinaFactor * _frameZoomFactor + - _viewPortRect.origin.y * _retinaFactor * _frameZoomFactor); + vp.x = (int)(x * _scaleX * _retinaFactor * _frameZoomFactor + _viewPortRect.origin.x * _retinaFactor * _frameZoomFactor); + vp.y = (int)(y * _scaleY * _retinaFactor * _frameZoomFactor + _viewPortRect.origin.y * _retinaFactor * _frameZoomFactor); vp.w = (unsigned int)(w * _scaleX * _retinaFactor * _frameZoomFactor); vp.h = (unsigned int)(h * _scaleY * _retinaFactor * _frameZoomFactor); Camera::setDefaultViewport(vp); } -void GLViewImpl::setScissorInPoints(float x, float y, float w, float h) +void GLViewImpl::setScissorInPoints(float x , float y , float w , float h) { - auto x1 = (int)(x * _scaleX * _retinaFactor * _frameZoomFactor + - _viewPortRect.origin.x * _retinaFactor * _frameZoomFactor); - auto y1 = (int)(y * _scaleY * _retinaFactor * _frameZoomFactor + - _viewPortRect.origin.y * _retinaFactor * _frameZoomFactor); - auto width1 = (unsigned int)(w * _scaleX * _retinaFactor * _frameZoomFactor); - auto height1 = (unsigned int)(h * _scaleY * _retinaFactor * _frameZoomFactor); + auto x1 = (int)(x * _scaleX * _retinaFactor * _frameZoomFactor + _viewPortRect.origin.x * _retinaFactor * _frameZoomFactor); + auto y1 = (int)(y * _scaleY * _retinaFactor * _frameZoomFactor + _viewPortRect.origin.y * _retinaFactor * _frameZoomFactor); + auto width1 = (unsigned int)(w * _scaleX * _retinaFactor * _frameZoomFactor); + auto height1 = (unsigned int)(h * _scaleY * _retinaFactor * _frameZoomFactor); auto renderer = Director::getInstance()->getRenderer(); renderer->setScissorRect(x1, y1, width1, height1); } @@ -829,14 +798,12 @@ void GLViewImpl::setScissorInPoints(float x, float y, float w, float h) Rect GLViewImpl::getScissorRect() const { auto renderer = Director::getInstance()->getRenderer(); - auto& rect = renderer->getScissorRect(); + auto& rect = renderer->getScissorRect(); - float x = (rect.x - _viewPortRect.origin.x * _retinaFactor * _frameZoomFactor) / - (_scaleX * _retinaFactor * _frameZoomFactor); - float y = (rect.y - _viewPortRect.origin.y * _retinaFactor * _frameZoomFactor) / - (_scaleY * _retinaFactor * _frameZoomFactor); + float x = (rect.x - _viewPortRect.origin.x * _retinaFactor * _frameZoomFactor) / (_scaleX * _retinaFactor * _frameZoomFactor); + float y = (rect.y - _viewPortRect.origin.y * _retinaFactor * _frameZoomFactor) / (_scaleY * _retinaFactor * _frameZoomFactor); float w = rect.width / (_scaleX * _retinaFactor * _frameZoomFactor); - float h = rect.height / (_scaleY * _retinaFactor * _frameZoomFactor); + float h = rect.height / (_scaleY * _retinaFactor * _frameZoomFactor); return Rect(x, y, w, h); } @@ -855,41 +822,40 @@ void GLViewImpl::onGLFWError(int errorID, const char* errorDesc) void GLViewImpl::onGLFWMouseCallBack(GLFWwindow* /*window*/, int button, int action, int /*modify*/) { - if (GLFW_MOUSE_BUTTON_LEFT == button) + if(GLFW_MOUSE_BUTTON_LEFT == button) { - if (GLFW_PRESS == action) + if(GLFW_PRESS == action) { _captured = true; - if (this->getViewPortRect().equals(Rect::ZERO) || - this->getViewPortRect().containsPoint(Vec2(_mouseX, _mouseY))) + if (this->getViewPortRect().equals(Rect::ZERO) || this->getViewPortRect().containsPoint(Vec2(_mouseX,_mouseY))) { intptr_t id = 0; this->handleTouchesBegin(1, &id, &_mouseX, &_mouseY); } } - else if (GLFW_RELEASE == action) + else if(GLFW_RELEASE == action) { if (_captured) { - _captured = false; + _captured = false; intptr_t id = 0; this->handleTouchesEnd(1, &id, &_mouseX, &_mouseY); } } } - - // Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here + + //Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here float cursorX = (_mouseX - _viewPortRect.origin.x) / _scaleX; float cursorY = (_viewPortRect.origin.y + _viewPortRect.size.height - _mouseY) / _scaleY; - if (GLFW_PRESS == action) + if(GLFW_PRESS == action) { EventMouse event(EventMouse::MouseEventType::MOUSE_DOWN); event.setCursorPosition(cursorX, cursorY); event.setMouseButton(static_cast(button)); Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); } - else if (GLFW_RELEASE == action) + else if(GLFW_RELEASE == action) { EventMouse event(EventMouse::MouseEventType::MOUSE_UP); event.setCursorPosition(cursorX, cursorY); @@ -920,8 +886,8 @@ void GLViewImpl::onGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y) intptr_t id = 0; this->handleTouchesMove(1, &id, &_mouseX, &_mouseY); } - - // Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here + + //Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here float cursorX = (_mouseX - _viewPortRect.origin.x) / _scaleX; float cursorY = (_viewPortRect.origin.y + _viewPortRect.size.height - _mouseY) / _scaleY; @@ -946,7 +912,7 @@ void GLViewImpl::onGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y) void GLViewImpl::onGLFWMouseScrollCallback(GLFWwindow* /*window*/, double x, double y) { EventMouse event(EventMouse::MouseEventType::MOUSE_SCROLL); - // Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here + //Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here float cursorX = (_mouseX - _viewPortRect.origin.x) / _scaleX; float cursorY = (_viewPortRect.origin.y + _viewPortRect.size.height - _mouseY) / _scaleY; event.setScrollData((float)x, -(float)y); @@ -986,26 +952,26 @@ void GLViewImpl::onGLFWKeyCallback(GLFWwindow* /*window*/, int key, int /*scanco void GLViewImpl::onGLFWCharCallback(GLFWwindow* /*window*/, unsigned int character) { - char16_t wcharString[2] = {(char16_t)character, 0}; + char16_t wcharString[2] = { (char16_t) character, 0 }; std::string utf8String; - StringUtils::UTF16ToUTF8(wcharString, utf8String); + StringUtils::UTF16ToUTF8( wcharString, utf8String ); static std::set controlUnicode = { - "\xEF\x9C\x80", // up - "\xEF\x9C\x81", // down - "\xEF\x9C\x82", // left - "\xEF\x9C\x83", // right - "\xEF\x9C\xA8", // delete - "\xEF\x9C\xA9", // home - "\xEF\x9C\xAB", // end - "\xEF\x9C\xAC", // pageup - "\xEF\x9C\xAD", // pagedown - "\xEF\x9C\xB9" // clear + "\xEF\x9C\x80", // up + "\xEF\x9C\x81", // down + "\xEF\x9C\x82", // left + "\xEF\x9C\x83", // right + "\xEF\x9C\xA8", // delete + "\xEF\x9C\xA9", // home + "\xEF\x9C\xAB", // end + "\xEF\x9C\xAC", // pageup + "\xEF\x9C\xAD", // pagedown + "\xEF\x9C\xB9" // clear }; // Check for send control key if (controlUnicode.find(utf8String) == controlUnicode.end()) { - IMEDispatcher::sharedDispatcher()->dispatchInsertText(utf8String.c_str(), utf8String.size()); + IMEDispatcher::sharedDispatcher()->dispatchInsertText( utf8String.c_str(), utf8String.size() ); } } @@ -1018,18 +984,18 @@ void GLViewImpl::onGLFWWindowSizeCallback(GLFWwindow* /*window*/, int width, int { if (width && height && _resolutionPolicy != ResolutionPolicy::UNKNOWN) { - Size baseDesignSize = _designResolutionSize; + Size baseDesignSize = _designResolutionSize; ResolutionPolicy baseResolutionPolicy = _resolutionPolicy; - int frameWidth = width / _frameZoomFactor; + int frameWidth = width / _frameZoomFactor; int frameHeight = height / _frameZoomFactor; setFrameSize(frameWidth, frameHeight); setDesignResolutionSize(baseDesignSize.width, baseDesignSize.height, baseResolutionPolicy); Director::getInstance()->setViewport(); Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(GLViewImpl::EVENT_WINDOW_RESIZED, nullptr); - + #if defined(CC_USE_METAL) - // update metal attachment texture size. + //update metal attachment texture size. int fbWidth, fbHeight; glfwGetFramebufferSize(_mainWindow, &fbWidth, &fbHeight); backend::UtilsMTL::resizeDefaultAttachmentTexture(fbWidth, fbHeight); @@ -1061,4 +1027,4 @@ void GLViewImpl::onGLFWWindowFocusCallback(GLFWwindow* /*window*/, int focused) } } -NS_CC_END // end of namespace cocos2d; +NS_CC_END // end of namespace cocos2d; diff --git a/cocos/platform/win32/CCApplication-win32.cpp b/cocos/platform/win32/CCApplication-win32.cpp index ea159d973b..3f51532ce9 100644 --- a/cocos/platform/win32/CCApplication-win32.cpp +++ b/cocos/platform/win32/CCApplication-win32.cpp @@ -287,14 +287,14 @@ std::string Application::getVersion() return verString; } -bool Application::openURL(std::string_view url) +bool Application::openURL(const std::string& url) { std::wstring wURL = ntcvt::from_chars(url, CP_UTF8); HINSTANCE r = ShellExecuteW(NULL, L"open", wURL.c_str(), NULL, NULL, SW_SHOWNORMAL); return (size_t)r > 32; } -void Application::setResourceRootPath(std::string_view rootResDir) +void Application::setResourceRootPath(const std::string& rootResDir) { _resourceRootPath = rootResDir; std::replace(_resourceRootPath.begin(), _resourceRootPath.end(), '\\', '/'); @@ -308,12 +308,12 @@ void Application::setResourceRootPath(std::string_view rootResDir) pFileUtils->setSearchPaths(searchPaths); } -std::string_view Application::getResourceRootPath(void) +const std::string& Application::getResourceRootPath(void) { return _resourceRootPath; } -void Application::setStartupScriptFilename(std::string_view startupScriptFile) +void Application::setStartupScriptFilename(const std::string& startupScriptFile) { _startupScriptFilename = startupScriptFile; std::replace(_startupScriptFilename.begin(), _startupScriptFilename.end(), '\\', '/'); diff --git a/cocos/platform/win32/CCApplication-win32.h b/cocos/platform/win32/CCApplication-win32.h index 56fcc81e84..011100a3f2 100644 --- a/cocos/platform/win32/CCApplication-win32.h +++ b/cocos/platform/win32/CCApplication-win32.h @@ -78,23 +78,23 @@ public: @param String with url to open. @return true if the resource located by the URL was successfully opened; otherwise false. */ - virtual bool openURL(std::string_view url); + virtual bool openURL(const std::string& url); /** * Sets the Resource root path. * @deprecated Please use FileUtils::getInstance()->setSearchPaths() instead. */ - CC_DEPRECATED_ATTRIBUTE void setResourceRootPath(std::string_view rootResDir); + CC_DEPRECATED_ATTRIBUTE void setResourceRootPath(const std::string& rootResDir); /** * Gets the Resource root path. * @deprecated Please use FileUtils::getInstance()->getSearchPaths() instead. */ - CC_DEPRECATED_ATTRIBUTE std::string_view getResourceRootPath(); + CC_DEPRECATED_ATTRIBUTE const std::string& getResourceRootPath(); - void setStartupScriptFilename(std::string_view startupScriptFile); + void setStartupScriptFilename(const std::string& startupScriptFile); - std::string_view getStartupScriptFilename() { return _startupScriptFilename; } + const std::string& getStartupScriptFilename() { return _startupScriptFilename; } protected: HINSTANCE _instance; diff --git a/cocos/platform/win32/CCFileUtils-win32.cpp b/cocos/platform/win32/CCFileUtils-win32.cpp index 3b70dd413b..1dd25374af 100644 --- a/cocos/platform/win32/CCFileUtils-win32.cpp +++ b/cocos/platform/win32/CCFileUtils-win32.cpp @@ -26,6 +26,7 @@ THE SOFTWARE. ****************************************************************************/ #include "platform/win32/CCFileUtils-win32.h" #include "platform/CCCommon.h" +#include "tinydir/tinydir.h" #include #include #include @@ -44,14 +45,14 @@ NS_CC_BEGIN // The root path of resources, the character encoding is UTF-8. // UTF-8 is the only encoding supported by adxe API by default. -static std::wstring s_workingPath; -static std::string s_exePath; +static std::string s_workingPath = ""; +static std::string s_exePath = ""; // D:\aaa\bbb\ccc\ddd\abc.txt --> D:/aaa/bbb/ccc/ddd/abc.txt -static std::string convertPathFormatToUnixStyle(std::string_view path) +static std::string convertPathFormatToUnixStyle(const std::string& path) { - std::string ret{path}; - int len = ret.length(); + std::string ret = path; + int len = ret.length(); for (int i = 0; i < len; ++i) { if (ret[i] == '\\') @@ -62,20 +63,6 @@ static std::string convertPathFormatToUnixStyle(std::string_view path) return ret; } -static std::string convertPathFormatToWinStyle(std::string_view path) -{ - std::string ret{path}; - int len = ret.length(); - for (int i = 0; i < len; ++i) - { - if (ret[i] == '/') - { - ret[i] = '\\'; - } - } - return ret; -} - static void _checkWorkingPath() { if (s_workingPath.empty()) @@ -83,9 +70,15 @@ static void _checkWorkingPath() WCHAR utf16Path[CC_MAX_PATH] = {0}; int nNum = GetCurrentDirectoryW(CC_MAX_PATH - 2, utf16Path); - s_workingPath.reserve(nNum + 1); - s_workingPath.assign(utf16Path, nNum); - s_workingPath.push_back('\\'); + char utf8WorkingDir[CC_MAX_PATH] = {0}; + nNum = + WideCharToMultiByte(CP_UTF8, 0, utf16Path, nNum, utf8WorkingDir, sizeof(utf8WorkingDir), nullptr, nullptr); + if (nNum < (CC_MAX_PATH - 2)) + { + utf8WorkingDir[nNum] = '\\'; + utf8WorkingDir[nNum + 1] = '\0'; + s_workingPath = convertPathFormatToUnixStyle(utf8WorkingDir); + } } } @@ -128,26 +121,25 @@ bool FileUtilsWin32::init() DECLARE_GUARD; _checkWorkingPath(); - _defaultResRootPath = ntcvt::from_chars(s_workingPath); - _defaultResRootPathUtf16 = s_workingPath; + _defaultResRootPath = s_workingPath; bool bRet = FileUtils::init(); _checkExePath(); - if (_defaultResRootPath != s_exePath) + if (s_workingPath != s_exePath) addSearchPath(s_exePath); return bRet; } -bool FileUtilsWin32::isDirectoryExistInternal(std::string_view dirPath) const +bool FileUtilsWin32::isDirectoryExistInternal(const std::string& dirPath) const { uint32_t fAttrib = GetFileAttributesW(ntcvt::from_chars(dirPath).c_str()); return (fAttrib != INVALID_FILE_ATTRIBUTES && (fAttrib & FILE_ATTRIBUTE_DIRECTORY)); } -bool FileUtilsWin32::isFileExistInternal(std::string_view strFilePath) const +bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const { DECLARE_GUARD; if (strFilePath.empty()) @@ -155,19 +147,17 @@ bool FileUtilsWin32::isFileExistInternal(std::string_view strFilePath) const return false; } - std::wstring strPathUtf16; - if (!isAbsolutePath(strFilePath)) + std::string strPath = strFilePath; + if (!isAbsolutePath(strPath)) { // Not absolute path, add the default root path at the beginning. - strPathUtf16.insert(0, _defaultResRootPathUtf16); + strPath.insert(0, _defaultResRootPath); } - else - strPathUtf16 = ntcvt::from_chars(strFilePath); - DWORD attr = GetFileAttributesW(strPathUtf16.c_str()); + DWORD attr = GetFileAttributesW(ntcvt::from_chars(strPath).c_str()); return (attr != INVALID_FILE_ATTRIBUTES && !(attr & FILE_ATTRIBUTE_DIRECTORY)); } -FileUtils::Status FileUtilsWin32::getContents(std::string_view filename, ResizableBuffer* buffer) const +FileUtils::Status FileUtilsWin32::getContents(const std::string& filename, ResizableBuffer* buffer) const { if (filename.empty()) return FileUtils::Status::NotExists; @@ -209,9 +199,9 @@ FileUtils::Status FileUtilsWin32::getContents(std::string_view filename, Resizab return FileUtils::Status::OK; } -std::string FileUtilsWin32::getPathForFilename(std::string_view filename, - std::string_view resolutionDirectory, - std::string_view searchPath) const +std::string FileUtilsWin32::getPathForFilename(const std::string& filename, + const std::string& resolutionDirectory, + const std::string& searchPath) const { std::string unixFileName = convertPathFormatToUnixStyle(filename); std::string unixResolutionDirectory = convertPathFormatToUnixStyle(resolutionDirectory); @@ -220,8 +210,8 @@ std::string FileUtilsWin32::getPathForFilename(std::string_view filename, return FileUtils::getPathForFilename(unixFileName, unixResolutionDirectory, unixSearchPath); } -std::string FileUtilsWin32::getFullPathForFilenameWithinDirectory(std::string_view strDirectory, - std::string_view strFilename) const +std::string FileUtilsWin32::getFullPathForFilenameWithinDirectory(const std::string& strDirectory, + const std::string& strFilename) const { std::string unixDirectory = convertPathFormatToUnixStyle(strDirectory); std::string unixFilename = convertPathFormatToUnixStyle(strFilename); @@ -229,7 +219,53 @@ std::string FileUtilsWin32::getFullPathForFilenameWithinDirectory(std::string_vi return FileUtils::getFullPathForFilenameWithinDirectory(unixDirectory, unixFilename); } -int64_t FileUtilsWin32::getFileSize(std::string_view filepath) const +void FileUtilsWin32::listFilesRecursively(const std::string& dirPath, std::vector* files) const +{ + std::string fullpath = fullPathForDirectory(dirPath); + if (isDirectoryExist(fullpath)) + { + tinydir_dir dir; + std::wstring fullpathstr = ntcvt::from_chars(fullpath); + + if (tinydir_open(&dir, &fullpathstr[0]) != -1) + { + while (dir.has_next) + { + tinydir_file file; + if (tinydir_readfile(&dir, &file) == -1) + { + // Error getting file + break; + } + std::string fileName = ntcvt::from_chars(file.name); + + if (fileName != "." && fileName != "..") + { + std::string filepath = ntcvt::from_chars(file.path); + if (file.is_dir) + { + filepath.push_back('/'); + files->push_back(filepath); + listFilesRecursively(filepath, files); + } + else + { + files->push_back(std::move(filepath)); + } + } + + if (tinydir_next(&dir) == -1) + { + // Error getting next file + break; + } + } + } + tinydir_close(&dir); + } +} + +int64_t FileUtilsWin32::getFileSize(const std::string& filepath) const { if (filepath.empty()) return -1; @@ -240,6 +276,49 @@ int64_t FileUtilsWin32::getFileSize(std::string_view filepath) const return -1; } +std::vector FileUtilsWin32::listFiles(const std::string& dirPath) const +{ + std::string fullpath = fullPathForDirectory(dirPath); + std::vector files; + if (isDirectoryExist(fullpath)) + { + tinydir_dir dir; + std::wstring fullpathstr = ntcvt::from_chars(fullpath); + + if (tinydir_open(&dir, &fullpathstr[0]) != -1) + { + while (dir.has_next) + { + tinydir_file file; + if (tinydir_readfile(&dir, &file) == -1) + { + // Error getting file + break; + } + + std::string fileName = ntcvt::from_chars(file.name); + if (fileName != "." && fileName != "..") + { + std::string filepath = ntcvt::from_chars(file.path); + if (file.is_dir) + { + filepath.push_back('/'); + } + files.push_back(std::move(filepath)); + } + + if (tinydir_next(&dir) == -1) + { + // Error getting next file + break; + } + } + } + tinydir_close(&dir); + } + return files; +} + std::string FileUtilsWin32::getWritablePath() const { DECLARE_GUARD; @@ -301,7 +380,7 @@ std::string FileUtilsWin32::getNativeWritableAbsolutePath() const return convertPathFormatToUnixStyle(ntcvt::from_chars(retPath)); } -bool FileUtilsWin32::renameFile(std::string_view oldfullpath, std::string_view newfullpath) const +bool FileUtilsWin32::renameFile(const std::string& oldfullpath, const std::string& newfullpath) const { CCASSERT(!oldfullpath.empty(), "Invalid path"); CCASSERT(!newfullpath.empty(), "Invalid path"); @@ -313,7 +392,7 @@ bool FileUtilsWin32::renameFile(std::string_view oldfullpath, std::string_view n { if (!DeleteFile(_wNew.c_str())) { - CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newfullpath.data(), GetLastError()); + CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newfullpath.c_str(), GetLastError()); } } @@ -323,19 +402,17 @@ bool FileUtilsWin32::renameFile(std::string_view oldfullpath, std::string_view n } else { - CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldfullpath.data(), newfullpath.data(), + CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldfullpath.c_str(), newfullpath.c_str(), GetLastError()); return false; } } -bool FileUtilsWin32::renameFile(std::string_view path, std::string_view oldname, std::string_view name) const +bool FileUtilsWin32::renameFile(const std::string& path, const std::string& oldname, const std::string& name) const { CCASSERT(!path.empty(), "Invalid path"); - std::string oldPath{path}; - oldPath += oldname; - std::string newPath{path}; - newPath += name; + std::string oldPath = path + oldname; + std::string newPath = path + name; std::regex pat("\\/"); std::string _old = std::regex_replace(oldPath, pat, "\\"); @@ -344,7 +421,7 @@ bool FileUtilsWin32::renameFile(std::string_view path, std::string_view oldname, return renameFile(_old, _new); } -bool FileUtilsWin32::createDirectory(std::string_view dirPath) const +bool FileUtilsWin32::createDirectory(const std::string& dirPath) const { CCASSERT(!dirPath.empty(), "Invalid path"); @@ -401,9 +478,10 @@ bool FileUtilsWin32::createDirectory(std::string_view dirPath) const return true; } -bool FileUtilsWin32::removeFile(std::string_view filepath) const +bool FileUtilsWin32::removeFile(const std::string& filepath) const { - std::string win32path = convertPathFormatToWinStyle(filepath); + std::regex pat("\\/"); + std::string win32path = std::regex_replace(filepath, pat, "\\"); if (DeleteFileW(ntcvt::from_chars(win32path).c_str())) { @@ -411,14 +489,14 @@ bool FileUtilsWin32::removeFile(std::string_view filepath) const } else { - CCLOGERROR("Fail remove file %s !Error code is 0x%x", filepath.data(), GetLastError()); + CCLOGERROR("Fail remove file %s !Error code is 0x%x", filepath.c_str(), GetLastError()); return false; } } -bool FileUtilsWin32::removeDirectory(std::string_view dirPath) const +bool FileUtilsWin32::removeDirectory(const std::string& dirPath) const { - std::string dirPathCopy{dirPath}; + std::string dirPathCopy = dirPath; if (!dirPath.empty() && dirPath[dirPath.length() - 1] != '/' && dirPath[dirPath.length() - 1] != '\\') { dirPathCopy.push_back('/'); diff --git a/cocos/platform/win32/CCFileUtils-win32.h b/cocos/platform/win32/CCFileUtils-win32.h index d68f8c54aa..5188e7f83a 100644 --- a/cocos/platform/win32/CCFileUtils-win32.h +++ b/cocos/platform/win32/CCFileUtils-win32.h @@ -53,7 +53,7 @@ public: virtual std::string getNativeWritableAbsolutePath() const override; protected: - virtual bool isFileExistInternal(std::string_view strFilePath) const override; + virtual bool isFileExistInternal(const std::string& strFilePath) const override; /** * Renames a file under the given directory. @@ -63,7 +63,9 @@ protected: * @param name The new name of the file. * @return True if the file have been renamed successfully, false if not. */ - virtual bool renameFile(std::string_view path, std::string_view oldname, std::string_view name) const override; + virtual bool renameFile(const std::string& path, + const std::string& oldname, + const std::string& name) const override; /** * Renames a file under the given directory. @@ -72,14 +74,14 @@ protected: * @param newfullpath The new path + name of the file. * @return True if the file have been renamed successfully, false if not. */ - virtual bool renameFile(std::string_view oldfullpath, std::string_view newfullpath) const override; + virtual bool renameFile(const std::string& oldfullpath, const std::string& newfullpath) const override; /** * Checks whether a directory exists without considering search paths and resolution orders. * @param dirPath The directory (with absolute path) to look up for * @return Returns true if the directory found at the given absolute path, otherwise returns false */ - virtual bool isDirectoryExistInternal(std::string_view dirPath) const override; + virtual bool isDirectoryExistInternal(const std::string& dirPath) const override; /** * Removes a file. @@ -87,7 +89,7 @@ protected: * @param filepath The full path of the file, it must be an absolute path. * @return True if the file have been removed successfully, false if not. */ - virtual bool removeFile(std::string_view filepath) const override; + virtual bool removeFile(const std::string& filepath) const override; /** * Creates a directory. @@ -95,7 +97,7 @@ protected: * @param dirPath The path of the directory, it must be an absolute path. * @return True if the directory have been created successfully, false if not. */ - virtual bool createDirectory(std::string_view dirPath) const override; + virtual bool createDirectory(const std::string& dirPath) const override; /** * Removes a directory. @@ -103,11 +105,11 @@ protected: * @param dirPath The full path of the directory, it must be an absolute path. * @return True if the directory have been removed successfully, false if not. */ - virtual bool removeDirectory(std::string_view dirPath) const override; + virtual bool removeDirectory(const std::string& dirPath) const override; - virtual FileUtils::Status getContents(std::string_view filename, ResizableBuffer* buffer) const override; + virtual FileUtils::Status getContents(const std::string& filename, ResizableBuffer* buffer) const override; - virtual int64_t getFileSize(std::string_view filepath) const override; + virtual int64_t getFileSize(const std::string& filepath) const override; /** * Gets full path for filename, resolution directory and search path. @@ -117,9 +119,9 @@ protected: * @param searchPath The search path. * @return The full path of the file. It will return an empty string if the full path of the file doesn't exist. */ - virtual std::string getPathForFilename(std::string_view filename, - std::string_view resolutionDirectory, - std::string_view searchPath) const override; + virtual std::string getPathForFilename(const std::string& filename, + const std::string& resolutionDirectory, + const std::string& searchPath) const override; /** * Gets full path for the directory and the filename. @@ -131,11 +133,24 @@ protected: * @param filename The name of the file. * @return The full path of the file, if the file can't be found, it will return an empty string. */ - virtual std::string getFullPathForFilenameWithinDirectory(std::string_view directory, - std::string_view filename) const override; + virtual std::string getFullPathForFilenameWithinDirectory(const std::string& directory, + const std::string& filename) const override; -private: - std::wstring_view _defaultResRootPathUtf16; + /** + * List all files in a directory. + * + * @param dirPath The path of the directory, it could be a relative or an absolute path. + * @return File paths in a string vector + */ + virtual std::vector listFiles(const std::string& dirPath) const override; + + /** + * List all files recursively in a directory. + * + * @param dirPath The path of the directory, it could be a relative or an absolute path. + * @return File paths in a string vector + */ + virtual void listFilesRecursively(const std::string& dirPath, std::vector* files) const override; }; // end of platform group diff --git a/cocos/renderer/CCMaterial.cpp b/cocos/renderer/CCMaterial.cpp index da4aeb7cf1..17a43f39b9 100644 --- a/cocos/renderer/CCMaterial.cpp +++ b/cocos/renderer/CCMaterial.cpp @@ -48,7 +48,7 @@ NS_CC_BEGIN namespace { -std::string replaceDefines(std::string_view compileTimeDefines) +std::string replaceDefines(const std::string& compileTimeDefines) { auto defineParts = Console::Utility::split(compileTimeDefines, ';'); @@ -72,7 +72,7 @@ std::string replaceDefines(std::string_view compileTimeDefines) static const char* getOptionalString(Properties* properties, const char* key, const char* defaultValue); static bool isValidUniform(const char* name); -Material* Material::createWithFilename(std::string_view filepath) +Material* Material::createWithFilename(const std::string& filepath) { auto validfilename = FileUtils::getInstance()->fullPathForFilename(filepath); if (!validfilename.empty()) @@ -130,7 +130,7 @@ bool Material::initWithProgramState(backend::ProgramState* state) return false; } -bool Material::initWithFile(std::string_view validfilename) +bool Material::initWithFile(const std::string& validfilename) { // Warning: properties is not a "Ref" object, must be manually deleted Properties* properties = Properties::createNonRefCounted(validfilename); @@ -496,7 +496,7 @@ bool Material::parseRenderState(RenderState::StateBlock* state, Properties* prop return true; } -void Material::setName(std::string_view name) +void Material::setName(const std::string& name) { _name = name; } @@ -542,7 +542,7 @@ const Vector& Material::getTechniques() const return _techniques; } -Technique* Material::getTechniqueByName(std::string_view name) +Technique* Material::getTechniqueByName(const std::string& name) { for (const auto& technique : _techniques) { @@ -564,7 +564,7 @@ void Material::addTechnique(Technique* technique) _techniques.pushBack(technique); } -void Material::setTechnique(std::string_view techniqueName) +void Material::setTechnique(const std::string& techniqueName) { auto technique = getTechniqueByName(techniqueName); if (technique) diff --git a/cocos/renderer/CCMaterial.h b/cocos/renderer/CCMaterial.h index bc94addc47..acc8ccdda2 100644 --- a/cocos/renderer/CCMaterial.h +++ b/cocos/renderer/CCMaterial.h @@ -78,7 +78,7 @@ public: * * @return A new Material or NULL if there was an error. */ - static Material* createWithFilename(std::string_view path); + static Material* createWithFilename(const std::string& path); /** Creates a Material with a GLProgramState. It will only contain one Technique and one Pass. @@ -107,12 +107,12 @@ public: /// returns the material name std::string getName() const; /// sets the material name - void setName(std::string_view name); + void setName(const std::string& name); /** Returns a Technique by its name. returns `nullptr` if the Technique can't be found. */ - Technique* getTechniqueByName(std::string_view name); + Technique* getTechniqueByName(const std::string& name); /** Returns a Technique by index. returns `nullptr` if the index is invalid. @@ -132,7 +132,7 @@ public: void addTechnique(Technique* technique); /** Sets the current technique */ - void setTechnique(std::string_view techniqueName); + void setTechnique(const std::string& techniqueName); /** returns a clone (deep-copy) of the material */ virtual Material* clone() const; @@ -147,7 +147,7 @@ protected: Material(); ~Material(); bool initWithProgramState(backend::ProgramState* state); - bool initWithFile(std::string_view file); + bool initWithFile(const std::string& file); bool initWithProperties(Properties* materialProperties); void setTarget(Node* target); diff --git a/cocos/renderer/CCPass.h b/cocos/renderer/CCPass.h index 483112611e..ee095d854f 100644 --- a/cocos/renderer/CCPass.h +++ b/cocos/renderer/CCPass.h @@ -94,8 +94,8 @@ public: */ VertexAttribBinding* getVertexAttributeBinding() const; - void setName(std::string_view name) { _name = name; } - std::string_view getName() const { return _name; } + void setName(const std::string& name) { _name = name; } + const std::string& getName() const { return _name; } inline RenderState::StateBlock& getStateBlock() { return _renderState._state; } diff --git a/cocos/renderer/CCRenderState.cpp b/cocos/renderer/CCRenderState.cpp index 690af0e459..4a1b8821d7 100644 --- a/cocos/renderer/CCRenderState.cpp +++ b/cocos/renderer/CCRenderState.cpp @@ -183,12 +183,12 @@ void RenderState::StateBlock::restoreUnmodifiedStates(int32_t overrideBits, Pipe } } -static bool parseBoolean(std::string_view value) +static bool parseBoolean(const std::string& value) { return (value.compare("true") == 0); } -static backend::BlendFactor parseBlend(std::string_view value) +static backend::BlendFactor parseBlend(const std::string& value) { // Convert the string to uppercase for comparison. std::string upper(value); @@ -222,12 +222,12 @@ static backend::BlendFactor parseBlend(std::string_view value) else { CCLOG("Unsupported blend value (%s). (Will default to BLEND_ONE if errors are treated as warnings)", - value.data()); + value.c_str()); return backend::BlendFactor::ONE; } } -static DepthFunction parseDepthFunc(std::string_view value) +static DepthFunction parseDepthFunc(const std::string& value) { // Convert string to uppercase for comparison std::string upper(value); @@ -251,12 +251,12 @@ static DepthFunction parseDepthFunc(std::string_view value) else { CCLOG("Unsupported depth function value (%s). Will default to DEPTH_LESS if errors are treated as warnings)", - value.data()); + value.c_str()); return DepthFunction::LESS; } } -static CullFaceSide parseCullFaceSide(std::string_view value) +static CullFaceSide parseCullFaceSide(const std::string& value) { // Convert string to uppercase for comparison std::string upper(value); @@ -271,12 +271,12 @@ static CullFaceSide parseCullFaceSide(std::string_view value) else { CCLOG("Unsupported cull face side value (%s). Will default to BACK if errors are treated as warnings.", - value.data()); + value.c_str()); return CullFaceSide::BACK; } } -static FrontFace parseFrontFace(std::string_view value) +static FrontFace parseFrontFace(const std::string& value) { // Convert string to uppercase for comparison std::string upper(value); @@ -288,12 +288,12 @@ static FrontFace parseFrontFace(std::string_view value) else { CCLOG("Unsupported front face side value (%s). Will default to CCW if errors are treated as warnings.", - value.data()); + value.c_str()); return FrontFace::COUNTER_CLOCK_WISE; } } -void RenderState::StateBlock::setState(std::string_view name, std::string_view value) +void RenderState::StateBlock::setState(const std::string& name, const std::string& value) { if (name.compare("blend") == 0) { @@ -333,7 +333,7 @@ void RenderState::StateBlock::setState(std::string_view name, std::string_view v } else { - CCLOG("Unsupported render state string '%s'.", name.data()); + CCLOG("Unsupported render state string '%s'.", name.c_str()); } } diff --git a/cocos/renderer/CCRenderState.h b/cocos/renderer/CCRenderState.h index 27fd7c4973..3e94b36afb 100644 --- a/cocos/renderer/CCRenderState.h +++ b/cocos/renderer/CCRenderState.h @@ -194,7 +194,7 @@ public: * @param name Name of the render state to set. * @param value Value of the specified render state. */ - void setState(std::string_view name, std::string_view value); + void setState(const std::string& name, const std::string& value); uint32_t getHash() const; bool isDirty() const; diff --git a/cocos/renderer/CCTechnique.cpp b/cocos/renderer/CCTechnique.cpp index bc7e20896a..88e5ee9e8b 100644 --- a/cocos/renderer/CCTechnique.cpp +++ b/cocos/renderer/CCTechnique.cpp @@ -98,7 +98,7 @@ std::string Technique::getName() const return _name; } -void Technique::setName(std::string_view name) +void Technique::setName(const std::string& name) { _name = name; } diff --git a/cocos/renderer/CCTechnique.h b/cocos/renderer/CCTechnique.h index 6c7641b557..aaf4c937d8 100644 --- a/cocos/renderer/CCTechnique.h +++ b/cocos/renderer/CCTechnique.h @@ -91,7 +91,7 @@ protected: ~Technique(); bool init(Material* parent); - void setName(std::string_view name); + void setName(const std::string& name); RenderState _renderState; std::string _name; Vector _passes; diff --git a/cocos/renderer/CCTexture2D.cpp b/cocos/renderer/CCTexture2D.cpp index a81f654cd3..55995f8d5a 100644 --- a/cocos/renderer/CCTexture2D.cpp +++ b/cocos/renderer/CCTexture2D.cpp @@ -460,7 +460,7 @@ bool Texture2D::initWithImage(Image* image, backend::PixelFormat format) // implementation Texture2D (Text) bool Texture2D::initWithString(const char* text, - std::string_view fontName, + const std::string& fontName, float fontSize, const Vec2& dimensions /* = Vec2(0, 0)*/, TextHAlignment hAlignment /* = TextHAlignment::CENTER */, @@ -741,7 +741,7 @@ void Texture2D::initProgram() // setup vertex layout auto vertexLayout = _programState->getVertexLayout(); - auto attributes = _programState->getProgram()->getActiveAttributes(); + auto& attributes = _programState->getProgram()->getActiveAttributes(); auto iter = attributes.find("a_position"); if (iter != attributes.end()) vertexLayout->setAttribute("a_position", iter->second.location, backend::VertexFormat::FLOAT2, 0, false); diff --git a/cocos/renderer/CCTexture2D.h b/cocos/renderer/CCTexture2D.h index 9d4fb89c84..19afa61928 100644 --- a/cocos/renderer/CCTexture2D.h +++ b/cocos/renderer/CCTexture2D.h @@ -273,7 +273,7 @@ public: @param overflow Whether shrink font size when content larger than the dimensions. */ bool initWithString(const char* text, - std::string_view fontName, + const std::string& fontName, float fontSize, const Vec2& dimensions = Vec2(0, 0), TextHAlignment hAlignment = TextHAlignment::CENTER, diff --git a/cocos/renderer/CCTextureAtlas.cpp b/cocos/renderer/CCTextureAtlas.cpp index 0810493c9f..5617481f55 100644 --- a/cocos/renderer/CCTextureAtlas.cpp +++ b/cocos/renderer/CCTextureAtlas.cpp @@ -99,7 +99,7 @@ void TextureAtlas::setQuads(V3F_C4B_T2F_Quad* quads) // TextureAtlas - alloc & init -TextureAtlas* TextureAtlas::create(std::string_view file, ssize_t capacity) +TextureAtlas* TextureAtlas::create(const std::string& file, ssize_t capacity) { TextureAtlas* textureAtlas = new TextureAtlas(); if (textureAtlas->initWithFile(file, capacity)) @@ -123,7 +123,7 @@ TextureAtlas* TextureAtlas::createWithTexture(Texture2D* texture, ssize_t capaci return nullptr; } -bool TextureAtlas::initWithFile(std::string_view file, ssize_t capacity) +bool TextureAtlas::initWithFile(const std::string& file, ssize_t capacity) { // retained in property Texture2D* texture = Director::getInstance()->getTextureCache()->addImage(file); @@ -134,7 +134,7 @@ bool TextureAtlas::initWithFile(std::string_view file, ssize_t capacity) } else { - CCLOG("cocos2d: Could not open file: %s", file.data()); + CCLOG("cocos2d: Could not open file: %s", file.c_str()); return false; } } diff --git a/cocos/renderer/CCTextureAtlas.h b/cocos/renderer/CCTextureAtlas.h index e088f3e95f..0f8abffd26 100644 --- a/cocos/renderer/CCTextureAtlas.h +++ b/cocos/renderer/CCTextureAtlas.h @@ -68,7 +68,7 @@ public: @param file The file path. @param capacity Capacity for Quads. */ - static TextureAtlas* create(std::string_view file, ssize_t capacity); + static TextureAtlas* create(const std::string& file, ssize_t capacity); /** Creates a TextureAtlas with a previously initialized Texture2D object, and * with an initial capacity for n Quads. @@ -95,7 +95,7 @@ public: @param file The file path. @param capacity Capacity for Quads. */ - bool initWithFile(std::string_view file, ssize_t capacity); + bool initWithFile(const std::string& file, ssize_t capacity); /** Initializes a TextureAtlas with a previously initialized Texture2D object, and * with an initial capacity for Quads. diff --git a/cocos/renderer/CCTextureCache.cpp b/cocos/renderer/CCTextureCache.cpp index f99bcfc4de..3315479d7b 100644 --- a/cocos/renderer/CCTextureCache.cpp +++ b/cocos/renderer/CCTextureCache.cpp @@ -52,7 +52,7 @@ std::string TextureCache::s_etc1AlphaFileSuffix = "@alpha"; // implementation TextureCache -void TextureCache::setETC1AlphaFileSuffix(std::string_view suffix) +void TextureCache::setETC1AlphaFileSuffix(const std::string& suffix) { s_etc1AlphaFileSuffix = suffix; } @@ -82,7 +82,7 @@ std::string TextureCache::getDescription() const struct TextureCache::AsyncStruct { public: - AsyncStruct(std::string_view fn, const std::function& f, std::string_view key) + AsyncStruct(const std::string& fn, const std::function& f, const std::string& key) : filename(fn) , callback(f) , callbackKey(key) @@ -131,7 +131,7 @@ public: Call unbindImageAsync(path) to prevent the call to the callback when the texture is loaded. */ -void TextureCache::addImageAsync(std::string_view path, const std::function& callback) +void TextureCache::addImageAsync(const std::string& path, const std::function& callback) { addImageAsync(path, callback, path); } @@ -170,9 +170,9 @@ void TextureCache::addImageAsync(std::string_view path, const std::function& callback, - std::string_view callbackKey) + const std::string& callbackKey) { Texture2D* texture = nullptr; @@ -223,7 +223,7 @@ void TextureCache::addImageAsync(std::string_view path, _sleepCondition.notify_one(); } -void TextureCache::unbindImageAsync(std::string_view callbackKey) +void TextureCache::unbindImageAsync(const std::string& callbackKey) { if (_asyncStructQueue.empty()) { @@ -383,7 +383,7 @@ void TextureCache::addImageAsyncCallBack(float /*dt*/) } } -Texture2D* TextureCache::addImage(std::string_view path) +Texture2D* TextureCache::addImage(const std::string& path) { Texture2D* texture = nullptr; Image* image = nullptr; @@ -422,8 +422,7 @@ Texture2D* TextureCache::addImage(std::string_view path) _textures.emplace(fullpath, texture); //-- ANDROID ETC1 ALPHA SUPPORTS. - std::string alphaFullPath{path}; - alphaFullPath += s_etc1AlphaFileSuffix; + std::string alphaFullPath = path + s_etc1AlphaFileSuffix; if (image->getFileType() == Image::Format::ETC1 && !s_etc1AlphaFileSuffix.empty() && FileUtils::getInstance()->isFileExist(alphaFullPath)) { @@ -439,7 +438,7 @@ Texture2D* TextureCache::addImage(std::string_view path) } else { - CCLOG("cocos2d: Couldn't create texture for file:%s in TextureCache", path.data()); + CCLOG("cocos2d: Couldn't create texture for file:%s in TextureCache", path.c_str()); CC_SAFE_RELEASE(texture); texture = nullptr; } @@ -451,7 +450,7 @@ Texture2D* TextureCache::addImage(std::string_view path) return texture; } -void TextureCache::parseNinePatchImage(cocos2d::Image* image, cocos2d::Texture2D* texture, std::string_view path) +void TextureCache::parseNinePatchImage(cocos2d::Image* image, cocos2d::Texture2D* texture, const std::string& path) { if (NinePatchImageParser::isNinePatchImage(path)) { @@ -461,7 +460,7 @@ void TextureCache::parseNinePatchImage(cocos2d::Image* image, cocos2d::Texture2D } } -Texture2D* TextureCache::addImage(Image* image, std::string_view key) +Texture2D* TextureCache::addImage(Image* image, const std::string& key) { CCASSERT(image != nullptr, "TextureCache: image MUST not be nil"); CCASSERT(image->getData() != nullptr, "TextureCache: image MUST not be nil"); @@ -498,7 +497,7 @@ Texture2D* TextureCache::addImage(Image* image, std::string_view key) return texture; } -bool TextureCache::reloadTexture(std::string_view fileName) +bool TextureCache::reloadTexture(const std::string& fileName) { Texture2D* texture = nullptr; @@ -586,14 +585,15 @@ void TextureCache::removeTexture(Texture2D* texture) } } -void TextureCache::removeTextureForKey(std::string_view textureKeyName) +void TextureCache::removeTextureForKey(const std::string& textureKeyName) { - auto it = _textures.find(textureKeyName); + std::string key = textureKeyName; + auto it = _textures.find(key); if (it == _textures.end()) { - auto key = FileUtils::getInstance()->fullPathForFilename(textureKeyName); - it = _textures.find(key); + key = FileUtils::getInstance()->fullPathForFilename(textureKeyName); + it = _textures.find(key); } if (it != _textures.end()) @@ -603,14 +603,15 @@ void TextureCache::removeTextureForKey(std::string_view textureKeyName) } } -Texture2D* TextureCache::getTextureForKey(std::string_view textureKeyName) const +Texture2D* TextureCache::getTextureForKey(const std::string& textureKeyName) const { - auto it = _textures.find(textureKeyName); + std::string key = textureKeyName; + auto it = _textures.find(key); if (it == _textures.end()) { - auto key = FileUtils::getInstance()->fullPathForFilename(textureKeyName); - it = _textures.find(key); + key = FileUtils::getInstance()->fullPathForFilename(textureKeyName); + it = _textures.find(key); } if (it != _textures.end()) @@ -675,14 +676,15 @@ std::string TextureCache::getCachedTextureInfo() const return buffer; } -void TextureCache::renameTextureWithKey(std::string_view srcName, std::string_view dstName) +void TextureCache::renameTextureWithKey(const std::string& srcName, const std::string& dstName) { - auto it = _textures.find(srcName); + std::string key = srcName; + auto it = _textures.find(key); if (it == _textures.end()) { - auto key = FileUtils::getInstance()->fullPathForFilename(srcName); - it = _textures.find(key); + key = FileUtils::getInstance()->fullPathForFilename(srcName); + it = _textures.find(key); } if (it != _textures.end()) @@ -721,7 +723,7 @@ VolatileTexture::~VolatileTexture() CC_SAFE_RELEASE(_uiImage); } -void VolatileTextureMgr::addImageTexture(Texture2D* tt, std::string_view imageFileName) +void VolatileTextureMgr::addImageTexture(Texture2D* tt, const std::string& imageFileName) { if (_isReloading) { @@ -864,7 +866,9 @@ void VolatileTextureMgr::reloadAllTextures() _isReloading = false; } -void VolatileTextureMgr::reloadTexture(Texture2D* texture, std::string_view filename, backend::PixelFormat pixelFormat) +void VolatileTextureMgr::reloadTexture(Texture2D* texture, + const std::string& filename, + backend::PixelFormat pixelFormat) { if (!texture) return; diff --git a/cocos/renderer/CCTextureCache.h b/cocos/renderer/CCTextureCache.h index f066436758..2aca398feb 100644 --- a/cocos/renderer/CCTextureCache.h +++ b/cocos/renderer/CCTextureCache.h @@ -64,7 +64,7 @@ class CC_DLL TextureCache : public Ref { public: // ETC1 ALPHA supports. - static void setETC1AlphaFileSuffix(std::string_view suffix); + static void setETC1AlphaFileSuffix(const std::string& suffix); static std::string getETC1AlphaFileSuffix(); public: @@ -92,7 +92,7 @@ public: * Supported image extensions: .png, .bmp, .jpeg, .pvr. @param filepath The file path. */ - Texture2D* addImage(std::string_view filepath); + Texture2D* addImage(const std::string& filepath); /** Returns a Texture2D object given a file image. * If the file image was not previously loaded, it will create a new Texture2D object and it will return it. @@ -104,11 +104,11 @@ public: @param callback A callback function would be invoked after the image is loaded. @since v0.8 */ - virtual void addImageAsync(std::string_view filepath, const std::function& callback); + virtual void addImageAsync(const std::string& filepath, const std::function& callback); - void addImageAsync(std::string_view path, + void addImageAsync(const std::string& path, const std::function& callback, - std::string_view callbackKey); + const std::string& callbackKey); /** Unbind a specified bound image asynchronous callback. * In the case an object who was bound to an image asynchronous callback was destroyed before the callback is @@ -116,7 +116,7 @@ public: * @param filename It's the related/absolute path of the file image. * @since v3.1 */ - virtual void unbindImageAsync(std::string_view filename); + virtual void unbindImageAsync(const std::string& filename); /** Unbind all bound image asynchronous load callbacks. * @since v3.1 @@ -129,13 +129,13 @@ public: * @param key The "key" parameter will be used as the "key" for the cache. * If "key" is nil, then a new texture will be created each time. */ - Texture2D* addImage(Image* image, std::string_view key); + Texture2D* addImage(Image* image, const std::string& key); /** Returns an already created texture. Returns nil if the texture doesn't exist. @param key It's the related/absolute path of the file image. @since v0.99.5 */ - Texture2D* getTextureForKey(std::string_view key) const; + Texture2D* getTextureForKey(const std::string& key) const; /** Reload texture from the image file. * If the file image hasn't loaded before, load it. @@ -143,7 +143,7 @@ public: * @param fileName It's the related/absolute path of the file image. * @return True if the reloading is succeed, otherwise return false. */ - bool reloadTexture(std::string_view fileName); + bool reloadTexture(const std::string& fileName); /** Purges the dictionary of loaded textures. * Call this method if you receive the "Memory Warning". @@ -168,7 +168,7 @@ public: @param key It's the related/absolute path of the file image. @since v0.99.4 */ - void removeTextureForKey(std::string_view key); + void removeTextureForKey(const std::string& key); /** Output to CCLOG the current contents of this TextureCache. * This will attempt to calculate the size of each texture, and the total texture memory in use. @@ -198,12 +198,12 @@ public: * * @since v3.10 */ - void renameTextureWithKey(std::string_view srcName, std::string_view dstName); + void renameTextureWithKey(const std::string& srcName, const std::string& dstName); private: void addImageAsyncCallBack(float dt); void loadImage(); - void parseNinePatchImage(Image* image, Texture2D* texture, std::string_view path); + void parseNinePatchImage(Image* image, Texture2D* texture, const std::string& path); public: protected: @@ -224,7 +224,7 @@ protected: int _asyncRefCount; - hlookup::string_map _textures; + std::unordered_map _textures; static std::string s_etc1AlphaFileSuffix; }; @@ -272,7 +272,7 @@ protected: class CC_DLL VolatileTextureMgr { public: - static void addImageTexture(Texture2D* tt, std::string_view imageFileName); + static void addImageTexture(Texture2D* tt, const std::string& imageFileName); static void addStringTexture(Texture2D* tt, const char* text, const FontDefinition& fontDefinition); static void addDataTexture(Texture2D* tt, void* data, @@ -292,7 +292,7 @@ public: static VolatileTexture* findVolotileTexture(Texture2D* tt); private: - static void reloadTexture(Texture2D* texture, std::string_view filename, backend::PixelFormat pixelFormat); + static void reloadTexture(Texture2D* texture, const std::string& filename, backend::PixelFormat pixelFormat); }; #endif diff --git a/cocos/renderer/CCTextureCube.cpp b/cocos/renderer/CCTextureCube.cpp index 9a757b2264..d7a7929cb4 100644 --- a/cocos/renderer/CCTextureCube.cpp +++ b/cocos/renderer/CCTextureCube.cpp @@ -119,7 +119,7 @@ unsigned char* getImageData(Image* img, backend::PixelFormat& ePixFmt) return pTmpData; } -Image* createImage(std::string_view path) +Image* createImage(const std::string& path) { // Split up directory and filename // MUTEX: @@ -150,12 +150,12 @@ TextureCube::~TextureCube() CC_SAFE_RELEASE_NULL(_texture); } -TextureCube* TextureCube::create(std::string_view positive_x, - std::string_view negative_x, - std::string_view positive_y, - std::string_view negative_y, - std::string_view positive_z, - std::string_view negative_z) +TextureCube* TextureCube::create(const std::string& positive_x, + const std::string& negative_x, + const std::string& positive_y, + const std::string& negative_y, + const std::string& positive_z, + const std::string& negative_z) { auto ret = new TextureCube(); if (ret->init(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z)) @@ -167,12 +167,12 @@ TextureCube* TextureCube::create(std::string_view positive_x, return nullptr; } -bool TextureCube::init(std::string_view positive_x, - std::string_view negative_x, - std::string_view positive_y, - std::string_view negative_y, - std::string_view positive_z, - std::string_view negative_z) +bool TextureCube::init(const std::string& positive_x, + const std::string& negative_x, + const std::string& positive_y, + const std::string& negative_y, + const std::string& positive_z, + const std::string& negative_z) { _imgPath[0] = positive_x; _imgPath[1] = negative_x; diff --git a/cocos/renderer/CCTextureCube.h b/cocos/renderer/CCTextureCube.h index 578c32ecca..99ee3f1c3e 100644 --- a/cocos/renderer/CCTextureCube.h +++ b/cocos/renderer/CCTextureCube.h @@ -56,12 +56,12 @@ public: @param negative_z texture for the rear side of the texture cube face. @return A new texture cube inited with given parameters. */ - static TextureCube* create(std::string_view positive_x, - std::string_view negative_x, - std::string_view positive_y, - std::string_view negative_y, - std::string_view positive_z, - std::string_view negative_z); + static TextureCube* create(const std::string& positive_x, + const std::string& negative_x, + const std::string& positive_y, + const std::string& negative_y, + const std::string& positive_z, + const std::string& negative_z); /** Sets the min filter, mag filter, wrap s and wrap t texture parameters. If the texture size is NPOT (non power of 2), then in can only use GL_CLAMP_TO_EDGE in GL_TEXTURE_WRAP_{S,T}. @@ -86,12 +86,12 @@ public: virtual ~TextureCube(); protected: - bool init(std::string_view positive_x, - std::string_view negative_x, - std::string_view positive_y, - std::string_view negative_y, - std::string_view positive_z, - std::string_view negative_z); + bool init(const std::string& positive_x, + const std::string& negative_x, + const std::string& positive_y, + const std::string& negative_y, + const std::string& positive_z, + const std::string& negative_z); private: std::vector _imgPath; diff --git a/cocos/renderer/backend/Device.h b/cocos/renderer/backend/Device.h index 27a498e334..fbf8934bc5 100644 --- a/cocos/renderer/backend/Device.h +++ b/cocos/renderer/backend/Device.h @@ -125,7 +125,7 @@ public: * @param fragmentShader Specifes this is a fragment shader source. * @return A Program instance. */ - virtual Program* newProgram(std::string_view vertexShader, std::string_view fragmentShader) = 0; + virtual Program* newProgram(const std::string& vertexShader, const std::string& fragmentShader) = 0; /** * Get a DeviceInfo object. @@ -140,7 +140,7 @@ protected: * @param source Specifies shader source. * @return A ShaderModule object. */ - virtual ShaderModule* newShaderModule(ShaderStage stage, std::string_view source) = 0; + virtual ShaderModule* newShaderModule(ShaderStage stage, const std::string& source) = 0; DeviceInfo* _deviceInfo = nullptr; ///< Device information. diff --git a/cocos/renderer/backend/Program.cpp b/cocos/renderer/backend/Program.cpp index b92ab3d0b2..4c3da6cfaa 100644 --- a/cocos/renderer/backend/Program.cpp +++ b/cocos/renderer/backend/Program.cpp @@ -27,7 +27,7 @@ CC_BACKEND_BEGIN -Program::Program(std::string_view vs, std::string_view fs) : _vertexShader(vs), _fragmentShader(fs) {} +Program::Program(const std::string& vs, const std::string& fs) : _vertexShader(vs), _fragmentShader(fs) {} void Program::setProgramType(uint32_t type) { diff --git a/cocos/renderer/backend/Program.h b/cocos/renderer/backend/Program.h index fceb28f8f4..3cc20bdf21 100644 --- a/cocos/renderer/backend/Program.h +++ b/cocos/renderer/backend/Program.h @@ -60,7 +60,7 @@ public: * @param uniform Specifies the uniform name. * @return The uniform location. */ - virtual UniformLocation getUniformLocation(std::string_view uniform) const = 0; + virtual UniformLocation getUniformLocation(const std::string& uniform) const = 0; /** * Get uniform location by engine built-in uniform enum name. @@ -74,7 +74,7 @@ public: * @param name Specifies the attribute name. * @return The attribute location. */ - virtual int getAttributeLocation(std::string_view name) const = 0; + virtual int getAttributeLocation(const std::string& name) const = 0; /** * Get attribute location by engine built-in attribute enum name. @@ -99,19 +99,19 @@ public: * Get active vertex attributes. * @return Active vertex attributes. key is active attribute name, Value is corresponding attribute info. */ - virtual const hlookup::string_map getActiveAttributes() const = 0; + virtual const std::unordered_map getActiveAttributes() const = 0; /** * Get vertex shader. * @return Vertex shader. */ - std::string_view getVertexShader() const { return _vertexShader; } + const std::string& getVertexShader() const { return _vertexShader; } /** * Get fragment shader. * @ Fragment shader. */ - std::string_view getFragmentShader() const { return _fragmentShader; } + const std::string& getFragmentShader() const { return _fragmentShader; } /** * Get engine built-in program type. @@ -138,7 +138,7 @@ public: * Get all uniformInfos. * @return The uniformInfos. */ - virtual const hlookup::string_map& getAllActiveUniformInfo(ShaderStage stage) const = 0; + virtual const std::unordered_map& getAllActiveUniformInfo(ShaderStage stage) const = 0; /** * Set engin built-in program type. @@ -151,7 +151,7 @@ protected: * @param vs Specifes the vertex shader source. * @param fs Specifes the fragment shader source. */ - Program(std::string_view vs, std::string_view fs); + Program(const std::string& vs, const std::string& fs); #if CC_ENABLE_CACHE_TEXTURE_DATA /** diff --git a/cocos/renderer/backend/ProgramState.cpp b/cocos/renderer/backend/ProgramState.cpp index 79e036e3e0..8eacbc2bb6 100644 --- a/cocos/renderer/backend/ProgramState.cpp +++ b/cocos/renderer/backend/ProgramState.cpp @@ -263,7 +263,7 @@ backend::UniformLocation ProgramState::getUniformLocation(backend::Uniform name) return _program->getUniformLocation(name); } -backend::UniformLocation ProgramState::getUniformLocation(std::string_view uniform) const +backend::UniformLocation ProgramState::getUniformLocation(const std::string& uniform) const { return _program->getUniformLocation(uniform); } @@ -514,13 +514,13 @@ void ProgramState::setTextureArray(int location, #endif } -void ProgramState::setParameterAutoBinding(std::string_view uniform, std::string_view autoBinding) +void ProgramState::setParameterAutoBinding(const std::string& uniform, const std::string& autoBinding) { _autoBindings.emplace(uniform, autoBinding); applyAutoBinding(uniform, autoBinding); } -void ProgramState::applyAutoBinding(std::string_view uniformName, std::string_view autoBinding) +void ProgramState::applyAutoBinding(const std::string& uniformName, const std::string& autoBinding) { for (const auto resolver : _customAutoBindingResolvers) { diff --git a/cocos/renderer/backend/ProgramState.h b/cocos/renderer/backend/ProgramState.h index 8c31ca9685..7a5f756e61 100644 --- a/cocos/renderer/backend/ProgramState.h +++ b/cocos/renderer/backend/ProgramState.h @@ -124,7 +124,7 @@ public: * @return Uniform location. * @see `backend::UniformLocation getUniformLocation(backend::Uniform name) const` */ - backend::UniformLocation getUniformLocation(std::string_view uniform) const; + backend::UniformLocation getUniformLocation(const std::string& uniform) const; /** * Get uniform location in a more efficient way by the given built-in uniform name. @@ -138,15 +138,15 @@ public: * Get an attribute location by the actual attribute name. * @param name Specifies the attribute name. * @return Attribute location. - * @see `int getAttributeLocation(std::string_view name) const` + * @see `int getAttributeLocation(const std::string& name) const` */ - inline int getAttributeLocation(std::string_view name) const { return _program->getAttributeLocation(name); } + inline int getAttributeLocation(const std::string& name) const { return _program->getAttributeLocation(name); } /** * Get an attribute location by the engine built-in attribute name. * @param name Specifies the built-in attribute name. * @return Attribute location. - * @see `int getAttributeLocation(std::string_view name) const` + * @see `int getAttributeLocation(const std::string& name) const` */ inline int getAttributeLocation(Attribute name) const { return _program->getAttributeLocation(name); } @@ -278,7 +278,9 @@ public: * @return True if the auto binding is handled and the associated parameter is * bound, false otherwise. */ - virtual bool resolveAutoBinding(ProgramState*, std::string_view uniformName, std::string_view autoBinding) = 0; + virtual bool resolveAutoBinding(ProgramState*, + const std::string& uniformName, + const std::string& autoBinding) = 0; }; /** * Sets a uniform auto-binding. @@ -290,7 +292,7 @@ public: * @param uniformName The name of the material parameter to store an auto-binding for. * @param autoBinding A string matching one of the built-in AutoBinding enum constants. */ - void setParameterAutoBinding(std::string_view uniformName, std::string_view autoBinding); + void setParameterAutoBinding(const std::string& uniformName, const std::string& autoBinding); inline std::shared_ptr getVertexLayout() const { return _vertexLayout; } @@ -377,7 +379,7 @@ protected: * @param uniformName Name of the shader uniform. * @param autoBinding Name of the auto binding. */ - void applyAutoBinding(std::string_view, std::string_view); + void applyAutoBinding(const std::string&, const std::string&); backend::Program* _program = nullptr; std::unordered_map _callbackUniforms; diff --git a/cocos/renderer/backend/ShaderCache.cpp b/cocos/renderer/backend/ShaderCache.cpp index 149fc2fcb7..7d92c21ba7 100644 --- a/cocos/renderer/backend/ShaderCache.cpp +++ b/cocos/renderer/backend/ShaderCache.cpp @@ -62,21 +62,21 @@ bool ShaderCache::init() return true; } -backend::ShaderModule* ShaderCache::newVertexShaderModule(std::string_view shaderSource) +backend::ShaderModule* ShaderCache::newVertexShaderModule(const std::string& shaderSource) { auto vertexShaderModule = newShaderModule(backend::ShaderStage::VERTEX, shaderSource); return vertexShaderModule; } -backend::ShaderModule* ShaderCache::newFragmentShaderModule(std::string_view shaderSource) +backend::ShaderModule* ShaderCache::newFragmentShaderModule(const std::string& shaderSource) { auto fragmenShaderModule = newShaderModule(backend::ShaderStage::FRAGMENT, shaderSource); return fragmenShaderModule; } -backend::ShaderModule* ShaderCache::newShaderModule(backend::ShaderStage stage, std::string_view shaderSource) +backend::ShaderModule* ShaderCache::newShaderModule(backend::ShaderStage stage, const std::string& shaderSource) { - std::size_t key = std::hash{}(shaderSource); + std::size_t key = std::hash{}(shaderSource); auto iter = _cachedShaders.find(key); if (_cachedShaders.end() != iter) return iter->second; diff --git a/cocos/renderer/backend/ShaderCache.h b/cocos/renderer/backend/ShaderCache.h index 87709042f5..d5daf870ae 100644 --- a/cocos/renderer/backend/ShaderCache.h +++ b/cocos/renderer/backend/ShaderCache.h @@ -54,14 +54,14 @@ public: * If it is created before, then just return the cached shader module. * @param shaderSource The source code of the shader. */ - static backend::ShaderModule* newVertexShaderModule(std::string_view shaderSource); + static backend::ShaderModule* newVertexShaderModule(const std::string& shaderSource); /** * Create a fragment shader module. * If it is created before, then just return the cached shader module. * @param shaderSource The source code of the shader. */ - static backend::ShaderModule* newFragmentShaderModule(std::string_view shaderSource); + static backend::ShaderModule* newFragmentShaderModule(const std::string& shaderSource); /** * Remove all unused shaders. @@ -85,7 +85,7 @@ protected: * @param source Specifies shader source. * @return A ShaderModule object. */ - static backend::ShaderModule* newShaderModule(backend::ShaderStage stage, std::string_view shaderSource); + static backend::ShaderModule* newShaderModule(backend::ShaderStage stage, const std::string& shaderSource); static std::unordered_map _cachedShaders; static ShaderCache* _sharedShaderCache; diff --git a/cocos/renderer/backend/VertexLayout.cpp b/cocos/renderer/backend/VertexLayout.cpp index fbd4be4d3e..044a2661c0 100644 --- a/cocos/renderer/backend/VertexLayout.cpp +++ b/cocos/renderer/backend/VertexLayout.cpp @@ -28,7 +28,7 @@ CC_BACKEND_BEGIN -void VertexLayout::setAttribute(std::string_view name, +void VertexLayout::setAttribute(const std::string& name, std::size_t index, VertexFormat format, std::size_t offset, @@ -37,11 +37,7 @@ void VertexLayout::setAttribute(std::string_view name, if (index == -1) return; - // FIXME 2021/12/25 TODO: store name key is enough - hlookup::set_item( - _attributes, name, - Attribute{name, index, format, offset, - needToBeNormallized}); // _attributes[name] = {name, index, format, offset, needToBeNormallized}; + _attributes[name] = {name, index, format, offset, needToBeNormallized}; } void VertexLayout::setLayout(std::size_t stride) diff --git a/cocos/renderer/backend/VertexLayout.h b/cocos/renderer/backend/VertexLayout.h index 3c11bf49f3..e3b33746e4 100644 --- a/cocos/renderer/backend/VertexLayout.h +++ b/cocos/renderer/backend/VertexLayout.h @@ -48,7 +48,7 @@ public: struct Attribute { Attribute() = default; - Attribute(std::string_view _name, + Attribute(const std::string& _name, std::size_t _index, VertexFormat _format, std::size_t _offset, @@ -74,7 +74,7 @@ public: * @param needToBeNormallized Specifies whether fixed-point data values should be normalized (true) or converted * directly as fixed-point values (false) when they are accessed. */ - void setAttribute(std::string_view name, + void setAttribute(const std::string& name, std::size_t index, VertexFormat format, std::size_t offset, @@ -103,7 +103,7 @@ public: * Get attribute informations * @return Atrribute informations. */ - inline const hlookup::string_map& getAttributes() const { return _attributes; } + inline const std::unordered_map& getAttributes() const { return _attributes; } /** * Check if vertex layout has been set. @@ -111,7 +111,7 @@ public: inline bool isValid() const { return _stride != 0; } private: - hlookup::string_map _attributes; + std::unordered_map _attributes; std::size_t _stride = 0; VertexStepMode _stepMode = VertexStepMode::VERTEX; }; diff --git a/cocos/renderer/backend/metal/BufferMTL.mm b/cocos/renderer/backend/metal/BufferMTL.mm index fb336acfd5..9abe3d62a4 100644 --- a/cocos/renderer/backend/metal/BufferMTL.mm +++ b/cocos/renderer/backend/metal/BufferMTL.mm @@ -21,7 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "BufferMTL.h" #include "../Macros.h" #include "BufferManager.h" @@ -29,15 +29,15 @@ CC_BACKEND_BEGIN BufferMTL::BufferMTL(id mtlDevice, std::size_t size, BufferType type, BufferUsage usage) - : Buffer(size, type, usage) +: Buffer(size, type, usage) { if (BufferUsage::DYNAMIC == usage) { - NSMutableArray* mutableDynamicDataBuffers = [NSMutableArray arrayWithCapacity:MAX_INFLIGHT_BUFFER]; + NSMutableArray *mutableDynamicDataBuffers = [NSMutableArray arrayWithCapacity:MAX_INFLIGHT_BUFFER]; for (int i = 0; i < MAX_INFLIGHT_BUFFER; ++i) { // Create a new buffer with enough capacity to store one instance of the dynamic buffer data - id dynamicDataBuffer = [mtlDevice newBufferWithLength:size options:MTLResourceStorageModeShared]; + id dynamicDataBuffer = [mtlDevice newBufferWithLength:size options:MTLResourceStorageModeShared]; [mutableDynamicDataBuffers addObject:dynamicDataBuffer]; } _dynamicDataBuffers = [mutableDynamicDataBuffers copy]; @@ -97,8 +97,8 @@ void BufferMTL::updateIndex() if (BufferUsage::DYNAMIC == _usage && !_indexUpdated) { _currentFrameIndex = (_currentFrameIndex + 1) % MAX_INFLIGHT_BUFFER; - _mtlBuffer = _dynamicDataBuffers[_currentFrameIndex]; - _indexUpdated = true; + _mtlBuffer = _dynamicDataBuffers[_currentFrameIndex]; + _indexUpdated = true; } } diff --git a/cocos/renderer/backend/metal/BufferManager.mm b/cocos/renderer/backend/metal/BufferManager.mm index 0fae9871b2..22776b4799 100644 --- a/cocos/renderer/backend/metal/BufferManager.mm +++ b/cocos/renderer/backend/metal/BufferManager.mm @@ -21,7 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "BufferManager.h" #include "BufferMTL.h" diff --git a/cocos/renderer/backend/metal/CommandBufferMTL.mm b/cocos/renderer/backend/metal/CommandBufferMTL.mm index 3d881af178..0490fa5624 100644 --- a/cocos/renderer/backend/metal/CommandBufferMTL.mm +++ b/cocos/renderer/backend/metal/CommandBufferMTL.mm @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "CommandBufferMTL.h" #include "BufferMTL.h" #include "DeviceMTL.h" @@ -39,131 +39,130 @@ CC_BACKEND_BEGIN namespace { -#define byte(n) ((n)*8) +#define byte(n) ((n) * 8) #define bit(n) (n) -static uint8_t getBitsPerElementMTL(MTLPixelFormat pixleFormat) -{ - switch (pixleFormat) + static uint8_t getBitsPerElementMTL(MTLPixelFormat pixleFormat) { - case MTLPixelFormatDepth32Float_Stencil8: - return byte(8); - case MTLPixelFormatBGRA8Unorm: - case MTLPixelFormatRGBA8Unorm: - case MTLPixelFormatDepth32Float: - return byte(4); -#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) - case MTLPixelFormatDepth24Unorm_Stencil8: - return byte(4); -#else - case MTLPixelFormatABGR4Unorm: - case MTLPixelFormatBGR5A1Unorm: - case MTLPixelFormatB5G6R5Unorm: - case MTLPixelFormatA1BGR5Unorm: - return byte(2); -#endif - case MTLPixelFormatA8Unorm: - case MTLPixelFormatR8Unorm: - return byte(1); - default: - assert(false); - break; + switch (pixleFormat) + { + case MTLPixelFormatDepth32Float_Stencil8: + return byte(8); + case MTLPixelFormatBGRA8Unorm: + case MTLPixelFormatRGBA8Unorm: + case MTLPixelFormatDepth32Float: + return byte(4); + #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) + case MTLPixelFormatDepth24Unorm_Stencil8: + return byte(4); + #else + case MTLPixelFormatABGR4Unorm: + case MTLPixelFormatBGR5A1Unorm: + case MTLPixelFormatB5G6R5Unorm: + case MTLPixelFormatA1BGR5Unorm: + return byte(2); + #endif + case MTLPixelFormatA8Unorm: + case MTLPixelFormatR8Unorm: + return byte(1); + default: + assert(false); + break; + } + return 0; } - return 0; -} -static MTLWinding toMTLWinding(Winding winding) -{ - if (Winding::CLOCK_WISE == winding) - return MTLWindingClockwise; - else - return MTLWindingCounterClockwise; -} - -static MTLPrimitiveType toMTLPrimitive(PrimitiveType primitiveType) -{ - MTLPrimitiveType ret = MTLPrimitiveTypeTriangle; - switch (primitiveType) + static MTLWinding toMTLWinding(Winding winding) { - case PrimitiveType::POINT: - ret = MTLPrimitiveTypePoint; - break; - case PrimitiveType::LINE: - ret = MTLPrimitiveTypeLine; - break; - case PrimitiveType::LINE_STRIP: - ret = MTLPrimitiveTypeLineStrip; - break; - case PrimitiveType::TRIANGLE: - ret = MTLPrimitiveTypeTriangle; - break; - case PrimitiveType::TRIANGLE_STRIP: - ret = MTLPrimitiveTypeTriangleStrip; - break; - default: - break; + if (Winding::CLOCK_WISE == winding) + return MTLWindingClockwise; + else + return MTLWindingCounterClockwise; } - return ret; -} -static MTLIndexType toMTLIndexType(IndexFormat indexFormat) -{ - if (IndexFormat::U_SHORT == indexFormat) - return MTLIndexTypeUInt16; - else - return MTLIndexTypeUInt32; -} - -static MTLCullMode toMTLCullMode(CullMode mode) -{ - switch (mode) + static MTLPrimitiveType toMTLPrimitive(PrimitiveType primitiveType) { - case CullMode::NONE: - return MTLCullModeNone; - case CullMode::FRONT: - return MTLCullModeFront; - case CullMode::BACK: - return MTLCullModeBack; + MTLPrimitiveType ret = MTLPrimitiveTypeTriangle; + switch (primitiveType) + { + case PrimitiveType::POINT: + ret = MTLPrimitiveTypePoint; + break; + case PrimitiveType::LINE: + ret = MTLPrimitiveTypeLine; + break; + case PrimitiveType::LINE_STRIP: + ret = MTLPrimitiveTypeLineStrip; + break; + case PrimitiveType::TRIANGLE: + ret = MTLPrimitiveTypeTriangle; + break; + case PrimitiveType::TRIANGLE_STRIP: + ret = MTLPrimitiveTypeTriangleStrip; + break; + default: + break; + } + return ret; } -} - -static MTLRenderPassDescriptor* toMTLRenderPassDescriptor(const RenderTarget* rt, const RenderPassDescriptor& desc) -{ - MTLRenderPassDescriptor* mtlDescritpor = [MTLRenderPassDescriptor renderPassDescriptor]; - - auto rtMTL = static_cast(rt); - rtMTL->applyRenderPassAttachments(desc, mtlDescritpor); - return mtlDescritpor; -} - -static id getMTLTexture(TextureBackend* texture, int index) -{ - return reinterpret_cast>(texture->getHandler(index)); -} - -static id getMTLSamplerState(TextureBackend* texture) -{ - switch (texture->getTextureType()) + + static MTLIndexType toMTLIndexType(IndexFormat indexFormat) { - case TextureType::TEXTURE_2D: - return static_cast(texture)->getMTLSamplerState(); - case TextureType::TEXTURE_CUBE: - return static_cast(texture)->getMTLSamplerState(); - default: - assert(false); - return nil; + if (IndexFormat::U_SHORT == indexFormat) + return MTLIndexTypeUInt16; + else + return MTLIndexTypeUInt32; + } + + static MTLCullMode toMTLCullMode(CullMode mode) + { + switch (mode) { + case CullMode::NONE: + return MTLCullModeNone; + case CullMode::FRONT: + return MTLCullModeFront; + case CullMode::BACK: + return MTLCullModeBack; + } + } + + static MTLRenderPassDescriptor* toMTLRenderPassDescriptor(const RenderTarget* rt, const RenderPassDescriptor& desc) + { + MTLRenderPassDescriptor* mtlDescritpor = [MTLRenderPassDescriptor renderPassDescriptor]; + + auto rtMTL = static_cast(rt); + rtMTL->applyRenderPassAttachments(desc, mtlDescritpor); + return mtlDescritpor; + } + + static id getMTLTexture(TextureBackend* texture, int index) + { + return reinterpret_cast>(texture->getHandler(index)); + } + + static id getMTLSamplerState(TextureBackend* texture) + { + switch (texture->getTextureType()) + { + case TextureType::TEXTURE_2D: + return static_cast(texture)->getMTLSamplerState(); + case TextureType::TEXTURE_CUBE: + return static_cast(texture)->getMTLSamplerState(); + default: + assert(false); + return nil; + } } -} -inline int clamp(int value, int min, int max) -{ - return std::min(max, std::max(min, value)); -} + inline int clamp(int value, int min, int max) { + return std::min(max, std::max(min, value)); + } } CommandBufferMTL::CommandBufferMTL(DeviceMTL* deviceMTL) - : _mtlCommandQueue(deviceMTL->getMTLCommandQueue()) - , _frameBoundarySemaphore(dispatch_semaphore_create(MAX_INFLIGHT_BUFFER)) -{} +: _mtlCommandQueue(deviceMTL->getMTLCommandQueue()) +, _frameBoundarySemaphore(dispatch_semaphore_create(MAX_INFLIGHT_BUFFER)) +{ +} CommandBufferMTL::~CommandBufferMTL() { @@ -172,7 +171,7 @@ CommandBufferMTL::~CommandBufferMTL() id oneOffBuffer = [_mtlCommandQueue commandBuffer]; [oneOffBuffer commit]; [oneOffBuffer waitUntilCompleted]; - + dispatch_semaphore_signal(_frameBoundarySemaphore); } @@ -200,37 +199,38 @@ bool CommandBufferMTL::beginFrame() return true; } -void CommandBufferMTL::updateRenderCommandEncoder(const RenderTarget* renderTarget, - const RenderPassDescriptor& renderPassDesc) +void CommandBufferMTL::updateRenderCommandEncoder(const RenderTarget* renderTarget, const RenderPassDescriptor& renderPassDesc) { - if (_mtlRenderEncoder != nil && _currentRenderPassDesc == renderPassDesc && _currentRenderTarget == renderTarget && - _currentRenderTargetFlags == renderTarget->getTargetFlags()) + if(_mtlRenderEncoder != nil && + _currentRenderPassDesc == renderPassDesc && + _currentRenderTarget == renderTarget && + _currentRenderTargetFlags == renderTarget->getTargetFlags()) { return _mtlRenderEncoder; } - - _currentRenderTarget = renderTarget; - _currentRenderPassDesc = renderPassDesc; + + _currentRenderTarget = renderTarget; + _currentRenderPassDesc = renderPassDesc; _currentRenderTargetFlags = renderTarget->getTargetFlags(); - - if (_mtlRenderEncoder != nil) + + if(_mtlRenderEncoder != nil) { [_mtlRenderEncoder endEncoding]; [_mtlRenderEncoder release]; _mtlRenderEncoder = nil; } - auto mtlDescriptor = toMTLRenderPassDescriptor(renderTarget, renderPassDesc); - _renderTargetWidth = (unsigned int)mtlDescriptor.colorAttachments[0].texture.width; + auto mtlDescriptor = toMTLRenderPassDescriptor(renderTarget, renderPassDesc); + _renderTargetWidth = (unsigned int)mtlDescriptor.colorAttachments[0].texture.width; _renderTargetHeight = (unsigned int)mtlDescriptor.colorAttachments[0].texture.height; - _mtlRenderEncoder = [_mtlCommandBuffer renderCommandEncoderWithDescriptor:mtlDescriptor]; + _mtlRenderEncoder = [_mtlCommandBuffer renderCommandEncoderWithDescriptor:mtlDescriptor]; [_mtlRenderEncoder retain]; } void CommandBufferMTL::beginRenderPass(const RenderTarget* renderTarget, const RenderPassDescriptor& renderPassDesc) { updateRenderCommandEncoder(renderTarget, renderPassDesc); - // [_mtlRenderEncoder setFrontFacingWinding:MTLWindingCounterClockwise]; +// [_mtlRenderEncoder setFrontFacingWinding:MTLWindingCounterClockwise]; } void CommandBufferMTL::updateDepthStencilState(const DepthStencilDescriptor& descriptor) @@ -249,10 +249,10 @@ void CommandBufferMTL::setViewport(int x, int y, unsigned int w, unsigned int h) MTLViewport viewport; viewport.originX = x; viewport.originY = (int)(_renderTargetHeight - y - h); - viewport.width = w; - viewport.height = h; - viewport.znear = 0; - viewport.zfar = 1; + viewport.width = w; + viewport.height = h; + viewport.znear = 0; + viewport.zfar = 1; [_mtlRenderEncoder setViewport:viewport]; } @@ -269,7 +269,9 @@ void CommandBufferMTL::setWinding(Winding winding) void CommandBufferMTL::setVertexBuffer(Buffer* buffer) { // Vertex buffer is bound in index 0. - [_mtlRenderEncoder setVertexBuffer:static_cast(buffer)->getMTLBuffer() offset:0 atIndex:0]; + [_mtlRenderEncoder setVertexBuffer:static_cast(buffer)->getMTLBuffer() + offset:0 + atIndex:0]; } void CommandBufferMTL::setProgramState(ProgramState* programState) @@ -284,21 +286,20 @@ void CommandBufferMTL::setIndexBuffer(Buffer* buffer) assert(buffer != nullptr); if (!buffer) return; - + _mtlIndexBuffer = static_cast(buffer)->getMTLBuffer(); [_mtlIndexBuffer retain]; } -void CommandBufferMTL::drawArrays(PrimitiveType primitiveType, std::size_t start, std::size_t count) +void CommandBufferMTL::drawArrays(PrimitiveType primitiveType, std::size_t start, std::size_t count) { prepareDrawing(); - [_mtlRenderEncoder drawPrimitives:toMTLPrimitive(primitiveType) vertexStart:start vertexCount:count]; + [_mtlRenderEncoder drawPrimitives:toMTLPrimitive(primitiveType) + vertexStart:start + vertexCount:count]; } -void CommandBufferMTL::drawElements(PrimitiveType primitiveType, - IndexFormat indexType, - std::size_t count, - std::size_t offset) +void CommandBufferMTL::drawElements(PrimitiveType primitiveType, IndexFormat indexType, std::size_t count, std::size_t offset) { prepareDrawing(); [_mtlRenderEncoder drawIndexedPrimitives:toMTLPrimitive(primitiveType) @@ -306,6 +307,7 @@ void CommandBufferMTL::drawElements(PrimitiveType primitiveType, indexType:toMTLIndexType(indexType) indexBuffer:_mtlIndexBuffer indexBufferOffset:offset]; + } void CommandBufferMTL::endRenderPass() @@ -316,7 +318,7 @@ void CommandBufferMTL::endRenderPass() void CommandBufferMTL::readPixels(RenderTarget* rt, std::function callback) { auto rtMTL = static_cast(rt); - + // we only read form color attachment 0 // if it's nullptr, will regard as screen to perform capture auto texture = rtMTL->_color[0].texture; @@ -329,14 +331,14 @@ void CommandBufferMTL::endFrame() [_mtlRenderEncoder endEncoding]; [_mtlRenderEncoder release]; _mtlRenderEncoder = nil; - + auto currentDrawable = DeviceMTL::getCurrentDrawable(); [_mtlCommandBuffer presentDrawable:currentDrawable]; _drawableTexture = currentDrawable.texture; [_mtlCommandBuffer addCompletedHandler:^(id commandBuffer) { - // GPU work is complete - // Signal the semaphore to start the CPU work - dispatch_semaphore_signal(_frameBoundarySemaphore); + // GPU work is complete + // Signal the semaphore to start the CPU work + dispatch_semaphore_signal(_frameBoundarySemaphore); }]; flush(); @@ -347,13 +349,12 @@ void CommandBufferMTL::endFrame() void CommandBufferMTL::flush() { - if (_mtlCommandBuffer) - { + if(_mtlCommandBuffer) { assert(_mtlCommandBuffer.status != MTLCommandBufferStatusCommitted); [_mtlCommandBuffer commit]; - + flushCaptureCommands(); - + [_mtlCommandBuffer release]; _mtlCommandBuffer = nil; } @@ -361,30 +362,24 @@ void CommandBufferMTL::flush() void CommandBufferMTL::flushCaptureCommands() { - if (!_captureCallbacks.empty()) - { + if(!_captureCallbacks.empty()) { // !!!important, if have capture request, must wait pending commandBuffer finish at this frame, // because readPixels require sync operation to get screen pixels properly without data race issue, // otherwise, will lead dead-lock // !!!Notes, MTL is mutli-threading, all GPU handler is dispatch at GPU threads [_mtlCommandBuffer waitUntilCompleted]; - + PixelBufferDescriptor screenPixelData; - for (auto& cb : _captureCallbacks) - { - if (cb.first == nil) - { // screen capture - if (!screenPixelData) - { - CommandBufferMTL::readPixels(_drawableTexture, 0, 0, [_drawableTexture width], - [_drawableTexture height], screenPixelData); + for(auto& cb : _captureCallbacks) { + if(cb.first == nil) { // screen capture + if(!screenPixelData) { + CommandBufferMTL::readPixels(_drawableTexture, 0, 0, [_drawableTexture width], [_drawableTexture height], screenPixelData); // screen framebuffer copied, restore screen framebuffer only to true backend::Device::getInstance()->setFrameBufferOnly(true); } cb.second(screenPixelData); } - else - { + else { PixelBufferDescriptor pixelData; auto texture = cb.first; assert(texture != nullptr); @@ -404,7 +399,7 @@ void CommandBufferMTL::afterDraw() [_mtlIndexBuffer release]; _mtlIndexBuffer = nullptr; } - + CC_SAFE_RELEASE_NULL(_programState); } @@ -412,7 +407,7 @@ void CommandBufferMTL::prepareDrawing() const { setUniformBuffer(); setTextures(); - + auto mtlDepthStencilState = _depthStencilStateMTL->getMTLDepthStencilState(); if (mtlDepthStencilState) { @@ -433,33 +428,36 @@ void CommandBufferMTL::setTextures() const void CommandBufferMTL::doSetTextures(bool isVertex) const { - const auto& bindTextureInfos = - (isVertex) ? _programState->getVertexTextureInfos() : _programState->getFragmentTextureInfos(); + const auto& bindTextureInfos = (isVertex) ? _programState->getVertexTextureInfos() : _programState->getFragmentTextureInfos(); - for (const auto& iter : bindTextureInfos) + for(const auto& iter : bindTextureInfos) { /* About mutli textures support - * a. TODO: sampler2DArray, not implemented in Metal Renderer currently - * b. texture slot, one BackendTexture, multi GPU texture handlers, used by etc1, restrict: textures must have - * same size c. Bind multi BackendTexture to 1 Shader Program, see the ShaderTest d. iter.second.slots not used - * for Metal Renderer - */ - auto location = iter.first; + * a. TODO: sampler2DArray, not implemented in Metal Renderer currently + * b. texture slot, one BackendTexture, multi GPU texture handlers, used by etc1, restrict: textures must have same size + * c. Bind multi BackendTexture to 1 Shader Program, see the ShaderTest + * d. iter.second.slots not used for Metal Renderer + */ + auto location = iter.first; auto& textures = iter.second.textures; - auto& indexs = iter.second.indexs; - + auto& indexs = iter.second.indexs; + auto texture = textures[0]; - auto index = indexs[0]; + auto index = indexs[0]; if (isVertex) { - [_mtlRenderEncoder setVertexTexture:getMTLTexture(texture, index) atIndex:location]; - [_mtlRenderEncoder setVertexSamplerState:getMTLSamplerState(texture) atIndex:location]; + [_mtlRenderEncoder setVertexTexture:getMTLTexture(texture, index) + atIndex:location]; + [_mtlRenderEncoder setVertexSamplerState:getMTLSamplerState(texture) + atIndex:location]; } else { - [_mtlRenderEncoder setFragmentTexture:getMTLTexture(texture, index) atIndex:location]; - [_mtlRenderEncoder setFragmentSamplerState:getMTLSamplerState(texture) atIndex:location]; + [_mtlRenderEncoder setFragmentTexture:getMTLTexture(texture, index) + atIndex:location]; + [_mtlRenderEncoder setFragmentSamplerState:getMTLSamplerState(texture) + atIndex:location]; } } } @@ -468,122 +466,108 @@ void CommandBufferMTL::setUniformBuffer() const { if (_programState) { - auto& callbackUniforms = _programState->getCallbackUniforms(); - for (auto& cb : callbackUniforms) - cb.second(_programState, cb.first); + auto& callbackUniforms = _programState->getCallbackUniforms(); + for(auto& cb : callbackUniforms) + cb.second(_programState, cb.first); // Uniform buffer is bound to index 1. std::size_t bufferSize = 0; - char* vertexBuffer = nullptr; + char* vertexBuffer = nullptr; _programState->getVertexUniformBuffer(&vertexBuffer, bufferSize); - if (vertexBuffer) + if(vertexBuffer) { - [_mtlRenderEncoder setVertexBytes:vertexBuffer length:bufferSize atIndex:1]; + [_mtlRenderEncoder setVertexBytes:vertexBuffer + length:bufferSize + atIndex:1]; } - + char* fragmentBuffer = nullptr; _programState->getFragmentUniformBuffer(&fragmentBuffer, bufferSize); - if (fragmentBuffer) + if(fragmentBuffer) { - [_mtlRenderEncoder setFragmentBytes:fragmentBuffer length:bufferSize atIndex:1]; + [_mtlRenderEncoder setFragmentBytes:fragmentBuffer + length:bufferSize + atIndex:1]; } } } -void CommandBufferMTL::setLineWidth(float lineWidth) {} +void CommandBufferMTL::setLineWidth(float lineWidth) +{ +} void CommandBufferMTL::setScissorRect(bool isEnabled, float x, float y, float width, float height) { MTLScissorRect scissorRect; - if (isEnabled) + if(isEnabled) { - y = _renderTargetHeight - height - y; - int minX = clamp((int)x, 0, (int)_renderTargetWidth); - int minY = clamp((int)y, 0, (int)_renderTargetHeight); - int maxX = clamp((int)(x + width), 0, (int)_renderTargetWidth); - int maxY = clamp((int)(y + height), 0, (int)_renderTargetHeight); - scissorRect.x = minX; - scissorRect.y = minY; - scissorRect.width = maxX - minX; + y = _renderTargetHeight - height - y; + int minX = clamp((int)x, 0, (int)_renderTargetWidth); + int minY = clamp((int)y, 0, (int)_renderTargetHeight); + int maxX = clamp((int)(x + width), 0, (int)_renderTargetWidth); + int maxY = clamp((int)(y + height), 0, (int)_renderTargetHeight); + scissorRect.x = minX; + scissorRect.y = minY; + scissorRect.width = maxX - minX; scissorRect.height = maxY - minY; - if (scissorRect.width == 0 || scissorRect.height == 0) - { - scissorRect.width = 0; + if (scissorRect.width == 0 || scissorRect.height == 0) { + scissorRect.width = 0; scissorRect.height = 0; } } else { - scissorRect.x = 0; - scissorRect.y = 0; - scissorRect.width = _renderTargetWidth; + scissorRect.x = 0; + scissorRect.y = 0; + scissorRect.width = _renderTargetWidth; scissorRect.height = _renderTargetHeight; } [_mtlRenderEncoder setScissorRect:scissorRect]; } -void CommandBufferMTL::readPixels(TextureBackend* texture, - std::size_t origX, - std::size_t origY, - std::size_t rectWidth, - std::size_t rectHeight, - PixelBufferDescriptor& pbd) +void CommandBufferMTL::readPixels(TextureBackend* texture, std::size_t origX, std::size_t origY, std::size_t rectWidth, std::size_t rectHeight, PixelBufferDescriptor& pbd) { - CommandBufferMTL::readPixels(reinterpret_cast>(texture->getHandler()), origX, origY, rectWidth, - rectHeight, pbd); + CommandBufferMTL::readPixels(reinterpret_cast>(texture->getHandler()), origX, origY, rectWidth, rectHeight, pbd); } -void CommandBufferMTL::readPixels(id texture, - std::size_t origX, - std::size_t origY, - std::size_t rectWidth, - std::size_t rectHeight, - PixelBufferDescriptor& pbd) +void CommandBufferMTL::readPixels(id texture, std::size_t origX, std::size_t origY, std::size_t rectWidth, std::size_t rectHeight, PixelBufferDescriptor& pbd) { - NSUInteger texWidth = texture.width; - NSUInteger texHeight = texture.height; - MTLRegion region = MTLRegionMake2D(0, 0, texWidth, texHeight); + NSUInteger texWidth = texture.width; + NSUInteger texHeight = texture.height; + MTLRegion region = MTLRegionMake2D(0, 0, texWidth, texHeight); MTLRegion imageRegion = MTLRegionMake2D(origX, origY, rectWidth, rectHeight); - + MTLTextureDescriptor* textureDescriptor = - [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:[texture pixelFormat] - width:texWidth - height:texHeight - mipmapped:NO]; - id device = static_cast(DeviceMTL::getInstance())->getMTLDevice(); + [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:[texture pixelFormat] + width:texWidth + height:texHeight + mipmapped:NO]; + id device = static_cast(DeviceMTL::getInstance())->getMTLDevice(); id readPixelsTexture = [device newTextureWithDescriptor:textureDescriptor]; - + id commandQueue = static_cast(DeviceMTL::getInstance())->getMTLCommandQueue(); - auto commandBuffer = [commandQueue commandBuffer]; + auto commandBuffer = [commandQueue commandBuffer]; // [commandBuffer enqueue]; - + id blitCommandEncoder = [commandBuffer blitCommandEncoder]; - [blitCommandEncoder copyFromTexture:texture - sourceSlice:0 - sourceLevel:0 - sourceOrigin:region.origin - sourceSize:region.size - toTexture:readPixelsTexture - destinationSlice:0 - destinationLevel:0 - destinationOrigin:region.origin]; - + [blitCommandEncoder copyFromTexture:texture sourceSlice:0 sourceLevel:0 sourceOrigin:region.origin sourceSize:region.size toTexture:readPixelsTexture destinationSlice:0 destinationLevel:0 destinationOrigin:region.origin]; + #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) [blitCommandEncoder synchronizeResource:readPixelsTexture]; #endif [blitCommandEncoder endEncoding]; - + [commandBuffer addCompletedHandler:^(id commandBufferMTL) { - auto bytePerRow = rectWidth * getBitsPerElementMTL(texture.pixelFormat) / 8; - auto texelData = pbd._data.resize(bytePerRow * rectHeight); - if (texelData != nullptr) - { + auto bytePerRow = rectWidth * getBitsPerElementMTL(texture.pixelFormat) / 8; + auto texelData = pbd._data.resize(bytePerRow * rectHeight); + if(texelData != nullptr) + { [readPixelsTexture getBytes:texelData bytesPerRow:bytePerRow fromRegion:imageRegion mipmapLevel:0]; UtilsMTL::swizzleImage(texelData, rectWidth, rectHeight, readPixelsTexture.pixelFormat); - pbd._width = rectWidth; + pbd._width = rectWidth; pbd._height = rectHeight; - } - [readPixelsTexture release]; + } + [readPixelsTexture release]; }]; [commandBuffer commit]; [commandBuffer waitUntilCompleted]; diff --git a/cocos/renderer/backend/metal/DepthStencilStateMTL.mm b/cocos/renderer/backend/metal/DepthStencilStateMTL.mm index 4b1e0955a9..9c84efcb79 100644 --- a/cocos/renderer/backend/metal/DepthStencilStateMTL.mm +++ b/cocos/renderer/backend/metal/DepthStencilStateMTL.mm @@ -21,7 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "DepthStencilStateMTL.h" #include "../RenderTarget.h" #include "xxhash.h" @@ -30,110 +30,108 @@ CC_BACKEND_BEGIN namespace { -MTLCompareFunction toMTLCompareFunction(CompareFunction compareFunction) -{ - MTLCompareFunction ret = MTLCompareFunctionNever; - switch (compareFunction) + MTLCompareFunction toMTLCompareFunction(CompareFunction compareFunction) { - case CompareFunction::NEVER: - ret = MTLCompareFunctionNever; - break; - case CompareFunction::LESS: - ret = MTLCompareFunctionLess; - break; - case CompareFunction::LESS_EQUAL: - ret = MTLCompareFunctionLessEqual; - break; - case CompareFunction::GREATER: - ret = MTLCompareFunctionGreater; - break; - case CompareFunction::GREATER_EQUAL: - ret = MTLCompareFunctionGreaterEqual; - break; - case CompareFunction::EQUAL: - ret = MTLCompareFunctionEqual; - break; - case CompareFunction::NOT_EQUAL: - ret = MTLCompareFunctionNotEqual; - break; - case CompareFunction::ALWAYS: - ret = MTLCompareFunctionAlways; - break; - default: - assert(false); - break; + MTLCompareFunction ret = MTLCompareFunctionNever; + switch (compareFunction) { + case CompareFunction::NEVER: + ret = MTLCompareFunctionNever; + break; + case CompareFunction::LESS: + ret = MTLCompareFunctionLess; + break; + case CompareFunction::LESS_EQUAL: + ret = MTLCompareFunctionLessEqual; + break; + case CompareFunction::GREATER: + ret = MTLCompareFunctionGreater; + break; + case CompareFunction::GREATER_EQUAL: + ret = MTLCompareFunctionGreaterEqual; + break; + case CompareFunction::EQUAL: + ret = MTLCompareFunctionEqual; + break; + case CompareFunction::NOT_EQUAL: + ret = MTLCompareFunctionNotEqual; + break; + case CompareFunction::ALWAYS: + ret = MTLCompareFunctionAlways; + break; + default: + assert(false); + break; + } + return ret; } - return ret; -} - -MTLStencilOperation toMTLStencilOperation(StencilOperation operation) -{ - MTLStencilOperation ret = MTLStencilOperationKeep; - switch (operation) + + MTLStencilOperation toMTLStencilOperation(StencilOperation operation) { - case StencilOperation::KEEP: - ret = MTLStencilOperationKeep; - break; - case StencilOperation::ZERO: - ret = MTLStencilOperationZero; - break; - case StencilOperation::REPLACE: - ret = MTLStencilOperationReplace; - break; - case StencilOperation::INVERT: - ret = MTLStencilOperationInvert; - break; - case StencilOperation::INCREMENT_WRAP: - ret = MTLStencilOperationIncrementWrap; - break; - case StencilOperation::DECREMENT_WRAP: - ret = MTLStencilOperationDecrementWrap; - break; - default: - assert(false); - break; + MTLStencilOperation ret = MTLStencilOperationKeep; + switch (operation) { + case StencilOperation::KEEP: + ret = MTLStencilOperationKeep; + break; + case StencilOperation::ZERO: + ret = MTLStencilOperationZero; + break; + case StencilOperation::REPLACE: + ret = MTLStencilOperationReplace; + break; + case StencilOperation::INVERT: + ret = MTLStencilOperationInvert; + break; + case StencilOperation::INCREMENT_WRAP: + ret = MTLStencilOperationIncrementWrap; + break; + case StencilOperation::DECREMENT_WRAP: + ret = MTLStencilOperationDecrementWrap; + break; + default: + assert(false); + break; + } + return ret; + } + + void setMTLStencilDescriptor(MTLStencilDescriptor* stencilDescriptor, const StencilDescriptor& descriptor) + { + stencilDescriptor.stencilFailureOperation = toMTLStencilOperation(descriptor.stencilFailureOperation); + stencilDescriptor.depthFailureOperation = toMTLStencilOperation(descriptor.depthFailureOperation); + stencilDescriptor.depthStencilPassOperation = toMTLStencilOperation(descriptor.depthStencilPassOperation); + stencilDescriptor.stencilCompareFunction = toMTLCompareFunction(descriptor.stencilCompareFunction); + stencilDescriptor.readMask = descriptor.readMask; + stencilDescriptor.writeMask = descriptor.writeMask; } - return ret; } -void setMTLStencilDescriptor(MTLStencilDescriptor* stencilDescriptor, const StencilDescriptor& descriptor) +DepthStencilStateMTL::DepthStencilStateMTL(id mtlDevice) : _mtlDevice(mtlDevice) { - stencilDescriptor.stencilFailureOperation = toMTLStencilOperation(descriptor.stencilFailureOperation); - stencilDescriptor.depthFailureOperation = toMTLStencilOperation(descriptor.depthFailureOperation); - stencilDescriptor.depthStencilPassOperation = toMTLStencilOperation(descriptor.depthStencilPassOperation); - stencilDescriptor.stencilCompareFunction = toMTLCompareFunction(descriptor.stencilCompareFunction); - stencilDescriptor.readMask = descriptor.readMask; - stencilDescriptor.writeMask = descriptor.writeMask; } -} - -DepthStencilStateMTL::DepthStencilStateMTL(id mtlDevice) : _mtlDevice(mtlDevice) {} void DepthStencilStateMTL::update(const DepthStencilDescriptor& dsDesc) { DepthStencilState::update(dsDesc); - - if (!isEnabled()) - { + + if(!isEnabled()) { _mtlDepthStencilState = nil; return; } - + DepthStencilDescriptor hashMe; memset(&hashMe, 0, sizeof(hashMe)); hashMe.depthCompareFunction = dsDesc.depthCompareFunction; - hashMe.backFaceStencil = dsDesc.backFaceStencil; - hashMe.frontFaceStencil = dsDesc.frontFaceStencil; - hashMe.flags = dsDesc.flags; - + hashMe.backFaceStencil = dsDesc.backFaceStencil; + hashMe.frontFaceStencil = dsDesc.frontFaceStencil; + hashMe.flags = dsDesc.flags; + auto key = XXH32((const void*)&hashMe, sizeof(hashMe), 0); - auto it = _mtlStateCache.find(key); - if (it != _mtlStateCache.end()) - { + auto it = _mtlStateCache.find(key); + if(it != _mtlStateCache.end()) { _mtlDepthStencilState = it->second; return; } - + MTLDepthStencilDescriptor* mtlDescriptor = [[MTLDepthStencilDescriptor alloc] init]; if (bitmask::any(dsDesc.flags, DepthStencilFlags::DEPTH_TEST)) @@ -151,7 +149,7 @@ void DepthStencilStateMTL::update(const DepthStencilDescriptor& dsDesc) _mtlDepthStencilState = [_mtlDevice newDepthStencilStateWithDescriptor:mtlDescriptor]; [mtlDescriptor release]; - + // emplace to state cache _mtlStateCache.emplace(key, _mtlDepthStencilState); } @@ -159,7 +157,7 @@ void DepthStencilStateMTL::update(const DepthStencilDescriptor& dsDesc) DepthStencilStateMTL::~DepthStencilStateMTL() { _mtlDepthStencilState = nullptr; - for (auto& stateItem : _mtlStateCache) + for(auto& stateItem : _mtlStateCache) [stateItem.second release]; _mtlStateCache.clear(); } diff --git a/cocos/renderer/backend/metal/DeviceInfoMTL.mm b/cocos/renderer/backend/metal/DeviceInfoMTL.mm index 18208a5e8a..87d0e6a65e 100644 --- a/cocos/renderer/backend/metal/DeviceInfoMTL.mm +++ b/cocos/renderer/backend/metal/DeviceInfoMTL.mm @@ -22,367 +22,367 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + #include "DeviceInfoMTL.h" #include "base/ccMacros.h" #include "UtilsMTL.h" CC_BACKEND_BEGIN -namespace -{ -int getMaxVertexAttributes(FeatureSet featureSet) -{ - int maxAttributes = 0; - switch (featureSet) +namespace { + int getMaxVertexAttributes(FeatureSet featureSet) { - case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: - maxAttributes = 31; - break; - default: - break; + int maxAttributes = 0; + switch (featureSet) + { + case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: + maxAttributes = 31; + break; + default: + break; + } + return maxAttributes; } - return maxAttributes; -} - -int getMaxTextureEntries(FeatureSet featureSet) -{ - int maxTextureEntries = 0; - switch (featureSet) + + int getMaxTextureEntries(FeatureSet featureSet) { - case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: - maxTextureEntries = 31; - break; - case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: - maxTextureEntries = 128; - break; - default: - break; + int maxTextureEntries = 0; + switch (featureSet) + { + case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: + maxTextureEntries = 31; + break; + case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: + maxTextureEntries = 128; + break; + default: + break; + } + return maxTextureEntries; } - return maxTextureEntries; -} - -int getMaxSamplerEntries(FeatureSet featureSet) -{ - int maxSamplerEntries = 0; - switch (featureSet) + + int getMaxSamplerEntries(FeatureSet featureSet) { - case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: - maxSamplerEntries = 16; - break; - default: - break; + int maxSamplerEntries = 0; + switch (featureSet) + { + case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: + maxSamplerEntries = 16; + break; + default: + break; + } + return maxSamplerEntries; } - return maxSamplerEntries; -} - -int getMaxTextureWidthHeight(FeatureSet featureSet) -{ - int maxTextureSize = 0; - switch (featureSet) + + int getMaxTextureWidthHeight(FeatureSet featureSet) { - case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: - maxTextureSize = 4096; - break; - case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: - maxTextureSize = 8192; - break; - case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: - maxTextureSize = 16384; - break; - default: - break; + int maxTextureSize = 0; + switch (featureSet) + { + case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: + maxTextureSize = 4096; + break; + case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: + maxTextureSize = 8192; + break; + case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: + maxTextureSize = 16384; + break; + default: + break; + } + return maxTextureSize; } - return maxTextureSize; -} - -const char* featureSetToString(FeatureSet featureSet) -{ - switch (featureSet) + + const char* featureSetToString(FeatureSet featureSet) { - case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: - return "iOS_GPUFamily1_v1"; - case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: - return "iOS_GPUFamily2_v1"; - case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: - return "iOS_GPUFamily1_v2"; - case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: - return "iOS_GPUFamily2_v2"; - case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: - return "iOS_GPUFamily1_v3"; - case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: - return "iOS_GPUFamily2_v3"; - case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: - return "iOS_GPUFamily1_v4"; - case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: - return "iOS_GPUFamily2_v4"; - case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: - return "iOS_GPUFamily1_v5"; - case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: - return "iOS_GPUFamily2_v5"; - case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: - return "iOS_GPUFamily3_v1"; - case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: - return "iOS_GPUFamily3_v2"; - case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: - return "iOS_GPUFamily3_v3"; - case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: - return "iOS_GPUFamily4_v1"; - case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: - return "iOS_GPUFamily3_v4"; - case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: - return "iOS_GPUFamily4_v2"; - case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: - return "macOS_GPUFamily1_v1"; - case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: - return "macOS_GPUFamily1_v2"; - case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: - return "macOS_ReadWriteTextureTier2"; - case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: - return "macOS_GPUFamily1_v3"; - case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: - return "macOS_GPUFamily1_v4"; - case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: - return "macOS_GPUFamily2_v1"; - default: - break; + switch (featureSet) + { + case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: + return "iOS_GPUFamily1_v1"; + case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: + return "iOS_GPUFamily2_v1"; + case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: + return "iOS_GPUFamily1_v2"; + case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: + return "iOS_GPUFamily2_v2"; + case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: + return "iOS_GPUFamily1_v3"; + case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: + return "iOS_GPUFamily2_v3"; + case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: + return "iOS_GPUFamily1_v4"; + case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: + return "iOS_GPUFamily2_v4"; + case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + return "iOS_GPUFamily1_v5"; + case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: + return "iOS_GPUFamily2_v5"; + case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: + return "iOS_GPUFamily3_v1"; + case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: + return "iOS_GPUFamily3_v2"; + case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: + return "iOS_GPUFamily3_v3"; + case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: + return "iOS_GPUFamily4_v1"; + case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: + return "iOS_GPUFamily3_v4"; + case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: + return "iOS_GPUFamily4_v2"; + case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: + return "macOS_GPUFamily1_v1"; + case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: + return "macOS_GPUFamily1_v2"; + case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: + return "macOS_ReadWriteTextureTier2"; + case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: + return "macOS_GPUFamily1_v3"; + case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: + return "macOS_GPUFamily1_v4"; + case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: + return "macOS_GPUFamily2_v1"; + default: + break; + } + return ""; } - return ""; -} - -bool supportPVRTC(FeatureSet featureSet) -{ - switch (featureSet) + + bool supportPVRTC(FeatureSet featureSet) { - case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: - return true; - case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: + switch (featureSet) + { + case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: + return true; + case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: + return false; + default: + break; + } return false; - default: - break; } - return false; -} - -bool supportEACETC(FeatureSet featureSet) -{ - switch (featureSet) + + bool supportEACETC(FeatureSet featureSet) { - case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: - return true; - case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: + switch (featureSet) + { + case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: + return true; + case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: + return false; + default: + break; + } return false; - default: - break; } - return false; -} - -bool supportASTC(FeatureSet featureSet) -{ - switch (featureSet) + + bool supportASTC(FeatureSet featureSet) { - case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + switch (featureSet) + { + case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + return false; + case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: + return true; + case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: + return false; + default: + break; + } return false; - case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: - return true; - case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: - return false; - default: - break; } - return false; -} - -bool supportS3TC(FeatureSet featureSet) -{ - switch (featureSet) + + bool supportS3TC(FeatureSet featureSet) { - case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: + switch (featureSet) + { + case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: + return false; + case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: + return true; + default: + break; + } return false; - case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: - return true; - default: - break; } - return false; -} } bool DeviceInfoMTL::_isDepth24Stencil8PixelFormatSupported = false; DeviceInfoMTL::DeviceInfoMTL(id device) { - _deviceName = [device.name UTF8String]; - + _deviceName = [device.name UTF8String]; + #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) const FeatureSet minRequiredFeatureSet = FeatureSet::FeatureSet_iOS_GPUFamily1_v1; - const FeatureSet maxKnownFeatureSet = FeatureSet::FeatureSet_iOS_GPUFamily4_v2; + const FeatureSet maxKnownFeatureSet = FeatureSet::FeatureSet_iOS_GPUFamily4_v2; #else const FeatureSet minRequiredFeatureSet = FeatureSet::FeatureSet_macOS_GPUFamily1_v1; - const FeatureSet maxKnownFeatureSet = FeatureSet::FeatureSet_macOS_GPUFamily2_v1; + const FeatureSet maxKnownFeatureSet = FeatureSet::FeatureSet_macOS_GPUFamily2_v1; _isDepth24Stencil8PixelFormatSupported = [device isDepth24Stencil8PixelFormatSupported]; #endif - + for (auto featureSet = maxKnownFeatureSet; featureSet >= minRequiredFeatureSet; --featureSet) { if ([device supportsFeatureSet:MTLFeatureSet(featureSet)]) @@ -391,17 +391,17 @@ DeviceInfoMTL::DeviceInfoMTL(id device) break; } } - + UtilsMTL::initGPUTextureFormats(); } bool DeviceInfoMTL::init() { - _maxAttributes = getMaxVertexAttributes(_featureSet); + _maxAttributes = getMaxVertexAttributes(_featureSet); _maxSamplesAllowed = getMaxSamplerEntries(_featureSet); - _maxTextureUnits = getMaxTextureEntries(_featureSet); - _maxTextureSize = getMaxTextureWidthHeight(_featureSet); - + _maxTextureUnits = getMaxTextureEntries(_featureSet); + _maxTextureSize = getMaxTextureWidthHeight(_featureSet); + return true; } diff --git a/cocos/renderer/backend/metal/DeviceMTL.h b/cocos/renderer/backend/metal/DeviceMTL.h index 10cfdd30f2..fac8be126d 100644 --- a/cocos/renderer/backend/metal/DeviceMTL.h +++ b/cocos/renderer/backend/metal/DeviceMTL.h @@ -133,7 +133,7 @@ public: * @param fragmentShader Specifes this is a fragment shader source. * @return A Program instance. */ - virtual Program* newProgram(std::string_view vertexShader, std::string_view fragmentShader) override; + virtual Program* newProgram(const std::string& vertexShader, const std::string& fragmentShader) override; /** * Get a MTLDevice object. @@ -154,7 +154,7 @@ protected: * @param source Specifies shader source. * @return A ShaderModule object. */ - virtual ShaderModule* newShaderModule(ShaderStage stage, std::string_view source) override; + virtual ShaderModule* newShaderModule(ShaderStage stage, const std::string& source) override; private: static CAMetalLayer* _metalLayer; diff --git a/cocos/renderer/backend/metal/DeviceMTL.mm b/cocos/renderer/backend/metal/DeviceMTL.mm index fddde3997e..174e2807a9 100644 --- a/cocos/renderer/backend/metal/DeviceMTL.mm +++ b/cocos/renderer/backend/metal/DeviceMTL.mm @@ -21,7 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "DeviceMTL.h" #include "CommandBufferMTL.h" #include "BufferMTL.h" @@ -37,12 +37,12 @@ CC_BACKEND_BEGIN -CAMetalLayer* DeviceMTL::_metalLayer = nil; +CAMetalLayer* DeviceMTL::_metalLayer = nil; id DeviceMTL::_currentDrawable = nil; Device* Device::getInstance() { - if (!Device::_instance) + if (! Device::_instance) Device::_instance = new DeviceMTL(); return Device::_instance; @@ -55,9 +55,9 @@ void DeviceMTL::setCAMetalLayer(CAMetalLayer* metalLayer) id DeviceMTL::getCurrentDrawable() { - if (!DeviceMTL::_currentDrawable) + if (! DeviceMTL::_currentDrawable) DeviceMTL::_currentDrawable = [DeviceMTL::_metalLayer nextDrawable]; - + return DeviceMTL::_currentDrawable; } @@ -68,10 +68,10 @@ void DeviceMTL::resetCurrentDrawable() DeviceMTL::DeviceMTL() { - _mtlDevice = DeviceMTL::_metalLayer.device; + _mtlDevice = DeviceMTL::_metalLayer.device; _mtlCommandQueue = [_mtlDevice newCommandQueue]; - _deviceInfo = new DeviceInfoMTL(_mtlDevice); - if (!_deviceInfo->init()) + _deviceInfo = new DeviceInfoMTL(_mtlDevice); + if(!_deviceInfo->init()) { delete _deviceInfo; _deviceInfo = nullptr; @@ -97,15 +97,15 @@ Buffer* DeviceMTL::newBuffer(std::size_t size, BufferType type, BufferUsage usag TextureBackend* DeviceMTL::newTexture(const TextureDescriptor& descriptor) { - switch (descriptor.textureType) + switch(descriptor.textureType) { - case TextureType::TEXTURE_2D: - return new TextureMTL(_mtlDevice, descriptor); - case TextureType::TEXTURE_CUBE: - return new TextureCubeMTL(_mtlDevice, descriptor); - default: - CCASSERT(false, "invalidate texture type"); - return nullptr; + case TextureType::TEXTURE_2D: + return new TextureMTL(_mtlDevice, descriptor); + case TextureType::TEXTURE_CUBE: + return new TextureCubeMTL(_mtlDevice, descriptor); + default: + CCASSERT(false, "invalidate texture type"); + return nullptr; } } @@ -117,21 +117,21 @@ RenderTarget* DeviceMTL::newDefaultRenderTarget(TargetBufferFlags rtf) } RenderTarget* DeviceMTL::newRenderTarget(TargetBufferFlags rtf, - TextureBackend* colorAttachment, - TextureBackend* depthAttachment, - TextureBackend* stencilAttachhment) + TextureBackend* colorAttachment, + TextureBackend* depthAttachment, + TextureBackend* stencilAttachhment) { auto rtGL = new RenderTargetMTL(false); rtGL->setTargetFlags(rtf); rtGL->bindFrameBuffer(); - RenderTarget::ColorAttachment colors{{colorAttachment, 0}}; + RenderTarget::ColorAttachment colors{ {colorAttachment, 0} }; rtGL->setColorAttachment(colors); rtGL->setDepthAttachment(depthAttachment); rtGL->setStencilAttachment(stencilAttachhment); return rtGL; } -ShaderModule* DeviceMTL::newShaderModule(ShaderStage stage, std::string_view source) +ShaderModule* DeviceMTL::newShaderModule(ShaderStage stage, const std::string& source) { return new ShaderModuleMTL(_mtlDevice, stage, source); } @@ -146,7 +146,7 @@ RenderPipeline* DeviceMTL::newRenderPipeline() return new RenderPipelineMTL(_mtlDevice); } -Program* DeviceMTL::newProgram(std::string_view vertexShader, std::string_view fragmentShader) +Program* DeviceMTL::newProgram(const std::string& vertexShader, const std::string& fragmentShader) { return new ProgramMTL(vertexShader, fragmentShader); } diff --git a/cocos/renderer/backend/metal/ProgramMTL.h b/cocos/renderer/backend/metal/ProgramMTL.h index c6c0be6b95..0b014941bd 100644 --- a/cocos/renderer/backend/metal/ProgramMTL.h +++ b/cocos/renderer/backend/metal/ProgramMTL.h @@ -47,7 +47,7 @@ public: * @param vertexShader Specifes the vertex shader source. * @param fragmentShader Specifes the fragment shader source. */ - ProgramMTL(std::string_view vertexShader, std::string_view fragmentShader); + ProgramMTL(const std::string& vertexShader, const std::string& fragmentShader); virtual ~ProgramMTL(); /** @@ -55,7 +55,7 @@ public: * @param uniform Specifies the uniform name. * @return The uniform location. */ - virtual UniformLocation getUniformLocation(std::string_view uniform) const override; + virtual UniformLocation getUniformLocation(const std::string& uniform) const override; /** * Get uniform location by engine built-in uniform enum name. @@ -69,7 +69,7 @@ public: * @param name Specifies the attribute name. * @return The attribute location. */ - virtual int getAttributeLocation(std::string_view name) const override; + virtual int getAttributeLocation(const std::string& name) const override; /** * Get attribute location by engine built-in attribute enum name. @@ -94,7 +94,7 @@ public: * Get active vertex attributes. * @return Active vertex attributes. key is active attribute name, Value is corresponding attribute info. */ - const hlookup::string_map getActiveAttributes() const override; + const std::unordered_map getActiveAttributes() const override; /** * Get maximum vertex location. @@ -127,7 +127,8 @@ public: * Get all uniformInfos. * @return The uniformInfos. */ - virtual const hlookup::string_map& getAllActiveUniformInfo(ShaderStage stage) const override; + virtual const std::unordered_map& getAllActiveUniformInfo( + ShaderStage stage) const override; private: ShaderModuleMTL* _vertexShader = nullptr; diff --git a/cocos/renderer/backend/metal/ProgramMTL.mm b/cocos/renderer/backend/metal/ProgramMTL.mm index 3bbe43cae4..d1f2cb7a86 100644 --- a/cocos/renderer/backend/metal/ProgramMTL.mm +++ b/cocos/renderer/backend/metal/ProgramMTL.mm @@ -21,24 +21,21 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "ProgramMTL.h" #include "ShaderModuleMTL.h" #include "base/ccMacros.h" CC_BACKEND_BEGIN -namespace -{ -constexpr std::string_view metalSpecificDefine = "#define METAL\n"sv; +namespace { + const std::string metalSpecificDefine = "#define METAL\n"; } -ProgramMTL::ProgramMTL(std::string_view vertexShader, std::string_view fragmentShader) - : Program(vertexShader, fragmentShader) +ProgramMTL::ProgramMTL(const std::string& vertexShader, const std::string& fragmentShader) +: Program(vertexShader, fragmentShader) { _vertexShader = static_cast(ShaderCache::newVertexShaderModule(vertexShader)); - std::string combinedSource{metalSpecificDefine}; - combinedSource += fragmentShader; - _fragmentShader = static_cast(ShaderCache::newFragmentShaderModule(std::move(combinedSource))); + _fragmentShader = static_cast(ShaderCache::newFragmentShaderModule(std::move(metalSpecificDefine + fragmentShader))); CC_SAFE_RETAIN(_vertexShader); CC_SAFE_RETAIN(_fragmentShader); @@ -55,7 +52,7 @@ int ProgramMTL::getAttributeLocation(Attribute name) const return _vertexShader->getAttributeLocation(name); } -int ProgramMTL::getAttributeLocation(std::string_view name) const +int ProgramMTL::getAttributeLocation(const std::string &name) const { return _vertexShader->getAttributeLocation(name); } @@ -65,13 +62,13 @@ UniformLocation ProgramMTL::getUniformLocation(backend::Uniform name) const UniformLocation uniformLocation; auto vsLocation = _vertexShader->getUniformLocation(name); auto fsLocation = _fragmentShader->getUniformLocation(name); - if (vsLocation != -1 && fsLocation != -1) + if(vsLocation != -1 && fsLocation != -1) { uniformLocation.shaderStage = ShaderStage::VERTEX_AND_FRAGMENT; uniformLocation.location[0] = vsLocation; uniformLocation.location[1] = fsLocation; } - else if (vsLocation != -1) + else if( vsLocation != -1) { uniformLocation.shaderStage = ShaderStage::VERTEX; uniformLocation.location[0] = vsLocation; @@ -84,18 +81,18 @@ UniformLocation ProgramMTL::getUniformLocation(backend::Uniform name) const return uniformLocation; } -UniformLocation ProgramMTL::getUniformLocation(std::string_view uniform) const +UniformLocation ProgramMTL::getUniformLocation(const std::string& uniform) const { UniformLocation uniformLocation; auto vsLocation = _vertexShader->getUniformLocation(uniform); auto fsLocation = _fragmentShader->getUniformLocation(uniform); - if (vsLocation != -1 && fsLocation != -1) + if(vsLocation != -1 && fsLocation != -1) { uniformLocation.shaderStage = ShaderStage::VERTEX_AND_FRAGMENT; uniformLocation.location[0] = vsLocation; uniformLocation.location[1] = fsLocation; } - else if (vsLocation != -1) + else if( vsLocation != -1) { uniformLocation.shaderStage = ShaderStage::VERTEX; uniformLocation.location[0] = vsLocation; @@ -118,64 +115,63 @@ int ProgramMTL::getMaxFragmentLocation() const return _fragmentShader->getMaxLocation(); } -const hlookup::string_map ProgramMTL::getActiveAttributes() const +const std::unordered_map ProgramMTL::getActiveAttributes() const { return _vertexShader->getAttributeInfo(); } -// const std::vector& ProgramMTL::cloneUniformBuffer(ShaderStage stage) const +//const std::vector& ProgramMTL::cloneUniformBuffer(ShaderStage stage) const //{ -// switch (stage) { -// case ShaderStage::VERTEX: -// return _vertexShader->cloneUniformBuffer(); -// break; -// case ShaderStage::FRAGMENT: -// return _fragmentShader->cloneUniformBuffer(); -// default: -// CCASSERT(false, "Invalid shader stage."); -// break; -// } -// } +// switch (stage) { +// case ShaderStage::VERTEX: +// return _vertexShader->cloneUniformBuffer(); +// break; +// case ShaderStage::FRAGMENT: +// return _fragmentShader->cloneUniformBuffer(); +// default: +// CCASSERT(false, "Invalid shader stage."); +// break; +// } +//} const UniformInfo& ProgramMTL::getActiveUniformInfo(ShaderStage stage, int location) const { - switch (stage) - { - case ShaderStage::VERTEX: - return _vertexShader->getActiveUniform(location); - case ShaderStage::FRAGMENT: - return _fragmentShader->getActiveUniform(location); - default: - CCASSERT(false, "Invalid shader stage."); + switch (stage) { + case ShaderStage::VERTEX: + return _vertexShader->getActiveUniform(location); + case ShaderStage::FRAGMENT: + return _fragmentShader->getActiveUniform(location); + default: + CCASSERT(false, "Invalid shader stage."); break; } } + std::size_t ProgramMTL::getUniformBufferSize(ShaderStage stage) const { - switch (stage) - { - case ShaderStage::VERTEX: - return _vertexShader->getUniformBufferSize(); - case ShaderStage::FRAGMENT: - return _fragmentShader->getUniformBufferSize(); - default: - CCASSERT(false, "Invalid shader stage."); - break; + switch (stage) { + case ShaderStage::VERTEX: + return _vertexShader->getUniformBufferSize(); + case ShaderStage::FRAGMENT: + return _fragmentShader->getUniformBufferSize(); + default: + CCASSERT(false, "Invalid shader stage."); + break; } return 0; } -const hlookup::string_map& ProgramMTL::getAllActiveUniformInfo(ShaderStage stage) const +const std::unordered_map& ProgramMTL::getAllActiveUniformInfo(ShaderStage stage) const { - switch (stage) - { - case ShaderStage::VERTEX: - return _vertexShader->getAllActiveUniformInfo(); - case ShaderStage::FRAGMENT: - return _fragmentShader->getAllActiveUniformInfo(); - default: - CCASSERT(false, "Invalid shader stage."); + switch (stage) { + case ShaderStage::VERTEX: + return _vertexShader->getAllActiveUniformInfo(); + case ShaderStage::FRAGMENT: + return _fragmentShader->getAllActiveUniformInfo(); + default: + CCASSERT(false, "Invalid shader stage."); + break; } } diff --git a/cocos/renderer/backend/metal/RenderPipelineMTL.mm b/cocos/renderer/backend/metal/RenderPipelineMTL.mm index 30ed67d008..14f3e65bf3 100644 --- a/cocos/renderer/backend/metal/RenderPipelineMTL.mm +++ b/cocos/renderer/backend/metal/RenderPipelineMTL.mm @@ -21,7 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "RenderPipelineMTL.h" #include "DeviceMTL.h" #include "RenderTargetMTL.h" @@ -35,133 +35,133 @@ CC_BACKEND_BEGIN namespace { -MTLVertexStepFunction toMTLVertexStepFunction(VertexStepMode vertexStepMode) -{ - if (VertexStepMode::VERTEX == vertexStepMode) - return MTLVertexStepFunctionPerVertex; - else - return MTLVertexStepFunctionPerInstance; -} - -MTLVertexFormat toMTLVertexFormat(VertexFormat vertexFormat, bool needNormalize) -{ - MTLVertexFormat ret = MTLVertexFormatFloat4; - switch (vertexFormat) + MTLVertexStepFunction toMTLVertexStepFunction(VertexStepMode vertexStepMode) { - case VertexFormat::FLOAT4: - ret = MTLVertexFormatFloat4; - break; - case VertexFormat::FLOAT3: - ret = MTLVertexFormatFloat3; - break; - case VertexFormat::FLOAT2: - ret = MTLVertexFormatFloat2; - break; - case VertexFormat::FLOAT: - ret = MTLVertexFormatFloat; - break; - case VertexFormat::INT4: - ret = MTLVertexFormatInt4; - break; - case VertexFormat::INT3: - ret = MTLVertexFormatInt3; - break; - case VertexFormat::INT2: - ret = MTLVertexFormatInt2; - break; - case VertexFormat::INT: - ret = MTLVertexFormatInt; - break; - case VertexFormat::USHORT4: - ret = MTLVertexFormatUShort4; - break; - case VertexFormat::USHORT2: - ret = MTLVertexFormatUShort2; - break; - case VertexFormat::UBYTE4: - if (needNormalize) - ret = MTLVertexFormatUChar4Normalized; + if (VertexStepMode::VERTEX == vertexStepMode) + return MTLVertexStepFunctionPerVertex; else - ret = MTLVertexFormatUChar4; - break; - default: - assert(false); - break; + return MTLVertexStepFunctionPerInstance; } - return ret; -} - -MTLColorWriteMask toMTLColorWriteMask(ColorWriteMask mask) -{ - switch (mask) + + MTLVertexFormat toMTLVertexFormat(VertexFormat vertexFormat, bool needNormalize) { - case ColorWriteMask::NONE: - return MTLColorWriteMaskNone; - case ColorWriteMask::RED: - return MTLColorWriteMaskRed; - case ColorWriteMask::GREEN: - return MTLColorWriteMaskGreen; - case ColorWriteMask::BLUE: - return MTLColorWriteMaskBlue; - case ColorWriteMask::ALPHA: - return MTLColorWriteMaskAlpha; - case ColorWriteMask::ALL: - return MTLColorWriteMaskAll; + MTLVertexFormat ret = MTLVertexFormatFloat4; + switch (vertexFormat) + { + case VertexFormat::FLOAT4: + ret = MTLVertexFormatFloat4; + break; + case VertexFormat::FLOAT3: + ret = MTLVertexFormatFloat3; + break; + case VertexFormat::FLOAT2: + ret = MTLVertexFormatFloat2; + break; + case VertexFormat::FLOAT: + ret = MTLVertexFormatFloat; + break; + case VertexFormat::INT4: + ret = MTLVertexFormatInt4; + break; + case VertexFormat::INT3: + ret = MTLVertexFormatInt3; + break; + case VertexFormat::INT2: + ret = MTLVertexFormatInt2; + break; + case VertexFormat::INT: + ret = MTLVertexFormatInt; + break; + case VertexFormat::USHORT4: + ret = MTLVertexFormatUShort4; + break; + case VertexFormat::USHORT2: + ret = MTLVertexFormatUShort2; + break; + case VertexFormat::UBYTE4: + if (needNormalize) + ret = MTLVertexFormatUChar4Normalized; + else + ret = MTLVertexFormatUChar4; + break; + default: + assert(false); + break; + } + return ret; } -} - -MTLBlendFactor toMTLBlendFactor(BlendFactor factor) -{ - switch (factor) + + MTLColorWriteMask toMTLColorWriteMask(ColorWriteMask mask) { - case BlendFactor::ZERO: - return MTLBlendFactorZero; - case BlendFactor::ONE: - return MTLBlendFactorOne; - case BlendFactor::SRC_COLOR: - return MTLBlendFactorSourceColor; - case BlendFactor::ONE_MINUS_SRC_COLOR: - return MTLBlendFactorOneMinusSourceColor; - case BlendFactor::SRC_ALPHA: - return MTLBlendFactorSourceAlpha; - case BlendFactor::ONE_MINUS_SRC_ALPHA: - return MTLBlendFactorOneMinusSourceAlpha; - case BlendFactor::DST_COLOR: - return MTLBlendFactorDestinationColor; - case BlendFactor::ONE_MINUS_DST_COLOR: - return MTLBlendFactorOneMinusDestinationColor; - case BlendFactor::DST_ALPHA: - return MTLBlendFactorDestinationAlpha; - case BlendFactor::ONE_MINUS_DST_ALPHA: - return MTLBlendFactorOneMinusDestinationAlpha; - case BlendFactor::SRC_ALPHA_SATURATE: - return MTLBlendFactorSourceAlphaSaturated; - case BlendFactor::BLEND_CLOLOR: - return MTLBlendFactorBlendColor; - default: - return MTLBlendFactorZero; + switch (mask) { + case ColorWriteMask::NONE: + return MTLColorWriteMaskNone; + case ColorWriteMask::RED: + return MTLColorWriteMaskRed; + case ColorWriteMask::GREEN: + return MTLColorWriteMaskGreen; + case ColorWriteMask::BLUE: + return MTLColorWriteMaskBlue; + case ColorWriteMask::ALPHA: + return MTLColorWriteMaskAlpha; + case ColorWriteMask::ALL: + return MTLColorWriteMaskAll; + } } -} - -MTLBlendOperation toMTLBlendOperation(BlendOperation operation) -{ - switch (operation) + + MTLBlendFactor toMTLBlendFactor(BlendFactor factor) { - case BlendOperation::ADD: - return MTLBlendOperationAdd; - case BlendOperation::SUBTRACT: - return MTLBlendOperationSubtract; - case BlendOperation::RESERVE_SUBTRACT: - return MTLBlendOperationReverseSubtract; - default: - return MTLBlendOperationAdd; + switch (factor) { + case BlendFactor::ZERO: + return MTLBlendFactorZero; + case BlendFactor::ONE: + return MTLBlendFactorOne; + case BlendFactor::SRC_COLOR: + return MTLBlendFactorSourceColor; + case BlendFactor::ONE_MINUS_SRC_COLOR: + return MTLBlendFactorOneMinusSourceColor; + case BlendFactor::SRC_ALPHA: + return MTLBlendFactorSourceAlpha; + case BlendFactor::ONE_MINUS_SRC_ALPHA: + return MTLBlendFactorOneMinusSourceAlpha; + case BlendFactor::DST_COLOR: + return MTLBlendFactorDestinationColor; + case BlendFactor::ONE_MINUS_DST_COLOR: + return MTLBlendFactorOneMinusDestinationColor; + case BlendFactor::DST_ALPHA: + return MTLBlendFactorDestinationAlpha; + case BlendFactor::ONE_MINUS_DST_ALPHA: + return MTLBlendFactorOneMinusDestinationAlpha; + case BlendFactor::SRC_ALPHA_SATURATE: + return MTLBlendFactorSourceAlphaSaturated; + case BlendFactor::BLEND_CLOLOR: + return MTLBlendFactorBlendColor; + default: + return MTLBlendFactorZero; + } + } + + MTLBlendOperation toMTLBlendOperation(BlendOperation operation) + { + switch (operation) { + case BlendOperation::ADD: + return MTLBlendOperationAdd; + case BlendOperation::SUBTRACT: + return MTLBlendOperationSubtract; + case BlendOperation::RESERVE_SUBTRACT: + return MTLBlendOperationReverseSubtract; + default: + return MTLBlendOperationAdd; + } } } + +RenderPipelineMTL::RenderPipelineMTL(id mtlDevice) +: _mtlDevice(mtlDevice) +{ } -RenderPipelineMTL::RenderPipelineMTL(id mtlDevice) : _mtlDevice(mtlDevice) {} - -void RenderPipelineMTL::update(const RenderTarget* renderTarget, const PipelineDescriptor& pipelineDescirptor) +void RenderPipelineMTL::update(const RenderTarget* renderTarget, const PipelineDescriptor & pipelineDescirptor) { struct { @@ -179,140 +179,135 @@ void RenderPipelineMTL::update(const RenderTarget* renderTarget, const PipelineD unsigned int destinationRGBBlendFactor; unsigned int sourceAlphaBlendFactor; unsigned int destinationAlphaBlendFactor; - } hashMe; - + }hashMe; + memset(&hashMe, 0, sizeof(hashMe)); const auto& blendDescriptor = pipelineDescirptor.blendDescriptor; chooseAttachmentFormat(renderTarget, _colorAttachmentsFormat, _depthAttachmentFormat, _stencilAttachmentFormat); - auto program = static_cast(pipelineDescirptor.programState->getProgram()); - hashMe.vertexShaderHash = program->getVertexShader()->getHashValue(); + auto program = static_cast(pipelineDescirptor.programState->getProgram()); + hashMe.vertexShaderHash = program->getVertexShader()->getHashValue(); hashMe.fragmentShaderHash = program->getFragmentShader()->getHashValue(); memcpy(&hashMe.colorAttachment, &_colorAttachmentsFormat, sizeof(_colorAttachmentsFormat)); - hashMe.depthAttachment = _depthAttachmentFormat; - hashMe.stencilAttachment = _stencilAttachmentFormat; - hashMe.blendEnabled = blendDescriptor.blendEnabled; - hashMe.writeMask = (unsigned int)blendDescriptor.writeMask; - hashMe.rgbBlendOperation = (unsigned int)blendDescriptor.rgbBlendOperation; - hashMe.alphaBlendOperation = (unsigned int)blendDescriptor.alphaBlendOperation; - hashMe.sourceRGBBlendFactor = (unsigned int)blendDescriptor.sourceRGBBlendFactor; - hashMe.destinationRGBBlendFactor = (unsigned int)blendDescriptor.destinationRGBBlendFactor; - hashMe.sourceAlphaBlendFactor = (unsigned int)blendDescriptor.sourceAlphaBlendFactor; + hashMe.depthAttachment = _depthAttachmentFormat; + hashMe.stencilAttachment =_stencilAttachmentFormat; + hashMe.blendEnabled = blendDescriptor.blendEnabled; + hashMe.writeMask = (unsigned int)blendDescriptor.writeMask; + hashMe.rgbBlendOperation = (unsigned int)blendDescriptor.rgbBlendOperation; + hashMe.alphaBlendOperation = (unsigned int)blendDescriptor.alphaBlendOperation; + hashMe.sourceRGBBlendFactor = (unsigned int)blendDescriptor.sourceRGBBlendFactor; + hashMe.destinationRGBBlendFactor = (unsigned int)blendDescriptor.destinationRGBBlendFactor; + hashMe.sourceAlphaBlendFactor = (unsigned int)blendDescriptor.sourceAlphaBlendFactor; hashMe.destinationAlphaBlendFactor = (unsigned int)blendDescriptor.destinationAlphaBlendFactor; - int index = 0; - auto vertexLayout = pipelineDescirptor.programState->getVertexLayout(); - const auto& attributes = vertexLayout->getAttributes(); + int index = 0; + auto vertexLayout = pipelineDescirptor.programState->getVertexLayout(); + const auto& attributes = vertexLayout->getAttributes(); for (const auto& it : attributes) { - auto& attribute = it.second; + auto &attribute = it.second; /* stepFunction:1 stride:15 offest:10 format:5 needNormalized:1 bit31 bit30 ~ bit16 bit15 ~ bit6 bit5 ~ bit1 bit0 */ hashMe.vertexLayoutInfo[index++] = - ((unsigned int)vertexLayout->getVertexStepMode() & 0x1) << 31 | - ((unsigned int)(vertexLayout->getStride() & 0x7FFF)) << 16 | ((unsigned int)attribute.offset & 0x3FF) << 6 | - ((unsigned int)attribute.format & 0x1F) << 1 | ((unsigned int)attribute.needToBeNormallized & 0x1); + ((unsigned int)vertexLayout->getVertexStepMode() & 0x1) << 31 | + ((unsigned int)(vertexLayout->getStride() & 0x7FFF)) << 16 | + ((unsigned int)attribute.offset & 0x3FF) << 6 | + ((unsigned int)attribute.format & 0x1F) << 1 | + ((unsigned int)attribute.needToBeNormallized & 0x1); } - + unsigned int hash = XXH32((const void*)&hashMe, sizeof(hashMe), 0); - auto it = _mtlStateCache.find(hash); - if (it != _mtlStateCache.end()) - { + auto it = _mtlStateCache.find(hash); + if(it != _mtlStateCache.end()) { _mtlRenderPipelineState = it->second; return; } - + _mtlRenderPipelineDescriptor = [[MTLRenderPipelineDescriptor alloc] init]; - + setShaderModules(pipelineDescirptor); setVertexLayout(_mtlRenderPipelineDescriptor, pipelineDescirptor); - + setBlendStateAndFormat(pipelineDescirptor.blendDescriptor); - - NSError* error = nil; - _mtlRenderPipelineState = [_mtlDevice newRenderPipelineStateWithDescriptor:_mtlRenderPipelineDescriptor - error:&error]; + + NSError *error = nil; + _mtlRenderPipelineState = [_mtlDevice newRenderPipelineStateWithDescriptor:_mtlRenderPipelineDescriptor error:&error]; if (error) NSLog(@"Can not create renderpipeline state: %@", error); - + [_mtlRenderPipelineDescriptor release]; - + _mtlStateCache.emplace(hash, _mtlRenderPipelineState); } RenderPipelineMTL::~RenderPipelineMTL() { - for (auto& item : _mtlStateCache) + for(auto& item : _mtlStateCache) [item.second release]; } -void RenderPipelineMTL::setVertexLayout(MTLRenderPipelineDescriptor* mtlDescriptor, - const PipelineDescriptor& descriptor) +void RenderPipelineMTL::setVertexLayout(MTLRenderPipelineDescriptor* mtlDescriptor, const PipelineDescriptor& descriptor) { - int vertexIndex = 0; + int vertexIndex = 0; auto vertexLayout = descriptor.programState->getVertexLayout(); if (!vertexLayout->isValid()) return; - + mtlDescriptor.vertexDescriptor.layouts[vertexIndex].stride = vertexLayout->getStride(); - mtlDescriptor.vertexDescriptor.layouts[vertexIndex].stepFunction = - toMTLVertexStepFunction(vertexLayout->getVertexStepMode()); - + mtlDescriptor.vertexDescriptor.layouts[vertexIndex].stepFunction = toMTLVertexStepFunction(vertexLayout->getVertexStepMode()); + const auto& attributes = vertexLayout->getAttributes(); for (const auto& it : attributes) { auto attribute = it.second; - mtlDescriptor.vertexDescriptor.attributes[attribute.index].format = - toMTLVertexFormat(attribute.format, attribute.needToBeNormallized); + mtlDescriptor.vertexDescriptor.attributes[attribute.index].format = toMTLVertexFormat(attribute.format, attribute.needToBeNormallized); mtlDescriptor.vertexDescriptor.attributes[attribute.index].offset = attribute.offset; // Buffer index will always be 0; mtlDescriptor.vertexDescriptor.attributes[attribute.index].bufferIndex = 0; } + } void RenderPipelineMTL::setBlendState(MTLRenderPipelineColorAttachmentDescriptor* colorAttachmentDescriptor, const BlendDescriptor& blendDescriptor) { colorAttachmentDescriptor.blendingEnabled = blendDescriptor.blendEnabled; - colorAttachmentDescriptor.writeMask = toMTLColorWriteMask(blendDescriptor.writeMask); - - colorAttachmentDescriptor.rgbBlendOperation = toMTLBlendOperation(blendDescriptor.rgbBlendOperation); + colorAttachmentDescriptor.writeMask = toMTLColorWriteMask(blendDescriptor.writeMask); + + colorAttachmentDescriptor.rgbBlendOperation = toMTLBlendOperation(blendDescriptor.rgbBlendOperation); colorAttachmentDescriptor.alphaBlendOperation = toMTLBlendOperation(blendDescriptor.alphaBlendOperation); - - colorAttachmentDescriptor.sourceRGBBlendFactor = toMTLBlendFactor(blendDescriptor.sourceRGBBlendFactor); + + colorAttachmentDescriptor.sourceRGBBlendFactor = toMTLBlendFactor(blendDescriptor.sourceRGBBlendFactor); colorAttachmentDescriptor.destinationRGBBlendFactor = toMTLBlendFactor(blendDescriptor.destinationRGBBlendFactor); - colorAttachmentDescriptor.sourceAlphaBlendFactor = toMTLBlendFactor(blendDescriptor.sourceAlphaBlendFactor); - colorAttachmentDescriptor.destinationAlphaBlendFactor = - toMTLBlendFactor(blendDescriptor.destinationAlphaBlendFactor); + colorAttachmentDescriptor.sourceAlphaBlendFactor = toMTLBlendFactor(blendDescriptor.sourceAlphaBlendFactor); + colorAttachmentDescriptor.destinationAlphaBlendFactor = toMTLBlendFactor(blendDescriptor.destinationAlphaBlendFactor); } void RenderPipelineMTL::setShaderModules(const PipelineDescriptor& descriptor) { auto vertexShaderModule = static_cast(descriptor.programState->getProgram())->getVertexShader(); _mtlRenderPipelineDescriptor.vertexFunction = vertexShaderModule->getMTLFunction(); - + auto fragShaderModule = static_cast(descriptor.programState->getProgram())->getFragmentShader(); _mtlRenderPipelineDescriptor.fragmentFunction = fragShaderModule->getMTLFunction(); } void RenderPipelineMTL::chooseAttachmentFormat(const RenderTarget* renderTarget, - PixelFormat colorAttachmentsFormat[MAX_COLOR_ATTCHMENT], - PixelFormat& depthFormat, - PixelFormat& stencilFormat) + PixelFormat colorAttachmentsFormat[MAX_COLOR_ATTCHMENT], + PixelFormat& depthFormat, + PixelFormat& stencilFormat) { // Choose color attachment format - auto rtMTL = static_cast(renderTarget); + auto rtMTL = static_cast(renderTarget); auto rtflags = rtMTL->getTargetFlags(); - for (auto i = 0; i < MAX_COLOR_ATTCHMENT; ++i) - { - colorAttachmentsFormat[i] = - bitmask::any(rtflags, getMRTColorFlag(i)) ? rtMTL->getColorAttachmentPixelFormat(i) : PixelFormat::NONE; + for(auto i = 0; i < MAX_COLOR_ATTCHMENT; ++i) { + colorAttachmentsFormat[i] = bitmask::any(rtflags, getMRTColorFlag(i)) ? rtMTL->getColorAttachmentPixelFormat(i) : PixelFormat::NONE; } - + if (bitmask::any(rtflags, RenderTargetFlag::DEPTH_AND_STENCIL)) { - depthFormat = rtMTL->getDepthAttachmentPixelFormat(); - stencilFormat = rtMTL->getStencilAttachmentPixelFormat(); + depthFormat = rtMTL->getDepthAttachmentPixelFormat(); + stencilFormat =rtMTL->getStencilAttachmentPixelFormat(); } else { @@ -324,17 +319,15 @@ void RenderPipelineMTL::setBlendStateAndFormat(const BlendDescriptor& blendDescr { for (int i = 0; i < MAX_COLOR_ATTCHMENT; ++i) { - if (PixelFormat::NONE == _colorAttachmentsFormat[i]) - { + if (PixelFormat::NONE == _colorAttachmentsFormat[i]) { _mtlRenderPipelineDescriptor.colorAttachments[i].pixelFormat = MTLPixelFormat::MTLPixelFormatInvalid; continue; } - - _mtlRenderPipelineDescriptor.colorAttachments[i].pixelFormat = - UtilsMTL::toMTLPixelFormat(_colorAttachmentsFormat[i]); + + _mtlRenderPipelineDescriptor.colorAttachments[i].pixelFormat = UtilsMTL::toMTLPixelFormat(_colorAttachmentsFormat[i]); setBlendState(_mtlRenderPipelineDescriptor.colorAttachments[i], blendDescriptor); } - _mtlRenderPipelineDescriptor.depthAttachmentPixelFormat = UtilsMTL::toMTLPixelFormat(_depthAttachmentFormat); + _mtlRenderPipelineDescriptor.depthAttachmentPixelFormat = UtilsMTL::toMTLPixelFormat(_depthAttachmentFormat); _mtlRenderPipelineDescriptor.stencilAttachmentPixelFormat = UtilsMTL::toMTLPixelFormat(_stencilAttachmentFormat); } diff --git a/cocos/renderer/backend/metal/RenderTargetMTL.mm b/cocos/renderer/backend/metal/RenderTargetMTL.mm index d909f2efff..cd9b46e161 100644 --- a/cocos/renderer/backend/metal/RenderTargetMTL.mm +++ b/cocos/renderer/backend/metal/RenderTargetMTL.mm @@ -3,77 +3,83 @@ CC_BACKEND_BEGIN -static MTLLoadAction getLoadAction(const RenderPassDescriptor& params, TargetBufferFlags buffer) -{ - const auto clearFlags = (TargetBufferFlags)params.flags.clear; +static MTLLoadAction getLoadAction(const RenderPassDescriptor& params, + TargetBufferFlags buffer) { + const auto clearFlags = (TargetBufferFlags) params.flags.clear; const auto discardStartFlags = params.flags.discardStart; - if (bitmask::any(clearFlags, buffer)) - { + if (bitmask::any(clearFlags, buffer)) { return MTLLoadActionClear; - } - else if (bitmask::any(discardStartFlags, buffer)) - { + } else if (bitmask::any(discardStartFlags, buffer)) { return MTLLoadActionDontCare; } return MTLLoadActionLoad; } -static MTLStoreAction getStoreAction(const RenderPassDescriptor& params, TargetBufferFlags buffer) -{ +static MTLStoreAction getStoreAction(const RenderPassDescriptor& params, + TargetBufferFlags buffer) { const auto discardEndFlags = params.flags.discardEnd; - if (bitmask::any(discardEndFlags, buffer)) - { + if (bitmask::any(discardEndFlags, buffer)) { return MTLStoreActionDontCare; } return MTLStoreActionStore; } -RenderTargetMTL::RenderTargetMTL(bool defaultRenderTarget) : RenderTarget(defaultRenderTarget) {} -RenderTargetMTL::~RenderTargetMTL() {} +RenderTargetMTL::RenderTargetMTL(bool defaultRenderTarget) : RenderTarget(defaultRenderTarget) +{ + +} +RenderTargetMTL::~RenderTargetMTL() +{ +} -void RenderTargetMTL::bindFrameBuffer() const {} +void RenderTargetMTL::bindFrameBuffer() const +{ +} -void RenderTargetMTL::unbindFrameBuffer() const {} +void RenderTargetMTL::unbindFrameBuffer() const +{ +} void RenderTargetMTL::setColorAttachment(ColorAttachment attachment) { RenderTarget::setColorAttachment(attachment); + + } void RenderTargetMTL::setDepthAttachment(TextureBackend* attachment, int level) { RenderTarget::setDepthAttachment(attachment, level); + + } void RenderTargetMTL::setStencilAttachment(TextureBackend* attachment, int level) { RenderTarget::setStencilAttachment(attachment, level); + } -void RenderTargetMTL::applyRenderPassAttachments(const RenderPassDescriptor& params, - MTLRenderPassDescriptor* descriptor) const +void RenderTargetMTL::applyRenderPassAttachments(const RenderPassDescriptor& params, MTLRenderPassDescriptor* descriptor) const { // const auto discardFlags = params.flags.discardEnd; auto clearFlags = params.flags.clear; - - for (size_t i = 0; i < MAX_COLOR_ATTCHMENT; i++) - { + + for (size_t i = 0; i < MAX_COLOR_ATTCHMENT; i++) { auto attachment = getColorAttachment(i); - if (!attachment) - { + if (!attachment) { continue; } - + const auto MRTColorFlag = getMRTColorFlag(i); - + descriptor.colorAttachments[i].texture = attachment.texture; - descriptor.colorAttachments[i].level = attachment.level; + descriptor.colorAttachments[i].level = attachment.level; // descriptor.colorAttachments[i].slice = attachment.layer; - descriptor.colorAttachments[i].loadAction = getLoadAction(params, MRTColorFlag); - descriptor.colorAttachments[i].storeAction = getStoreAction(params, MRTColorFlag); - if (bitmask::any(clearFlags, MRTColorFlag)) - descriptor.colorAttachments[i].clearColor = - MTLClearColorMake(params.clearColorValue[0], params.clearColorValue[1], params.clearColorValue[2], - params.clearColorValue[3]); + descriptor.colorAttachments[i].loadAction = getLoadAction(params, MRTColorFlag); + descriptor.colorAttachments[i].storeAction = getStoreAction(params,MRTColorFlag); + if(bitmask::any(clearFlags, MRTColorFlag)) + descriptor.colorAttachments[i].clearColor = MTLClearColorMake( + params.clearColorValue[0], params.clearColorValue[1], params.clearColorValue[2], params.clearColorValue[3]); #if 0 if (multisampledColor[i]) { // We're rendering into our temporary MSAA texture and doing an automatic resolve. @@ -93,35 +99,32 @@ void RenderTargetMTL::applyRenderPassAttachments(const RenderPassDescriptor& par } #endif } - + // Sets descriptor depth and stencil params, should match RenderTargetMTL::chooseAttachmentFormat - if (bitmask::any(this->_flags, RenderTargetFlag::DEPTH_AND_STENCIL)) - { + if(bitmask::any(this->_flags, RenderTargetFlag::DEPTH_AND_STENCIL)) { auto depthAttachment = getDepthAttachment(); - if (depthAttachment) - { + if(depthAttachment){ descriptor.depthAttachment.texture = depthAttachment.texture; - descriptor.depthAttachment.level = depthAttachment.level; + descriptor.depthAttachment.level = depthAttachment.level; // descriptor.depthAttachment.slice = depthAttachment.layer; - descriptor.depthAttachment.loadAction = getLoadAction(params, TargetBufferFlags::DEPTH); + descriptor.depthAttachment.loadAction = getLoadAction(params, TargetBufferFlags::DEPTH); descriptor.depthAttachment.storeAction = getStoreAction(params, TargetBufferFlags::DEPTH); - if (bitmask::any(clearFlags, TargetBufferFlags::DEPTH)) + if(bitmask::any(clearFlags, TargetBufferFlags::DEPTH)) descriptor.depthAttachment.clearDepth = params.clearDepthValue; } - + auto stencilAttachment = getStencilAttachment(); - if (stencilAttachment) - { + if(stencilAttachment) { descriptor.stencilAttachment.texture = stencilAttachment.texture; - descriptor.stencilAttachment.level = stencilAttachment.level; + descriptor.stencilAttachment.level = stencilAttachment.level; // descriptor.stencilAttachment.slice = depthAttachment.layer; - descriptor.stencilAttachment.loadAction = getLoadAction(params, TargetBufferFlags::STENCIL); + descriptor.stencilAttachment.loadAction = getLoadAction(params, TargetBufferFlags::STENCIL); descriptor.stencilAttachment.storeAction = getStoreAction(params, TargetBufferFlags::STENCIL); - if (bitmask::any(clearFlags, TargetBufferFlags::STENCIL)) + if(bitmask::any(clearFlags, TargetBufferFlags::STENCIL)) descriptor.stencilAttachment.clearStencil = params.clearStencilValue; } } - + #if 0 if (multisampledDepth) { // We're rendering into our temporary MSAA texture and doing an automatic resolve. @@ -144,16 +147,15 @@ void RenderTargetMTL::applyRenderPassAttachments(const RenderPassDescriptor& par RenderTargetMTL::Attachment RenderTargetMTL::getColorAttachment(int index) const { - if (isDefaultRenderTarget() && index == 0) + if(isDefaultRenderTarget() && index == 0) return {DeviceMTL::getCurrentDrawable().texture, 0}; auto& rb = this->_color[index]; - return RenderTargetMTL::Attachment{static_cast(rb) ? (id)(rb.texture->getHandler()) : nil, - rb.level}; + return RenderTargetMTL::Attachment{static_cast(rb) ? (id)(rb.texture->getHandler()) : nil, rb.level}; } RenderTargetMTL::Attachment RenderTargetMTL::getDepthAttachment() const { - if (isDefaultRenderTarget()) + if(isDefaultRenderTarget()) return {UtilsMTL::getDefaultDepthStencilTexture(), 0}; auto& rb = this->_depth; return RenderTargetMTL::Attachment{!!rb ? (id)(rb.texture->getHandler()) : nil, rb.level}; @@ -161,7 +163,7 @@ RenderTargetMTL::Attachment RenderTargetMTL::getDepthAttachment() const RenderTargetMTL::Attachment RenderTargetMTL::getStencilAttachment() const { - if (isDefaultRenderTarget()) + if(isDefaultRenderTarget()) return RenderTargetMTL::Attachment{UtilsMTL::getDefaultDepthStencilTexture(), 0}; auto& rb = this->_stencil; return RenderTargetMTL::Attachment{!!rb ? (id)(rb.texture->getHandler()) : nil, rb.level}; @@ -171,17 +173,16 @@ PixelFormat RenderTargetMTL::getColorAttachmentPixelFormat(int index) const { // !!!important // the default framebuffer pixel format is: MTLPixelFormatBGRA8Unorm - if (isDefaultRenderTarget() && index == 0) + if(isDefaultRenderTarget() && index == 0) return PixelFormat::BGRA8; auto& rb = this->_color[index]; return rb ? rb.texture->getTextureFormat() : PixelFormat::NONE; } PixelFormat RenderTargetMTL::getDepthAttachmentPixelFormat() const -{ // FIXME: adxe only support D24S8 - if (bitmask::any(_flags, TargetBufferFlags::DEPTH_AND_STENCIL)) - { - if (isDefaultRenderTarget() || !_depth) +{ // FIXME: adxe only support D24S8 + if(bitmask::any(_flags, TargetBufferFlags::DEPTH_AND_STENCIL)) { + if(isDefaultRenderTarget() || !_depth) return PixelFormat::D24S8; return _depth.texture->getTextureFormat(); } @@ -189,10 +190,9 @@ PixelFormat RenderTargetMTL::getDepthAttachmentPixelFormat() const } PixelFormat RenderTargetMTL::getStencilAttachmentPixelFormat() const -{ // FIXME: adxe only support D24S8 - if (bitmask::any(_flags, TargetBufferFlags::DEPTH_AND_STENCIL)) - { - if (isDefaultRenderTarget() || !_stencil) +{ // FIXME: adxe only support D24S8 + if(bitmask::any(_flags, TargetBufferFlags::DEPTH_AND_STENCIL)) { + if(isDefaultRenderTarget() || !_stencil) return PixelFormat::D24S8; return _stencil.texture->getTextureFormat(); } diff --git a/cocos/renderer/backend/metal/ShaderModuleMTL.h b/cocos/renderer/backend/metal/ShaderModuleMTL.h index d8fe9df735..1272c3b409 100644 --- a/cocos/renderer/backend/metal/ShaderModuleMTL.h +++ b/cocos/renderer/backend/metal/ShaderModuleMTL.h @@ -52,7 +52,7 @@ public: * @param stage Specify what kinds of shader to be created. * @param source Specify the shader source. */ - ShaderModuleMTL(id mtlDevice, ShaderStage stage, std::string_view source); + ShaderModuleMTL(id mtlDevice, ShaderStage stage, const std::string& source); ~ShaderModuleMTL(); /** @@ -71,7 +71,7 @@ public: * Get all uniformInfos. * @return The uniformInfos. */ - inline const hlookup::string_map& getAllActiveUniformInfo() const { return _uniformInfos; } + inline const std::unordered_map& getAllActiveUniformInfo() const { return _uniformInfos; } /** * Get maximum uniform location. @@ -83,7 +83,7 @@ public: * Get active attribute informations. * @return Active attribute informations. key is attribute name and Value is corresponding attribute info. */ - inline const hlookup::string_map getAttributeInfo() const { return _attributeInfo; } + inline const std::unordered_map getAttributeInfo() const { return _attributeInfo; } /** * Get uniform location by engine built-in uniform enum name. @@ -97,7 +97,7 @@ public: * @param uniform Specifies the uniform name. * @return The uniform location. */ - int getUniformLocation(std::string_view name) const; + int getUniformLocation(const std::string& name) const; /** * Get attribute location by engine built-in attribute enum name. @@ -111,7 +111,7 @@ public: * @param name Specifies the attribute name. * @return The attribute location. */ - int getAttributeLocation(std::string_view name); + int getAttributeLocation(std::string name); /** * Get uniform buffer size in bytes that holds all the uniforms. @@ -128,9 +128,9 @@ private: id _mtlFunction = nil; - hlookup::string_map _uniformInfos; + std::unordered_map _uniformInfos; std::unordered_map _activeUniformInfos; - hlookup::string_map _attributeInfo; + std::unordered_map _attributeInfo; int _maxLocation = -1; int _uniformLocation[UNIFORM_MAX]; diff --git a/cocos/renderer/backend/metal/ShaderModuleMTL.mm b/cocos/renderer/backend/metal/ShaderModuleMTL.mm index f52e414a78..d0f8291a41 100644 --- a/cocos/renderer/backend/metal/ShaderModuleMTL.mm +++ b/cocos/renderer/backend/metal/ShaderModuleMTL.mm @@ -21,7 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "ShaderModuleMTL.h" #include "DeviceMTL.h" @@ -29,41 +29,43 @@ CC_BACKEND_BEGIN -ShaderModuleMTL::ShaderModuleMTL(id mtlDevice, ShaderStage stage, std::string_view source) - : ShaderModule(stage) +ShaderModuleMTL::ShaderModuleMTL(id mtlDevice, ShaderStage stage, const std::string& source) +: ShaderModule(stage) { // Convert GLSL shader to metal shader - // TODO: don't crreate/destroy ctx every time. - glslopt_ctx* ctx = glslopt_initialize(kGlslTargetMetal); + //TODO: don't crreate/destroy ctx every time. + glslopt_ctx* ctx = glslopt_initialize(kGlslTargetMetal); glslopt_shader_type shaderType = stage == ShaderStage::VERTEX ? kGlslOptShaderVertex : kGlslOptShaderFragment; - glslopt_shader* glslShader = glslopt_optimize(ctx, shaderType, source.data(), 0); + glslopt_shader* glslShader = glslopt_optimize(ctx, shaderType, source.c_str(), 0); if (!glslShader) { NSLog(@"Can not translate GLSL shader to metal shader:"); - NSLog(@"%s", source.data()); + NSLog(@"%s", source.c_str()); return; } - + const char* metalShader = glslopt_get_output(glslShader); if (!metalShader) { NSLog(@"Can not get metal shader:"); - NSLog(@"%s", source.data()); + NSLog(@"%s", source.c_str()); glslopt_cleanup(ctx); return; } - - // NSLog(@"%s", metalShader); - + +// NSLog(@"%s", metalShader); + parseAttibute(mtlDevice, glslShader); parseUniform(mtlDevice, glslShader); parseTexture(mtlDevice, glslShader); setBuiltinUniformLocation(); setBuiltinAttributeLocation(); - + NSString* shader = [NSString stringWithUTF8String:metalShader]; NSError* error; - id library = [mtlDevice newLibraryWithSource:shader options:nil error:&error]; + id library = [mtlDevice newLibraryWithSource:shader + options:nil + error:&error]; if (!library) { NSLog(@"Can not compile metal shader: %@", error); @@ -72,7 +74,7 @@ ShaderModuleMTL::ShaderModuleMTL(id mtlDevice, ShaderStage stage, std glslopt_cleanup(ctx); return; } - + if (ShaderStage::VERTEX == stage) _mtlFunction = [library newFunctionWithName:@"xlatMtlMain1"]; else @@ -83,7 +85,7 @@ ShaderModuleMTL::ShaderModuleMTL(id mtlDevice, ShaderStage stage, std NSLog(@"%s", metalShader); assert(false); } - + glslopt_shader_delete(glslShader); glslopt_cleanup(ctx); [library release]; @@ -97,27 +99,26 @@ ShaderModuleMTL::~ShaderModuleMTL() void ShaderModuleMTL::parseAttibute(id mtlDevice, glslopt_shader* shader) { const int attributeCount = glslopt_shader_get_input_count(shader); - for (int i = 0; i < attributeCount; i++) + for(int i = 0; i < attributeCount; i++) { const char* parName; glslopt_basic_type parType; glslopt_precision parPrec; int parVecSize, parMatSize, parArrSize, location; - glslopt_shader_get_input_desc(shader, i, &parName, &parType, &parPrec, &parVecSize, &parMatSize, &parArrSize, - &location); - + glslopt_shader_get_input_desc(shader, i, &parName, &parType, &parPrec, &parVecSize, &parMatSize, &parArrSize, &location); + AttributeBindInfo attributeInfo; attributeInfo.attributeName = parName; - attributeInfo.location = location; - _attributeInfo[parName] = attributeInfo; + attributeInfo.location = location; + _attributeInfo[parName] = attributeInfo; } } void ShaderModuleMTL::parseUniform(id mtlDevice, glslopt_shader* shader) { const int uniformCount = glslopt_shader_get_uniform_count(shader); - _uniformBufferSize = glslopt_shader_get_uniform_total_size(shader); - + _uniformBufferSize = glslopt_shader_get_uniform_total_size(shader); + for (int i = 0; i < uniformCount; ++i) { int nextLocation = -1; @@ -125,33 +126,31 @@ void ShaderModuleMTL::parseUniform(id mtlDevice, glslopt_shader* shad glslopt_basic_type parType; glslopt_precision parPrec; int parVecSize, parMatSize, parArrSize, location; - if (i + 1 < uniformCount) + if( i+1 < uniformCount) { - glslopt_shader_get_uniform_desc(shader, i + 1, &parName, &parType, &parPrec, &parVecSize, &parMatSize, - &parArrSize, &location); + glslopt_shader_get_uniform_desc(shader, i+1, &parName, &parType, &parPrec, &parVecSize, &parMatSize, &parArrSize, &location); nextLocation = location; } else { nextLocation = static_cast(_uniformBufferSize); } - - glslopt_shader_get_uniform_desc(shader, i, &parName, &parType, &parPrec, &parVecSize, &parMatSize, &parArrSize, - &location); - + + glslopt_shader_get_uniform_desc(shader, i, &parName, &parType, &parPrec, &parVecSize, &parMatSize, &parArrSize, &location); + parArrSize = (parArrSize > 0) ? parArrSize : 1; UniformInfo uniform; - uniform.count = parArrSize; - uniform.location = location; - uniform.isArray = parArrSize; - uniform.size = nextLocation - location; - uniform.bufferOffset = location; - uniform.needConvert = (parVecSize == 3) ? true : false; - uniform.type = static_cast(parType); - uniform.isMatrix = (parMatSize > 1) ? true : false; - _uniformInfos[parName] = uniform; + uniform.count = parArrSize; + uniform.location = location; + uniform.isArray = parArrSize; + uniform.size = nextLocation - location; + uniform.bufferOffset = location; + uniform.needConvert = (parVecSize == 3) ? true : false; + uniform.type = static_cast(parType); + uniform.isMatrix = (parMatSize > 1) ? true : false; + _uniformInfos[parName] = uniform; _activeUniformInfos[location] = uniform; - _maxLocation = _maxLocation < location ? (location + 1) : _maxLocation; + _maxLocation = _maxLocation < location ? (location + 1) : _maxLocation; } } @@ -160,12 +159,12 @@ int ShaderModuleMTL::getUniformLocation(Uniform name) const return _uniformLocation[name]; } -int ShaderModuleMTL::getUniformLocation(std::string_view name) const +int ShaderModuleMTL::getUniformLocation(const std::string& name) const { - auto iter = _uniformInfos.find(name); - if (iter != _uniformInfos.end()) + const auto& iter = _uniformInfos.find(name); + if(iter != _uniformInfos.end()) { - return iter->second.location; + return _uniformInfos.at(name).location; } else return -1; @@ -174,44 +173,44 @@ int ShaderModuleMTL::getUniformLocation(std::string_view name) const void ShaderModuleMTL::setBuiltinUniformLocation() { std::fill(_uniformLocation, _uniformLocation + UNIFORM_MAX, -1); - /// u_mvpMatrix + ///u_mvpMatrix auto iter = _uniformInfos.find(UNIFORM_NAME_MVP_MATRIX); - if (iter != _uniformInfos.end()) + if(iter != _uniformInfos.end()) { _uniformLocation[Uniform::MVP_MATRIX] = iter->second.location; } - - /// u_textColor + + ///u_textColor iter = _uniformInfos.find(UNIFORM_NAME_TEXT_COLOR); - if (iter != _uniformInfos.end()) + if(iter != _uniformInfos.end()) { _uniformLocation[Uniform::TEXT_COLOR] = iter->second.location; } - - /// u_effectColor + + ///u_effectColor iter = _uniformInfos.find(UNIFORM_NAME_EFFECT_COLOR); - if (iter != _uniformInfos.end()) + if(iter != _uniformInfos.end()) { _uniformLocation[Uniform::EFFECT_COLOR] = iter->second.location; } - - /// u_effectType + + ///u_effectType iter = _uniformInfos.find(UNIFORM_NAME_EFFECT_TYPE); - if (iter != _uniformInfos.end()) + if(iter != _uniformInfos.end()) { _uniformLocation[Uniform::EFFECT_TYPE] = iter->second.location; } - - /// u_texture + + ///u_texture iter = _uniformInfos.find(UNIFORM_NAME_TEXTURE); - if (iter != _uniformInfos.end()) + if(iter != _uniformInfos.end()) { _uniformLocation[Uniform::TEXTURE] = iter->second.location; } - - /// u_texture1 + + ///u_texture1 iter = _uniformInfos.find(UNIFORM_NAME_TEXTURE1); - if (iter != _uniformInfos.end()) + if(iter != _uniformInfos.end()) { _uniformLocation[Uniform::TEXTURE1] = iter->second.location; } @@ -222,10 +221,10 @@ int ShaderModuleMTL::getAttributeLocation(Attribute name) const return _attributeLocation[name]; } -int ShaderModuleMTL::getAttributeLocation(std::string_view name) +int ShaderModuleMTL::getAttributeLocation(std::string name) { auto iter = _attributeInfo.find(name); - if (iter != _attributeInfo.end()) + if(iter != _attributeInfo.end()) return _attributeInfo[name].location; else return -1; @@ -234,23 +233,23 @@ int ShaderModuleMTL::getAttributeLocation(std::string_view name) void ShaderModuleMTL::setBuiltinAttributeLocation() { std::fill(_attributeLocation, _attributeLocation + ATTRIBUTE_MAX, -1); - /// a_position + ///a_position auto iter = _attributeInfo.find(ATTRIBUTE_NAME_POSITION); - if (iter != _attributeInfo.end()) + if(iter != _attributeInfo.end()) { _attributeLocation[Attribute::POSITION] = iter->second.location; } - - /// a_color + + ///a_color iter = _attributeInfo.find(ATTRIBUTE_NAME_COLOR); - if (iter != _attributeInfo.end()) + if(iter != _attributeInfo.end()) { _attributeLocation[Attribute::COLOR] = iter->second.location; } - - /// a_texCoord + + ///a_texCoord iter = _attributeInfo.find(ATTRIBUTE_NAME_TEXCOORD); - if (iter != _attributeInfo.end()) + if(iter != _attributeInfo.end()) { _attributeLocation[Attribute::TEXCOORD] = iter->second.location; } @@ -265,13 +264,12 @@ void ShaderModuleMTL::parseTexture(id mtlDevice, glslopt_shader* shad glslopt_basic_type parType; glslopt_precision parPrec; int parVecSize, parMatSize, parArrSize, location; - glslopt_shader_get_texture_desc(shader, i, &parName, &parType, &parPrec, &parVecSize, &parMatSize, &parArrSize, - &location); - + glslopt_shader_get_texture_desc(shader, i, &parName, &parType, &parPrec, &parVecSize, &parMatSize, &parArrSize, &location); + UniformInfo uniform; - uniform.count = parArrSize; - uniform.location = location; - uniform.isArray = parArrSize > 0; + uniform.count = parArrSize; + uniform.location = location; + uniform.isArray = parArrSize > 0; _uniformInfos[parName] = uniform; } } diff --git a/cocos/renderer/backend/metal/TextureMTL.mm b/cocos/renderer/backend/metal/TextureMTL.mm index 332aa6f1e0..ff1929f104 100644 --- a/cocos/renderer/backend/metal/TextureMTL.mm +++ b/cocos/renderer/backend/metal/TextureMTL.mm @@ -21,7 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "TextureMTL.h" #include "UtilsMTL.h" #include "base/ccMacros.h" @@ -31,86 +31,78 @@ CC_BACKEND_BEGIN namespace { -MTLSamplerAddressMode toMTLSamplerAddressMode(SamplerAddressMode mode) -{ - MTLSamplerAddressMode ret = MTLSamplerAddressModeRepeat; - switch (mode) + MTLSamplerAddressMode toMTLSamplerAddressMode(SamplerAddressMode mode) { - case SamplerAddressMode::REPEAT: - ret = MTLSamplerAddressModeRepeat; - break; - case SamplerAddressMode::MIRROR_REPEAT: - ret = MTLSamplerAddressModeMirrorRepeat; - break; - case SamplerAddressMode::CLAMP_TO_EDGE: - ret = MTLSamplerAddressModeClampToEdge; - break; - default: - CCASSERT(false, "Not supported sampler address mode!"); - break; + MTLSamplerAddressMode ret = MTLSamplerAddressModeRepeat; + switch (mode) { + case SamplerAddressMode::REPEAT: + ret = MTLSamplerAddressModeRepeat; + break; + case SamplerAddressMode::MIRROR_REPEAT: + ret = MTLSamplerAddressModeMirrorRepeat; + break; + case SamplerAddressMode::CLAMP_TO_EDGE: + ret = MTLSamplerAddressModeClampToEdge; + break; + default: + CCASSERT(false, "Not supported sampler address mode!"); + break; + } + return ret; } - return ret; -} - -MTLSamplerMinMagFilter toMTLSamplerMinMagFilter(SamplerFilter mode) -{ - switch (mode) + + MTLSamplerMinMagFilter toMTLSamplerMinMagFilter(SamplerFilter mode) { - case SamplerFilter::NEAREST: - case SamplerFilter::NEAREST_MIPMAP_LINEAR: - case SamplerFilter::NEAREST_MIPMAP_NEAREST: - return MTLSamplerMinMagFilterNearest; - case SamplerFilter::LINEAR: - case SamplerFilter::LINEAR_MIPMAP_LINEAR: - case SamplerFilter::LINEAR_MIPMAP_NEAREST: - return MTLSamplerMinMagFilterLinear; - case SamplerFilter::DONT_CARE: - return MTLSamplerMinMagFilterNearest; + switch (mode) { + case SamplerFilter::NEAREST: + case SamplerFilter::NEAREST_MIPMAP_LINEAR: + case SamplerFilter::NEAREST_MIPMAP_NEAREST: + return MTLSamplerMinMagFilterNearest; + case SamplerFilter::LINEAR: + case SamplerFilter::LINEAR_MIPMAP_LINEAR: + case SamplerFilter::LINEAR_MIPMAP_NEAREST: + return MTLSamplerMinMagFilterLinear; + case SamplerFilter::DONT_CARE: + return MTLSamplerMinMagFilterNearest; + } } -} - -bool isColorRenderable(PixelFormat textureFormat) -{ - switch (textureFormat) + + bool isColorRenderable(PixelFormat textureFormat) { - case PixelFormat::RGBA8: - case PixelFormat::RGBA4: - case PixelFormat::RGB565: - case PixelFormat::RGB5A1: - return true; - default: - return false; + switch (textureFormat) + { + case PixelFormat::RGBA8: + case PixelFormat::RGBA4: + case PixelFormat::RGB565: + case PixelFormat::RGB5A1: + return true; + default: + return false; + } } } -} /// CLASS TextureInfoMTL id TextureInfoMTL::ensure(int index, int target) { - if (index < CC_META_TEXTURES) - { + if(index < CC_META_TEXTURES) { id& mtlTexture = _mtlTextures[index]; - if (mtlTexture) - return mtlTexture; + if(mtlTexture) return mtlTexture; mtlTexture = createTexture(_mtlDevice, _descriptor, target); - if (_maxIdx < index) - _maxIdx = index; + if(_maxIdx < index) _maxIdx = index; return mtlTexture; } return nil; } -void TextureInfoMTL::destroy() -{ - if (_maxIdx == -1) - return; +void TextureInfoMTL::destroy() { + if(_maxIdx == -1) return; id texture; int i = 0; - while ((texture = _mtlTextures[i++])) + while((texture = _mtlTextures[i++])) [texture release]; - if (_mtlSamplerState) - { + if(_mtlSamplerState) { [_mtlSamplerState release]; _mtlSamplerState = nil; } @@ -120,143 +112,120 @@ void TextureInfoMTL::destroy() id TextureInfoMTL::createTexture(id mtlDevice, const TextureDescriptor& descriptor, int target) { MTLPixelFormat pixelFormat = UtilsMTL::toMTLPixelFormat(descriptor.textureFormat); - if (pixelFormat == MTLPixelFormatInvalid) + if(pixelFormat == MTLPixelFormatInvalid) return nil; - + MTLTextureDescriptor* textureDescriptor = nil; - switch (target) - { + switch(target) { case MTL_TEXTURE_2D: textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:pixelFormat - width:descriptor.width - height:descriptor.height - mipmapped:YES]; + width:descriptor.width + height:descriptor.height + mipmapped:YES]; break; case MTL_TEXTURE_CUBE: - textureDescriptor = [MTLTextureDescriptor textureCubeDescriptorWithPixelFormat:pixelFormat - size:descriptor.width - mipmapped:YES]; + textureDescriptor = [MTLTextureDescriptor textureCubeDescriptorWithPixelFormat:pixelFormat size:descriptor.width mipmapped:YES]; break; - default: - return nil; + default: return nil; } - + if (TextureUsage::RENDER_TARGET == descriptor.textureUsage) { - // DepthStencil, and Multisample textures must be allocated with the MTLResourceStorageModePrivate resource - // option - if (PixelFormat::D24S8 == descriptor.textureFormat && target == MTL_TEXTURE_2D) + //DepthStencil, and Multisample textures must be allocated with the MTLResourceStorageModePrivate resource option + if(PixelFormat::D24S8 == descriptor.textureFormat && target == MTL_TEXTURE_2D) textureDescriptor.resourceOptions = MTLResourceStorageModePrivate; textureDescriptor.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead; } - + return [mtlDevice newTextureWithDescriptor:textureDescriptor]; } -void TextureInfoMTL::recreateSampler(const SamplerDescriptor& descriptor) +void TextureInfoMTL::recreateSampler(const SamplerDescriptor &descriptor) { - MTLSamplerDescriptor* mtlDescriptor = [MTLSamplerDescriptor new]; - mtlDescriptor.sAddressMode = descriptor.sAddressMode == SamplerAddressMode::DONT_CARE - ? _sAddressMode - : toMTLSamplerAddressMode(descriptor.sAddressMode); - mtlDescriptor.tAddressMode = descriptor.tAddressMode == SamplerAddressMode::DONT_CARE - ? _tAddressMode - : toMTLSamplerAddressMode(descriptor.tAddressMode); - - mtlDescriptor.minFilter = - descriptor.minFilter == SamplerFilter::DONT_CARE ? _minFilter : toMTLSamplerMinMagFilter(descriptor.minFilter); - mtlDescriptor.magFilter = - descriptor.magFilter == SamplerFilter::DONT_CARE ? _magFilter : toMTLSamplerMinMagFilter(descriptor.magFilter); - - if (_mtlSamplerState) + MTLSamplerDescriptor *mtlDescriptor = [MTLSamplerDescriptor new]; + mtlDescriptor.sAddressMode = descriptor.sAddressMode == SamplerAddressMode::DONT_CARE ? _sAddressMode : toMTLSamplerAddressMode(descriptor.sAddressMode); + mtlDescriptor.tAddressMode = descriptor.tAddressMode == SamplerAddressMode::DONT_CARE ? _tAddressMode : toMTLSamplerAddressMode(descriptor.tAddressMode); + + mtlDescriptor.minFilter = descriptor.minFilter == SamplerFilter::DONT_CARE ? _minFilter : toMTLSamplerMinMagFilter(descriptor.minFilter); + mtlDescriptor.magFilter = descriptor.magFilter == SamplerFilter::DONT_CARE ? _magFilter : toMTLSamplerMinMagFilter(descriptor.magFilter); + + if(_mtlSamplerState) { [_mtlSamplerState release]; _mtlSamplerState = nil; } - + _sAddressMode = mtlDescriptor.sAddressMode; _tAddressMode = mtlDescriptor.tAddressMode; - _minFilter = mtlDescriptor.minFilter; - _magFilter = mtlDescriptor.magFilter; - _mipFilter = mtlDescriptor.mipFilter; - + _minFilter = mtlDescriptor.minFilter; + _magFilter = mtlDescriptor.magFilter; + _mipFilter = mtlDescriptor.mipFilter; + _mtlSamplerState = [_mtlDevice newSamplerStateWithDescriptor:mtlDescriptor]; - + [mtlDescriptor release]; } /// CLASS TextureMTL -TextureMTL::TextureMTL(id mtlDevice, const TextureDescriptor& descriptor) : _textureInfo(mtlDevice) +TextureMTL::TextureMTL(id mtlDevice, const TextureDescriptor& descriptor) +: _textureInfo(mtlDevice) { updateTextureDescriptor(descriptor); } -TextureMTL::~TextureMTL() {} +TextureMTL::~TextureMTL() +{ +} -void TextureMTL::updateSamplerDescriptor(const SamplerDescriptor& sampler) +void TextureMTL::updateSamplerDescriptor(const SamplerDescriptor &sampler) { _textureInfo.recreateSampler(sampler); } -void TextureMTL::updateTextureDescriptor(const cocos2d::backend::TextureDescriptor& descriptor, int index) +void TextureMTL::updateTextureDescriptor(const cocos2d::backend::TextureDescriptor &descriptor, int index) { TextureBackend::updateTextureDescriptor(descriptor, index); _textureInfo._descriptor = descriptor; _textureInfo.ensure(index, MTL_TEXTURE_2D); updateSamplerDescriptor(descriptor.samplerDescriptor); - + _textureInfo._bytesPerRow = PixelFormatUtils::computeRowPitch(descriptor.textureFormat, descriptor.width); } -void TextureMTL::updateData(uint8_t* data, std::size_t width, std::size_t height, std::size_t level, int index) +void TextureMTL::updateData(uint8_t* data, std::size_t width , std::size_t height, std::size_t level, int index) { updateSubData(0, 0, width, height, level, data, index); } -void TextureMTL::updateSubData(std::size_t xoffset, - std::size_t yoffset, - std::size_t width, - std::size_t height, - std::size_t level, - uint8_t* data, - int index) +void TextureMTL::updateSubData(std::size_t xoffset, std::size_t yoffset, std::size_t width, std::size_t height, std::size_t level, uint8_t* data, int index) { auto mtlTexture = _textureInfo.ensure(index, MTL_TEXTURE_2D); - if (!mtlTexture) - return; - - MTLRegion region = { + if(!mtlTexture) return; + + MTLRegion region = + { {xoffset, yoffset, 0}, // MTLOrigin {width, height, 1} // MTLSize }; - + auto bytesPerRow = PixelFormatUtils::computeRowPitch(_textureFormat, width); - - [mtlTexture replaceRegion:region mipmapLevel:level withBytes:data bytesPerRow:bytesPerRow]; - - if (!_hasMipmaps && level > 0) + + [mtlTexture replaceRegion:region + mipmapLevel:level + withBytes:data + bytesPerRow:bytesPerRow]; + + if(!_hasMipmaps && level > 0) _hasMipmaps = true; } -void TextureMTL::updateCompressedData(uint8_t* data, - std::size_t width, - std::size_t height, - std::size_t dataLen, - std::size_t level, - int index) +void TextureMTL::updateCompressedData(uint8_t *data, std::size_t width, std::size_t height, std::size_t dataLen, std::size_t level, int index) { updateCompressedSubData(0, 0, width, height, dataLen, level, data, index); } -void TextureMTL::updateCompressedSubData(std::size_t xoffset, - std::size_t yoffset, - std::size_t width, - std::size_t height, - std::size_t dataLen, - std::size_t level, - uint8_t* data, - int index) +void TextureMTL::updateCompressedSubData(std::size_t xoffset, std::size_t yoffset, std::size_t width, std::size_t height, std::size_t dataLen, std::size_t level, uint8_t *data, int index) { updateSubData(xoffset, yoffset, width, height, level, data, index); } @@ -265,8 +234,8 @@ void TextureMTL::generateMipmaps() { if (TextureUsage::RENDER_TARGET == _textureUsage || isColorRenderable(_textureFormat) == false) return; - - if (!_hasMipmaps) + + if(!_hasMipmaps) { _hasMipmaps = true; UtilsMTL::generateMipmaps(reinterpret_cast>(this->getHandler())); @@ -274,52 +243,54 @@ void TextureMTL::generateMipmaps() } /// CLASS TextureCubeMTL -TextureCubeMTL::TextureCubeMTL(id mtlDevice, const TextureDescriptor& descriptor) : _textureInfo(mtlDevice) +TextureCubeMTL::TextureCubeMTL(id mtlDevice, const TextureDescriptor& descriptor) +: _textureInfo(mtlDevice) { updateTextureDescriptor(descriptor); } -TextureCubeMTL::~TextureCubeMTL() {} +TextureCubeMTL::~TextureCubeMTL() +{ +} -void TextureCubeMTL::updateTextureDescriptor(const cocos2d::backend::TextureDescriptor& descriptor, int index) +void TextureCubeMTL::updateTextureDescriptor(const cocos2d::backend::TextureDescriptor &descriptor, int index) { TextureBackend::updateTextureDescriptor(descriptor, index); _textureInfo._descriptor = descriptor; _textureInfo.ensure(index, MTL_TEXTURE_CUBE); updateSamplerDescriptor(descriptor.samplerDescriptor); - + _textureInfo._bytesPerRow = PixelFormatUtils::computeRowPitch(descriptor.textureFormat, descriptor.width); - _bytesPerImage = _textureInfo._bytesPerRow * descriptor.width; - _region = MTLRegionMake2D(0, 0, descriptor.width, descriptor.height); + _bytesPerImage = _textureInfo._bytesPerRow * descriptor.width; + _region = MTLRegionMake2D(0, 0, descriptor.width, descriptor.height); } -void TextureCubeMTL::updateSamplerDescriptor(const SamplerDescriptor& sampler) +void TextureCubeMTL::updateSamplerDescriptor(const SamplerDescriptor &sampler) { _textureInfo.recreateSampler(sampler); } -void TextureCubeMTL::updateFaceData(TextureCubeFace side, void* data, int index) +void TextureCubeMTL::updateFaceData(TextureCubeFace side, void *data, int index) { NSUInteger slice = static_cast(side); - auto mtlTexture = _textureInfo.ensure(index, MTL_TEXTURE_CUBE); - if (!mtlTexture) - return; + auto mtlTexture = _textureInfo.ensure(index, MTL_TEXTURE_CUBE); + if(!mtlTexture) return; [mtlTexture replaceRegion:_region - mipmapLevel:0 - slice:slice - withBytes:data - bytesPerRow:_textureInfo._bytesPerRow - bytesPerImage:_bytesPerImage]; + mipmapLevel:0 + slice:slice + withBytes:data + bytesPerRow:_textureInfo._bytesPerRow + bytesPerImage:_bytesPerImage]; } void TextureCubeMTL::generateMipmaps() { if (TextureUsage::RENDER_TARGET == _textureUsage || isColorRenderable(_textureFormat) == false) return; - - if (!_hasMipmaps) + + if(!_hasMipmaps) { _hasMipmaps = true; UtilsMTL::generateMipmaps(reinterpret_cast>(this->getHandler())); diff --git a/cocos/renderer/backend/metal/UtilsMTL.mm b/cocos/renderer/backend/metal/UtilsMTL.mm index 7b5ac87a26..f37389d967 100644 --- a/cocos/renderer/backend/metal/UtilsMTL.mm +++ b/cocos/renderer/backend/metal/UtilsMTL.mm @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "UtilsMTL.h" #include "DeviceMTL.h" #include "DeviceInfoMTL.h" @@ -32,21 +32,20 @@ CC_BACKEND_BEGIN -id UtilsMTL::_defaultColorAttachmentTexture = nil; +id UtilsMTL::_defaultColorAttachmentTexture = nil; id UtilsMTL::_defaultDepthStencilAttachmentTexture = nil; -namespace -{ -MTLPixelFormat getSupportedDepthStencilFormat() -{ - MTLPixelFormat pixelFormat = MTLPixelFormatDepth32Float_Stencil8; +namespace { + MTLPixelFormat getSupportedDepthStencilFormat() + { + MTLPixelFormat pixelFormat = MTLPixelFormatDepth32Float_Stencil8; #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) - bool isDepth24Stencil8PixelFormatSupported = DeviceInfoMTL::supportD24S8(); - if (isDepth24Stencil8PixelFormatSupported) - pixelFormat = MTLPixelFormatDepth24Unorm_Stencil8; + bool isDepth24Stencil8PixelFormatSupported = DeviceInfoMTL::supportD24S8(); + if(isDepth24Stencil8PixelFormatSupported) + pixelFormat = MTLPixelFormatDepth24Unorm_Stencil8; #endif - return pixelFormat; -} + return pixelFormat; + } } struct GPUTextureFormatInfo @@ -55,77 +54,76 @@ struct GPUTextureFormatInfo MTLPixelFormat fmtSrgb; }; -static GPUTextureFormatInfo s_textureFormats[] = { +static GPUTextureFormatInfo s_textureFormats[] = +{ /* pvrtc v1 */ - {MTLPixelFormat(162 /*PVRTC_RGB_4BPP*/), MTLPixelFormat(163 /*PVRTC_RGB_4BPP_sRGB*/)}, // PTC14 - {MTLPixelFormat(166 /*PVRTC_RGBA_4BPP*/), MTLPixelFormat(167 /*PVRTC_RGBA_4BPP_sRGB*/)}, // PTC14A - {MTLPixelFormat(160 /*PVRTC_RGB_2BPP*/), MTLPixelFormat(161 /*PVRTC_RGB_2BPP_sRGB*/)}, // PTC12 - {MTLPixelFormat(164 /*PVRTC_RGBA_2BPP*/), MTLPixelFormat(165 /*PVRTC_RGBA_2BPP_sRGB*/)}, // PTC12A - + { MTLPixelFormat(162/*PVRTC_RGB_4BPP*/), MTLPixelFormat(163/*PVRTC_RGB_4BPP_sRGB*/) }, // PTC14 + { MTLPixelFormat(166/*PVRTC_RGBA_4BPP*/), MTLPixelFormat(167/*PVRTC_RGBA_4BPP_sRGB*/) }, // PTC14A + { MTLPixelFormat(160/*PVRTC_RGB_2BPP*/), MTLPixelFormat(161/*PVRTC_RGB_2BPP_sRGB*/) }, // PTC12 + { MTLPixelFormat(164/*PVRTC_RGBA_2BPP*/), MTLPixelFormat(165/*PVRTC_RGBA_2BPP_sRGB*/) }, // PTC12A + /* etc */ - {MTLPixelFormat(180 /*ETC2_RGB8*/), MTLPixelFormat(181 /*ETC2_RGB8_sRGB*/)}, // ETC1 - {MTLPixelFormat(180 /*ETC2_RGB8*/), MTLPixelFormat(181 /*ETC2_RGB8_sRGB*/)}, // ETC2 - {MTLPixelFormat(178 /*EAC_RGBA8*/), MTLPixelFormat(179 /*EAC_RGBA8_sRGB*/)}, // ETC2A - + { MTLPixelFormat(180/*ETC2_RGB8*/), MTLPixelFormat(181/*ETC2_RGB8_sRGB*/) }, // ETC1 + { MTLPixelFormat(180/*ETC2_RGB8*/), MTLPixelFormat(181/*ETC2_RGB8_sRGB*/) }, // ETC2 + { MTLPixelFormat(178/*EAC_RGBA8*/), MTLPixelFormat(179/*EAC_RGBA8_sRGB*/) }, // ETC2A + /* s3tc */ - {MTLPixelFormat(130 /*BC1_RGBA*/), MTLPixelFormat(131 /*BC1_RGBA_sRGB*/)}, // S3TC_DXT1/BC1 - {MTLPixelFormat(132 /*BC2_RGBA*/), MTLPixelFormat(133 /*BC2_RGBA_sRGB*/)}, // S3TC_DXT3/BC2 - {MTLPixelFormat(134 /*BC3_RGBA*/), MTLPixelFormat(135 /*BC3_RGBA_sRGB*/)}, // S3TC_DXT5/BC3 - + { MTLPixelFormat(130/*BC1_RGBA*/), MTLPixelFormat(131/*BC1_RGBA_sRGB*/) }, // S3TC_DXT1/BC1 + { MTLPixelFormat(132/*BC2_RGBA*/), MTLPixelFormat(133/*BC2_RGBA_sRGB*/) }, // S3TC_DXT3/BC2 + { MTLPixelFormat(134/*BC3_RGBA*/), MTLPixelFormat(135/*BC3_RGBA_sRGB*/) }, // S3TC_DXT5/BC3 + /* atc */ - {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ATC_RGB - {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ATC_EXPLICIT_ALPHA - {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ATC_INTERPOLATED_ALPHA - -/* astc */ + { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ATC_RGB + { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ATC_EXPLICIT_ALPHA + { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ATC_INTERPOLATED_ALPHA + + /* astc */ #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) - {MTLPixelFormatASTC_4x4_LDR, MTLPixelFormatASTC_4x4_sRGB}, // ASTC4x4 - {MTLPixelFormatASTC_5x5_LDR, MTLPixelFormatASTC_5x5_sRGB}, // ASTC5x5 - {MTLPixelFormatASTC_6x6_LDR, MTLPixelFormatASTC_6x6_sRGB}, // ASTC6x6 - {MTLPixelFormatASTC_8x5_LDR, MTLPixelFormatASTC_8x5_sRGB}, // ASTC8x5 - {MTLPixelFormatASTC_8x6_LDR, MTLPixelFormatASTC_8x6_sRGB}, // ASTC8x6 - {MTLPixelFormatASTC_8x8_LDR, MTLPixelFormatASTC_8x8_sRGB}, // ASTC8x8 - {MTLPixelFormatASTC_10x5_LDR, MTLPixelFormatASTC_10x5_sRGB}, // ASTC10x5 + { MTLPixelFormatASTC_4x4_LDR, MTLPixelFormatASTC_4x4_sRGB }, // ASTC4x4 + { MTLPixelFormatASTC_5x5_LDR, MTLPixelFormatASTC_5x5_sRGB }, // ASTC5x5 + { MTLPixelFormatASTC_6x6_LDR, MTLPixelFormatASTC_6x6_sRGB }, // ASTC6x6 + { MTLPixelFormatASTC_8x5_LDR, MTLPixelFormatASTC_8x5_sRGB }, // ASTC8x5 + { MTLPixelFormatASTC_8x6_LDR, MTLPixelFormatASTC_8x6_sRGB }, // ASTC8x6 + { MTLPixelFormatASTC_8x8_LDR, MTLPixelFormatASTC_8x8_sRGB }, // ASTC8x8 + { MTLPixelFormatASTC_10x5_LDR, MTLPixelFormatASTC_10x5_sRGB }, // ASTC10x5 #else - {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ASTC4x4 - {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ASTC5x5 - {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ASTC6x6 - {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ASTC8x5 - {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ASTC8x6 - {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ASTC8x8 - {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ASTC10x5 + { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC4x4 + { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC5x5 + { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC6x6 + { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC8x5 + { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC8x6 + { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC8x8 + { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC10x5 #endif - + /* normal */ - {MTLPixelFormatRGBA8Unorm, MTLPixelFormatRGBA8Unorm_sRGB}, // RGBA8 - {MTLPixelFormatBGRA8Unorm, MTLPixelFormatBGRA8Unorm_sRGB}, // BGRA8 - {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // RGB8 - {MTLPixelFormat(40 /*B5G6R5Unorm*/), MTLPixelFormatInvalid}, // R5G6B5 - {MTLPixelFormat(42 /*ABGR4Unorm*/), MTLPixelFormatInvalid}, // RGBA4 - {MTLPixelFormat(41 /*A1BGR5Unorm*/), MTLPixelFormatInvalid}, // RGB5A1 - {MTLPixelFormatA8Unorm, MTLPixelFormatInvalid}, // A8 - {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // L8 - {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // LA8 - + { MTLPixelFormatRGBA8Unorm, MTLPixelFormatRGBA8Unorm_sRGB }, // RGBA8 + { MTLPixelFormatBGRA8Unorm, MTLPixelFormatBGRA8Unorm_sRGB }, // BGRA8 + { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // RGB8 + { MTLPixelFormat(40/*B5G6R5Unorm*/), MTLPixelFormatInvalid }, // R5G6B5 + { MTLPixelFormat(42/*ABGR4Unorm*/), MTLPixelFormatInvalid }, // RGBA4 + { MTLPixelFormat(41/*A1BGR5Unorm*/), MTLPixelFormatInvalid }, // RGB5A1 + { MTLPixelFormatA8Unorm, MTLPixelFormatInvalid }, // A8 + { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // L8 + { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // LA8 + /* depth stencil */ - {MTLPixelFormat(255 /*Depth24Unorm_Stencil8*/), MTLPixelFormatInvalid}, // D24S8 + { MTLPixelFormat(255/*Depth24Unorm_Stencil8*/), MTLPixelFormatInvalid }, // D24S8 }; -static_assert(CC_ARRAYSIZE(s_textureFormats) == (int)PixelFormat::COUNT, - "The OpenGL GPU texture format info table incomplete!"); +static_assert(CC_ARRAYSIZE(s_textureFormats) == (int)PixelFormat::COUNT, "The OpenGL GPU texture format info table incomplete!"); void UtilsMTL::initGPUTextureFormats() { - // on mac, D24S8 means MTLPixelFormatDepth24Unorm_Stencil8, while on ios it means - // MTLPixelFormatDepth32Float_Stencil8 + //on mac, D24S8 means MTLPixelFormatDepth24Unorm_Stencil8, while on ios it means MTLPixelFormatDepth32Float_Stencil8 auto& info = s_textureFormats[(int)PixelFormat::D24S8]; - info.fmt = getSupportedDepthStencilFormat(); + info.fmt = getSupportedDepthStencilFormat(); } id UtilsMTL::getDefaultDepthStencilTexture() { - if (!_defaultDepthStencilAttachmentTexture) + if (! _defaultDepthStencilAttachmentTexture) _defaultDepthStencilAttachmentTexture = UtilsMTL::createDepthStencilAttachmentTexture(); - + return _defaultDepthStencilAttachmentTexture; } @@ -136,8 +134,7 @@ void UtilsMTL::updateDefaultColorAttachmentTexture(id texture) MTLPixelFormat UtilsMTL::toMTLPixelFormat(PixelFormat textureFormat) { - if (UTILS_LIKELY(textureFormat < PixelFormat::COUNT)) - { + if (UTILS_LIKELY(textureFormat < PixelFormat::COUNT)) { return s_textureFormats[(int)textureFormat].fmt; } return MTLPixelFormatInvalid; @@ -152,49 +149,48 @@ void UtilsMTL::resizeDefaultAttachmentTexture(std::size_t width, std::size_t hei id UtilsMTL::createDepthStencilAttachmentTexture() { - auto CAMetalLayer = DeviceMTL::getCAMetalLayer(); + auto CAMetalLayer = DeviceMTL::getCAMetalLayer(); MTLTextureDescriptor* textureDescriptor = [[MTLTextureDescriptor alloc] init]; - textureDescriptor.width = CAMetalLayer.drawableSize.width; - textureDescriptor.height = CAMetalLayer.drawableSize.height; - textureDescriptor.pixelFormat = s_textureFormats[(int)PixelFormat::D24S8].fmt; - textureDescriptor.resourceOptions = MTLResourceStorageModePrivate; - textureDescriptor.usage = MTLTextureUsageRenderTarget; - auto ret = [CAMetalLayer.device newTextureWithDescriptor:textureDescriptor]; + textureDescriptor.width = CAMetalLayer.drawableSize.width; + textureDescriptor.height = CAMetalLayer.drawableSize.height; + textureDescriptor.pixelFormat = s_textureFormats[(int)PixelFormat::D24S8].fmt; + textureDescriptor.resourceOptions = MTLResourceStorageModePrivate; + textureDescriptor.usage = MTLTextureUsageRenderTarget; + auto ret = [CAMetalLayer.device newTextureWithDescriptor:textureDescriptor]; [textureDescriptor release]; - + return ret; } void UtilsMTL::generateMipmaps(id texture) { - auto commandQueue = static_cast(DeviceMTL::getInstance())->getMTLCommandQueue(); - auto commandBuffer = [commandQueue commandBuffer]; + auto commandQueue = static_cast(DeviceMTL::getInstance())->getMTLCommandQueue(); + auto commandBuffer = [commandQueue commandBuffer]; id commandEncoder = [commandBuffer blitCommandEncoder]; [commandEncoder generateMipmapsForTexture:texture]; [commandEncoder endEncoding]; [commandBuffer commit]; } -void UtilsMTL::swizzleImage(unsigned char* image, std::size_t width, std::size_t height, MTLPixelFormat format) +void UtilsMTL::swizzleImage(unsigned char *image, std::size_t width, std::size_t height, MTLPixelFormat format) { - if (!image) + if(!image) return; - + auto len = width * height; - switch (format) - { - // convert to RGBA - case MTLPixelFormatBGRA8Unorm: - for (int i = 0; i < len; i++) - { - unsigned char temp = image[i * 4]; - image[i * 4] = image[i * 4 + 2]; - image[i * 4 + 2] = temp; - } - break; - - default: - break; + switch (format) { + //convert to RGBA + case MTLPixelFormatBGRA8Unorm: + for(int i=0; i ProgramGL::getActiveAttributes() const +const std::unordered_map ProgramGL::getActiveAttributes() const { - hlookup::string_map attributes; + std::unordered_map attributes; if (!_program) return attributes; @@ -293,9 +293,9 @@ int ProgramGL::getAttributeLocation(Attribute name) const return _builtinAttributeLocation[name]; } -int ProgramGL::getAttributeLocation(std::string_view name) const +int ProgramGL::getAttributeLocation(const std::string& name) const { - return glGetAttribLocation(_program, name.data()); + return glGetAttribLocation(_program, name.c_str()); } UniformLocation ProgramGL::getUniformLocation(backend::Uniform name) const @@ -303,7 +303,7 @@ UniformLocation ProgramGL::getUniformLocation(backend::Uniform name) const return _builtinUniformLocation[name]; } -UniformLocation ProgramGL::getUniformLocation(std::string_view uniform) const +UniformLocation ProgramGL::getUniformLocation(const std::string& uniform) const { UniformLocation uniformLocation; if (_activeUniformInfos.find(uniform) != _activeUniformInfos.end()) @@ -352,7 +352,7 @@ const UniformInfo& ProgramGL::getActiveUniformInfo(ShaderStage stage, int locati return s_emptyInfo; } -const hlookup::string_map& ProgramGL::getAllActiveUniformInfo(ShaderStage stage) const +const std::unordered_map& ProgramGL::getAllActiveUniformInfo(ShaderStage stage) const { return _activeUniformInfos; } diff --git a/cocos/renderer/backend/opengl/ProgramGL.h b/cocos/renderer/backend/opengl/ProgramGL.h index d433e94c7d..25be64d6f5 100644 --- a/cocos/renderer/backend/opengl/ProgramGL.h +++ b/cocos/renderer/backend/opengl/ProgramGL.h @@ -68,7 +68,7 @@ public: * @param vertexShader Specifes the vertex shader source. * @param fragmentShader Specifes the fragment shader source. */ - ProgramGL(std::string_view vertexShader, std::string_view fragmentShader); + ProgramGL(const std::string& vertexShader, const std::string& fragmentShader); ~ProgramGL(); @@ -89,7 +89,7 @@ public: * @param uniform Specifies the uniform name. * @return The uniform location. */ - virtual UniformLocation getUniformLocation(std::string_view uniform) const override; + virtual UniformLocation getUniformLocation(const std::string& uniform) const override; /** * Get uniform location by engine built-in uniform enum name. @@ -103,7 +103,7 @@ public: * @param name Specifies the attribute name. * @return The attribute location. */ - virtual int getAttributeLocation(std::string_view name) const override; + virtual int getAttributeLocation(const std::string& name) const override; /** * Get attribute location by engine built-in attribute enum name. @@ -128,7 +128,7 @@ public: * Get active vertex attributes. * @return Active vertex attributes. key is active attribute name, Value is corresponding attribute info. */ - virtual const hlookup::string_map getActiveAttributes() const override; + virtual const std::unordered_map getActiveAttributes() const override; /** * Get uniform buffer size in bytes that can hold all the uniforms. @@ -149,11 +149,12 @@ public: * Get all uniformInfos. * @return The uniformInfos. */ - virtual const hlookup::string_map& getAllActiveUniformInfo(ShaderStage stage) const override; + virtual const std::unordered_map& getAllActiveUniformInfo( + ShaderStage stage) const override; private: void compileProgram(); - bool getAttributeLocation(std::string_view attributeName, unsigned int& location) const; + bool getAttributeLocation(const std::string& attributeName, unsigned int& location) const; void computeUniformInfos(); void computeLocations(); #if CC_ENABLE_CACHE_TEXTURE_DATA @@ -171,7 +172,7 @@ private: ShaderModuleGL* _fragmentShaderModule = nullptr; std::vector _attributeInfos; - hlookup::string_map _activeUniformInfos; + std::unordered_map _activeUniformInfos; #if CC_ENABLE_CACHE_TEXTURE_DATA std::unordered_map _originalUniformLocations; ///< record the uniform location when shader was first created. diff --git a/cocos/renderer/backend/opengl/ShaderModuleGL.cpp b/cocos/renderer/backend/opengl/ShaderModuleGL.cpp index 3b6f49e6dd..23c1a1629b 100644 --- a/cocos/renderer/backend/opengl/ShaderModuleGL.cpp +++ b/cocos/renderer/backend/opengl/ShaderModuleGL.cpp @@ -31,7 +31,7 @@ CC_BACKEND_BEGIN -ShaderModuleGL::ShaderModuleGL(ShaderStage stage, std::string_view source) : ShaderModule(stage) +ShaderModuleGL::ShaderModuleGL(ShaderStage stage, const std::string& source) : ShaderModule(stage) { compileShader(stage, source); } @@ -41,10 +41,10 @@ ShaderModuleGL::~ShaderModuleGL() deleteShader(); } -void ShaderModuleGL::compileShader(ShaderStage stage, std::string_view source) +void ShaderModuleGL::compileShader(ShaderStage stage, const std::string& source) { GLenum shaderType = stage == ShaderStage::VERTEX ? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER; - const GLchar* sourcePtr = reinterpret_cast(source.data()); + const GLchar* sourcePtr = reinterpret_cast(source.c_str()); _shader = glCreateShader(shaderType); if (!_shader) return; @@ -64,7 +64,7 @@ void ShaderModuleGL::compileShader(ShaderStage stage, std::string_view source) cocos2d::Data errorLog{}; glGetShaderInfoLog(_shader, logLength, nullptr, (GLchar*)errorLog.resize(logLength)); cocos2d::log("cocos2d: ERROR: Failed to compile shader, detail: %s\n%s", errorLog.getBytes(), - source.data()); + source.c_str()); } else { diff --git a/cocos/renderer/backend/opengl/ShaderModuleGL.h b/cocos/renderer/backend/opengl/ShaderModuleGL.h index 81ea52691a..5bae6962bb 100644 --- a/cocos/renderer/backend/opengl/ShaderModuleGL.h +++ b/cocos/renderer/backend/opengl/ShaderModuleGL.h @@ -44,7 +44,7 @@ public: * @param stage Specifies whether is vertex shader or fragment shader. * @param source Specifies shader source. */ - ShaderModuleGL(ShaderStage stage, std::string_view source); + ShaderModuleGL(ShaderStage stage, const std::string& source); ~ShaderModuleGL(); /** @@ -54,7 +54,7 @@ public: inline GLuint getShader() const { return _shader; } private: - void compileShader(ShaderStage stage, std::string_view source); + void compileShader(ShaderStage stage, const std::string& source); void deleteShader(); GLuint _shader = 0; diff --git a/cocos/renderer/shaders/label_sdf.frag b/cocos/renderer/shaders/label_sdf.frag deleted file mode 100644 index 00d9133694..0000000000 --- a/cocos/renderer/shaders/label_sdf.frag +++ /dev/null @@ -1,52 +0,0 @@ -/**************************************************************************** - Copyright (c) 2018-2019 Xiamen Yaji Software Co., Ltd. - - 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. - ****************************************************************************/ - -const char* label_distanceNormal_frag = R"( - -#ifdef GL_ES -precision lowp float; -#endif - -varying vec4 v_fragmentColor; -varying vec2 v_texCoord; - -uniform vec4 u_textColor; -uniform sampler2D u_texture; - -void main() -{ - vec4 color = texture2D(u_texture, v_texCoord); - //the texture use dual channel 16-bit output for distance_map - //float dist = color.b+color.g/256.0; - // the texture use single channel 8-bit output for distance_map - float dist = color.a; - //TODO: Implementation 'fwidth' for glsl 1.0 - float width = fwidth(dist); - //assign width for constant will lead to a little bit fuzzy,it's temporary measure. - //float width = 0.04; - //float width = 1.0/16.0; - float alpha = smoothstep(0.5-width, 0.5+width, dist) * u_textColor.a; - gl_FragColor = v_fragmentColor * vec4(u_textColor.rgb,alpha); -} -)"; diff --git a/cocos/ui/CMakeLists.txt b/cocos/ui/CMakeLists.txt index af648011fe..607206af86 100644 --- a/cocos/ui/CMakeLists.txt +++ b/cocos/ui/CMakeLists.txt @@ -1,23 +1,14 @@ if(WINDOWS) - if(ADXE_ENABLE_WEBVIEW2) - set(COCOS_UI_SPECIFIC_HEADER - ui/UIEditBox/UIEditBoxImpl-win32.h - ui/UIWebView/UIWebViewImpl-win32.h - ui/UIWebView/UIWebView.h - ) - set(COCOS_UI_SPECIFIC_SRC - ui/UIEditBox/UIEditBoxImpl-win32.cpp - ui/UIWebView/UIWebViewImpl-win32.cpp - ui/UIWebView/UIWebView.cpp - ) - else() - set(COCOS_UI_SPECIFIC_HEADER - ui/UIEditBox/UIEditBoxImpl-win32.h - ) - set(COCOS_UI_SPECIFIC_SRC - ui/UIEditBox/UIEditBoxImpl-win32.cpp - ) - endif() + set(COCOS_UI_SPECIFIC_HEADER + ui/UIEditBox/UIEditBoxImpl-win32.h + ui/UIWebView/UIWebViewImpl-win32.h + ui/UIWebView/UIWebView.h + ) + set(COCOS_UI_SPECIFIC_SRC + ui/UIEditBox/UIEditBoxImpl-win32.cpp + ui/UIWebView/UIWebViewImpl-win32.cpp + ui/UIWebView/UIWebView.cpp + ) elseif(APPLE) if(MACOSX) set(COCOS_UI_SPECIFIC_HEADER diff --git a/cocos/ui/UIAbstractCheckButton.cpp b/cocos/ui/UIAbstractCheckButton.cpp index 412a33b46b..aec8a369de 100644 --- a/cocos/ui/UIAbstractCheckButton.cpp +++ b/cocos/ui/UIAbstractCheckButton.cpp @@ -73,11 +73,11 @@ AbstractCheckButton::AbstractCheckButton() AbstractCheckButton::~AbstractCheckButton() {} -bool AbstractCheckButton::init(std::string_view backGround, - std::string_view backGroundSelected, - std::string_view cross, - std::string_view backGroundDisabled, - std::string_view frontCrossDisabled, +bool AbstractCheckButton::init(const std::string& backGround, + const std::string& backGroundSelected, + const std::string& cross, + const std::string& backGroundDisabled, + const std::string& frontCrossDisabled, TextureResType texType) { bool ret = true; @@ -120,11 +120,11 @@ void AbstractCheckButton::initRenderer() addProtectedChild(_frontCrossDisabledRenderer, FRONTCROSSDISABLED_RENDERER_Z, -1); } -void AbstractCheckButton::loadTextures(std::string_view backGround, - std::string_view backGroundSelected, - std::string_view cross, - std::string_view backGroundDisabled, - std::string_view frontCrossDisabled, +void AbstractCheckButton::loadTextures(const std::string& backGround, + const std::string& backGroundSelected, + const std::string& cross, + const std::string& backGroundDisabled, + const std::string& frontCrossDisabled, TextureResType texType) { loadTextureBackGround(backGround, texType); @@ -134,7 +134,7 @@ void AbstractCheckButton::loadTextures(std::string_view backGround, loadTextureFrontCrossDisabled(frontCrossDisabled, texType); } -void AbstractCheckButton::loadTextureBackGround(std::string_view backGround, TextureResType texType) +void AbstractCheckButton::loadTextureBackGround(const std::string& backGround, TextureResType texType) { _backGroundFileName = backGround; @@ -169,7 +169,7 @@ void AbstractCheckButton::loadTextureBackGround(SpriteFrame* spriteFrame) this->setupBackgroundTexture(); } -void AbstractCheckButton::loadTextureBackGroundSelected(std::string_view backGroundSelected, TextureResType texType) +void AbstractCheckButton::loadTextureBackGroundSelected(const std::string& backGroundSelected, TextureResType texType) { _backGroundSelectedFileName = backGroundSelected; _isBackgroundSelectedTextureLoaded = !backGroundSelected.empty(); @@ -203,7 +203,7 @@ void AbstractCheckButton::setupBackgroundSelectedTexture() _backGroundSelectedBoxRendererAdaptDirty = true; } -void AbstractCheckButton::loadTextureFrontCross(std::string_view cross, TextureResType texType) +void AbstractCheckButton::loadTextureFrontCross(const std::string& cross, TextureResType texType) { _frontCrossFileName = cross; @@ -234,7 +234,7 @@ void AbstractCheckButton::setupFrontCrossTexture() _frontCrossRendererAdaptDirty = true; } -void AbstractCheckButton::loadTextureBackGroundDisabled(std::string_view backGroundDisabled, TextureResType texType) +void AbstractCheckButton::loadTextureBackGroundDisabled(const std::string& backGroundDisabled, TextureResType texType) { _backGroundDisabledFileName = backGroundDisabled; _isBackgroundDisabledTextureLoaded = !backGroundDisabled.empty(); @@ -269,7 +269,7 @@ void AbstractCheckButton::setupBackgroundDisable() _backGroundBoxDisabledRendererAdaptDirty = true; } -void AbstractCheckButton::loadTextureFrontCrossDisabled(std::string_view frontCrossDisabled, TextureResType texType) +void AbstractCheckButton::loadTextureFrontCrossDisabled(const std::string& frontCrossDisabled, TextureResType texType) { _frontCrossDisabledFileName = frontCrossDisabled; _isFrontCrossDisabledTextureLoaded = !frontCrossDisabled.empty(); diff --git a/cocos/ui/UIAbstractCheckButton.h b/cocos/ui/UIAbstractCheckButton.h index 7d801dba76..38f97b046a 100644 --- a/cocos/ui/UIAbstractCheckButton.h +++ b/cocos/ui/UIAbstractCheckButton.h @@ -57,11 +57,11 @@ public: * @param frontCrossDisabled The front cross disabled state image name. * @param texType @see `Widget::TextureResType` */ - void loadTextures(std::string_view background, - std::string_view backgroundSelected, - std::string_view cross, - std::string_view backgroundDisabled, - std::string_view frontCrossDisabled, + void loadTextures(const std::string& background, + const std::string& backgroundSelected, + const std::string& cross, + const std::string& backgroundDisabled, + const std::string& frontCrossDisabled, TextureResType texType = TextureResType::LOCAL); /** @@ -70,7 +70,7 @@ public: * @param backGround The background image name. * @param type @see `Widget::TextureResType` */ - void loadTextureBackGround(std::string_view backGround, TextureResType type = TextureResType::LOCAL); + void loadTextureBackGround(const std::string& backGround, TextureResType type = TextureResType::LOCAL); /** * Load background selected state texture for check button. @@ -78,7 +78,7 @@ public: * @param backGroundSelected The background selected state image name. * @param texType @see `Widget::TextureResType` */ - void loadTextureBackGroundSelected(std::string_view backGroundSelected, + void loadTextureBackGroundSelected(const std::string& backGroundSelected, TextureResType texType = TextureResType::LOCAL); /** @@ -87,7 +87,7 @@ public: * @param crossTextureName The cross texture name. * @param texType @see `Widget::TextureResType` */ - void loadTextureFrontCross(std::string_view crossTextureName, TextureResType texType = TextureResType::LOCAL); + void loadTextureFrontCross(const std::string& crossTextureName, TextureResType texType = TextureResType::LOCAL); /** * Load background disabled state texture for checkbox. @@ -96,7 +96,7 @@ public: * * @param texType @see `Widget::TextureResType` */ - void loadTextureBackGroundDisabled(std::string_view backGroundDisabled, + void loadTextureBackGroundDisabled(const std::string& backGroundDisabled, TextureResType texType = TextureResType::LOCAL); /** @@ -105,7 +105,7 @@ public: * @param frontCrossDisabled The front cross disabled state texture name. * @param texType @see `Widget::TextureResType` */ - void loadTextureFrontCrossDisabled(std::string_view frontCrossDisabled, + void loadTextureFrontCrossDisabled(const std::string& frontCrossDisabled, TextureResType texType = TextureResType::LOCAL); /** @@ -174,11 +174,11 @@ public: ResourceData getCrossDisabledFile(); CC_CONSTRUCTOR_ACCESS : virtual bool init() override; - virtual bool init(std::string_view backGround, - std::string_view backGroundSelected, - std::string_view cross, - std::string_view backGroundDisabled, - std::string_view frontCrossDisabled, + virtual bool init(const std::string& backGround, + const std::string& backGroundSelected, + const std::string& cross, + const std::string& backGroundDisabled, + const std::string& frontCrossDisabled, TextureResType texType = TextureResType::LOCAL); protected: diff --git a/cocos/ui/UIButton.cpp b/cocos/ui/UIButton.cpp index 195bdde8eb..8b2025a1a7 100644 --- a/cocos/ui/UIButton.cpp +++ b/cocos/ui/UIButton.cpp @@ -92,9 +92,9 @@ Button* Button::create() return nullptr; } -Button* Button::create(std::string_view normalImage, - std::string_view selectedImage, - std::string_view disableImage, +Button* Button::create(const std::string& normalImage, + const std::string& selectedImage, + const std::string& disableImage, TextureResType texType) { Button* btn = new Button; @@ -107,9 +107,9 @@ Button* Button::create(std::string_view normalImage, return nullptr; } -bool Button::init(std::string_view normalImage, - std::string_view selectedImage, - std::string_view disableImage, +bool Button::init(const std::string& normalImage, + const std::string& selectedImage, + const std::string& disableImage, TextureResType texType) { @@ -250,9 +250,9 @@ void Button::ignoreContentAdaptWithSize(bool ignore) } } -void Button::loadTextures(std::string_view normal, - std::string_view selected, - std::string_view disabled, +void Button::loadTextures(const std::string& normal, + const std::string& selected, + const std::string& disabled, TextureResType texType) { loadTextureNormal(normal, texType); @@ -260,7 +260,7 @@ void Button::loadTextures(std::string_view normal, loadTextureDisabled(disabled, texType); } -void Button::loadTextureNormal(std::string_view normal, TextureResType texType) +void Button::loadTextureNormal(const std::string& normal, TextureResType texType) { _normalFileName = normal; _normalTexType = texType; @@ -319,7 +319,7 @@ void Button::loadTextureNormal(SpriteFrame* normalSpriteFrame) this->setupNormalTexture(nullptr != normalSpriteFrame); } -void Button::loadTexturePressed(std::string_view selected, TextureResType texType) +void Button::loadTexturePressed(const std::string& selected, TextureResType texType) { _clickedFileName = selected; _pressedTexType = texType; @@ -362,7 +362,7 @@ void Button::loadTexturePressed(SpriteFrame* pressedSpriteFrame) this->setupPressedTexture(nullptr != pressedSpriteFrame); } -void Button::loadTextureDisabled(std::string_view disabled, TextureResType texType) +void Button::loadTextureDisabled(const std::string& disabled, TextureResType texType) { _disabledFileName = disabled; _disabledTexType = texType; @@ -718,7 +718,7 @@ void Button::setTitleAlignment(TextHAlignment hAlignment, TextVAlignment vAlignm _titleRenderer->setAlignment(hAlignment, vAlignment); } -void Button::setTitleText(std::string_view text) +void Button::setTitleText(const std::string& text) { if (text.compare(getTitleText()) == 0) { @@ -737,7 +737,7 @@ void Button::setTitleText(std::string_view text) updateTitleLocation(); } -std::string_view Button::getTitleText() const +std::string Button::getTitleText() const { if (!_titleRenderer) { @@ -806,13 +806,13 @@ float Button::getZoomScale() const return _zoomScale; } -void Button::setTitleFontName(std::string_view fontName) +void Button::setTitleFontName(const std::string& fontName) { createTitleRendererIfNull(); if (FileUtils::getInstance()->isFileExist(fontName)) { - std::string lowerCasedFontName{fontName}; + std::string lowerCasedFontName = fontName; std::transform(lowerCasedFontName.begin(), lowerCasedFontName.end(), lowerCasedFontName.begin(), ::tolower); if (lowerCasedFontName.find(".fnt") != std::string::npos) { @@ -838,7 +838,7 @@ Label* Button::getTitleRenderer() const return _titleRenderer; } -std::string_view Button::getTitleFontName() const +std::string Button::getTitleFontName() const { if (_titleRenderer) { @@ -857,7 +857,7 @@ std::string_view Button::getTitleFontName() const } } - return ""sv; + return ""; } std::string Button::getDescription() const diff --git a/cocos/ui/UIButton.h b/cocos/ui/UIButton.h index ad881f2d39..3db6e5c123 100644 --- a/cocos/ui/UIButton.h +++ b/cocos/ui/UIButton.h @@ -80,10 +80,10 @@ public: * @param texType @see `TextureResType` * @return a Button instance. */ - static Button* create(std::string_view normalImage, - std::string_view selectedImage = "", - std::string_view disableImage = "", - TextureResType texType = TextureResType::LOCAL); + static Button* create(const std::string& normalImage, + const std::string& selectedImage = "", + const std::string& disableImage = "", + TextureResType texType = TextureResType::LOCAL); /** * Load textures for button. @@ -93,10 +93,10 @@ public: * @param disabled disabled state texture name. * @param texType @see `TextureResType` */ - void loadTextures(std::string_view normal, - std::string_view selected, - std::string_view disabled = "", - TextureResType texType = TextureResType::LOCAL); + void loadTextures(const std::string& normal, + const std::string& selected, + const std::string& disabled = "", + TextureResType texType = TextureResType::LOCAL); /** * Load normal state texture for button. @@ -104,7 +104,7 @@ public: * @param normal normal state texture. * @param texType @see `TextureResType` */ - void loadTextureNormal(std::string_view normal, TextureResType texType = TextureResType::LOCAL); + void loadTextureNormal(const std::string& normal, TextureResType texType = TextureResType::LOCAL); /** * Load selected state texture for button. @@ -112,7 +112,7 @@ public: * @param selected selected state texture. * @param texType @see `TextureResType` */ - void loadTexturePressed(std::string_view selected, TextureResType texType = TextureResType::LOCAL); + void loadTexturePressed(const std::string& selected, TextureResType texType = TextureResType::LOCAL); /** * Load disabled state texture for button. @@ -120,7 +120,7 @@ public: * @param disabled dark state texture. * @param texType @see `TextureResType` */ - void loadTextureDisabled(std::string_view disabled, TextureResType texType = TextureResType::LOCAL); + void loadTextureDisabled(const std::string& disabled, TextureResType texType = TextureResType::LOCAL); /** * Sets capInsets for button. @@ -206,13 +206,13 @@ public: * Change the content of button's title. *@param text The title in std::string. */ - void setTitleText(std::string_view text); + void setTitleText(const std::string& text); /** * Query the button title content. *@return Get the button's title content. */ - std::string_view getTitleText() const; + std::string getTitleText() const; /** * Change the color of button's title. @@ -242,13 +242,13 @@ public: * Change the font name of button's title *@param fontName a font name string. */ - void setTitleFontName(std::string_view fontName); + void setTitleFontName(const std::string& fontName); /** * Query the font name of button's title *@return font name in std::string */ - std::string_view getTitleFontName() const; + std::string getTitleFontName() const; /** * Sets the title's text horizontal alignment. @@ -314,10 +314,10 @@ public: ResourceData getDisabledFile(); CC_CONSTRUCTOR_ACCESS : virtual bool init() override; - virtual bool init(std::string_view normalImage, - std::string_view selectedImage = "", - std::string_view disableImage = "", - TextureResType texType = TextureResType::LOCAL); + virtual bool init(const std::string& normalImage, + const std::string& selectedImage = "", + const std::string& disableImage = "", + TextureResType texType = TextureResType::LOCAL); virtual Vec2 getNormalTextureSize() const; diff --git a/cocos/ui/UICheckBox.cpp b/cocos/ui/UICheckBox.cpp index c98813b251..6cce622d6f 100644 --- a/cocos/ui/UICheckBox.cpp +++ b/cocos/ui/UICheckBox.cpp @@ -48,11 +48,11 @@ CheckBox* CheckBox::create() return nullptr; } -CheckBox* CheckBox::create(std::string_view backGround, - std::string_view backGroundSelected, - std::string_view cross, - std::string_view backGroundDisabled, - std::string_view frontCrossDisabled, +CheckBox* CheckBox::create(const std::string& backGround, + const std::string& backGroundSelected, + const std::string& cross, + const std::string& backGroundDisabled, + const std::string& frontCrossDisabled, TextureResType texType) { CheckBox* pWidget = new CheckBox; @@ -65,7 +65,7 @@ CheckBox* CheckBox::create(std::string_view backGround, return nullptr; } -CheckBox* CheckBox::create(std::string_view backGround, std::string_view cross, TextureResType texType) +CheckBox* CheckBox::create(const std::string& backGround, const std::string& cross, TextureResType texType) { CheckBox* pWidget = new CheckBox; if (pWidget->init(backGround, "", cross, "", "", texType)) diff --git a/cocos/ui/UICheckBox.h b/cocos/ui/UICheckBox.h index 5d3d43d02c..ec29f433b1 100644 --- a/cocos/ui/UICheckBox.h +++ b/cocos/ui/UICheckBox.h @@ -93,11 +93,11 @@ public: * * @return A CheckBox instance pointer. */ - static CheckBox* create(std::string_view backGround, - std::string_view backGroundSelected, - std::string_view cross, - std::string_view backGroundDisabled, - std::string_view frontCrossDisabled, + static CheckBox* create(const std::string& backGround, + const std::string& backGroundSelected, + const std::string& cross, + const std::string& backGroundDisabled, + const std::string& frontCrossDisabled, TextureResType texType = TextureResType::LOCAL); /** @@ -108,8 +108,8 @@ public: * @param texType The texture's resource type in `Widget::TextureResType`. * @return A CheckBox instance pointer */ - static CheckBox* create(std::string_view backGround, - std::string_view cross, + static CheckBox* create(const std::string& backGround, + const std::string& cross, TextureResType texType = TextureResType::LOCAL); /** diff --git a/cocos/ui/UIEditBox/Mac/CCUIEditBoxMac.mm b/cocos/ui/UIEditBox/Mac/CCUIEditBoxMac.mm index 36411c3fd3..bd2cf3d9d2 100644 --- a/cocos/ui/UIEditBox/Mac/CCUIEditBoxMac.mm +++ b/cocos/ui/UIEditBox/Mac/CCUIEditBoxMac.mm @@ -2,19 +2,19 @@ Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2013-2016 zilongshanren Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -30,94 +30,92 @@ #include "ui/UIEditBox/Mac/CCUIPasswordTextField.h" #include "ui/UIEditBox/Mac/CCUIMultilineTextField.h" -#define getEditBoxImplMac() ((cocos2d::ui::EditBoxImplMac*)_editBox) +#define getEditBoxImplMac() ((cocos2d::ui::EditBoxImplMac *)_editBox) + @implementation UIEditBoxImplMac -- (instancetype)initWithFrame:(NSRect)frameRect editBox:(void*)editBox +- (instancetype)initWithFrame:(NSRect)frameRect editBox:(void *)editBox { self = [super init]; - - if (self) - { - - _editState = NO; + + if (self) { + + _editState = NO; self.frameRect = frameRect; - - self.editBox = editBox; - self.dataInputMode = cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS; + + self.editBox = editBox; + self.dataInputMode = cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS; self.keyboardReturnType = cocos2d::ui::EditBox::KeyboardReturnType::DEFAULT; - + [self createMultiLineTextField]; } - + return self; } - (void)createSingleLineTextField { - CCUISingleLineTextField* textField = [[[CCUISingleLineTextField alloc] initWithFrame:self.frameRect] autorelease]; - + CCUISingleLineTextField *textField = [[[CCUISingleLineTextField alloc] initWithFrame:self.frameRect] autorelease]; + self.textInput = textField; } - (void)createMultiLineTextField { - CCUIMultilineTextField* textView = [[[CCUIMultilineTextField alloc] initWithFrame:self.frameRect] autorelease]; + CCUIMultilineTextField *textView = [[[CCUIMultilineTextField alloc] initWithFrame:self.frameRect] autorelease]; [textView setVerticallyResizable:NO]; self.textInput = textView; } - (void)createPasswordTextField { - CCUIPasswordTextField* textField = [[[CCUIPasswordTextField alloc] initWithFrame:self.frameRect] autorelease]; - + CCUIPasswordTextField *textField = [[[CCUIPasswordTextField alloc] initWithFrame:self.frameRect] autorelease]; + self.textInput = textField; } -- (void)setTextInput:(NSView*)textInput +- (void)setTextInput:(NSView *)textInput { - if (_textInput == textInput) - { + if (_textInput == textInput) { return; } // Migrate properties - textInput.ccui_textColor = _textInput.ccui_textColor ?: [NSColor whiteColor]; - textInput.ccui_text = _textInput.ccui_text ?: @""; + textInput.ccui_textColor = _textInput.ccui_textColor ?: [NSColor whiteColor]; + textInput.ccui_text = _textInput.ccui_text ?: @""; textInput.ccui_placeholder = _textInput.ccui_placeholder ?: @""; - textInput.ccui_font = _textInput.ccui_font ?: [NSFont systemFontOfSize:self.frameRect.size.height * 3 / 2]; - textInput.ccui_maxLength = getEditBoxImplMac()->getMaxLength(); - textInput.ccui_alignment = _textInput.ccui_alignment; - + textInput.ccui_font = _textInput.ccui_font ?: [NSFont systemFontOfSize:self.frameRect.size.height*3/2]; + textInput.ccui_maxLength = getEditBoxImplMac()->getMaxLength(); + textInput.ccui_alignment = _textInput.ccui_alignment; + [_textInput removeFromSuperview]; [_textInput release]; - + _textInput = [textInput retain]; - + [_textInput performSelector:@selector(setTextColor:) withObject:_textInput.ccui_textColor]; [_textInput performSelector:@selector(setBackgroundColor:) withObject:[NSColor clearColor]]; - - if (![_textInput isKindOfClass:[NSTextView class]]) - { + + if (![_textInput isKindOfClass:[NSTextView class]]) { [_textInput performSelector:@selector(setBordered:) withObject:nil]; } - _textInput.hidden = NO; + _textInput.hidden = NO; _textInput.wantsLayer = YES; - + [_textInput ccui_setDelegate:self]; - + [self setInputFlag:self.dataInputMode]; [self setReturnType:self.keyboardReturnType]; } - (void)updateFrame:(CGRect)rect { - NSRect frame = self.textInput.frame; - frame.origin.x = rect.origin.x; - frame.origin.y = rect.origin.y; + NSRect frame = self.textInput.frame; + frame.origin.x = rect.origin.x; + frame.origin.y = rect.origin.y; frame.size.height = rect.size.height; - frame.size.width = rect.size.width; + frame.size.width = rect.size.width; self.textInput.frame = frame; } @@ -125,11 +123,11 @@ - (void)dealloc { self.textInput = nil; - + [super dealloc]; } -- (NSWindow*)window +- (NSWindow *)window { auto glview = cocos2d::Director::getInstance()->getOpenGLView(); return glview->getCocoaWindow(); @@ -139,44 +137,41 @@ { [self.window.contentView addSubview:self.textInput]; - if (![self.textInput isKindOfClass:[NSTextView class]]) - { + if (![self.textInput isKindOfClass:[NSTextView class]]) { [self.textInput becomeFirstResponder]; - } - else - { + }else { [self.window makeFirstResponder:self.textInput]; } - + auto editbox = getEditBoxImplMac()->getEditBox(); - auto oldPos = editbox->getPosition(); - editbox->setPosition(oldPos + cocos2d::Vec2(10, 20)); + auto oldPos = editbox->getPosition(); + editbox->setPosition(oldPos + cocos2d::Vec2(10,20)); editbox->setPosition(oldPos); } - (void)closeKeyboard { - if (![self.textInput isKindOfClass:[NSTextView class]]) - { + if (![self.textInput isKindOfClass:[NSTextView class]]) { [self.textInput resignFirstResponder]; } [self.textInput removeFromSuperview]; } -- (const char*)getText + +- (const char*) getText { return [self.textInput.ccui_text UTF8String]; } -- (void)controlTextDidBeginEditing:(NSNotification*)notification +- (void)controlTextDidBeginEditing:(NSNotification *)notification { _editState = YES; - + getEditBoxImplMac()->editBoxEditingDidBegin(); } -- (void)controlTextDidEndEditing:(NSNotification*)notification +- (void)controlTextDidEndEditing:(NSNotification *)notification { _editState = NO; @@ -191,32 +186,27 @@ /** * Called each time when the text field's text has changed. */ -- (void)controlTextDidChange:(NSNotification*)notification +- (void)controlTextDidChange:(NSNotification *)notification { getEditBoxImplMac()->editBoxEditingChanged([self getText]); } -- (NSString*)getDefaultFontName +- (NSString *)getDefaultFontName { return self.textInput.ccui_font.fontName ?: @""; } - (void)setInputMode:(cocos2d::ui::EditBox::InputMode)inputMode { - // multiline input - if (inputMode == cocos2d::ui::EditBox::InputMode::ANY) - { - if (![self.textInput isKindOfClass:[NSTextView class]]) - { + //multiline input + if (inputMode == cocos2d::ui::EditBox::InputMode::ANY) { + if (![self.textInput isKindOfClass:[NSTextView class]]) { [self createMultiLineTextField]; } } - else - { - if (self.dataInputMode != cocos2d::ui::EditBox::InputFlag::PASSWORD) - { - if (![self.textInput isKindOfClass:[NSTextField class]]) - { + else { + if (self.dataInputMode != cocos2d::ui::EditBox::InputFlag::PASSWORD) { + if (![self.textInput isKindOfClass:[NSTextField class]]) { [self createSingleLineTextField]; } } @@ -225,45 +215,42 @@ - (void)setInputFlag:(cocos2d::ui::EditBox::InputFlag)inputFlag { - if (self.dataInputMode == inputFlag) - { + if (self.dataInputMode == inputFlag) { return; } - - if (self.dataInputMode == cocos2d::ui::EditBox::InputFlag::PASSWORD && - inputFlag != cocos2d::ui::EditBox::InputFlag::PASSWORD) - { + + if (self.dataInputMode == cocos2d::ui::EditBox::InputFlag::PASSWORD + && inputFlag != cocos2d::ui::EditBox::InputFlag::PASSWORD) { [self createSingleLineTextField]; } - - if (self.dataInputMode != cocos2d::ui::EditBox::InputFlag::PASSWORD && - inputFlag == cocos2d::ui::EditBox::InputFlag::PASSWORD) - { + + if (self.dataInputMode != cocos2d::ui::EditBox::InputFlag::PASSWORD + && inputFlag == cocos2d::ui::EditBox::InputFlag::PASSWORD) { [self createPasswordTextField]; } switch (inputFlag) { - case cocos2d::ui::EditBox::InputFlag::PASSWORD: - self.dataInputMode = inputFlag; - break; - case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_WORD: - CCLOG("INITIAL_CAPS_WORD not implemented"); - break; - case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_SENTENCE: - CCLOG("INITIAL_CAPS_SENTENCE not implemented"); - break; - case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_ALL_CHARACTERS: - CCLOG("INITIAL_CAPS_ALL_CHARACTERS not implemented"); - break; - case cocos2d::ui::EditBox::InputFlag::SENSITIVE: - CCLOG("SENSITIVE not implemented"); - break; - case cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS: - CCLOG("LOWERCASE_ALL_CHARACTERS not implemented"); - break; - default: - break; + case cocos2d::ui::EditBox::InputFlag::PASSWORD: + self.dataInputMode = inputFlag; + break; + case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_WORD: + CCLOG("INITIAL_CAPS_WORD not implemented"); + break; + case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_SENTENCE: + CCLOG("INITIAL_CAPS_SENTENCE not implemented"); + break; + case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_ALL_CHARACTERS: + CCLOG("INITIAL_CAPS_ALL_CHARACTERS not implemented"); + break; + case cocos2d::ui::EditBox::InputFlag::SENSITIVE: + CCLOG("SENSITIVE not implemented"); + break; + case cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS: + CCLOG("LOWERCASE_ALL_CHARACTERS not implemented"); + break; + default: + break; } } @@ -275,14 +262,12 @@ - (void)setTextHorizontalAlignment:(cocos2d::TextHAlignment)alignment { // swizzle center & right, for some reason they're backwards on !TARGET_OS_IPHONE - if (alignment == cocos2d::TextHAlignment::CENTER) - alignment = cocos2d::TextHAlignment::RIGHT; - else if (alignment == cocos2d::TextHAlignment::RIGHT) - alignment = cocos2d::TextHAlignment::CENTER; + if (alignment == cocos2d::TextHAlignment::CENTER) alignment = cocos2d::TextHAlignment::RIGHT; + else if (alignment == cocos2d::TextHAlignment::RIGHT) alignment = cocos2d::TextHAlignment::CENTER; self.textInput.ccui_alignment = static_cast(alignment); } -- (void)setPlaceHolder:(const char*)text +- (void)setPlaceHolder:(const char *)text { self.textInput.ccui_placeholder = [NSString stringWithUTF8String:text]; } @@ -297,15 +282,14 @@ self.textInput.ccui_textColor = color; } -- (void)setFont:(NSFont*)font +- (void)setFont:(NSFont *)font { - if (font != nil) - { + if (font != nil) { self.textInput.ccui_font = font; } } -- (void)setPlaceholderFontColor:(NSColor*)color +- (void)setPlaceholderFontColor:(NSColor *)color { self.textInput.ccui_placeholderColor = color; } @@ -315,76 +299,70 @@ self.textInput.ccui_placeholderFont = font; } -- (void)setText:(NSString*)text +- (void)setText:(NSString *)text { self.textInput.ccui_text = text; } -- (BOOL)textShouldBeginEditing:(NSText*)textObject // YES means do it +- (BOOL)textShouldBeginEditing:(NSText *)textObject // YES means do it { _editState = YES; - + getEditBoxImplMac()->editBoxEditingDidBegin(); return YES; } -- (void)textDidEndEditing:(NSNotification*)notification +- (void)textDidEndEditing:(NSNotification *)notification { _editState = NO; getEditBoxImplMac()->editBoxEditingDidEnd([self getText], [self getEndAction:notification]); } -- (cocos2d::ui::EditBoxDelegate::EditBoxEndAction)getEndAction:(NSNotification*)notification +- (cocos2d::ui::EditBoxDelegate::EditBoxEndAction)getEndAction:(NSNotification *)notification { - auto type = cocos2d::ui::EditBoxDelegate::EditBoxEndAction::UNKNOWN; + auto type = cocos2d::ui::EditBoxDelegate::EditBoxEndAction::UNKNOWN; NSUInteger reasonForEnding = [[[notification userInfo] objectForKey:@"NSTextMovement"] unsignedIntValue]; - if (reasonForEnding == NSTabTextMovement) - { + if (reasonForEnding == NSTabTextMovement) { type = cocos2d::ui::EditBoxDelegate::EditBoxEndAction::TAB_TO_NEXT; - } - else if (reasonForEnding == NSBacktabTextMovement) - { + } else if (reasonForEnding == NSBacktabTextMovement) { type = cocos2d::ui::EditBoxDelegate::EditBoxEndAction::TAB_TO_PREVIOUS; - } - else if (reasonForEnding == NSReturnTextMovement) - { + } else if (reasonForEnding == NSReturnTextMovement) { type = cocos2d::ui::EditBoxDelegate::EditBoxEndAction::RETURN; } return type; } -- (void)textDidChange:(NSNotification*)notification +- (void)textDidChange:(NSNotification *)notification { NSTextView* textView = notification.object; - + const char* inputText = [textView.string UTF8String]; - + getEditBoxImplMac()->editBoxEditingChanged(inputText); } -- (BOOL)textView:(NSTextView*)textView - shouldChangeTextInRange:(NSRange)affectedCharRange - replacementString:(NSString*)replacementString +- (BOOL)textView:(NSTextView *)textView shouldChangeTextInRange:(NSRange)affectedCharRange replacementString:(NSString *)replacementString { int maxLength = getEditBoxImplMac()->getMaxLength(); if (maxLength < 0) { return YES; } - - if (affectedCharRange.length + affectedCharRange.location > textView.string.length) - { + + if (affectedCharRange.length + affectedCharRange.location > textView.string.length) { return NO; } - - NSUInteger oldLength = textView.string.length; + + NSUInteger oldLength = textView.string.length; NSUInteger replacementLength = replacementString.length; - NSUInteger rangeLength = affectedCharRange.length; - + NSUInteger rangeLength = affectedCharRange.length; + NSUInteger newLength = oldLength - rangeLength + replacementLength; - + return newLength <= maxLength; } + + @end diff --git a/cocos/ui/UIEditBox/UIEditBox.cpp b/cocos/ui/UIEditBox/UIEditBox.cpp index fefa1cdcb3..78c7eb1c04 100644 --- a/cocos/ui/UIEditBox/UIEditBox.cpp +++ b/cocos/ui/UIEditBox/UIEditBox.cpp @@ -56,15 +56,15 @@ void EditBox::openKeyboard() const _editBoxImpl->openKeyboard(); } -EditBox* EditBox::create(const Vec2& size, std::string_view normalImage, TextureResType texType) +EditBox* EditBox::create(const Vec2& size, const std::string& normalImage, TextureResType texType) { return EditBox::create(size, normalImage, "", "", texType); } EditBox* EditBox::create(const Vec2& size, - std::string_view normalImage, - std::string_view pressedImage /* = "" */, - std::string_view disabledImage /* = "" */, + const std::string& normalImage, + const std::string& pressedImage /* = "" */, + const std::string& disabledImage /* = "" */, TextureResType texType /* = TextureResType::LOCAL */) { EditBox* pRet = new EditBox(); @@ -136,16 +136,16 @@ bool EditBox::initWithSizeAndBackgroundSprite(const Vec2& size, } bool EditBox::initWithSizeAndBackgroundSprite(const Vec2& size, - std::string_view pNormal9SpriteBg, + const std::string& pNormal9SpriteBg, TextureResType texType) { return initWithSizeAndTexture(size, pNormal9SpriteBg, "", "", texType); } bool EditBox::initWithSizeAndTexture(const Vec2& size, - std::string_view normalImage, - std::string_view pressedImage /* = "" */, - std::string_view disabledImage /* = "" */, + const std::string& normalImage, + const std::string& pressedImage /* = "" */, + const std::string& disabledImage /* = "" */, TextureResType texType /* = TextureResType::LOCAL */) { if (Widget::init()) @@ -178,9 +178,9 @@ void EditBox::initRenderer() addProtectedChild(_disabledRenderer, DISABLED_RENDERER_Z, -1); } -void EditBox::loadTextures(std::string_view normal, - std::string_view pressed, - std::string_view disabled, +void EditBox::loadTextures(const std::string& normal, + const std::string& pressed, + const std::string& disabled, TextureResType texType) { loadTextureNormal(normal, texType); @@ -188,7 +188,7 @@ void EditBox::loadTextures(std::string_view normal, loadTextureDisabled(disabled, texType); } -void EditBox::loadTextureNormal(std::string_view normal, TextureResType texType) +void EditBox::loadTextureNormal(const std::string& normal, TextureResType texType) { _normalFileName = normal; _normalTexType = texType; @@ -236,7 +236,7 @@ void EditBox::loadTextureNormal(SpriteFrame* normalSpriteFrame) this->setupNormalTexture(nullptr != normalSpriteFrame); } -void EditBox::loadTexturePressed(std::string_view pressed, TextureResType texType) +void EditBox::loadTexturePressed(const std::string& pressed, TextureResType texType) { _pressedFileName = pressed; _pressedTexType = texType; @@ -279,7 +279,7 @@ void EditBox::loadTexturePressed(SpriteFrame* pressedSpriteFrame) this->setupPressedTexture(nullptr != pressedSpriteFrame); } -void EditBox::loadTextureDisabled(std::string_view disabled, TextureResType texType) +void EditBox::loadTextureDisabled(const std::string& disabled, TextureResType texType) { _disabledFileName = disabled; _disabledTexType = texType; diff --git a/cocos/ui/UIEditBox/UIEditBox.h b/cocos/ui/UIEditBox/UIEditBox.h index 990e4ab843..9d76b3bf78 100644 --- a/cocos/ui/UIEditBox/UIEditBox.h +++ b/cocos/ui/UIEditBox/UIEditBox.h @@ -78,7 +78,7 @@ public: * @param editBox The edit box object that generated the event. * @param text The new text. */ - virtual void editBoxTextChanged(EditBox* /*editBox*/, std::string_view /*text*/) {} + virtual void editBoxTextChanged(EditBox* /*editBox*/, const std::string& /*text*/) {} /** * This method is called when the return button was pressed or the outside area of keyboard was touched. @@ -214,17 +214,17 @@ public: * create a edit box with size. * @return An autorelease pointer of EditBox, you don't need to release it only if you retain it again. */ - static EditBox* create(const Size& size, std::string_view normalImage, TextureResType texType); + static EditBox* create(const Size& size, const std::string& normalImage, TextureResType texType); /** * create a edit box with size. * @return An autorelease pointer of EditBox, you don't need to release it only if you retain it again. */ static EditBox* create(const Size& size, - std::string_view normalImage, - std::string_view pressedImage = "", - std::string_view disabledImage = "", - TextureResType texType = TextureResType::LOCAL); + const std::string& normalImage, + const std::string& pressedImage = "", + const std::string& disabledImage = "", + TextureResType texType = TextureResType::LOCAL); /** * Constructor. @@ -248,7 +248,7 @@ public: * @return Whether initialization is successfully or not. */ bool initWithSizeAndBackgroundSprite(const Size& size, - std::string_view normal9SpriteBg, + const std::string& normal9SpriteBg, TextureResType texType = TextureResType::LOCAL); /** @@ -281,10 +281,10 @@ public: * @return Whether initialization is successfully or not. */ bool initWithSizeAndTexture(const Size& size, - std::string_view normalImage, - std::string_view pressedImage = "", - std::string_view disabledImage = "", - TextureResType texType = TextureResType::LOCAL); + const std::string& normalImage, + const std::string& pressedImage = "", + const std::string& disabledImage = "", + TextureResType texType = TextureResType::LOCAL); /** * Load textures for edit box. @@ -294,10 +294,10 @@ public: * @param disabled disabled state texture name. * @param texType @see `TextureResType` */ - void loadTextures(std::string_view normal, - std::string_view pressed, - std::string_view disabled = "", - TextureResType texType = TextureResType::LOCAL); + void loadTextures(const std::string& normal, + const std::string& pressed, + const std::string& disabled = "", + TextureResType texType = TextureResType::LOCAL); /** * Load normal state texture for edit box. @@ -305,7 +305,7 @@ public: * @param normal normal state texture. * @param texType @see `TextureResType` */ - void loadTextureNormal(std::string_view normal, TextureResType texType = TextureResType::LOCAL); + void loadTextureNormal(const std::string& normal, TextureResType texType = TextureResType::LOCAL); /** * Load pressed state texture for edit box. @@ -313,7 +313,7 @@ public: * @param pressed pressed state texture. * @param texType @see `TextureResType` */ - void loadTexturePressed(std::string_view pressed, TextureResType texType = TextureResType::LOCAL); + void loadTexturePressed(const std::string& pressed, TextureResType texType = TextureResType::LOCAL); /** * Load disabled state texture for edit box. @@ -321,7 +321,7 @@ public: * @param disabled dark state texture. * @param texType @see `TextureResType` */ - void loadTextureDisabled(std::string_view disabled, TextureResType texType = TextureResType::LOCAL); + void loadTextureDisabled(const std::string& disabled, TextureResType texType = TextureResType::LOCAL); /** * Sets capInsets for edit box. diff --git a/cocos/ui/UIEditBox/UIEditBoxImpl-android.cpp b/cocos/ui/UIEditBox/UIEditBoxImpl-android.cpp index d99aaea1cd..f23a4345c0 100644 --- a/cocos/ui/UIEditBox/UIEditBoxImpl-android.cpp +++ b/cocos/ui/UIEditBox/UIEditBoxImpl-android.cpp @@ -43,15 +43,15 @@ NS_CC_BEGIN -static const char* editBoxClassName = "org.cocos2dx.lib.Cocos2dxEditBoxHelper"; +static const std::string editBoxClassName = "org.cocos2dx.lib.Cocos2dxEditBoxHelper"; namespace ui { # define LOGD(...) __android_log_print(ANDROID_LOG_ERROR, "", __VA_ARGS__) static void editBoxEditingDidBegin(int index); -static void editBoxEditingDidChanged(int index, std::string_view text); -static void editBoxEditingDidEnd(int index, std::string_view text, int action); +static void editBoxEditingDidChanged(int index, const std::string& text); +static void editBoxEditingDidEnd(int index, const std::string& text, int action); extern "C" { JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxEditBoxHelper_editBoxEditingDidBegin(JNIEnv*, jclass, jint index) { @@ -221,7 +221,7 @@ void editBoxEditingDidBegin(int index) s_allEditBoxes[index]->editBoxEditingDidBegin(); } } -void editBoxEditingDidChanged(int index, std::string_view text) +void editBoxEditingDidChanged(int index, const std::string& text) { auto it = s_allEditBoxes.find(index); if (it != s_allEditBoxes.end()) @@ -230,7 +230,7 @@ void editBoxEditingDidChanged(int index, std::string_view text) } } -void editBoxEditingDidEnd(int index, std::string_view text, int action) +void editBoxEditingDidEnd(int index, const std::string& text, int action) { auto it = s_allEditBoxes.find(index); if (it != s_allEditBoxes.end()) diff --git a/cocos/ui/UIEditBox/UIEditBoxImpl-common.cpp b/cocos/ui/UIEditBox/UIEditBoxImpl-common.cpp index bd3fe9ba63..bf99aa2f5d 100644 --- a/cocos/ui/UIEditBox/UIEditBoxImpl-common.cpp +++ b/cocos/ui/UIEditBox/UIEditBoxImpl-common.cpp @@ -346,7 +346,7 @@ void EditBoxImplCommon::closeKeyboard() _editingMode = false; } -void EditBoxImplCommon::onEndEditing(std::string_view /*text*/) +void EditBoxImplCommon::onEndEditing(const std::string& /*text*/) { _editBox->setBrightStyle(Widget::BrightStyle::NORMAL); _editingMode = false; @@ -374,7 +374,7 @@ void EditBoxImplCommon::editBoxEditingDidBegin() #endif } -void EditBoxImplCommon::editBoxEditingDidEnd(std::string_view text, EditBoxDelegate::EditBoxEndAction action) +void EditBoxImplCommon::editBoxEditingDidEnd(const std::string& text, EditBoxDelegate::EditBoxEndAction action) { // LOGD("textFieldShouldEndEditing..."); _text = text; @@ -405,7 +405,7 @@ void EditBoxImplCommon::editBoxEditingDidEnd(std::string_view text, EditBoxDeleg } } -void EditBoxImplCommon::editBoxEditingChanged(std::string_view text) +void EditBoxImplCommon::editBoxEditingChanged(const std::string& text) { // LOGD("editBoxTextChanged..."); cocos2d::ui::EditBoxDelegate* pDelegate = _editBox->getDelegate(); diff --git a/cocos/ui/UIEditBox/UIEditBoxImpl-common.h b/cocos/ui/UIEditBox/UIEditBoxImpl-common.h index b14e41fe6b..419ce7a0c9 100644 --- a/cocos/ui/UIEditBox/UIEditBoxImpl-common.h +++ b/cocos/ui/UIEditBox/UIEditBoxImpl-common.h @@ -107,11 +107,11 @@ public: virtual void openKeyboard() override; virtual void closeKeyboard() override; - virtual void onEndEditing(std::string_view text); + virtual void onEndEditing(const std::string& text); void editBoxEditingDidBegin(); - void editBoxEditingChanged(std::string_view text); - void editBoxEditingDidEnd(std::string_view text, + void editBoxEditingChanged(const std::string& text); + void editBoxEditingDidEnd(const std::string& text, EditBoxDelegate::EditBoxEndAction action = EditBoxDelegate::EditBoxEndAction::UNKNOWN); virtual bool isEditing() override = 0; diff --git a/cocos/ui/UIEditBox/UIEditBoxImpl-ios.mm b/cocos/ui/UIEditBox/UIEditBoxImpl-ios.mm index 862e73f88b..9ac548fd83 100644 --- a/cocos/ui/UIEditBox/UIEditBoxImpl-ios.mm +++ b/cocos/ui/UIEditBox/UIEditBoxImpl-ios.mm @@ -3,19 +3,19 @@ Copyright (c) 2012 James Chen Copyright (c) 2013-2015 zilongshanren Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -28,38 +28,43 @@ #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) -# define kLabelZOrder 9999 +#define kLabelZOrder 9999 -# include "ui/UIEditBox/UIEditBox.h" -# include "base/CCDirector.h" -# include "2d/CCLabel.h" -# import "platform/ios/CCEAGLView-ios.h" +#include "ui/UIEditBox/UIEditBox.h" +#include "base/CCDirector.h" +#include "2d/CCLabel.h" +#import "platform/ios/CCEAGLView-ios.h" -# import -# import +#import +#import -# import "ui/UIEditBox/iOS/CCUIEditBoxIOS.h" +#import "ui/UIEditBox/iOS/CCUIEditBoxIOS.h" + +#define getEditBoxImplIOS() ((cocos2d::ui::EditBoxImplIOS *)_editBox) -# define getEditBoxImplIOS() ((cocos2d::ui::EditBoxImplIOS*)_editBox) NS_CC_BEGIN -namespace ui -{ +namespace ui { EditBoxImpl* __createSystemEditBox(EditBox* pEditBox) { return new EditBoxImplIOS(pEditBox); } -EditBoxImplIOS::EditBoxImplIOS(EditBox* pEditText) : EditBoxImplCommon(pEditText), _systemControl(nullptr) {} +EditBoxImplIOS::EditBoxImplIOS(EditBox* pEditText) +: EditBoxImplCommon(pEditText) +, _systemControl(nullptr) +{ + +} EditBoxImplIOS::~EditBoxImplIOS() { [_systemControl release]; _systemControl = nil; } - + void EditBoxImplIOS::createNativeControl(const Rect& frame) { auto glview = cocos2d::Director::getInstance()->getOpenGLView(); @@ -70,10 +75,13 @@ void EditBoxImplIOS::createNativeControl(const Rect& frame) rect.size.width /= factor; rect.size.height /= factor; + + _systemControl = [[UIEditBoxImplIOS_objc alloc] initWithFrame:CGRectMake(rect.origin.x, + rect.origin.y, + rect.size.width, + rect.size.height) + editBox:this]; - _systemControl = [[UIEditBoxImplIOS_objc alloc] - initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height) - editBox:this]; } bool EditBoxImplIOS::isEditing() @@ -83,34 +91,32 @@ bool EditBoxImplIOS::isEditing() void EditBoxImplIOS::doAnimationWhenKeyboardMove(float duration, float distance) { - if ([_systemControl isEditState] || distance < 0.0f) - { + if ([_systemControl isEditState] || distance < 0.0f) { [_systemControl doAnimationWhenKeyboardMoveWithDuration:duration distance:distance]; } } - + void EditBoxImplIOS::setNativeFont(const char* pFontName, int fontSize) { UIFont* textFont = constructFont(pFontName, fontSize); - if (textFont != nil) - { + if (textFont != nil) { [_systemControl setFont:textFont]; } } - + void EditBoxImplIOS::setNativeFontColor(const Color4B& color) { _systemControl.textColor = [UIColor colorWithRed:color.r / 255.0f - green:color.g / 255.0f - blue:color.b / 255.0f - alpha:color.a / 255.f]; + green:color.g / 255.0f + blue:color.b / 255.0f + alpha:color.a / 255.f]; + } void EditBoxImplIOS::setNativePlaceholderFont(const char* pFontName, int fontSize) { UIFont* textFont = constructFont(pFontName, fontSize); - if (textFont != nil) - { + if (textFont != nil) { [_systemControl setPlaceholderFont:textFont]; } } @@ -118,9 +124,9 @@ void EditBoxImplIOS::setNativePlaceholderFont(const char* pFontName, int fontSiz void EditBoxImplIOS::setNativePlaceholderFontColor(const Color4B& color) { [_systemControl setPlaceholderTextColor:[UIColor colorWithRed:color.r / 255.0f - green:color.g / 255.0f - blue:color.b / 255.0f - alpha:color.a / 255.f]]; + green:color.g / 255.0f + blue:color.b / 255.0f + alpha:color.a / 255.f]]; } void EditBoxImplIOS::setNativeInputMode(EditBox::InputMode inputMode) @@ -128,7 +134,7 @@ void EditBoxImplIOS::setNativeInputMode(EditBox::InputMode inputMode) [_systemControl setInputMode:inputMode]; auto oldPos = _editBox->getPosition(); - _editBox->setPosition(oldPos + Vec2(10, 10)); + _editBox->setPosition(oldPos + Vec2(10,10)); _editBox->setPosition(oldPos); } @@ -136,7 +142,7 @@ void EditBoxImplIOS::setNativeInputFlag(EditBox::InputFlag inputFlag) { [_systemControl setInputFlag:inputFlag]; } - + NSString* removeSiriString(NSString* str) { NSString* siriString = @"\xef\xbf\xbc"; @@ -148,6 +154,7 @@ const char* EditBoxImplIOS::getText() return [removeSiriString(_systemControl.text) UTF8String]; } + void EditBoxImplIOS::setNativeReturnType(EditBox::KeyboardReturnType returnType) { [_systemControl setReturnType:returnType]; @@ -160,9 +167,8 @@ void EditBoxImplIOS::setNativeTextHorizontalAlignment(cocos2d::TextHAlignment al void EditBoxImplIOS::setNativeText(const char* pText) { - NSString* nsText = [NSString stringWithUTF8String:pText]; - if ([nsText compare:_systemControl.text] != NSOrderedSame) - { + NSString* nsText =[NSString stringWithUTF8String:pText]; + if ([nsText compare:_systemControl.text] != NSOrderedSame) { _systemControl.text = nsText; } } @@ -179,13 +185,16 @@ void EditBoxImplIOS::setNativeVisible(bool visible) void EditBoxImplIOS::updateNativeFrame(const Rect& rect) { - auto glview = cocos2d::Director::getInstance()->getOpenGLView(); - CCEAGLView* eaglview = (CCEAGLView*)glview->getEAGLView(); + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView *eaglview = (CCEAGLView *) glview->getEAGLView(); float factor = eaglview.contentScaleFactor; - - [_systemControl updateFrame:CGRectMake(rect.origin.x / factor, rect.origin.y / factor, rect.size.width / factor, + + [_systemControl updateFrame:CGRectMake(rect.origin.x / factor, + rect.origin.y / factor, + rect.size.width / factor, rect.size.height / factor)]; + } const char* EditBoxImplIOS::getNativeDefaultFontName() @@ -204,34 +213,33 @@ void EditBoxImplIOS::nativeCloseKeyboard() { [_systemControl closeKeyboard]; } - -UIFont* EditBoxImplIOS::constructFont(const char* fontName, int fontSize) + +UIFont* EditBoxImplIOS::constructFont(const char *fontName, int fontSize) { CCASSERT(fontName != nullptr, "fontName can't be nullptr"); - CCEAGLView* eaglview = static_cast(cocos2d::Director::getInstance()->getOpenGLView()->getEAGLView()); - float retinaFactor = eaglview.contentScaleFactor; - NSString* fntName = [NSString stringWithUTF8String:fontName]; - + CCEAGLView *eaglview = static_cast(cocos2d::Director::getInstance()->getOpenGLView()->getEAGLView()); + float retinaFactor = eaglview.contentScaleFactor; + NSString * fntName = [NSString stringWithUTF8String:fontName]; + fntName = [[fntName lastPathComponent] stringByDeletingPathExtension]; - - auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); float scaleFactor = glview->getScaleX(); - + if (fontSize == -1) { - fontSize = _systemControl.frameRect.size.height * 2 / 3; + fontSize = _systemControl.frameRect.size.height*2/3; } else { fontSize = fontSize * scaleFactor / retinaFactor; } - - UIFont* textFont = nil; + + UIFont *textFont = nil; if (strlen(fontName) > 0) { textFont = [UIFont fontWithName:fntName size:fontSize]; - if (textFont == nil) - { + if (textFont == nil) { textFont = [UIFont systemFontOfSize:fontSize]; } } @@ -246,3 +254,5 @@ UIFont* EditBoxImplIOS::constructFont(const char* fontName, int fontSize) NS_CC_END #endif /* #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) */ + + diff --git a/cocos/ui/UIEditBox/UIEditBoxImpl-mac.mm b/cocos/ui/UIEditBox/UIEditBoxImpl-mac.mm index 800f9c916b..50099ae059 100644 --- a/cocos/ui/UIEditBox/UIEditBoxImpl-mac.mm +++ b/cocos/ui/UIEditBox/UIEditBoxImpl-mac.mm @@ -2,19 +2,19 @@ Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2012 Jozef Pridavok Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,23 +27,24 @@ #include "platform/CCPlatformConfig.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -# include "ui/UIEditBox/UIEditBoxImpl-mac.h" -# include "base/CCDirector.h" -# include "base/ccUTF8.h" -# include "ui/UIEditBox/UIEditBox.h" -# include "ui/UIEditBox/Mac/CCUIEditBoxMac.h" +#include "ui/UIEditBox/UIEditBoxImpl-mac.h" +#include "base/CCDirector.h" +#include "base/ccUTF8.h" +#include "ui/UIEditBox/UIEditBox.h" +#include "ui/UIEditBox/Mac/CCUIEditBoxMac.h" NS_CC_BEGIN -namespace ui -{ +namespace ui { EditBoxImpl* __createSystemEditBox(EditBox* pEditBox) { return new EditBoxImplMac(pEditBox); } -EditBoxImplMac::EditBoxImplMac(EditBox* pEditText) : EditBoxImplCommon(pEditText), _sysEdit(nullptr) +EditBoxImplMac::EditBoxImplMac(EditBox* pEditText) +: EditBoxImplCommon(pEditText) +, _sysEdit(nullptr) { //! TODO: Retina on Mac //! _inRetinaMode = [[CCEAGLView sharedEGLView] contentScaleFactor] == 2.0f ? true : false; @@ -55,40 +56,42 @@ EditBoxImplMac::~EditBoxImplMac() [_sysEdit release]; } -void EditBoxImplMac::createNativeControl(const cocos2d::Rect& frame) +void EditBoxImplMac::createNativeControl(const cocos2d::Rect &frame) { auto glview = cocos2d::Director::getInstance()->getOpenGLView(); - Size size = frame.size; - NSRect rect = NSMakeRect(0, 0, size.width * glview->getScaleX(), size.height * glview->getScaleY()); - + Size size = frame.size; + NSRect rect = NSMakeRect(0, 0, + size.width * glview->getScaleX(), + size.height * glview->getScaleY()); + float factor = cocos2d::Director::getInstance()->getContentScaleFactor(); - + rect.size.width /= factor; rect.size.height /= factor; - + _sysEdit = [[UIEditBoxImplMac alloc] initWithFrame:rect editBox:this]; this->setNativeVisible(false); } - -NSFont* EditBoxImplMac::constructFont(const char* fontName, int fontSize) + +NSFont* EditBoxImplMac::constructFont(const char *fontName, int fontSize) { - NSString* fntName = [NSString stringWithUTF8String:fontName]; - fntName = [[fntName lastPathComponent] stringByDeletingPathExtension]; + NSString * fntName = [NSString stringWithUTF8String:fontName]; + fntName = [[fntName lastPathComponent] stringByDeletingPathExtension]; float retinaFactor = _inRetinaMode ? 2.0f : 1.0f; - auto glview = cocos2d::Director::getInstance()->getOpenGLView(); - float scaleFactor = glview->getScaleX(); - + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + float scaleFactor = glview->getScaleX(); + if (fontSize == -1) { NSRect frameRect = [_sysEdit.textInput frame]; - fontSize = frameRect.size.height * 2 / 3; + fontSize = frameRect.size.height*2/3; } else { fontSize = fontSize * scaleFactor / retinaFactor; } - - NSFont* textFont = nil; + + NSFont *textFont = nil; if (strlen(fontName) == 0) { textFont = [NSFont systemFontOfSize:fontSize]; @@ -96,49 +99,47 @@ NSFont* EditBoxImplMac::constructFont(const char* fontName, int fontSize) else { textFont = [NSFont fontWithName:fntName size:fontSize]; - if (textFont == nil) - { + if (textFont == nil) { textFont = [NSFont systemFontOfSize:fontSize]; } } - + return textFont; } -void EditBoxImplMac::setNativeFont(const char* pFontName, int fontSize) +void EditBoxImplMac::setNativeFont(const char *pFontName, int fontSize) { NSFont* textFont = constructFont(pFontName, fontSize); [_sysEdit setFont:textFont]; } -void EditBoxImplMac::setNativePlaceholderFont(const char* pFontName, int fontSize) +void EditBoxImplMac::setNativePlaceholderFont(const char *pFontName, int fontSize) { - NSFont* textFont = constructFont(pFontName, fontSize); - - if (!textFont) - { + NSFont *textFont = constructFont(pFontName, fontSize); + + if (!textFont) { CCLOGWARN("Font not found: %s", pFontName); return; } [_sysEdit setPlaceholderFont:textFont]; } -void EditBoxImplMac::setNativeFontColor(const cocos2d::Color4B& color) +void EditBoxImplMac::setNativeFontColor(const cocos2d::Color4B &color) { - NSColor* newColor = [NSColor colorWithCalibratedRed:color.r / 255.0f + NSColor *newColor = [NSColor colorWithCalibratedRed:color.r / 255.0f green:color.g / 255.0f blue:color.b / 255.0f alpha:color.a / 255.f]; [_sysEdit setTextColor:newColor]; } - -void EditBoxImplMac::setNativePlaceholderFontColor(const cocos2d::Color4B& color) + +void EditBoxImplMac::setNativePlaceholderFontColor(const cocos2d::Color4B &color) { - NSColor* newColor = [NSColor colorWithCalibratedRed:color.r / 255.f - green:color.g / 255.f - blue:color.b / 255.f - alpha:color.a / 255.f]; + NSColor *newColor = [NSColor colorWithCalibratedRed:color.r/255.f + green:color.g / 255.f + blue:color.b / 255.f + alpha:color.a / 255.f]; [_sysEdit setPlaceholderFontColor:newColor]; } @@ -146,7 +147,7 @@ void EditBoxImplMac::setNativeInputMode(EditBox::InputMode inputMode) { [_sysEdit setInputMode:inputMode]; auto oldPosition = _editBox->getPosition(); - _editBox->setPosition(_editBox->getPosition() + Vec2(10, 10)); + _editBox->setPosition(_editBox->getPosition() + Vec2(10,10)); _editBox->setPosition(oldPosition); } @@ -155,6 +156,7 @@ void EditBoxImplMac::setNativeMaxLength(int maxLength) [_sysEdit setMaxLength:maxLength]; } + void EditBoxImplMac::setNativeInputFlag(EditBox::InputFlag inputFlag) { [_sysEdit setInputFlag:inputFlag]; @@ -175,12 +177,12 @@ bool EditBoxImplMac::isEditing() return [_sysEdit isEditState] ? true : false; } -void EditBoxImplMac::setNativeText(const char* pText) +void EditBoxImplMac::setNativeText(const char *pText) { - NSString* text = [NSString stringWithUTF8String:pText]; + NSString *text = [NSString stringWithUTF8String:pText]; [_sysEdit setText:text]; } - + void EditBoxImplMac::setNativePlaceHolder(const char* pText) { [_sysEdit setPlaceHolder:pText]; @@ -191,21 +193,24 @@ void EditBoxImplMac::setNativeVisible(bool visible) [_sysEdit setVisible:visible]; } -void EditBoxImplMac::updateNativeFrame(const cocos2d::Rect& rect) +void EditBoxImplMac::updateNativeFrame(const cocos2d::Rect &rect) { GLView* eglView = Director::getInstance()->getOpenGLView(); - auto frameSize = eglView->getFrameSize(); + auto frameSize = eglView->getFrameSize(); // Coordinate System on OSX has its origin at the lower left corner. - // https://developer.apple.com/library/ios/documentation/General/Conceptual/Devpedia-CocoaApp/CoordinateSystem.html +// https://developer.apple.com/library/ios/documentation/General/Conceptual/Devpedia-CocoaApp/CoordinateSystem.html auto screenPosY = frameSize.height - rect.origin.y - rect.size.height; - [_sysEdit updateFrame:CGRectMake(rect.origin.x, screenPosY, rect.size.width, rect.size.height)]; + [_sysEdit updateFrame:CGRectMake(rect.origin.x, + screenPosY, + rect.size.width, rect.size.height)]; } - + const char* EditBoxImplMac::getNativeDefaultFontName() { return [[_sysEdit getDefaultFontName] UTF8String]; } + void EditBoxImplMac::nativeOpenKeyboard() { [_sysEdit setVisible:YES]; @@ -221,4 +226,6 @@ void EditBoxImplMac::nativeCloseKeyboard() NS_CC_END -#endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) +#endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) + + diff --git a/cocos/ui/UIEditBox/iOS/CCUIEditBoxIOS.mm b/cocos/ui/UIEditBox/iOS/CCUIEditBoxIOS.mm index 134e0a540f..eb33fd0a2b 100644 --- a/cocos/ui/UIEditBox/iOS/CCUIEditBoxIOS.mm +++ b/cocos/ui/UIEditBox/iOS/CCUIEditBoxIOS.mm @@ -4,19 +4,19 @@ Copyright (c) 2013-2015 zilongshanren Copyright (c) 2015 Mazyad Alabduljaleel Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,7 +33,8 @@ #import "platform/ios/CCEAGLView-ios.h" #include "base/CCDirector.h" -#define getEditBoxImplIOS() ((cocos2d::ui::EditBoxImplIOS*)_editBox) +#define getEditBoxImplIOS() ((cocos2d::ui::EditBoxImplIOS *)_editBox) + @implementation UIEditBoxImplIOS_objc @@ -42,28 +43,27 @@ + (void)initialize { [super initialize]; - + LoadUITextViewCCUITextInputCategory(); LoadUITextFieldCCUITextInputCategory(); } #pragma mark - Init & Dealloc -- (instancetype)initWithFrame:(CGRect)frameRect editBox:(void*)editBox +- (instancetype)initWithFrame:(CGRect)frameRect editBox:(void *)editBox { self = [super init]; - if (self) - { - - _editState = NO; - self.frameRect = frameRect; - self.editBox = editBox; - self.dataInputMode = cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS; + if (self) { + + _editState = NO; + self.frameRect = frameRect; + self.editBox = editBox; + self.dataInputMode = cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS; self.keyboardReturnType = cocos2d::ui::EditBox::KeyboardReturnType::DEFAULT; - + [self createMultiLineTextField]; } - + return self; } @@ -71,39 +71,38 @@ { // custom setter cleanup self.textInput = nil; - + [super dealloc]; } #pragma mark - Properties -- (void)setTextInput:(UIView*)textInput +- (void)setTextInput:(UIView *)textInput { - if (_textInput == textInput) - { + if (_textInput == textInput) { return; } - + // common init textInput.backgroundColor = [UIColor clearColor]; - textInput.hidden = true; - textInput.returnKeyType = UIReturnKeyDefault; + textInput.hidden = true; + textInput.returnKeyType = UIReturnKeyDefault; [textInput ccui_setDelegate:self]; - + // Migrate properties - textInput.ccui_textColor = _textInput.ccui_textColor ?: [UIColor whiteColor]; - textInput.ccui_text = _textInput.ccui_text ?: @""; + textInput.ccui_textColor = _textInput.ccui_textColor ?: [UIColor whiteColor]; + textInput.ccui_text = _textInput.ccui_text ?: @""; textInput.ccui_placeholder = _textInput.ccui_placeholder ?: @""; - textInput.ccui_font = _textInput.ccui_font ?: [UIFont systemFontOfSize:self.frameRect.size.height * 2 / 3]; - textInput.ccui_placeholderFont = _textInput.ccui_placeholderFont ?: textInput.ccui_font; + textInput.ccui_font = _textInput.ccui_font ?: [UIFont systemFontOfSize:self.frameRect.size.height*2/3]; + textInput.ccui_placeholderFont = _textInput.ccui_placeholderFont ?: textInput.ccui_font; textInput.ccui_placeholderTextColor = _textInput.ccui_placeholderTextColor ?: [UIColor lightGrayColor]; - + [_textInput resignFirstResponder]; [_textInput removeFromSuperview]; [_textInput release]; - + _textInput = [textInput retain]; - + [self setInputFlag:self.dataInputMode]; [self setReturnType:self.keyboardReturnType]; } @@ -112,24 +111,24 @@ - (void)createSingleLineTextField { - CCUISingleLineTextField* textField = [[[CCUISingleLineTextField alloc] initWithFrame:self.frameRect] autorelease]; + CCUISingleLineTextField *textField = [[[CCUISingleLineTextField alloc] initWithFrame:self.frameRect] autorelease]; textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; - textField.borderStyle = UITextBorderStyleNone; - + textField.borderStyle = UITextBorderStyleNone; + [textField addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventEditingChanged]; - + self.textInput = textField; } - (void)createMultiLineTextField { - CCUIMultilineTextField* textView = [[[CCUIMultilineTextField alloc] initWithFrame:self.frameRect] autorelease]; - self.textInput = textView; + CCUIMultilineTextField *textView = [[[CCUIMultilineTextField alloc] initWithFrame:self.frameRect] autorelease]; + self.textInput = textView; } #pragma mark - Public methods -- (void)setFont:(UIFont*)font +- (void)setFont:(UIFont *)font { self.textInput.ccui_font = font; } @@ -139,57 +138,53 @@ self.textInput.ccui_textColor = color; } -- (void)setPlaceholderFont:(UIFont*)font +- (void)setPlaceholderFont:(UIFont *)font { self.textInput.ccui_placeholderFont = font; } -- (void)setPlaceholderTextColor:(UIColor*)color +- (void)setPlaceholderTextColor:(UIColor *)color { self.textInput.ccui_placeholderTextColor = color; } - (void)setInputMode:(cocos2d::ui::EditBox::InputMode)inputMode { - // multiline input - if (inputMode == cocos2d::ui::EditBox::InputMode::ANY) - { - if (![self.textInput isKindOfClass:[UITextView class]]) - { + //multiline input + if (inputMode == cocos2d::ui::EditBox::InputMode::ANY) { + if (![self.textInput isKindOfClass:[UITextView class]]) { [self createMultiLineTextField]; } } - else - { - if (![self.textInput isKindOfClass:[UITextField class]]) - { + else { + if (![self.textInput isKindOfClass:[UITextField class]]) { [self createSingleLineTextField]; } } - + switch (inputMode) { - case cocos2d::ui::EditBox::InputMode::EMAIL_ADDRESS: - self.keyboardType = UIKeyboardTypeEmailAddress; - break; - case cocos2d::ui::EditBox::InputMode::NUMERIC: - self.keyboardType = UIKeyboardTypeDecimalPad; - break; - case cocos2d::ui::EditBox::InputMode::PHONE_NUMBER: - self.keyboardType = UIKeyboardTypePhonePad; - break; - case cocos2d::ui::EditBox::InputMode::URL: - self.keyboardType = UIKeyboardTypeURL; - break; - case cocos2d::ui::EditBox::InputMode::DECIMAL: - self.keyboardType = UIKeyboardTypeDecimalPad; - break; - case cocos2d::ui::EditBox::InputMode::SINGLE_LINE: - self.keyboardType = UIKeyboardTypeDefault; - break; - default: - self.keyboardType = UIKeyboardTypeDefault; - break; + case cocos2d::ui::EditBox::InputMode::EMAIL_ADDRESS: + self.keyboardType = UIKeyboardTypeEmailAddress; + break; + case cocos2d::ui::EditBox::InputMode::NUMERIC: + self.keyboardType = UIKeyboardTypeDecimalPad; + break; + case cocos2d::ui::EditBox::InputMode::PHONE_NUMBER: + self.keyboardType = UIKeyboardTypePhonePad; + break; + case cocos2d::ui::EditBox::InputMode::URL: + self.keyboardType = UIKeyboardTypeURL; + break; + case cocos2d::ui::EditBox::InputMode::DECIMAL: + self.keyboardType = UIKeyboardTypeDecimalPad; + break; + case cocos2d::ui::EditBox::InputMode::SINGLE_LINE: + self.keyboardType = UIKeyboardTypeDefault; + break; + default: + self.keyboardType = UIKeyboardTypeDefault; + break; } } @@ -203,68 +198,67 @@ self.dataInputMode = flag; switch (flag) { - case cocos2d::ui::EditBox::InputFlag::PASSWORD: - // textView can't be used for input password - self.textInput.ccui_secureTextEntry = YES; - break; - - case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_WORD: - self.textInput.autocapitalizationType = UITextAutocapitalizationTypeWords; - break; - - case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_SENTENCE: - self.textInput.autocapitalizationType = UITextAutocapitalizationTypeSentences; - break; - - case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_ALL_CHARACTERS: - self.textInput.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters; - break; - - case cocos2d::ui::EditBox::InputFlag::SENSITIVE: - self.textInput.autocorrectionType = UITextAutocorrectionTypeNo; - break; - - case cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS: - self.textInput.autocapitalizationType = UITextAutocapitalizationTypeNone; - break; - - default: - break; + case cocos2d::ui::EditBox::InputFlag::PASSWORD: + //textView can't be used for input password + self.textInput.ccui_secureTextEntry = YES; + break; + + case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_WORD: + self.textInput.autocapitalizationType = UITextAutocapitalizationTypeWords; + break; + + case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_SENTENCE: + self.textInput.autocapitalizationType = UITextAutocapitalizationTypeSentences; + break; + + case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_ALL_CHARACTERS: + self.textInput.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters; + break; + + case cocos2d::ui::EditBox::InputFlag::SENSITIVE: + self.textInput.autocorrectionType = UITextAutocorrectionTypeNo; + break; + + case cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS: + self.textInput.autocapitalizationType = UITextAutocapitalizationTypeNone; + break; + + default: + break; } } - (void)setReturnType:(cocos2d::ui::EditBox::KeyboardReturnType)returnType { self.keyboardReturnType = returnType; - switch (returnType) - { - case cocos2d::ui::EditBox::KeyboardReturnType::DEFAULT: - self.textInput.returnKeyType = UIReturnKeyDefault; - break; + switch (returnType) { + case cocos2d::ui::EditBox::KeyboardReturnType::DEFAULT: + self.textInput.returnKeyType = UIReturnKeyDefault; + break; + + case cocos2d::ui::EditBox::KeyboardReturnType::DONE: + self.textInput.returnKeyType = UIReturnKeyDone; + break; + + case cocos2d::ui::EditBox::KeyboardReturnType::SEND: + self.textInput.returnKeyType = UIReturnKeySend; + break; + + case cocos2d::ui::EditBox::KeyboardReturnType::SEARCH: + self.textInput.returnKeyType = UIReturnKeySearch; + break; + + case cocos2d::ui::EditBox::KeyboardReturnType::GO: + self.textInput.returnKeyType = UIReturnKeyGo; + break; + + case cocos2d::ui::EditBox::KeyboardReturnType::NEXT: + self.textInput.returnKeyType = UIReturnKeyNext; + break; - case cocos2d::ui::EditBox::KeyboardReturnType::DONE: - self.textInput.returnKeyType = UIReturnKeyDone; - break; - - case cocos2d::ui::EditBox::KeyboardReturnType::SEND: - self.textInput.returnKeyType = UIReturnKeySend; - break; - - case cocos2d::ui::EditBox::KeyboardReturnType::SEARCH: - self.textInput.returnKeyType = UIReturnKeySearch; - break; - - case cocos2d::ui::EditBox::KeyboardReturnType::GO: - self.textInput.returnKeyType = UIReturnKeyGo; - break; - - case cocos2d::ui::EditBox::KeyboardReturnType::NEXT: - self.textInput.returnKeyType = UIReturnKeyNext; - break; - - default: - self.textInput.returnKeyType = UIReturnKeyDefault; - break; + default: + self.textInput.returnKeyType = UIReturnKeyDefault; + break; } } @@ -273,12 +267,12 @@ self.textInput.ccui_alignment = static_cast(alignment); } -- (void)setText:(NSString*)text +- (void)setText:(NSString *)text { self.textInput.ccui_text = text; } -- (NSString*)text +- (NSString *)text { return self.textInput.ccui_text ?: @""; } @@ -288,7 +282,7 @@ self.textInput.hidden = !visible; } -- (NSString*)getDefaultFontName +- (NSString *)getDefaultFontName { return self.textInput.ccui_font.fontName ?: @""; } @@ -296,32 +290,28 @@ - (cocos2d::ui::EditBoxDelegate::EditBoxEndAction)getEndAction { cocos2d::ui::EditBoxDelegate::EditBoxEndAction action = cocos2d::ui::EditBoxDelegate::EditBoxEndAction::UNKNOWN; - if (self.returnPressed) - { - if (self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::NEXT) - { + if (self.returnPressed) { + if (self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::NEXT) { action = cocos2d::ui::EditBoxDelegate::EditBoxEndAction::TAB_TO_NEXT; - } - else if (self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::GO || - self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::SEND || - self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::SEARCH) - { + } else if (self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::GO || + self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::SEND || + self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::SEARCH) { action = cocos2d::ui::EditBoxDelegate::EditBoxEndAction::RETURN; } } return action; } -- (void)setPlaceHolder:(NSString*)text +- (void)setPlaceHolder:(NSString *)text { self.textInput.ccui_placeholder = text; } - (void)doAnimationWhenKeyboardMoveWithDuration:(float)duration distance:(float)distance { - auto view = cocos2d::Director::getInstance()->getOpenGLView(); - CCEAGLView* eaglview = (CCEAGLView*)view->getEAGLView(); - + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView *eaglview = (CCEAGLView *)view->getEAGLView(); + [eaglview doAnimationWhenKeyboardMoveWithDuration:duration distance:distance]; } @@ -329,16 +319,16 @@ { CGRect frame = self.textInput.frame; frame.origin = rect.origin; - frame.size = rect.size; - + frame.size = rect.size; + self.textInput.frame = frame; } - (void)openKeyboard { - auto view = cocos2d::Director::getInstance()->getOpenGLView(); - CCEAGLView* eaglview = (CCEAGLView*)view->getEAGLView(); - + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView *eaglview = (CCEAGLView *)view->getEAGLView(); + [eaglview addSubview:self.textInput]; [self.textInput becomeFirstResponder]; } @@ -349,10 +339,9 @@ [self.textInput removeFromSuperview]; } -- (BOOL)textFieldShouldReturn:(UITextField*)sender +- (BOOL)textFieldShouldReturn:(UITextField *)sender { - if (sender == self.textInput) - { + if (sender == self.textInput) { self.returnPressed = YES; [sender resignFirstResponder]; } @@ -361,33 +350,32 @@ - (void)animationSelector { - auto view = cocos2d::Director::getInstance()->getOpenGLView(); - CCEAGLView* eaglview = (CCEAGLView*)view->getEAGLView(); - + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView *eaglview = (CCEAGLView *)view->getEAGLView(); + [eaglview doAnimationWhenAnotherEditBeClicked]; } #pragma mark - UITextView delegate methods -- (BOOL)textViewShouldBeginEditing:(UITextView*)textView +- (BOOL)textViewShouldBeginEditing:(UITextView *)textView { CCLOG("textFieldShouldBeginEditing..."); - _editState = YES; + _editState = YES; _returnPressed = NO; - - auto view = cocos2d::Director::getInstance()->getOpenGLView(); - CCEAGLView* eaglview = (CCEAGLView*)view->getEAGLView(); - - if ([eaglview isKeyboardShown]) - { + + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView *eaglview = (CCEAGLView *) view->getEAGLView(); + + if ([eaglview isKeyboardShown]) { [self performSelector:@selector(animationSelector) withObject:nil afterDelay:0.0f]; } - + getEditBoxImplIOS()->editBoxEditingDidBegin(); return YES; } -- (BOOL)textViewShouldEndEditing:(UITextView*)textView +- (BOOL)textViewShouldEndEditing:(UITextView *)textView { CCLOG("textFieldShouldEndEditing..."); _editState = NO; @@ -395,99 +383,94 @@ const char* inputText = [textView.text UTF8String]; getEditBoxImplIOS()->editBoxEditingDidEnd(inputText, [self getEndAction]); - + return YES; } -- (BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text +- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { - if (self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::DONE && [text isEqualToString:@"\n"]) + if ( self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::DONE && + [text isEqualToString: @"\n"] ) { [self closeKeyboard]; } - + int maxLength = getEditBoxImplIOS()->getMaxLength(); if (maxLength < 0) { return YES; } - - // Prevent crashing undo bug - // http://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfield - if (range.length + range.location > textView.text.length) - { + + // Prevent crashing undo bug http://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfield + if (range.length + range.location > textView.text.length) { return NO; } - - NSUInteger oldLength = textView.text.length; + + NSUInteger oldLength = textView.text.length; NSUInteger replacementLength = text.length; - NSUInteger rangeLength = range.length; - + NSUInteger rangeLength = range.length; + NSUInteger newLength = oldLength - rangeLength + replacementLength; - + return newLength <= maxLength; } -- (void)textViewDidChange:(UITextView*)textView +- (void)textViewDidChange:(UITextView *)textView { int maxLength = getEditBoxImplIOS()->getMaxLength(); - if (textView.markedTextRange == nil) - { - if (textView.text.length > maxLength) - { + if (textView.markedTextRange == nil) { + if (textView.text.length > maxLength) { textView.text = [textView.text substringToIndex:maxLength]; } - + const char* inputText = [textView.text UTF8String]; getEditBoxImplIOS()->editBoxEditingChanged(inputText); } } + #pragma mark - UITextField delegate methods /** * Called each time when the text field's text has changed. */ -- (void)textChanged:(UITextField*)textField +- (void)textChanged:(UITextField *)textField { int maxLength = getEditBoxImplIOS()->getMaxLength(); - if (textField.markedTextRange == nil) - { - if (textField.text.length > maxLength) - { + if (textField.markedTextRange == nil) { + if (textField.text.length > maxLength) { textField.text = [textField.text substringToIndex:maxLength]; } - + const char* inputText = [textField.text UTF8String]; getEditBoxImplIOS()->editBoxEditingChanged(inputText); } } -- (BOOL)textFieldShouldBeginEditing:(UITextField*)sender // return NO to disallow editing. +- (BOOL)textFieldShouldBeginEditing:(UITextField *)sender // return NO to disallow editing. { CCLOG("textFieldShouldBeginEditing..."); - _editState = YES; + _editState = YES; _returnPressed = NO; - - auto view = cocos2d::Director::getInstance()->getOpenGLView(); - CCEAGLView* eaglview = (CCEAGLView*)view->getEAGLView(); - - if ([eaglview isKeyboardShown]) - { + + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView *eaglview = (CCEAGLView *)view->getEAGLView(); + + if ([eaglview isKeyboardShown]) { [self performSelector:@selector(animationSelector) withObject:nil afterDelay:0.0f]; } - + getEditBoxImplIOS()->editBoxEditingDidBegin(); return YES; } -- (BOOL)textFieldShouldEndEditing:(UITextField*)sender +- (BOOL)textFieldShouldEndEditing:(UITextField *)sender { CCLOG("textFieldShouldEndEditing..."); - _editState = NO; + _editState = NO; const char* inputText = [sender.text UTF8String]; getEditBoxImplIOS()->editBoxEditingDidEnd(inputText, [self getEndAction]); - + return YES; } @@ -498,29 +481,24 @@ * @param string The replacement string. * @return YES if the specified text range should be replaced; otherwise, NO to keep the old text. */ -- (BOOL)textField:(UITextField*)textField - shouldChangeCharactersInRange:(NSRange)range - replacementString:(NSString*)string +- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { int maxLength = getEditBoxImplIOS()->getMaxLength(); - if (maxLength < 0) - { + if (maxLength < 0) { return YES; } - - // Prevent crashing undo bug - // http://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfield - if (range.length + range.location > textField.text.length) - { + + // Prevent crashing undo bug http://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfield + if (range.length + range.location > textField.text.length) { return NO; } - - NSUInteger oldLength = textField.text.length; + + NSUInteger oldLength = textField.text.length; NSUInteger replacementLength = string.length; - NSUInteger rangeLength = range.length; - + NSUInteger rangeLength = range.length; + NSUInteger newLength = oldLength - rangeLength + replacementLength; - + return newLength <= maxLength; } diff --git a/cocos/ui/UIEditBox/iOS/CCUIMultilineTextField.mm b/cocos/ui/UIEditBox/iOS/CCUIMultilineTextField.mm index d574b8269b..0f84f752dc 100644 --- a/cocos/ui/UIEditBox/iOS/CCUIMultilineTextField.mm +++ b/cocos/ui/UIEditBox/iOS/CCUIMultilineTextField.mm @@ -3,19 +3,19 @@ Copyright (c) 2012 James Chen Copyright (c) 2015 Mazyad Alabduljaleel Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,6 +34,7 @@ */ CGFloat const UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION = 0.25; + @implementation CCUIMultilineTextField #pragma mark - Init & Dealloc @@ -41,9 +42,8 @@ CGFloat const UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION = 0.25; - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; - if (self) - { - + if (self) { + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification @@ -55,50 +55,51 @@ CGFloat const UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION = 0.25; - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; - + [_placeHolderLabel release]; - + [super dealloc]; } #pragma mark - Properties -- (NSString*)placeholder +- (NSString *)placeholder { return self.placeHolderLabel.text; } -- (void)setPlaceholder:(NSString*)placeholder +- (void)setPlaceholder:(NSString *)placeholder { self.placeHolderLabel.text = placeholder; [self.placeHolderLabel sizeToFit]; } -- (void)setText:(NSString*)text +- (void)setText:(NSString *)text { [super setText:text]; [self textChanged:nil]; } -- (UILabel*)placeHolderLabel +- (UILabel *)placeHolderLabel { - if (_placeHolderLabel == nil) - { - auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + if (_placeHolderLabel == nil) { + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); float padding = CC_EDIT_BOX_PADDING * glview->getScaleX() / glview->getContentScaleFactor(); - _placeHolderLabel = - [[UILabel alloc] initWithFrame:CGRectMake(padding, padding, self.bounds.size.width - padding * 2, 0)]; - _placeHolderLabel.lineBreakMode = NSLineBreakByWordWrapping; - _placeHolderLabel.numberOfLines = 0; - _placeHolderLabel.font = self.font; + _placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(padding, + padding, + self.bounds.size.width - padding * 2, + 0)]; + _placeHolderLabel.lineBreakMode = NSLineBreakByWordWrapping; + _placeHolderLabel.numberOfLines = 0; + _placeHolderLabel.font = self.font; _placeHolderLabel.backgroundColor = [UIColor clearColor]; - _placeHolderLabel.textColor = [UIColor lightGrayColor]; - _placeHolderLabel.alpha = 0; - + _placeHolderLabel.textColor = [UIColor lightGrayColor]; + _placeHolderLabel.alpha = 0; + [self addSubview:_placeHolderLabel]; } - + return _placeHolderLabel; } @@ -107,7 +108,7 @@ CGFloat const UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION = 0.25; - (CGRect)textRectForBounds:(CGRect)bounds { auto glview = cocos2d::Director::getInstance()->getOpenGLView(); - + float padding = CC_EDIT_BOX_PADDING * glview->getScaleX() / glview->getContentScaleFactor(); return CGRectInset(bounds, padding, padding); } @@ -120,37 +121,34 @@ CGFloat const UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION = 0.25; - (void)layoutSubviews { [super layoutSubviews]; - - if (self.placeholder.length > 0) - { + + if (self.placeholder.length > 0) { [self sendSubviewToBack:self.placeHolderLabel]; } } - (void)drawRect:(CGRect)rect { - if (self.text.length == 0 && self.placeholder.length > 0) - { + if (self.text.length == 0 && self.placeholder.length > 0) { self.placeHolderLabel.alpha = 1; } - + [super drawRect:rect]; } #pragma mark - NSNotification Observers -- (void)textChanged:(NSNotification*)notification +- (void)textChanged:(NSNotification *)notification { - if (self.placeholder.length == 0) - { + if (self.placeholder.length == 0) { return; } - - [UIView animateWithDuration:UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION - animations:^{ - CGFloat alpha = (self.text.length == 0 ? 1 : 0); - self.placeHolderLabel.alpha = alpha; - }]; + + [UIView animateWithDuration:UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION animations:^{ + + CGFloat alpha = (self.text.length == 0 ? 1 : 0); + self.placeHolderLabel.alpha = alpha; + }]; } @end diff --git a/cocos/ui/UIEditBox/iOS/CCUISingleLineTextField.mm b/cocos/ui/UIEditBox/iOS/CCUISingleLineTextField.mm index 6a4e1b3f3c..2c4b28e624 100644 --- a/cocos/ui/UIEditBox/iOS/CCUISingleLineTextField.mm +++ b/cocos/ui/UIEditBox/iOS/CCUISingleLineTextField.mm @@ -3,19 +3,19 @@ Copyright (c) 2012 James Chen Copyright (c) 2015 Mazyad Alabduljaleel Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,6 +34,7 @@ * http://stackoverflow.com/questions/18244790/changing-uitextfield-placeholder-font */ + @implementation CCUISingleLineTextField #pragma mark - Init & Dealloc @@ -48,28 +49,29 @@ #pragma mark - Properties -- (UIColor*)placeholderTextColor +- (UIColor *)placeholderTextColor { return _placeholderTextColor; } -- (UIFont*)placeholderFont +- (UIFont *)placeholderFont { return _placeholderFont; } #pragma mark - Public methods -- (void)drawPlaceholderInRect:(CGRect)rect -{ - NSDictionary* attributes = - @{NSForegroundColorAttributeName : _placeholderTextColor, NSFontAttributeName : _placeholderFont}; - +- (void)drawPlaceholderInRect:(CGRect)rect { + NSDictionary *attributes = @{ + NSForegroundColorAttributeName:_placeholderTextColor, + NSFontAttributeName:_placeholderFont + }; + // center vertically CGSize textSize = [self.placeholder sizeWithAttributes:attributes]; - CGFloat hdif = rect.size.height - textSize.height; - hdif = MAX(0, hdif); - rect.origin.y += ceil(hdif / 2.0); + CGFloat hdif = rect.size.height - textSize.height; + hdif = MAX(0, hdif); + rect.origin.y += ceil(hdif/2.0); [[self placeholder] drawInRect:rect withAttributes:attributes]; } @@ -77,7 +79,7 @@ - (CGRect)textRectForBounds:(CGRect)bounds { auto glview = cocos2d::Director::getInstance()->getOpenGLView(); - + float padding = CC_EDIT_BOX_PADDING * glview->getScaleX() / glview->getContentScaleFactor(); return CGRectInset(bounds, padding, padding); } diff --git a/cocos/ui/UIEditBox/iOS/UITextField+CCUITextInput.mm b/cocos/ui/UIEditBox/iOS/UITextField+CCUITextInput.mm index 77f51f2a3c..07fdd0a955 100644 --- a/cocos/ui/UIEditBox/iOS/UITextField+CCUITextInput.mm +++ b/cocos/ui/UIEditBox/iOS/UITextField+CCUITextInput.mm @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2015 Mazyad Alabduljaleel Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,90 +27,86 @@ @implementation UITextField (CCUITextInput) -- (NSString*)ccui_text +- (NSString *)ccui_text { return self.text; } -- (void)ccui_setText:(NSString*)ccui_text +- (void)ccui_setText:(NSString *)ccui_text { self.text = ccui_text; } -- (NSString*)ccui_placeholder +- (NSString *)ccui_placeholder { return self.placeholder; } -- (void)ccui_setPlaceholder:(NSString*)ccui_placeholder +- (void)ccui_setPlaceholder:(NSString *)ccui_placeholder { self.placeholder = ccui_placeholder; } -- (UIColor*)ccui_textColor +- (UIColor *)ccui_textColor { return self.textColor; } -- (void)ccui_setTextColor:(UIColor*)ccui_textColor +- (void)ccui_setTextColor:(UIColor *)ccui_textColor { self.textColor = ccui_textColor; } -- (UIFont*)ccui_font +- (UIFont *)ccui_font { return self.font; } -- (void)ccui_setFont:(UIFont*)ccui_font +- (void)ccui_setFont:(UIFont *)ccui_font { self.font = ccui_font; } - (NSTextAlignment)ccui_alignment { - return self.textAlignment; + return self.textAlignment; } - (void)ccui_setTextHorizontalAlignment:(NSTextAlignment)ccui_alignment { - self.textAlignment = ccui_alignment; + self.textAlignment = ccui_alignment; } -- (UIColor*)ccui_placeholderTextColor +- (UIColor *)ccui_placeholderTextColor { SEL selector = NSSelectorFromString(@"placeholderTextColor"); - if ([self respondsToSelector:selector]) - { + if ([self respondsToSelector:selector]) { return [self performSelector:selector]; } return nil; } -- (void)ccui_setPlaceholderTextColor:(UIColor*)ccui_placeholderTextColor +- (void)ccui_setPlaceholderTextColor:(UIColor *)ccui_placeholderTextColor { SEL selector = NSSelectorFromString(@"setPlaceholderTextColor:"); - if ([self respondsToSelector:selector]) - { + if ([self respondsToSelector:selector]) { [self performSelector:selector withObject:ccui_placeholderTextColor]; } } -- (UIFont*)ccui_placeholderFont +- (UIFont *)ccui_placeholderFont { SEL selector = NSSelectorFromString(@"placeholderFont"); - if ([self respondsToSelector:selector]) - { + if ([self respondsToSelector:selector]) { return [self performSelector:selector]; } return nil; } -- (void)ccui_setPlaceholderFont:(UIFont*)ccui_placeholderFont +- (void)ccui_setPlaceholderFont:(UIFont *)ccui_placeholderFont { SEL selector = NSSelectorFromString(@"setPlaceholderFont:"); - if ([self respondsToSelector:selector]) - { + if ([self respondsToSelector:selector]) { [self performSelector:selector withObject:ccui_placeholderFont]; } } @@ -125,14 +121,14 @@ self.secureTextEntry = ccui_secureTextEntry; } -- (void)ccui_setDelegate:(id)delegate +- (void)ccui_setDelegate:(id)delegate { self.delegate = delegate; } @end -void LoadUITextFieldCCUITextInputCategory() -{ + +void LoadUITextFieldCCUITextInputCategory() { // noop } diff --git a/cocos/ui/UIEditBox/iOS/UITextView+CCUITextInput.mm b/cocos/ui/UIEditBox/iOS/UITextView+CCUITextInput.mm index 94ce69956a..04fc84d87f 100644 --- a/cocos/ui/UIEditBox/iOS/UITextView+CCUITextInput.mm +++ b/cocos/ui/UIEditBox/iOS/UITextView+CCUITextInput.mm @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2015 Mazyad Alabduljaleel Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -25,53 +25,52 @@ #import "ui/UIEditBox/iOS/UITextView+CCUITextInput.h" + @implementation UITextView (CCUITextInput) -- (NSString*)ccui_text +- (NSString *)ccui_text { return self.text; } -- (void)ccui_setText:(NSString*)ccui_text +- (void)ccui_setText:(NSString *)ccui_text { self.text = ccui_text; } -- (NSString*)ccui_placeholder +- (NSString *)ccui_placeholder { SEL selector = @selector(placeholder); - if ([self respondsToSelector:selector]) - { + if ([self respondsToSelector:selector]) { return [self performSelector:selector]; } return nil; } -- (void)ccui_setPlaceholder:(NSString*)ccui_placeholder +- (void)ccui_setPlaceholder:(NSString *)ccui_placeholder { SEL selector = @selector(setPlaceholder:); - if ([self respondsToSelector:selector]) - { + if ([self respondsToSelector:selector]) { [self performSelector:selector withObject:ccui_placeholder]; } } -- (UIColor*)ccui_textColor +- (UIColor *)ccui_textColor { return self.textColor; } -- (void)ccui_setTextColor:(UIColor*)ccui_textColor +- (void)ccui_setTextColor:(UIColor *)ccui_textColor { self.textColor = ccui_textColor; } -- (UIFont*)ccui_font +- (UIFont *)ccui_font { return self.font; } -- (void)ccui_setFont:(UIFont*)ccui_font +- (void)ccui_setFont:(UIFont *)ccui_font { self.font = ccui_font; } @@ -86,41 +85,37 @@ self.textAlignment = ccui_alignment; } -- (UIColor*)ccui_placeholderTextColor +- (UIColor *)ccui_placeholderTextColor { SEL selector = NSSelectorFromString(@"placeHolderLabel"); - if ([self respondsToSelector:selector]) - { - return ((UILabel*)[self performSelector:selector]).textColor; + if ([self respondsToSelector:selector]) { + return ((UILabel *)[self performSelector:selector]).textColor; } return nil; } -- (void)ccui_setPlaceholderTextColor:(UIColor*)ccui_placeholderTextColor +- (void)ccui_setPlaceholderTextColor:(UIColor *)ccui_placeholderTextColor { SEL selector = NSSelectorFromString(@"placeHolderLabel"); - if ([self respondsToSelector:selector]) - { - ((UILabel*)[self performSelector:selector]).textColor = ccui_placeholderTextColor; + if ([self respondsToSelector:selector]) { + ((UILabel *)[self performSelector:selector]).textColor = ccui_placeholderTextColor; } } -- (UIFont*)ccui_placeholderFont +- (UIFont *)ccui_placeholderFont { SEL selector = NSSelectorFromString(@"placeHolderLabel"); - if ([self respondsToSelector:selector]) - { - return ((UILabel*)[self performSelector:selector]).font; + if ([self respondsToSelector:selector]) { + return ((UILabel *)[self performSelector:selector]).font; } return nil; } -- (void)ccui_setPlaceholderFont:(UIFont*)ccui_placeholderFont +- (void)ccui_setPlaceholderFont:(UIFont *)ccui_placeholderFont { SEL selector = NSSelectorFromString(@"placeHolderLabel"); - if ([self respondsToSelector:selector]) - { - ((UILabel*)[self performSelector:selector]).font = ccui_placeholderFont; + if ([self respondsToSelector:selector]) { + ((UILabel *)[self performSelector:selector]).font = ccui_placeholderFont; } } @@ -134,11 +129,14 @@ self.secureTextEntry = ccui_secureTextEntry; } -- (void)ccui_setDelegate:(id)delegate +- (void)ccui_setDelegate:(id)delegate { self.delegate = delegate; } @end -void LoadUITextViewCCUITextInputCategory() {} + +void LoadUITextViewCCUITextInputCategory() { + +} diff --git a/cocos/ui/UIHelper.cpp b/cocos/ui/UIHelper.cpp index eaa645c707..60f3a98ebb 100644 --- a/cocos/ui/UIHelper.cpp +++ b/cocos/ui/UIHelper.cpp @@ -63,7 +63,7 @@ Widget* Helper::seekWidgetByTag(Widget* root, int tag) return nullptr; } -Widget* Helper::seekWidgetByName(Widget* root, std::string_view name) +Widget* Helper::seekWidgetByName(Widget* root, const std::string& name) { if (!root) { @@ -116,25 +116,25 @@ Widget* Helper::seekActionWidgetByActionTag(Widget* root, int tag) return nullptr; } -std::string Helper::getSubStringOfUTF8String(std::string_view str, +std::string Helper::getSubStringOfUTF8String(const std::string& str, std::string::size_type start, std::string::size_type length) { std::u32string utf32; if (!StringUtils::UTF8ToUTF32(str, utf32)) { - CCLOGERROR("Can't convert string to UTF-32: %s", str.data()); + CCLOGERROR("Can't convert string to UTF-32: %s", str.c_str()); return ""; } if (utf32.size() < start) { - CCLOGERROR("'start' is out of range: %d, %s", static_cast(start), str.data()); + CCLOGERROR("'start' is out of range: %d, %s", static_cast(start), str.c_str()); return ""; } std::string result; if (!StringUtils::UTF32ToUTF8(utf32.substr(start, length), result)) { - CCLOGERROR("Can't convert internal UTF-32 string to UTF-8: %s", str.data()); + CCLOGERROR("Can't convert internal UTF-32 string to UTF-8: %s", str.c_str()); return ""; } return result; diff --git a/cocos/ui/UIHelper.h b/cocos/ui/UIHelper.h index 9d49b129c7..9f833bef18 100644 --- a/cocos/ui/UIHelper.h +++ b/cocos/ui/UIHelper.h @@ -66,7 +66,7 @@ public: * @param name The widget name. * @return Widget instance pointer. */ - static Widget* seekWidgetByName(Widget* root, std::string_view name); + static Widget* seekWidgetByName(Widget* root, const std::string& name); /** * Find a widget with a specific action tag from root widget @@ -87,7 +87,7 @@ public: * @return a UTF8 substring * @js NA */ - static std::string getSubStringOfUTF8String(std::string_view str, + static std::string getSubStringOfUTF8String(const std::string& str, std::string::size_type start, std::string::size_type length); diff --git a/cocos/ui/UIImageView.cpp b/cocos/ui/UIImageView.cpp index ffa0391536..da9ed8c515 100644 --- a/cocos/ui/UIImageView.cpp +++ b/cocos/ui/UIImageView.cpp @@ -50,7 +50,7 @@ ImageView::ImageView() ImageView::~ImageView() {} -ImageView* ImageView::create(std::string_view imageFileName, TextureResType texType) +ImageView* ImageView::create(const std::string& imageFileName, TextureResType texType) { ImageView* widget = new ImageView(); if (widget->init(imageFileName, texType)) @@ -89,7 +89,7 @@ bool ImageView::init() return ret; } -bool ImageView::init(std::string_view imageFileName, TextureResType texType) +bool ImageView::init(const std::string& imageFileName, TextureResType texType) { bool bRet = true; do @@ -113,7 +113,7 @@ void ImageView::initRenderer() addProtectedChild(_imageRenderer, IMAGE_RENDERER_Z, -1); } -void ImageView::loadTexture(std::string_view fileName, TextureResType texType) +void ImageView::loadTexture(const std::string& fileName, TextureResType texType) { if (fileName.empty()) { diff --git a/cocos/ui/UIImageView.h b/cocos/ui/UIImageView.h index 5fbb2cbde5..525cdd2195 100644 --- a/cocos/ui/UIImageView.h +++ b/cocos/ui/UIImageView.h @@ -75,7 +75,7 @@ public: * @param texType @see `Widget::TextureResType` * @return A ImageView instance. */ - static ImageView* create(std::string_view imageFileName, TextureResType texType = TextureResType::LOCAL); + static ImageView* create(const std::string& imageFileName, TextureResType texType = TextureResType::LOCAL); /** * Load texture for imageview. @@ -83,7 +83,7 @@ public: * @param fileName file name of texture. * @param texType @see `Widget::TextureResType` */ - void loadTexture(std::string_view fileName, TextureResType texType = TextureResType::LOCAL); + void loadTexture(const std::string& fileName, TextureResType texType = TextureResType::LOCAL); /** * Updates the texture rect of the ImageView in points. @@ -150,7 +150,7 @@ public: // initializes state of widget. virtual bool init() override; - virtual bool init(std::string_view imageFileName, TextureResType texType = TextureResType::LOCAL); + virtual bool init(const std::string& imageFileName, TextureResType texType = TextureResType::LOCAL); protected: virtual void initRenderer() override; diff --git a/cocos/ui/UILayout.cpp b/cocos/ui/UILayout.cpp index a8444a5d64..d3c914d1eb 100644 --- a/cocos/ui/UILayout.cpp +++ b/cocos/ui/UILayout.cpp @@ -166,7 +166,7 @@ void Layout::addChild(Node* child, int zOrder, int tag) _doLayoutDirty = true; } -void Layout::addChild(Node* child, int zOrder, std::string_view name) +void Layout::addChild(Node* child, int zOrder, const std::string& name) { if (dynamic_cast(child)) { @@ -566,7 +566,7 @@ bool Layout::isBackGroundImageScale9Enabled() const return _backGroundScale9Enabled; } -void Layout::setBackGroundImage(std::string_view fileName, TextureResType texType) +void Layout::setBackGroundImage(const std::string& fileName, TextureResType texType) { if (fileName.empty()) { diff --git a/cocos/ui/UILayout.h b/cocos/ui/UILayout.h index d1dba4fbce..33c8903a3d 100644 --- a/cocos/ui/UILayout.h +++ b/cocos/ui/UILayout.h @@ -171,7 +171,7 @@ public: * @param fileName image file path. * @param texType @see TextureResType. */ - void setBackGroundImage(std::string_view fileName, TextureResType texType = TextureResType::LOCAL); + void setBackGroundImage(const std::string& fileName, TextureResType texType = TextureResType::LOCAL); /** * Sets a background image capinsets for layout, it only affects the scale9 enabled background image @@ -371,7 +371,7 @@ public: * @param tag A integer to identify the node easily. Please refer to setTag(int) */ virtual void addChild(Node* child, int localZOrder, int tag) override; - virtual void addChild(Node* child, int localZOrder, std::string_view name) override; + virtual void addChild(Node* child, int localZOrder, const std::string& name) override; virtual void visit(Renderer* renderer, const Mat4& parentTransform, uint32_t parentFlags) override; diff --git a/cocos/ui/UILayoutManager.cpp b/cocos/ui/UILayoutManager.cpp index 7213065df7..6c40796bae 100644 --- a/cocos/ui/UILayoutManager.cpp +++ b/cocos/ui/UILayoutManager.cpp @@ -236,7 +236,7 @@ Widget* RelativeLayoutManager::getRelativeWidget(Widget* widget) { Widget* relativeWidget = nullptr; RelativeLayoutParameter* layoutParameter = dynamic_cast(widget->getLayoutParameter()); - auto relativeName = layoutParameter->getRelativeToWidgetName(); + const std::string relativeName = layoutParameter->getRelativeToWidgetName(); if (!relativeName.empty()) { diff --git a/cocos/ui/UILayoutParameter.cpp b/cocos/ui/UILayoutParameter.cpp index d80d751a16..0bf409a4dc 100644 --- a/cocos/ui/UILayoutParameter.cpp +++ b/cocos/ui/UILayoutParameter.cpp @@ -146,22 +146,22 @@ RelativeLayoutParameter::RelativeAlign RelativeLayoutParameter::getAlign() const return _relativeAlign; } -void RelativeLayoutParameter::setRelativeToWidgetName(std::string_view name) +void RelativeLayoutParameter::setRelativeToWidgetName(const std::string& name) { _relativeWidgetName = name; } -std::string_view RelativeLayoutParameter::getRelativeToWidgetName() const +const std::string& RelativeLayoutParameter::getRelativeToWidgetName() const { return _relativeWidgetName; } -void RelativeLayoutParameter::setRelativeName(std::string_view name) +void RelativeLayoutParameter::setRelativeName(const std::string& name) { _relativeLayoutName = name; } -std::string_view RelativeLayoutParameter::getRelativeName() const +const std::string& RelativeLayoutParameter::getRelativeName() const { return _relativeLayoutName; } diff --git a/cocos/ui/UILayoutParameter.h b/cocos/ui/UILayoutParameter.h index 9e6b92a5d8..1a2615da8f 100644 --- a/cocos/ui/UILayoutParameter.h +++ b/cocos/ui/UILayoutParameter.h @@ -363,27 +363,27 @@ public: * * @param name Relative widget name. */ - void setRelativeToWidgetName(std::string_view name); + void setRelativeToWidgetName(const std::string& name); /** * Get the relative widget name. * @return name A relative widget name in string. */ - std::string_view getRelativeToWidgetName() const; + const std::string& getRelativeToWidgetName() const; /** * Set a name for LayoutParameter in Relative Layout. * * @param name A string name. */ - void setRelativeName(std::string_view name); + void setRelativeName(const std::string& name); /** * Get a name of LayoutParameter in Relative Layout. * * @return name Relative name in string. */ - std::string_view getRelativeName() const; + const std::string& getRelativeName() const; // override functions. virtual LayoutParameter* createCloneInstance() override; diff --git a/cocos/ui/UIListView.cpp b/cocos/ui/UIListView.cpp index 68b62f2c17..32616f2bb5 100644 --- a/cocos/ui/UIListView.cpp +++ b/cocos/ui/UIListView.cpp @@ -292,7 +292,7 @@ void ListView::addChild(cocos2d::Node* child, int zOrder) ListView::addChild(child, zOrder, child->getName()); } -void ListView::addChild(Node* child, int zOrder, std::string_view name) +void ListView::addChild(Node* child, int zOrder, const std::string& name) { ScrollView::addChild(child, zOrder, name); diff --git a/cocos/ui/UIListView.h b/cocos/ui/UIListView.h index 2b961b2a9b..b1b54b8e56 100644 --- a/cocos/ui/UIListView.h +++ b/cocos/ui/UIListView.h @@ -309,7 +309,7 @@ public: virtual void addChild(Node* child) override; virtual void addChild(Node* child, int localZOrder) override; virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, std::string_view name) override; + virtual void addChild(Node* child, int zOrder, const std::string& name) override; virtual void removeAllChildren() override; virtual void removeAllChildrenWithCleanup(bool cleanup) override; virtual void removeChild(Node* child, bool cleanup = true) override; diff --git a/cocos/ui/UILoadingBar.cpp b/cocos/ui/UILoadingBar.cpp index b3518941ce..e1a9e518df 100644 --- a/cocos/ui/UILoadingBar.cpp +++ b/cocos/ui/UILoadingBar.cpp @@ -71,12 +71,12 @@ LoadingBar* LoadingBar::create() return nullptr; } -LoadingBar* LoadingBar::create(std::string_view textureName, float percentage) +LoadingBar* LoadingBar::create(const std::string& textureName, float percentage) { return LoadingBar::create(textureName, TextureResType::LOCAL, percentage); } -LoadingBar* LoadingBar::create(std::string_view textureName, TextureResType texType, float percentage) +LoadingBar* LoadingBar::create(const std::string& textureName, TextureResType texType, float percentage) { LoadingBar* widget = new LoadingBar; if (widget->init()) @@ -125,7 +125,7 @@ LoadingBar::Direction LoadingBar::getDirection() const return _direction; } -void LoadingBar::loadTexture(std::string_view texture, TextureResType texType) +void LoadingBar::loadTexture(const std::string& texture, TextureResType texType) { if (texture.empty()) { diff --git a/cocos/ui/UILoadingBar.h b/cocos/ui/UILoadingBar.h index 6206bf32f1..b83b298db6 100644 --- a/cocos/ui/UILoadingBar.h +++ b/cocos/ui/UILoadingBar.h @@ -88,7 +88,7 @@ public: * @param percentage A percentage in float. * @return A LoadingBar instance. */ - static LoadingBar* create(std::string_view textureName, float percentage = 0); + static LoadingBar* create(const std::string& textureName, float percentage = 0); /** * @brief Create a LoadingBar with a texture name along with its texture type and a predefined progress value. @@ -98,7 +98,7 @@ public: * @param percentage A percentage in float, default value is 0. * @return A LoadingBar instance. */ - static LoadingBar* create(std::string_view textureName, TextureResType texType, float percentage = 0); + static LoadingBar* create(const std::string& textureName, TextureResType texType, float percentage = 0); /** * Change the progress direction of LoadingBar. @@ -122,7 +122,7 @@ public: * @param texture File name of texture. * @param texType Texture resource type,@see TextureResType. */ - void loadTexture(std::string_view texture, TextureResType texType = TextureResType::LOCAL); + void loadTexture(const std::string& texture, TextureResType texType = TextureResType::LOCAL); /** * Changes the progress value of LoadingBar. diff --git a/cocos/ui/UIPageView.cpp b/cocos/ui/UIPageView.cpp index b92f56a7b6..06a56f3258 100644 --- a/cocos/ui/UIPageView.cpp +++ b/cocos/ui/UIPageView.cpp @@ -465,7 +465,7 @@ float PageView::getIndicatorIndexNodesScale() const return _indicator->getIndexNodesScale(); } -void PageView::setIndicatorIndexNodesTexture(std::string_view texName, Widget::TextureResType texType) +void PageView::setIndicatorIndexNodesTexture(const std::string& texName, Widget::TextureResType texType) { if (_indicator != nullptr) { diff --git a/cocos/ui/UIPageView.h b/cocos/ui/UIPageView.h index 6325e9561c..97d8320ddf 100644 --- a/cocos/ui/UIPageView.h +++ b/cocos/ui/UIPageView.h @@ -314,7 +314,7 @@ public: * @param fileName File name of texture. * @param resType @see TextureResType . */ - void setIndicatorIndexNodesTexture(std::string_view texName, + void setIndicatorIndexNodesTexture(const std::string& texName, Widget::TextureResType texType = Widget::TextureResType::LOCAL); /** diff --git a/cocos/ui/UIPageViewIndicator.cpp b/cocos/ui/UIPageViewIndicator.cpp index 94590ced01..530df5a82c 100644 --- a/cocos/ui/UIPageViewIndicator.cpp +++ b/cocos/ui/UIPageViewIndicator.cpp @@ -195,7 +195,7 @@ void PageViewIndicator::setIndexNodesScale(float indexNodesScale) rearrange(); } -void PageViewIndicator::setIndexNodesTexture(std::string_view texName, Widget::TextureResType texType) +void PageViewIndicator::setIndexNodesTexture(const std::string& texName, Widget::TextureResType texType) { _useDefaultTexture = false; _indexNodesTextureFile = texName; diff --git a/cocos/ui/UIPageViewIndicator.h b/cocos/ui/UIPageViewIndicator.h index 21c0360b04..d498c4cdfd 100644 --- a/cocos/ui/UIPageViewIndicator.h +++ b/cocos/ui/UIPageViewIndicator.h @@ -74,7 +74,8 @@ public: * @param fileName File name of texture. * @param resType @see TextureResType . */ - void setIndexNodesTexture(std::string_view texName, Widget::TextureResType texType = Widget::TextureResType::LOCAL); + void setIndexNodesTexture(const std::string& texName, + Widget::TextureResType texType = Widget::TextureResType::LOCAL); protected: bool init() override; diff --git a/cocos/ui/UIRadioButton.cpp b/cocos/ui/UIRadioButton.cpp index ff1ad49f1d..14d9e639d9 100644 --- a/cocos/ui/UIRadioButton.cpp +++ b/cocos/ui/UIRadioButton.cpp @@ -52,11 +52,11 @@ RadioButton* RadioButton::create() return nullptr; } -RadioButton* RadioButton::create(std::string_view backGround, - std::string_view backGroundSelected, - std::string_view cross, - std::string_view backGroundDisabled, - std::string_view frontCrossDisabled, +RadioButton* RadioButton::create(const std::string& backGround, + const std::string& backGroundSelected, + const std::string& cross, + const std::string& backGroundDisabled, + const std::string& frontCrossDisabled, TextureResType texType) { RadioButton* pWidget = new RadioButton(); @@ -69,7 +69,7 @@ RadioButton* RadioButton::create(std::string_view backGround, return nullptr; } -RadioButton* RadioButton::create(std::string_view backGround, std::string_view cross, TextureResType texType) +RadioButton* RadioButton::create(const std::string& backGround, const std::string& cross, TextureResType texType) { RadioButton* pWidget = new RadioButton(); if (pWidget->init(backGround, "", cross, "", "", texType)) diff --git a/cocos/ui/UIRadioButton.h b/cocos/ui/UIRadioButton.h index 43deb3b92e..9adb3c8357 100644 --- a/cocos/ui/UIRadioButton.h +++ b/cocos/ui/UIRadioButton.h @@ -98,11 +98,11 @@ public: * * @return A RadioButton instance pointer. */ - static RadioButton* create(std::string_view backGround, - std::string_view backGroundSelected, - std::string_view cross, - std::string_view backGroundDisabled, - std::string_view frontCrossDisabled, + static RadioButton* create(const std::string& backGround, + const std::string& backGroundSelected, + const std::string& cross, + const std::string& backGroundDisabled, + const std::string& frontCrossDisabled, TextureResType texType = TextureResType::LOCAL); /** @@ -113,8 +113,8 @@ public: * @param texType The texture's resource type in `Widget::TextureResType`. * @return A RadioButton instance pointer */ - static RadioButton* create(std::string_view backGround, - std::string_view cross, + static RadioButton* create(const std::string& backGround, + const std::string& cross, TextureResType texType = TextureResType::LOCAL); /** diff --git a/cocos/ui/UIRichText.cpp b/cocos/ui/UIRichText.cpp index a65700cc4e..e46456085b 100644 --- a/cocos/ui/UIRichText.cpp +++ b/cocos/ui/UIRichText.cpp @@ -1,9 +1,8 @@ /**************************************************************************** Copyright (c) 2013 cocos2d-x.org Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - Copyright (c) 2021 Bytedance Inc. - https://adxeproject.github.io + 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 @@ -52,7 +51,7 @@ public: static const std::string COMPONENT_NAME; /*!< component name */ static ListenerComponent* create(Node* parent, - std::string_view url, + const std::string& url, const RichText::OpenUrlHandler handleOpenUrl = nullptr) { auto component = new ListenerComponent(parent, url, std::move(handleOpenUrl)); @@ -60,7 +59,7 @@ public: return component; } - explicit ListenerComponent(Node* parent, std::string_view url, const RichText::OpenUrlHandler handleOpenUrl) + explicit ListenerComponent(Node* parent, const std::string& url, const RichText::OpenUrlHandler handleOpenUrl) : _parent(parent), _url(url), _handleOpenUrl(std::move(handleOpenUrl)) { setName(ListenerComponent::COMPONENT_NAME); @@ -125,11 +124,11 @@ void RichElement::setColor(const Color3B& color) RichElementText* RichElementText::create(int tag, const Color3B& color, uint8_t opacity, - std::string_view text, - std::string_view fontName, + const std::string& text, + const std::string& fontName, float fontSize, uint32_t flags, - std::string_view url, + const std::string& url, const Color3B& outlineColor, int outlineSize, const Color3B& shadowColor, @@ -151,11 +150,11 @@ RichElementText* RichElementText::create(int tag, bool RichElementText::init(int tag, const Color3B& color, uint8_t opacity, - std::string_view text, - std::string_view fontName, + const std::string& text, + const std::string& fontName, float fontSize, uint32_t flags, - std::string_view url, + const std::string& url, const Color3B& outlineColor, int outlineSize, const Color3B& shadowColor, @@ -184,8 +183,8 @@ bool RichElementText::init(int tag, RichElementImage* RichElementImage::create(int tag, const Color3B& color, uint8_t opacity, - std::string_view filePath, - std::string_view url, + const std::string& filePath, + const std::string& url, Widget::TextureResType texType) { RichElementImage* element = new RichElementImage(); @@ -201,8 +200,8 @@ RichElementImage* RichElementImage::create(int tag, bool RichElementImage::init(int tag, const Color3B& color, uint8_t opacity, - std::string_view filePath, - std::string_view url, + const std::string& filePath, + const std::string& url, Widget::TextureResType texType) { if (RichElement::init(tag, color, opacity)) @@ -227,7 +226,7 @@ void RichElementImage::setHeight(int height) _height = height; } -void RichElementImage::setUrl(std::string_view url) +void RichElementImage::setUrl(const std::string& url) { _url = url; } @@ -335,7 +334,7 @@ private: bool isFontElement; RichText::VisitEnterHandler handleVisitEnter; }; - typedef hlookup::string_map TagTables; + typedef std::unordered_map TagTables; static TagTables _tagTables; @@ -377,11 +376,11 @@ public: void pushBackElement(RichElement* element); - static void setTagDescription(std::string_view tag, + static void setTagDescription(const std::string& tag, bool isFontElement, RichText::VisitEnterHandler&& handleVisitEnter); - static void removeTagDescription(std::string_view tag); + static void removeTagDescription(const std::string& tag); private: ValueMap tagAttrMapWithXMLElement(const char** attrs); @@ -908,19 +907,14 @@ void MyXMLVisitor::pushBackElement(RichElement* element) _richText->pushBackElement(element); } -void MyXMLVisitor::setTagDescription(std::string_view tag, +void MyXMLVisitor::setTagDescription(const std::string& tag, bool isFontElement, RichText::VisitEnterHandler&& handleVisitEnter) { - hlookup::set_item( - MyXMLVisitor::_tagTables, tag, - TagBehavior{ - isFontElement, - std::move( - handleVisitEnter)}); // MyXMLVisitor::_tagTables[tag] = {isFontElement, std::move(handleVisitEnter)}; + MyXMLVisitor::_tagTables[tag] = {isFontElement, std::move(handleVisitEnter)}; } -void MyXMLVisitor::removeTagDescription(std::string_view tag) +void MyXMLVisitor::removeTagDescription(const std::string& tag) { MyXMLVisitor::_tagTables.erase(tag); } @@ -1010,7 +1004,7 @@ RichText* RichText::create() return nullptr; } -RichText* RichText::createWithXML(std::string_view xml, const ValueMap& defaults, const OpenUrlHandler& handleOpenUrl) +RichText* RichText::createWithXML(const std::string& xml, const ValueMap& defaults, const OpenUrlHandler& handleOpenUrl) { RichText* widget = new RichText(); if (widget->initWithXML(xml, defaults, handleOpenUrl)) @@ -1031,7 +1025,7 @@ bool RichText::init() return false; } -bool RichText::initWithXML(std::string_view origxml, const ValueMap& defaults, const OpenUrlHandler& handleOpenUrl) +bool RichText::initWithXML(const std::string& origxml, const ValueMap& defaults, const OpenUrlHandler& handleOpenUrl) { static std::function startTagFont = [](RichText* richText) { std::string fontFace = richText->getFontFace(); @@ -1115,7 +1109,7 @@ void RichText::setHorizontalAlignment(cocos2d::ui::RichText::HorizontalAlignment } } -void RichText::setFontColor(std::string_view color) +void RichText::setFontColor(const std::string& color) { _defaults[KEY_FONT_COLOR_STRING] = color; } @@ -1140,7 +1134,7 @@ float RichText::getFontSize() return _defaults.at(KEY_FONT_SIZE).asFloat(); } -void RichText::setFontFace(std::string_view face) +void RichText::setFontFace(const std::string& face) { _defaults[KEY_FONT_FACE] = face; } @@ -1150,7 +1144,7 @@ std::string RichText::getFontFace() return _defaults.at(KEY_FONT_FACE).asString(); } -void RichText::setAnchorFontColor(std::string_view color) +void RichText::setAnchorFontColor(const std::string& color) { _defaults[KEY_ANCHOR_FONT_COLOR_STRING] = color; } @@ -1399,12 +1393,12 @@ ValueMap RichText::getDefaults() const return defaults; } -cocos2d::Color3B RichText::color3BWithString(std::string_view color) +cocos2d::Color3B RichText::color3BWithString(const std::string& color) { if (color.length() == 4) { - unsigned int r, g, b; - sscanf(color.data(), "%*c%1x%1x%1x", &r, &g, &b); + int r, g, b; + sscanf(color.c_str(), "%*c%1x%1x%1x", &r, &g, &b); r += r * 16; g += g * 16; b += b * 16; @@ -1412,14 +1406,14 @@ cocos2d::Color3B RichText::color3BWithString(std::string_view color) } else if (color.length() == 7) { - unsigned int r, g, b; - sscanf(color.data(), "%*c%2x%2x%2x", &r, &g, &b); + int r, g, b; + sscanf(color.c_str(), "%*c%2x%2x%2x", &r, &g, &b); return Color3B(r, g, b); } else if (color.length() == 9) { - unsigned int r, g, b, a; - sscanf(color.data(), "%*c%2x%2x%2x%2x", &r, &g, &b, &a); + int r, g, b, a; + sscanf(color.c_str(), "%*c%2x%2x%2x%2x", &r, &g, &b, &a); return Color3B(r, g, b); } return Color3B::WHITE; @@ -1446,17 +1440,17 @@ std::string RichText::stringWithColor4B(const cocos2d::Color4B& color4b) return std::string(buf, 9); } -void RichText::setTagDescription(std::string_view tag, bool isFontElement, VisitEnterHandler handleVisitEnter) +void RichText::setTagDescription(const std::string& tag, bool isFontElement, VisitEnterHandler handleVisitEnter) { MyXMLVisitor::setTagDescription(tag, isFontElement, std::move(handleVisitEnter)); } -void RichText::removeTagDescription(std::string_view tag) +void RichText::removeTagDescription(const std::string& tag) { MyXMLVisitor::removeTagDescription(tag); } -void RichText::openUrl(std::string_view url) +void RichText::openUrl(const std::string& url) { if (_handleOpenUrl) { @@ -1773,13 +1767,13 @@ int findSplitPositionForChar(Label* label, } } // namespace -void RichText::handleTextRenderer(std::string_view text, - std::string_view fontName, +void RichText::handleTextRenderer(const std::string& text, + const std::string& fontName, float fontSize, const Color3B& color, uint8_t opacity, uint32_t flags, - std::string_view url, + const std::string& url, const Color3B& outlineColor, int outlineSize, const Color3B& shadowColor, @@ -1791,8 +1785,7 @@ void RichText::handleTextRenderer(std::string_view text, RichText::WrapMode wrapMode = static_cast(_defaults.at(KEY_WRAP_MODE).asInt()); // split text by \n - std::stringstream ss; - ss << text; + std::stringstream ss(text); std::string currentText; size_t realLines = 0; while (std::getline(ss, currentText, '\n')) @@ -1884,13 +1877,13 @@ void RichText::handleTextRenderer(std::string_view text, } } -void RichText::handleImageRenderer(std::string_view filePath, +void RichText::handleImageRenderer(const std::string& filePath, Widget::TextureResType textureType, const Color3B& /*color*/, uint8_t /*opacity*/, int width, int height, - std::string_view url) + const std::string& url) { Sprite* imageRenderer; if (textureType == Widget::TextureResType::LOCAL) @@ -2069,9 +2062,10 @@ bool isWhitespace(char c) { return std::isspace(c, std::locale()); } -void rtrim(std::string& s) +std::string rtrim(std::string s) { s.erase(std::find_if_not(s.rbegin(), s.rend(), isWhitespace).base(), s.end()); + return s; } } // namespace @@ -2081,9 +2075,8 @@ float RichText::stripTrailingWhitespace(const Vector& row) { if (auto label = dynamic_cast(row.back())) { - const auto width = label->getContentSize().width; - std::string trimmedString{label->getString()}; - rtrim(trimmedString); + const auto width = label->getContentSize().width; + const auto trimmedString = rtrim(label->getString()); if (label->getString() != trimmedString) { label->setString(trimmedString); diff --git a/cocos/ui/UIRichText.h b/cocos/ui/UIRichText.h index 7428a38bc1..4c694c8af9 100644 --- a/cocos/ui/UIRichText.h +++ b/cocos/ui/UIRichText.h @@ -148,11 +148,11 @@ public: bool init(int tag, const Color3B& color, uint8_t opacity, - std::string_view text, - std::string_view fontName, + const std::string& text, + const std::string& fontName, float fontSize, uint32_t flags, - std::string_view url, + const std::string& url, const Color3B& outlineColor = Color3B::WHITE, int outlineSize = -1, const Color3B& shadowColor = Color3B::BLACK, @@ -182,11 +182,11 @@ public: static RichElementText* create(int tag, const Color3B& color, uint8_t opacity, - std::string_view text, - std::string_view fontName, + const std::string& text, + const std::string& fontName, float fontSize, uint32_t flags = 0, - std::string_view url = "", + const std::string& url = "", const Color3B& outlineColor = Color3B::WHITE, int outlineSize = -1, const Color3B& shadowColor = Color3B::BLACK, @@ -244,8 +244,8 @@ public: bool init(int tag, const Color3B& color, uint8_t opacity, - std::string_view filePath, - std::string_view url = "", + const std::string& filePath, + const std::string& url = "", Widget::TextureResType texType = Widget::TextureResType::LOCAL); /** @@ -262,13 +262,13 @@ public: static RichElementImage* create(int tag, const Color3B& color, uint8_t opacity, - std::string_view filePath, - std::string_view url = "", + const std::string& filePath, + const std::string& url = "", Widget::TextureResType texType = Widget::TextureResType::LOCAL); void setWidth(int width); void setHeight(int height); - void setUrl(std::string_view url); + void setUrl(const std::string& url); protected: std::string _filePath; @@ -386,7 +386,7 @@ public: * @brief call to open a resource specified by a URL * @param url a URL */ - typedef std::function OpenUrlHandler; + typedef std::function OpenUrlHandler; /** * @brief called on the specified tag @@ -461,7 +461,7 @@ public: * * @return RichText instance. */ - static RichText* createWithXML(std::string_view xml, + static RichText* createWithXML(const std::string& xml, const ValueMap& defaults = ValueMap(), const OpenUrlHandler& handleOpenUrl = nullptr); @@ -517,24 +517,24 @@ public: HorizontalAlignment a); /*!< sets the horizontal alignment mode: LEFT, CENTER, or RIGHT */ HorizontalAlignment getHorizontalAlignment() const; /*!< returns the current horizontal alignment mode */ void setFontColor( - std::string_view color); /*!< Set the font color. @param color the #RRGGBB hexadecimal notation. */ - std::string getFontColor(); /*!< return the current font color */ - Color3B getFontColor3B(); /*!< return the current font color */ - void setFontSize(float size); /*!< Set the font size. @param size the font size. */ - float getFontSize(); /*!< return the current font size */ - void setFontFace(std::string_view face); /*!< Set the font face. @param face the font face. */ - std::string getFontFace(); /*!< return the current font face */ - void setAnchorFontColor(std::string_view color); /*!< Set the font color of a-tag. @param face the font color. */ - std::string getAnchorFontColor(); /*!< return the current font color of a-tag */ - cocos2d::Color3B getAnchorFontColor3B(); /*!< return the current font color of a-tag */ - void setAnchorTextBold(bool enable); /*!< enable bold text of a-tag */ - bool isAnchorTextBoldEnabled(); /*!< valid style is bold text of a-tag? */ - void setAnchorTextItalic(bool enable); /*!< enable italic text of a-tag */ - bool isAnchorTextItalicEnabled(); /*!< valid style is italic text of a-tag? */ - void setAnchorTextDel(bool enable); /*!< enable the strikethrough of a-tag */ - bool isAnchorTextDelEnabled(); /*!< valid strikethrough of a-tag? */ - void setAnchorTextUnderline(bool enable); /*!< enable the underline of a-tag */ - bool isAnchorTextUnderlineEnabled(); /*!< valid underline of a-tag? */ + const std::string& color); /*!< Set the font color. @param color the #RRGGBB hexadecimal notation. */ + std::string getFontColor(); /*!< return the current font color */ + Color3B getFontColor3B(); /*!< return the current font color */ + void setFontSize(float size); /*!< Set the font size. @param size the font size. */ + float getFontSize(); /*!< return the current font size */ + void setFontFace(const std::string& face); /*!< Set the font face. @param face the font face. */ + std::string getFontFace(); /*!< return the current font face */ + void setAnchorFontColor(const std::string& color); /*!< Set the font color of a-tag. @param face the font color. */ + std::string getAnchorFontColor(); /*!< return the current font color of a-tag */ + cocos2d::Color3B getAnchorFontColor3B(); /*!< return the current font color of a-tag */ + void setAnchorTextBold(bool enable); /*!< enable bold text of a-tag */ + bool isAnchorTextBoldEnabled(); /*!< valid style is bold text of a-tag? */ + void setAnchorTextItalic(bool enable); /*!< enable italic text of a-tag */ + bool isAnchorTextItalicEnabled(); /*!< valid style is italic text of a-tag? */ + void setAnchorTextDel(bool enable); /*!< enable the strikethrough of a-tag */ + bool isAnchorTextDelEnabled(); /*!< valid strikethrough of a-tag? */ + void setAnchorTextUnderline(bool enable); /*!< enable the underline of a-tag */ + bool isAnchorTextUnderlineEnabled(); /*!< valid underline of a-tag? */ /** @brief enable the outline of a-tag */ void setAnchorTextOutline(bool enable, const Color3B& outlineColor = Color3B::WHITE, int outlineSize = -1); bool isAnchorTextOutlineEnabled(); /*!< valid outline of a-tag? */ @@ -555,7 +555,7 @@ public: void setDefaults(const ValueMap& defaults); /*!< set the default values */ ValueMap getDefaults() const; /*!< returns the default values */ - cocos2d::Color3B color3BWithString(std::string_view color); /*!< convert a color string into a Color3B. */ + cocos2d::Color3B color3BWithString(const std::string& color); /*!< convert a color string into a Color3B. */ std::string stringWithColor3B(const cocos2d::Color3B& color3b); /*!< convert a Color3B into a color string. */ std::string stringWithColor4B(const cocos2d::Color4B& color4b); /*!< convert a Color4B into a color string. */ @@ -565,15 +565,15 @@ public: * @param isFontElement use attributes of text tag * @param handleVisitEnter callback */ - static void setTagDescription(std::string_view tag, bool isFontElement, VisitEnterHandler handleVisitEnter); + static void setTagDescription(const std::string& tag, bool isFontElement, VisitEnterHandler handleVisitEnter); /** * @brief remove a callback to own tag. * @param tag tag's name */ - static void removeTagDescription(std::string_view tag); + static void removeTagDescription(const std::string& tag); - void openUrl(std::string_view url); + void openUrl(const std::string& url); /** * @brief Asks the callback to open a resource specified by a URL. @@ -584,7 +584,7 @@ public: CC_CONSTRUCTOR_ACCESS : virtual bool init() override; - bool initWithXML(std::string_view xml, + bool initWithXML(const std::string& xml, const ValueMap& defaults = ValueMap(), const OpenUrlHandler& handleOpenUrl = nullptr); @@ -593,26 +593,26 @@ protected: virtual void initRenderer() override; void pushToContainer(Node* renderer); - void handleTextRenderer(std::string_view text, - std::string_view fontName, + void handleTextRenderer(const std::string& text, + const std::string& fontName, float fontSize, const Color3B& color, uint8_t opacity, uint32_t flags, - std::string_view url = "", + const std::string& url = "", const Color3B& outlineColor = Color3B::WHITE, int outlineSize = -1, const Color3B& shadowColor = Color3B::BLACK, const Vec2& shadowOffset = Vec2(2.0, -2.0), int shadowBlurRadius = 0, const Color3B& glowColor = Color3B::WHITE); - void handleImageRenderer(std::string_view filePath, + void handleImageRenderer(const std::string& filePath, Widget::TextureResType textureType, const Color3B& color, uint8_t opacity, int width, int height, - std::string_view url); + const std::string& url); void handleCustomRenderer(Node* renderer); void formatRenderers(); void addNewLine(); diff --git a/cocos/ui/UIScale9Sprite.cpp b/cocos/ui/UIScale9Sprite.cpp index eedb3152d4..dba22480e4 100644 --- a/cocos/ui/UIScale9Sprite.cpp +++ b/cocos/ui/UIScale9Sprite.cpp @@ -53,7 +53,7 @@ Scale9Sprite* Scale9Sprite::create() return nullptr; } -Scale9Sprite* Scale9Sprite::create(std::string_view filename, const Rect& rect, const Rect& capInsets) +Scale9Sprite* Scale9Sprite::create(const std::string& filename, const Rect& rect, const Rect& capInsets) { Scale9Sprite* ret = new Scale9Sprite(); if (ret->initWithFile(filename, rect, capInsets)) @@ -65,12 +65,12 @@ Scale9Sprite* Scale9Sprite::create(std::string_view filename, const Rect& rect, return nullptr; } -Scale9Sprite* Scale9Sprite::create(std::string_view filename, const Rect& rect) +Scale9Sprite* Scale9Sprite::create(const std::string& filename, const Rect& rect) { return create(filename, rect, Rect::ZERO); } -Scale9Sprite* Scale9Sprite::create(const Rect& capInsets, std::string_view file) +Scale9Sprite* Scale9Sprite::create(const Rect& capInsets, const std::string& file) { Scale9Sprite* ret = new Scale9Sprite(); if (ret->initWithFile(capInsets, file)) @@ -82,7 +82,7 @@ Scale9Sprite* Scale9Sprite::create(const Rect& capInsets, std::string_view file) return nullptr; } -Scale9Sprite* Scale9Sprite::create(std::string_view fileaname) +Scale9Sprite* Scale9Sprite::create(const std::string& fileaname) { return create(Rect::ZERO, fileaname); } @@ -104,7 +104,7 @@ Scale9Sprite* Scale9Sprite::createWithSpriteFrame(SpriteFrame* spriteFrame) return createWithSpriteFrame(spriteFrame, Rect::ZERO); } -Scale9Sprite* Scale9Sprite::createWithSpriteFrameName(std::string_view spriteFrameName, const Rect& capInsets) +Scale9Sprite* Scale9Sprite::createWithSpriteFrameName(const std::string& spriteFrameName, const Rect& capInsets) { Scale9Sprite* ret = new Scale9Sprite(); if (ret->initWithSpriteFrameName(spriteFrameName, capInsets)) @@ -116,7 +116,7 @@ Scale9Sprite* Scale9Sprite::createWithSpriteFrameName(std::string_view spriteFra return nullptr; } -Scale9Sprite* Scale9Sprite::createWithSpriteFrameName(std::string_view spriteFrameName) +Scale9Sprite* Scale9Sprite::createWithSpriteFrameName(const std::string& spriteFrameName) { Scale9Sprite* ret = new Scale9Sprite(); if (ret->initWithSpriteFrameName(spriteFrameName, Rect::ZERO)) @@ -142,7 +142,7 @@ Scale9Sprite::Scale9Sprite() Scale9Sprite::~Scale9Sprite() {} -bool Scale9Sprite::initWithFile(const Rect& capInsets, std::string_view file) +bool Scale9Sprite::initWithFile(const Rect& capInsets, const std::string& file) { // calls super bool ret = Sprite::initWithFile(file); @@ -150,7 +150,7 @@ bool Scale9Sprite::initWithFile(const Rect& capInsets, std::string_view file) return ret; } -bool Scale9Sprite::initWithFile(std::string_view filename) +bool Scale9Sprite::initWithFile(const std::string& filename) { // calls super auto originalCapInsets = this->getCapInsets(); @@ -159,7 +159,7 @@ bool Scale9Sprite::initWithFile(std::string_view filename) return ret; } -bool Scale9Sprite::initWithFile(std::string_view filename, const Rect& rect) +bool Scale9Sprite::initWithFile(const std::string& filename, const Rect& rect) { // calls super auto originalCapInsets = this->getCapInsets(); @@ -176,7 +176,7 @@ bool Scale9Sprite::initWithSpriteFrame(SpriteFrame* spriteFrame, const Rect& cap return ret; } -bool Scale9Sprite::initWithSpriteFrameName(std::string_view spriteFrameName, const Rect& capInsets) +bool Scale9Sprite::initWithSpriteFrameName(const std::string& spriteFrameName, const Rect& capInsets) { // calls super bool ret = Sprite::initWithSpriteFrameName(spriteFrameName); @@ -184,7 +184,7 @@ bool Scale9Sprite::initWithSpriteFrameName(std::string_view spriteFrameName, con return ret; } -bool Scale9Sprite::initWithSpriteFrameName(std::string_view spriteFrameName) +bool Scale9Sprite::initWithSpriteFrameName(const std::string& spriteFrameName) { // calls super auto originalCapInsets = this->getCapInsets(); @@ -242,7 +242,7 @@ bool Scale9Sprite::init(Sprite* sprite, return ret; } -bool Scale9Sprite::initWithFile(std::string_view filename, const Rect& rect, const Rect& capInsets) +bool Scale9Sprite::initWithFile(const std::string& filename, const Rect& rect, const Rect& capInsets) { // calls super bool ret = false; diff --git a/cocos/ui/UIScale9Sprite.h b/cocos/ui/UIScale9Sprite.h index 3e11d0743c..94c4226d58 100644 --- a/cocos/ui/UIScale9Sprite.h +++ b/cocos/ui/UIScale9Sprite.h @@ -108,7 +108,7 @@ public: * @param capInsets A specified cap insets. * @return A Scale9Sprite instance. */ - static Scale9Sprite* create(std::string_view file, const Rect& rect, const Rect& capInsets); + static Scale9Sprite* create(const std::string& file, const Rect& rect, const Rect& capInsets); /** * Creates a 9-slice sprite with a texture file. The whole texture will be @@ -119,7 +119,7 @@ public: * @param file A texture file name. * @return A Scale9Sprite instance. */ - static Scale9Sprite* create(const Rect& capInsets, std::string_view file); + static Scale9Sprite* create(const Rect& capInsets, const std::string& file); /** * Creates a 9-slice sprite with a texture file and a delimitation zone. The @@ -130,7 +130,7 @@ public: * @param rect A delimitation zone. * @return A Scale9Sprite instance. */ - static Scale9Sprite* create(std::string_view file, const Rect& rect); + static Scale9Sprite* create(const std::string& file, const Rect& rect); /** * Creates a 9-slice sprite with a texture file. The whole texture will be @@ -140,7 +140,7 @@ public: * @param file A texture file name. * @return A Scale9Sprite instance. */ - static Scale9Sprite* create(std::string_view file); + static Scale9Sprite* create(const std::string& file); /** * Creates a 9-slice sprite with an sprite frame. @@ -177,7 +177,7 @@ public: * @param spriteFrameName A sprite frame name. * @return A Scale9Sprite instance. */ - static Scale9Sprite* createWithSpriteFrameName(std::string_view spriteFrameName); + static Scale9Sprite* createWithSpriteFrameName(const std::string& spriteFrameName); /** * Creates a 9-slice sprite with an sprite frame name and the centre of its zone. @@ -190,7 +190,7 @@ public: * @param capInsets A delimitation zone. * @return A Scale9Sprite instance. */ - static Scale9Sprite* createWithSpriteFrameName(std::string_view spriteFrameName, const Rect& capInsets); + static Scale9Sprite* createWithSpriteFrameName(const std::string& spriteFrameName, const Rect& capInsets); // overridden methods that takes different parameters using Sprite::initWithFile; @@ -212,7 +212,7 @@ public: * @param capInsets The values to use for the cap insets. * @return True if initialize success, false otherwise. */ - virtual bool initWithFile(std::string_view file, const Rect& rect, const Rect& capInsets); + virtual bool initWithFile(const std::string& file, const Rect& rect, const Rect& capInsets); /** * Initializes a 9-slice sprite with a texture file and with the specified cap @@ -225,7 +225,7 @@ public: * @param capInsets The values to use for the cap insets. * @return True if initializes success, false otherwise. */ - virtual bool initWithFile(const Rect& capInsets, std::string_view file); + virtual bool initWithFile(const Rect& capInsets, const std::string& file); /** * Initializes a 9-slice sprite with an sprite frame and with the specified @@ -251,7 +251,7 @@ public: * @param capInsets The values to use for the cap insets. * @return True if initializes success, false otherwise. */ - virtual bool initWithSpriteFrameName(std::string_view spriteFrameName, const Rect& capInsets); + virtual bool initWithSpriteFrameName(const std::string& spriteFrameName, const Rect& capInsets); // override function @@ -268,7 +268,7 @@ public: * texture's full rect. * @return True if initializes success, false otherwise. */ - virtual bool initWithFile(std::string_view file, const Rect& rect) override; + virtual bool initWithFile(const std::string& file, const Rect& rect) override; /** * Initializes a 9-slice sprite with a texture file. The whole texture will be @@ -280,7 +280,7 @@ public: * @param file The name of the texture file. * @return True if initializes success, false otherwise. */ - virtual bool initWithFile(std::string_view file) override; + virtual bool initWithFile(const std::string& file) override; /** * Initializes a 9-slice sprite with an sprite frame name. @@ -291,7 +291,7 @@ public: * @param spriteFrameName The sprite frame name. * @return True if initializes success, false otherwise. */ - virtual bool initWithSpriteFrameName(std::string_view spriteFrameName) override; + virtual bool initWithSpriteFrameName(const std::string& spriteFrameName) override; virtual bool init() override; diff --git a/cocos/ui/UIScrollView.cpp b/cocos/ui/UIScrollView.cpp index b0df2ffd9e..ae12b010d5 100644 --- a/cocos/ui/UIScrollView.cpp +++ b/cocos/ui/UIScrollView.cpp @@ -287,7 +287,7 @@ void ScrollView::addChild(Node* child, int zOrder, int tag) _innerContainer->addChild(child, zOrder, tag); } -void ScrollView::addChild(Node* child, int zOrder, std::string_view name) +void ScrollView::addChild(Node* child, int zOrder, const std::string& name) { child->setGlobalZOrder(_globalZOrder); _innerContainer->addChild(child, zOrder, name); @@ -328,7 +328,7 @@ Node* ScrollView::getChildByTag(int tag) const return _innerContainer->getChildByTag(tag); } -Node* ScrollView::getChildByName(std::string_view name) const +Node* ScrollView::getChildByName(const std::string& name) const { return _innerContainer->getChildByName(name); } diff --git a/cocos/ui/UIScrollView.h b/cocos/ui/UIScrollView.h index c1cbe9ba8c..96d9949a77 100644 --- a/cocos/ui/UIScrollView.h +++ b/cocos/ui/UIScrollView.h @@ -343,7 +343,7 @@ public: virtual void addChild(Node* child) override; virtual void addChild(Node* child, int localZOrder) override; virtual void addChild(Node* child, int localZOrder, int tag) override; - virtual void addChild(Node* child, int localZOrder, std::string_view name) override; + virtual void addChild(Node* child, int localZOrder, const std::string& name) override; virtual void removeAllChildren() override; virtual void removeAllChildrenWithCleanup(bool cleanup) override; virtual void removeChild(Node* child, bool cleanup = true) override; @@ -351,7 +351,7 @@ public: virtual const Vector& getChildren() const override; virtual ssize_t getChildrenCount() const override; virtual Node* getChildByTag(int tag) const override; - virtual Node* getChildByName(std::string_view name) const override; + virtual Node* getChildByName(const std::string& name) const override; // touch event callback virtual bool onTouchBegan(Touch* touch, Event* unusedEvent) override; virtual void onTouchMoved(Touch* touch, Event* unusedEvent) override; diff --git a/cocos/ui/UISlider.cpp b/cocos/ui/UISlider.cpp index 2baeabcf27..c28cfbbca5 100644 --- a/cocos/ui/UISlider.cpp +++ b/cocos/ui/UISlider.cpp @@ -103,7 +103,9 @@ Slider* Slider::create() return nullptr; } -Slider* Slider::create(std::string_view barTextureName, std::string_view normalBallTextureName, TextureResType resType) +Slider* Slider::create(const std::string& barTextureName, + const std::string& normalBallTextureName, + TextureResType resType) { Slider* widget = new Slider(); if (widget->init()) @@ -155,7 +157,7 @@ void Slider::initRenderer() addProtectedChild(_slidBallRenderer, SLIDBALL_RENDERER_Z, -1); } -void Slider::loadBarTexture(std::string_view fileName, TextureResType texType) +void Slider::loadBarTexture(const std::string& fileName, TextureResType texType) { _textureFile = fileName; _barTexType = texType; @@ -200,7 +202,7 @@ void Slider::setupBarTexture() _originalBarRect = _barRenderer->getTextureRect(); } -void Slider::loadProgressBarTexture(std::string_view fileName, TextureResType texType) +void Slider::loadProgressBarTexture(const std::string& fileName, TextureResType texType) { _progressBarTextureFile = fileName; _progressBarTexType = texType; @@ -328,9 +330,9 @@ const Rect& Slider::getCapInsetsProgressBarRenderer() const return _capInsetsProgressBarRenderer; } -void Slider::loadSlidBallTextures(std::string_view normal, - std::string_view pressed, - std::string_view disabled, +void Slider::loadSlidBallTextures(const std::string& normal, + const std::string& pressed, + const std::string& disabled, TextureResType texType) { loadSlidBallTextureNormal(normal, texType); @@ -338,7 +340,7 @@ void Slider::loadSlidBallTextures(std::string_view normal, loadSlidBallTextureDisabled(disabled, texType); } -void Slider::loadSlidBallTextureNormal(std::string_view normal, TextureResType texType) +void Slider::loadSlidBallTextureNormal(const std::string& normal, TextureResType texType) { _slidBallNormalTextureFile = normal; _ballNTexType = texType; @@ -368,7 +370,7 @@ void Slider::loadSlidBallTextureNormal(SpriteFrame* spriteframe) this->updateChildrenDisplayedRGBA(); } -void Slider::loadSlidBallTexturePressed(std::string_view pressed, TextureResType texType) +void Slider::loadSlidBallTexturePressed(const std::string& pressed, TextureResType texType) { _slidBallPressedTextureFile = pressed; _isSliderBallPressedTextureLoaded = !pressed.empty(); @@ -400,7 +402,7 @@ void Slider::loadSlidBallTexturePressed(SpriteFrame* spriteframe) this->updateChildrenDisplayedRGBA(); } -void Slider::loadSlidBallTextureDisabled(std::string_view disabled, TextureResType texType) +void Slider::loadSlidBallTextureDisabled(const std::string& disabled, TextureResType texType) { _slidBallDisabledTextureFile = disabled; _isSliderBallDisabledTexturedLoaded = !disabled.empty(); diff --git a/cocos/ui/UISlider.h b/cocos/ui/UISlider.h index 63a3e62bad..b0b30ad0c9 100644 --- a/cocos/ui/UISlider.h +++ b/cocos/ui/UISlider.h @@ -98,8 +98,8 @@ public: * @param resType Texture resource type. * @return An autoreleased Slider object. */ - static Slider* create(std::string_view barTextureName, - std::string_view normalBallTextureName, + static Slider* create(const std::string& barTextureName, + const std::string& normalBallTextureName, TextureResType resType = TextureResType::LOCAL); /** @@ -108,7 +108,7 @@ public: * @param fileName File name of texture. * @param resType @see TextureResType . */ - void loadBarTexture(std::string_view fileName, TextureResType resType = TextureResType::LOCAL); + void loadBarTexture(const std::string& fileName, TextureResType resType = TextureResType::LOCAL); /** * Sets if slider is using scale9 renderer. @@ -162,10 +162,10 @@ public: * @param disabled Disabled state texture. * @param texType @see TextureResType . */ - void loadSlidBallTextures(std::string_view normal, - std::string_view pressed = "", - std::string_view disabled = "", - TextureResType texType = TextureResType::LOCAL); + void loadSlidBallTextures(const std::string& normal, + const std::string& pressed = "", + const std::string& disabled = "", + TextureResType texType = TextureResType::LOCAL); /** * Load normal state texture for slider ball. @@ -173,7 +173,7 @@ public: * @param normal Normal state texture. * @param resType @see TextureResType . */ - void loadSlidBallTextureNormal(std::string_view normal, TextureResType resType = TextureResType::LOCAL); + void loadSlidBallTextureNormal(const std::string& normal, TextureResType resType = TextureResType::LOCAL); /** * Load pressed state texture for slider ball. @@ -181,7 +181,7 @@ public: * @param pressed Pressed state texture. * @param resType @see TextureResType . */ - void loadSlidBallTexturePressed(std::string_view pressed, TextureResType resType = TextureResType::LOCAL); + void loadSlidBallTexturePressed(const std::string& pressed, TextureResType resType = TextureResType::LOCAL); /** * Load disabled state texture for slider ball. @@ -189,7 +189,7 @@ public: * @param disabled Disabled state texture. * @param resType @see TextureResType . */ - void loadSlidBallTextureDisabled(std::string_view disabled, TextureResType resType = TextureResType::LOCAL); + void loadSlidBallTextureDisabled(const std::string& disabled, TextureResType resType = TextureResType::LOCAL); /** * Load dark state texture for slider progress bar. @@ -197,7 +197,7 @@ public: * @param fileName File path of texture. * @param resType @see TextureResType . */ - void loadProgressBarTexture(std::string_view fileName, TextureResType resType = TextureResType::LOCAL); + void loadProgressBarTexture(const std::string& fileName, TextureResType resType = TextureResType::LOCAL); /** * Changes the progress direction of slider. diff --git a/cocos/ui/UITabControl.cpp b/cocos/ui/UITabControl.cpp index 37e9c39614..65c9b54f9a 100644 --- a/cocos/ui/UITabControl.cpp +++ b/cocos/ui/UITabControl.cpp @@ -487,9 +487,9 @@ TabHeader* TabHeader::create() return nullptr; } -TabHeader* TabHeader::create(std::string_view titleStr, - std::string_view backGround, - std::string_view cross, +TabHeader* TabHeader::create(const std::string& titleStr, + const std::string& backGround, + const std::string& cross, TextureResType texType) { TabHeader* tabcell = new TabHeader; @@ -505,12 +505,12 @@ TabHeader* TabHeader::create(std::string_view titleStr, return nullptr; } -TabHeader* TabHeader::create(std::string_view titleStr, - std::string_view backGround, - std::string_view backGroundSelected, - std::string_view cross, - std::string_view backGroundDisabled, - std::string_view frontCrossDisabled, +TabHeader* TabHeader::create(const std::string& titleStr, + const std::string& backGround, + const std::string& backGroundSelected, + const std::string& cross, + const std::string& backGroundDisabled, + const std::string& frontCrossDisabled, TextureResType texType /*= TextureResType::LOCAL*/) { TabHeader* tabcell = new TabHeader; @@ -543,7 +543,7 @@ void TabHeader::initRenderer() addProtectedChild(_tabLabelRender, -1, -1); } -void TabHeader::setTitleText(std::string_view text) +void TabHeader::setTitleText(const std::string& text) { if (text == getTitleText()) { @@ -555,11 +555,11 @@ void TabHeader::setTitleText(std::string_view text) _tabLabelRender->setPosition(_contentSize * 0.5f); } -std::string_view TabHeader::getTitleText() const +std::string TabHeader::getTitleText() const { if (nullptr == _tabLabelRender) { - return ""sv; + return ""; } return _tabLabelRender->getString(); } @@ -609,11 +609,11 @@ void TabHeader::updateContentSize() onSizeChanged(); } -void TabHeader::setTitleFontName(std::string_view fontName) +void TabHeader::setTitleFontName(const std::string& fontName) { if (FileUtils::getInstance()->isFileExist(fontName)) { - std::string lowerCasedFontName{fontName}; + std::string lowerCasedFontName = fontName; std::transform(lowerCasedFontName.begin(), lowerCasedFontName.end(), lowerCasedFontName.begin(), ::tolower); if (lowerCasedFontName.find(".fnt") != std::string::npos) { @@ -647,7 +647,7 @@ Label* TabHeader::getTitleRenderer() const return _tabLabelRender; } -std::string_view TabHeader::getTitleFontName() const +std::string TabHeader::getTitleFontName() const { if (this->_fontType == FontType::SYSTEM) { @@ -661,7 +661,7 @@ std::string_view TabHeader::getTitleFontName() const { return _tabLabelRender->getBMFontFilePath(); } - return ""sv; + return ""; } void TabHeader::onSizeChanged() diff --git a/cocos/ui/UITabControl.h b/cocos/ui/UITabControl.h index 98765bdde4..7da800751d 100644 --- a/cocos/ui/UITabControl.h +++ b/cocos/ui/UITabControl.h @@ -70,9 +70,9 @@ public: * @param texType The texture's resource type in `Widget::TextureResType`. * @return A TabHeader instance pointer */ - static TabHeader* create(std::string_view titleStr, - std::string_view backGround, - std::string_view cross, + static TabHeader* create(const std::string& titleStr, + const std::string& backGround, + const std::string& cross, TextureResType texType = TextureResType::LOCAL); /** @@ -87,12 +87,12 @@ public: * * @return A TabHeader instance pointer. */ - static TabHeader* create(std::string_view titleStr, - std::string_view backGround, - std::string_view backGroundSelected, - std::string_view cross, - std::string_view backGroundDisabled, - std::string_view frontCrossDisabled, + static TabHeader* create(const std::string& titleStr, + const std::string& backGround, + const std::string& backGroundSelected, + const std::string& cross, + const std::string& backGroundDisabled, + const std::string& frontCrossDisabled, TextureResType texType = TextureResType::LOCAL); /** * Return the inner Label renderer of TabHeader. @@ -104,13 +104,13 @@ public: * Change the content of Header's text. *@param text The Header's text. */ - void setTitleText(std::string_view text); + void setTitleText(const std::string& text); /** * get the TabHeader text *@return he TabHeader text */ - std::string_view getTitleText() const; + std::string getTitleText() const; /** * Change the color of he TabHeader text @@ -140,13 +140,13 @@ public: * Change the font name of TabHeader text *@param fontName a font name string. */ - void setTitleFontName(std::string_view fontName); + void setTitleFontName(const std::string& fontName); /** * get the font name of TabHeader text *@return font name in std::string */ - std::string_view getTitleFontName() const; + std::string getTitleFontName() const; /** * get the index this header in the TabControl diff --git a/cocos/ui/UIText.cpp b/cocos/ui/UIText.cpp index 554e024292..db2457e216 100644 --- a/cocos/ui/UIText.cpp +++ b/cocos/ui/UIText.cpp @@ -71,7 +71,7 @@ bool Text::init() return false; } -Text* Text::create(std::string_view textContent, std::string_view fontName, float fontSize) +Text* Text::create(const std::string& textContent, const std::string& fontName, float fontSize) { Text* text = new Text(); if (text->init(textContent, fontName, fontSize)) @@ -83,7 +83,7 @@ Text* Text::create(std::string_view textContent, std::string_view fontName, floa return nullptr; } -bool Text::init(std::string_view textContent, std::string_view fontName, float fontSize) +bool Text::init(const std::string& textContent, const std::string& fontName, float fontSize) { bool ret = true; do @@ -117,7 +117,7 @@ void Text::setString(std::string_view text) _labelRendererAdaptDirty = true; } -std::string_view Text::getString() const +const std::string& Text::getString() const { return _labelRenderer->getString(); } @@ -149,7 +149,7 @@ float Text::getFontSize() const return _fontSize; } -void Text::setFontName(std::string_view name) +void Text::setFontName(const std::string& name) { if (FileUtils::getInstance()->isFileExist(name)) { @@ -173,7 +173,7 @@ void Text::setFontName(std::string_view name) _labelRendererAdaptDirty = true; } -std::string_view Text::getFontName() const +const std::string& Text::getFontName() const { return _fontName; } diff --git a/cocos/ui/UIText.h b/cocos/ui/UIText.h index 10b980a381..39721ef697 100644 --- a/cocos/ui/UIText.h +++ b/cocos/ui/UIText.h @@ -96,7 +96,7 @@ public: * @param fontSize A given font size. * @return An autoreleased Text object. */ - static Text* create(std::string_view textContent, std::string_view fontName, float fontSize); + static Text* create(const std::string& textContent, const std::string& fontName, float fontSize); /** * Changes the string value of label. @@ -110,7 +110,7 @@ public: * * @return String value. */ - std::string_view getString() const; + const std::string& getString() const; /** * Gets the string length of the label. @@ -151,13 +151,13 @@ public: * @endcode * @param name Font name. */ - void setFontName(std::string_view name); + void setFontName(const std::string& name); /** Gets the font name. * * @return Font name. */ - std::string_view getFontName() const; + const std::string& getFontName() const; /** Gets the font type. * @return The font type. @@ -342,7 +342,7 @@ public: virtual const BlendFunc& getBlendFunc() const override; CC_CONSTRUCTOR_ACCESS : virtual bool init() override; - virtual bool init(std::string_view textContent, std::string_view fontName, float fontSize); + virtual bool init(const std::string& textContent, const std::string& fontName, float fontSize); protected: virtual void initRenderer() override; diff --git a/cocos/ui/UITextAtlas.cpp b/cocos/ui/UITextAtlas.cpp index e6ab8300fe..98eb85c0e8 100644 --- a/cocos/ui/UITextAtlas.cpp +++ b/cocos/ui/UITextAtlas.cpp @@ -66,11 +66,11 @@ void TextAtlas::initRenderer() addProtectedChild(_labelAtlasRenderer, LABELATLAS_RENDERER_Z, -1); } -TextAtlas* TextAtlas::create(std::string_view stringValue, - std::string_view charMapFile, +TextAtlas* TextAtlas::create(const std::string& stringValue, + const std::string& charMapFile, int itemWidth, int itemHeight, - std::string_view startCharMap) + const std::string& startCharMap) { TextAtlas* widget = new TextAtlas(); if (widget->init()) @@ -83,11 +83,11 @@ TextAtlas* TextAtlas::create(std::string_view stringValue, return nullptr; } -void TextAtlas::setProperty(std::string_view stringValue, - std::string_view charMapFile, +void TextAtlas::setProperty(const std::string& stringValue, + const std::string& charMapFile, int itemWidth, int itemHeight, - std::string_view startCharMap) + const std::string& startCharMap) { _stringValue = stringValue; _charMapFileName = charMapFile; @@ -116,7 +116,7 @@ void TextAtlas::setString(std::string_view value) // CCLOG("cssss w %f, h %f", _contentSize.width, _contentSize.height); } -std::string_view TextAtlas::getString() const +const std::string& TextAtlas::getString() const { return _labelAtlasRenderer->getString(); } diff --git a/cocos/ui/UITextAtlas.h b/cocos/ui/UITextAtlas.h index 25b9817f57..f84739ada0 100644 --- a/cocos/ui/UITextAtlas.h +++ b/cocos/ui/UITextAtlas.h @@ -82,11 +82,11 @@ public: * @param startCharMap The starting char of the atlas. * @return An autoreleased TextAtlas object. */ - static TextAtlas* create(std::string_view stringValue, - std::string_view charMapFile, + static TextAtlas* create(const std::string& stringValue, + const std::string& charMapFile, int itemWidth, int itemHeight, - std::string_view startCharMap); + const std::string& startCharMap); /** Initializes the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and * the starting char of the atlas. @@ -98,11 +98,11 @@ public: * @param startCharMap The starting char of the atlas. */ - void setProperty(std::string_view stringValue, - std::string_view charMapFile, + void setProperty(const std::string& stringValue, + const std::string& charMapFile, int itemWidth, int itemHeight, - std::string_view startCharMap); + const std::string& startCharMap); /**Set string value for labelatlas. * @@ -114,7 +114,7 @@ public: * * @return The string value of TextAtlas. */ - std::string_view getString() const; + const std::string& getString() const; /** * Gets the string length of the label. diff --git a/cocos/ui/UITextBMFont.cpp b/cocos/ui/UITextBMFont.cpp index 28de90891b..125f921598 100644 --- a/cocos/ui/UITextBMFont.cpp +++ b/cocos/ui/UITextBMFont.cpp @@ -53,7 +53,7 @@ TextBMFont* TextBMFont::create() return nullptr; } -TextBMFont* TextBMFont::create(std::string_view text, std::string_view filename) +TextBMFont* TextBMFont::create(const std::string& text, const std::string& filename) { TextBMFont* widget = new TextBMFont(); if (widget->init()) @@ -73,7 +73,7 @@ void TextBMFont::initRenderer() addProtectedChild(_labelBMFontRenderer, LABELBMFONT_RENDERER_Z, -1); } -void TextBMFont::setFntFile(std::string_view fileName) +void TextBMFont::setFntFile(const std::string& fileName) { if (fileName.empty()) { @@ -86,7 +86,7 @@ void TextBMFont::setFntFile(std::string_view fileName) _labelBMFontRendererAdaptDirty = true; } -void TextBMFont::setString(std::string_view value) +void TextBMFont::setString(const std::string& value) { if (value == _labelBMFontRenderer->getString()) { @@ -98,7 +98,7 @@ void TextBMFont::setString(std::string_view value) _labelBMFontRendererAdaptDirty = true; } -std::string_view TextBMFont::getString() const +const std::string& TextBMFont::getString() const { return _stringValue; } diff --git a/cocos/ui/UITextBMFont.h b/cocos/ui/UITextBMFont.h index eb3f16fc67..70fb5564d1 100644 --- a/cocos/ui/UITextBMFont.h +++ b/cocos/ui/UITextBMFont.h @@ -69,16 +69,16 @@ public: */ static TextBMFont* create(); - static TextBMFont* create(std::string_view text, std::string_view filename); + static TextBMFont* create(const std::string& text, const std::string& filename); /** init a bitmap font atlas with an initial string and the FNT file */ - void setFntFile(std::string_view fileName); + void setFntFile(const std::string& fileName); /** set string value for labelbmfont*/ - void setString(std::string_view value); + void setString(const std::string& value); /** get string value for labelbmfont*/ - std::string_view getString() const; + const std::string& getString() const; /** * Gets the string length of the label. diff --git a/cocos/ui/UITextField.cpp b/cocos/ui/UITextField.cpp index 8e16b2a83a..25b75a61e2 100644 --- a/cocos/ui/UITextField.cpp +++ b/cocos/ui/UITextField.cpp @@ -52,7 +52,7 @@ UICCTextField::UICCTextField() UICCTextField::~UICCTextField() {} -UICCTextField* UICCTextField::create(std::string_view placeholder, std::string_view fontName, float fontSize) +UICCTextField* UICCTextField::create(const std::string& placeholder, const std::string& fontName, float fontSize) { UICCTextField* pRet = new UICCTextField(); @@ -191,12 +191,12 @@ bool UICCTextField::isPasswordEnabled() const return this->isSecureTextEntry(); } -void UICCTextField::setPasswordStyleText(std::string_view styleText) +void UICCTextField::setPasswordStyleText(const std::string& styleText) { this->setPasswordTextStyle(styleText); } -void UICCTextField::setPasswordText(std::string_view text) +void UICCTextField::setPasswordText(const std::string& text) { std::string tempStr = ""; int32_t text_count = StringUtils::getCharacterCountInUTF8String(text); @@ -292,7 +292,7 @@ TextField* TextField::create() return nullptr; } -TextField* TextField::create(std::string_view placeholder, std::string_view fontName, int fontSize) +TextField* TextField::create(const std::string& placeholder, const std::string& fontName, int fontSize) { TextField* widget = new TextField(); if (widget->init()) @@ -358,7 +358,7 @@ Vec2 TextField::getTouchSize() const return Vec2(_touchWidth, _touchHeight); } -void TextField::setString(std::string_view text) +void TextField::setString(const std::string& text) { std::string strText(text); @@ -386,14 +386,14 @@ void TextField::setString(std::string_view text) updateContentSizeWithTextureSize(_textFieldRenderer->getContentSize()); } -void TextField::setPlaceHolder(std::string_view value) +void TextField::setPlaceHolder(const std::string& value) { _textFieldRenderer->setPlaceHolder(value); _textFieldRendererAdaptDirty = true; updateContentSizeWithTextureSize(_textFieldRenderer->getContentSize()); } -std::string_view TextField::getPlaceHolder() const +const std::string& TextField::getPlaceHolder() const { return _textFieldRenderer->getPlaceHolder(); } @@ -449,11 +449,11 @@ int TextField::getFontSize() const return _fontSize; } -void TextField::setFontName(std::string_view name) +void TextField::setFontName(const std::string& name) { if (FileUtils::getInstance()->isFileExist(name)) { - std::string lcName{name}; + std::string lcName = name; std::transform(lcName.begin(), lcName.end(), lcName.begin(), ::tolower); if (lcName.substr(lcName.length() - 4) == ".fnt") { @@ -483,7 +483,7 @@ void TextField::setFontName(std::string_view name) updateContentSizeWithTextureSize(_textFieldRenderer->getContentSize()); } -std::string_view TextField::getFontName() const +const std::string& TextField::getFontName() const { return _fontName; } @@ -493,7 +493,7 @@ void TextField::didNotSelectSelf() _textFieldRenderer->detachWithIME(); } -std::string_view TextField::getString() const +const std::string& TextField::getString() const { return _textFieldRenderer->getString(); } @@ -563,7 +563,7 @@ void TextField::setPasswordStyleText(const char* styleText) const char* TextField::getPasswordStyleText() const { - return _textFieldRenderer->getPasswordTextStyle().data(); + return _textFieldRenderer->getPasswordTextStyle().c_str(); } void TextField::update(float /*dt*/) diff --git a/cocos/ui/UITextField.h b/cocos/ui/UITextField.h index c39bcc410b..2e9c8a8362 100644 --- a/cocos/ui/UITextField.h +++ b/cocos/ui/UITextField.h @@ -74,7 +74,7 @@ public: *@param fontSize Font size in float. *@return A UICCTextField instance. */ - static UICCTextField* create(std::string_view placeholder, std::string_view fontName, float fontSize); + static UICCTextField* create(const std::string& placeholder, const std::string& fontName, float fontSize); // override functions virtual bool onTextFieldAttachWithIME(TextFieldTTF* pSender) override; @@ -142,14 +142,14 @@ public: * * @param styleText The styleText for password mask, the default value is "*". */ - void setPasswordStyleText(std::string_view styleText); + void setPasswordStyleText(const std::string& styleText); /** * @brief Set the password text content. * * @param text The content of password. */ - void setPasswordText(std::string_view text); + void setPasswordText(const std::string& text); /** * @brief Toggle attach with IME. @@ -270,7 +270,7 @@ public: * @param fontSize The font size. * @return A TextField instance. */ - static TextField* create(std::string_view placeholder, std::string_view fontName, int fontSize); + static TextField* create(const std::string& placeholder, const std::string& fontName, int fontSize); /** * @brief Set the touch size @@ -300,14 +300,14 @@ public: * * @param value The string value of placeholder. */ - void setPlaceHolder(std::string_view value); + void setPlaceHolder(const std::string& value); /** * @brief Get the placeholder of TextField. * * @return A placeholder string. */ - std::string_view getPlaceHolder() const; + const std::string& getPlaceHolder() const; /** * @brief Query the placeholder string color. @@ -363,14 +363,14 @@ public: * * @param name The font name string. */ - void setFontName(std::string_view name); + void setFontName(const std::string& name); /** * @brief Query the TextField's font name. * * @return The font name string. */ - std::string_view getFontName() const; + const std::string& getFontName() const; /** * @brief Detach the IME. @@ -381,13 +381,13 @@ public: *Change content of TextField. *@param text A string content. */ - void setString(std::string_view text); + void setString(const std::string& text); /** *Query the content of TextField. *@return The string value of TextField. */ - std::string_view getString() const; + const std::string& getString() const; virtual bool onTouchBegan(Touch* touch, Event* unusedEvent) override; diff --git a/cocos/ui/UITextFieldEx.cpp b/cocos/ui/UITextFieldEx.cpp index a14258c1b8..90e45b4a28 100644 --- a/cocos/ui/UITextFieldEx.cpp +++ b/cocos/ui/UITextFieldEx.cpp @@ -28,8 +28,8 @@ NS_CC_BEGIN # define nxbeep(t) #endif -static Label* createLabel(std::string_view text, - std::string_view font, +static Label* createLabel(const std::string& text, + const std::string& font, float fontSize, const Vec2& dimensions = Vec2::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT, @@ -161,7 +161,7 @@ static int _truncateUTF8String(const char* text, int limit, int& nb) return n; } -static void internalSetLableFont(Label* l, std::string_view fontName, float fontSize) +static void internalSetLableFont(Label* l, const std::string& fontName, float fontSize) { if (FileUtils::getInstance()->isFileExist(fontName)) { @@ -178,7 +178,7 @@ static void internalSetLableFont(Label* l, std::string_view fontName, float font } } -static float internalCalcStringWidth(std::string_view s, std::string_view fontName, float fontSize) +static float internalCalcStringWidth(std::string_view s, const std::string& fontName, float fontSize) { auto label = createLabel(std::string{s}, fontName, fontSize); return label->getContentSize().width; @@ -269,8 +269,8 @@ TextFieldEx::~TextFieldEx() ////////////////////////////////////////////////////////////////////////// // static constructor ////////////////////////////////////////////////////////////////////////// -TextFieldEx* TextFieldEx::create(std::string_view placeholder, - std::string_view fontName, +TextFieldEx* TextFieldEx::create(const std::string& placeholder, + const std::string& fontName, float fontSize, float cursorWidth, const Color4B& cursorColor) @@ -292,8 +292,8 @@ TextFieldEx* TextFieldEx::create(std::string_view placeholder, ////////////////////////////////////////////////////////////////////////// // initialize ////////////////////////////////////////////////////////////////////////// -bool TextFieldEx::initWithPlaceHolder(std::string_view placeholder, - std::string_view fontName, +bool TextFieldEx::initWithPlaceHolder(const std::string& placeholder, + const std::string& fontName, float fontSize, float cursorWidth, const Color4B& cursorColor) @@ -316,12 +316,12 @@ bool TextFieldEx::initWithPlaceHolder(std::string_view placeholder, return true; } -std::string_view TextFieldEx::getTextFontName() const +const std::string& TextFieldEx::getTextFontName() const { return this->fontName; } -void TextFieldEx::setTextFontName(std::string_view fontName) +void TextFieldEx::setTextFontName(const std::string& fontName) { if (FileUtils::getInstance()->isFileExist(fontName)) { @@ -740,7 +740,7 @@ void TextFieldEx::handleDeleteKeyEvent() this->onTextModify(); } -std::string_view TextFieldEx::getContentText() +const std::string& TextFieldEx::getContentText() { return inputText; } @@ -784,7 +784,7 @@ void TextFieldEx::setPlaceholderColor(const Color4B& color) ////////////////////////////////////////////////////////////////////////// // input text property -void TextFieldEx::setString(std::string_view text) +void TextFieldEx::setString(const std::string& text) { static char bulletString[] = {(char)0xe2, (char)0x80, (char)0xa2, (char)0x00}; @@ -838,13 +838,13 @@ void TextFieldEx::updateContentSize(void) this->setContentSize(renderLabel->getContentSize()); } -std::string_view TextFieldEx::getString() const +const std::string& TextFieldEx::getString() const { return inputText; } // place holder text property -void TextFieldEx::setPlaceholderText(std::string_view text) +void TextFieldEx::setPlaceholderText(const std::string& text) { placeHolder = text; if (inputText.empty()) @@ -854,7 +854,7 @@ void TextFieldEx::setPlaceholderText(std::string_view text) } } -std::string_view TextFieldEx::getPlaceholderText() const +const std::string& TextFieldEx::getPlaceholderText() const { return placeHolder; } diff --git a/cocos/ui/UITextFieldEx.h b/cocos/ui/UITextFieldEx.h index a337388c0f..b94a7c7a2b 100644 --- a/cocos/ui/UITextFieldEx.h +++ b/cocos/ui/UITextFieldEx.h @@ -29,14 +29,14 @@ public: */ virtual ~TextFieldEx(); - static TextFieldEx* create(std::string_view placeholder, - std::string_view fontName, + static TextFieldEx* create(const std::string& placeholder, + const std::string& fontName, float fontSize, float cursorWidth = 2, const Color4B& color = Color4B::WHITE); - bool initWithPlaceHolder(std::string_view placeholder, - std::string_view fontName, + bool initWithPlaceHolder(const std::string& placeholder, + const std::string& fontName, float fontSize, float cursorWidth = 2, const Color4B& color = Color4B::WHITE); @@ -58,8 +58,8 @@ public: const Color3B& getCursorColor(void) const; // input text property - virtual void setString(std::string_view text); - virtual std::string_view getString() const; + virtual void setString(const std::string& text); + virtual const std::string& getString() const; // Continuous touch event trigger support. void setContinuousTouchDelayTime(float delay) { _continuousTouchDelayTime = delay; } @@ -71,8 +71,8 @@ public: // place holder text property // place holder text displayed when there is no text in the text field. - virtual void setPlaceholderText(std::string_view text); - virtual std::string_view getPlaceholderText(void) const; + virtual void setPlaceholderText(const std::string& text); + virtual const std::string& getPlaceholderText(void) const; virtual void setPasswordEnabled(bool value); virtual bool isPasswordEnabled() const; @@ -97,8 +97,8 @@ public: /// fonts void setTextFontSize(float size); float getTextFontSize() const; - void setTextFontName(std::string_view fontName); - std::string_view getTextFontName() const; + void setTextFontName(const std::string& fontName); + const std::string& getTextFontName() const; CC_SYNTHESIZE(size_t, charLimit, CharLimit); @@ -122,7 +122,7 @@ protected: virtual bool canDetachWithIME() override; virtual void deleteBackward() override; - virtual std::string_view getContentText() override; + virtual const std::string& getContentText() override; void handleDeleteKeyEvent(); diff --git a/cocos/ui/UIVideoPlayer-android.cpp b/cocos/ui/UIVideoPlayer-android.cpp index 0f61d490fc..dab2aafc7b 100644 --- a/cocos/ui/UIVideoPlayer-android.cpp +++ b/cocos/ui/UIVideoPlayer-android.cpp @@ -38,7 +38,7 @@ //----------------------------------------------------------------------------------------------------------- -static const char* videoHelperClassName = "org.cocos2dx.lib.Cocos2dxVideoHelper"; +static const std::string videoHelperClassName = "org.cocos2dx.lib.Cocos2dxVideoHelper"; USING_NS_CC; @@ -60,7 +60,7 @@ int createVideoWidgetJNI() { JniMethodInfo t; int ret = -1; - if (JniHelper::getStaticMethodInfo(t, videoHelperClassName, "createVideoWidget", "()I")) + if (JniHelper::getStaticMethodInfo(t, videoHelperClassName.c_str(), "createVideoWidget", "()I")) { ret = t.env->CallStaticIntMethod(t.classID, t.methodID); @@ -73,7 +73,7 @@ int createVideoWidgetJNI() void setLoopingJNI(int index, bool looping) { JniMethodInfo t; - if (JniHelper::getStaticMethodInfo(t, videoHelperClassName, "setLooping", "(IZ)V")) + if (JniHelper::getStaticMethodInfo(t, videoHelperClassName.c_str(), "setLooping", "(IZ)V")) { t.env->CallStaticVoidMethod(t.classID, t.methodID, index, looping); @@ -84,7 +84,7 @@ void setLoopingJNI(int index, bool looping) void setUserInputEnabledJNI(int index, bool enableInput) { JniMethodInfo t; - if (JniHelper::getStaticMethodInfo(t, videoHelperClassName, "setUserInputEnabled", "(IZ)V")) + if (JniHelper::getStaticMethodInfo(t, videoHelperClassName.c_str(), "setUserInputEnabled", "(IZ)V")) { t.env->CallStaticVoidMethod(t.classID, t.methodID, index, enableInput); @@ -124,7 +124,7 @@ VideoPlayer::~VideoPlayer() JniHelper::callStaticVoidMethod(videoHelperClassName, "removeVideoWidget", _videoPlayerIndex); } -void VideoPlayer::setFileName(std::string_view fileName) +void VideoPlayer::setFileName(const std::string& fileName) { _videoURL = FileUtils::getInstance()->fullPathForFilename(fileName); _videoSource = VideoPlayer::Source::FILENAME; @@ -132,7 +132,7 @@ void VideoPlayer::setFileName(std::string_view fileName) _videoURL); } -void VideoPlayer::setURL(std::string_view videoUrl) +void VideoPlayer::setURL(const std::string& videoUrl) { _videoURL = videoUrl; _videoSource = VideoPlayer::Source::URL; diff --git a/cocos/ui/UIVideoPlayer-ios.mm b/cocos/ui/UIVideoPlayer-ios.mm index c1494ed511..f41d63a57f 100644 --- a/cocos/ui/UIVideoPlayer-ios.mm +++ b/cocos/ui/UIVideoPlayer-ios.mm @@ -31,11 +31,11 @@ using namespace cocos2d::ui; //------------------------------------------------------------------------------------- -# include "platform/ios/CCEAGLView-ios.h" -# import -# import -# include "base/CCDirector.h" -# include "platform/CCFileUtils.h" +#include "platform/ios/CCEAGLView-ios.h" +#import +#import +#include "base/CCDirector.h" +#include "platform/CCFileUtils.h" @interface UIVideoViewWrapperIos : NSObject @@ -47,29 +47,31 @@ typedef NS_ENUM(NSInteger, PlayerbackState) { PlayerbackStateCompleted }; -@property(assign, nonatomic) AVPlayerViewController* playerController; +@property (assign, nonatomic) AVPlayerViewController * playerController; -- (void)setFrame:(int)left:(int)top:(int)width:(int)height; -- (void)setURL:(int)videoSource:(std::string&)videoUrl; -- (void)play; -- (void)pause; -- (void)resume; -- (void)stop; -- (void)seekTo:(float)sec; -- (void)setVisible:(BOOL)visible; -- (void)setKeepRatioEnabled:(BOOL)enabled; -- (void)setFullScreenEnabled:(BOOL)enabled; -- (BOOL)isFullScreenEnabled; -- (void)showPlaybackControls:(BOOL)value; -- (void)setRepeatEnabled:(BOOL)enabled; -- (void)setUserInteractionEnabled:(BOOL)userInteractionEnabled; +- (void) setFrame:(int) left :(int) top :(int) width :(int) height; +- (void) setURL:(int) videoSource :(std::string&) videoUrl; +- (void) play; +- (void) pause; +- (void) resume; +- (void) stop; +- (void) seekTo:(float) sec; +- (void) setVisible:(BOOL) visible; +- (void) setKeepRatioEnabled:(BOOL) enabled; +- (void) setFullScreenEnabled:(BOOL) enabled; +- (BOOL) isFullScreenEnabled; +- (void) showPlaybackControls:(BOOL) value; +- (void) setRepeatEnabled:(BOOL)enabled; +- (void) setUserInteractionEnabled:(BOOL)userInteractionEnabled; -- (id)init:(void*)videoPlayer; -- (void)videoFinished:(NSNotification*)notification; + +-(id) init:(void*) videoPlayer; +-(void) videoFinished:(NSNotification*) notification; @end -@implementation UIVideoViewWrapperIos { +@implementation UIVideoViewWrapperIos +{ int _left; int _top; int _width; @@ -82,25 +84,24 @@ typedef NS_ENUM(NSInteger, PlayerbackState) { VideoPlayer* _videoPlayer; } -- (id)init:(void*)videoPlayer +-(id)init:(void*)videoPlayer { - if (self = [super init]) - { + if (self = [super init]) { self.playerController = [AVPlayerViewController new]; [self setRepeatEnabled:FALSE]; [self showPlaybackControls:TRUE]; [self setUserInteractionEnabled:TRUE]; [self setKeepRatioEnabled:FALSE]; - + _videoPlayer = (VideoPlayer*)videoPlayer; - _state = PlayerbackStateUnknown; + _state = PlayerbackStateUnknown; } return self; } -- (void)dealloc +-(void) dealloc { _videoPlayer = nullptr; [self clean]; @@ -108,44 +109,44 @@ typedef NS_ENUM(NSInteger, PlayerbackState) { [super dealloc]; } -- (void)clean +-(void) clean { [self stop]; [self removePlayerEventListener]; [self.playerController.view removeFromSuperview]; } -- (void)setFrame:(int)left:(int)top:(int)width:(int)height +-(void) setFrame:(int)left :(int)top :(int)width :(int)height { - _left = left; - _width = width; - _top = top; + _left = left; + _width = width; + _top = top; _height = height; [self.playerController.view setFrame:CGRectMake(left, top, width, height)]; } -- (void)setFullScreenEnabled:(BOOL)enabled +-(void) setFullScreenEnabled:(BOOL) enabled { // AVPlayerViewController doesn't provide API to enable fullscreen. But you can toggle // fullsreen by the playback controllers. } -- (BOOL)isFullScreenEnabled +-(BOOL) isFullScreenEnabled { return false; } -- (void)showPlaybackControls:(BOOL)value + +-(void) showPlaybackControls:(BOOL)value { - _showPlaybackControls = value; + _showPlaybackControls = value; self.playerController.showsPlaybackControls = value; } -- (void)setRepeatEnabled:(BOOL)enabled +-(void) setRepeatEnabled:(BOOL)enabled { _repeatEnabled = enabled; - if (self.playerController.player) - { + if (self.playerController.player) { if (_repeatEnabled) self.playerController.player.actionAtItemEnd = AVPlayerActionAtItemEndNone; else @@ -153,61 +154,57 @@ typedef NS_ENUM(NSInteger, PlayerbackState) { } } -- (void)setUserInteractionEnabled:(BOOL)userInteractionEnabled +-(void) setUserInteractionEnabled:(BOOL)userInteractionEnabled { - _userInteractionEnabled = userInteractionEnabled; + _userInteractionEnabled = userInteractionEnabled; self.playerController.view.userInteractionEnabled = _userInteractionEnabled; } -- (void)setURL:(int)videoSource:(std::string&)videoUrl +-(void) setURL:(int)videoSource :(std::string &)videoUrl { [self clean]; if (videoSource == 1) - self.playerController.player = - [[[AVPlayer alloc] initWithURL:[NSURL URLWithString:@(videoUrl.c_str())]] autorelease]; + self.playerController.player = [[[AVPlayer alloc] initWithURL:[NSURL URLWithString:@(videoUrl.c_str())]] autorelease]; else - self.playerController.player = - [[[AVPlayer alloc] initWithURL:[NSURL fileURLWithPath:@(videoUrl.c_str())]] autorelease]; + self.playerController.player = [[[AVPlayer alloc] initWithURL:[NSURL fileURLWithPath:@(videoUrl.c_str())]] autorelease]; [self setRepeatEnabled:_repeatEnabled]; [self setKeepRatioEnabled:_keepRatioEnabled]; [self setUserInteractionEnabled:_userInteractionEnabled]; [self showPlaybackControls:_showPlaybackControls]; - auto view = cocos2d::Director::getInstance()->getOpenGLView(); - auto eaglview = (CCEAGLView*)view->getEAGLView(); + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + auto eaglview = (CCEAGLView *) view->getEAGLView(); [eaglview addSubview:self.playerController.view]; [self registerPlayerEventListener]; } -- (void)videoFinished:(NSNotification*)notification +-(void) videoFinished:(NSNotification *)notification { - if (_videoPlayer != nullptr) - { + if(_videoPlayer != nullptr) { _videoPlayer->onPlayEvent((int)VideoPlayer::EventType::COMPLETED); _state = PlayerbackStateCompleted; - if (_repeatEnabled) - { + if (_repeatEnabled) { [self seekTo:0]; [self play]; } } } -- (void)seekTo:(float)sec +-(void) seekTo:(float)sec { if (self.playerController.player) [self.playerController.player seekToTime:CMTimeMake(sec, 1)]; } -- (void)setVisible:(BOOL)visible +-(void) setVisible:(BOOL)visible { [self.playerController.view setHidden:!visible]; } -- (void)setKeepRatioEnabled:(BOOL)enabled +-(void) setKeepRatioEnabled:(BOOL)enabled { _keepRatioEnabled = enabled; if (_keepRatioEnabled) @@ -216,41 +213,38 @@ typedef NS_ENUM(NSInteger, PlayerbackState) { self.playerController.videoGravity = AVLayerVideoGravityResizeAspectFill; } -- (void)play +-(void) play { - if (self.playerController.player && _state != PlayerbackStatePlaying) - { + if (self.playerController.player && _state != PlayerbackStatePlaying) { [self.playerController.player play]; _state = PlayerbackStatePlaying; _videoPlayer->onPlayEvent((int)VideoPlayer::EventType::PLAYING); } } -- (void)pause +-(void) pause { - if (self.playerController.player && _state == PlayerbackStatePlaying) - { + if (self.playerController.player && _state == PlayerbackStatePlaying) { [self.playerController.player pause]; _state = PlayerbackStatePaused; _videoPlayer->onPlayEvent((int)VideoPlayer::EventType::PAUSED); } } -- (void)resume +-(void) resume { if (self.playerController.player && _state == PlayerbackStatePaused) [self play]; } -- (void)stop +-(void) stop { // AVPlayer doesn't have stop, so just pause it, and seek time to 0. - if (self.playerController.player && _state != PlayerbackStopped) - { + if (self.playerController.player && _state != PlayerbackStopped) { [self seekTo:0]; [self.playerController.player pause]; _state = PlayerbackStopped; - + // stop() will be invoked in dealloc, which is invoked by _videoPlayer's destructor, // so do't send the message when _videoPlayer is being deleted. if (_videoPlayer) @@ -258,21 +252,21 @@ typedef NS_ENUM(NSInteger, PlayerbackState) { } } -- (void)registerPlayerEventListener +-(void) registerPlayerEventListener { if (self.playerController.player) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoFinished:) - name:AVPlayerItemDidPlayToEndTimeNotification - object:self.playerController.player.currentItem]; + name:AVPlayerItemDidPlayToEndTimeNotification + object:self.playerController.player.currentItem]; } -- (void)removePlayerEventListener +-(void) removePlayerEventListener { if (self.playerController.player) [[NSNotificationCenter defaultCenter] removeObserver:self - name:AVPlayerItemDidPlayToEndTimeNotification - object:self.playerController.player.currentItem]; + name:AVPlayerItemDidPlayToEndTimeNotification + object:self.playerController.player.currentItem]; } @end @@ -282,32 +276,32 @@ VideoPlayer::VideoPlayer() { _videoView = [[UIVideoViewWrapperIos alloc] init:this]; -# if CC_VIDEOPLAYER_DEBUG_DRAW +#if CC_VIDEOPLAYER_DEBUG_DRAW _debugDrawNode = DrawNode::create(); addChild(_debugDrawNode); -# endif +#endif } VideoPlayer::~VideoPlayer() { - if (_videoView) + if(_videoView) { [((UIVideoViewWrapperIos*)_videoView) dealloc]; } } -void VideoPlayer::setFileName(std::string_view fileName) +void VideoPlayer::setFileName(const std::string& fileName) { - _videoURL = FileUtils::getInstance()->fullPathForFilename(fileName); + _videoURL = FileUtils::getInstance()->fullPathForFilename(fileName); _videoSource = VideoPlayer::Source::FILENAME; - [((UIVideoViewWrapperIos*)_videoView) setURL:(int) _videoSource:_videoURL]; + [((UIVideoViewWrapperIos*)_videoView) setURL:(int)_videoSource :_videoURL]; } -void VideoPlayer::setURL(std::string_view videoUrl) +void VideoPlayer::setURL(const std::string& videoUrl) { - _videoURL = videoUrl; + _videoURL = videoUrl; _videoSource = VideoPlayer::Source::URL; - [((UIVideoViewWrapperIos*)_videoView) setURL:(int) _videoSource:_videoURL]; + [((UIVideoViewWrapperIos*)_videoView) setURL:(int)_videoSource :_videoURL]; } void VideoPlayer::setLooping(bool looping) @@ -326,52 +320,56 @@ void VideoPlayer::setStyle(StyleType style) { _styleType = style; - switch (style) - { - case StyleType::DEFAULT: - [((UIVideoViewWrapperIos*)_videoView) showPlaybackControls:TRUE]; - break; + switch (style) { + case StyleType::DEFAULT: + [((UIVideoViewWrapperIos*)_videoView) showPlaybackControls:TRUE]; + break; - case StyleType::NONE: - [((UIVideoViewWrapperIos*)_videoView) showPlaybackControls:FALSE]; - break; + case StyleType::NONE: + [((UIVideoViewWrapperIos*)_videoView) showPlaybackControls:FALSE]; + break; } } -void VideoPlayer::draw(Renderer* renderer, const Mat4& transform, uint32_t flags) +void VideoPlayer::draw(Renderer* renderer, const Mat4 &transform, uint32_t flags) { - cocos2d::ui::Widget::draw(renderer, transform, flags); + cocos2d::ui::Widget::draw(renderer,transform,flags); if (flags & FLAGS_TRANSFORM_DIRTY) { auto directorInstance = Director::getInstance(); - auto glView = directorInstance->getOpenGLView(); - auto frameSize = glView->getFrameSize(); - auto scaleFactor = [static_cast(glView->getEAGLView()) contentScaleFactor]; + auto glView = directorInstance->getOpenGLView(); + auto frameSize = glView->getFrameSize(); + auto scaleFactor = [static_cast(glView->getEAGLView()) contentScaleFactor]; auto winSize = directorInstance->getWinSize(); auto leftBottom = convertToWorldSpace(Vec2::ZERO); - auto rightTop = convertToWorldSpace(Vec2(_contentSize.width, _contentSize.height)); + auto rightTop = convertToWorldSpace(Vec2(_contentSize.width,_contentSize.height)); - auto uiLeft = (frameSize.width / 2 + (leftBottom.x - winSize.width / 2) * glView->getScaleX()) / scaleFactor; - auto uiTop = (frameSize.height / 2 - (rightTop.y - winSize.height / 2) * glView->getScaleY()) / scaleFactor; + auto uiLeft = (frameSize.width / 2 + (leftBottom.x - winSize.width / 2 ) * glView->getScaleX()) / scaleFactor; + auto uiTop = (frameSize.height /2 - (rightTop.y - winSize.height / 2) * glView->getScaleY()) / scaleFactor; - [((UIVideoViewWrapperIos*)_videoView) setFrame: - uiLeft:uiTop:(rightTop.x - leftBottom.x) * glView->getScaleX() / - scaleFactor:((rightTop.y - leftBottom.y) * glView->getScaleY() / - scaleFactor)]; + [((UIVideoViewWrapperIos*)_videoView) setFrame :uiLeft :uiTop + :(rightTop.x - leftBottom.x) * glView->getScaleX() / scaleFactor + :( (rightTop.y - leftBottom.y) * glView->getScaleY()/scaleFactor)]; } -# if CC_VIDEOPLAYER_DEBUG_DRAW +#if CC_VIDEOPLAYER_DEBUG_DRAW _debugDrawNode->clear(); - auto size = getContentSize(); - Point vertices[4] = {Point::ZERO, Point(size.width, 0), Point(size.width, size.height), Point(0, size.height)}; + auto size = getContentSize(); + Point vertices[4]= + { + Point::ZERO, + Point(size.width, 0), + Point(size.width, size.height), + Point(0, size.height) + }; _debugDrawNode->drawPoly(vertices, 4, true, Color4F(1.0, 1.0, 1.0, 1.0)); -# endif +#endif } -bool VideoPlayer::isFullScreenEnabled() const +bool VideoPlayer::isFullScreenEnabled()const { return [((UIVideoViewWrapperIos*)_videoView) isFullScreenEnabled]; } @@ -392,7 +390,7 @@ void VideoPlayer::setKeepAspectRatioEnabled(bool enable) void VideoPlayer::play() { - if (!_videoURL.empty()) + if (! _videoURL.empty()) { [((UIVideoViewWrapperIos*)_videoView) play]; } @@ -400,7 +398,7 @@ void VideoPlayer::play() void VideoPlayer::pause() { - if (!_videoURL.empty()) + if (! _videoURL.empty()) { [((UIVideoViewWrapperIos*)_videoView) pause]; } @@ -408,7 +406,7 @@ void VideoPlayer::pause() void VideoPlayer::resume() { - if (!_videoURL.empty()) + if (! _videoURL.empty()) { [((UIVideoViewWrapperIos*)_videoView) resume]; } @@ -416,7 +414,7 @@ void VideoPlayer::resume() void VideoPlayer::stop() { - if (!_videoURL.empty()) + if (! _videoURL.empty()) { [((UIVideoViewWrapperIos*)_videoView) stop]; } @@ -424,7 +422,7 @@ void VideoPlayer::stop() void VideoPlayer::seekTo(float sec) { - if (!_videoURL.empty()) + if (! _videoURL.empty()) { [((UIVideoViewWrapperIos*)_videoView) seekTo:sec]; } @@ -453,7 +451,7 @@ void VideoPlayer::setVisible(bool visible) { [((UIVideoViewWrapperIos*)_videoView) setVisible:NO]; } - else if (isRunning()) + else if(isRunning()) { [((UIVideoViewWrapperIos*)_videoView) setVisible:YES]; } @@ -464,14 +462,14 @@ void VideoPlayer::onEnter() Widget::onEnter(); if (isVisible()) { - [((UIVideoViewWrapperIos*)_videoView) setVisible:YES]; + [((UIVideoViewWrapperIos*)_videoView) setVisible: YES]; } } void VideoPlayer::onExit() { Widget::onExit(); - [((UIVideoViewWrapperIos*)_videoView) setVisible:NO]; + [((UIVideoViewWrapperIos*)_videoView) setVisible: NO]; } void VideoPlayer::addEventListener(const VideoPlayer::ccVideoPlayerCallback& callback) @@ -481,12 +479,9 @@ void VideoPlayer::addEventListener(const VideoPlayer::ccVideoPlayerCallback& cal void VideoPlayer::onPlayEvent(int event) { - if (event == (int)VideoPlayer::EventType::PLAYING) - { + if (event == (int)VideoPlayer::EventType::PLAYING) { _isPlaying = true; - } - else - { + } else { _isPlaying = false; } @@ -501,23 +496,23 @@ cocos2d::ui::Widget* VideoPlayer::createCloneInstance() return VideoPlayer::create(); } -void VideoPlayer::copySpecialProperties(Widget* widget) +void VideoPlayer::copySpecialProperties(Widget *widget) { VideoPlayer* videoPlayer = dynamic_cast(widget); if (videoPlayer) { - _isPlaying = videoPlayer->_isPlaying; - _isLooping = videoPlayer->_isLooping; - _isUserInputEnabled = videoPlayer->_isUserInputEnabled; - _styleType = videoPlayer->_styleType; - _fullScreenEnabled = videoPlayer->_fullScreenEnabled; - _fullScreenDirty = videoPlayer->_fullScreenDirty; - _videoURL = videoPlayer->_videoURL; + _isPlaying = videoPlayer->_isPlaying; + _isLooping = videoPlayer->_isLooping; + _isUserInputEnabled = videoPlayer->_isUserInputEnabled; + _styleType = videoPlayer->_styleType; + _fullScreenEnabled = videoPlayer->_fullScreenEnabled; + _fullScreenDirty = videoPlayer->_fullScreenDirty; + _videoURL = videoPlayer->_videoURL; _keepAspectRatioEnabled = videoPlayer->_keepAspectRatioEnabled; - _videoSource = videoPlayer->_videoSource; - _videoPlayerIndex = videoPlayer->_videoPlayerIndex; - _eventCallback = videoPlayer->_eventCallback; - _videoView = videoPlayer->_videoView; + _videoSource = videoPlayer->_videoSource; + _videoPlayerIndex = videoPlayer->_videoPlayerIndex; + _eventCallback = videoPlayer->_eventCallback; + _videoView = videoPlayer->_videoView; } } diff --git a/cocos/ui/UIVideoPlayer.h b/cocos/ui/UIVideoPlayer.h index 76e82663f2..c97d5c3b7b 100644 --- a/cocos/ui/UIVideoPlayer.h +++ b/cocos/ui/UIVideoPlayer.h @@ -86,26 +86,26 @@ public: /** * Sets a file path as a video source for VideoPlayer. */ - virtual void setFileName(std::string_view videoPath); + virtual void setFileName(const std::string& videoPath); /** * @brief Get the local video file name. * * @return The video file name. */ - virtual std::string_view getFileName() const { return _videoURL; } + virtual const std::string& getFileName() const { return _videoURL; } /** * Sets a URL as a video source for VideoPlayer. */ - virtual void setURL(std::string_view _videoURL); + virtual void setURL(const std::string& _videoURL); /** * @brief Get the URL of remoting video source. * * @return A remoting URL address. */ - virtual std::string_view getURL() const { return _videoURL; } + virtual const std::string& getURL() const { return _videoURL; } /** * @brief Set if playback is done in loop mode diff --git a/cocos/ui/UIWebView/UIWebView-inl.h b/cocos/ui/UIWebView/UIWebView-inl.h index 8f510b0177..586aecc8e5 100644 --- a/cocos/ui/UIWebView/UIWebView-inl.h +++ b/cocos/ui/UIWebView/UIWebView-inl.h @@ -53,35 +53,35 @@ WebView* WebView::create() return nullptr; } -void WebView::setJavascriptInterfaceScheme(std::string_view scheme) +void WebView::setJavascriptInterfaceScheme(const std::string& scheme) { _impl->setJavascriptInterfaceScheme(scheme); } void WebView::loadData(const cocos2d::Data& data, - std::string_view MIMEType, - std::string_view encoding, - std::string_view baseURL) + const std::string& MIMEType, + const std::string& encoding, + const std::string& baseURL) { _impl->loadData(data, MIMEType, encoding, baseURL); } -void WebView::loadHTMLString(std::string_view string, std::string_view baseURL) +void WebView::loadHTMLString(const std::string& string, const std::string& baseURL) { _impl->loadHTMLString(string, baseURL); } -void WebView::loadURL(std::string_view url) +void WebView::loadURL(const std::string& url) { this->loadURL(url, false); } -void WebView::loadURL(std::string_view url, bool cleanCachedData) +void WebView::loadURL(const std::string& url, bool cleanCachedData) { _impl->loadURL(url, cleanCachedData); } -void WebView::loadFile(std::string_view fileName) +void WebView::loadFile(const std::string& fileName) { _impl->loadFile(fileName); } @@ -116,7 +116,7 @@ void WebView::goForward() _impl->goForward(); } -void WebView::evaluateJS(std::string_view js) +void WebView::evaluateJS(const std::string& js) { _impl->evaluateJS(js); } @@ -204,7 +204,7 @@ void WebView::setOnDidFinishLoading(const ccWebViewCallback& callback) _onDidFinishLoading = callback; } -void WebView::setOnShouldStartLoading(const std::function& callback) +void WebView::setOnShouldStartLoading(const std::function& callback) { _onShouldStartLoading = callback; } @@ -214,7 +214,7 @@ void WebView::setOnJSCallback(const ccWebViewCallback& callback) _onJSCallback = callback; } -std::function WebView::getOnShouldStartLoading() const +std::function WebView::getOnShouldStartLoading() const { return _onShouldStartLoading; } diff --git a/cocos/ui/UIWebView/UIWebView.h b/cocos/ui/UIWebView/UIWebView.h index a685f7af73..bc37e130d2 100644 --- a/cocos/ui/UIWebView/UIWebView.h +++ b/cocos/ui/UIWebView/UIWebView.h @@ -59,7 +59,7 @@ public: * * @see WebView::setOnJSCallback() */ - void setJavascriptInterfaceScheme(std::string_view scheme); + void setJavascriptInterfaceScheme(const std::string& scheme); /** * Sets the main page contents, MIME type, content encoding, and base URL. @@ -70,9 +70,9 @@ public: * @param baseURL The base URL for the content. */ void loadData(const cocos2d::Data& data, - std::string_view MIMEType, - std::string_view encoding, - std::string_view baseURL); + const std::string& MIMEType, + const std::string& encoding, + const std::string& baseURL); /** * Sets the main page content and base URL. @@ -80,28 +80,28 @@ public: * @param string The content for the main page. * @param baseURL The base URL for the content. */ - void loadHTMLString(std::string_view string, std::string_view baseURL = ""); + void loadHTMLString(const std::string& string, const std::string& baseURL = ""); /** * Loads the given URL. It doesn't clean cached data. * * @param url Content URL. */ - void loadURL(std::string_view url); + void loadURL(const std::string& url); /** * Loads the given URL with cleaning cached data or not. * @param url Content URL. * @cleanCachedData Whether to clean cached data. */ - void loadURL(std::string_view url, bool cleanCachedData); + void loadURL(const std::string& url, bool cleanCachedData); /** * Loads the given fileName. * * @param fileName Content fileName. */ - void loadFile(std::string_view fileName); + void loadFile(const std::string& fileName); /** * Stops the current load. @@ -140,7 +140,7 @@ public: /** * Evaluates JavaScript in the context of the currently displayed page. */ - void evaluateJS(std::string_view js); + void evaluateJS(const std::string& js); /** * Set WebView should support zooming. The default value is false. @@ -153,12 +153,12 @@ public: * @param callback The web view that is about to load new content. * @return YES if the web view should begin loading content; otherwise, NO. */ - void setOnShouldStartLoading(const std::function& callback); + void setOnShouldStartLoading(const std::function& callback); /** * A callback which will be called when a WebView event happens. */ - typedef std::function ccWebViewCallback; + typedef std::function ccWebViewCallback; /** * Call after a web view finishes loading. @@ -182,7 +182,7 @@ public: /** * Get the callback when WebView is about to start. */ - std::function getOnShouldStartLoading() const; + std::function getOnShouldStartLoading() const; /** * Get the callback when WebView has finished loading. @@ -231,10 +231,10 @@ protected: virtual cocos2d::ui::Widget* createCloneInstance() override; virtual void copySpecialProperties(Widget* model) override; - std::function _onShouldStartLoading = nullptr; - ccWebViewCallback _onDidFinishLoading = nullptr; - ccWebViewCallback _onDidFailLoading = nullptr; - ccWebViewCallback _onJSCallback = nullptr; + std::function _onShouldStartLoading = nullptr; + ccWebViewCallback _onDidFinishLoading = nullptr; + ccWebViewCallback _onDidFailLoading = nullptr; + ccWebViewCallback _onJSCallback = nullptr; CC_CONSTRUCTOR_ACCESS : /** diff --git a/cocos/ui/UIWebView/UIWebView.mm b/cocos/ui/UIWebView/UIWebView.mm index a80e16512c..31a5694674 100644 --- a/cocos/ui/UIWebView/UIWebView.mm +++ b/cocos/ui/UIWebView/UIWebView.mm @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2014-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 diff --git a/cocos/ui/UIWebView/UIWebViewImpl-android.cpp b/cocos/ui/UIWebView/UIWebViewImpl-android.cpp index b5ec6cac0f..cd61a73d6e 100644 --- a/cocos/ui/UIWebView/UIWebViewImpl-android.cpp +++ b/cocos/ui/UIWebView/UIWebViewImpl-android.cpp @@ -37,14 +37,14 @@ #include "ui/UIHelper.h" #include "yasio/cxx17/string_view.hpp" -static const char* className = "org.cocos2dx.lib.Cocos2dxWebViewHelper"; +static const std::string className = "org.cocos2dx.lib.Cocos2dxWebViewHelper"; #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "", __VA_ARGS__) -static constexpr std::string_view s_defaultBaseUrl = "file:///android_asset/"sv; -static constexpr std::string_view s_sdRootBaseUrl = "file://"sv; +static const std::string s_defaultBaseUrl = "file:///android_asset/"; +static const std::string s_sdRootBaseUrl = "file://"; -static std::string getFixedBaseUrl(std::string_view baseUrl) +static std::string getFixedBaseUrl(const std::string& baseUrl) { std::string fixedBaseUrl; if (baseUrl.empty()) @@ -55,26 +55,26 @@ static std::string getFixedBaseUrl(std::string_view baseUrl) { fixedBaseUrl = baseUrl; } - else if (baseUrl[0] != '/') + else if (baseUrl.c_str()[0] != '/') { using namespace cxx17; // for cxx17::string_view literal - if (cxx20::starts_with(baseUrl, "assets/"_sv)) + if (cxx20::starts_with(cxx17::string_view{baseUrl}, "assets/"_sv)) { - fixedBaseUrl.assign(s_defaultBaseUrl).push_back(baseUrl[7]); + fixedBaseUrl = s_defaultBaseUrl + baseUrl.c_str()[7]; } else { - fixedBaseUrl.assign(s_defaultBaseUrl).append(baseUrl); + fixedBaseUrl = s_defaultBaseUrl + baseUrl; } } else { - fixedBaseUrl.assign(s_sdRootBaseUrl).append(baseUrl); + fixedBaseUrl = s_sdRootBaseUrl + baseUrl; } if (fixedBaseUrl.c_str()[fixedBaseUrl.length() - 1] != '/') { - fixedBaseUrl.push_back('/'); + fixedBaseUrl += "/"; } return fixedBaseUrl; @@ -155,7 +155,7 @@ namespace int createWebViewJNI() { cocos2d::JniMethodInfo t; - if (cocos2d::JniHelper::getStaticMethodInfo(t, className, "createWebView", "()I")) + if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), "createWebView", "()I")) { // LOGD("error: %s,%d",__func__,__LINE__); jint viewTag = t.env->CallStaticIntMethod(t.classID, t.methodID); @@ -165,7 +165,7 @@ int createWebViewJNI() return -1; } -std::string getUrlStringByFileName(std::string_view fileName) +std::string getUrlStringByFileName(const std::string& fileName) { // LOGD("error: %s,%d",__func__,__LINE__); const std::string basePath("file:///android_asset/"); @@ -214,31 +214,31 @@ WebViewImpl::~WebViewImpl() } void WebViewImpl::loadData(const Data& data, - std::string_view MIMEType, - std::string_view encoding, - std::string_view baseURL) + const std::string& MIMEType, + const std::string& encoding, + const std::string& baseURL) { std::string dataString(reinterpret_cast(data.getBytes()), static_cast(data.getSize())); JniHelper::callStaticVoidMethod(className, "setJavascriptInterfaceScheme", _viewTag, dataString, MIMEType, encoding, baseURL); } -void WebViewImpl::loadHTMLString(std::string_view string, std::string_view baseURL) +void WebViewImpl::loadHTMLString(const std::string& string, const std::string& baseURL) { JniHelper::callStaticVoidMethod(className, "loadHTMLString", _viewTag, string, getFixedBaseUrl(baseURL)); } -void WebViewImpl::loadURL(std::string_view url) +void WebViewImpl::loadURL(const std::string& url) { this->loadURL(url, false); } -void WebViewImpl::loadURL(std::string_view url, bool cleanCachedData) +void WebViewImpl::loadURL(const std::string& url, bool cleanCachedData) { JniHelper::callStaticVoidMethod(className, "loadUrl", _viewTag, url, cleanCachedData); } -void WebViewImpl::loadFile(std::string_view fileName) +void WebViewImpl::loadFile(const std::string& fileName) { auto fullPath = getUrlStringByFileName(fileName); JniHelper::callStaticVoidMethod(className, "loadFile", _viewTag, fullPath); @@ -274,12 +274,12 @@ void WebViewImpl::goForward() JniHelper::callStaticVoidMethod(className, "goForward", _viewTag); } -void WebViewImpl::setJavascriptInterfaceScheme(std::string_view scheme) +void WebViewImpl::setJavascriptInterfaceScheme(const std::string& scheme) { JniHelper::callStaticVoidMethod(className, "setJavascriptInterfaceScheme", _viewTag, scheme); } -void WebViewImpl::evaluateJS(std::string_view js) +void WebViewImpl::evaluateJS(const std::string& js) { JniHelper::callStaticVoidMethod(className, "evaluateJS", _viewTag, js); } @@ -289,7 +289,7 @@ void WebViewImpl::setScalesPageToFit(const bool scalesPageToFit) JniHelper::callStaticVoidMethod(className, "setScalesPageToFit", _viewTag, scalesPageToFit); } -bool WebViewImpl::shouldStartLoading(const int viewTag, std::string_view url) +bool WebViewImpl::shouldStartLoading(const int viewTag, const std::string& url) { bool allowLoad = true; auto it = s_WebViewImpls.find(viewTag); @@ -304,7 +304,7 @@ bool WebViewImpl::shouldStartLoading(const int viewTag, std::string_view url) return allowLoad; } -void WebViewImpl::didFinishLoading(const int viewTag, std::string_view url) +void WebViewImpl::didFinishLoading(const int viewTag, const std::string& url) { auto it = s_WebViewImpls.find(viewTag); if (it != s_WebViewImpls.end()) @@ -317,7 +317,7 @@ void WebViewImpl::didFinishLoading(const int viewTag, std::string_view url) } } -void WebViewImpl::didFailLoading(const int viewTag, std::string_view url) +void WebViewImpl::didFailLoading(const int viewTag, const std::string& url) { auto it = s_WebViewImpls.find(viewTag); if (it != s_WebViewImpls.end()) @@ -330,7 +330,7 @@ void WebViewImpl::didFailLoading(const int viewTag, std::string_view url) } } -void WebViewImpl::onJsCallback(const int viewTag, std::string_view message) +void WebViewImpl::onJsCallback(const int viewTag, const std::string& message) { auto it = s_WebViewImpls.find(viewTag); if (it != s_WebViewImpls.end()) diff --git a/cocos/ui/UIWebView/UIWebViewImpl-android.h b/cocos/ui/UIWebView/UIWebViewImpl-android.h index 9f1a178a5a..653078cc28 100644 --- a/cocos/ui/UIWebView/UIWebViewImpl-android.h +++ b/cocos/ui/UIWebView/UIWebViewImpl-android.h @@ -28,8 +28,6 @@ #include #include -#include -#include namespace cocos2d { @@ -55,19 +53,19 @@ public: virtual ~WebViewImpl(); - void setJavascriptInterfaceScheme(std::string_view scheme); + void setJavascriptInterfaceScheme(const std::string& scheme); void loadData(const cocos2d::Data& data, - std::string_view MIMEType, - std::string_view encoding, - std::string_view baseURL); + const std::string& MIMEType, + const std::string& encoding, + const std::string& baseURL); - void loadHTMLString(std::string_view string, std::string_view baseURL); + void loadHTMLString(const std::string& string, const std::string& baseURL); - void loadURL(std::string_view url); - void loadURL(std::string_view url, bool cleanCachedData); + void loadURL(const std::string& url); + void loadURL(const std::string& url, bool cleanCachedData); - void loadFile(std::string_view fileName); + void loadFile(const std::string& fileName); void stopLoading(); @@ -81,7 +79,7 @@ public: void goForward(); - void evaluateJS(std::string_view js); + void evaluateJS(const std::string& js); void setScalesPageToFit(const bool scalesPageToFit); @@ -97,10 +95,10 @@ public: void setBackgroundTransparent(); - static bool shouldStartLoading(const int viewTag, std::string_view url); - static void didFinishLoading(const int viewTag, std::string_view url); - static void didFailLoading(const int viewTag, std::string_view url); - static void onJsCallback(const int viewTag, std::string_view message); + static bool shouldStartLoading(const int viewTag, const std::string& url); + static void didFinishLoading(const int viewTag, const std::string& url); + static void didFailLoading(const int viewTag, const std::string& url); + static void onJsCallback(const int viewTag, const std::string& message); private: int _viewTag; diff --git a/cocos/ui/UIWebView/UIWebViewImpl-ios.h b/cocos/ui/UIWebView/UIWebViewImpl-ios.h index 0d9294fd54..03fe18cc86 100644 --- a/cocos/ui/UIWebView/UIWebViewImpl-ios.h +++ b/cocos/ui/UIWebView/UIWebViewImpl-ios.h @@ -27,8 +27,6 @@ #include #include -#include -#include @class UIWebViewWrapper; @@ -51,19 +49,19 @@ public: virtual ~WebViewImpl(); - void setJavascriptInterfaceScheme(std::string_view scheme); + void setJavascriptInterfaceScheme(const std::string& scheme); void loadData(const cocos2d::Data& data, - std::string_view MIMEType, - std::string_view encoding, - std::string_view baseURL); + const std::string& MIMEType, + const std::string& encoding, + const std::string& baseURL); - void loadHTMLString(std::string_view string, std::string_view baseURL); + void loadHTMLString(const std::string& string, const std::string& baseURL); - void loadURL(std::string_view url); - void loadURL(std::string_view url, bool cleanCachedData); + void loadURL(const std::string& url); + void loadURL(const std::string& url, bool cleanCachedData); - void loadFile(std::string_view fileName); + void loadFile(const std::string& fileName); void stopLoading(); @@ -77,7 +75,7 @@ public: void goForward(); - void evaluateJS(std::string_view js); + void evaluateJS(const std::string& js); void setScalesPageToFit(const bool scalesPageToFit); diff --git a/cocos/ui/UIWebView/UIWebViewImpl-ios.mm b/cocos/ui/UIWebView/UIWebViewImpl-ios.mm index 7c1979f0a6..e2c448249e 100644 --- a/cocos/ui/UIWebView/UIWebViewImpl-ios.mm +++ b/cocos/ui/UIWebView/UIWebViewImpl-ios.mm @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2014-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -35,10 +35,10 @@ #include "platform/CCFileUtils.h" @interface UIWebViewWrapper : NSObject -@property(nonatomic) std::function shouldStartLoading; -@property(nonatomic) std::function didFinishLoading; -@property(nonatomic) std::function didFailLoading; -@property(nonatomic) std::function onJsCallback; +@property (nonatomic) std::function shouldStartLoading; +@property (nonatomic) std::function didFinishLoading; +@property (nonatomic) std::function didFailLoading; +@property (nonatomic) std::function onJsCallback; @property(nonatomic, readonly, getter=canGoBack) BOOL canGoBack; @property(nonatomic, readonly, getter=canGoForward) BOOL canGoForward; @@ -57,24 +57,21 @@ - (void)setFrameWithX:(float)x y:(float)y width:(float)width height:(float)height; -- (void)setJavascriptInterfaceScheme:(std::string_view)scheme; +- (void)setJavascriptInterfaceScheme:(const std::string &)scheme; -- (void)loadData:(std::string_view)data - MIMEType:(std::string_view)MIMEType - textEncodingName:(std::string_view)encodingName - baseURL:(std::string_view)baseURL; +- (void)loadData:(const std::string &)data MIMEType:(const std::string &)MIMEType textEncodingName:(const std::string &)encodingName baseURL:(const std::string &)baseURL; -- (void)loadHTMLString:(std::string_view)string baseURL:(std::string_view)baseURL; +- (void)loadHTMLString:(const std::string &)string baseURL:(const std::string &)baseURL; -- (void)loadUrl:(std::string_view)urlString cleanCachedData:(BOOL)needCleanCachedData; +- (void)loadUrl:(const std::string &)urlString cleanCachedData:(BOOL) needCleanCachedData; -- (void)loadFile:(std::string_view)filePath; +- (void)loadFile:(const std::string &)filePath; - (void)stopLoading; - (void)reload; -- (void)evaluateJS:(std::string_view)js; +- (void)evaluateJS:(const std::string &)js; - (void)goBack; @@ -83,236 +80,178 @@ - (void)setScalesPageToFit:(const bool)scalesPageToFit; @end -@interface UIWebViewWrapper () -@property(nonatomic) WKWebView* wkWebView; -@property(nonatomic, copy) NSString* jsScheme; +@interface UIWebViewWrapper () +@property(nonatomic) WKWebView *wkWebView; + +@property(nonatomic, copy) NSString *jsScheme; @end @implementation UIWebViewWrapper { + } -+ (instancetype)newWebViewWrapper -{ ++ (instancetype) newWebViewWrapper { return [[self alloc] init]; } -- (instancetype)init -{ +- (instancetype)init { self = [super init]; - if (self) - { - self.wkWebView = nil; + if (self) { + self.wkWebView = nil; self.shouldStartLoading = nullptr; - self.didFinishLoading = nullptr; - self.didFailLoading = nullptr; + self.didFinishLoading = nullptr; + self.didFailLoading = nullptr; } return self; } -- (void)dealloc -{ - self.wkWebView.UIDelegate = nil; +- (void)dealloc { + self.wkWebView.UIDelegate = nil; self.wkWebView.navigationDelegate = nil; [self.wkWebView removeFromSuperview]; [self.wkWebView release]; self.wkWebView = nil; - self.jsScheme = nil; + self.jsScheme = nil; [super dealloc]; } -- (void)setupWebView -{ - if (!self.wkWebView) - { - self.wkWebView = [[WKWebView alloc] init]; - self.wkWebView.UIDelegate = self; +- (void)setupWebView { + if (!self.wkWebView) { + self.wkWebView = [[WKWebView alloc] init]; + self.wkWebView.UIDelegate = self; self.wkWebView.navigationDelegate = self; } - if (!self.wkWebView.superview) - { - auto view = cocos2d::Director::getInstance()->getOpenGLView(); - auto eaglview = (CCEAGLView*)view->getEAGLView(); + if (!self.wkWebView.superview) { + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + auto eaglview = (CCEAGLView *) view->getEAGLView(); [eaglview addSubview:self.wkWebView]; } } -- (void)setVisible:(bool)visible -{ - if (!self.wkWebView) - { - [self setupWebView]; - } +- (void)setVisible:(bool)visible { + if (!self.wkWebView) {[self setupWebView];} self.wkWebView.hidden = !visible; } -- (void)setBounces:(bool)bounces -{ - self.wkWebView.scrollView.bounces = bounces; +- (void)setBounces:(bool)bounces { + self.wkWebView.scrollView.bounces = bounces; } -- (void)setOpacityWebView:(float)opacity -{ - if (!self.wkWebView) - { - [self setupWebView]; - } +- (void)setOpacityWebView:(float)opacity { + if (!self.wkWebView) { [self setupWebView]; } self.wkWebView.alpha = opacity; [self.wkWebView setOpaque:YES]; } -- (float)getOpacityWebView -{ +-(float) getOpacityWebView{ return self.wkWebView.alpha; } -- (void)setBackgroundTransparent -{ - if (!self.wkWebView) - { - [self setupWebView]; - } +-(void) setBackgroundTransparent{ + if (!self.wkWebView) {[self setupWebView];} [self.wkWebView setOpaque:NO]; [self.wkWebView setBackgroundColor:[UIColor clearColor]]; } -- (void)setFrameWithX:(float)x y:(float)y width:(float)width height:(float)height -{ - if (!self.wkWebView) - { - [self setupWebView]; - } +- (void)setFrameWithX:(float)x y:(float)y width:(float)width height:(float)height { + if (!self.wkWebView) {[self setupWebView];} CGRect newFrame = CGRectMake(x, y, width, height); - if (!CGRectEqualToRect(self.wkWebView.frame, newFrame)) - { + if (!CGRectEqualToRect(self.wkWebView.frame, newFrame)) { self.wkWebView.frame = CGRectMake(x, y, width, height); } } -- (void)setJavascriptInterfaceScheme:(std::string_view)scheme -{ - self.jsScheme = @(scheme.data()); +- (void)setJavascriptInterfaceScheme:(const std::string &)scheme { + self.jsScheme = @(scheme.c_str()); } -- (void)loadData:(std::string_view)data - MIMEType:(std::string_view)MIMEType - textEncodingName:(std::string_view)encodingName - baseURL:(std::string_view)baseURL -{ +- (void)loadData:(const std::string &)data MIMEType:(const std::string &)MIMEType textEncodingName:(const std::string &)encodingName baseURL:(const std::string &)baseURL { auto path = [[NSBundle mainBundle] resourcePath]; - path = [path stringByAppendingPathComponent:@(baseURL.data())]; - auto url = [NSURL fileURLWithPath:path]; + path = [path stringByAppendingPathComponent:@(baseURL.c_str() )]; + auto url = [NSURL fileURLWithPath:path]; - [self.wkWebView loadData:[NSData dataWithBytes:data.data() length:data.length()] - MIMEType:@(MIMEType.data()) - characterEncodingName:@(encodingName.data()) - baseURL:url]; + [self.wkWebView loadData:[NSData dataWithBytes:data.c_str() length:data.length()] + MIMEType:@(MIMEType.c_str()) + characterEncodingName:@(encodingName.c_str()) + baseURL:url]; } -- (void)loadHTMLString:(std::string_view)string baseURL:(std::string_view)baseURL -{ - if (!self.wkWebView) - { - [self setupWebView]; - } +- (void)loadHTMLString:(const std::string &)string baseURL:(const std::string &)baseURL { + if (!self.wkWebView) {[self setupWebView];} auto path = [[NSBundle mainBundle] resourcePath]; - path = [path stringByAppendingPathComponent:@(baseURL.data())]; - auto url = [NSURL fileURLWithPath:path]; - [self.wkWebView loadHTMLString:@(string.data()) baseURL:url]; + path = [path stringByAppendingPathComponent:@(baseURL.c_str() )]; + auto url = [NSURL fileURLWithPath:path]; + [self.wkWebView loadHTMLString:@(string.c_str()) baseURL:url]; } -- (void)loadUrl:(std::string_view)urlString cleanCachedData:(BOOL)needCleanCachedData -{ - if (!self.wkWebView) - { - [self setupWebView]; - } - NSURL* url = [NSURL URLWithString:@(urlString.data())]; +- (void)loadUrl:(const std::string &)urlString cleanCachedData:(BOOL) needCleanCachedData { + if (!self.wkWebView) {[self setupWebView];} + NSURL *url = [NSURL URLWithString:@(urlString.c_str())]; - NSURLRequest* request = nil; + NSURLRequest *request = nil; if (needCleanCachedData) - request = [NSURLRequest requestWithURL:url - cachePolicy:NSURLRequestReloadIgnoringLocalCacheData - timeoutInterval:60]; + request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60]; else request = [NSURLRequest requestWithURL:url]; [self.wkWebView loadRequest:request]; } -- (void)loadFile:(std::string_view)filePath -{ - if (!self.wkWebView) - { - [self setupWebView]; - } - NSURL* url = [NSURL fileURLWithPath:@(filePath.data())]; - NSURLRequest* request = [NSURLRequest requestWithURL:url]; +- (void)loadFile:(const std::string &)filePath { + if (!self.wkWebView) {[self setupWebView];} + NSURL *url = [NSURL fileURLWithPath:@(filePath.c_str())]; + NSURLRequest *request = [NSURLRequest requestWithURL:url]; [self.wkWebView loadRequest:request]; } -- (void)stopLoading -{ +- (void)stopLoading { [self.wkWebView stopLoading]; } -- (void)reload -{ +- (void)reload { [self.wkWebView reload]; } -- (BOOL)canGoForward -{ +- (BOOL)canGoForward { return self.wkWebView.canGoForward; } -- (BOOL)canGoBack -{ +- (BOOL)canGoBack { return self.wkWebView.canGoBack; } -- (void)goBack -{ +- (void)goBack { [self.wkWebView goBack]; } -- (void)goForward -{ +- (void)goForward { [self.wkWebView goForward]; } -- (void)evaluateJS:(std::string_view)js -{ - if (!self.wkWebView) - { - [self setupWebView]; - } - [self.wkWebView evaluateJavaScript:@(js.data()) completionHandler:nil]; +- (void)evaluateJS:(const std::string &)js { + if (!self.wkWebView) {[self setupWebView];} + [self.wkWebView evaluateJavaScript:@(js.c_str()) completionHandler:nil]; } -- (void)setScalesPageToFit:(const bool)scalesPageToFit -{ - // TODO: there is not corresponding API in WK. - // https://stackoverflow.com/questions/26295277/wkwebview-equivalent-for-uiwebviews-scalespagetofit/43048514 seems - // has a solution, but it doesn't support setting it dynamically. If we want to set this feature dynamically, then - // it will be too complex. +- (void)setScalesPageToFit:(const bool)scalesPageToFit { +// TODO: there is not corresponding API in WK. +// https://stackoverflow.com/questions/26295277/wkwebview-equivalent-for-uiwebviews-scalespagetofit/43048514 seems has a solution, +// but it doesn't support setting it dynamically. If we want to set this feature dynamically, then it will be too complex. } + + #pragma mark - WKNavigationDelegate -- (void)webView:(WKWebView*)webView - decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction - decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler -{ - NSString* url = [[[navigationAction request] URL] absoluteString]; - if ([[webView.URL scheme] isEqualToString:self.jsScheme]) - { +- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { + NSString *url = [[[navigationAction request] URL] absoluteString]; + if ([[webView.URL scheme] isEqualToString:self.jsScheme]) { self.onJsCallback([url UTF8String]); decisionHandler(WKNavigationActionPolicyCancel); return; } - if (self.shouldStartLoading && url) - { - if (self.shouldStartLoading([url UTF8String])) + if (self.shouldStartLoading && url) { + if (self.shouldStartLoading([url UTF8String]) ) decisionHandler(WKNavigationActionPolicyAllow); else decisionHandler(WKNavigationActionPolicyCancel); @@ -323,22 +262,17 @@ decisionHandler(WKNavigationActionPolicyAllow); } -- (void)webView:(WKWebView*)webView didFinishNavigation:(WKNavigation*)navigation -{ - if (self.didFinishLoading) - { - NSString* url = [webView.URL absoluteString]; +- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { + if (self.didFinishLoading) { + NSString *url = [webView.URL absoluteString]; self.didFinishLoading([url UTF8String]); } } -- (void)webView:(WKWebView*)webView didFailProvisionalNavigation:(WKNavigation*)navigation withError:(NSError*)error -{ - if (self.didFailLoading) - { - NSString* errorInfo = error.userInfo[NSURLErrorFailingURLStringErrorKey]; - if (errorInfo) - { +- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error { + if (self.didFailLoading) { + NSString *errorInfo = error.userInfo[NSURLErrorFailingURLStringErrorKey]; + if (errorInfo) { self.didFailLoading([errorInfo UTF8String]); } } @@ -347,196 +281,168 @@ #pragma WKUIDelegate // Implement js alert function. -- (void)webView:(WKWebView*)webView - runJavaScriptAlertPanelWithMessage:(NSString*)message - initiatedByFrame:(WKFrameInfo*)frame - completionHandler:(void (^)())completionHandler +- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)())completionHandler { - UIAlertController* alertController = [UIAlertController alertControllerWithTitle:message + UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert]; [alertController addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel - handler:^(UIAlertAction* action) { - completionHandler(); + handler:^(UIAlertAction *action) { + completionHandler(); }]]; auto rootViewController = [UIApplication sharedApplication].windows[0].rootViewController; - [rootViewController presentViewController:alertController - animated:YES - completion:^{ - }]; + [rootViewController presentViewController:alertController animated:YES completion:^{}]; } @end -namespace cocos2d -{ -namespace ui -{ -WebViewImpl::WebViewImpl(WebView* webView) : _uiWebViewWrapper([UIWebViewWrapper newWebViewWrapper]), _webView(webView) -{ +namespace cocos2d { +namespace ui{ + +WebViewImpl::WebViewImpl(WebView *webView) + : _uiWebViewWrapper([UIWebViewWrapper newWebViewWrapper]), + _webView(webView) { + _uiWebViewWrapper.shouldStartLoading = [this](std::string url) { - if (this->_webView->_onShouldStartLoading) - { + if (this->_webView->_onShouldStartLoading) { return this->_webView->_onShouldStartLoading(this->_webView, url); } return true; }; _uiWebViewWrapper.didFinishLoading = [this](std::string url) { - if (this->_webView->_onDidFinishLoading) - { + if (this->_webView->_onDidFinishLoading) { this->_webView->_onDidFinishLoading(this->_webView, url); } }; _uiWebViewWrapper.didFailLoading = [this](std::string url) { - if (this->_webView->_onDidFailLoading) - { + if (this->_webView->_onDidFailLoading) { this->_webView->_onDidFailLoading(this->_webView, url); } }; _uiWebViewWrapper.onJsCallback = [this](std::string url) { - if (this->_webView->_onJSCallback) - { + if (this->_webView->_onJSCallback) { this->_webView->_onJSCallback(this->_webView, url); } }; } -WebViewImpl::~WebViewImpl() -{ +WebViewImpl::~WebViewImpl(){ [_uiWebViewWrapper release]; _uiWebViewWrapper = nullptr; } -void WebViewImpl::setJavascriptInterfaceScheme(std::string_view scheme) -{ +void WebViewImpl::setJavascriptInterfaceScheme(const std::string &scheme) { [_uiWebViewWrapper setJavascriptInterfaceScheme:scheme]; } -void WebViewImpl::loadData(const Data& data, - std::string_view MIMEType, - std::string_view encoding, - std::string_view baseURL) -{ - - std::string dataString(reinterpret_cast(data.getBytes()), static_cast(data.getSize())); +void WebViewImpl::loadData(const Data &data, + const std::string &MIMEType, + const std::string &encoding, + const std::string &baseURL) { + + std::string dataString(reinterpret_cast(data.getBytes()), static_cast(data.getSize())); [_uiWebViewWrapper loadData:dataString MIMEType:MIMEType textEncodingName:encoding baseURL:baseURL]; } -void WebViewImpl::loadHTMLString(std::string_view string, std::string_view baseURL) -{ +void WebViewImpl::loadHTMLString(const std::string &string, const std::string &baseURL) { [_uiWebViewWrapper loadHTMLString:string baseURL:baseURL]; } -void WebViewImpl::loadURL(std::string_view url) -{ +void WebViewImpl::loadURL(const std::string &url) { this->loadURL(url, false); } -void WebViewImpl::loadURL(std::string_view url, bool cleanCachedData) -{ +void WebViewImpl::loadURL(const std::string &url, bool cleanCachedData) { [_uiWebViewWrapper loadUrl:url cleanCachedData:cleanCachedData]; } -void WebViewImpl::loadFile(std::string_view fileName) -{ +void WebViewImpl::loadFile(const std::string &fileName) { auto fullPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(fileName); [_uiWebViewWrapper loadFile:fullPath]; } -void WebViewImpl::stopLoading() -{ +void WebViewImpl::stopLoading() { [_uiWebViewWrapper stopLoading]; } -void WebViewImpl::reload() -{ +void WebViewImpl::reload() { [_uiWebViewWrapper reload]; } -bool WebViewImpl::canGoBack() -{ +bool WebViewImpl::canGoBack() { return _uiWebViewWrapper.canGoBack; } -bool WebViewImpl::canGoForward() -{ +bool WebViewImpl::canGoForward() { return _uiWebViewWrapper.canGoForward; } -void WebViewImpl::goBack() -{ +void WebViewImpl::goBack() { [_uiWebViewWrapper goBack]; } -void WebViewImpl::goForward() -{ +void WebViewImpl::goForward() { [_uiWebViewWrapper goForward]; } -void WebViewImpl::evaluateJS(std::string_view js) -{ +void WebViewImpl::evaluateJS(const std::string &js) { [_uiWebViewWrapper evaluateJS:js]; } -void WebViewImpl::setBounces(bool bounces) -{ +void WebViewImpl::setBounces(bool bounces) { [_uiWebViewWrapper setBounces:bounces]; } -void WebViewImpl::setScalesPageToFit(const bool scalesPageToFit) -{ +void WebViewImpl::setScalesPageToFit(const bool scalesPageToFit) { [_uiWebViewWrapper setScalesPageToFit:scalesPageToFit]; } -void WebViewImpl::draw(cocos2d::Renderer* renderer, cocos2d::Mat4 const& transform, uint32_t flags) -{ - if (flags & cocos2d::Node::FLAGS_TRANSFORM_DIRTY) - { - - auto director = cocos2d::Director::getInstance(); - auto glView = director->getOpenGLView(); +void WebViewImpl::draw(cocos2d::Renderer *renderer, cocos2d::Mat4 const &transform, uint32_t flags) { + if (flags & cocos2d::Node::FLAGS_TRANSFORM_DIRTY) { + + auto director = cocos2d::Director::getInstance(); + auto glView = director->getOpenGLView(); auto frameSize = glView->getFrameSize(); - - auto scaleFactor = [static_cast(glView->getEAGLView()) contentScaleFactor]; + + auto scaleFactor = [static_cast(glView->getEAGLView()) contentScaleFactor]; auto winSize = director->getWinSize(); auto leftBottom = this->_webView->convertToWorldSpace(cocos2d::Vec2::ZERO); - auto rightTop = this->_webView->convertToWorldSpace( - cocos2d::Vec2(this->_webView->getContentSize().width, this->_webView->getContentSize().height)); + auto rightTop = this->_webView->convertToWorldSpace(cocos2d::Vec2(this->_webView->getContentSize().width, this->_webView->getContentSize().height)); - auto x = (frameSize.width / 2 + (leftBottom.x - winSize.width / 2) * glView->getScaleX()) / scaleFactor; - auto y = (frameSize.height / 2 - (rightTop.y - winSize.height / 2) * glView->getScaleY()) / scaleFactor; - auto width = (rightTop.x - leftBottom.x) * glView->getScaleX() / scaleFactor; + auto x = (frameSize.width / 2 + (leftBottom.x - winSize.width / 2) * glView->getScaleX()) / scaleFactor; + auto y = (frameSize.height / 2 - (rightTop.y - winSize.height / 2) * glView->getScaleY()) / scaleFactor; + auto width = (rightTop.x - leftBottom.x) * glView->getScaleX() / scaleFactor; auto height = (rightTop.y - leftBottom.y) * glView->getScaleY() / scaleFactor; - [_uiWebViewWrapper setFrameWithX:x y:y width:width height:height]; + [_uiWebViewWrapper setFrameWithX:x + y:y + width:width + height:height]; } } -void WebViewImpl::setVisible(bool visible) -{ +void WebViewImpl::setVisible(bool visible){ [_uiWebViewWrapper setVisible:visible]; } - -void WebViewImpl::setOpacityWebView(float opacity) -{ - [_uiWebViewWrapper setOpacityWebView:opacity]; + +void WebViewImpl::setOpacityWebView(float opacity){ + [_uiWebViewWrapper setOpacityWebView: opacity]; } - -float WebViewImpl::getOpacityWebView() const -{ + +float WebViewImpl::getOpacityWebView() const{ return [_uiWebViewWrapper getOpacityWebView]; } -void WebViewImpl::setBackgroundTransparent() -{ +void WebViewImpl::setBackgroundTransparent(){ [_uiWebViewWrapper setBackgroundTransparent]; } -} // namespace ui -} // namespace cocos2d + +} // namespace ui +} //namespace cocos2d diff --git a/cocos/ui/UIWebView/UIWebViewImpl-win32.cpp b/cocos/ui/UIWebView/UIWebViewImpl-win32.cpp index 4ec42ecfb0..89ecd6d052 100644 --- a/cocos/ui/UIWebView/UIWebViewImpl-win32.cpp +++ b/cocos/ui/UIWebView/UIWebViewImpl-win32.cpp @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 && defined(ADXE_HAVE_WEBVIEW2) +#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 # include "UIWebViewImpl-win32.h" # include "UIWebView.h" @@ -57,9 +57,9 @@ USING_NS_CC; using namespace rapidjson; -using msg_cb_t = std::function; +using msg_cb_t = std::function; -inline std::string htmlFromUri(std::string_view s) +inline std::string htmlFromUri(const std::string& s) { if (s.substr(0, 15) == "data:text/html,") { @@ -139,14 +139,14 @@ inline int jsonUnescape(const char* s, size_t n, char* out) // The following is a special case, where the exact json string is not returned due // to how rapidjson re-creates the nested object, original: "{"bar": 1}", parsed result: "{"bar":1}" // assert(jsonParse(R"({"foo": {"bar": 1}})", "foo", -1) == R"({"bar":1})"); -inline std::string jsonParse(std::string_view s, std::string_view key, const int index) +inline std::string jsonParse(const std::string& s, const std::string& key, const int index) { const char* value = nullptr; size_t value_sz{}; StringBuffer sb; Writer writer(sb); Document d; - d.Parse(s.data()); + d.Parse(s.c_str()); if (key.empty() && index > -1) { if (d.IsArray()) @@ -162,7 +162,7 @@ inline std::string jsonParse(std::string_view s, std::string_view key, const int } else { - auto&& fieldItr = d.FindMember(key.data()); + auto&& fieldItr = d.FindMember(key.c_str()); if (fieldItr != d.MemberEnd()) { auto&& jsonValue = fieldItr->value; @@ -214,12 +214,12 @@ static std::string getUriStringFromArgs(ArgType* args) return {}; } -static std::string getDataURI(std::string_view data, std::string_view mime_type) +static std::string getDataURI(const std::string& data, const std::string& mime_type) { char* encodedData; cocos2d::base64Encode(reinterpret_cast(data.data()), static_cast(data.size()), &encodedData); - return std::string{"data:"}.append(mime_type).append(";base64,").append(utils::urlEncode(encodedData)); + return "data:" + mime_type + ";base64," + utils::urlEncode(encodedData); } static double getDeviceScaleFactor() @@ -250,24 +250,24 @@ class Win32WebControl public: Win32WebControl(); - bool createWebView(const std::function& shouldStartLoading, - const std::function& didFinishLoading, - const std::function& didFailLoading, - const std::function& onJsCallback); + bool createWebView(const std::function& shouldStartLoading, + const std::function& didFinishLoading, + const std::function& didFailLoading, + const std::function& onJsCallback); void removeWebView(); void setWebViewRect(const int left, const int top, const int width, const int height); - void setJavascriptInterfaceScheme(std::string_view scheme); - void loadHTMLString(std::string_view html, std::string_view baseURL); - void loadURL(std::string_view url, bool cleanCachedData); - void loadFile(std::string_view filePath); + void setJavascriptInterfaceScheme(const std::string& scheme); + void loadHTMLString(const std::string& html, const std::string& baseURL); + void loadURL(const std::string& url, bool cleanCachedData); + void loadFile(const std::string& filePath); void stopLoading(); void reload() const; bool canGoBack() const; bool canGoForward() const; void goBack() const; void goForward() const; - void evaluateJS(std::string_view js); + void evaluateJS(const std::string& js); void setScalesPageToFit(const bool scalesPageToFit); void setWebViewVisible(const bool visible) const; void setBounces(bool bounces); @@ -286,19 +286,19 @@ private: std::string m_jsScheme; bool _scalesPageToFit{}; - std::function _shouldStartLoading; - std::function _didFinishLoading; - std::function _didFailLoading; - std::function _onJsCallback; + std::function _shouldStartLoading; + std::function _didFinishLoading; + std::function _didFailLoading; + std::function _onJsCallback; static bool s_isInitialized; static void lazyInit(); - static LPWSTR to_lpwstr(std::string_view s) + static LPWSTR to_lpwstr(const std::string s) { - const int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), -1, NULL, 0); + const int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, NULL, 0); auto* ws = new wchar_t[n]; - MultiByteToWideChar(CP_UTF8, 0, s.data(), -1, ws, n); + MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, ws, n); return ws; } @@ -325,7 +325,7 @@ private: m_webview->AddRef(); flag.clear(); }, - [this](std::string_view url) -> bool { + [this](const std::string& url) -> bool { const auto scheme = url.substr(0, url.find_first_of(':')); if (scheme == m_jsScheme) { @@ -358,7 +358,7 @@ private: if (_didFailLoading) _didFailLoading(result); }, - [this](std::string_view url) { loadURL(url, false); })); + [this](const std::string& url) { loadURL(url, false); })); if (res != S_OK) { @@ -386,28 +386,28 @@ private: m_controller->put_Bounds(bounds); } - void navigate(std::string_view url) + void navigate(const std::string url) { auto wurl = to_lpwstr(url); m_webview->Navigate(wurl); delete[] wurl; } - void init(std::string_view js) + void init(const std::string js) { LPCWSTR wjs = to_lpwstr(js); m_webview->AddScriptToExecuteOnDocumentCreated(wjs, nullptr); delete[] wjs; } - void eval(std::string_view js) + void eval(const std::string js) { LPCWSTR wjs = to_lpwstr(js); m_webview->ExecuteScript(wjs, nullptr); delete[] wjs; } - void on_message(std::string_view msg) + void on_message(const std::string msg) { const auto seq = jsonParse(msg, "id", 0); const auto name = jsonParse(msg, "method", 0); @@ -440,10 +440,10 @@ private: webview2_com_handler(HWND hwnd, msg_cb_t msgCb, webview2_com_handler_cb_t cb, - std::function navStartingCallback, + std::function navStartingCallback, std::function navCompleteCallback, std::function navErrorCallback, - std::function loadUrlCallback) + std::function loadUrlCallback) : m_window(hwnd) , m_msgCb(std::move(msgCb)) , m_cb(std::move(cb)) @@ -587,10 +587,10 @@ private: HWND m_window; msg_cb_t m_msgCb; webview2_com_handler_cb_t m_cb; - std::function m_navStartingCallback; + std::function m_navStartingCallback; std::function m_navCompleteCallback; std::function m_navErrorCallback; - std::function m_loadUrlCallback; + std::function m_loadUrlCallback; }; }; @@ -607,7 +607,7 @@ WebViewImpl::WebViewImpl(WebView* webView) : _createSucceeded(false), _systemWeb } _createSucceeded = _systemWebControl->createWebView( - [this](std::string_view url) -> bool { + [this](const std::string& url) -> bool { const auto shouldStartLoading = _webView->getOnShouldStartLoading(); if (shouldStartLoading != nullptr) { @@ -615,21 +615,21 @@ WebViewImpl::WebViewImpl(WebView* webView) : _createSucceeded(false), _systemWeb } return true; }, - [this](std::string_view url) { + [this](const std::string& url) { WebView::ccWebViewCallback didFinishLoading = _webView->getOnDidFinishLoading(); if (didFinishLoading != nullptr) { didFinishLoading(_webView, url); } }, - [this](std::string_view url) { + [this](const std::string& url) { WebView::ccWebViewCallback didFailLoading = _webView->getOnDidFailLoading(); if (didFailLoading != nullptr) { didFailLoading(_webView, url); } }, - [this](std::string_view url) { + [this](const std::string& url) { WebView::ccWebViewCallback onJsCallback = _webView->getOnJSCallback(); if (onJsCallback != nullptr) { @@ -649,9 +649,9 @@ WebViewImpl::~WebViewImpl() } void WebViewImpl::loadData(const Data& data, - std::string_view MIMEType, - std::string_view encoding, - std::string_view baseURL) + const std::string& MIMEType, + const std::string& encoding, + const std::string& baseURL) { if (_createSucceeded) { @@ -662,7 +662,7 @@ void WebViewImpl::loadData(const Data& data, } } -void WebViewImpl::loadHTMLString(std::string_view string, std::string_view baseURL) +void WebViewImpl::loadHTMLString(const std::string& string, const std::string& baseURL) { if (_createSucceeded) { @@ -684,7 +684,7 @@ void WebViewImpl::loadHTMLString(std::string_view string, std::string_view baseU } } -void WebViewImpl::loadURL(std::string_view url, bool cleanCachedData) +void WebViewImpl::loadURL(const std::string& url, bool cleanCachedData) { if (_createSucceeded) { @@ -692,7 +692,7 @@ void WebViewImpl::loadURL(std::string_view url, bool cleanCachedData) } } -void WebViewImpl::loadFile(std::string_view fileName) +void WebViewImpl::loadFile(const std::string& fileName) { if (_createSucceeded) { @@ -751,7 +751,7 @@ void WebViewImpl::goForward() } } -void WebViewImpl::setJavascriptInterfaceScheme(std::string_view scheme) +void WebViewImpl::setJavascriptInterfaceScheme(const std::string& scheme) { if (_createSucceeded) { @@ -759,7 +759,7 @@ void WebViewImpl::setJavascriptInterfaceScheme(std::string_view scheme) } } -void WebViewImpl::evaluateJS(std::string_view js) +void WebViewImpl::evaluateJS(const std::string& js) { if (_createSucceeded) { @@ -838,10 +838,10 @@ Win32WebControl::Win32WebControl() : _shouldStartLoading(nullptr), _didFinishLoa } } -bool Win32WebControl::createWebView(const std::function& shouldStartLoading, - const std::function& didFinishLoading, - const std::function& didFailLoading, - const std::function& onJsCallback) +bool Win32WebControl::createWebView(const std::function& shouldStartLoading, + const std::function& didFinishLoading, + const std::function& didFailLoading, + const std::function& onJsCallback) { bool ret = false; do @@ -905,7 +905,7 @@ bool Win32WebControl::createWebView(const std::function& UpdateWindow(m_window); SetFocus(m_window); - auto cb = [this](std::string_view msg) { on_message(msg); }; + auto cb = [this](const std::string msg) { on_message(msg); }; if (!embed(m_window, false, cb)) { @@ -956,12 +956,12 @@ void Win32WebControl::setWebViewRect(const int left, const int top, const int wi m_controller->put_ZoomFactor(_scalesPageToFit ? getDeviceScaleFactor() : 1.0); } -void Win32WebControl::setJavascriptInterfaceScheme(std::string_view scheme) +void Win32WebControl::setJavascriptInterfaceScheme(const std::string& scheme) { m_jsScheme = scheme; } -void Win32WebControl::loadHTMLString(std::string_view html, std::string_view baseURL) +void Win32WebControl::loadHTMLString(const std::string& html, const std::string& baseURL) { if (!html.empty()) { @@ -971,7 +971,7 @@ void Win32WebControl::loadHTMLString(std::string_view html, std::string_view bas } } -void Win32WebControl::loadURL(std::string_view url, bool cleanCachedData) +void Win32WebControl::loadURL(const std::string& url, bool cleanCachedData) { if (cleanCachedData) { @@ -980,7 +980,7 @@ void Win32WebControl::loadURL(std::string_view url, bool cleanCachedData) navigate(url); } -void Win32WebControl::loadFile(std::string_view filePath) +void Win32WebControl::loadFile(const std::string& filePath) { auto fullPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(filePath); if (fullPath.find("file:///") != 0) @@ -1029,7 +1029,7 @@ void Win32WebControl::goForward() const m_webview->GoForward(); } -void Win32WebControl::evaluateJS(std::string_view js) +void Win32WebControl::evaluateJS(const std::string& js) { eval(js); } diff --git a/cocos/ui/UIWebView/UIWebViewImpl-win32.h b/cocos/ui/UIWebView/UIWebViewImpl-win32.h index 4f56727d17..b963ba4a86 100644 --- a/cocos/ui/UIWebView/UIWebViewImpl-win32.h +++ b/cocos/ui/UIWebView/UIWebViewImpl-win32.h @@ -28,7 +28,7 @@ #include "platform/CCPlatformConfig.h" -#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 && defined(ADXE_HAVE_WEBVIEW2) +#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 # include # include "CCStdC.h" @@ -58,21 +58,21 @@ public: WebViewImpl(cocos2d::ui::WebView* webView); virtual ~WebViewImpl(); - void setJavascriptInterfaceScheme(std::string_view scheme); + void setJavascriptInterfaceScheme(const std::string& scheme); void loadData(const cocos2d::Data& data, - std::string_view MIMEType, - std::string_view encoding, - std::string_view baseURL); - void loadHTMLString(std::string_view string, std::string_view baseURL); - void loadURL(std::string_view url, bool cleanCachedData); - void loadFile(std::string_view fileName); + const std::string& MIMEType, + const std::string& encoding, + const std::string& baseURL); + void loadHTMLString(const std::string& string, const std::string& baseURL); + void loadURL(const std::string& url, bool cleanCachedData); + void loadFile(const std::string& fileName); void stopLoading(); void reload(); bool canGoBack(); bool canGoForward(); void goBack(); void goForward(); - void evaluateJS(std::string_view js); + void evaluateJS(const std::string& js); void setScalesPageToFit(const bool scalesPageToFit); virtual void draw(cocos2d::Renderer* renderer, cocos2d::Mat4 const& transform, uint32_t flags); diff --git a/cocos/ui/UIWidget.h b/cocos/ui/UIWidget.h index 29c9a3786f..98e841c538 100644 --- a/cocos/ui/UIWidget.h +++ b/cocos/ui/UIWidget.h @@ -684,25 +684,25 @@ public: * Set callback name. *@param callbackName A string representation of callback name. */ - void setCallbackName(std::string_view callbackName) { _callbackName = callbackName; } + void setCallbackName(const std::string& callbackName) { _callbackName = callbackName; } /** * Query callback name. *@return The callback name. */ - std::string_view getCallbackName() const { return _callbackName; } + const std::string& getCallbackName() const { return _callbackName; } /** * Set callback type. * @param callbackType A string representation of callback type. */ - void setCallbackType(std::string_view callbackType) { _callbackType = callbackType; } + void setCallbackType(const std::string& callbackType) { _callbackType = callbackType; } /** * Query callback type. *@return Callback type string. */ - std::string_view getCallbackType() const { return _callbackType; } + const std::string& getCallbackType() const { return _callbackType; } /** * Toggle layout component enable. diff --git a/extensions/DragonBones/CCArmatureDisplay.cpp b/extensions/DragonBones/CCArmatureDisplay.cpp index 81c12b564e..5f11f16381 100644 --- a/extensions/DragonBones/CCArmatureDisplay.cpp +++ b/extensions/DragonBones/CCArmatureDisplay.cpp @@ -1,4 +1,4 @@ -#include "CCArmatureDisplay.h" +#include "CCArmatureDisplay.h" #include "CCSlot.h" DRAGONBONES_NAMESPACE_BEGIN @@ -56,7 +56,7 @@ void CCArmatureDisplay::dbUpdate() } } -void CCArmatureDisplay::addDBEventListener(std::string_view type, const std::function& callback) +void CCArmatureDisplay::addDBEventListener(const std::string& type, const std::function& callback) { auto lambda = [callback](cocos2d::EventCustom* event) -> void { callback(static_cast(event->getUserData())); @@ -64,12 +64,13 @@ void CCArmatureDisplay::addDBEventListener(std::string_view type, const std::fun _dispatcher->addCustomEventListener(type, lambda); } -void CCArmatureDisplay::dispatchDBEvent(std::string_view type, EventObject* value) +void CCArmatureDisplay::dispatchDBEvent(const std::string& type, EventObject* value) { _dispatcher->dispatchCustomEvent(type, value); } -void CCArmatureDisplay::removeDBEventListener(std::string_view type, const std::function& callback) +void CCArmatureDisplay::removeDBEventListener(const std::string& type, + const std::function& callback) { // TODO _dispatcher->removeCustomEventListeners(type); diff --git a/extensions/DragonBones/CCArmatureDisplay.h b/extensions/DragonBones/CCArmatureDisplay.h index a055e6add0..2e594a566c 100644 --- a/extensions/DragonBones/CCArmatureDisplay.h +++ b/extensions/DragonBones/CCArmatureDisplay.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -83,19 +83,20 @@ public: /** * @inheritDoc */ - inline virtual bool hasDBEventListener(std::string_view type) const override { return _dispatcher->isEnabled(); } + inline virtual bool hasDBEventListener(const std::string& type) const override { return _dispatcher->isEnabled(); } /** * @inheritDoc */ - virtual void dispatchDBEvent(std::string_view type, EventObject* value) override; + virtual void dispatchDBEvent(const std::string& type, EventObject* value) override; /** * @inheritDoc */ - virtual void addDBEventListener(std::string_view type, const std::function& listener) override; + virtual void addDBEventListener(const std::string& type, + const std::function& listener) override; /** * @inheritDoc */ - virtual void removeDBEventListener(std::string_view type, + virtual void removeDBEventListener(const std::string& type, const std::function& listener) override; /** * @inheritDoc diff --git a/extensions/DragonBones/CCFactory.cpp b/extensions/DragonBones/CCFactory.cpp index ee24fc555c..85c8565d04 100644 --- a/extensions/DragonBones/CCFactory.cpp +++ b/extensions/DragonBones/CCFactory.cpp @@ -1,4 +1,4 @@ -#include "CCFactory.h" +#include "CCFactory.h" #include "CCTextureAtlasData.h" #include "CCArmatureDisplay.h" #include "CCSlot.h" @@ -144,7 +144,7 @@ Slot* CCFactory::_buildSlot(const BuildArmaturePackage& dataPackage, const SlotD return slot; } -DragonBonesData* CCFactory::loadDragonBonesData(std::string_view filePath, std::string_view name, float scale) +DragonBonesData* CCFactory::loadDragonBonesData(const std::string& filePath, const std::string& name, float scale) { if (!name.empty()) { @@ -185,7 +185,7 @@ DragonBonesData* CCFactory::loadDragonBonesData(std::string_view filePath, std:: return nullptr; } -TextureAtlasData* CCFactory::loadTextureAtlasData(std::string_view filePath, std::string_view name, float scale) +TextureAtlasData* CCFactory::loadTextureAtlasData(const std::string& filePath, const std::string& name, float scale) { _prevPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(filePath); const auto data = cocos2d::FileUtils::getInstance()->getStringFromFile(_prevPath); @@ -197,10 +197,10 @@ TextureAtlasData* CCFactory::loadTextureAtlasData(std::string_view filePath, std return static_cast(BaseFactory::parseTextureAtlasData(data.c_str(), nullptr, name, scale)); } -CCArmatureDisplay* CCFactory::buildArmatureDisplay(std::string_view armatureName, - std::string_view dragonBonesName, - std::string_view skinName, - std::string_view textureAtlasName) const +CCArmatureDisplay* CCFactory::buildArmatureDisplay(const std::string& armatureName, + const std::string& dragonBonesName, + const std::string& skinName, + const std::string& textureAtlasName) const { const auto armature = buildArmature(armatureName, dragonBonesName, skinName, textureAtlasName); if (armature != nullptr) @@ -213,7 +213,7 @@ CCArmatureDisplay* CCFactory::buildArmatureDisplay(std::string_view armatureName return nullptr; } -cocos2d::Sprite* CCFactory::getTextureDisplay(std::string_view textureName, std::string_view dragonBonesName) const +cocos2d::Sprite* CCFactory::getTextureDisplay(const std::string& textureName, const std::string& dragonBonesName) const { const auto textureData = static_cast(_getTextureData(dragonBonesName, textureName)); if (textureData != nullptr && textureData->spriteFrame != nullptr) diff --git a/extensions/DragonBones/CCFactory.h b/extensions/DragonBones/CCFactory.h index d4fbfdc4eb..4ffa184008 100644 --- a/extensions/DragonBones/CCFactory.h +++ b/extensions/DragonBones/CCFactory.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -102,9 +102,9 @@ protected: Armature* armature) const override; public: - virtual DragonBonesData* loadDragonBonesData(std::string_view filePath, - std::string_view name = "", - float scale = 1.0f); + virtual DragonBonesData* loadDragonBonesData(const std::string& filePath, + const std::string& name = "", + float scale = 1.0f); /** * - Load and parse a texture atlas data and texture from the local and cache them to the factory. * @param filePath - The file path of texture atlas data. @@ -132,9 +132,9 @@ public: * * @language zh_CN */ - virtual TextureAtlasData* loadTextureAtlasData(std::string_view filePath, - std::string_view name = "", - float scale = 1.0f); + virtual TextureAtlasData* loadTextureAtlasData(const std::string& filePath, + const std::string& name = "", + float scale = 1.0f); /** * - Create a armature from cached DragonBonesData instances and TextureAtlasData instances, then use the {@link * #clock} to update it. The difference is that the armature created by {@link #buildArmature} is not WorldClock @@ -168,10 +168,10 @@ public: * * @language zh_CN */ - virtual CCArmatureDisplay* buildArmatureDisplay(std::string_view armatureName, - std::string_view dragonBonesName = "", - std::string_view skinName = "", - std::string_view textureAtlasName = "") const; + virtual CCArmatureDisplay* buildArmatureDisplay(const std::string& armatureName, + const std::string& dragonBonesName = "", + const std::string& skinName = "", + const std::string& textureAtlasName = "") const; /** * - Create the display object with the specified texture. * @param textureName - The texture data name. @@ -186,8 +186,8 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - virtual cocos2d::Sprite* getTextureDisplay(std::string_view textureName, - std::string_view dragonBonesName = "") const; + virtual cocos2d::Sprite* getTextureDisplay(const std::string& textureName, + const std::string& dragonBonesName = "") const; /** * - A global sound event manager. * Sound events can be listened to uniformly from the manager. diff --git a/extensions/DragonBones/animation/Animation.cpp b/extensions/DragonBones/animation/Animation.cpp index 20dd91bafd..56de838922 100644 --- a/extensions/DragonBones/animation/Animation.cpp +++ b/extensions/DragonBones/animation/Animation.cpp @@ -1,4 +1,4 @@ -#include "Animation.h" +#include "Animation.h" #include "../model/DisplayData.h" #include "../model/AnimationConfig.h" #include "../model/AnimationData.h" @@ -216,7 +216,7 @@ void Animation::reset() _lastAnimationState = nullptr; } -void Animation::stop(std::string_view animationName) +void Animation::stop(const std::string& animationName) { if (!animationName.empty()) { @@ -384,7 +384,7 @@ AnimationState* Animation::playConfig(AnimationConfig* animationConfig) return animationState; } -AnimationState* Animation::play(std::string_view animationName, int playTimes) +AnimationState* Animation::play(const std::string& animationName, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; @@ -418,18 +418,18 @@ AnimationState* Animation::play(std::string_view animationName, int playTimes) return _lastAnimationState; } #ifdef EGRET_WASM -AnimationState* Animation::fadeIn(std::string_view animationName, +AnimationState* Animation::fadeIn(const std::string& animationName, float fadeInTime, int playTimes, int layer, - std::string_view group, + const std::string& group, int fadeOutMode /*AnimationFadeOutMode*/ #else -AnimationState* Animation::fadeIn(std::string_view animationName, +AnimationState* Animation::fadeIn(const std::string& animationName, float fadeInTime, int playTimes, int layer, - std::string_view group, + const std::string& group, AnimationFadeOutMode fadeOutMode #endif // EGRET_WASM ) @@ -445,7 +445,7 @@ AnimationState* Animation::fadeIn(std::string_view animationName, return playConfig(_animationConfig); } -AnimationState* Animation::gotoAndPlayByTime(std::string_view animationName, float time, int playTimes) +AnimationState* Animation::gotoAndPlayByTime(const std::string& animationName, float time, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; @@ -457,7 +457,7 @@ AnimationState* Animation::gotoAndPlayByTime(std::string_view animationName, flo return playConfig(_animationConfig); } -AnimationState* Animation::gotoAndPlayByFrame(std::string_view animationName, unsigned frame, int playTimes) +AnimationState* Animation::gotoAndPlayByFrame(const std::string& animationName, unsigned frame, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; @@ -474,7 +474,7 @@ AnimationState* Animation::gotoAndPlayByFrame(std::string_view animationName, un return playConfig(_animationConfig); } -AnimationState* Animation::gotoAndPlayByProgress(std::string_view animationName, float progress, int playTimes) +AnimationState* Animation::gotoAndPlayByProgress(const std::string& animationName, float progress, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; @@ -491,7 +491,7 @@ AnimationState* Animation::gotoAndPlayByProgress(std::string_view animationName, return playConfig(_animationConfig); } -AnimationState* Animation::gotoAndStopByTime(std::string_view animationName, float time) +AnimationState* Animation::gotoAndStopByTime(const std::string& animationName, float time) { const auto animationState = gotoAndPlayByTime(animationName, time, 1); if (animationState != nullptr) @@ -502,7 +502,7 @@ AnimationState* Animation::gotoAndStopByTime(std::string_view animationName, flo return animationState; } -AnimationState* Animation::gotoAndStopByFrame(std::string_view animationName, unsigned frame) +AnimationState* Animation::gotoAndStopByFrame(const std::string& animationName, unsigned frame) { const auto animationState = gotoAndPlayByFrame(animationName, frame, 1); if (animationState != nullptr) @@ -513,7 +513,7 @@ AnimationState* Animation::gotoAndStopByFrame(std::string_view animationName, un return animationState; } -AnimationState* Animation::gotoAndStopByProgress(std::string_view animationName, float progress) +AnimationState* Animation::gotoAndStopByProgress(const std::string& animationName, float progress) { const auto animationState = gotoAndPlayByProgress(animationName, progress, 1); if (animationState != nullptr) @@ -524,7 +524,7 @@ AnimationState* Animation::gotoAndStopByProgress(std::string_view animationName, return animationState; } -AnimationState* Animation::getState(std::string_view animationName) const +AnimationState* Animation::getState(const std::string& animationName) const { int i = _animationStates.size(); while (i--) @@ -539,7 +539,7 @@ AnimationState* Animation::getState(std::string_view animationName) const return nullptr; } -bool Animation::hasAnimation(std::string_view animationName) const +bool Animation::hasAnimation(const std::string& animationName) const { return _animations.find(animationName) != _animations.end(); } @@ -570,7 +570,7 @@ bool Animation::isCompleted() const return !_animationStates.empty(); } -std::string_view Animation::getLastAnimationName() const +const std::string& Animation::getLastAnimationName() const { if (_lastAnimationState != nullptr) { @@ -581,7 +581,7 @@ std::string_view Animation::getLastAnimationName() const return DEFAULT_NAME; } -void Animation::setAnimations(const hlookup::string_map& value) +void Animation::setAnimations(const std::map& value) { if (_animations == value) { diff --git a/extensions/DragonBones/animation/Animation.h b/extensions/DragonBones/animation/Animation.h index 524ade25fb..33927b75ab 100644 --- a/extensions/DragonBones/animation/Animation.h +++ b/extensions/DragonBones/animation/Animation.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -64,7 +64,7 @@ private: float _inheritTimeScale; std::vector _animationNames; std::vector _animationStates; - hlookup::string_map _animations; + std::map _animations; Armature* _armature; AnimationConfig* _animationConfig; AnimationState* _lastAnimationState; @@ -115,7 +115,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - void stop(std::string_view animationName); + void stop(const std::string& animationName); /** * - Play animation with a specific animation config. * The API is still in the experimental phase and may encounter bugs or stability or compatibility issues when used. @@ -166,7 +166,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - AnimationState* play(std::string_view animationName = "", int playTimes = -1); + AnimationState* play(const std::string& animationName = "", int playTimes = -1); /** * - Fade in a specific animation. * @param animationName - The name of animation data. @@ -211,11 +211,11 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* fadeIn(std::string_view animationName, + AnimationState* fadeIn(const std::string& animationName, float fadeInTime = -1.f, int playTimes = -1, int layer = 0, - std::string_view group = "", + const std::string& group = "", AnimationFadeOutMode fadeOutMode = AnimationFadeOutMode::SameLayerAndGroup); /** * - Play a specific animation from the specific time. @@ -236,7 +236,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* gotoAndPlayByTime(std::string_view animationName, float time = 0.f, int playTimes = -1); + AnimationState* gotoAndPlayByTime(const std::string& animationName, float time = 0.f, int playTimes = -1); /** * - Play a specific animation from the specific frame. * @param animationName - The name of animation data. @@ -256,7 +256,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* gotoAndPlayByFrame(std::string_view animationName, unsigned frame = 0, int playTimes = -1); + AnimationState* gotoAndPlayByFrame(const std::string& animationName, unsigned frame = 0, int playTimes = -1); /** * - Play a specific animation from the specific progress. * @param animationName - The name of animation data. @@ -276,7 +276,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* gotoAndPlayByProgress(std::string_view animationName, float progress = 0.f, int playTimes = -1); + AnimationState* gotoAndPlayByProgress(const std::string& animationName, float progress = 0.f, int playTimes = -1); /** * - Stop a specific animation at the specific time. * @param animationName - The name of animation data. @@ -293,7 +293,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* gotoAndStopByTime(std::string_view animationName, float time = 0.f); + AnimationState* gotoAndStopByTime(const std::string& animationName, float time = 0.f); /** * - Stop a specific animation at the specific frame. * @param animationName - The name of animation data. @@ -310,7 +310,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* gotoAndStopByFrame(std::string_view animationName, unsigned frame = 0); + AnimationState* gotoAndStopByFrame(const std::string& animationName, unsigned frame = 0); /** * - Stop a specific animation at the specific progress. * @param animationName - The name of animation data. @@ -327,7 +327,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* gotoAndStopByProgress(std::string_view animationName, float progress = 0.f); + AnimationState* gotoAndStopByProgress(const std::string& animationName, float progress = 0.f); /** * - Get a specific animation state. * @param animationName - The name of animation state. @@ -354,7 +354,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - AnimationState* getState(std::string_view animationName) const; + AnimationState* getState(const std::string& animationName) const; /** * - Check whether a specific animation data is included. * @param animationName - The name of animation data. @@ -369,7 +369,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - bool hasAnimation(std::string_view animationName) const; + bool hasAnimation(const std::string& animationName) const; /** * - Get all the animation states. * @version DragonBones 5.1 @@ -419,7 +419,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - std::string_view getLastAnimationName() const; + const std::string& getLastAnimationName() const; /** * - The name of all animation data * @version DragonBones 4.5 @@ -441,8 +441,8 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - inline const hlookup::string_map& getAnimations() const { return _animations; } - void setAnimations(const hlookup::string_map& value); + inline const std::map& getAnimations() const { return _animations; } + void setAnimations(const std::map& value); /** * - An AnimationConfig instance that can be used quickly. * @see dragonBones.AnimationConfig diff --git a/extensions/DragonBones/animation/AnimationState.cpp b/extensions/DragonBones/animation/AnimationState.cpp index 0540ce842f..48274df194 100644 --- a/extensions/DragonBones/animation/AnimationState.cpp +++ b/extensions/DragonBones/animation/AnimationState.cpp @@ -1,4 +1,4 @@ -#include "AnimationState.h" +#include "AnimationState.h" #include "WorldClock.h" #include "../model/DisplayData.h" #include "../model/AnimationConfig.h" @@ -83,7 +83,7 @@ void AnimationState::_onClear() void AnimationState::_updateTimelines() { { // Update constraint timelines. - hlookup::string_map> constraintTimelines; + std::map> constraintTimelines; for (const auto timeline : _constraintTimelines) // Create constraint timelines map. { constraintTimelines[timeline->constraint->getName()].push_back(timeline); @@ -137,7 +137,7 @@ void AnimationState::_updateTimelines() void AnimationState::_updateBoneAndSlotTimelines() { { // Update bone timelines. - hlookup::string_map> boneTimelines; + std::map> boneTimelines; for (const auto timeline : _boneTimelines) // Create bone timelines map. { boneTimelines[timeline->bone->getName()].push_back(timeline); @@ -238,7 +238,7 @@ void AnimationState::_updateBoneAndSlotTimelines() } { // Update slot timelines. - hlookup::string_map> slotTimelines; + std::map> slotTimelines; std::vector ffdFlags; for (const auto timeline : _slotTimelines) // Create slot timelines map. { @@ -745,12 +745,12 @@ void AnimationState::fadeOut(float fadeOutTime, bool pausePlayhead) _fadeTime = fadeTotalTime * (1.0f - _fadeProgress); } -bool AnimationState::containsBoneMask(std::string_view boneName) const +bool AnimationState::containsBoneMask(const std::string& boneName) const { return _boneMask.empty() || std::find(_boneMask.cbegin(), _boneMask.cend(), boneName) != _boneMask.cend(); } -void AnimationState::addBoneMask(std::string_view boneName, bool recursive) +void AnimationState::addBoneMask(const std::string& boneName, bool recursive) { const auto currentBone = _armature->getBone(boneName); if (currentBone == nullptr) @@ -760,7 +760,7 @@ void AnimationState::addBoneMask(std::string_view boneName, bool recursive) if (std::find(_boneMask.cbegin(), _boneMask.cend(), boneName) == _boneMask.cend()) { - _boneMask.push_back(std::string{boneName}); + _boneMask.push_back(boneName); } if (recursive) // Add recursive mixing. @@ -770,7 +770,7 @@ void AnimationState::addBoneMask(std::string_view boneName, bool recursive) if (std::find(_boneMask.cbegin(), _boneMask.cend(), bone->getName()) == _boneMask.cend() && currentBone->contains(bone)) { - _boneMask.push_back(std::string{bone->getName()}); + _boneMask.push_back(bone->getName()); } } } @@ -778,7 +778,7 @@ void AnimationState::addBoneMask(std::string_view boneName, bool recursive) _timelineDirty = 1; } -void AnimationState::removeBoneMask(std::string_view boneName, bool recursive) +void AnimationState::removeBoneMask(const std::string& boneName, bool recursive) { { auto iterator = std::find(_boneMask.begin(), _boneMask.end(), boneName); @@ -816,7 +816,7 @@ void AnimationState::removeBoneMask(std::string_view boneName, bool recursive) if (!currentBone->contains(bone)) { - _boneMask.push_back(std::string{bone->getName()}); + _boneMask.push_back(bone->getName()); } } } diff --git a/extensions/DragonBones/animation/AnimationState.h b/extensions/DragonBones/animation/AnimationState.h index faf9d3ab17..a99da36f0e 100644 --- a/extensions/DragonBones/animation/AnimationState.h +++ b/extensions/DragonBones/animation/AnimationState.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -251,7 +251,7 @@ private: std::vector _slotTimelines; std::vector _constraintTimelines; std::vector> _poseTimelines; - hlookup::string_map _bonePoses; + std::map _bonePoses; Armature* _armature; ZOrderTimelineState* _zOrderTimeline; @@ -325,7 +325,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - bool containsBoneMask(std::string_view boneName) const; + bool containsBoneMask(const std::string& boneName) const; /** * - Add a specific bone mask. * @param boneName - The bone name. @@ -340,7 +340,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - void addBoneMask(std::string_view boneName, bool recursive = true); + void addBoneMask(const std::string& boneName, bool recursive = true); /** * - Remove the mask of a specific bone. * @param boneName - The bone name. @@ -355,7 +355,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - void removeBoneMask(std::string_view boneName, bool recursive = true); + void removeBoneMask(const std::string& boneName, bool recursive = true); /** * - Remove all bone masks. * @version DragonBones 3.0 @@ -456,7 +456,7 @@ public: */ float getCurrentTime() const; void setCurrentTime(float value); - inline std::string_view getName() const { return name; } + inline const std::string& getName() const { return name; } /** * - The animation data. diff --git a/extensions/DragonBones/armature/Armature.cpp b/extensions/DragonBones/armature/Armature.cpp index e4aabc2763..7e6cc57b95 100644 --- a/extensions/DragonBones/armature/Armature.cpp +++ b/extensions/DragonBones/armature/Armature.cpp @@ -1,4 +1,4 @@ -#include "Armature.h" +#include "Armature.h" #include "../model/TextureAtlasData.h" #include "../model/UserData.h" #include "../animation/WorldClock.h" @@ -275,7 +275,7 @@ void Armature::advanceTime(float passedTime) _proxy->dbUpdate(); } -void Armature::invalidUpdate(std::string_view boneName, bool updateSlot) +void Armature::invalidUpdate(const std::string& boneName, bool updateSlot) { if (!boneName.empty()) { @@ -431,7 +431,7 @@ Slot* Armature::intersectsSegment(float xA, return intSlotA; } -Bone* Armature::getBone(std::string_view name) const +Bone* Armature::getBone(const std::string& name) const { for (const auto& bone : _bones) { @@ -451,7 +451,7 @@ Bone* Armature::getBoneByDisplay(void* display) const return slot != nullptr ? slot->getParent() : nullptr; } -Slot* Armature::getSlot(std::string_view name) const +Slot* Armature::getSlot(const std::string& name) const { for (const auto slot : _slots) { diff --git a/extensions/DragonBones/armature/Armature.h b/extensions/DragonBones/armature/Armature.h index c78d0fe9a2..6f6f5f7bbe 100644 --- a/extensions/DragonBones/armature/Armature.h +++ b/extensions/DragonBones/armature/Armature.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -201,7 +201,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - void invalidUpdate(std::string_view boneName = "", bool updateSlot = false); + void invalidUpdate(const std::string& boneName = "", bool updateSlot = false); /** * - Check whether a specific point is inside a custom bounding box in a slot. * The coordinate system of the point is the inner coordinate system of the armature. @@ -278,7 +278,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - Bone* getBone(std::string_view name) const; + Bone* getBone(const std::string& name) const; /** * - Get a specific bone by the display. * @param display - The display object. @@ -308,7 +308,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - Slot* getSlot(std::string_view name) const; + Slot* getSlot(const std::string& name) const; /** * - Get a specific slot by the display. * @param display - The display object. @@ -426,7 +426,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline std::string_view getName() const { return _armatureData->name; } + inline const std::string& getName() const { return _armatureData->name; } /** * - The armature data. * @see dragonBones.ArmatureData diff --git a/extensions/DragonBones/armature/Bone.h b/extensions/DragonBones/armature/Bone.h index 3541143b0b..cba7c2d650 100644 --- a/extensions/DragonBones/armature/Bone.h +++ b/extensions/DragonBones/armature/Bone.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -198,7 +198,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline std::string_view getName() const { return _boneData->name; } + inline const std::string& getName() const { return _boneData->name; } /** * - The parent bone to which it belongs. * @version DragonBones 3.0 diff --git a/extensions/DragonBones/armature/Constraint.h b/extensions/DragonBones/armature/Constraint.h index 99d38b15ec..92ba6e9f50 100644 --- a/extensions/DragonBones/armature/Constraint.h +++ b/extensions/DragonBones/armature/Constraint.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -75,7 +75,7 @@ public: virtual void update() = 0; virtual void invalidUpdate() = 0; - inline std::string_view getName() { return _constraintData->name; } + inline const std::string& getName() { return _constraintData->name; } }; /** * @internal diff --git a/extensions/DragonBones/armature/Slot.h b/extensions/DragonBones/armature/Slot.h index 6700737b08..234e2f79c6 100644 --- a/extensions/DragonBones/armature/Slot.h +++ b/extensions/DragonBones/armature/Slot.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -343,7 +343,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline std::string_view getName() const { return _slotData->name; } + inline const std::string& getName() const { return _slotData->name; } /** * - Contains a display list of display objects or child armatures. * @version DragonBones 3.0 diff --git a/extensions/DragonBones/core/DragonBones.h b/extensions/DragonBones/core/DragonBones.h index 336357fecf..9ddab3b97a 100644 --- a/extensions/DragonBones/core/DragonBones.h +++ b/extensions/DragonBones/core/DragonBones.h @@ -33,7 +33,6 @@ #include #include #include -#include "base/hlookup.h" // dragonBones assert #define DRAGONBONES_ASSERT(cond, msg) \ do \ @@ -360,15 +359,15 @@ inline int indexOf(const std::vector& vector, const T& value) return -1; } -template -inline auto mapFind(Cont& map, std::string_view key) +template +inline T* mapFind(const std::map& map, const std::string& key) { auto iterator = map.find(key); return (iterator != map.end()) ? iterator->second : nullptr; } -template -inline auto mapFindB(Cont& map, std::string_view key) +template +inline T* mapFindB(std::map& map, const std::string& key) { auto iterator = map.find(key); return (iterator != map.end()) ? &iterator->second : nullptr; diff --git a/extensions/DragonBones/event/IEventDispatcher.h b/extensions/DragonBones/event/IEventDispatcher.h index 26476941ee..ded91d92db 100644 --- a/extensions/DragonBones/event/IEventDispatcher.h +++ b/extensions/DragonBones/event/IEventDispatcher.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -56,7 +56,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - virtual bool hasDBEventListener(std::string_view type) const = 0; + virtual bool hasDBEventListener(const std::string& type) const = 0; /** * - Dispatches an event into the event flow. * @param type - Event type. @@ -73,7 +73,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - virtual void dispatchDBEvent(std::string_view type, EventObject* value) = 0; + virtual void dispatchDBEvent(const std::string& type, EventObject* value) = 0; /** * - Add an event listener object so that the listener receives notification of an event. * @param type - Event type. @@ -90,7 +90,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - virtual void addDBEventListener(std::string_view type, const std::function& listener) = 0; + virtual void addDBEventListener(const std::string& type, const std::function& listener) = 0; /** * - Removes a listener from the object. * @param type - Event type. @@ -107,7 +107,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - virtual void removeDBEventListener(std::string_view type, const std::function& listener) = 0; + virtual void removeDBEventListener(const std::string& type, const std::function& listener) = 0; }; DRAGONBONES_NAMESPACE_END diff --git a/extensions/DragonBones/factory/BaseFactory.cpp b/extensions/DragonBones/factory/BaseFactory.cpp index afa0b9fa13..c7eb5242e2 100644 --- a/extensions/DragonBones/factory/BaseFactory.cpp +++ b/extensions/DragonBones/factory/BaseFactory.cpp @@ -1,11 +1,11 @@ -#include "BaseFactory.h" +#include "BaseFactory.h" DRAGONBONES_NAMESPACE_BEGIN JSONDataParser BaseFactory::_jsonParser; BinaryDataParser BaseFactory::_binaryParser; -TextureData* BaseFactory::_getTextureData(std::string_view textureAtlasName, std::string_view textureName) const +TextureData* BaseFactory::_getTextureData(const std::string& textureAtlasName, const std::string& textureName) const { const auto iterator = _textureAtlasDataMap.find(textureAtlasName); if (iterator != _textureAtlasDataMap.end()) @@ -42,12 +42,12 @@ TextureData* BaseFactory::_getTextureData(std::string_view textureAtlasName, std } bool BaseFactory::_fillBuildArmaturePackage(BuildArmaturePackage& dataPackage, - std::string_view dragonBonesName, - std::string_view armatureName, - std::string_view skinName, - std::string_view textureAtlasName) const + const std::string& dragonBonesName, + const std::string& armatureName, + const std::string& skinName, + const std::string& textureAtlasName) const { - auto mapName = dragonBonesName; + std::string mapName = dragonBonesName; DragonBonesData* dragonBonesData = nullptr; ArmatureData* armatureData = nullptr; @@ -141,7 +141,7 @@ void BaseFactory::_buildSlots(const BuildArmaturePackage& dataPackage, Armature* return; } - hlookup::string_map*> skinSlots; + std::map*> skinSlots; for (auto& pair : defaultSkin->displays) { auto& displays = pair.second; @@ -309,7 +309,7 @@ std::pair BaseFactory::_getSlotDisplay(const BuildArmaturePa return display; } -DragonBonesData* BaseFactory::parseDragonBonesData(const char* rawData, std::string_view name, float scale) +DragonBonesData* BaseFactory::parseDragonBonesData(const char* rawData, const std::string& name, float scale) { DRAGONBONES_ASSERT(rawData != nullptr, ""); @@ -350,7 +350,7 @@ DragonBonesData* BaseFactory::parseDragonBonesData(const char* rawData, std::str TextureAtlasData* BaseFactory::parseTextureAtlasData(const char* rawData, void* textureAtlas, - std::string_view name, + const std::string& name, float scale) { const auto textureAtlasData = _buildTextureAtlasData(nullptr, nullptr); @@ -361,7 +361,7 @@ TextureAtlasData* BaseFactory::parseTextureAtlasData(const char* rawData, return textureAtlasData; } -void BaseFactory::addDragonBonesData(DragonBonesData* data, std::string_view name) +void BaseFactory::addDragonBonesData(DragonBonesData* data, const std::string& name) { const auto& mapName = !name.empty() ? name : data->name; if (_dragonBonesDataMap.find(mapName) != _dragonBonesDataMap.cend()) @@ -378,7 +378,7 @@ void BaseFactory::addDragonBonesData(DragonBonesData* data, std::string_view nam _dragonBonesDataMap[mapName] = data; } -void BaseFactory::removeDragonBonesData(std::string_view name, bool disposeData) +void BaseFactory::removeDragonBonesData(const std::string& name, bool disposeData) { const auto iterator = _dragonBonesDataMap.find(name); if (iterator != _dragonBonesDataMap.cend()) @@ -392,7 +392,7 @@ void BaseFactory::removeDragonBonesData(std::string_view name, bool disposeData) } } -void BaseFactory::addTextureAtlasData(TextureAtlasData* data, std::string_view name) +void BaseFactory::addTextureAtlasData(TextureAtlasData* data, const std::string& name) { const auto& mapName = !name.empty() ? name : data->name; auto& textureAtlasList = _textureAtlasDataMap[mapName]; @@ -402,7 +402,7 @@ void BaseFactory::addTextureAtlasData(TextureAtlasData* data, std::string_view n } } -void BaseFactory::removeTextureAtlasData(std::string_view name, bool disposeData) +void BaseFactory::removeTextureAtlasData(const std::string& name, bool disposeData) { const auto iterator = _textureAtlasDataMap.find(name); if (iterator != _textureAtlasDataMap.end()) @@ -419,7 +419,7 @@ void BaseFactory::removeTextureAtlasData(std::string_view name, bool disposeData } } -ArmatureData* BaseFactory::getArmatureData(std::string_view name, std::string_view dragonBonesName) const +ArmatureData* BaseFactory::getArmatureData(const std::string& name, const std::string& dragonBonesName) const { BuildArmaturePackage dataPackage; if (!_fillBuildArmaturePackage(dataPackage, dragonBonesName, name, "", "")) @@ -452,10 +452,10 @@ void BaseFactory::clear(bool disposeData) _textureAtlasDataMap.clear(); } -Armature* BaseFactory::buildArmature(std::string_view armatureName, - std::string_view dragonBonesName, - std::string_view skinName, - std::string_view textureAtlasName) const +Armature* BaseFactory::buildArmature(const std::string& armatureName, + const std::string& dragonBonesName, + const std::string& skinName, + const std::string& textureAtlasName) const { BuildArmaturePackage dataPackage; if (!_fillBuildArmaturePackage(dataPackage, dragonBonesName, armatureName, skinName, textureAtlasName)) @@ -512,10 +512,10 @@ void BaseFactory::replaceDisplay(Slot* slot, DisplayData* displayData, int displ slot->setDisplayList(displayList); } -bool BaseFactory::replaceSlotDisplay(std::string_view dragonBonesName, - std::string_view armatureName, - std::string_view slotName, - std::string_view displayName, +bool BaseFactory::replaceSlotDisplay(const std::string& dragonBonesName, + const std::string& armatureName, + const std::string& slotName, + const std::string& displayName, Slot* slot, int displayIndex) const { @@ -538,9 +538,9 @@ bool BaseFactory::replaceSlotDisplay(std::string_view dragonBonesName, return true; } -bool BaseFactory::replaceSlotDisplayList(std::string_view dragonBonesName, - std::string_view armatureName, - std::string_view slotName, +bool BaseFactory::replaceSlotDisplayList(const std::string& dragonBonesName, + const std::string& armatureName, + const std::string& slotName, Slot* slot) const { DRAGONBONES_ASSERT(slot, "Arguments error."); diff --git a/extensions/DragonBones/factory/BaseFactory.h b/extensions/DragonBones/factory/BaseFactory.h index dcd8d8d334..8d9329d579 100644 --- a/extensions/DragonBones/factory/BaseFactory.h +++ b/extensions/DragonBones/factory/BaseFactory.h @@ -68,8 +68,8 @@ public: bool autoSearch; protected: - hlookup::string_map _dragonBonesDataMap; - hlookup::string_map> _textureAtlasDataMap; + std::map _dragonBonesDataMap; + std::map> _textureAtlasDataMap; DragonBones* _dragonBones; DataParser* _dataParser; @@ -99,12 +99,12 @@ public: protected: virtual inline bool _isSupportMesh() const { return true; } - virtual TextureData* _getTextureData(std::string_view textureAtlasName, std::string_view textureName) const; + virtual TextureData* _getTextureData(const std::string& textureAtlasName, const std::string& textureName) const; virtual bool _fillBuildArmaturePackage(BuildArmaturePackage& dataPackage, - std::string_view dragonBonesName, - std::string_view armatureName, - std::string_view skinName, - std::string_view textureAtlasName) const; + const std::string& dragonBonesName, + const std::string& armatureName, + const std::string& skinName, + const std::string& textureAtlasName) const; virtual void _buildBones(const BuildArmaturePackage& dataPackage, Armature* armature) const; /** * @private @@ -151,7 +151,9 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - virtual DragonBonesData* parseDragonBonesData(const char* rawData, std::string_view name = "", float scale = 1.0f); + virtual DragonBonesData* parseDragonBonesData(const char* rawData, + const std::string& name = "", + float scale = 1.0f); /** * - Parse the raw texture atlas data and the texture atlas object to a TextureAtlasData instance and cache it to * the factory. @@ -184,8 +186,8 @@ public: */ virtual TextureAtlasData* parseTextureAtlasData(const char* rawData, void* textureAtlas, - std::string_view name = "", - float scale = 1.0f); + const std::string& name = "", + float scale = 1.0f); /** * - Get a specific DragonBonesData instance. * @param name - The DragonBonesData instance cache name. @@ -208,7 +210,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline DragonBonesData* getDragonBonesData(std::string_view name) const + inline DragonBonesData* getDragonBonesData(const std::string& name) const { return mapFind(_dragonBonesDataMap, name); } @@ -235,7 +237,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - virtual void addDragonBonesData(DragonBonesData* data, std::string_view name = ""); + virtual void addDragonBonesData(DragonBonesData* data, const std::string& name = ""); /** * - Remove a DragonBonesData instance. * @param name - The DragonBonesData instance cache name. @@ -258,7 +260,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - virtual void removeDragonBonesData(std::string_view name, bool disposeData = true); + virtual void removeDragonBonesData(const std::string& name, bool disposeData = true); /** * - Get a list of specific TextureAtlasData instances. * @param name - The TextureAtlasData cahce name. @@ -279,7 +281,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline std::vector* getTextureAtlasData(std::string_view name) + inline std::vector* getTextureAtlasData(const std::string& name) { return mapFindB(_textureAtlasDataMap, name); } @@ -306,7 +308,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - virtual void addTextureAtlasData(TextureAtlasData* data, std::string_view name = ""); + virtual void addTextureAtlasData(TextureAtlasData* data, const std::string& name = ""); /** * - Remove a TextureAtlasData instance. * @param name - The TextureAtlasData instance cache name. @@ -329,7 +331,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - virtual void removeTextureAtlasData(std::string_view name, bool disposeData = true); + virtual void removeTextureAtlasData(const std::string& name, bool disposeData = true); /** * - Get a specific armature data. * @param name - The armature data name. @@ -346,7 +348,7 @@ public: * @version DragonBones 5.1 * @language zh_CN */ - virtual ArmatureData* getArmatureData(std::string_view name, std::string_view dragonBonesName = "") const; + virtual ArmatureData* getArmatureData(const std::string& name, const std::string& dragonBonesName = "") const; /** * - Clear all cached DragonBonesData instances and TextureAtlasData instances. * @param disposeData - Whether to dispose data. @@ -401,10 +403,10 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - virtual Armature* buildArmature(std::string_view armatureName, - std::string_view dragonBonesName = "", - std::string_view skinName = "", - std::string_view textureAtlasName = "") const; + virtual Armature* buildArmature(const std::string& armatureName, + const std::string& dragonBonesName = "", + const std::string& skinName = "", + const std::string& textureAtlasName = "") const; /** * @private */ @@ -446,18 +448,18 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - virtual bool replaceSlotDisplay(std::string_view dragonBonesName, - std::string_view armatureName, - std::string_view slotName, - std::string_view displayName, + virtual bool replaceSlotDisplay(const std::string& dragonBonesName, + const std::string& armatureName, + const std::string& slotName, + const std::string& displayName, Slot* slot, int displayIndex = -1) const; /** * @private */ - virtual bool replaceSlotDisplayList(std::string_view dragonBonesName, - std::string_view armatureName, - std::string_view slotName, + virtual bool replaceSlotDisplayList(const std::string& dragonBonesName, + const std::string& armatureName, + const std::string& slotName, Slot* slot) const; /** * - Share specific skin data with specific armature. @@ -548,14 +550,14 @@ public: /** * @private */ - inline const hlookup::string_map>& getAllTextureAtlasData() const + inline const std::map>& getAllTextureAtlasData() const { return _textureAtlasDataMap; } /** * @private */ - inline const hlookup::string_map& getAllDragonBonesData() const { return _dragonBonesDataMap; } + inline const std::map& getAllDragonBonesData() const { return _dragonBonesDataMap; } /** * - An Worldclock instance updated by engine. * @version DragonBones 5.7 diff --git a/extensions/DragonBones/model/AnimationConfig.cpp b/extensions/DragonBones/model/AnimationConfig.cpp index 8ee7dac7d6..26d198f630 100644 --- a/extensions/DragonBones/model/AnimationConfig.cpp +++ b/extensions/DragonBones/model/AnimationConfig.cpp @@ -1,4 +1,4 @@ -#include "AnimationConfig.h" +#include "AnimationConfig.h" #include "../armature/Armature.h" #include "../armature/Bone.h" @@ -63,12 +63,12 @@ void AnimationConfig::copyFrom(AnimationConfig* value) boneMask = value->boneMask; } -bool AnimationConfig::containsBoneMask(std::string_view boneName) const +bool AnimationConfig::containsBoneMask(const std::string& boneName) const { return boneMask.empty() || std::find(boneMask.cbegin(), boneMask.cend(), boneName) != boneMask.cend(); } -void AnimationConfig::addBoneMask(Armature* armature, std::string_view boneName, bool recursive) +void AnimationConfig::addBoneMask(Armature* armature, const std::string& boneName, bool recursive) { const auto currentBone = armature->getBone(boneName); if (currentBone == nullptr) @@ -78,7 +78,7 @@ void AnimationConfig::addBoneMask(Armature* armature, std::string_view boneName, if (std::find(boneMask.cbegin(), boneMask.cend(), boneName) == boneMask.cend()) // Add mixing { - boneMask.push_back(std::string{boneName}); + boneMask.push_back(boneName); } if (recursive) // Add recursive mixing. @@ -88,13 +88,13 @@ void AnimationConfig::addBoneMask(Armature* armature, std::string_view boneName, if (std::find(boneMask.cbegin(), boneMask.cend(), bone->getName()) == boneMask.cend() && currentBone->contains(bone)) { - boneMask.push_back(std::string{bone->getName()}); + boneMask.push_back(bone->getName()); } } } } -void AnimationConfig::removeBoneMask(Armature* armature, std::string_view boneName, bool recursive) +void AnimationConfig::removeBoneMask(Armature* armature, const std::string& boneName, bool recursive) { { auto iterator = std::find(boneMask.begin(), boneMask.end(), boneName); @@ -131,7 +131,7 @@ void AnimationConfig::removeBoneMask(Armature* armature, std::string_view boneNa if (!currentBone->contains(bone)) { - boneMask.push_back(std::string{bone->getName()}); + boneMask.push_back(bone->getName()); } } } diff --git a/extensions/DragonBones/model/AnimationConfig.h b/extensions/DragonBones/model/AnimationConfig.h index dd90b4e7c8..c53fe730c1 100644 --- a/extensions/DragonBones/model/AnimationConfig.h +++ b/extensions/DragonBones/model/AnimationConfig.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -296,15 +296,15 @@ public: /** * @private */ - bool containsBoneMask(std::string_view boneName) const; + bool containsBoneMask(const std::string& boneName) const; /** * @private */ - void addBoneMask(Armature* armature, std::string_view boneName, bool recursive); + void addBoneMask(Armature* armature, const std::string& boneName, bool recursive); /** * @private */ - void removeBoneMask(Armature* armature, std::string_view boneName, bool recursive); + void removeBoneMask(Armature* armature, const std::string& boneName, bool recursive); public: // For WebAssembly. int getFadeOutMode() const { return (int)fadeOutMode; } diff --git a/extensions/DragonBones/model/AnimationData.h b/extensions/DragonBones/model/AnimationData.h index 64e7be54df..8d7a37708e 100644 --- a/extensions/DragonBones/model/AnimationData.h +++ b/extensions/DragonBones/model/AnimationData.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -126,23 +126,23 @@ public: /** * @private */ - hlookup::string_map> boneTimelines; + std::map> boneTimelines; /** * @private */ - hlookup::string_map> slotTimelines; + std::map> slotTimelines; /** * @private */ - hlookup::string_map> constraintTimelines; + std::map> constraintTimelines; /** * @private */ - hlookup::string_map> boneCachedFrameIndices; + std::map> boneCachedFrameIndices; /** * @private */ - hlookup::string_map> slotCachedFrameIndices; + std::map> slotCachedFrameIndices; /** * @private */ @@ -181,35 +181,35 @@ public: /** * @private */ - std::vector* getBoneTimelines(std::string_view timelineName) + std::vector* getBoneTimelines(const std::string& timelineName) { return mapFindB(boneTimelines, timelineName); } /** * @private */ - inline std::vector* getSlotTimelines(std::string_view timelineName) + inline std::vector* getSlotTimelines(const std::string& timelineName) { return mapFindB(slotTimelines, timelineName); } /** * @private */ - inline std::vector* getConstraintTimelines(std::string_view timelineName) + inline std::vector* getConstraintTimelines(const std::string& timelineName) { return mapFindB(constraintTimelines, timelineName); } /** * @private */ - inline std::vector* getBoneCachedFrameIndices(std::string_view boneName) + inline std::vector* getBoneCachedFrameIndices(const std::string& boneName) { return mapFindB(boneCachedFrameIndices, boneName); } /** * @private */ - inline std::vector* getSlotCachedFrameIndices(std::string_view slotName) + inline std::vector* getSlotCachedFrameIndices(const std::string& slotName) { return mapFindB(slotCachedFrameIndices, slotName); } diff --git a/extensions/DragonBones/model/ArmatureData.cpp b/extensions/DragonBones/model/ArmatureData.cpp index 66f9dfca75..9cc86af721 100644 --- a/extensions/DragonBones/model/ArmatureData.cpp +++ b/extensions/DragonBones/model/ArmatureData.cpp @@ -1,4 +1,4 @@ -#include "ArmatureData.h" +#include "ArmatureData.h" #include "UserData.h" #include "DragonBonesData.h" #include "ConstraintData.h" @@ -264,9 +264,9 @@ void ArmatureData::addAction(ActionData* value, bool isDefault) } } -MeshDisplayData* ArmatureData::getMesh(std::string_view skinName, - std::string_view slotName, - std::string_view meshName) const +MeshDisplayData* ArmatureData::getMesh(const std::string& skinName, + const std::string& slotName, + const std::string& meshName) const { const auto skin = getSkin(skinName); if (skin == nullptr) diff --git a/extensions/DragonBones/model/ArmatureData.h b/extensions/DragonBones/model/ArmatureData.h index 7c39c718bb..838df4adb7 100644 --- a/extensions/DragonBones/model/ArmatureData.h +++ b/extensions/DragonBones/model/ArmatureData.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -113,23 +113,23 @@ public: /** * @private */ - hlookup::string_map bones; + std::map bones; /** * @private */ - hlookup::string_map slots; + std::map slots; /** * @private */ - hlookup::string_map constraints; + std::map constraints; /** * @private */ - hlookup::string_map skins; + std::map skins; /** * @private */ - hlookup::string_map animations; + std::map animations; /** * - The default skin data. * @version DragonBones 4.5 @@ -223,7 +223,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline BoneData* getBone(std::string_view boneName) const { return mapFind(bones, boneName); } + inline BoneData* getBone(const std::string& boneName) const { return mapFind(bones, boneName); } /** * - Get a specific slot data. * @param slotName - The slot name. @@ -236,13 +236,13 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline SlotData* getSlot(std::string_view slotName) const { return mapFind(slots, slotName); } + inline SlotData* getSlot(const std::string& slotName) const { return mapFind(slots, slotName); } /** * @private */ - inline ConstraintData* getConstraint(std::string_view constraintName) const + inline ConstraintData* getConstraint(const std::string& constraintName) const { - return mapFind(constraints, constraintName); + return mapFind(constraints, constraintName); } /** * - Get a specific skin data. @@ -256,11 +256,13 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline SkinData* getSkin(std::string_view skinName) const { return mapFind(skins, skinName); } + inline SkinData* getSkin(const std::string& skinName) const { return mapFind(skins, skinName); } /** * @private */ - MeshDisplayData* getMesh(std::string_view skinName, std::string_view slotName, std::string_view meshName) const; + MeshDisplayData* getMesh(const std::string& skinName, + const std::string& slotName, + const std::string& meshName) const; /** * - Get a specific animation data. * @param animationName - The animation animationName. @@ -273,7 +275,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline AnimationData* getAnimation(std::string_view animationName) const + inline AnimationData* getAnimation(const std::string& animationName) const { return mapFind(animations, animationName); } diff --git a/extensions/DragonBones/model/DragonBonesData.h b/extensions/DragonBones/model/DragonBonesData.h index 539d34896f..eef82b2b87 100644 --- a/extensions/DragonBones/model/DragonBonesData.h +++ b/extensions/DragonBones/model/DragonBonesData.h @@ -107,7 +107,7 @@ public: /** * @private */ - hlookup::string_map armatures; + std::map armatures; /** * @internal */ @@ -158,7 +158,10 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline ArmatureData* getArmature(std::string_view armatureName) const { return mapFind(armatures, armatureName); } + inline ArmatureData* getArmature(const std::string& armatureName) const + { + return mapFind(armatures, armatureName); + } protected: virtual void _onClear() override; diff --git a/extensions/DragonBones/model/SkinData.cpp b/extensions/DragonBones/model/SkinData.cpp index 7f53de7acf..7e6fe25011 100644 --- a/extensions/DragonBones/model/SkinData.cpp +++ b/extensions/DragonBones/model/SkinData.cpp @@ -1,4 +1,4 @@ -#include "SkinData.h" +#include "SkinData.h" #include "DisplayData.h" DRAGONBONES_NAMESPACE_BEGIN @@ -21,7 +21,7 @@ void SkinData::_onClear() parent = nullptr; } -void SkinData::addDisplay(std::string_view slotName, DisplayData* value) +void SkinData::addDisplay(const std::string& slotName, DisplayData* value) { if (value != nullptr) { @@ -31,7 +31,7 @@ void SkinData::addDisplay(std::string_view slotName, DisplayData* value) displays[slotName].push_back(value); // TODO clear prev } -DisplayData* SkinData::getDisplay(std::string_view slotName, std::string_view displayName) +DisplayData* SkinData::getDisplay(const std::string& slotName, const std::string& displayName) { const auto slotDisplays = getDisplays(slotName); if (slotDisplays != nullptr) diff --git a/extensions/DragonBones/model/SkinData.h b/extensions/DragonBones/model/SkinData.h index 89e7abfc99..e054e9f96c 100644 --- a/extensions/DragonBones/model/SkinData.h +++ b/extensions/DragonBones/model/SkinData.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -24,7 +24,6 @@ #define DRAGONBONES_SKIN_DATA_H #include "../core/BaseObject.h" -#include "base/hlookup.h" DRAGONBONES_NAMESPACE_BEGIN /** @@ -56,7 +55,7 @@ public: /** * @private */ - hlookup::string_map> displays; + std::map> displays; /** * @private */ @@ -69,18 +68,18 @@ public: /** * @internal */ - void addDisplay(std::string_view slotName, DisplayData* value); + void addDisplay(const std::string& slotName, DisplayData* value); /** * @private */ - DisplayData* getDisplay(std::string_view slotName, std::string_view displayName); + DisplayData* getDisplay(const std::string& slotName, const std::string& displayName); /** * @private */ - std::vector* getDisplays(std::string_view slotName) { return mapFindB(displays, slotName); } + std::vector* getDisplays(const std::string& slotName) { return mapFindB(displays, slotName); } public: // For WebAssembly. TODO parent - const hlookup::string_map>& getSlotDisplays() const { return displays; } + const std::map>& getSlotDisplays() const { return displays; } }; DRAGONBONES_NAMESPACE_END diff --git a/extensions/DragonBones/model/TextureAtlasData.h b/extensions/DragonBones/model/TextureAtlasData.h index 08b266d356..ad5bcb504b 100644 --- a/extensions/DragonBones/model/TextureAtlasData.h +++ b/extensions/DragonBones/model/TextureAtlasData.h @@ -84,7 +84,7 @@ public: /** * @private */ - hlookup::string_map textures; + std::map textures; /** * @private */ @@ -100,13 +100,13 @@ public: /** * @private */ - inline TextureData* getTexture(std::string_view textureName) const { return mapFind(textures, textureName); } + inline TextureData* getTexture(const std::string& textureName) const { return mapFind(textures, textureName); } protected: virtual void _onClear() override; public: // For WebAssembly. - const hlookup::string_map& getTextures() const { return textures; } + const std::map& getTextures() const { return textures; } }; /** * @internal diff --git a/extensions/DragonBones/parser/DataParser.cpp b/extensions/DragonBones/parser/DataParser.cpp index 3d0207d8d9..684d192e25 100644 --- a/extensions/DragonBones/parser/DataParser.cpp +++ b/extensions/DragonBones/parser/DataParser.cpp @@ -1,4 +1,4 @@ -#include "DataParser.h" +#include "DataParser.h" DRAGONBONES_NAMESPACE_BEGIN @@ -125,9 +125,9 @@ const char* DataParser::GOTO_AND_PLAY = "gotoAndPlay"; const char* DataParser::DEFAULT_NAME = "default"; -TextureFormat DataParser::_getTextureFormat(std::string_view value) +TextureFormat DataParser::_getTextureFormat(const std::string& value) { - std::string lower{value}; + auto lower = value; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); if (lower == "rgba8888") @@ -158,9 +158,9 @@ TextureFormat DataParser::_getTextureFormat(std::string_view value) return TextureFormat::DEFAULT; } -ArmatureType DataParser::_getArmatureType(std::string_view value) +ArmatureType DataParser::_getArmatureType(const std::string& value) { - std::string lower{value}; + auto lower = value; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); if (lower == "armature") @@ -179,9 +179,9 @@ ArmatureType DataParser::_getArmatureType(std::string_view value) return ArmatureType::Armature; } -DisplayType DataParser::_getDisplayType(std::string_view value) +DisplayType DataParser::_getDisplayType(const std::string& value) { - std::string lower{value}; + auto lower = value; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); if (lower == "image") @@ -204,9 +204,9 @@ DisplayType DataParser::_getDisplayType(std::string_view value) return DisplayType::Image; } -BoundingBoxType DataParser::_getBoundingBoxType(std::string_view value) +BoundingBoxType DataParser::_getBoundingBoxType(const std::string& value) { - std::string lower{value}; + auto lower = value; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); if (lower == "rectangle") @@ -225,9 +225,9 @@ BoundingBoxType DataParser::_getBoundingBoxType(std::string_view value) return BoundingBoxType::Rectangle; } -ActionType DataParser::_getActionType(std::string_view value) +ActionType DataParser::_getActionType(const std::string& value) { - std::string lower{value}; + auto lower = value; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); if (lower == "play") @@ -246,9 +246,9 @@ ActionType DataParser::_getActionType(std::string_view value) return ActionType::Play; } -BlendMode DataParser::_getBlendMode(std::string_view value) +BlendMode DataParser::_getBlendMode(const std::string& value) { - std::string lower{value}; + auto lower = value; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); if (lower == "normal") diff --git a/extensions/DragonBones/parser/DataParser.h b/extensions/DragonBones/parser/DataParser.h index ccad44049d..08328ccd5f 100644 --- a/extensions/DragonBones/parser/DataParser.h +++ b/extensions/DragonBones/parser/DataParser.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -166,12 +166,12 @@ protected: static const char* DEFAULT_NAME; - static TextureFormat _getTextureFormat(std::string_view value); - static ArmatureType _getArmatureType(std::string_view value); - static DisplayType _getDisplayType(std::string_view value); - static BoundingBoxType _getBoundingBoxType(std::string_view value); - static ActionType _getActionType(std::string_view value); - static BlendMode _getBlendMode(std::string_view value); + static TextureFormat _getTextureFormat(const std::string& value); + static ArmatureType _getArmatureType(const std::string& value); + static DisplayType _getDisplayType(const std::string& value); + static BoundingBoxType _getBoundingBoxType(const std::string& value); + static ActionType _getActionType(const std::string& value); + static BlendMode _getBlendMode(const std::string& value); public: virtual DragonBonesData* parseDragonBonesData(const char* rawData, float scale = 1.0f) = 0; diff --git a/extensions/DragonBones/parser/JSONDataParser.h b/extensions/DragonBones/parser/JSONDataParser.h index 21a437dac3..afa6e045d4 100644 --- a/extensions/DragonBones/parser/JSONDataParser.h +++ b/extensions/DragonBones/parser/JSONDataParser.h @@ -1,4 +1,4 @@ -#ifndef DRAGONBONES_JSON_DATA_PARSER_H +#ifndef DRAGONBONES_JSON_DATA_PARSER_H #define DRAGONBONES_JSON_DATA_PARSER_H #include "DataParser.h" @@ -81,7 +81,7 @@ protected: inline static std::string _getString(const rapidjson::Value& rawData, const char* key, - std::string_view defaultValue) + const std::string& defaultValue) { if (rawData.HasMember(key)) { @@ -93,7 +93,7 @@ protected: return dragonBones::to_string(rawData[key].GetDouble()); } - return std::string{defaultValue}; + return defaultValue; } inline static int _getParameter(const rapidjson::Value& rawData, std::size_t index, int defaultValue) @@ -118,14 +118,14 @@ protected: inline static std::string _getParameter(const rapidjson::Value& rawData, std::size_t index, - std::string_view defaultValue) + const std::string& defaultValue) { if (rawData.Size() > index) { return rawData[(int)index].GetString(); } - return std::string{defaultValue}; + return defaultValue; } protected: @@ -160,10 +160,10 @@ private: std::vector _cacheRawMeshes; std::vector _cacheMeshes; std::vector _actionFrames; - hlookup::string_map _weightSlotPose; - hlookup::string_map _weightBonePoses; - hlookup::string_map> _cacheBones; - hlookup::string_map> _slotChildActions; + std::map _weightSlotPose; + std::map _weightBonePoses; + std::map> _cacheBones; + std::map> _slotChildActions; public: JSONDataParser() diff --git a/extensions/GUI/CCControlExtension/CCControlButton.cpp b/extensions/GUI/CCControlExtension/CCControlButton.cpp index 1d9ea36046..ba95b0ed8e 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.cpp +++ b/extensions/GUI/CCControlExtension/CCControlButton.cpp @@ -141,15 +141,15 @@ ControlButton* ControlButton::create(Node* label, return pRet; } -bool ControlButton::initWithTitleAndFontNameAndFontSize(std::string_view title, - std::string_view fontName, +bool ControlButton::initWithTitleAndFontNameAndFontSize(const std::string& title, + const std::string& fontName, float fontSize) { return initWithLabelAndBackgroundSprite(Label::createWithSystemFont(title, fontName, fontSize), cocos2d::ui::Scale9Sprite::create(), true); } -ControlButton* ControlButton::create(std::string_view title, std::string_view fontName, float fontSize) +ControlButton* ControlButton::create(const std::string& title, const std::string& fontName, float fontSize) { ControlButton* pRet = new ControlButton(); pRet->initWithTitleAndFontNameAndFontSize(title, fontName, fontSize); @@ -291,7 +291,7 @@ std::string ControlButton::getTitleForState(State state) return iter != _titleDispatchTable.end() ? iter->second : ""; } -void ControlButton::setTitleForState(std::string_view title, State state) +void ControlButton::setTitleForState(const std::string& title, State state) { _titleDispatchTable.erase((int)state); @@ -371,12 +371,12 @@ void ControlButton::setTitleLabelForState(Node* titleLabel, State state) } } -void ControlButton::setTitleTTFForState(std::string_view fontName, State state) +void ControlButton::setTitleTTFForState(const std::string& fontName, State state) { this->setTitleLabelForState(Label::createWithSystemFont(getTitleForState(state), fontName, 12), state); } -std::string_view ControlButton::getTitleTTFForState(State state) +const std::string& ControlButton::getTitleTTFForState(State state) { LabelProtocol* label = dynamic_cast(this->getTitleLabelForState(state)); Label* labelTTF = dynamic_cast(label); @@ -416,13 +416,13 @@ float ControlButton::getTitleTTFSizeForState(State state) } } -void ControlButton::setTitleBMFontForState(std::string_view fntFile, State state) +void ControlButton::setTitleBMFontForState(const std::string& fntFile, State state) { std::string title = this->getTitleForState(state); this->setTitleLabelForState(Label::createWithBMFont(fntFile, title), state); } -std::string_view ControlButton::getTitleBMFontForState(State state) +const std::string& ControlButton::getTitleBMFontForState(State state) { LabelProtocol* label = dynamic_cast(this->getTitleLabelForState(state)); auto labelBMFont = dynamic_cast(label); diff --git a/extensions/GUI/CCControlExtension/CCControlButton.h b/extensions/GUI/CCControlExtension/CCControlButton.h index 9a5f80734f..51a8fcac34 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.h +++ b/extensions/GUI/CCControlExtension/CCControlButton.h @@ -57,7 +57,7 @@ public: static ControlButton* create(); static ControlButton* create(cocos2d::ui::Scale9Sprite* sprite); static ControlButton* create(Node* label, cocos2d::ui::Scale9Sprite* backgroundSprite); - static ControlButton* create(std::string_view title, std::string_view fontName, float fontSize); + static ControlButton* create(const std::string& title, const std::string& fontName, float fontSize); static ControlButton* create(Node* label, cocos2d::ui::Scale9Sprite* backgroundSprite, bool adjustBackGroundSize); virtual void needsLayout() override; @@ -87,7 +87,7 @@ public: * @param state The state that uses the specified title. The values are described * in "CCControlState". */ - virtual void setTitleForState(std::string_view title, State state); + virtual void setTitleForState(const std::string& title, State state); /** * Returns the title color used for a state. @@ -128,8 +128,8 @@ public: */ virtual void setTitleLabelForState(Node* label, State state); - virtual void setTitleTTFForState(std::string_view fntFile, State state); - virtual std::string_view getTitleTTFForState(State state); + virtual void setTitleTTFForState(const std::string& fntFile, State state); + virtual const std::string& getTitleTTFForState(State state); virtual void setTitleTTFSizeForState(float size, State state); virtual float getTitleTTFSizeForState(State state); @@ -140,8 +140,8 @@ public: * @param state The state that uses the specified fntFile. The values are described * in "CCControlState". */ - virtual void setTitleBMFontForState(std::string_view fntFile, State state); - virtual std::string_view getTitleBMFontForState(State state); + virtual void setTitleBMFontForState(const std::string& fntFile, State state); + virtual const std::string& getTitleBMFontForState(State state); /** * Returns the background sprite used for a state. @@ -188,7 +188,7 @@ public: virtual void setColor(const Color3B&) override; virtual void updateDisplayedColor(const Color3B& parentColor) override; - std::string_view getCurrentTitle() const { return _currentTitle; }; + const std::string& getCurrentTitle() const { return _currentTitle; }; std::string getCurrentTitle() { return _currentTitle; }; CC_CONSTRUCTOR_ACCESS : @@ -207,7 +207,9 @@ public: cocos2d::ui::Scale9Sprite* backgroundSprite, bool adjustBackGroundSize); virtual bool initWithBackgroundSprite(cocos2d::ui::Scale9Sprite* sprite); - virtual bool initWithTitleAndFontNameAndFontSize(std::string_view title, std::string_view fontName, float fontSize); + virtual bool initWithTitleAndFontNameAndFontSize(const std::string& title, + const std::string& fontName, + float fontSize); protected: bool _isPushed; diff --git a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp index 431b465a6c..09d14b6e6a 100644 --- a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp +++ b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp @@ -78,7 +78,7 @@ public: * @js NA * @lua NA */ - virtual void updateTweenAction(float value, std::string_view key) override; + virtual void updateTweenAction(float value, const std::string& key) override; /** Contains the position (in x-axis) of the slider inside the receiver. */ float _sliderXPosition; @@ -214,7 +214,7 @@ bool ControlSwitchSprite::initWithMaskSprite(Sprite* maskSprite, return false; } -void ControlSwitchSprite::updateTweenAction(float value, std::string_view key) +void ControlSwitchSprite::updateTweenAction(float value, const std::string& key) { CCLOGINFO("key = %s, value = %f", key.c_str(), value); setSliderXPosition(value); diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index bfa2cf5e12..6bf9f47288 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -327,7 +327,7 @@ void ScrollView::setZoomScaleInDuration(float s, float dt) } } -void ScrollView::updateTweenAction(float value, std::string_view /*key*/) +void ScrollView::updateTweenAction(float value, const std::string& /*key*/) { this->setZoomScale(value); } @@ -551,7 +551,7 @@ void ScrollView::removeAllChildren() removeAllChildrenWithCleanup(true); } -void ScrollView::addChild(Node* child, int zOrder, std::string_view name) +void ScrollView::addChild(Node* child, int zOrder, const std::string& name) { if (_container != child) { diff --git a/extensions/GUI/CCScrollView/CCScrollView.h b/extensions/GUI/CCScrollView/CCScrollView.h index 9aef265af4..304f4cab75 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.h +++ b/extensions/GUI/CCScrollView/CCScrollView.h @@ -251,7 +251,7 @@ public: using Node::addChild; virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, std::string_view name) override; + virtual void addChild(Node* child, int zOrder, const std::string& name) override; virtual void removeAllChildren() override; virtual void removeAllChildrenWithCleanup(bool cleanup) override; @@ -259,7 +259,7 @@ public: /** * CCActionTweenDelegate */ - void updateTweenAction(float value, std::string_view key) override; + void updateTweenAction(float value, const std::string& key) override; bool hasVisibleParents() const; diff --git a/extensions/ImGuiEXT/CCImGuiEXT.cpp b/extensions/ImGuiEXT/CCImGuiEXT.cpp index 000806050e..b3b801a33e 100644 --- a/extensions/ImGuiEXT/CCImGuiEXT.cpp +++ b/extensions/ImGuiEXT/CCImGuiEXT.cpp @@ -5,12 +5,12 @@ NS_CC_EXT_BEGIN -static uint32_t fourccValue(std::string_view str) +static uint32_t fourccValue(const std::string& str) { if (str.empty() || str[0] != '#') return (uint32_t)-1; uint32_t value = 0; - memcpy(&value, str.data() + 1, std::min(sizeof(value), str.size() - 1)); + memcpy(&value, str.c_str() + 1, std::min(sizeof(value), str.size() - 1)); return value; } @@ -246,7 +246,7 @@ float ImGuiEXT::scaleAllByDPI(float userScale) return zoomFactor; } -void ImGuiEXT::addFont(std::string_view fontFile, float fontSize, CHS_GLYPH_RANGE glyphRange) +void ImGuiEXT::addFont(const std::string& fontFile, float fontSize, CHS_GLYPH_RANGE glyphRange) { if (FileUtils::getInstance()->isFileExistInternal(fontFile)) { @@ -255,7 +255,7 @@ void ImGuiEXT::addFont(std::string_view fontFile, float fontSize, CHS_GLYPH_RANG } } -void ImGuiEXT::removeFont(std::string_view fontFile) +void ImGuiEXT::removeFont(const std::string& fontFile) { auto count = _fontsInfoMap.size(); _fontsInfoMap.erase(fontFile); @@ -339,7 +339,7 @@ void ImGuiEXT::update() // commands will be processed after update } -bool ImGuiEXT::addRenderLoop(std::string_view id, std::function func, Scene* target) +bool ImGuiEXT::addRenderLoop(const std::string& id, std::function func, Scene* target) { // TODO: check whether exist auto fourccId = fourccValue(id); @@ -362,7 +362,7 @@ bool ImGuiEXT::addRenderLoop(std::string_view id, std::function func, Sc return false; } -void ImGuiEXT::removeRenderLoop(std::string_view id) +void ImGuiEXT::removeRenderLoop(const std::string& id) { auto fourccId = fourccValue(id); const auto iter = _renderPiplines.find(fourccId); @@ -603,16 +603,16 @@ void ImGuiEXT::setLabelColor(Label* label, ImGuiCol col) setLabelColor(label, ImGui::GetStyleColorVec4(col)); } -ImWchar* ImGuiEXT::addGlyphRanges(std::string_view key, const std::vector& ranges) +ImWchar* ImGuiEXT::addGlyphRanges(const std::string& key, const std::vector& ranges) { auto it = glyphRanges.find(key); // the pointer must be persistant, do not replace if (it != glyphRanges.end()) return it->second.data(); - it = glyphRanges.emplace(key, ranges).first; // glyphRanges[key] = ranges; + glyphRanges[key] = ranges; if (ranges.empty()) - it->second.push_back(0); - return it->second.data(); + glyphRanges[key].push_back(0); + return glyphRanges[key].data(); } void ImGuiEXT::mergeFontGlyphs(ImFont* dst, ImFont* src, ImWchar start, ImWchar end) @@ -712,13 +712,13 @@ void ImGuiEXT::setMarkdownFont(int index, ImFont* font, bool seperator, float sc ImGuiMarkdownConfig.headingScales[index] = scale; } -void ImGuiEXT::setMarkdownLinkIcon(std::string_view icon) +void ImGuiEXT::setMarkdownLinkIcon(const std::string& icon) { ImGuiMarkdownLinkIcon = icon; ImGuiMarkdownConfig.linkIcon = ImGuiMarkdownLinkIcon.c_str(); } -void ImGuiEXT::markdown(std::string_view content) +void ImGuiEXT::markdown(const std::string& content) { ImGui::Markdown(content.c_str(), content.size(), ImGuiMarkdownConfig); } diff --git a/extensions/ImGuiEXT/CCImGuiEXT.h b/extensions/ImGuiEXT/CCImGuiEXT.h index c03cddc0c2..7c80b711c7 100644 --- a/extensions/ImGuiEXT/CCImGuiEXT.h +++ b/extensions/ImGuiEXT/CCImGuiEXT.h @@ -50,10 +50,10 @@ public: /// /// /// - void addFont(std::string_view fontFile, + void addFont(const std::string& fontFile, float fontSize = DEFAULT_FONT_SIZE, CHS_GLYPH_RANGE glyphRange = CHS_GLYPH_RANGE::NONE); - void removeFont(std::string_view fontFile); + void removeFont(const std::string& fontFile); void clearFonts(); /// @@ -62,13 +62,13 @@ public: /// The FOURCC id of render loop, starts with '#', such as "#abcd" /// the ImGui render loop /// The target scene to track event, nullptr for global, useful for global GM tools - bool addRenderLoop(std::string_view id, std::function func, Scene* target); + bool addRenderLoop(const std::string& id, std::function func, Scene* target); /// /// Remove ImGui render loop /// /// FOURCC starts with '#', such as "#abcd" - void removeRenderLoop(std::string_view id); + void removeRenderLoop(const std::string& id); void end(); @@ -112,7 +112,7 @@ public: static void setLabelColor(Label* label, bool disabled = false); static void setLabelColor(Label* label, ImGuiCol col); - ImWchar* addGlyphRanges(std::string_view key, const std::vector& ranges); + ImWchar* addGlyphRanges(const std::string& key, const std::vector& ranges); static void mergeFontGlyphs(ImFont* dst, ImFont* src, ImWchar start, ImWchar end); int getCCRefId(Ref* p); @@ -126,8 +126,8 @@ public: void setMarkdownLinkCallback(const MdLinkCallback& f); void setMarkdownImageCallback(const MdImageCallback& f); void setMarkdownFont(int index, ImFont* font, bool seperator, float scale = 1.f); - void setMarkdownLinkIcon(std::string_view icon); - void markdown(std::string_view content); + void setMarkdownLinkIcon(const std::string& icon); + void markdown(const std::string& content); #endif private: @@ -154,7 +154,7 @@ private: std::unordered_map usedCCRefIdMap; // cocos objects should be retained until next frame Vector usedCCRef; - hlookup::string_map> glyphRanges; + std::unordered_map> glyphRanges; float _contentZoomFactor = 1.0f; @@ -168,7 +168,7 @@ private: CHS_GLYPH_RANGE glyphRange; }; - hlookup::string_map _fontsInfoMap; + std::unordered_map _fontsInfoMap; bool _purgeNextLoop = false; }; diff --git a/extensions/ImGuiEXT/imgui/imconfig.h b/extensions/ImGuiEXT/imgui/imconfig.h index 768377be30..d84c59423b 100644 --- a/extensions/ImGuiEXT/imgui/imconfig.h +++ b/extensions/ImGuiEXT/imgui/imconfig.h @@ -32,36 +32,36 @@ //#define IMGUI_API __declspec( dllimport ) //---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to avoid -// using soon-to-be obsolete function/names. #define IMGUI_DISABLE_OBSOLETE_FUNCTIONS +//using soon-to-be obsolete function/names. #define IMGUI_DISABLE_OBSOLETE_FUNCTIONS //---- Disable all of Dear ImGui or don't implement standard windows. // It is very strongly recommended to NOT disable the demo windows during development. Please read comments in // imgui_demo.cpp. //#define IMGUI_DISABLE // Disable everything: all headers and source files will be -// empty. #define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: -// ShowDemoWindow()/ShowStyleEditor() will be empty. Not recommended. #define IMGUI_DISABLE_METRICS_WINDOW // Disable -// metrics/debugger window: ShowMetricsWindow() will be empty. +//empty. #define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: +//ShowDemoWindow()/ShowStyleEditor() will be empty. Not recommended. #define IMGUI_DISABLE_METRICS_WINDOW // Disable +//metrics/debugger window: ShowMetricsWindow() will be empty. //---- Don't implement some functions to reduce linkage requirements. //#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't -// use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a) #define -// IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME -// handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW) #define -// IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't -// implement default IME handler (won't require imm32.lib/.a) #define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use -// and link with any Win32 function (clipboard, ime). #define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] -// Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not -// the default). #define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement -// ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf) +//use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a) #define +//IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME +//handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW) #define +//IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't +//implement default IME handler (won't require imm32.lib/.a) #define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use +//and link with any Win32 function (clipboard, ime). #define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] +//Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not +//the default). #define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement +//ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf) //#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement -// ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself. #define -// IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite -// and ImFileHandle at all (replace them with dummies) #define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // -// Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if -// you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function. #define -// IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to -// avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). #define IMGUI_DISABLE_SSE // Disable -// use of SSE intrinsics even if available +//ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself. #define +//IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and +//ImFileHandle at all (replace them with dummies) #define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't +//implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you +//don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function. #define +//IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to +//avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). #define IMGUI_DISABLE_SSE // Disable +//use of SSE intrinsics even if available //---- Include imgui_user.h at the end of imgui.h as a convenience //#define IMGUI_INCLUDE_IMGUI_USER_H @@ -70,7 +70,7 @@ //#define IMGUI_USE_BGRA_PACKED_COLOR //---- Use 32-bit for ImWchar (default is 16-bit) to support unicode planes 1-16. (e.g. point beyond 0xFFFF like -// emoticons, dingbats, symbols, shapes, ancient languages, etc...) #define IMGUI_USE_WCHAR32 +//emoticons, dingbats, symbols, shapes, ancient languages, etc...) #define IMGUI_USE_WCHAR32 //---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version // By default the embedded implementations are declared static and not available outside of Dear ImGui sources files. @@ -80,13 +80,13 @@ //#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION //---- Use stb_printf's faster implementation of vsnprintf instead of the one from libc (unless -// IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined) +//IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined) // Requires 'stb_sprintf.h' to be available in the include path. Compatibility checks of arguments and formats done by // clang and GCC will be disabled in order to support the extra formats provided by STB sprintf. #define // IMGUI_USE_STB_SPRINTF //---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear -// ImGui) +//ImGui) // Requires FreeType headers to be available in the include path. Requires program to be compiled with // 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided). On Windows you may use // vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'. diff --git a/extensions/ImGuiEXT/imgui/imgui.cpp b/extensions/ImGuiEXT/imgui/imgui.cpp index e9c52c3bf0..e8f0481d39 100644 --- a/extensions/ImGuiEXT/imgui/imgui.cpp +++ b/extensions/ImGuiEXT/imgui/imgui.cpp @@ -1115,7 +1115,7 @@ you share your issues (on GitHub or privately). # endif # pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' # pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more - // terse. + // terse. # pragma clang diagnostic ignored \ "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing // against same constants (typically 0.0f) is ok. @@ -19477,7 +19477,7 @@ void ImGui::DebugNodeViewport(ImGuiViewportP* viewport) } BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags, //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is - // the standard + //the standard (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "", (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "", (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "", diff --git a/extensions/ImGuiEXT/imgui/imgui.h b/extensions/ImGuiEXT/imgui/imgui.h index 91c3a68e89..279b007319 100644 --- a/extensions/ImGuiEXT/imgui/imgui.h +++ b/extensions/ImGuiEXT/imgui/imgui.h @@ -2114,9 +2114,9 @@ enum ImGuiTableFlags_ // Obsolete names (will be removed soon) # ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS //, ImGuiTableFlags_ColumnsWidthFixed = ImGuiTableFlags_SizingFixedFit, ImGuiTableFlags_ColumnsWidthStretch = -// ImGuiTableFlags_SizingStretchSame // WIP Tables 2020/12 , ImGuiTableFlags_SizingPolicyFixed = -// ImGuiTableFlags_SizingFixedFit, ImGuiTableFlags_SizingPolicyStretch = ImGuiTableFlags_SizingStretchSame // WIP -// Tables 2021/01 +//ImGuiTableFlags_SizingStretchSame // WIP Tables 2020/12 , ImGuiTableFlags_SizingPolicyFixed = +//ImGuiTableFlags_SizingFixedFit, ImGuiTableFlags_SizingPolicyStretch = ImGuiTableFlags_SizingStretchSame // WIP +//Tables 2021/01 # endif }; diff --git a/extensions/ImGuiEXT/imgui/imgui_demo.cpp b/extensions/ImGuiEXT/imgui/imgui_demo.cpp index 26d3e0c97a..1818e5ff63 100644 --- a/extensions/ImGuiEXT/imgui/imgui_demo.cpp +++ b/extensions/ImGuiEXT/imgui/imgui_demo.cpp @@ -112,7 +112,7 @@ Index of this file: # endif # pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' # pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more - // terse. + // terse. # pragma clang diagnostic ignored \ "-Wdeprecated-declarations" // warning: 'xx' is deprecated: The POSIX name for this.. // for strdup used // in demo code (so user can copy & paste the code) diff --git a/extensions/ImGuiEXT/imgui/imgui_draw.cpp b/extensions/ImGuiEXT/imgui/imgui_draw.cpp index b251bc25fa..7732f20105 100644 --- a/extensions/ImGuiEXT/imgui/imgui_draw.cpp +++ b/extensions/ImGuiEXT/imgui/imgui_draw.cpp @@ -81,7 +81,7 @@ Index of this file: # endif # pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' # pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more - // terse. + // terse. # pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // // storing and comparing against same constants ok. # pragma clang diagnostic ignored \ diff --git a/extensions/ImGuiEXT/imgui/imgui_tables.cpp b/extensions/ImGuiEXT/imgui/imgui_tables.cpp index c29b320b6f..beac7c6287 100644 --- a/extensions/ImGuiEXT/imgui/imgui_tables.cpp +++ b/extensions/ImGuiEXT/imgui/imgui_tables.cpp @@ -260,7 +260,7 @@ Index of this file: # endif # pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' # pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more - // terse. + // terse. # pragma clang diagnostic ignored \ "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing // against same constants (typically 0.0f) is ok. diff --git a/extensions/ImGuiEXT/imgui/imgui_widgets.cpp b/extensions/ImGuiEXT/imgui/imgui_widgets.cpp index 02be448625..9b68c0359f 100644 --- a/extensions/ImGuiEXT/imgui/imgui_widgets.cpp +++ b/extensions/ImGuiEXT/imgui/imgui_widgets.cpp @@ -78,7 +78,7 @@ Index of this file: # endif # pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' # pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more - // terse. + // terse. # pragma clang diagnostic ignored \ "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing // against same constants (typically 0.0f) is ok. diff --git a/extensions/Particle3D/CCParticle3DRender.cpp b/extensions/Particle3D/CCParticle3DRender.cpp index d2907930af..58b022430e 100644 --- a/extensions/Particle3D/CCParticle3DRender.cpp +++ b/extensions/Particle3D/CCParticle3DRender.cpp @@ -51,7 +51,7 @@ Particle3DQuadRender::~Particle3DQuadRender() CC_SAFE_RELEASE(_indexBuffer); } -Particle3DQuadRender* Particle3DQuadRender::create(std::string_view texFile) +Particle3DQuadRender* Particle3DQuadRender::create(const std::string& texFile) { auto ret = new Particle3DQuadRender(); if (ret->initQuadRender(texFile)) @@ -185,7 +185,7 @@ void Particle3DQuadRender::render(Renderer* renderer, const Mat4& transform, Par renderer->addCommand(&_afterCommand); } -bool Particle3DQuadRender::initQuadRender(std::string_view texFile) +bool Particle3DQuadRender::initQuadRender(const std::string& texFile) { CC_SAFE_RELEASE_NULL(_programState); @@ -285,7 +285,7 @@ Particle3DModelRender::~Particle3DModelRender() } } -Particle3DModelRender* Particle3DModelRender::create(std::string_view modelFile, std::string_view texFile) +Particle3DModelRender* Particle3DModelRender::create(const std::string& modelFile, const std::string& texFile) { auto ret = new Particle3DModelRender(); ret->_modelFile = modelFile; diff --git a/extensions/Particle3D/CCParticle3DRender.h b/extensions/Particle3D/CCParticle3DRender.h index 0d2d0b0188..aaa0d70104 100644 --- a/extensions/Particle3D/CCParticle3DRender.h +++ b/extensions/Particle3D/CCParticle3DRender.h @@ -95,7 +95,7 @@ protected: class CC_EX_DLL Particle3DQuadRender : public Particle3DRender { public: - static Particle3DQuadRender* create(std::string_view texFile = ""); + static Particle3DQuadRender* create(const std::string& texFile = ""); virtual void render(Renderer* renderer, const Mat4& transform, ParticleSystem3D* particleSystem) override; @@ -104,7 +104,7 @@ public: virtual ~Particle3DQuadRender(); protected: - bool initQuadRender(std::string_view texFile); + bool initQuadRender(const std::string& texFile); void onBeforeDraw(); void onAfterDraw(); @@ -145,7 +145,7 @@ protected: class CC_EX_DLL Particle3DModelRender : public Particle3DRender { public: - static Particle3DModelRender* create(std::string_view modelFile, std::string_view texFile = ""); + static Particle3DModelRender* create(const std::string& modelFile, const std::string& texFile = ""); virtual void render(Renderer* renderer, const Mat4& transform, ParticleSystem3D* particleSystem) override; diff --git a/extensions/Particle3D/PU/CCPUAffector.cpp b/extensions/Particle3D/PU/CCPUAffector.cpp index a41dfc001d..7f0ea5bbdd 100644 --- a/extensions/Particle3D/PU/CCPUAffector.cpp +++ b/extensions/Particle3D/PU/CCPUAffector.cpp @@ -161,16 +161,16 @@ void PUAffector::copyAttributesTo(PUAffector* affector) affector->_excludedEmitters = _excludedEmitters; } -void PUAffector::addEmitterToExclude(std::string_view emitterName) +void PUAffector::addEmitterToExclude(const std::string& emitterName) { auto iter = std::find(_excludedEmitters.begin(), _excludedEmitters.end(), emitterName); if (iter == _excludedEmitters.end()) { - _excludedEmitters.push_back(std::string{emitterName}); + _excludedEmitters.push_back(emitterName); } } -void PUAffector::removeEmitterToExclude(std::string_view emitterName) +void PUAffector::removeEmitterToExclude(const std::string& emitterName) { auto iter = std::find(_excludedEmitters.begin(), _excludedEmitters.end(), emitterName); if (iter != _excludedEmitters.end()) @@ -189,8 +189,8 @@ void PUAffector::process(PUParticle3D* particle, float delta, bool firstParticle if (!_excludedEmitters.empty() && particle->parentEmitter) { // Return if the emitter which emits this particle is part of the vector - auto emitterName = particle->parentEmitter->getName(); - auto iter = std::find(_excludedEmitters.begin(), _excludedEmitters.end(), emitterName); + std::string emitterName = particle->parentEmitter->getName(); + auto iter = std::find(_excludedEmitters.begin(), _excludedEmitters.end(), emitterName); if (iter != _excludedEmitters.end()) { return; diff --git a/extensions/Particle3D/PU/CCPUAffector.h b/extensions/Particle3D/PU/CCPUAffector.h index 255401c9a6..219d620568 100644 --- a/extensions/Particle3D/PU/CCPUAffector.h +++ b/extensions/Particle3D/PU/CCPUAffector.h @@ -91,22 +91,22 @@ public: /** Todo */ - std::string_view getAffectorType() const { return _affectorType; }; - void setAffectorType(std::string_view affectorType) { _affectorType = affectorType; }; + const std::string& getAffectorType() const { return _affectorType; }; + void setAffectorType(const std::string& affectorType) { _affectorType = affectorType; }; /** Add a ParticleEmitter name that excludes Particles emitted by this ParticleEmitter from being affected. */ - void addEmitterToExclude(std::string_view emitterName); + void addEmitterToExclude(const std::string& emitterName); /** Remove a ParticleEmitter name that excludes Particles emitted by this ParticleEmitter. */ - void removeEmitterToExclude(std::string_view emitterName); + void removeEmitterToExclude(const std::string& emitterName); /** Todo */ - std::string_view getName() const { return _name; }; - void setName(std::string_view name) { _name = name; }; + const std::string& getName() const { return _name; }; + void setName(const std::string& name) { _name = name; }; virtual void copyAttributesTo(PUAffector* affector); diff --git a/extensions/Particle3D/PU/CCPUAffectorManager.cpp b/extensions/Particle3D/PU/CCPUAffectorManager.cpp index c5be72d24d..e9b4e5e00f 100644 --- a/extensions/Particle3D/PU/CCPUAffectorManager.cpp +++ b/extensions/Particle3D/PU/CCPUAffectorManager.cpp @@ -63,7 +63,7 @@ PUAffectorManager* PUAffectorManager::Instance() return &pam; } -PUScriptTranslator* PUAffectorManager::getTranslator(std::string_view type) +PUScriptTranslator* PUAffectorManager::getTranslator(const std::string& type) { if (type == "Align") { @@ -172,7 +172,7 @@ PUScriptTranslator* PUAffectorManager::getTranslator(std::string_view type) return nullptr; } -PUAffector* PUAffectorManager::createAffector(std::string_view type) +PUAffector* PUAffectorManager::createAffector(const std::string& type) { if (type == "Align") { diff --git a/extensions/Particle3D/PU/CCPUAffectorManager.h b/extensions/Particle3D/PU/CCPUAffectorManager.h index 9a768d52fe..8fe439c10f 100644 --- a/extensions/Particle3D/PU/CCPUAffectorManager.h +++ b/extensions/Particle3D/PU/CCPUAffectorManager.h @@ -66,8 +66,8 @@ public: /** */ - PUScriptTranslator* getTranslator(std::string_view type); - PUAffector* createAffector(std::string_view type); + PUScriptTranslator* getTranslator(const std::string& type); + PUAffector* createAffector(const std::string& type); CC_CONSTRUCTOR_ACCESS : PUAffectorManager(); ~PUAffectorManager(); diff --git a/extensions/Particle3D/PU/CCPUBeamRender.cpp b/extensions/Particle3D/PU/CCPUBeamRender.cpp index d278f52dc8..c68c2f603e 100644 --- a/extensions/Particle3D/PU/CCPUBeamRender.cpp +++ b/extensions/Particle3D/PU/CCPUBeamRender.cpp @@ -49,7 +49,7 @@ const float PUBeamRender::DEFAULT_DEVIATION const size_t PUBeamRender::DEFAULT_NUMBER_OF_SEGMENTS = 2; const PUBillboardChain::TexCoordDirection PUBeamRender::DEFAULT_TEXTURE_DIRECTION = PUBillboardChain::TCD_V; -PUBeamRender* PUBeamRender::create(std::string_view texFile) +PUBeamRender* PUBeamRender::create(const std::string& texFile) { auto br = new PUBeamRender(); br->autorelease(); diff --git a/extensions/Particle3D/PU/CCPUBeamRender.h b/extensions/Particle3D/PU/CCPUBeamRender.h index 6d6e270295..0d0ccc8ed6 100644 --- a/extensions/Particle3D/PU/CCPUBeamRender.h +++ b/extensions/Particle3D/PU/CCPUBeamRender.h @@ -87,7 +87,7 @@ public: static const size_t DEFAULT_NUMBER_OF_SEGMENTS; static const PUBillboardChain::TexCoordDirection DEFAULT_TEXTURE_DIRECTION; - static PUBeamRender* create(std::string_view texFile = ""); + static PUBeamRender* create(const std::string& texFile = ""); virtual void prepare() override; virtual void unPrepare() override; diff --git a/extensions/Particle3D/PU/CCPUBehaviour.h b/extensions/Particle3D/PU/CCPUBehaviour.h index 745cfb669a..15d098d439 100644 --- a/extensions/Particle3D/PU/CCPUBehaviour.h +++ b/extensions/Particle3D/PU/CCPUBehaviour.h @@ -45,8 +45,8 @@ class CC_EX_DLL PUBehaviour : public Ref public: /** Todo */ - std::string_view getBehaviourType() const { return _behaviourType; }; - void setBehaviourType(std::string_view behaviourType) { _behaviourType = behaviourType; }; + const std::string& getBehaviourType() const { return _behaviourType; }; + void setBehaviourType(const std::string& behaviourType) { _behaviourType = behaviourType; }; /** Notify that the Behaviour is rescaled. */ diff --git a/extensions/Particle3D/PU/CCPUBehaviourManager.cpp b/extensions/Particle3D/PU/CCPUBehaviourManager.cpp index 2ce24c156a..6ff319f616 100644 --- a/extensions/Particle3D/PU/CCPUBehaviourManager.cpp +++ b/extensions/Particle3D/PU/CCPUBehaviourManager.cpp @@ -38,7 +38,7 @@ PUBehaviourManager* PUBehaviourManager::Instance() return &pam; } -PUScriptTranslator* PUBehaviourManager::getTranslator(std::string_view type) +PUScriptTranslator* PUBehaviourManager::getTranslator(const std::string& type) { if (type == "Slave") { @@ -47,7 +47,7 @@ PUScriptTranslator* PUBehaviourManager::getTranslator(std::string_view type) return nullptr; } -PUBehaviour* PUBehaviourManager::createBehaviour(std::string_view type) +PUBehaviour* PUBehaviourManager::createBehaviour(const std::string& type) { if (type == "Slave") { diff --git a/extensions/Particle3D/PU/CCPUBehaviourManager.h b/extensions/Particle3D/PU/CCPUBehaviourManager.h index 7f468f173a..91dfffb450 100644 --- a/extensions/Particle3D/PU/CCPUBehaviourManager.h +++ b/extensions/Particle3D/PU/CCPUBehaviourManager.h @@ -41,8 +41,8 @@ public: /** */ - PUScriptTranslator* getTranslator(std::string_view type); - PUBehaviour* createBehaviour(std::string_view type); + PUScriptTranslator* getTranslator(const std::string& type); + PUBehaviour* createBehaviour(const std::string& type); CC_CONSTRUCTOR_ACCESS : PUBehaviourManager(); ~PUBehaviourManager(); diff --git a/extensions/Particle3D/PU/CCPUBillboardChain.cpp b/extensions/Particle3D/PU/CCPUBillboardChain.cpp index f0646533e2..b83a9dcb4e 100644 --- a/extensions/Particle3D/PU/CCPUBillboardChain.cpp +++ b/extensions/Particle3D/PU/CCPUBillboardChain.cpp @@ -48,8 +48,8 @@ PUBillboardChain::Element::Element(const Vec3& pos, float w, float tex, const Ve : position(pos), width(w), texCoord(tex), color(col), orientation(ori) {} //----------------------------------------------------------------------- -PUBillboardChain::PUBillboardChain(std::string_view /*name*/, - std::string_view texFile, +PUBillboardChain::PUBillboardChain(const std::string& /*name*/, + const std::string& texFile, size_t maxElements, size_t numberOfChains, bool useTextureCoords, @@ -627,7 +627,7 @@ void PUBillboardChain::updateIndexBuffer() } } //----------------------------------------------------------------------- -void PUBillboardChain::init(std::string_view texFile) +void PUBillboardChain::init(const std::string& texFile) { CC_SAFE_RELEASE_NULL(_programState); diff --git a/extensions/Particle3D/PU/CCPUBillboardChain.h b/extensions/Particle3D/PU/CCPUBillboardChain.h index ce4b77cac5..329029d2ac 100644 --- a/extensions/Particle3D/PU/CCPUBillboardChain.h +++ b/extensions/Particle3D/PU/CCPUBillboardChain.h @@ -77,13 +77,13 @@ public: @param useVertexColours If true, use vertex colours from the chain elements @param dynamic If true, buffers are created with the intention of being updated */ - PUBillboardChain(std::string_view name, - std::string_view texFile = "", - size_t maxElements = 20, - size_t numberOfChains = 1, - bool useTextureCoords = true, - bool useColours = true, - bool dynamic = true); + PUBillboardChain(const std::string& name, + const std::string& texFile = "", + size_t maxElements = 20, + size_t numberOfChains = 1, + bool useTextureCoords = true, + bool useColours = true, + bool dynamic = true); /// destructor virtual ~PUBillboardChain(); @@ -245,7 +245,7 @@ protected: /// Update the contents of the index buffer virtual void updateIndexBuffer(); - void init(std::string_view texFile); + void init(const std::string& texFile); private: void onBeforeDraw(); diff --git a/extensions/Particle3D/PU/CCPUDoAffectorEventHandler.h b/extensions/Particle3D/PU/CCPUDoAffectorEventHandler.h index b4425d880c..3c2985c3d1 100644 --- a/extensions/Particle3D/PU/CCPUDoAffectorEventHandler.h +++ b/extensions/Particle3D/PU/CCPUDoAffectorEventHandler.h @@ -57,11 +57,11 @@ public: /** Get the name of the affector that must be enabled or disabled. */ - std::string_view getAffectorName() const { return _affectorName; }; + const std::string& getAffectorName() const { return _affectorName; }; /** Set the name of the affector. */ - void setAffectorName(std::string_view affectorName) { _affectorName = affectorName; }; + void setAffectorName(const std::string& affectorName) { _affectorName = affectorName; }; /** If the _handle() function of this class is invoked (by an Observer), it searches the ParticleAffector defined by the its name. diff --git a/extensions/Particle3D/PU/CCPUDoEnableComponentEventHandler.h b/extensions/Particle3D/PU/CCPUDoEnableComponentEventHandler.h index 94e56865f2..9c9ff4c0fd 100644 --- a/extensions/Particle3D/PU/CCPUDoEnableComponentEventHandler.h +++ b/extensions/Particle3D/PU/CCPUDoEnableComponentEventHandler.h @@ -47,11 +47,11 @@ public: /** Get the name of the component that must be enabled or disabled. */ - std::string_view getComponentName() const { return _componentName; }; + const std::string& getComponentName() const { return _componentName; }; /** Set the name of the component that must be enabled or disables. */ - void setComponentName(std::string_view componentName) { _componentName = componentName; }; + void setComponentName(const std::string& componentName) { _componentName = componentName; }; /** Get the value that identifies whether the component must be enabled or disabled. */ diff --git a/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.cpp b/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.cpp index d572be1118..f70ba179ff 100644 --- a/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.cpp +++ b/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.cpp @@ -241,7 +241,7 @@ void PUDoPlacementParticleEventHandler::particleExpired(PUParticleSystem3D* /*pa {} //----------------------------------------------------------------------- -void PUDoPlacementParticleEventHandler::setForceEmitterName(std::string_view forceEmitterName) +void PUDoPlacementParticleEventHandler::setForceEmitterName(const std::string& forceEmitterName) { _forceEmitterName = forceEmitterName; } diff --git a/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.h b/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.h index 3304e73094..cb33bb8cbd 100644 --- a/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.h +++ b/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.h @@ -78,11 +78,11 @@ public: /** Get the name of the emitter that is used to emit its particles. */ - std::string_view getForceEmitterName() const { return _forceEmitterName; }; + const std::string& getForceEmitterName() const { return _forceEmitterName; }; /** Set the name of the emitter that is used to emit its particles. */ - void setForceEmitterName(std::string_view forceEmitterName); + void setForceEmitterName(const std::string& forceEmitterName); /** Returns a pointer to the emitter that is used as a force emitter. */ diff --git a/extensions/Particle3D/PU/CCPUEmitter.cpp b/extensions/Particle3D/PU/CCPUEmitter.cpp index 2914895a70..fdf3ac0487 100644 --- a/extensions/Particle3D/PU/CCPUEmitter.cpp +++ b/extensions/Particle3D/PU/CCPUEmitter.cpp @@ -497,7 +497,7 @@ void PUEmitter::setParticleTextureCoordsRangeEnd(const unsigned short& particleT } //----------------------------------------------------------------------- -void PUEmitter::setEmitsName(std::string_view emitsName) +void PUEmitter::setEmitsName(const std::string& emitsName) { _emitsName = emitsName; _emitsEntity = nullptr; diff --git a/extensions/Particle3D/PU/CCPUEmitter.h b/extensions/Particle3D/PU/CCPUEmitter.h index bccc699bdf..4aa3c3a163 100644 --- a/extensions/Particle3D/PU/CCPUEmitter.h +++ b/extensions/Particle3D/PU/CCPUEmitter.h @@ -112,13 +112,13 @@ public: /** Todo */ - std::string_view getEmitterType() const { return _emitterType; } - void setEmitterType(std::string_view emitterType) { _emitterType = emitterType; }; + const std::string& getEmitterType() const { return _emitterType; } + void setEmitterType(const std::string& emitterType) { _emitterType = emitterType; }; /** Todo */ - std::string_view getName() const { return _name; } - void setName(std::string_view name) { _name = name; }; + const std::string& getName() const { return _name; } + void setName(const std::string& name) { _name = name; }; /** Todo */ @@ -188,8 +188,8 @@ public: /** Todo */ - std::string_view getEmitsName() const { return _emitsName; } - void setEmitsName(std::string_view emitsName); + const std::string& getEmitsName() const { return _emitsName; } + void setEmitsName(const std::string& emitsName); PUParticle3D::ParticleType getEmitsType() const { return _emitsType; } void setEmitsType(PUParticle3D::ParticleType type) { _emitsType = type; }; Ref* getEmitsEntityPtr() const; diff --git a/extensions/Particle3D/PU/CCPUEmitterManager.cpp b/extensions/Particle3D/PU/CCPUEmitterManager.cpp index 4c587b04aa..f18566fc94 100644 --- a/extensions/Particle3D/PU/CCPUEmitterManager.cpp +++ b/extensions/Particle3D/PU/CCPUEmitterManager.cpp @@ -45,7 +45,7 @@ PUEmitterManager* PUEmitterManager::Instance() return &ptm; } -PUScriptTranslator* PUEmitterManager::getTranslator(std::string_view type) +PUScriptTranslator* PUEmitterManager::getTranslator(const std::string& type) { if (type == "Box") { @@ -86,7 +86,7 @@ PUScriptTranslator* PUEmitterManager::getTranslator(std::string_view type) return nullptr; } -PUEmitter* PUEmitterManager::createEmitter(std::string_view type) +PUEmitter* PUEmitterManager::createEmitter(const std::string& type) { if (type == "Box") { diff --git a/extensions/Particle3D/PU/CCPUEmitterManager.h b/extensions/Particle3D/PU/CCPUEmitterManager.h index 5affa49ef8..00ee4c33ae 100644 --- a/extensions/Particle3D/PU/CCPUEmitterManager.h +++ b/extensions/Particle3D/PU/CCPUEmitterManager.h @@ -48,8 +48,8 @@ public: /** */ - PUScriptTranslator* getTranslator(std::string_view type); - PUEmitter* createEmitter(std::string_view type); + PUScriptTranslator* getTranslator(const std::string& type); + PUEmitter* createEmitter(const std::string& type); CC_CONSTRUCTOR_ACCESS : PUEmitterManager(); ~PUEmitterManager(); diff --git a/extensions/Particle3D/PU/CCPUEventHandler.h b/extensions/Particle3D/PU/CCPUEventHandler.h index a9f4582b77..771252122f 100644 --- a/extensions/Particle3D/PU/CCPUEventHandler.h +++ b/extensions/Particle3D/PU/CCPUEventHandler.h @@ -44,8 +44,8 @@ class CC_EX_DLL PUEventHandler : public Ref public: /** Todo */ - std::string_view getName() const { return _name; }; - void setName(std::string_view name) { _name = name; }; + const std::string& getName() const { return _name; }; + void setName(const std::string& name) { _name = name; }; /** Todo */ @@ -54,8 +54,8 @@ public: /** Todo */ - std::string_view getEventHandlerType() const { return _eventHandlerType; }; - void setEventHandlerType(std::string_view eventHandlerType) { _eventHandlerType = eventHandlerType; }; + const std::string& getEventHandlerType() const { return _eventHandlerType; }; + void setEventHandlerType(const std::string& eventHandlerType) { _eventHandlerType = eventHandlerType; }; /** Notify that the event handler is rescaled. */ diff --git a/extensions/Particle3D/PU/CCPUEventHandlerManager.cpp b/extensions/Particle3D/PU/CCPUEventHandlerManager.cpp index 06206b7b99..df3803a8f4 100644 --- a/extensions/Particle3D/PU/CCPUEventHandlerManager.cpp +++ b/extensions/Particle3D/PU/CCPUEventHandlerManager.cpp @@ -44,7 +44,7 @@ PUEventHandlerManager* PUEventHandlerManager::Instance() return &pem; } -PUScriptTranslator* PUEventHandlerManager::getTranslator(std::string_view type) +PUScriptTranslator* PUEventHandlerManager::getTranslator(const std::string& type) { if (type == "DoAffector") { @@ -77,7 +77,7 @@ PUScriptTranslator* PUEventHandlerManager::getTranslator(std::string_view type) return nullptr; } -PUEventHandler* PUEventHandlerManager::createEventHandler(std::string_view type) +PUEventHandler* PUEventHandlerManager::createEventHandler(const std::string& type) { if (type == "DoAffector") { diff --git a/extensions/Particle3D/PU/CCPUEventHandlerManager.h b/extensions/Particle3D/PU/CCPUEventHandlerManager.h index bd09e1487c..2cc470c60b 100644 --- a/extensions/Particle3D/PU/CCPUEventHandlerManager.h +++ b/extensions/Particle3D/PU/CCPUEventHandlerManager.h @@ -45,8 +45,8 @@ public: /** */ - PUScriptTranslator* getTranslator(std::string_view type); - PUEventHandler* createEventHandler(std::string_view type); + PUScriptTranslator* getTranslator(const std::string& type); + PUEventHandler* createEventHandler(const std::string& type); CC_CONSTRUCTOR_ACCESS : diff --git a/extensions/Particle3D/PU/CCPULineEmitter.cpp b/extensions/Particle3D/PU/CCPULineEmitter.cpp index 674822c247..394307f312 100644 --- a/extensions/Particle3D/PU/CCPULineEmitter.cpp +++ b/extensions/Particle3D/PU/CCPULineEmitter.cpp @@ -92,7 +92,7 @@ unsigned short PULineEmitter::calculateRequestedParticles(float timeElapsed) //{ // notifyStart(); // mParentTechnique->lockAllParticles(); // Needed to set the first generated particle also first in the - // list with particles + //list with particles // } } diff --git a/extensions/Particle3D/PU/CCPUMaterialManager.cpp b/extensions/Particle3D/PU/CCPUMaterialManager.cpp index 3e1d3469e5..05aa70292c 100644 --- a/extensions/Particle3D/PU/CCPUMaterialManager.cpp +++ b/extensions/Particle3D/PU/CCPUMaterialManager.cpp @@ -77,7 +77,7 @@ PUMaterialCache* PUMaterialCache::Instance() return &pmm; } -PUMaterial* PUMaterialCache::getMaterial(std::string_view name) +PUMaterial* PUMaterialCache::getMaterial(const std::string& name) { for (auto iter : _materialMap) { @@ -87,7 +87,7 @@ PUMaterial* PUMaterialCache::getMaterial(std::string_view name) return nullptr; } -bool PUMaterialCache::loadMaterials(std::string_view file) +bool PUMaterialCache::loadMaterials(const std::string& file) { bool isFirstCompile = true; auto list = PUScriptCompiler::Instance()->compile(file, isFirstCompile); @@ -128,59 +128,53 @@ int iterPath(const char* fpath, const struct stat* /*sb*/, int typeflag) } #endif -bool PUMaterialCache::loadMaterialsFromSearchPaths(std::string_view fileFolder) +bool PUMaterialCache::loadMaterialsFromSearchPaths(const std::string& fileFolder) { bool state = false; #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) std::string seg("/"); - std::string fullPath{fileFolder}; - fullPath += seg; - fullPath += std::string("*.material"); + std::string fullPath = fileFolder + seg + std::string("*.material"); _finddata_t data; intptr_t handle = _findfirst(fullPath.c_str(), &data); int done = 0; while ((handle != -1) && (done == 0)) { - fullPath = fileFolder; - fullPath += seg; - fullPath += data.name; - loadMaterials(fullPath); + loadMaterials(fileFolder + seg + std::string(data.name)); done = _findnext(handle, &data); state = true; } _findclose(handle); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID /* || CC_TARGET_PLATFORM == CC_PLATFORM_LINUX*/) - std::string::size_type pos = fileFolder.find("assets/"); - std::string_view relativePath = fileFolder; + std::string::size_type pos = fileFolder.find("assets/"); + std::string relativePath = fileFolder; if (pos != std::string::npos) { // "assets/" is at the beginning of the path and we don't want it relativePath = fileFolder.substr(pos + strlen("assets/")); } - AAssetDir* dir = AAssetManager_openDir(FileUtilsAndroid::getAssetManager(), relativePath.data()); + AAssetDir* dir = AAssetManager_openDir(FileUtilsAndroid::getAssetManager(), relativePath.c_str()); const char* fileName = nullptr; - std::string_view seg("/", 1); - std::string fullpath; + std::string seg("/"); while ((fileName = AAssetDir_getNextFileName(dir)) != nullptr) { if (FileUtils::getInstance()->getFileExtension(fileName) == ".material") { - fullpath.assign(fileFolder).append(seg).append(fileName); + std::string fullpath = fileFolder + seg + std::string(fileName); loadMaterials(fullpath); } } AAssetDir_close(dir); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) - ftw(fileFolder.data(), iterPath, 500); + ftw(fileFolder.c_str(), iterPath, 500); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX || CC_TARGET_PLATFORM == CC_PLATFORM_TIZEN) DIR* d; // dir handle struct dirent* file; // readdir struct stat statbuf; - if (!(d = opendir(fileFolder.data()))) + if (!(d = opendir(fileFolder.c_str()))) { - CCLOG("error opendir %s!!!\n", fileFolder.data()); + CCLOG("error opendir %s!!!\n", fileFolder.c_str()); return false; } while ((file = readdir(d)) != NULL) @@ -192,8 +186,7 @@ bool PUMaterialCache::loadMaterialsFromSearchPaths(std::string_view fileFolder) if (FileUtils::getInstance()->getFileExtension(file->d_name) == ".material") { - std::string fullpath{fileFolder}; - fullpath.append("/"sv).append(file->d_name); + std::string fullpath = fileFolder + "/" + file->d_name; CCLOG("%s", fullpath.c_str()); loadMaterials(fullpath); state = true; diff --git a/extensions/Particle3D/PU/CCPUMaterialManager.h b/extensions/Particle3D/PU/CCPUMaterialManager.h index a5cbac8934..54543ce349 100644 --- a/extensions/Particle3D/PU/CCPUMaterialManager.h +++ b/extensions/Particle3D/PU/CCPUMaterialManager.h @@ -63,9 +63,9 @@ public: static PUMaterialCache* Instance(); - bool loadMaterials(std::string_view file); - bool loadMaterialsFromSearchPaths(std::string_view fileFolder); - PUMaterial* getMaterial(std::string_view name); + bool loadMaterials(const std::string& file); + bool loadMaterialsFromSearchPaths(const std::string& fileFolder); + PUMaterial* getMaterial(const std::string& name); void addMaterial(PUMaterial* material); protected: diff --git a/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.cpp b/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.cpp index 2c787ebd3e..b453dc4126 100644 --- a/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.cpp +++ b/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.cpp @@ -162,7 +162,7 @@ const PUTriangle::PositionAndNormal PUTriangle::getRandomVertexAndNormal() //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- -MeshInfo::MeshInfo(std::string_view /*meshName*/, +MeshInfo::MeshInfo(const std::string& /*meshName*/, MeshSurfaceDistribution distribution, const Quaternion& /*orientation*/, const Vec3& /*scale*/) @@ -307,7 +307,7 @@ const PUTriangle::PositionAndNormal MeshInfo::getRandomPositionAndNormal(const s // { // Ogre::SubMesh* submesh = mesh->getSubMesh(i); // Ogre::VertexData* vertex_data = submesh->useSharedVertices ? mesh->sharedVertexData : -// submesh->vertexData; +//submesh->vertexData; // // if((!submesh->useSharedVertices)||(submesh->useSharedVertices && !added_shared)) // { @@ -318,11 +318,10 @@ const PUTriangle::PositionAndNormal MeshInfo::getRandomPositionAndNormal(const s // } // // const Ogre::VertexElement* posElem = -// vertex_data->vertexDeclaration->findElementBySemantic(Ogre::VES_POSITION); const -// Ogre::VertexElement* normalElem = vertex_data->vertexDeclaration->findElementBySemantic(Ogre::VES_NORMAL); -// Ogre::HardwareVertexBufferSharedPtr vbuf = vertex_data->vertexBufferBinding->getBuffer(posElem->getSource()); -// unsigned char* vertex = static_cast(vbuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY)); -// float* pReal; +//vertex_data->vertexDeclaration->findElementBySemantic(Ogre::VES_POSITION); const Ogre::VertexElement* normalElem = +//vertex_data->vertexDeclaration->findElementBySemantic(Ogre::VES_NORMAL); Ogre::HardwareVertexBufferSharedPtr vbuf = +//vertex_data->vertexBufferBinding->getBuffer(posElem->getSource()); unsigned char* vertex = static_cast(vbuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY)); float* pReal; // // for( size_t j = 0; j < vertex_data->vertexCount; ++j, vertex += vbuf->getVertexSize()) // { @@ -360,7 +359,7 @@ const PUTriangle::PositionAndNormal MeshInfo::getRandomPositionAndNormal(const s // for ( size_t k = 0; k < numTrisMultThree; ++k) // { // indices[index_offset++] = static_cast(pShort[k]) + static_cast(offset); +//long>(offset); // } // } // @@ -528,12 +527,12 @@ void PUMeshSurfaceEmitter::initParticleDirection(PUParticle3D* particle) } } //----------------------------------------------------------------------- -std::string_view PUMeshSurfaceEmitter::getMeshName() const +const std::string& PUMeshSurfaceEmitter::getMeshName() const { return _meshName; } //----------------------------------------------------------------------- -void PUMeshSurfaceEmitter::setMeshName(std::string_view meshName, bool doBuild) +void PUMeshSurfaceEmitter::setMeshName(const std::string& meshName, bool doBuild) { _meshName = meshName; diff --git a/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.h b/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.h index 553d101176..9f1cd8389f 100644 --- a/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.h +++ b/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.h @@ -119,7 +119,7 @@ public: }; /** Constructor **/ - MeshInfo(std::string_view meshName, + MeshInfo(const std::string& meshName, const MeshSurfaceDistribution distribution = MSD_HOMOGENEOUS, const Quaternion& orientation = Quaternion(), const Vec3& scale = Vec3::ZERO); @@ -173,11 +173,11 @@ public: /** Returns the mesh name. */ - std::string_view getMeshName() const; + const std::string& getMeshName() const; /** Sets the mesh name. */ - void setMeshName(std::string_view meshName, bool doBuild = true); + void setMeshName(const std::string& meshName, bool doBuild = true); /** Returns true if normals are used for the particle direction. */ diff --git a/extensions/Particle3D/PU/CCPUObserver.cpp b/extensions/Particle3D/PU/CCPUObserver.cpp index edfc370560..6b93991b2a 100644 --- a/extensions/Particle3D/PU/CCPUObserver.cpp +++ b/extensions/Particle3D/PU/CCPUObserver.cpp @@ -130,7 +130,7 @@ void PUObserver::notifyRescaled(const Vec3& scale) } } //----------------------------------------------------------------------- -PUEventHandler* PUObserver::createEventHandler(std::string_view eventHandlerType) +PUEventHandler* PUObserver::createEventHandler(const std::string& eventHandlerType) { PUEventHandler* eventHandler = PUEventHandlerManager::Instance()->createEventHandler(eventHandlerType); addEventHandler(eventHandler); @@ -168,7 +168,7 @@ PUEventHandler* PUObserver::getEventHandler(size_t index) const return _eventHandlers[index]; } //----------------------------------------------------------------------- -PUEventHandler* PUObserver::getEventHandler(std::string_view eventHandlerName) const +PUEventHandler* PUObserver::getEventHandler(const std::string& eventHandlerName) const { if (eventHandlerName.empty()) return nullptr; diff --git a/extensions/Particle3D/PU/CCPUObserver.h b/extensions/Particle3D/PU/CCPUObserver.h index dcb354bc02..c2455aa036 100644 --- a/extensions/Particle3D/PU/CCPUObserver.h +++ b/extensions/Particle3D/PU/CCPUObserver.h @@ -63,8 +63,8 @@ public: /** Todo */ - std::string_view getObserverType() const { return _observerType; }; - void setObserverType(std::string_view observerType) { _observerType = observerType; }; + const std::string& getObserverType() const { return _observerType; }; + void setObserverType(const std::string& observerType) { _observerType = observerType; }; /** Todo */ @@ -93,8 +93,8 @@ public: /** Todo */ - std::string_view getName() const { return _name; }; - void setName(std::string_view name) { _name = name; }; + const std::string& getName() const { return _name; }; + void setName(const std::string& name) { _name = name; }; /** Todo */ @@ -115,7 +115,7 @@ public: /** Todo */ - PUEventHandler* createEventHandler(std::string_view eventHandlerType); + PUEventHandler* createEventHandler(const std::string& eventHandlerType); /** Todo */ @@ -131,7 +131,7 @@ public: /** Todo */ - PUEventHandler* getEventHandler(std::string_view eventHandlerName) const; + PUEventHandler* getEventHandler(const std::string& eventHandlerName) const; /** Todo */ diff --git a/extensions/Particle3D/PU/CCPUObserverManager.cpp b/extensions/Particle3D/PU/CCPUObserverManager.cpp index a90e2fdb09..3ac7859ed6 100644 --- a/extensions/Particle3D/PU/CCPUObserverManager.cpp +++ b/extensions/Particle3D/PU/CCPUObserverManager.cpp @@ -48,7 +48,7 @@ PUObserverManager* PUObserverManager::Instance() return &pem; } -PUScriptTranslator* PUObserverManager::getTranslator(std::string_view type) +PUScriptTranslator* PUObserverManager::getTranslator(const std::string& type) { if (type == "OnClear") { @@ -97,7 +97,7 @@ PUScriptTranslator* PUObserverManager::getTranslator(std::string_view type) return nullptr; } -PUObserver* PUObserverManager::createObserver(std::string_view type) +PUObserver* PUObserverManager::createObserver(const std::string& type) { if (type == "OnClear") { diff --git a/extensions/Particle3D/PU/CCPUObserverManager.h b/extensions/Particle3D/PU/CCPUObserverManager.h index 8134843e1b..cd1a69dac8 100644 --- a/extensions/Particle3D/PU/CCPUObserverManager.h +++ b/extensions/Particle3D/PU/CCPUObserverManager.h @@ -50,8 +50,8 @@ public: /** */ - PUScriptTranslator* getTranslator(std::string_view type); - PUObserver* createObserver(std::string_view type); + PUScriptTranslator* getTranslator(const std::string& type); + PUObserver* createObserver(const std::string& type); CC_CONSTRUCTOR_ACCESS : diff --git a/extensions/Particle3D/PU/CCPUParticleSystem3D.cpp b/extensions/Particle3D/PU/CCPUParticleSystem3D.cpp index 4f5ea0c393..e9818e3a25 100644 --- a/extensions/Particle3D/PU/CCPUParticleSystem3D.cpp +++ b/extensions/Particle3D/PU/CCPUParticleSystem3D.cpp @@ -259,7 +259,7 @@ PUParticleSystem3D* PUParticleSystem3D::create() return pups; } -PUParticleSystem3D* PUParticleSystem3D::create(std::string_view filePath, std::string_view materialPath) +PUParticleSystem3D* PUParticleSystem3D::create(const std::string& filePath, const std::string& materialPath) { PUParticleSystem3D* ret = new PUParticleSystem3D(); if (ret->initWithFilePathAndMaterialPath(filePath, materialPath)) @@ -274,7 +274,7 @@ PUParticleSystem3D* PUParticleSystem3D::create(std::string_view filePath, std::s } } -PUParticleSystem3D* PUParticleSystem3D::create(std::string_view filePath) +PUParticleSystem3D* PUParticleSystem3D::create(const std::string& filePath) { PUParticleSystem3D* ret = new PUParticleSystem3D(); if (ret->initWithFilePath(filePath)) @@ -289,7 +289,7 @@ PUParticleSystem3D* PUParticleSystem3D::create(std::string_view filePath) } } -bool PUParticleSystem3D::initWithFilePath(std::string_view filePath) +bool PUParticleSystem3D::initWithFilePath(const std::string& filePath) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); convertToUnixStylePath(fullPath); @@ -318,7 +318,7 @@ bool PUParticleSystem3D::initWithFilePath(std::string_view filePath) return true; } -bool PUParticleSystem3D::initWithFilePathAndMaterialPath(std::string_view filePath, std::string_view materialPath) +bool PUParticleSystem3D::initWithFilePathAndMaterialPath(const std::string& filePath, const std::string& materialPath) { std::string matfullPath = FileUtils::getInstance()->fullPathForFilename(materialPath); convertToUnixStylePath(matfullPath); @@ -629,24 +629,24 @@ void PUParticleSystem3D::unPrepared() _particlePool.lockAllDatas(); for (auto& iter : _emittedEmitterParticlePool) { - PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); + PUParticle3D* particle = static_cast(iter.second.getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->unPrepare(); - particle = static_cast(const_cast(iter.second).getNext()); + particle = static_cast(iter.second.getNext()); } - const_cast(iter.second).lockAllDatas(); + iter.second.lockAllDatas(); } for (auto& iter : _emittedSystemParticlePool) { - PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); + PUParticle3D* particle = static_cast(iter.second.getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->unPrepared(); - particle = static_cast(const_cast(iter.second).getNext()); + particle = static_cast(iter.second.getNext()); } - const_cast(iter.second).lockAllDatas(); + iter.second.lockAllDatas(); } _prepared = false; } @@ -692,21 +692,21 @@ void PUParticleSystem3D::preUpdator(float elapsedTime) for (auto& iter : _emittedEmitterParticlePool) { - PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); + PUParticle3D* particle = static_cast(iter.second.getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->preUpdateEmitter(elapsedTime); - particle = static_cast(const_cast(iter.second).getNext()); + particle = static_cast(iter.second.getNext()); } } for (auto& iter : _emittedSystemParticlePool) { - PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); + PUParticle3D* particle = static_cast(iter.second.getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->preUpdator(elapsedTime); - particle = static_cast(const_cast(iter.second).getNext()); + particle = static_cast(iter.second.getNext()); } } } @@ -719,12 +719,12 @@ void PUParticleSystem3D::updator(float elapsedTime) for (auto& iter : _emittedEmitterParticlePool) { - processParticle(const_cast(iter.second), firstActiveParticle, firstParticle, elapsedTime); + processParticle(iter.second, firstActiveParticle, firstParticle, elapsedTime); } for (auto& iter : _emittedSystemParticlePool) { - processParticle(const_cast(iter.second), firstActiveParticle, firstParticle, elapsedTime); + processParticle(iter.second, firstActiveParticle, firstParticle, elapsedTime); } } @@ -763,21 +763,21 @@ void PUParticleSystem3D::postUpdator(float elapsedTime) for (auto& iter : _emittedEmitterParticlePool) { - PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); + PUParticle3D* particle = static_cast(iter.second.getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->postUpdateEmitter(elapsedTime); - particle = static_cast(const_cast(iter.second).getNext()); + particle = static_cast(iter.second.getNext()); } } for (auto& iter : _emittedSystemParticlePool) { - PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); + PUParticle3D* particle = static_cast(iter.second.getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->postUpdator(elapsedTime); - particle = static_cast(const_cast(iter.second).getNext()); + particle = static_cast(iter.second.getNext()); } } } @@ -901,7 +901,7 @@ void PUParticleSystem3D::setMaxVelocity(float maxVelocity) _maxVelocitySet = true; } -bool PUParticleSystem3D::initSystem(std::string_view filePath) +bool PUParticleSystem3D::initSystem(const std::string& filePath) { bool isFirstCompile = true; auto list = PUScriptCompiler::Instance()->compile(filePath, isFirstCompile); @@ -922,7 +922,7 @@ void PUParticleSystem3D::addEmitter(PUEmitter* emitter) } } -PUAffector* PUParticleSystem3D::getAffector(std::string_view name) +PUAffector* PUParticleSystem3D::getAffector(const std::string& name) { for (auto iter : _affectors) { @@ -934,7 +934,7 @@ PUAffector* PUParticleSystem3D::getAffector(std::string_view name) return nullptr; } -PUEmitter* PUParticleSystem3D::getEmitter(std::string_view name) +PUEmitter* PUParticleSystem3D::getEmitter(const std::string& name) { for (auto iter : _emitters) { @@ -1040,7 +1040,7 @@ void PUParticleSystem3D::addObserver(PUObserver* observer) } } -PUObserver* PUParticleSystem3D::getObserver(std::string_view name) +PUObserver* PUParticleSystem3D::getObserver(const std::string& name) { for (auto iter : _observers) { @@ -1074,21 +1074,21 @@ void PUParticleSystem3D::notifyRescaled(const Vec3& scl) for (auto& iter : _emittedEmitterParticlePool) { - PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); + PUParticle3D* particle = static_cast(iter.second.getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->notifyRescaled(scl); - particle = static_cast(const_cast(iter.second).getNext()); + particle = static_cast(iter.second.getNext()); } } for (auto& iter : _emittedSystemParticlePool) { - PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); + PUParticle3D* particle = static_cast(iter.second.getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->notifyRescaled(scl); - particle = static_cast(const_cast(iter.second).getNext()); + particle = static_cast(iter.second.getNext()); } } } @@ -1113,7 +1113,7 @@ void PUParticleSystem3D::initParticleForExpiration(PUParticle3D* particle, float it->particleExpired(this, particle); } ///** Externs are also called to perform expiration activities. If needed, affectors and emitters may be added, but - /// at the moment + ///at the moment // there is no reason for (and we don't want to waste cpu resources). //*/ // if (!mExterns.empty()) @@ -1164,12 +1164,12 @@ void PUParticleSystem3D::clearAllParticles() _particlePool.lockAllDatas(); for (auto& iter : _emittedEmitterParticlePool) { - const_cast(iter.second).lockAllDatas(); + iter.second.lockAllDatas(); } for (auto& iter : _emittedSystemParticlePool) { - const_cast(iter.second).lockAllDatas(); + iter.second.lockAllDatas(); } } @@ -1303,11 +1303,11 @@ void PUParticleSystem3D::draw(Renderer* renderer, const Mat4& transform, uint32_ { for (auto& iter : _emittedSystemParticlePool) { - PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); + PUParticle3D* particle = static_cast(iter.second.getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->draw(renderer, transform, flags); - particle = static_cast(const_cast(iter.second).getNext()); + particle = static_cast(iter.second.getNext()); } } } diff --git a/extensions/Particle3D/PU/CCPUParticleSystem3D.h b/extensions/Particle3D/PU/CCPUParticleSystem3D.h index d7773d9892..4b73e26c1d 100644 --- a/extensions/Particle3D/PU/CCPUParticleSystem3D.h +++ b/extensions/Particle3D/PU/CCPUParticleSystem3D.h @@ -207,7 +207,7 @@ struct CC_EX_DLL PUParticle3D : public Particle3D class CC_EX_DLL PUParticleSystem3D : public ParticleSystem3D { public: - typedef hlookup::string_map ParticlePoolMap; + typedef std::unordered_map ParticlePoolMap; static const float DEFAULT_WIDTH; static const float DEFAULT_HEIGHT; @@ -218,8 +218,8 @@ public: static const float DEFAULT_MAX_VELOCITY; static PUParticleSystem3D* create(); - static PUParticleSystem3D* create(std::string_view filePath); - static PUParticleSystem3D* create(std::string_view filePath, std::string_view materialPath); + static PUParticleSystem3D* create(const std::string& filePath); + static PUParticleSystem3D* create(const std::string& filePath, const std::string& materialPath); virtual void draw(Renderer* renderer, const Mat4& transform, uint32_t flags) override; @@ -296,8 +296,8 @@ public: */ void setMaxVelocity(float maxVelocity); - void setMaterialName(std::string_view name) { _matName = name; }; - std::string_view getMaterialName() const { return _matName; }; + void setMaterialName(const std::string& name) { _matName = name; }; + const std::string& getMaterialName() const { return _matName; }; /** Forces emission of particles. * @remarks The number of requested particles are the exact number that are emitted. No down-scaling is applied. @@ -309,8 +309,8 @@ public: */ void addEmitter(PUEmitter* emitter); - PUAffector* getAffector(std::string_view name); - PUEmitter* getEmitter(std::string_view name); + PUAffector* getAffector(const std::string& name); + PUEmitter* getEmitter(const std::string& name); void removeAllEmitter(); void addListener(PUListener* listener); @@ -318,7 +318,7 @@ public: void removeAllListener(); void addObserver(PUObserver* observer); - PUObserver* getObserver(std::string_view name); + PUObserver* getObserver(const std::string& name); void removerAllObserver(); void addBehaviourTemplate(PUBehaviour* behaviour); @@ -346,13 +346,13 @@ public: virtual PUParticleSystem3D* clone(); virtual void copyAttributesTo(PUParticleSystem3D* system); - bool initSystem(std::string_view filePath); + bool initSystem(const std::string& filePath); CC_CONSTRUCTOR_ACCESS : PUParticleSystem3D(); virtual ~PUParticleSystem3D(); - bool initWithFilePath(std::string_view filePath); - bool initWithFilePathAndMaterialPath(std::string_view filePath, std::string_view materialPath); + bool initWithFilePath(const std::string& filePath); + bool initWithFilePathAndMaterialPath(const std::string& filePath, const std::string& materialPath); protected: void prepared(); diff --git a/extensions/Particle3D/PU/CCPUParticleSystem3DTranslator.cpp b/extensions/Particle3D/PU/CCPUParticleSystem3DTranslator.cpp index 819aa25f7d..29b6e08697 100644 --- a/extensions/Particle3D/PU/CCPUParticleSystem3DTranslator.cpp +++ b/extensions/Particle3D/PU/CCPUParticleSystem3DTranslator.cpp @@ -107,7 +107,7 @@ void PUParticleSystem3DTranslator::translate(PUScriptCompiler* compiler, PUAbstr // else // { // compiler->addError(PUScriptCompiler::CE_NUMBEREXPECTED, prop->file, - // prop->line, + //prop->line, // "PU Compiler: lod_distances expects only numbers as // arguments"); // } @@ -238,8 +238,7 @@ void PUParticleSystem3DTranslator::translate(PUScriptCompiler* compiler, PUAbstr // { // ParticleTechnique* technique = static_cast(alias); // ParticleTechnique* newTechnique = - // ParticleSystemManager::getSingletonPtr()->cloneTechnique(technique); - // mSystem->addTechnique(newTechnique); + //ParticleSystemManager::getSingletonPtr()->cloneTechnique(technique); mSystem->addTechnique(newTechnique); // } // } // } diff --git a/extensions/Particle3D/PU/CCPURender.cpp b/extensions/Particle3D/PU/CCPURender.cpp index 62c2505007..d22e2c977f 100644 --- a/extensions/Particle3D/PU/CCPURender.cpp +++ b/extensions/Particle3D/PU/CCPURender.cpp @@ -56,7 +56,7 @@ void PURender::copyAttributesTo(PURender* render) // return left->depthInView > right->depthInView; // } -PUParticle3DQuadRender* PUParticle3DQuadRender::create(std::string_view texFile) +PUParticle3DQuadRender* PUParticle3DQuadRender::create(const std::string& texFile) { auto ret = new PUParticle3DQuadRender(); if (ret->initRender(texFile)) @@ -227,25 +227,25 @@ void PUParticle3DQuadRender::render(Renderer* renderer, const Mat4& transform, P //_posuvcolors[vertexindex].position = (position + (- halfwidth - halfheight + halfwidth * offsetX + halfheight //* offsetY)); _posuvcolors[vertexindex].color = particle->color; _posuvcolors[vertexindex].uv.set(val.x + - // texOffset.x, val.y + texOffset.y); + //texOffset.x, val.y + texOffset.y); // val.set(particle->rt_uv.x - texOffset.x, particle->lb_uv.y - texOffset.y); // val.set(val.x * costheta - val.y * sintheta, val.x * sintheta + val.y * costheta); //_posuvcolors[vertexindex + 1].position = (position + (halfwidth - halfheight + halfwidth * offsetX + - // halfheight * offsetY)); _posuvcolors[vertexindex + 1].color = particle->color; _posuvcolors[vertexindex + - // 1].uv.set(val.x + texOffset.x, val.y + texOffset.y); + //halfheight * offsetY)); _posuvcolors[vertexindex + 1].color = particle->color; _posuvcolors[vertexindex + + //1].uv.set(val.x + texOffset.x, val.y + texOffset.y); // // val.set(particle->lb_uv.x - texOffset.x, particle->rt_uv.y - texOffset.y); // val.set(val.x * costheta - val.y * sintheta, val.x * sintheta + val.y * costheta); //_posuvcolors[vertexindex + 2].position = (position + (- halfwidth + halfheight + halfwidth * offsetX + - // halfheight * offsetY)); _posuvcolors[vertexindex + 2].color = particle->color; _posuvcolors[vertexindex + - // 2].uv.set(val.x + texOffset.x, val.y + texOffset.y); + //halfheight * offsetY)); _posuvcolors[vertexindex + 2].color = particle->color; _posuvcolors[vertexindex + + //2].uv.set(val.x + texOffset.x, val.y + texOffset.y); // // val.set(particle->rt_uv.x - texOffset.x, particle->rt_uv.y - texOffset.y); // val.set(val.x * costheta - val.y * sintheta, val.x * sintheta + val.y * costheta); //_posuvcolors[vertexindex + 3].position = (position + (halfwidth + halfheight + halfwidth * offsetX + - // halfheight * offsetY)); _posuvcolors[vertexindex + 3].color = particle->color; _posuvcolors[vertexindex + - // 3].uv.set(val.x + texOffset.x, val.y + texOffset.y); + //halfheight * offsetY)); _posuvcolors[vertexindex + 3].color = particle->color; _posuvcolors[vertexindex + + //3].uv.set(val.x + texOffset.x, val.y + texOffset.y); // // //_indexData[index] = vertexindex; @@ -488,7 +488,8 @@ PUParticle3DQuadRender* PUParticle3DQuadRender::clone() return render; } -PUParticle3DModelRender* PUParticle3DModelRender::create(std::string_view modelFile, std::string_view texFile /*= ""*/) +PUParticle3DModelRender* PUParticle3DModelRender::create(const std::string& modelFile, + const std::string& texFile /*= ""*/) { auto ret = new PUParticle3DModelRender(); ret->_modelFile = modelFile; @@ -613,7 +614,7 @@ PUParticle3DEntityRender::~PUParticle3DEntityRender() CC_SAFE_RELEASE(_indexBuffer); } -bool PUParticle3DEntityRender::initRender(std::string_view texFile) +bool PUParticle3DEntityRender::initRender(const std::string& texFile) { CC_SAFE_RELEASE_NULL(_programState); if (!texFile.empty()) @@ -692,7 +693,7 @@ PUParticle3DBoxRender::PUParticle3DBoxRender() PUParticle3DBoxRender::~PUParticle3DBoxRender() {} -PUParticle3DBoxRender* PUParticle3DBoxRender::create(std::string_view texFile) +PUParticle3DBoxRender* PUParticle3DBoxRender::create(const std::string& texFile) { auto ret = new PUParticle3DBoxRender(); if (ret->initRender(texFile)) @@ -882,7 +883,7 @@ PUParticle3DBoxRender* PUParticle3DBoxRender::clone() return render; } -PUSphereRender* PUSphereRender::create(std::string_view texFile) +PUSphereRender* PUSphereRender::create(const std::string& texFile) { auto ret = new PUSphereRender(); if (ret->initRender(texFile)) diff --git a/extensions/Particle3D/PU/CCPURender.h b/extensions/Particle3D/PU/CCPURender.h index 002f333daf..e4076c6565 100644 --- a/extensions/Particle3D/PU/CCPURender.h +++ b/extensions/Particle3D/PU/CCPURender.h @@ -47,8 +47,8 @@ public: virtual void unPrepare(){}; virtual void updateRender(PUParticle3D* particle, float deltaTime, bool firstParticle); - std::string_view getRenderType() const { return _renderType; }; - void setRenderType(std::string_view observerType) { _renderType = observerType; }; + const std::string& getRenderType() const { return _renderType; }; + void setRenderType(const std::string& observerType) { _renderType = observerType; }; virtual PURender* clone() = 0; void copyAttributesTo(PURender* render); @@ -70,7 +70,7 @@ public: virtual ~PUParticle3DEntityRender(); protected: - bool initRender(std::string_view texFile); + bool initRender(const std::string& texFile); void onBeforeDraw(); @@ -141,7 +141,7 @@ public: VERTEX }; - static PUParticle3DQuadRender* create(std::string_view texFile = ""); + static PUParticle3DQuadRender* create(const std::string& texFile = ""); void setType(Type type); Type getType() const { return _type; } @@ -191,7 +191,7 @@ protected: class CC_EX_DLL PUParticle3DModelRender : public PURender { public: - static PUParticle3DModelRender* create(std::string_view modelFile, std::string_view texFile = ""); + static PUParticle3DModelRender* create(const std::string& modelFile, const std::string& texFile = ""); virtual void render(Renderer* renderer, const Mat4& transform, ParticleSystem3D* particleSystem) override; @@ -212,7 +212,7 @@ protected: class CC_EX_DLL PUParticle3DBoxRender : public PUParticle3DEntityRender { public: - static PUParticle3DBoxRender* create(std::string_view texFile = ""); + static PUParticle3DBoxRender* create(const std::string& texFile = ""); virtual void render(Renderer* renderer, const Mat4& transform, ParticleSystem3D* particleSystem) override; @@ -228,7 +228,7 @@ protected: class CC_EX_DLL PUSphereRender : public PUParticle3DEntityRender { public: - static PUSphereRender* create(std::string_view texFile = ""); + static PUSphereRender* create(const std::string& texFile = ""); virtual void render(Renderer* renderer, const Mat4& transform, ParticleSystem3D* particleSystem) override; diff --git a/extensions/Particle3D/PU/CCPURibbonTrail.cpp b/extensions/Particle3D/PU/CCPURibbonTrail.cpp index fe05c38977..b5bc2fc10b 100644 --- a/extensions/Particle3D/PU/CCPURibbonTrail.cpp +++ b/extensions/Particle3D/PU/CCPURibbonTrail.cpp @@ -36,8 +36,8 @@ NS_CC_BEGIN -PURibbonTrail::PURibbonTrail(std::string_view name, - std::string_view texFile, +PURibbonTrail::PURibbonTrail(const std::string& name, + const std::string& texFile, size_t maxElements, size_t numberOfChains, bool useTextureCoords, diff --git a/extensions/Particle3D/PU/CCPURibbonTrail.h b/extensions/Particle3D/PU/CCPURibbonTrail.h index e2fa1183e9..e57ccf58e6 100644 --- a/extensions/Particle3D/PU/CCPURibbonTrail.h +++ b/extensions/Particle3D/PU/CCPURibbonTrail.h @@ -48,12 +48,12 @@ public: @param useVertexColors If true, use vertex colors from the chain elements (must be true if you intend to use fading) */ - PURibbonTrail(std::string_view name, - std::string_view texFile = "", - size_t maxElements = 20, - size_t numberOfChains = 1, - bool useTextureCoords = true, - bool useColours = true); + PURibbonTrail(const std::string& name, + const std::string& texFile = "", + size_t maxElements = 20, + size_t numberOfChains = 1, + bool useTextureCoords = true, + bool useColours = true); /// destructor virtual ~PURibbonTrail(); diff --git a/extensions/Particle3D/PU/CCPURibbonTrailRender.cpp b/extensions/Particle3D/PU/CCPURibbonTrailRender.cpp index 2079571115..8a924a9c4b 100644 --- a/extensions/Particle3D/PU/CCPURibbonTrailRender.cpp +++ b/extensions/Particle3D/PU/CCPURibbonTrailRender.cpp @@ -48,7 +48,7 @@ const bool PURibbonTrailRender::DEFAULT_RANDOM_INITIAL_COLOUR = true; const Vec4 PURibbonTrailRender::DEFAULT_INITIAL_COLOUR(1, 1, 1, 1); const Vec4 PURibbonTrailRender::DEFAULT_COLOUR_CHANGE(0.5, 0.5, 0.5, 0.5); -PURibbonTrailRender* PURibbonTrailRender::create(std::string_view texFile) +PURibbonTrailRender* PURibbonTrailRender::create(const std::string& texFile) { auto br = new PURibbonTrailRender(); br->autorelease(); @@ -233,7 +233,7 @@ void PURibbonTrailRender::prepare() ss << this; std::string childNodeNodeName = "ParticleUniverse" + ss.str(); //_childNode = - // mParentTechnique->getParentSystem()->getParentSceneNode()->createChildSceneNode(childNodeNodeName); + //mParentTechnique->getParentSystem()->getParentSceneNode()->createChildSceneNode(childNodeNodeName); //_childNode->setInheritOrientation(false); auto parent = _particleSystem->getParent(); if (parent) @@ -270,7 +270,7 @@ void PURibbonTrailRender::prepare() // sceneNodeName = "ParticleUniverse" + ss.str() + StringConverter::toString(i); // RibbonTrailRendererVisualData* visualData = // PU_NEW_T(RibbonTrailRendererVisualData, - // MEMCATEGORY_SCENE_OBJECTS)(_childNode->createChildSceneNode(sceneNodeName), _trail); + //MEMCATEGORY_SCENE_OBJECTS)(_childNode->createChildSceneNode(sceneNodeName), _trail); // visualData->node->setInheritOrientation(false); auto node = Node::create(); _childNode->addChild(node); diff --git a/extensions/Particle3D/PU/CCPURibbonTrailRender.h b/extensions/Particle3D/PU/CCPURibbonTrailRender.h index ec3bb38705..54ac52539b 100644 --- a/extensions/Particle3D/PU/CCPURibbonTrailRender.h +++ b/extensions/Particle3D/PU/CCPURibbonTrailRender.h @@ -83,7 +83,7 @@ public: static const Vec4 DEFAULT_INITIAL_COLOUR; static const Vec4 DEFAULT_COLOUR_CHANGE; - static PURibbonTrailRender* create(std::string_view texFile = ""); + static PURibbonTrailRender* create(const std::string& texFile = ""); virtual void notifyRescaled(const Vec3& scale) override; virtual void prepare() override; diff --git a/extensions/Particle3D/PU/CCPUScriptCompiler.cpp b/extensions/Particle3D/PU/CCPUScriptCompiler.cpp index 026311ffc5..c4b55f4abb 100644 --- a/extensions/Particle3D/PU/CCPUScriptCompiler.cpp +++ b/extensions/Particle3D/PU/CCPUScriptCompiler.cpp @@ -67,20 +67,19 @@ std::string PUObjectAbstractNode::getValue() const return cls; } -void PUObjectAbstractNode::addVariable(std::string_view inName) +void PUObjectAbstractNode::addVariable(const std::string& inName) { _env.emplace(inName, ""); } -void PUObjectAbstractNode::setVariable(std::string_view inName, std::string_view value) +void PUObjectAbstractNode::setVariable(const std::string& inName, const std::string& value) { - // _env[inName] = value; - hlookup::set_item(_env, inName, value); + _env[inName] = value; } -std::pair PUObjectAbstractNode::getVariable(std::string_view inName) const +std::pair PUObjectAbstractNode::getVariable(const std::string& inName) const { - auto i = _env.find(inName); + std::unordered_map::const_iterator i = _env.find(inName); if (i != _env.end()) return std::make_pair(true, i->second); @@ -95,7 +94,7 @@ std::pair PUObjectAbstractNode::getVariable(std::string_view return std::make_pair(false, ""); } -const hlookup::string_map& PUObjectAbstractNode::getVariables() const +const std::unordered_map& PUObjectAbstractNode::getVariables() const { return _env; } @@ -188,16 +187,15 @@ PUScriptCompiler::~PUScriptCompiler() _compiledScripts.clear(); } -hlookup::string_map::iterator PUScriptCompiler::compile(const PUConcreteNodeList& nodes, - std::string_view file) +bool PUScriptCompiler::compile(const PUConcreteNodeList& nodes, const std::string& file) { if (nodes.empty()) - return _compiledScripts.end(); + return false; PUAbstractNodeList aNodes; convertToAST(nodes, aNodes); - return hlookup::set_item(_compiledScripts, file, aNodes); // _compiledScripts[file] = aNodes; + _compiledScripts[file] = aNodes; // for(PUAbstractNodeList::iterator i = aNodes.begin(); i != aNodes.end(); ++i) //{ // PUScriptTranslator *translator = PUTranslateManager::Instance()->getTranslator(*i); @@ -214,10 +212,10 @@ hlookup::string_map::iterator PUScriptCompiler::compile(cons // for (auto iter : aNodes){ // delete iter; // } - // return true; + return true; } -const PUAbstractNodeList* PUScriptCompiler::compile(std::string_view file, bool& isFirstCompile) +const PUAbstractNodeList* PUScriptCompiler::compile(const std::string& file, bool& isFirstCompile) { auto iter = _compiledScripts.find(file); if (iter != _compiledScripts.end()) @@ -233,7 +231,7 @@ const PUAbstractNodeList* PUScriptCompiler::compile(std::string_view file, bool& PUConcreteNodeList creteNodeList; lexer.openLexer(data, file, tokenList); parser.parse(creteNodeList, tokenList); - auto it = compile(creteNodeList, file); + bool state = compile(creteNodeList, file); for (auto iter1 : creteNodeList) { @@ -246,9 +244,9 @@ const PUAbstractNodeList* PUScriptCompiler::compile(std::string_view file, bool& } isFirstCompile = true; - if (it != _compiledScripts.end()) + if (state) { - return &it->second; + return &_compiledScripts[file]; } return nullptr; } diff --git a/extensions/Particle3D/PU/CCPUScriptCompiler.h b/extensions/Particle3D/PU/CCPUScriptCompiler.h index e5bc4cc7b8..4834595f59 100644 --- a/extensions/Particle3D/PU/CCPUScriptCompiler.h +++ b/extensions/Particle3D/PU/CCPUScriptCompiler.h @@ -72,7 +72,7 @@ public: class CC_EX_DLL PUObjectAbstractNode : public PUAbstractNode { private: - hlookup::string_map _env; + std::unordered_map _env; public: std::string name, cls; @@ -88,10 +88,10 @@ public: PUAbstractNode* clone() const; std::string getValue() const; - void addVariable(std::string_view name); - void setVariable(std::string_view name, std::string_view value); - std::pair getVariable(std::string_view name) const; - const hlookup::string_map& getVariables() const; + void addVariable(const std::string& name); + void setVariable(const std::string& name, const std::string& value); + std::pair getVariable(const std::string& name) const; + const std::unordered_map& getVariables() const; }; /** This abstract node represents a script property */ @@ -130,9 +130,9 @@ class CC_EX_DLL PUScriptCompiler { private: - hlookup::string_map::iterator compile(const PUConcreteNodeList& nodes, std::string_view file); + bool compile(const PUConcreteNodeList& nodes, const std::string& file); // is it excluded?// - bool isNameExcluded(std::string_view cls, PUAbstractNode* parent); + bool isNameExcluded(const std::string& cls, PUAbstractNode* parent); public: typedef std::unordered_map IdMap; @@ -141,7 +141,7 @@ public: void setParticleSystem3D(PUParticleSystem3D* pu); - const PUAbstractNodeList* compile(std::string_view file, bool& isFirstCompile); + const PUAbstractNodeList* compile(const std::string& file, bool& isFirstCompile); void convertToAST(const PUConcreteNodeList& nodes, PUAbstractNodeList& aNodes); @@ -155,7 +155,7 @@ private: void visit(PUConcreteNode* node); private: - hlookup::string_map _compiledScripts; + std::unordered_map _compiledScripts; PUAbstractNode* _current; PUAbstractNodeList* _nodes; PUParticleSystem3D* _PUParticleSystem3D; diff --git a/extensions/Particle3D/PU/CCPUScriptLexer.cpp b/extensions/Particle3D/PU/CCPUScriptLexer.cpp index 75aca400f7..a8720fca0f 100644 --- a/extensions/Particle3D/PU/CCPUScriptLexer.cpp +++ b/extensions/Particle3D/PU/CCPUScriptLexer.cpp @@ -31,7 +31,7 @@ PUScriptLexer::PUScriptLexer() {} PUScriptLexer::~PUScriptLexer() {} -void PUScriptLexer::openLexer(std::string_view str, std::string_view source, PUScriptTokenList& tokens) +void PUScriptLexer::openLexer(const std::string& str, const std::string& source, PUScriptTokenList& tokens) { enum { @@ -55,7 +55,7 @@ void PUScriptLexer::openLexer(std::string_view str, std::string_view source, PUS // // Iterate over the input - std::string_view::const_iterator i = str.begin(), end = str.end(); + std::string::const_iterator i = str.begin(), end = str.end(); while (i != end) { lastc = c; @@ -233,7 +233,7 @@ void PUScriptLexer::openLexer(std::string_view str, std::string_view source, PUS } } -void PUScriptLexer::setToken(std::string_view lexeme, int line, std::string_view source, PUScriptTokenList* tokens) +void PUScriptLexer::setToken(const std::string& lexeme, int line, const std::string& source, PUScriptTokenList* tokens) { const char openBracket = '{', closeBracket = '}', colon = ':', quote = '\"', var = '$'; diff --git a/extensions/Particle3D/PU/CCPUScriptLexer.h b/extensions/Particle3D/PU/CCPUScriptLexer.h index 907ef09a7b..e5133cf323 100644 --- a/extensions/Particle3D/PU/CCPUScriptLexer.h +++ b/extensions/Particle3D/PU/CCPUScriptLexer.h @@ -67,12 +67,12 @@ public: PUScriptLexer(); ~PUScriptLexer(); - void openLexer(std::string_view str, std::string_view source, PUScriptTokenList& tokenList); + void openLexer(const std::string& str, const std::string& source, PUScriptTokenList& tokenList); /** Tokenizes the given input and returns the list of tokens found */ // tokenize(const std::string &str, const std::string &source); private: // Private utility operations - void setToken(std::string_view lexeme, int line, std::string_view source, PUScriptTokenList* tokens); + void setToken(const std::string& lexeme, int line, const std::string& source, PUScriptTokenList* tokens); bool isWhitespace(char c) const; bool isNewline(char c) const; }; diff --git a/extensions/Particle3D/PU/CCPUScriptTranslator.cpp b/extensions/Particle3D/PU/CCPUScriptTranslator.cpp index 3eeb334127..a73539e24a 100644 --- a/extensions/Particle3D/PU/CCPUScriptTranslator.cpp +++ b/extensions/Particle3D/PU/CCPUScriptTranslator.cpp @@ -517,7 +517,7 @@ bool PUScriptTranslator::getQuaternion(PUAbstractNodeList::const_iterator i, //------------------------------------------------------------------------- bool PUScriptTranslator::passValidateProperty(PUScriptCompiler* compiler, PUPropertyAbstractNode* prop, - std::string_view token2, + const std::string& token2, ValidationType validationType) { if (!passValidatePropertyNoValues(compiler, prop, token2)) @@ -594,7 +594,7 @@ bool PUScriptTranslator::passValidateProperty(PUScriptCompiler* compiler, //------------------------------------------------------------------------- bool PUScriptTranslator::passValidatePropertyNoValues(PUScriptCompiler* /*compiler*/, PUPropertyAbstractNode* prop, - std::string_view /*token2*/) + const std::string& /*token2*/) { if (prop->values.empty()) { @@ -607,7 +607,7 @@ bool PUScriptTranslator::passValidatePropertyNoValues(PUScriptCompiler* /*compil //------------------------------------------------------------------------- bool PUScriptTranslator::passValidatePropertyNumberOfValues(PUScriptCompiler* /*compiler*/, PUPropertyAbstractNode* prop, - std::string_view /*token2*/, + const std::string& /*token2*/, unsigned short numberOfValues) { if (prop->values.size() > numberOfValues) @@ -619,7 +619,7 @@ bool PUScriptTranslator::passValidatePropertyNumberOfValues(PUScriptCompiler* /* //------------------------------------------------------------------------- bool PUScriptTranslator::passValidatePropertyNumberOfValuesRange(PUScriptCompiler* /*compiler*/, PUPropertyAbstractNode* prop, - std::string_view /*token2*/, + const std::string& /*token2*/, unsigned short minNumberOfValues, unsigned short maxNumberOfValues) { diff --git a/extensions/Particle3D/PU/CCPUScriptTranslator.h b/extensions/Particle3D/PU/CCPUScriptTranslator.h index 623bec8d13..0e9af6d757 100644 --- a/extensions/Particle3D/PU/CCPUScriptTranslator.h +++ b/extensions/Particle3D/PU/CCPUScriptTranslator.h @@ -679,25 +679,27 @@ public: */ bool passValidateProperty(PUScriptCompiler* compiler, PUPropertyAbstractNode* prop, - std::string_view token, + const std::string& token, ValidationType validationType); /** Validate whether a property has values. */ - bool passValidatePropertyNoValues(PUScriptCompiler* compiler, PUPropertyAbstractNode* prop, std::string_view token); + bool passValidatePropertyNoValues(PUScriptCompiler* compiler, + PUPropertyAbstractNode* prop, + const std::string& token); /** Validate whether the number of values is correct. */ bool passValidatePropertyNumberOfValues(PUScriptCompiler* compiler, PUPropertyAbstractNode* prop, - std::string_view token, + const std::string& token, unsigned short numberOfValues); /** Validate whether the number of values is between a range. */ bool passValidatePropertyNumberOfValuesRange(PUScriptCompiler* compiler, PUPropertyAbstractNode* prop, - std::string_view token, + const std::string& token, unsigned short minNumberOfValues, unsigned short maxNumberOfValues); diff --git a/extensions/Particle3D/PU/CCPUSlaveEmitter.cpp b/extensions/Particle3D/PU/CCPUSlaveEmitter.cpp index e5880b2f9c..904cab168e 100644 --- a/extensions/Particle3D/PU/CCPUSlaveEmitter.cpp +++ b/extensions/Particle3D/PU/CCPUSlaveEmitter.cpp @@ -39,22 +39,22 @@ PUSlaveEmitter::PUSlaveEmitter() , _masterEmitterNameSet(false) {} //----------------------------------------------------------------------- -std::string_view PUSlaveEmitter::getMasterTechniqueName() const +const std::string& PUSlaveEmitter::getMasterTechniqueName() const { return _masterTechniqueName; } //----------------------------------------------------------------------- -void PUSlaveEmitter::setMasterTechniqueName(std::string_view masterTechniqueName) +void PUSlaveEmitter::setMasterTechniqueName(const std::string& masterTechniqueName) { _masterTechniqueName = masterTechniqueName; } //----------------------------------------------------------------------- -std::string_view PUSlaveEmitter::getMasterEmitterName() const +const std::string& PUSlaveEmitter::getMasterEmitterName() const { return _masterEmitterName; } //----------------------------------------------------------------------- -void PUSlaveEmitter::setMasterEmitterName(std::string_view masterEmitterName) +void PUSlaveEmitter::setMasterEmitterName(const std::string& masterEmitterName) { _masterEmitterName = masterEmitterName; _masterEmitterNameSet = true; diff --git a/extensions/Particle3D/PU/CCPUSlaveEmitter.h b/extensions/Particle3D/PU/CCPUSlaveEmitter.h index c260cf59e4..32ab26c3c0 100644 --- a/extensions/Particle3D/PU/CCPUSlaveEmitter.h +++ b/extensions/Particle3D/PU/CCPUSlaveEmitter.h @@ -39,15 +39,15 @@ public: /** */ - std::string_view getMasterTechniqueName() const; + const std::string& getMasterTechniqueName() const; /** */ - void setMasterTechniqueName(std::string_view masterTechniqueName); + void setMasterTechniqueName(const std::string& masterTechniqueName); /** */ - std::string_view getMasterEmitterName() const; + const std::string& getMasterEmitterName() const; /** See ParticleEmitter. */ @@ -79,7 +79,7 @@ public: /** */ - void setMasterEmitterName(std::string_view masterEmitterName); + void setMasterEmitterName(const std::string& masterEmitterName); virtual PUSlaveEmitter* clone() override; virtual void copyAttributesTo(PUEmitter* emitter) override; diff --git a/extensions/Particle3D/PU/CCPUVertexEmitter.cpp b/extensions/Particle3D/PU/CCPUVertexEmitter.cpp index 97f9fc2a22..c7fcbb0276 100644 --- a/extensions/Particle3D/PU/CCPUVertexEmitter.cpp +++ b/extensions/Particle3D/PU/CCPUVertexEmitter.cpp @@ -84,12 +84,12 @@ NS_CC_BEGIN // mStep = step; // } ////----------------------------------------------------------------------- -// std::string_view Particle3DVertexEmitter::getMeshName() const +// const std::string& Particle3DVertexEmitter::getMeshName() const //{ // return mMeshName; // } ////----------------------------------------------------------------------- -// void Particle3DVertexEmitter::setMeshName(std::string_view meshName) +// void Particle3DVertexEmitter::setMeshName(const std::string& meshName) //{ // _setDefaults(); // Triggers loading the new mesh // mMeshName = meshName; @@ -184,7 +184,7 @@ NS_CC_BEGIN // void Particle3DVertexEmitter::_loadMesh () //{ // Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().load(mMeshName, -// Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); mMesh = mesh.getPointer(); mMeshProcessed = false; +//Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); mMesh = mesh.getPointer(); mMeshProcessed = false; // // if (mMesh->getNumSubMeshes() > 0) // { diff --git a/extensions/Particle3D/PU/CCPUVertexEmitter.h b/extensions/Particle3D/PU/CCPUVertexEmitter.h index b808d43acd..7db52020dd 100644 --- a/extensions/Particle3D/PU/CCPUVertexEmitter.h +++ b/extensions/Particle3D/PU/CCPUVertexEmitter.h @@ -148,7 +148,7 @@ NS_CC_BEGIN // // /** // */ -// std::string_view getMeshName() const; +// const std::string& getMeshName() const; // // /** // */ @@ -156,7 +156,7 @@ NS_CC_BEGIN // // /** // */ -// void setMeshName(std::string_view meshName); +// void setMeshName(const std::string& meshName); // // /** // */ diff --git a/extensions/assets-manager/AssetsManager.cpp b/extensions/assets-manager/AssetsManager.cpp index 8b9b571df1..2566e7b0c2 100644 --- a/extensions/assets-manager/AssetsManager.cpp +++ b/extensions/assets-manager/AssetsManager.cpp @@ -182,7 +182,7 @@ AssetsManager::AssetsManager(const char* packageUrl /* =nullptr */, checkStoragePath(); // convert downloader error code to AssetsManager::ErrorCode _downloader->onTaskError = [this](const DownloadTask& /*task*/, int errorCode, int /*errorCodeInternal*/, - std::string_view /*errorStr*/) { + const std::string& /*errorStr*/) { _isDownloading = false; if (nullptr == _delegate) @@ -278,10 +278,10 @@ void AssetsManager::checkStoragePath() } // Multiple key names -static std::string keyWithHash(const char* prefix, std::string_view url) +static std::string keyWithHash(const char* prefix, const std::string& url) { char buf[256]; - sprintf(buf, "%s%zd", prefix, std::hash()(url)); + sprintf(buf, "%s%zd", prefix, std::hash()(url)); return buf; } @@ -565,9 +565,9 @@ void AssetsManager::setVersionFileUrl(const char* versionFileUrl) _versionFileUrl = versionFileUrl; } -std::string_view AssetsManager::getVersion() +string AssetsManager::getVersion() { - return UserDefault::getInstance()->getStringForKey(keyOfVersion().data()); + return UserDefault::getInstance()->getStringForKey(keyOfVersion().c_str()); } void AssetsManager::deleteVersion() diff --git a/extensions/assets-manager/AssetsManager.h b/extensions/assets-manager/AssetsManager.h index b6587157a1..34a1fb8125 100644 --- a/extensions/assets-manager/AssetsManager.h +++ b/extensions/assets-manager/AssetsManager.h @@ -137,7 +137,7 @@ public: /* @brief Gets current version code. */ - std::string_view getVersion(); + std::string getVersion(); /* @brief Deletes recorded version code. */ diff --git a/extensions/assets-manager/AssetsManagerEx.cpp b/extensions/assets-manager/AssetsManagerEx.cpp index 8636f4523e..10f555c1ce 100644 --- a/extensions/assets-manager/AssetsManagerEx.cpp +++ b/extensions/assets-manager/AssetsManagerEx.cpp @@ -168,7 +168,8 @@ int AssetManagerEx_error_file_func(voidpf opaque, voidpf stream) // Implementation of AssetsManagerEx -AssetsManagerEx::AssetsManagerEx(std::string_view manifestUrl, std::string_view storagePath) : _manifestUrl(manifestUrl) +AssetsManagerEx::AssetsManagerEx(const std::string& manifestUrl, const std::string& storagePath) + : _manifestUrl(manifestUrl) { // Init variables _eventDispatcher = Director::getInstance()->getEventDispatcher(); @@ -207,14 +208,14 @@ AssetsManagerEx::~AssetsManagerEx() CC_SAFE_RELEASE(_remoteManifest); } -AssetsManagerEx* AssetsManagerEx::create(std::string_view manifestUrl, std::string_view storagePath) +AssetsManagerEx* AssetsManagerEx::create(const std::string& manifestUrl, const std::string& storagePath) { AssetsManagerEx* ret = new AssetsManagerEx(manifestUrl, storagePath); ret->autorelease(); return ret; } -void AssetsManagerEx::initManifests(std::string_view manifestUrl) +void AssetsManagerEx::initManifests(const std::string& manifestUrl) { _inited = true; // Init and load local manifest @@ -259,7 +260,7 @@ void AssetsManagerEx::prepareLocalManifest() _localManifest->prependSearchPaths(); } -void AssetsManagerEx::loadLocalManifest(std::string_view /*manifestUrl*/) +void AssetsManagerEx::loadLocalManifest(const std::string& /*manifestUrl*/) { Manifest* cachedManifest = nullptr; // Find the cached manifest file @@ -328,7 +329,7 @@ void AssetsManagerEx::loadLocalManifest(std::string_view /*manifestUrl*/) } } -std::string_view AssetsManagerEx::basename(std::string_view path) const +std::string AssetsManagerEx::basename(const std::string& path) const { size_t found = path.find_last_of("/\\"); @@ -342,7 +343,7 @@ std::string_view AssetsManagerEx::basename(std::string_view path) const } } -std::string AssetsManagerEx::get(std::string_view key) const +std::string AssetsManagerEx::get(const std::string& key) const { auto it = _assets->find(key); if (it != _assets->cend()) @@ -363,12 +364,12 @@ const Manifest* AssetsManagerEx::getRemoteManifest() const return _remoteManifest; } -std::string_view AssetsManagerEx::getStoragePath() const +const std::string& AssetsManagerEx::getStoragePath() const { return _storagePath; } -void AssetsManagerEx::setStoragePath(std::string_view storagePath) +void AssetsManagerEx::setStoragePath(const std::string& storagePath) { _storagePath = storagePath; adjustPath(_storagePath); @@ -388,16 +389,16 @@ void AssetsManagerEx::adjustPath(std::string& path) } } -bool AssetsManagerEx::decompress(std::string_view zip) +bool AssetsManagerEx::decompress(const std::string& zip) { // Find root path for zip file size_t pos = zip.find_last_of("/\\"); if (pos == std::string::npos) { - CCLOG("AssetsManagerEx : no root path specified for zip file %s\n", zip.data()); + CCLOG("AssetsManagerEx : no root path specified for zip file %s\n", zip.c_str()); return false; } - const std::string_view rootPath = zip.substr(0, pos + 1); + const std::string rootPath = zip.substr(0, pos + 1); zlib_filefunc_def_s zipFunctionOverrides; fillZipFunctionOverrides(zipFunctionOverrides); @@ -408,10 +409,10 @@ bool AssetsManagerEx::decompress(std::string_view zip) zipFunctionOverrides.opaque = &zipFileInfo; // Open the zip file - unzFile zipfile = unzOpen2(zip.data(), &zipFunctionOverrides); + unzFile zipfile = unzOpen2(zip.c_str(), &zipFunctionOverrides); if (!zipfile) { - CCLOG("AssetsManagerEx : can not open downloaded zip file %s\n", zip.data()); + CCLOG("AssetsManagerEx : can not open downloaded zip file %s\n", zip.c_str()); return false; } @@ -419,7 +420,7 @@ bool AssetsManagerEx::decompress(std::string_view zip) unz_global_info global_info; if (unzGetGlobalInfo(zipfile, &global_info) != UNZ_OK) { - CCLOG("AssetsManagerEx : can not read file global info of %s\n", zip.data()); + CCLOG("AssetsManagerEx : can not read file global info of %s\n", zip.c_str()); unzClose(zipfile); return false; } @@ -439,8 +440,7 @@ bool AssetsManagerEx::decompress(std::string_view zip) unzClose(zipfile); return false; } - std::string fullPath{rootPath}; - fullPath += fileName; + const std::string fullPath = rootPath + fileName; // Check if this entry is a directory or a file. const size_t filenameLength = strlen(fileName); @@ -459,7 +459,7 @@ bool AssetsManagerEx::decompress(std::string_view zip) else { // Create all directories in advance to avoid issue - std::string_view dir = basename(fullPath); + std::string dir = basename(fullPath); if (!_fileUtils->isDirectoryExist(dir)) { if (!_fileUtils->createDirectory(dir)) @@ -531,7 +531,7 @@ bool AssetsManagerEx::decompress(std::string_view zip) return true; } -void AssetsManagerEx::decompressDownloadedZip(std::string_view customId, std::string_view storagePath) +void AssetsManagerEx::decompressDownloadedZip(const std::string& customId, const std::string& storagePath) { struct AsyncData { @@ -573,8 +573,8 @@ void AssetsManagerEx::decompressDownloadedZip(std::string_view customId, std::st } void AssetsManagerEx::dispatchUpdateEvent(EventAssetsManagerEx::EventCode code, - std::string_view assetId /* = ""*/, - std::string_view message /* = ""*/, + const std::string& assetId /* = ""*/, + const std::string& message /* = ""*/, int curle_code /* = CURLE_OK*/, int curlm_code /* = CURLM_OK*/) { @@ -619,7 +619,7 @@ void AssetsManagerEx::downloadVersion() if (_updateState > State::PREDOWNLOAD_VERSION) return; - std::string_view versionUrl = _localManifest->getVersionFileUrl(); + std::string versionUrl = _localManifest->getVersionFileUrl(); if (!versionUrl.empty()) { @@ -786,7 +786,7 @@ void AssetsManagerEx::startUpdate() _tempManifest = _remoteManifest; // Check difference between local manifest and remote manifest - hlookup::string_map diff_map = _localManifest->genDiff(_remoteManifest); + std::unordered_map diff_map = _localManifest->genDiff(_remoteManifest); if (diff_map.empty()) { updateSucceed(); @@ -794,7 +794,7 @@ void AssetsManagerEx::startUpdate() else { // Generate download units for all assets that need to be updated or added - std::string_view packageUrl = _remoteManifest->getPackageUrl(); + std::string packageUrl = _remoteManifest->getPackageUrl(); // Save current download manifest information for resuming _tempManifest->saveToFile(_tempManifestPath); // Preprocessing local files in previous version and creating download folders @@ -803,11 +803,10 @@ void AssetsManagerEx::startUpdate() Manifest::AssetDiff diff = it->second; if (diff.type != Manifest::DiffType::DELETED) { - const std::string& path = diff.asset.path; + std::string path = diff.asset.path; DownloadUnit unit; - unit.customId = it->first; - unit.srcUrl = packageUrl; - unit.srcUrl += path; + unit.customId = it->first; + unit.srcUrl = packageUrl + path; unit.storagePath = _tempStoragePath + path; unit.size = diff.asset.size; _downloadUnits.emplace(unit.customId, unit); @@ -1035,8 +1034,8 @@ void AssetsManagerEx::downloadFailedAssets() updateAssets(_failedUnits); } -void AssetsManagerEx::fileError(std::string_view identifier, - std::string_view errorStr, +void AssetsManagerEx::fileError(const std::string& identifier, + const std::string& errorStr, int errorCode, int errorCodeInternal) { @@ -1057,7 +1056,7 @@ void AssetsManagerEx::fileError(std::string_view identifier, queueDowload(); } -void AssetsManagerEx::fileSuccess(std::string_view customId, std::string_view storagePath) +void AssetsManagerEx::fileSuccess(const std::string& customId, const std::string& storagePath) { // Set download state to SUCCESSED _tempManifest->setAssetDownloadState(customId, Manifest::DownloadState::SUCCESSED); @@ -1090,7 +1089,7 @@ void AssetsManagerEx::fileSuccess(std::string_view customId, std::string_view st void AssetsManagerEx::onError(const network::DownloadTask& task, int errorCode, int errorCodeInternal, - std::string_view errorStr) + const std::string& errorStr) { // Skip version error occurred if (task.identifier == VERSION_ID) @@ -1111,7 +1110,10 @@ void AssetsManagerEx::onError(const network::DownloadTask& task, } } -void AssetsManagerEx::onProgress(double total, double downloaded, std::string_view /*url*/, std::string_view customId) +void AssetsManagerEx::onProgress(double total, + double downloaded, + const std::string& /*url*/, + const std::string& customId) { if (customId == VERSION_ID || customId == MANIFEST_ID) { @@ -1168,7 +1170,9 @@ void AssetsManagerEx::onProgress(double total, double downloaded, std::string_vi } } -void AssetsManagerEx::onSuccess(std::string_view /*srcUrl*/, std::string_view storagePath, std::string_view customId) +void AssetsManagerEx::onSuccess(const std::string& /*srcUrl*/, + const std::string& storagePath, + const std::string& customId) { if (customId == VERSION_ID) { diff --git a/extensions/assets-manager/AssetsManagerEx.h b/extensions/assets-manager/AssetsManagerEx.h index 7a77db5b44..7180323d2d 100644 --- a/extensions/assets-manager/AssetsManagerEx.h +++ b/extensions/assets-manager/AssetsManagerEx.h @@ -77,7 +77,7 @@ public: @warning The cached manifest in your storage path have higher priority and will be searched first, only if it doesn't exist, AssetsManagerEx will use the given manifestUrl. */ - static AssetsManagerEx* create(std::string_view manifestUrl, std::string_view storagePath); + static AssetsManagerEx* create(const std::string& manifestUrl, const std::string& storagePath); /** @brief Check out if there is a new version of manifest. * You may use this method before updating, then let user determine whether @@ -99,7 +99,7 @@ public: /** @brief Gets storage path. */ - std::string_view getStoragePath() const; + const std::string& getStoragePath() const; /** @brief Function for retrieving the local manifest object */ @@ -120,7 +120,8 @@ public: /** @brief Set the handle function for comparing manifests versions * @param handle The compare function */ - void setVersionCompareHandle(const std::function& handle) + void setVersionCompareHandle( + const std::function& handle) { _versionCompareHandle = handle; }; @@ -129,37 +130,37 @@ public: * verification * @param callback The verify callback function */ - void setVerifyCallback(const std::function& callback) + void setVerifyCallback(const std::function& callback) { _verifyCallback = callback; }; CC_CONSTRUCTOR_ACCESS : - AssetsManagerEx(std::string_view manifestUrl, std::string_view storagePath); + AssetsManagerEx(const std::string& manifestUrl, const std::string& storagePath); virtual ~AssetsManagerEx(); protected: - std::string_view basename(std::string_view path) const; + std::string basename(const std::string& path) const; - std::string get(std::string_view key) const; + std::string get(const std::string& key) const; - void initManifests(std::string_view manifestUrl); + void initManifests(const std::string& manifestUrl); - void loadLocalManifest(std::string_view manifestUrl); + void loadLocalManifest(const std::string& manifestUrl); void prepareLocalManifest(); - void setStoragePath(std::string_view storagePath); + void setStoragePath(const std::string& storagePath); void adjustPath(std::string& path); void dispatchUpdateEvent(EventAssetsManagerEx::EventCode code, - std::string_view message = "", - std::string_view assetId = "", - int curle_code = 0, - int curlm_code = 0); + const std::string& message = "", + const std::string& assetId = "", + int curle_code = 0, + int curlm_code = 0); void downloadVersion(); void parseVersion(); @@ -167,8 +168,8 @@ protected: void parseManifest(); void startUpdate(); void updateSucceed(); - bool decompress(std::string_view filename); - void decompressDownloadedZip(std::string_view customId, std::string_view storagePath); + bool decompress(const std::string& filename); + void decompressDownloadedZip(const std::string& customId, const std::string& storagePath); /** @brief Update a list of assets under the current AssetsManagerEx context */ @@ -186,12 +187,12 @@ protected: */ void queueDowload(); - void fileError(std::string_view identifier, - std::string_view errorStr, + void fileError(const std::string& identifier, + const std::string& errorStr, int errorCode = 0, int errorCodeInternal = 0); - void fileSuccess(std::string_view customId, std::string_view storagePath); + void fileSuccess(const std::string& customId, const std::string& storagePath); /** @brief Call back function for error handling, the error will then be reported to user's listener registed in addUpdateEventListener @@ -203,7 +204,7 @@ protected: virtual void onError(const network::DownloadTask& task, int errorCode, int errorCodeInternal, - std::string_view errorStr); + const std::string& errorStr); /** @brief Call back function for recording downloading percent of the current asset, the progression will then be reported to user's listener registed in addUpdateProgressEventListener @@ -215,7 +216,7 @@ protected: * @js NA * @lua NA */ - virtual void onProgress(double total, double downloaded, std::string_view url, std::string_view customId); + virtual void onProgress(double total, double downloaded, const std::string& url, const std::string& customId); /** @brief Call back function for success of the current asset the success event will then be send to user's listener registed in addUpdateEventListener @@ -225,7 +226,7 @@ protected: * @js NA * @lua NA */ - virtual void onSuccess(std::string_view srcUrl, std::string_view storagePath, std::string_view customId); + virtual void onSuccess(const std::string& srcUrl, const std::string& storagePath, const std::string& customId); private: void batchDownload(); @@ -249,7 +250,7 @@ private: std::shared_ptr _downloader; //! The reference to the local assets - const hlookup::string_map* _assets = nullptr; + const std::unordered_map* _assets = nullptr; //! The path to store successfully downloaded version. std::string _storagePath; @@ -319,7 +320,7 @@ private: double _totalSize; //! Downloaded size for each file - hlookup::string_map _downloadedSize; + std::unordered_map _downloadedSize; //! Total number of assets to download int _totalToDownload = 0; @@ -329,10 +330,10 @@ private: float _nextSavePoint = 0.f; //! Handle function to compare versions between different manifests - std::function _versionCompareHandle = nullptr; + std::function _versionCompareHandle = nullptr; //! Callback function to verify the downloaded assets - std::function _verifyCallback = nullptr; + std::function _verifyCallback = nullptr; //! Marker for whether the assets manager is inited bool _inited = false; diff --git a/extensions/assets-manager/CCEventAssetsManagerEx.cpp b/extensions/assets-manager/CCEventAssetsManagerEx.cpp index e14a7eed30..183daae660 100644 --- a/extensions/assets-manager/CCEventAssetsManagerEx.cpp +++ b/extensions/assets-manager/CCEventAssetsManagerEx.cpp @@ -30,13 +30,13 @@ NS_CC_EXT_BEGIN -EventAssetsManagerEx::EventAssetsManagerEx(std::string_view eventName, +EventAssetsManagerEx::EventAssetsManagerEx(const std::string& eventName, cocos2d::extension::AssetsManagerEx* manager, const EventCode& code, float percent /* = 0 */, float percentByFile /* = 0*/, - std::string_view assetId /* = "" */, - std::string_view message /* = "" */, + const std::string& assetId /* = "" */, + const std::string& message /* = "" */, int curle_code /* = CURLE_OK*/, int curlm_code /* = CURLM_OK*/) : EventCustom(eventName) diff --git a/extensions/assets-manager/CCEventAssetsManagerEx.h b/extensions/assets-manager/CCEventAssetsManagerEx.h index 11a6ad1220..0d261ac5b9 100644 --- a/extensions/assets-manager/CCEventAssetsManagerEx.h +++ b/extensions/assets-manager/CCEventAssetsManagerEx.h @@ -74,15 +74,15 @@ public: CC_CONSTRUCTOR_ACCESS : /** Constructor */ - EventAssetsManagerEx(std::string_view eventName, + EventAssetsManagerEx(const std::string& eventName, cocos2d::extension::AssetsManagerEx* manager, const EventCode& code, - float percent = 0, - float percentByFile = 0, - std::string_view assetId = "", - std::string_view message = "", - int curle_code = 0, - int curlm_code = 0); + float percent = 0, + float percentByFile = 0, + const std::string& assetId = "", + const std::string& message = "", + int curle_code = 0, + int curlm_code = 0); private: EventCode _code; diff --git a/extensions/assets-manager/Manifest.cpp b/extensions/assets-manager/Manifest.cpp index 98af1eb1e1..43dc418e19 100644 --- a/extensions/assets-manager/Manifest.cpp +++ b/extensions/assets-manager/Manifest.cpp @@ -50,16 +50,16 @@ NS_CC_EXT_BEGIN -static int cmpVersion(std::string_view v1, std::string_view v2) +static int cmpVersion(const std::string& v1, const std::string& v2) { int i; int oct_v1[4] = {0}, oct_v2[4] = {0}; - int filled1 = std::sscanf(v1.data(), "%d.%d.%d.%d", &oct_v1[0], &oct_v1[1], &oct_v1[2], &oct_v1[3]); - int filled2 = std::sscanf(v2.data(), "%d.%d.%d.%d", &oct_v2[0], &oct_v2[1], &oct_v2[2], &oct_v2[3]); + int filled1 = std::sscanf(v1.c_str(), "%d.%d.%d.%d", &oct_v1[0], &oct_v1[1], &oct_v1[2], &oct_v1[3]); + int filled2 = std::sscanf(v2.c_str(), "%d.%d.%d.%d", &oct_v2[0], &oct_v2[1], &oct_v2[2], &oct_v2[3]); if (filled1 == 0 || filled2 == 0) { - return v1 != v2; // strcmp(v1.data(), v2.data()); + return strcmp(v1.c_str(), v2.c_str()); } for (i = 0; i < 4; i++) { @@ -71,7 +71,7 @@ static int cmpVersion(std::string_view v1, std::string_view v2) return 0; } -Manifest::Manifest(std::string_view manifestUrl /* = ""*/) +Manifest::Manifest(const std::string& manifestUrl /* = ""*/) : _versionLoaded(false) , _loaded(false) , _manifestRoot("") @@ -86,7 +86,7 @@ Manifest::Manifest(std::string_view manifestUrl /* = ""*/) parse(manifestUrl); } -void Manifest::loadJson(std::string_view url) +void Manifest::loadJson(const std::string& url) { clear(); std::string content; @@ -97,7 +97,7 @@ void Manifest::loadJson(std::string_view url) if (content.empty()) { - CCLOG("Fail to retrieve local file content: %s\n", url.data()); + CCLOG("Fail to retrieve local file content: %s\n", url.c_str()); } else { @@ -116,7 +116,7 @@ void Manifest::loadJson(std::string_view url) } } -void Manifest::parseVersion(std::string_view versionUrl) +void Manifest::parseVersion(const std::string& versionUrl) { loadJson(versionUrl); @@ -126,7 +126,7 @@ void Manifest::parseVersion(std::string_view versionUrl) } } -void Manifest::parse(std::string_view manifestUrl) +void Manifest::parse(const std::string& manifestUrl) { loadJson(manifestUrl); @@ -161,8 +161,8 @@ bool Manifest::versionEquals(const Manifest* b) const // Check group versions else { - std::vector bGroups = b->getGroups(); - auto& bGroupVer = b->getGroupVerions(); + std::vector bGroups = b->getGroups(); + std::unordered_map bGroupVer = b->getGroupVerions(); // Check group size if (bGroups.size() != _groups.size()) return false; @@ -184,10 +184,10 @@ bool Manifest::versionEquals(const Manifest* b) const bool Manifest::versionGreater( const Manifest* b, - const std::function& handle) const + const std::function& handle) const { - std::string_view localVersion = getVersion(); - std::string_view bVersion = b->getVersion(); + std::string localVersion = getVersion(); + const std::string& bVersion = b->getVersion(); bool greater; if (handle) { @@ -200,16 +200,16 @@ bool Manifest::versionGreater( return greater; } -hlookup::string_map Manifest::genDiff(const Manifest* b) const +std::unordered_map Manifest::genDiff(const Manifest* b) const { - hlookup::string_map diff_map; - auto& bAssets = b->getAssets(); + std::unordered_map diff_map; + const std::unordered_map& bAssets = b->getAssets(); std::string key; Asset valueA; Asset valueB; - hlookup::string_map::const_iterator valueIt, it; + std::unordered_map::const_iterator valueIt, it; for (it = _assets.begin(); it != _assets.end(); ++it) { key = it->first; @@ -317,22 +317,22 @@ void Manifest::prependSearchPaths() } } -std::string_view Manifest::getPackageUrl() const +const std::string& Manifest::getPackageUrl() const { return _packageUrl; } -std::string_view Manifest::getManifestFileUrl() const +const std::string& Manifest::getManifestFileUrl() const { return _remoteManifestUrl; } -std::string_view Manifest::getVersionFileUrl() const +const std::string& Manifest::getVersionFileUrl() const { return _remoteVersionUrl; } -std::string_view Manifest::getVersion() const +const std::string& Manifest::getVersion() const { return _version; } @@ -342,22 +342,22 @@ const std::vector& Manifest::getGroups() const return _groups; } -const hlookup::string_map& Manifest::getGroupVerions() const +const std::unordered_map& Manifest::getGroupVerions() const { return _groupVer; } -std::string_view Manifest::getGroupVersion(std::string_view group) const +const std::string& Manifest::getGroupVersion(const std::string& group) const { return _groupVer.at(group); } -const hlookup::string_map& Manifest::getAssets() const +const std::unordered_map& Manifest::getAssets() const { return _assets; } -void Manifest::setAssetDownloadState(std::string_view key, const Manifest::DownloadState& state) +void Manifest::setAssetDownloadState(const std::string& key, const Manifest::DownloadState& state) { auto valueIt = _assets.find(key); if (valueIt != _assets.end()) @@ -372,9 +372,9 @@ void Manifest::setAssetDownloadState(std::string_view key, const Manifest::Downl rapidjson::Value& assets = _json[KEY_ASSETS]; if (assets.IsObject()) { - if (assets.HasMember(key.data())) + if (assets.HasMember(key.c_str())) { - rapidjson::Value& entry = assets[key.data()]; + rapidjson::Value& entry = assets[key.c_str()]; if (entry.HasMember(KEY_DOWNLOAD_STATE) && entry[KEY_DOWNLOAD_STATE].IsInt()) { entry[KEY_DOWNLOAD_STATE].SetInt((int)state); @@ -413,7 +413,7 @@ void Manifest::clear() } } -Manifest::Asset Manifest::parseAsset(std::string_view path, const rapidjson::Value& json) +Manifest::Asset Manifest::parseAsset(const std::string& path, const rapidjson::Value& json) { Asset asset; asset.path = path; @@ -553,7 +553,7 @@ void Manifest::loadManifest(const rapidjson::Document& json) _loaded = true; } -void Manifest::saveToFile(std::string_view filepath) +void Manifest::saveToFile(const std::string& filepath) { rapidjson::StringBuffer buffer; rapidjson::PrettyWriter writer(buffer); diff --git a/extensions/assets-manager/Manifest.h b/extensions/assets-manager/Manifest.h index d582608108..695cbe55c7 100644 --- a/extensions/assets-manager/Manifest.h +++ b/extensions/assets-manager/Manifest.h @@ -56,7 +56,7 @@ struct ManifestAsset int downloadState; }; -typedef hlookup::string_map DownloadUnits; +typedef std::unordered_map DownloadUnits; class CC_EX_DLL Manifest : public Ref { @@ -99,19 +99,19 @@ public: /** @brief Gets remote package url. */ - std::string_view getPackageUrl() const; + const std::string& getPackageUrl() const; /** @brief Gets remote manifest file url. */ - std::string_view getManifestFileUrl() const; + const std::string& getManifestFileUrl() const; /** @brief Gets remote version file url. */ - std::string_view getVersionFileUrl() const; + const std::string& getVersionFileUrl() const; /** @brief Gets manifest version. */ - std::string_view getVersion() const; + const std::string& getVersion() const; /** @brief Get the search paths list related to the Manifest. */ @@ -121,22 +121,22 @@ protected: /** @brief Constructor for Manifest class * @param manifestUrl Url of the local manifest */ - Manifest(std::string_view manifestUrl = ""); + Manifest(const std::string& manifestUrl = ""); /** @brief Load the json file into local json object * @param url Url of the json file */ - void loadJson(std::string_view url); + void loadJson(const std::string& url); /** @brief Parse the version file information into this manifest * @param versionUrl Url of the local version file */ - void parseVersion(std::string_view versionUrl); + void parseVersion(const std::string& versionUrl); /** @brief Parse the manifest file information into this manifest * @param manifestUrl Url of the local manifest */ - void parse(std::string_view manifestUrl); + void parse(const std::string& manifestUrl); /** @brief Check whether the version of this manifest equals to another. * @param b The other manifest @@ -149,13 +149,14 @@ protected: * @param [handle] Customized comparasion handle function * @return Greater or not */ - bool versionGreater(const Manifest* b, - const std::function& handle) const; + bool versionGreater( + const Manifest* b, + const std::function& handle) const; /** @brief Generate difference between this Manifest and another. * @param b The other manifest */ - hlookup::string_map genDiff(const Manifest* b) const; + std::unordered_map genDiff(const Manifest* b) const; /** @brief Generate resuming download assets list * @param units The download units reference to be modified by the generation result @@ -170,9 +171,9 @@ protected: void loadManifest(const rapidjson::Document& json); - void saveToFile(std::string_view filepath); + void saveToFile(const std::string& filepath); - Asset parseAsset(std::string_view path, const rapidjson::Value& json); + Asset parseAsset(const std::string& path, const rapidjson::Value& json); void clear(); @@ -182,26 +183,26 @@ protected: /** @brief Gets all groups version. */ - const hlookup::string_map& getGroupVerions() const; + const std::unordered_map& getGroupVerions() const; /** @brief Gets version for the given group. * @param group Key of the requested group */ - std::string_view getGroupVersion(std::string_view group) const; + const std::string& getGroupVersion(const std::string& group) const; /** * @brief Gets assets. * @lua NA */ - const hlookup::string_map& getAssets() const; + const std::unordered_map& getAssets() const; /** @brief Set the download state for an asset * @param key Key of the asset to set * @param state The current download state of the asset */ - void setAssetDownloadState(std::string_view key, const DownloadState& state); + void setAssetDownloadState(const std::string& key, const DownloadState& state); - void setManifestRoot(std::string_view root) { _manifestRoot = root; }; + void setManifestRoot(const std::string& root) { _manifestRoot = root; }; private: //! Indicate whether the version informations have been fully loaded @@ -232,13 +233,13 @@ private: std::vector _groups; //! The versions of all local group [Optional] - hlookup::string_map _groupVer; + std::unordered_map _groupVer; //! The version of local engine std::string _engineVer; //! Full assets list - hlookup::string_map _assets; + std::unordered_map _assets; //! All search paths std::vector _searchPaths; diff --git a/extensions/cocostudio/ActionTimeline/CCActionTimeline.cpp b/extensions/cocostudio/ActionTimeline/CCActionTimeline.cpp index 6edbb87073..bf4dd8ac18 100644 --- a/extensions/cocostudio/ActionTimeline/CCActionTimeline.cpp +++ b/extensions/cocostudio/ActionTimeline/CCActionTimeline.cpp @@ -319,12 +319,12 @@ void ActionTimeline::removeAnimationInfo(std::string animationName) _animationInfos.erase(animationName); } -bool ActionTimeline::IsAnimationInfoExists(std::string_view animationName) +bool ActionTimeline::IsAnimationInfoExists(const std::string& animationName) { return _animationInfos.find(animationName) != _animationInfos.end(); } -const AnimationInfo& ActionTimeline::getAnimationInfo(std::string_view animationName) +const AnimationInfo& ActionTimeline::getAnimationInfo(const std::string& animationName) { return _animationInfos.find(animationName)->second; } @@ -369,7 +369,7 @@ void ActionTimeline::emitFrameEvent(Frame* frame) } } -void ActionTimeline::addFrameEndCallFunc(int frameIndex, std::string_view funcKey, std::function func) +void ActionTimeline::addFrameEndCallFunc(int frameIndex, const std::string& funcKey, std::function func) { if (func != nullptr) { @@ -377,7 +377,7 @@ void ActionTimeline::addFrameEndCallFunc(int frameIndex, std::string_view funcKe } } -void ActionTimeline::removeFrameEndCallFunc(int frameIndex, std::string_view funcKey) +void ActionTimeline::removeFrameEndCallFunc(int frameIndex, const std::string& funcKey) { auto endClipCallsIter = _frameEndCallFuncs.find(frameIndex); if (endClipCallsIter != _frameEndCallFuncs.end()) diff --git a/extensions/cocostudio/ActionTimeline/CCActionTimeline.h b/extensions/cocostudio/ActionTimeline/CCActionTimeline.h index 0d57dea4a1..6437359ff4 100644 --- a/extensions/cocostudio/ActionTimeline/CCActionTimeline.h +++ b/extensions/cocostudio/ActionTimeline/CCActionTimeline.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org @@ -37,7 +37,7 @@ typedef struct AnimationInfo { AnimationInfo() : startIndex(0), endIndex(0) {} - AnimationInfo(std::string_view otherName, int otherStartIndex, int otherEndIndex) + AnimationInfo(const std::string& otherName, int otherStartIndex, int otherEndIndex) : name(otherName), startIndex(otherStartIndex), endIndex(otherEndIndex) {} @@ -150,8 +150,8 @@ public: /** AnimationInfo*/ virtual void addAnimationInfo(const AnimationInfo& animationInfo); virtual void removeAnimationInfo(std::string animationName); - virtual bool IsAnimationInfoExists(std::string_view animationName); - virtual const AnimationInfo& getAnimationInfo(std::string_view animationName); + virtual bool IsAnimationInfoExists(const std::string& animationName); + virtual const AnimationInfo& getAnimationInfo(const std::string& animationName); /**add a frame end call back to animation's end frame * @param animationName @addFrameEndCallFunc, make the animationName as funcKey * @param func the callback function @@ -171,9 +171,9 @@ public: * @param funcKey for identity the callback function * @param func the callback function */ - virtual void addFrameEndCallFunc(int frameIndex, std::string_view funcKey, std::function func); + virtual void addFrameEndCallFunc(int frameIndex, const std::string& funcKey, std::function func); // remove callback function after frameIndex which identified with funcKey - virtual void removeFrameEndCallFunc(int frameIndex, std::string_view funcKey); + virtual void removeFrameEndCallFunc(int frameIndex, const std::string& funcKey); // clear callback functions after frameIndex virtual void removeFrameEndCallFuncs(int frameIndex); // clear all the callback functions after frameIndexs in this actiontimeline @@ -224,8 +224,8 @@ protected: std::function _frameEventListener; std::function _lastFrameListener; - std::map>> _frameEndCallFuncs; - hlookup::string_map _animationInfos; + std::map>> _frameEndCallFuncs; + std::map _animationInfos; }; NS_TIMELINE_END diff --git a/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.cpp b/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.cpp index 5ca337f084..44af85a5c5 100644 --- a/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.cpp +++ b/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.cpp @@ -126,7 +126,7 @@ void ActionTimelineCache::init() */ } -void ActionTimelineCache::removeAction(std::string_view fileName) +void ActionTimelineCache::removeAction(const std::string& fileName) { if (_animationActions.find(fileName) != _animationActions.end()) { @@ -134,11 +134,11 @@ void ActionTimelineCache::removeAction(std::string_view fileName) } } -ActionTimeline* ActionTimelineCache::createAction(std::string_view filename) +ActionTimeline* ActionTimelineCache::createAction(const std::string& filename) { - auto path = filename; - size_t pos = path.find_last_of('.'); - auto suffix = path.substr(pos + 1, path.length()); + std::string path = filename; + size_t pos = path.find_last_of('.'); + std::string suffix = path.substr(pos + 1, path.length()); ActionTimelineCache* cache = ActionTimelineCache::getInstance(); @@ -154,7 +154,7 @@ ActionTimeline* ActionTimelineCache::createAction(std::string_view filename) return nullptr; } -ActionTimeline* ActionTimelineCache::createActionFromJson(std::string_view fileName) +ActionTimeline* ActionTimelineCache::createActionFromJson(const std::string& fileName) { ActionTimeline* action = _animationActions.at(fileName); if (action == nullptr) @@ -164,7 +164,7 @@ ActionTimeline* ActionTimelineCache::createActionFromJson(std::string_view fileN return action->clone(); } -ActionTimeline* ActionTimelineCache::createActionFromContent(std::string_view fileName, std::string_view content) +ActionTimeline* ActionTimelineCache::createActionFromContent(const std::string& fileName, const std::string& content) { ActionTimeline* action = _animationActions.at(fileName); if (action == nullptr) @@ -174,7 +174,7 @@ ActionTimeline* ActionTimelineCache::createActionFromContent(std::string_view fi return action->clone(); } -ActionTimeline* ActionTimelineCache::loadAnimationActionWithFile(std::string_view fileName) +ActionTimeline* ActionTimelineCache::loadAnimationActionWithFile(const std::string& fileName) { // Read content from file std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName); @@ -183,7 +183,8 @@ ActionTimeline* ActionTimelineCache::loadAnimationActionWithFile(std::string_vie return loadAnimationActionWithContent(fileName, contentStr); } -ActionTimeline* ActionTimelineCache::loadAnimationActionWithContent(std::string_view fileName, std::string_view content) +ActionTimeline* ActionTimelineCache::loadAnimationActionWithContent(const std::string& fileName, + const std::string& content) { // if already exists an action with filename, then return this action ActionTimeline* action = _animationActions.at(fileName); @@ -191,7 +192,7 @@ ActionTimeline* ActionTimelineCache::loadAnimationActionWithContent(std::string_ return action; rapidjson::Document doc; - doc.Parse<0>(content.data(), content.length()); + doc.Parse<0>(content.c_str()); if (doc.HasParseError()) { CCLOG("GetParseError %d\n", doc.GetParseError()); @@ -414,7 +415,7 @@ Frame* ActionTimelineCache::loadZOrderFrame(const rapidjson::Value& json) return frame; } -ActionTimeline* ActionTimelineCache::createActionWithFlatBuffersFile(std::string_view fileName) +ActionTimeline* ActionTimelineCache::createActionWithFlatBuffersFile(const std::string& fileName) { ActionTimeline* action = _animationActions.at(fileName); if (action == NULL) @@ -424,7 +425,7 @@ ActionTimeline* ActionTimelineCache::createActionWithFlatBuffersFile(std::string return action->clone(); } -ActionTimeline* ActionTimelineCache::createActionWithDataBuffer(Data data, std::string_view fileName) +ActionTimeline* ActionTimelineCache::createActionWithDataBuffer(Data data, const std::string& fileName) { ActionTimeline* action = _animationActions.at(fileName); if (action == NULL) @@ -434,13 +435,15 @@ ActionTimeline* ActionTimelineCache::createActionWithDataBuffer(Data data, std:: return action->clone(); } -ActionTimeline* ActionTimelineCache::loadAnimationActionWithFlatBuffersFile(std::string_view fileName) +ActionTimeline* ActionTimelineCache::loadAnimationActionWithFlatBuffersFile(const std::string& fileName) { // if already exists an action with filename, then return this action ActionTimeline* action = _animationActions.at(fileName); if (action) return action; + std::string path = fileName; + std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName); CC_ASSERT(FileUtils::getInstance()->isFileExist(fullPath)); @@ -452,13 +455,15 @@ ActionTimeline* ActionTimelineCache::loadAnimationActionWithFlatBuffersFile(std: return action; } -ActionTimeline* ActionTimelineCache::loadAnimationWithDataBuffer(const cocos2d::Data& data, std::string_view fileName) +ActionTimeline* ActionTimelineCache::loadAnimationWithDataBuffer(const cocos2d::Data& data, const std::string& fileName) { // if already exists an action with filename, then return this action ActionTimeline* action = _animationActions.at(fileName); if (action) return action; + std::string path = fileName; + std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName); CC_ASSERT(FileUtils::getInstance()->isFileExist(fullPath)); @@ -948,7 +953,7 @@ void ActionTimelineCache::loadEasingDataWithFlatBuffers(cocostudio::timeline::Fr } } -ActionTimeline* ActionTimelineCache::createActionWithFlatBuffersForSimulator(std::string_view fileName) +ActionTimeline* ActionTimelineCache::createActionWithFlatBuffersForSimulator(const std::string& fileName) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); fbs->_isSimulator = true; diff --git a/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.h b/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.h index ff3ecc26a0..052280d164 100644 --- a/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.h +++ b/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org @@ -71,24 +71,24 @@ public: void init(); /** Remove action with filename, and also remove other resource relate with this file */ - void removeAction(std::string_view fileName); + void removeAction(const std::string& fileName); - static ActionTimeline* createAction(std::string_view fileName); + static ActionTimeline* createAction(const std::string& fileName); /** Clone a action with the specified name from the container. */ - ActionTimeline* createActionFromJson(std::string_view fileName); - ActionTimeline* createActionFromContent(std::string_view fileName, std::string_view content); + ActionTimeline* createActionFromJson(const std::string& fileName); + ActionTimeline* createActionFromContent(const std::string& fileName, const std::string& content); - ActionTimeline* loadAnimationActionWithFile(std::string_view fileName); - ActionTimeline* loadAnimationActionWithContent(std::string_view fileName, std::string_view content); + ActionTimeline* loadAnimationActionWithFile(const std::string& fileName); + ActionTimeline* loadAnimationActionWithContent(const std::string& fileName, const std::string& content); - ActionTimeline* createActionWithFlatBuffersFile(std::string_view fileName); - ActionTimeline* createActionWithDataBuffer(cocos2d::Data data, std::string_view fileName); + ActionTimeline* createActionWithFlatBuffersFile(const std::string& fileName); + ActionTimeline* createActionWithDataBuffer(cocos2d::Data data, const std::string& fileName); - ActionTimeline* loadAnimationActionWithFlatBuffersFile(std::string_view fileName); - ActionTimeline* loadAnimationWithDataBuffer(const cocos2d::Data& data, std::string_view fileName); + ActionTimeline* loadAnimationActionWithFlatBuffersFile(const std::string& fileName); + ActionTimeline* loadAnimationWithDataBuffer(const cocos2d::Data& data, const std::string& fileName); - ActionTimeline* createActionWithFlatBuffersForSimulator(std::string_view fileName); + ActionTimeline* createActionWithFlatBuffersForSimulator(const std::string& fileName); protected: Timeline* loadTimeline(const rapidjson::Value& json); @@ -128,8 +128,8 @@ protected: typedef std::function FrameCreateFunc; typedef std::pair Pair; - hlookup::string_map _funcs; - cocos2d::StringMap _animationActions; + std::unordered_map _funcs; + cocos2d::Map _animationActions; }; NS_TIMELINE_END diff --git a/extensions/cocostudio/ActionTimeline/CCBoneNode.cpp b/extensions/cocostudio/ActionTimeline/CCBoneNode.cpp index b812c36371..de7d55ca31 100644 --- a/extensions/cocostudio/ActionTimeline/CCBoneNode.cpp +++ b/extensions/cocostudio/ActionTimeline/CCBoneNode.cpp @@ -75,20 +75,20 @@ bool BoneNode::init() setProgramState(new cocos2d::backend::ProgramState(program), false); pipelineDescriptor.programState = _programState; - _mvpLocation = _programState->getUniformLocation("u_MVPMatrix"sv); + _mvpLocation = _programState->getUniformLocation("u_MVPMatrix"); auto vertexLayout = _programState->getVertexLayout(); const auto& attributeInfo = _programState->getProgram()->getActiveAttributes(); - auto iter = attributeInfo.find("a_position"sv); + auto iter = attributeInfo.find("a_position"); if (iter != attributeInfo.end()) { - vertexLayout->setAttribute("a_position"sv, iter->second.location, cocos2d::backend::VertexFormat::FLOAT3, 0, + vertexLayout->setAttribute("a_position", iter->second.location, cocos2d::backend::VertexFormat::FLOAT3, 0, false); } - iter = attributeInfo.find("a_color"sv); + iter = attributeInfo.find("a_color"); if (iter != attributeInfo.end()) { - vertexLayout->setAttribute("a_color"sv, iter->second.location, cocos2d::backend::VertexFormat::FLOAT4, + vertexLayout->setAttribute("a_color", iter->second.location, cocos2d::backend::VertexFormat::FLOAT4, 3 * sizeof(float), false); } vertexLayout->setLayout(7 * sizeof(float)); @@ -108,7 +108,7 @@ void BoneNode::addChild(cocos2d::Node* child, int localZOrder, int tag) Node::addChild(child, localZOrder, tag); } -void BoneNode::addChild(Node* child, int localZOrder, std::string_view name) +void BoneNode::addChild(Node* child, int localZOrder, const std::string& name) { addToChildrenListHelper(child); Node::addChild(child, localZOrder, name); @@ -152,7 +152,7 @@ void BoneNode::removeFromBoneList(BoneNode* bone) { auto subBones = bone->getAllSubBones(); subBones.pushBack(bone); - for (auto subBone : subBones) + for (auto& subBone : subBones) { if (subBone->_rootSkeleton == nullptr) continue; @@ -186,7 +186,7 @@ void BoneNode::addToBoneList(BoneNode* bone) { auto subBones = bone->getAllSubBones(); subBones.pushBack(bone); - for (auto subBone : subBones) + for (auto& subBone : subBones) { subBone->_rootSkeleton = _rootSkeleton; auto bonename = subBone->getName(); @@ -198,8 +198,8 @@ void BoneNode::addToBoneList(BoneNode* bone) _rootSkeleton->_subBonesOrderDirty = true; } else - CCLOG("already has a bone named %s in skeleton %s", bonename.data(), - _rootSkeleton->getName().data()); + CCLOG("already has a bone named %s in skeleton %s", bonename.c_str(), + _rootSkeleton->getName().c_str()); } } else @@ -240,7 +240,7 @@ void BoneNode::displaySkin(SkinNode* skin, bool hideOthers) } } -void BoneNode::displaySkin(std::string_view skinName, bool hideOthers) +void BoneNode::displaySkin(const std::string& skinName, bool hideOthers) { for (auto& skin : _boneSkins) { @@ -661,7 +661,7 @@ void BoneNode::setLocalZOrder(int localZOrder) _rootSkeleton->_subBonesOrderDirty = true; } -void BoneNode::setName(std::string_view name) +void BoneNode::setName(const std::string& name) { auto oldname = getName(); Node::setName(name); diff --git a/extensions/cocostudio/ActionTimeline/CCBoneNode.h b/extensions/cocostudio/ActionTimeline/CCBoneNode.h index 60450caa79..02003d3ce7 100644 --- a/extensions/cocostudio/ActionTimeline/CCBoneNode.h +++ b/extensions/cocostudio/ActionTimeline/CCBoneNode.h @@ -52,7 +52,7 @@ public: using Node::addChild; // add child, and add child to bone list and skeleton's sub bone map or add it to skin list - virtual void addChild(cocos2d::Node* child, int localZOrder, std::string_view name) override; + virtual void addChild(cocos2d::Node* child, int localZOrder, const std::string& name) override; virtual void addChild(cocos2d::Node* child, int localZOrder, int tag) override; // remove child, and remove child from bone list and skeleton's sub bone map or remove it from skin list @@ -94,7 +94,7 @@ public: * prefer to use display(SkinNode* skin, bool hideOthers = false) * @param: hideOthers, set other skins invisible */ - virtual void displaySkin(std::string_view skinName, bool hideOthers); + virtual void displaySkin(const std::string& skinName, bool hideOthers); // get the skins which is visible (displaying skins) virtual cocos2d::Vector getVisibleSkins() const; @@ -146,7 +146,7 @@ public: virtual void setLocalZOrder(int localZOrder) override; // set name, and replace the subbone map in skeleton - virtual void setName(std::string_view name) override; + virtual void setName(const std::string& name) override; // set visible, and dirty the debugdraw to make debugdraw's render layer right virtual void setVisible(bool visible) override; diff --git a/extensions/cocostudio/ActionTimeline/CCFrame.cpp b/extensions/cocostudio/ActionTimeline/CCFrame.cpp index fff31a344d..2b410c5f27 100644 --- a/extensions/cocostudio/ActionTimeline/CCFrame.cpp +++ b/extensions/cocostudio/ActionTimeline/CCFrame.cpp @@ -548,7 +548,7 @@ void InnerActionFrame::setEndFrameIndex(int frameIndex) _endFrameIndex = frameIndex; } -void InnerActionFrame::setAnimationName(std::string_view animationName) +void InnerActionFrame::setAnimationName(const std::string& animationName) { if (!_enterWithName) { diff --git a/extensions/cocostudio/ActionTimeline/CCFrame.h b/extensions/cocostudio/ActionTimeline/CCFrame.h index 715972ca55..f9c0ccd37c 100644 --- a/extensions/cocostudio/ActionTimeline/CCFrame.h +++ b/extensions/cocostudio/ActionTimeline/CCFrame.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org @@ -119,8 +119,8 @@ public: virtual void onEnter(Frame* nextFrame, int currentFrameIndex) override; virtual Frame* clone() override; - inline void setTextureName(std::string_view textureName) { _textureName = textureName; } - inline std::string_view getTextureName() const { return _textureName; } + inline void setTextureName(std::string textureName) { _textureName = textureName; } + inline std::string getTextureName() const { return _textureName; } protected: cocos2d::Sprite* _sprite; @@ -293,7 +293,7 @@ public: void setEndFrameIndex(int frameIndex); inline int getEndFrameIndex() const { return _endFrameIndex; } - void setAnimationName(std::string_view animationNamed); + void setAnimationName(const std::string& animationNamed); inline void setSingleFrameIndex(int frameIndex) { _singleFrameIndex = frameIndex; } inline int getSingleFrameIndex() const { return _singleFrameIndex; } @@ -366,8 +366,8 @@ public: virtual void onEnter(Frame* nextFrame, int currentFrameIndex) override; virtual Frame* clone() override; - inline void setEvent(std::string_view event) { _event = event; } - inline std::string_view getEvent() const { return _event; } + inline void setEvent(std::string event) { _event = event; } + inline std::string getEvent() const { return _event; } protected: std::string _event; diff --git a/extensions/cocostudio/ActionTimeline/CCSkeletonNode.cpp b/extensions/cocostudio/ActionTimeline/CCSkeletonNode.cpp index d0a0749415..69417e6a47 100644 --- a/extensions/cocostudio/ActionTimeline/CCSkeletonNode.cpp +++ b/extensions/cocostudio/ActionTimeline/CCSkeletonNode.cpp @@ -298,7 +298,7 @@ void SkeletonNode::batchDrawAllSubBones() #endif // CC_STUDIO_ENABLED_VIEW } -void SkeletonNode::changeSkins(const hlookup::string_map& boneSkinNameMap) +void SkeletonNode::changeSkins(const std::map& boneSkinNameMap) { for (auto& boneskin : boneSkinNameMap) { @@ -308,7 +308,7 @@ void SkeletonNode::changeSkins(const hlookup::string_map& boneSkinN } } -void SkeletonNode::changeSkins(std::string_view skinGroupName) +void SkeletonNode::changeSkins(const std::string& skinGroupName) { auto suit = _skinGroupMap.find(skinGroupName); if (suit != _skinGroupMap.end()) @@ -317,7 +317,7 @@ void SkeletonNode::changeSkins(std::string_view skinGroupName) } } -BoneNode* SkeletonNode::getBoneNode(std::string_view boneName) +BoneNode* SkeletonNode::getBoneNode(const std::string& boneName) { auto iter = _subBonesMap.find(boneName); if (iter != _subBonesMap.end()) @@ -327,14 +327,14 @@ BoneNode* SkeletonNode::getBoneNode(std::string_view boneName) return nullptr; } -const cocos2d::StringMap& SkeletonNode::getAllSubBonesMap() const +const cocos2d::Map& SkeletonNode::getAllSubBonesMap() const { return _subBonesMap; } -void SkeletonNode::addSkinGroup(std::string groupName, hlookup::string_map boneSkinNameMap) +void SkeletonNode::addSkinGroup(std::string groupName, std::map boneSkinNameMap) { - _skinGroupMap.emplace(groupName, std::move(boneSkinNameMap)); + _skinGroupMap.emplace(groupName, boneSkinNameMap); } void SkeletonNode::checkSubBonesDirty() diff --git a/extensions/cocostudio/ActionTimeline/CCSkeletonNode.h b/extensions/cocostudio/ActionTimeline/CCSkeletonNode.h index 7e004a3938..e6117bdcb9 100644 --- a/extensions/cocostudio/ActionTimeline/CCSkeletonNode.h +++ b/extensions/cocostudio/ActionTimeline/CCSkeletonNode.h @@ -44,31 +44,31 @@ public: /** *get bonenode in skeleton node by bone name */ - BoneNode* getBoneNode(std::string_view boneName); + BoneNode* getBoneNode(const std::string& boneName); /** *get All bones in this skeleton, */ - const cocos2d::StringMap& getAllSubBonesMap() const; + const cocos2d::Map& getAllSubBonesMap() const; /** *@brief: change displays *@param: boneSkinNameMap, map */ - void changeSkins(const hlookup::string_map& boneSkinNameMap); + void changeSkins(const std::map& boneSkinNameMap); /** *@brief: change displays *@param: skinGroupName have */ - void changeSkins(std::string_view skinGroupName); + void changeSkins(const std::string& skinGroupName); /** *@brief: add a boneSkinNameMap as a SkinGroup named groupName *@param: groupName, key *@param: boneSkinNameMap, map */ - void addSkinGroup(std::string groupName, hlookup::string_map boneSkinNameMap); + void addSkinGroup(std::string groupName, std::map boneSkinNameMap); cocos2d::Rect getBoundingBox() const override; @@ -86,7 +86,7 @@ protected: virtual void draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, uint32_t flags) override; protected: - cocos2d::StringMap _subBonesMap; + cocos2d::Map _subBonesMap; private: struct VertexData @@ -98,7 +98,7 @@ private: cocos2d::Vec2 _squareVertices[8]; VertexData _vertexData[8]; - hlookup::string_map> + std::map> _skinGroupMap; // map< suit name, map< bone name, skin name> > CC_DISALLOW_COPY_AND_ASSIGN(SkeletonNode); diff --git a/extensions/cocostudio/ActionTimeline/CSLoader.cpp b/extensions/cocostudio/ActionTimeline/CSLoader.cpp index d414f5b7ea..fcb10cc04e 100644 --- a/extensions/cocostudio/ActionTimeline/CSLoader.cpp +++ b/extensions/cocostudio/ActionTimeline/CSLoader.cpp @@ -280,11 +280,11 @@ void CSLoader::init() _componentFuncs.insert(ComponentPair(ClassName_ComAudio, std::bind(&CSLoader::loadComAudio, this, _1))); } -Node* CSLoader::createNode(std::string_view filename) +Node* CSLoader::createNode(const std::string& filename) { - auto path = filename; - size_t pos = path.find_last_of('.'); - auto suffix = path.substr(pos + 1, path.length()); + std::string path = filename; + size_t pos = path.find_last_of('.'); + std::string suffix = path.substr(pos + 1, path.length()); CSLoader* load = CSLoader::getInstance(); @@ -300,11 +300,11 @@ Node* CSLoader::createNode(std::string_view filename) return nullptr; } -Node* CSLoader::createNode(std::string_view filename, const ccNodeLoadCallback& callback) +Node* CSLoader::createNode(const std::string& filename, const ccNodeLoadCallback& callback) { - auto path = filename; - size_t pos = path.find_last_of('.'); - auto suffix = path.substr(pos + 1, path.length()); + std::string path = filename; + size_t pos = path.find_last_of('.'); + std::string suffix = path.substr(pos + 1, path.length()); CSLoader* load = CSLoader::getInstance(); @@ -316,7 +316,7 @@ Node* CSLoader::createNode(std::string_view filename, const ccNodeLoadCallback& return nullptr; } -Node* CSLoader::createNodeWithVisibleSize(std::string_view filename) +Node* CSLoader::createNodeWithVisibleSize(const std::string& filename) { auto node = createNode(filename); if (node != nullptr) @@ -328,7 +328,7 @@ Node* CSLoader::createNodeWithVisibleSize(std::string_view filename) return node; } -Node* CSLoader::createNodeWithVisibleSize(std::string_view filename, const ccNodeLoadCallback& callback) +Node* CSLoader::createNodeWithVisibleSize(const std::string& filename, const ccNodeLoadCallback& callback) { auto node = createNode(filename, callback); if (node != nullptr) @@ -340,18 +340,18 @@ Node* CSLoader::createNodeWithVisibleSize(std::string_view filename, const ccNod return node; } -std::string_view CSLoader::getExtentionName(std::string_view name) +std::string CSLoader::getExtentionName(const std::string& name) { - auto path = name; - size_t pos = path.find_last_of('.'); - auto result = path.substr(pos + 1, path.length()); + std::string path = name; + size_t pos = path.find_last_of('.'); + std::string result = path.substr(pos + 1, path.length()); return result; } -ActionTimeline* CSLoader::createTimeline(std::string_view filename) +ActionTimeline* CSLoader::createTimeline(const std::string& filename) { - auto suffix = getExtentionName(filename); + std::string suffix = getExtentionName(filename); ActionTimelineCache* cache = ActionTimelineCache::getInstance(); @@ -367,9 +367,9 @@ ActionTimeline* CSLoader::createTimeline(std::string_view filename) return nullptr; } -ActionTimeline* CSLoader::createTimeline(const Data& data, std::string_view filename) +ActionTimeline* CSLoader::createTimeline(const Data& data, const std::string& filename) { - auto suffix = getExtentionName(filename); + std::string suffix = getExtentionName(filename); ActionTimelineCache* cache = ActionTimelineCache::getInstance(); @@ -379,7 +379,7 @@ ActionTimeline* CSLoader::createTimeline(const Data& data, std::string_view file } else if (suffix == "json" || suffix == "ExportJson") { - std::string_view content((char*)data.getBytes(), data.getSize()); + std::string content((char*)data.getBytes(), data.getSize()); return cache->createActionFromContent(filename, content); } @@ -387,7 +387,7 @@ ActionTimeline* CSLoader::createTimeline(const Data& data, std::string_view file } /* -ActionTimelineNode* CSLoader::createActionTimelineNode(std::string_view filename) +ActionTimelineNode* CSLoader::createActionTimelineNode(const std::string& filename) { Node* root = createNode(filename); ActionTimeline* action = createTimeline(filename); @@ -401,7 +401,7 @@ ActionTimelineNode* CSLoader::createActionTimelineNode(std::string_view filename ActionTimelineNode* node = ActionTimelineNode::create(root, action); return node; } -ActionTimelineNode* CSLoader::createActionTimelineNode(std::string_view filename, int startIndex, int endIndex, bool +ActionTimelineNode* CSLoader::createActionTimelineNode(const std::string& filename, int startIndex, int endIndex, bool loop) { ActionTimelineNode* node = createActionTimelineNode(filename); @@ -413,11 +413,11 @@ loop) } */ -Node* CSLoader::createNodeFromJson(std::string_view filename) +Node* CSLoader::createNodeFromJson(const std::string& filename) { if (_recordJsonPath) { - auto jsonPath = filename.substr(0, filename.find_last_of('/') + 1); + std::string jsonPath = filename.substr(0, filename.find_last_of('/') + 1); GUIReader::getInstance()->setFilePath(jsonPath); _jsonPath = jsonPath; @@ -432,7 +432,7 @@ Node* CSLoader::createNodeFromJson(std::string_view filename) return node; } -Node* CSLoader::loadNodeWithFile(std::string_view fileName) +Node* CSLoader::loadNodeWithFile(const std::string& fileName) { // Read content from file std::string contentStr = FileUtils::getInstance()->getStringFromFile(fileName); @@ -445,10 +445,10 @@ Node* CSLoader::loadNodeWithFile(std::string_view fileName) return node; } -Node* CSLoader::loadNodeWithContent(std::string_view content) +Node* CSLoader::loadNodeWithContent(const std::string& content) { rapidjson::Document doc; - doc.Parse<0>(content.data(), content.length()); + doc.Parse<0>(content.c_str()); if (doc.HasParseError()) { CCLOG("GetParseError %d\n", doc.GetParseError()); @@ -760,11 +760,11 @@ Node* CSLoader::loadWidget(const rapidjson::Value& json) if (isWidget(classname)) { - std::string readerName{getGUIClassName(classname)}; + std::string readerName = getGUIClassName(classname); readerName.append("Reader"); - std::string_view guiClassName = getGUIClassName(classname); - widget = dynamic_cast(ObjectFactory::getInstance()->createObject(guiClassName)); + std::string guiClassName = getGUIClassName(classname); + widget = dynamic_cast(ObjectFactory::getInstance()->createObject(guiClassName)); // fix memory leak for v3.3 // widget->retain(); @@ -785,7 +785,7 @@ Node* CSLoader::loadWidget(const rapidjson::Value& json) // // 1st., custom widget parse properties of parent widget with parent widget reader - std::string_view readerName = getWidgetReaderClassName(widget); + std::string readerName = getWidgetReaderClassName(widget); WidgetReaderProtocol* reader = dynamic_cast(ObjectFactory::getInstance()->createObject(readerName)); if (reader && widget) @@ -961,12 +961,12 @@ Node* CSLoader::createNode(const Data& data, const ccNodeLoadCallback& callback) return node; } -Node* CSLoader::createNodeWithFlatBuffersFile(std::string_view filename) +Node* CSLoader::createNodeWithFlatBuffersFile(const std::string& filename) { return createNodeWithFlatBuffersFile(filename, nullptr); } -Node* CSLoader::createNodeWithFlatBuffersFile(std::string_view filename, const ccNodeLoadCallback& callback) +Node* CSLoader::createNodeWithFlatBuffersFile(const std::string& filename, const ccNodeLoadCallback& callback) { Node* node = nodeWithFlatBuffersFile(filename, callback); @@ -990,17 +990,17 @@ inline void CSLoader::reconstructNestNode(cocos2d::Node* node) else { _rootNode = _callbackHandlers.back(); - CCLOG("after pop back _rootNode name = %s", _rootNode->getName().data()); + CCLOG("after pop back _rootNode name = %s", _rootNode->getName().c_str()); } } } -Node* CSLoader::nodeWithFlatBuffersFile(std::string_view fileName) +Node* CSLoader::nodeWithFlatBuffersFile(const std::string& fileName) { return nodeWithFlatBuffersFile(fileName, nullptr); } -Node* CSLoader::nodeWithFlatBuffersFile(std::string_view fileName, const ccNodeLoadCallback& callback) +Node* CSLoader::nodeWithFlatBuffersFile(const std::string& fileName, const ccNodeLoadCallback& callback) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName); @@ -1010,7 +1010,7 @@ Node* CSLoader::nodeWithFlatBuffersFile(std::string_view fileName, const ccNodeL if (buf.isNull()) { - CCLOG("CSLoader::nodeWithFlatBuffersFile - failed read file: %s", fileName.data()); + CCLOG("CSLoader::nodeWithFlatBuffersFile - failed read file: %s", fileName.c_str()); CC_ASSERT(false); return nullptr; } @@ -1144,7 +1144,7 @@ Node* CSLoader::nodeWithFlatBuffers(const flatbuffers::NodeTree* nodetree, const { classname = customClassName; } - std::string readername{getGUIClassName(classname)}; + std::string readername = getGUIClassName(classname); readername.append("Reader"); NodeReaderProtocol* reader = @@ -1178,8 +1178,8 @@ Node* CSLoader::nodeWithFlatBuffers(const flatbuffers::NodeTree* nodetree, const Widget* widget = dynamic_cast(node); if (widget) { - auto callbackName = widget->getCallbackName(); - auto callbackType = widget->getCallbackType(); + std::string callbackName = widget->getCallbackName(); + std::string callbackType = widget->getCallbackType(); bindCallback(callbackName, callbackType, widget, _rootNode); } @@ -1248,8 +1248,8 @@ Node* CSLoader::nodeWithFlatBuffers(const flatbuffers::NodeTree* nodetree, const } } -bool CSLoader::bindCallback(std::string_view callbackName, - std::string_view callbackType, +bool CSLoader::bindCallback(const std::string& callbackName, + const std::string& callbackType, cocos2d::ui::Widget* sender, cocos2d::Node* handler) { @@ -1288,12 +1288,12 @@ bool CSLoader::bindCallback(std::string_view callbackName, } } - CCLOG("callBackName %s cannot be found", callbackName.data()); + CCLOG("callBackName %s cannot be found", callbackName.c_str()); return false; } -bool CSLoader::isWidget(std::string_view type) +bool CSLoader::isWidget(const std::string& type) { return (type == ClassName_Panel || type == ClassName_Button || type == ClassName_CheckBox || type == ClassName_ImageView || type == ClassName_TextAtlas || type == ClassName_LabelAtlas || @@ -1303,7 +1303,7 @@ bool CSLoader::isWidget(std::string_view type) type == ClassName_PageView || type == ClassName_Widget || type == ClassName_Label); } -bool CSLoader::isCustomWidget(std::string_view type) +bool CSLoader::isCustomWidget(const std::string& type) { Widget* widget = dynamic_cast(ObjectFactory::getInstance()->createObject(type)); if (widget) @@ -1315,42 +1315,40 @@ bool CSLoader::isCustomWidget(std::string_view type) return false; } -std::string_view CSLoader::getGUIClassName(std::string_view name) +std::string CSLoader::getGUIClassName(const std::string& name) { - std::string_view convertedClassName; + std::string convertedClassName = name; if (name == "Panel") { - convertedClassName = "Layout"sv; + convertedClassName = "Layout"; } else if (name == "TextArea") { - convertedClassName = "Text"sv; + convertedClassName = "Text"; } else if (name == "TextButton") { - convertedClassName = "Button"sv; + convertedClassName = "Button"; } else if (name == "Label") { - convertedClassName = "Text"sv; + convertedClassName = "Text"; } else if (name == "LabelAtlas") { - convertedClassName = "TextAtlas"sv; + convertedClassName = "TextAtlas"; } else if (name == "LabelBMFont") { - convertedClassName = "TextBMFont"sv; + convertedClassName = "TextBMFont"; } - else - convertedClassName = name; return convertedClassName; } -std::string_view CSLoader::getWidgetReaderClassName(Widget* widget) +std::string CSLoader::getWidgetReaderClassName(Widget* widget) { - std::string_view readerName; + std::string readerName; // 1st., custom widget parse properties of parent widget with parent widget reader if (dynamic_cast(widget)) @@ -1410,13 +1408,11 @@ std::string_view CSLoader::getWidgetReaderClassName(Widget* widget) { readerName = "WidgetReader"; } - else - readerName = hlookup::empty_sv; return readerName; } -void CSLoader::registReaderObject(std::string_view className, ObjectFactory::Instance ins) +void CSLoader::registReaderObject(const std::string& className, ObjectFactory::Instance ins) { ObjectFactory::TInfo t; t._class = className; @@ -1425,7 +1421,7 @@ void CSLoader::registReaderObject(std::string_view className, ObjectFactory::Ins ObjectFactory::getInstance()->registerType(t); } -Node* CSLoader::createNodeWithFlatBuffersForSimulator(std::string_view filename) +Node* CSLoader::createNodeWithFlatBuffersForSimulator(const std::string& filename) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); fbs->_isSimulator = true; @@ -1499,7 +1495,7 @@ Node* CSLoader::nodeWithFlatBuffersForSimulator(const flatbuffers::NodeTree* nod } else { - std::string readername{getGUIClassName(classname)}; + std::string readername = getGUIClassName(classname); readername.append("Reader"); NodeReaderProtocol* reader = @@ -1512,8 +1508,8 @@ Node* CSLoader::nodeWithFlatBuffersForSimulator(const flatbuffers::NodeTree* nod Widget* widget = dynamic_cast(node); if (widget) { - auto callbackName = widget->getCallbackName(); - auto callbackType = widget->getCallbackType(); + std::string callbackName = widget->getCallbackName(); + std::string callbackType = widget->getCallbackType(); bindCallback(callbackName, callbackType, widget, _rootNode); } diff --git a/extensions/cocostudio/ActionTimeline/CSLoader.h b/extensions/cocostudio/ActionTimeline/CSLoader.h index 3ba1e7fedc..afcd41f583 100644 --- a/extensions/cocostudio/ActionTimeline/CSLoader.h +++ b/extensions/cocostudio/ActionTimeline/CSLoader.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org @@ -79,25 +79,25 @@ public: void init(); - static cocos2d::Node* createNode(std::string_view filename); - static cocos2d::Node* createNode(std::string_view filename, const ccNodeLoadCallback& callback); + static cocos2d::Node* createNode(const std::string& filename); + static cocos2d::Node* createNode(const std::string& filename, const ccNodeLoadCallback& callback); static cocos2d::Node* createNode(const Data& data); static cocos2d::Node* createNode(const Data& data, const ccNodeLoadCallback& callback); - static cocos2d::Node* createNodeWithVisibleSize(std::string_view filename); - static cocos2d::Node* createNodeWithVisibleSize(std::string_view filename, const ccNodeLoadCallback& callback); + static cocos2d::Node* createNodeWithVisibleSize(const std::string& filename); + static cocos2d::Node* createNodeWithVisibleSize(const std::string& filename, const ccNodeLoadCallback& callback); - static cocostudio::timeline::ActionTimeline* createTimeline(std::string_view filename); - static cocostudio::timeline::ActionTimeline* createTimeline(const Data& data, std::string_view filename); + static cocostudio::timeline::ActionTimeline* createTimeline(const std::string& filename); + static cocostudio::timeline::ActionTimeline* createTimeline(const Data& data, const std::string& filename); /* - static cocostudio::timeline::ActionTimelineNode* createActionTimelineNode(std::string_view filename); - static cocostudio::timeline::ActionTimelineNode* createActionTimelineNode(std::string_view filename, int + static cocostudio::timeline::ActionTimelineNode* createActionTimelineNode(const std::string& filename); + static cocostudio::timeline::ActionTimelineNode* createActionTimelineNode(const std::string& filename, int startIndex, int endIndex, bool loop); */ - cocos2d::Node* createNodeFromJson(std::string_view filename); - cocos2d::Node* loadNodeWithFile(std::string_view fileName); - cocos2d::Node* loadNodeWithContent(std::string_view content); + cocos2d::Node* createNodeFromJson(const std::string& filename); + cocos2d::Node* loadNodeWithFile(const std::string& fileName); + cocos2d::Node* loadNodeWithContent(const std::string& content); void setRecordJsonPath(bool record) { _recordJsonPath = record; } bool isRecordJsonPath() const { return _recordJsonPath; } @@ -105,23 +105,23 @@ public: void setJsonPath(std::string jsonPath) { _jsonPath = jsonPath; } std::string getJsonPath() const { return _jsonPath; } - cocos2d::Node* createNodeWithFlatBuffersFile(std::string_view filename); - cocos2d::Node* nodeWithFlatBuffersFile(std::string_view fileName); + cocos2d::Node* createNodeWithFlatBuffersFile(const std::string& filename); + cocos2d::Node* nodeWithFlatBuffersFile(const std::string& fileName); cocos2d::Node* nodeWithFlatBuffers(const flatbuffers::NodeTree* nodetree); - bool bindCallback(std::string_view callbackName, - std::string_view callbackType, + bool bindCallback(const std::string& callbackName, + const std::string& callbackType, cocos2d::ui::Widget* sender, cocos2d::Node* handler); - void registReaderObject(std::string_view className, ObjectFactory::Instance ins); + void registReaderObject(const std::string& className, ObjectFactory::Instance ins); - cocos2d::Node* createNodeWithFlatBuffersForSimulator(std::string_view filename); + cocos2d::Node* createNodeWithFlatBuffersForSimulator(const std::string& filename); cocos2d::Node* nodeWithFlatBuffersForSimulator(const flatbuffers::NodeTree* nodetree); protected: - cocos2d::Node* createNodeWithFlatBuffersFile(std::string_view filename, const ccNodeLoadCallback& callback); - cocos2d::Node* nodeWithFlatBuffersFile(std::string_view fileName, const ccNodeLoadCallback& callback); + cocos2d::Node* createNodeWithFlatBuffersFile(const std::string& filename, const ccNodeLoadCallback& callback); + cocos2d::Node* nodeWithFlatBuffersFile(const std::string& fileName, const ccNodeLoadCallback& callback); cocos2d::Node* nodeWithFlatBuffers(const flatbuffers::NodeTree* nodetree, const ccNodeLoadCallback& callback); cocos2d::Node* loadNode(const rapidjson::Value& json); @@ -144,14 +144,14 @@ protected: cocos2d::Component* loadComponent(const rapidjson::Value& json); cocos2d::Component* loadComAudio(const rapidjson::Value& json); - bool isWidget(std::string_view type); - bool isCustomWidget(std::string_view type); + bool isWidget(const std::string& type); + bool isCustomWidget(const std::string& type); - std::string_view getGUIClassName(std::string_view name); - std::string_view getWidgetReaderClassName(cocos2d::ui::Widget* widget); + std::string getGUIClassName(const std::string& name); + std::string getWidgetReaderClassName(cocos2d::ui::Widget* widget); inline void reconstructNestNode(cocos2d::Node* node); - static inline std::string_view getExtentionName(std::string_view name); + static inline std::string getExtentionName(const std::string& name); typedef std::function NodeCreateFunc; typedef std::pair Pair; diff --git a/extensions/cocostudio/CCActionNode.cpp b/extensions/cocostudio/CCActionNode.cpp index b514296e3e..88ffc8b5ed 100644 --- a/extensions/cocostudio/CCActionNode.cpp +++ b/extensions/cocostudio/CCActionNode.cpp @@ -188,11 +188,11 @@ void ActionNode::initWithDictionary(const rapidjson::Value& dic, Ref* root) initActionNodeFromRoot(root); } -int ActionNode::valueToInt(std::string_view value) +int ActionNode::valueToInt(const std::string& value) { - return atoi(value.data()); + return atoi(value.c_str()); } -bool ActionNode::valueToBool(std::string_view value) +bool ActionNode::valueToBool(const std::string& value) { int intValue = valueToInt(value); if (1 == intValue) @@ -204,9 +204,9 @@ bool ActionNode::valueToBool(std::string_view value) return false; } } -float ActionNode::valueToFloat(std::string_view value) +float ActionNode::valueToFloat(const std::string& value) { - return utils::atof(value.data()); + return utils::atof(value.c_str()); } void ActionNode::initWithBinary(CocoLoader* cocoLoader, stExpCocoNode* cocoNode, cocos2d::Ref* root) @@ -494,9 +494,8 @@ Spawn* ActionNode::refreshActionProperty() // #11173 Fixed every node of UI animation(json) is starting at frame 0. // if (frame->getFrameIndex() > 0) // { - // DelayTime* cDelayTime = - // DelayTime::create(frame->getFrameIndex() - //* getUnitTime()); if (cDelayTime != nullptr) + // DelayTime* cDelayTime = DelayTime::create(frame->getFrameIndex() * + //getUnitTime()); if (cDelayTime != nullptr) // cSequenceArray.pushBack(static_cast(cDelayTime)); // } } diff --git a/extensions/cocostudio/CCActionNode.h b/extensions/cocostudio/CCActionNode.h index ec1a6554c7..17c29ba996 100644 --- a/extensions/cocostudio/CCActionNode.h +++ b/extensions/cocostudio/CCActionNode.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -162,9 +162,9 @@ public: virtual bool isActionDoneOnce(); protected: - int valueToInt(std::string_view value); - bool valueToBool(std::string_view value); - float valueToFloat(std::string_view value); + int valueToInt(const std::string& value); + bool valueToBool(const std::string& value); + float valueToFloat(const std::string& value); int _currentFrameIndex; int _destFrameIndex; diff --git a/extensions/cocostudio/CCActionObject.cpp b/extensions/cocostudio/CCActionObject.cpp index 48c85bac15..badd9c4852 100644 --- a/extensions/cocostudio/CCActionObject.cpp +++ b/extensions/cocostudio/CCActionObject.cpp @@ -184,11 +184,11 @@ void ActionObject::initWithBinary(CocoLoader* cocoLoader, stExpCocoNode* cocoNod } } -int ActionObject::valueToInt(std::string_view value) +int ActionObject::valueToInt(const std::string& value) { - return atoi(value.data()); + return atoi(value.c_str()); } -bool ActionObject::valueToBool(std::string_view value) +bool ActionObject::valueToBool(const std::string& value) { int intValue = valueToInt(value); if (1 == intValue) @@ -200,9 +200,9 @@ bool ActionObject::valueToBool(std::string_view value) return false; } } -float ActionObject::valueToFloat(std::string_view value) +float ActionObject::valueToFloat(const std::string& value) { - return utils::atof(value.data()); + return utils::atof(value.c_str()); } void ActionObject::addActionNode(ActionNode* node) diff --git a/extensions/cocostudio/CCActionObject.h b/extensions/cocostudio/CCActionObject.h index b151631ed4..195c741d5b 100644 --- a/extensions/cocostudio/CCActionObject.h +++ b/extensions/cocostudio/CCActionObject.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -171,9 +171,9 @@ public: void simulationActionUpdate(float dt); protected: - int valueToInt(std::string_view value); - bool valueToBool(std::string_view value); - float valueToFloat(std::string_view value); + int valueToInt(const std::string& value); + bool valueToBool(const std::string& value); + float valueToFloat(const std::string& value); cocos2d::Vector _actionNodeList; std::string _name; diff --git a/extensions/cocostudio/CCArmature.cpp b/extensions/cocostudio/CCArmature.cpp index ab518eda85..985d3aec43 100644 --- a/extensions/cocostudio/CCArmature.cpp +++ b/extensions/cocostudio/CCArmature.cpp @@ -57,7 +57,7 @@ Armature* Armature::create() return nullptr; } -Armature* Armature::create(std::string_view name) +Armature* Armature::create(const std::string& name) { Armature* armature = new Armature(); if (armature->init(name)) @@ -69,7 +69,7 @@ Armature* Armature::create(std::string_view name) return nullptr; } -Armature* Armature::create(std::string_view name, Bone* parentBone) +Armature* Armature::create(const std::string& name, Bone* parentBone) { Armature* armature = new Armature(); if (armature->init(name, parentBone)) @@ -102,7 +102,7 @@ bool Armature::init() return init(""); } -bool Armature::init(std::string_view name) +bool Armature::init(const std::string& name) { bool bRet = false; do @@ -182,13 +182,13 @@ bool Armature::init(std::string_view name) return bRet; } -bool Armature::init(std::string_view name, Bone* parentBone) +bool Armature::init(const std::string& name, Bone* parentBone) { _parentBone = parentBone; return init(name); } -Bone* Armature::createBone(std::string_view boneName) +Bone* Armature::createBone(const std::string& boneName) { Bone* existedBone = getBone(boneName); if (existedBone != nullptr) @@ -217,7 +217,7 @@ Bone* Armature::createBone(std::string_view boneName) return bone; } -void Armature::addBone(Bone* bone, std::string_view parentName) +void Armature::addBone(Bone* bone, const std::string& parentName) { CCASSERT(bone != nullptr, "Argument must be non-nil"); CCASSERT(_boneDic.at(bone->getName()) == nullptr, "bone already added. It can't be added again"); @@ -260,12 +260,12 @@ void Armature::removeBone(Bone* bone, bool recursion) removeChild(bone, true); } -Bone* Armature::getBone(std::string_view name) const +Bone* Armature::getBone(const std::string& name) const { return _boneDic.at(name); } -void Armature::changeBoneParent(Bone* bone, std::string_view parentName) +void Armature::changeBoneParent(Bone* bone, const std::string& parentName) { CCASSERT(bone != nullptr, "bone must be added to the bone dictionary!"); @@ -294,7 +294,7 @@ void Armature::changeBoneParent(Bone* bone, std::string_view parentName) } } -const cocos2d::StringMap& Armature::getBoneDic() const +const cocos2d::Map& Armature::getBoneDic() const { return _boneDic; } diff --git a/extensions/cocostudio/CCArmature.h b/extensions/cocostudio/CCArmature.h index 66866ed2a8..d207940d85 100644 --- a/extensions/cocostudio/CCArmature.h +++ b/extensions/cocostudio/CCArmature.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -85,9 +85,9 @@ public: * @param name Armature will use the name to find the ArmatureData to initializes it. * @return A initialized armature which is marked as "autorelease". */ - static Armature* create(std::string_view name); + static Armature* create(const std::string& name); - static Armature* create(std::string_view name, Bone* parentBone); + static Armature* create(const std::string& name, Bone* parentBone); public: /** @@ -109,29 +109,29 @@ public: * Init an armature with specified name * @param name Armature name */ - virtual bool init(std::string_view name); + virtual bool init(const std::string& name); - virtual bool init(std::string_view name, Bone* parentBone); + virtual bool init(const std::string& name, Bone* parentBone); /** * Add a Bone to this Armature, * * @param bone The Bone you want to add to Armature * @param parentName The parent Bone's name you want to add to . If it's nullptr, then set Armature to its parent */ - virtual void addBone(Bone* bone, std::string_view parentName); + virtual void addBone(Bone* bone, const std::string& parentName); /** * Get a bone with the specified name * * @param name The bone's name you want to get */ - virtual Bone* getBone(std::string_view name) const; + virtual Bone* getBone(const std::string& name) const; /** * Change a bone's parent with the specified parent name. * * @param bone The bone you want to change parent * @param parentName The new parent's name. */ - virtual void changeBoneParent(Bone* bone, std::string_view parentName); + virtual void changeBoneParent(Bone* bone, const std::string& parentName); /** * Remove a bone with the specified name. If recursion it will also remove child Bone recursionly. * @@ -144,7 +144,7 @@ public: * Get Armature's bone dictionary * @return Armature's bone dictionary */ - const cocos2d::StringMap& getBoneDic() const; + const cocos2d::Map& getBoneDic() const; /** * This boundingBox will calculate all bones' boundingBox every time @@ -246,7 +246,7 @@ protected: * @js NA * @lua NA */ - Bone* createBone(std::string_view boneName); + Bone* createBone(const std::string& boneName); protected: ArmatureData* _armatureData; @@ -258,7 +258,7 @@ protected: mutable bool _armatureTransformDirty; - cocos2d::StringMap + cocos2d::Map _boneDic; //! The dictionary of the bones, include all bones in the armature, no matter it is the direct bone //! or the indirect bone. It is different from m_pChindren. diff --git a/extensions/cocostudio/CCArmatureAnimation.cpp b/extensions/cocostudio/CCArmatureAnimation.cpp index 3880ecabb3..5f02e393e1 100644 --- a/extensions/cocostudio/CCArmatureAnimation.cpp +++ b/extensions/cocostudio/CCArmatureAnimation.cpp @@ -138,7 +138,7 @@ void ArmatureAnimation::setSpeedScale(float speedScale) _processScale = !_movementData ? _speedScale : _speedScale * _movementData->scale; - auto& map = _armature->getBoneDic(); + const Map& map = _armature->getBoneDic(); for (auto& element : map) { Bone* bone = element.second; @@ -156,7 +156,7 @@ float ArmatureAnimation::getSpeedScale() const return _speedScale; } -void ArmatureAnimation::play(std::string_view animationName, int durationTo, int loop) +void ArmatureAnimation::play(const std::string& animationName, int durationTo, int loop) { if (animationName.empty()) { @@ -212,7 +212,7 @@ void ArmatureAnimation::play(std::string_view animationName, int durationTo, int MovementBoneData* movementBoneData = nullptr; _tweenList.clear(); - auto& map = _armature->getBoneDic(); + const Map& map = _armature->getBoneDic(); for (auto& element : map) { Bone* bone = element.second; @@ -469,12 +469,12 @@ void ArmatureAnimation::setFrameEventCallFunc(Ref* target, SEL_FrameEventCallFun } void ArmatureAnimation::setMovementEventCallFunc( - std::function listener) + std::function listener) { _movementEventListener = listener; } void ArmatureAnimation::setFrameEventCallFunc( - std::function + std::function listener) { _frameEventListener = listener; @@ -488,7 +488,7 @@ void ArmatureAnimation::setUserObject(Ref* pUserObject) } void ArmatureAnimation::frameEvent(Bone* bone, - std::string_view frameEventName, + const std::string& frameEventName, int originFrameIndex, int currentFrameIndex) { @@ -504,7 +504,7 @@ void ArmatureAnimation::frameEvent(Bone* bone, } } -void ArmatureAnimation::movementEvent(Armature* armature, MovementEventType movementType, std::string_view movementID) +void ArmatureAnimation::movementEvent(Armature* armature, MovementEventType movementType, const std::string& movementID) { if ((_movementEventTarget && _movementEventCallFunc) || _movementEventListener) { diff --git a/extensions/cocostudio/CCArmatureAnimation.h b/extensions/cocostudio/CCArmatureAnimation.h index 16ac005980..77eb5984a0 100644 --- a/extensions/cocostudio/CCArmatureAnimation.h +++ b/extensions/cocostudio/CCArmatureAnimation.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -43,8 +43,8 @@ enum MovementEventType class Armature; class Bone; -typedef void (cocos2d::Ref::*SEL_MovementEventCallFunc)(Armature*, MovementEventType, std::string_view); -typedef void (cocos2d::Ref::*SEL_FrameEventCallFunc)(Bone*, std::string_view, int, int); +typedef void (cocos2d::Ref::*SEL_MovementEventCallFunc)(Armature*, MovementEventType, const std::string&); +typedef void (cocos2d::Ref::*SEL_FrameEventCallFunc)(Bone*, const std::string&, int, int); #define movementEvent_selector(_SELECTOR) (cocostudio::SEL_MovementEventCallFunc)(&_SELECTOR) #define frameEvent_selector(_SELECTOR) (cocostudio::SEL_FrameEventCallFunc)(&_SELECTOR) @@ -123,7 +123,7 @@ public: * loop = 0 : this animation is not loop * loop > 0 : this animation is loop */ - virtual void play(std::string_view animationName, int durationTo = -1, int loop = -1); + virtual void play(const std::string& animationName, int durationTo = -1, int loop = -1); /** * Play animation by index, the other param is the same to play. @@ -192,9 +192,10 @@ public: CC_DEPRECATED_ATTRIBUTE void setFrameEventCallFunc(cocos2d::Ref* target, SEL_FrameEventCallFunc callFunc); void setMovementEventCallFunc( - std::function listener); + std::function + listener); void setFrameEventCallFunc( - std::function + std::function listener); virtual void setAnimationData(AnimationData* data) @@ -256,12 +257,12 @@ protected: * @js NA * @lua NA */ - void frameEvent(Bone* bone, std::string_view frameEventName, int originFrameIndex, int currentFrameIndex); + void frameEvent(Bone* bone, const std::string& frameEventName, int originFrameIndex, int currentFrameIndex); /** * Emit a movement event */ - void movementEvent(Armature* armature, MovementEventType movementType, std::string_view movementID); + void movementEvent(Armature* armature, MovementEventType movementType, const std::string& movementID); void updateMovementList(); @@ -321,9 +322,9 @@ protected: cocos2d::Ref* _movementEventTarget; cocos2d::Ref* _frameEventTarget; - std::function + std::function _movementEventListener; - std::function + std::function _frameEventListener; }; diff --git a/extensions/cocostudio/CCArmatureDataManager.cpp b/extensions/cocostudio/CCArmatureDataManager.cpp index ca323b807e..20f716f0e3 100644 --- a/extensions/cocostudio/CCArmatureDataManager.cpp +++ b/extensions/cocostudio/CCArmatureDataManager.cpp @@ -87,7 +87,7 @@ bool ArmatureDataManager::init() return bRet; } -void ArmatureDataManager::removeArmatureFileInfo(std::string_view configFilePath) +void ArmatureDataManager::removeArmatureFileInfo(const std::string& configFilePath) { if (RelativeData* data = getRelativeData(configFilePath)) { @@ -116,71 +116,73 @@ void ArmatureDataManager::removeArmatureFileInfo(std::string_view configFilePath } } -void ArmatureDataManager::addArmatureData(std::string_view id, +void ArmatureDataManager::addArmatureData(const std::string& id, ArmatureData* armatureData, - std::string_view configFilePath) + const std::string& configFilePath) { if (RelativeData* data = getRelativeData(configFilePath)) { - data->armatures.push_back(std::string{id}); + data->armatures.push_back(id); } _armarureDatas.insert(id, armatureData); } -ArmatureData* ArmatureDataManager::getArmatureData(std::string_view id) +ArmatureData* ArmatureDataManager::getArmatureData(const std::string& id) { return dynamic_cast(_armarureDatas.at(id)); } -void ArmatureDataManager::removeArmatureData(std::string_view id) +void ArmatureDataManager::removeArmatureData(const std::string& id) { _armarureDatas.erase(id); } -void ArmatureDataManager::addAnimationData(std::string_view id, +void ArmatureDataManager::addAnimationData(const std::string& id, AnimationData* animationData, - std::string_view configFilePath) + const std::string& configFilePath) { if (RelativeData* data = getRelativeData(configFilePath)) { - data->animations.push_back(std::string{id}); + data->animations.push_back(id); } _animationDatas.insert(id, animationData); } -AnimationData* ArmatureDataManager::getAnimationData(std::string_view id) +AnimationData* ArmatureDataManager::getAnimationData(const std::string& id) { return dynamic_cast(_animationDatas.at(id)); } -void ArmatureDataManager::removeAnimationData(std::string_view id) +void ArmatureDataManager::removeAnimationData(const std::string& id) { _animationDatas.erase(id); } -void ArmatureDataManager::addTextureData(std::string_view id, TextureData* textureData, std::string_view configFilePath) +void ArmatureDataManager::addTextureData(const std::string& id, + TextureData* textureData, + const std::string& configFilePath) { if (RelativeData* data = getRelativeData(configFilePath)) { - data->textures.push_back(std::string{id}); + data->textures.push_back(id); } _textureDatas.insert(id, textureData); } -TextureData* ArmatureDataManager::getTextureData(std::string_view id) +TextureData* ArmatureDataManager::getTextureData(const std::string& id) { return dynamic_cast(_textureDatas.at(id)); } -void ArmatureDataManager::removeTextureData(std::string_view id) +void ArmatureDataManager::removeTextureData(const std::string& id) { _textureDatas.erase(id); } -void ArmatureDataManager::addArmatureFileInfo(std::string_view configFilePath) +void ArmatureDataManager::addArmatureFileInfo(const std::string& configFilePath) { addRelativeData(configFilePath); @@ -188,7 +190,9 @@ void ArmatureDataManager::addArmatureFileInfo(std::string_view configFilePath) DataReaderHelper::getInstance()->addDataFromFile(configFilePath); } -void ArmatureDataManager::addArmatureFileInfoAsync(std::string_view configFilePath, Ref* target, SEL_SCHEDULE selector) +void ArmatureDataManager::addArmatureFileInfoAsync(const std::string& configFilePath, + Ref* target, + SEL_SCHEDULE selector) { addRelativeData(configFilePath); @@ -196,9 +200,9 @@ void ArmatureDataManager::addArmatureFileInfoAsync(std::string_view configFilePa DataReaderHelper::getInstance()->addDataFromFileAsync("", "", configFilePath, target, selector); } -void ArmatureDataManager::addArmatureFileInfo(std::string_view imagePath, - std::string_view plistPath, - std::string_view configFilePath) +void ArmatureDataManager::addArmatureFileInfo(const std::string& imagePath, + const std::string& plistPath, + const std::string& configFilePath) { addRelativeData(configFilePath); @@ -207,9 +211,9 @@ void ArmatureDataManager::addArmatureFileInfo(std::string_view imagePath, addSpriteFrameFromFile(plistPath, imagePath, configFilePath); } -void ArmatureDataManager::addArmatureFileInfoAsync(std::string_view imagePath, - std::string_view plistPath, - std::string_view configFilePath, +void ArmatureDataManager::addArmatureFileInfoAsync(const std::string& imagePath, + const std::string& plistPath, + const std::string& configFilePath, Ref* target, SEL_SCHEDULE selector) { @@ -220,13 +224,13 @@ void ArmatureDataManager::addArmatureFileInfoAsync(std::string_view imagePath, addSpriteFrameFromFile(plistPath, imagePath, configFilePath); } -void ArmatureDataManager::addSpriteFrameFromFile(std::string_view plistPath, - std::string_view imagePath, - std::string_view configFilePath) +void ArmatureDataManager::addSpriteFrameFromFile(const std::string& plistPath, + const std::string& imagePath, + const std::string& configFilePath) { if (RelativeData* data = getRelativeData(configFilePath)) { - data->plistFiles.push_back(std::string{plistPath}); + data->plistFiles.push_back(plistPath); } SpriteFrameCacheHelper::getInstance()->addSpriteFrameFromFile(plistPath, imagePath); } @@ -236,20 +240,20 @@ bool ArmatureDataManager::isAutoLoadSpriteFile() return _autoLoadSpriteFile; } -const cocos2d::StringMap& ArmatureDataManager::getArmatureDatas() const +const cocos2d::Map& ArmatureDataManager::getArmatureDatas() const { return _armarureDatas; } -const cocos2d::StringMap& ArmatureDataManager::getAnimationDatas() const +const cocos2d::Map& ArmatureDataManager::getAnimationDatas() const { return _animationDatas; } -const cocos2d::StringMap& ArmatureDataManager::getTextureDatas() const +const cocos2d::Map& ArmatureDataManager::getTextureDatas() const { return _textureDatas; } -void ArmatureDataManager::addRelativeData(std::string_view configFilePath) +void ArmatureDataManager::addRelativeData(const std::string& configFilePath) { if (_relativeDatas.find(configFilePath) == _relativeDatas.end()) { @@ -257,7 +261,7 @@ void ArmatureDataManager::addRelativeData(std::string_view configFilePath) } } -RelativeData* ArmatureDataManager::getRelativeData(std::string_view configFilePath) +RelativeData* ArmatureDataManager::getRelativeData(const std::string& configFilePath) { return &_relativeDatas[configFilePath]; } diff --git a/extensions/cocostudio/CCArmatureDataManager.h b/extensions/cocostudio/CCArmatureDataManager.h index 6b549e17b1..d7e9f5dd97 100644 --- a/extensions/cocostudio/CCArmatureDataManager.h +++ b/extensions/cocostudio/CCArmatureDataManager.h @@ -80,110 +80,112 @@ public: * @param id The id of the armature data * @param armatureData ArmatureData * */ - void addArmatureData(std::string_view id, ArmatureData* armatureData, std::string_view configFilePath = ""); + void addArmatureData(const std::string& id, ArmatureData* armatureData, const std::string& configFilePath = ""); /** * @brief get armature data * @param id the id of the armature data you want to get * @return ArmatureData * */ - ArmatureData* getArmatureData(std::string_view id); + ArmatureData* getArmatureData(const std::string& id); /** * @brief remove armature data * @param id the id of the armature data you want to get */ - void removeArmatureData(std::string_view id); + void removeArmatureData(const std::string& id); /** * @brief add animation data * @param id the id of the animation data * @return AnimationData * */ - void addAnimationData(std::string_view id, AnimationData* animationData, std::string_view configFilePath = ""); + void addAnimationData(const std::string& id, AnimationData* animationData, const std::string& configFilePath = ""); /** * @brief get animation data from _animationDatas(Dictionary) * @param id the id of the animation data you want to get * @return AnimationData * */ - AnimationData* getAnimationData(std::string_view id); + AnimationData* getAnimationData(const std::string& id); /** * @brief remove animation data * @param id the id of the animation data */ - void removeAnimationData(std::string_view id); + void removeAnimationData(const std::string& id); /** * @brief add texture data * @param id the id of the texture data * @return TextureData * */ - void addTextureData(std::string_view id, TextureData* textureData, std::string_view configFilePath = ""); + void addTextureData(const std::string& id, TextureData* textureData, const std::string& configFilePath = ""); /** * @brief get texture data * @param id the id of the texture data you want to get * @return TextureData * */ - TextureData* getTextureData(std::string_view id); + TextureData* getTextureData(const std::string& id); /** * @brief remove texture data * @param id the id of the texture data you want to get */ - void removeTextureData(std::string_view id); + void removeTextureData(const std::string& id); /** * @brief Add ArmatureFileInfo, it is managed by ArmatureDataManager. */ - void addArmatureFileInfo(std::string_view configFilePath); + void addArmatureFileInfo(const std::string& configFilePath); /** * @brief Add ArmatureFileInfo, it is managed by ArmatureDataManager. * It will load data in a new thread */ - void addArmatureFileInfoAsync(std::string_view configFilePath, + void addArmatureFileInfoAsync(const std::string& configFilePath, cocos2d::Ref* target, cocos2d::SEL_SCHEDULE selector); /** * @brief Add ArmatureFileInfo, it is managed by ArmatureDataManager. */ - void addArmatureFileInfo(std::string_view imagePath, std::string_view plistPath, std::string_view configFilePath); + void addArmatureFileInfo(const std::string& imagePath, + const std::string& plistPath, + const std::string& configFilePath); /** * @brief Add ArmatureFileInfo, it is managed by ArmatureDataManager. * It will load data in a new thread */ - void addArmatureFileInfoAsync(std::string_view imagePath, - std::string_view plistPath, - std::string_view configFilePath, + void addArmatureFileInfoAsync(const std::string& imagePath, + const std::string& plistPath, + const std::string& configFilePath, cocos2d::Ref* target, cocos2d::SEL_SCHEDULE selector); /** * @brief Add sprite frame to CCSpriteFrameCache, it will save display name and it's relative image name */ - void addSpriteFrameFromFile(std::string_view plistPath, - std::string_view imagePath, - std::string_view configFilePath = ""); + void addSpriteFrameFromFile(const std::string& plistPath, + const std::string& imagePath, + const std::string& configFilePath = ""); - virtual void removeArmatureFileInfo(std::string_view configFilePath); + virtual void removeArmatureFileInfo(const std::string& configFilePath); /** * @brief Judge whether or not need auto load sprite file */ bool isAutoLoadSpriteFile(); - const cocos2d::StringMap& getArmatureDatas() const; - const cocos2d::StringMap& getAnimationDatas() const; - const cocos2d::StringMap& getTextureDatas() const; + const cocos2d::Map& getArmatureDatas() const; + const cocos2d::Map& getAnimationDatas() const; + const cocos2d::Map& getTextureDatas() const; public: - void addRelativeData(std::string_view configFilePath); - RelativeData* getRelativeData(std::string_view configFilePath); + void addRelativeData(const std::string& configFilePath); + RelativeData* getRelativeData(const std::string& configFilePath); private: /** @@ -191,25 +193,25 @@ private: * @key std::string * @value ArmatureData * */ - cocos2d::StringMap _armarureDatas; + cocos2d::Map _armarureDatas; /** * @brief save animation datas * @key std::string * @value AnimationData * */ - cocos2d::StringMap _animationDatas; + cocos2d::Map _animationDatas; /** * @brief save texture datas * @key std::string * @value TextureData * */ - cocos2d::StringMap _textureDatas; + cocos2d::Map _textureDatas; bool _autoLoadSpriteFile; - hlookup::string_map _relativeDatas; + std::unordered_map _relativeDatas; }; } // namespace cocostudio diff --git a/extensions/cocostudio/CCBatchNode.cpp b/extensions/cocostudio/CCBatchNode.cpp index 4344dea841..f7ec04f519 100644 --- a/extensions/cocostudio/CCBatchNode.cpp +++ b/extensions/cocostudio/CCBatchNode.cpp @@ -69,7 +69,7 @@ void BatchNode::addChild(Node* child, int zOrder, int tag) } } -void BatchNode::addChild(cocos2d::Node* child, int zOrder, std::string_view name) +void BatchNode::addChild(cocos2d::Node* child, int zOrder, const std::string& name) { Node::addChild(child, zOrder, name); Armature* armature = dynamic_cast(child); diff --git a/extensions/cocostudio/CCBatchNode.h b/extensions/cocostudio/CCBatchNode.h index 7269f6dcbb..88a3983451 100644 --- a/extensions/cocostudio/CCBatchNode.h +++ b/extensions/cocostudio/CCBatchNode.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -58,7 +58,7 @@ public: virtual bool init() override; using Node::addChild; virtual void addChild(cocos2d::Node* pChild, int zOrder, int tag) override; - virtual void addChild(cocos2d::Node* pChild, int zOrder, std::string_view name) override; + virtual void addChild(cocos2d::Node* pChild, int zOrder, const std::string& name) override; virtual void removeChild(cocos2d::Node* child, bool cleanup) override; virtual void visit(cocos2d::Renderer* renderer, const cocos2d::Mat4& parentTransform, diff --git a/extensions/cocostudio/CCBone.cpp b/extensions/cocostudio/CCBone.cpp index 1fe824b92f..bbe38bb390 100644 --- a/extensions/cocostudio/CCBone.cpp +++ b/extensions/cocostudio/CCBone.cpp @@ -47,7 +47,7 @@ Bone* Bone::create() return nullptr; } -Bone* Bone::create(std::string_view name) +Bone* Bone::create(const std::string& name) { Bone* pBone = new Bone(); @@ -95,7 +95,7 @@ bool Bone::init() return Bone::init(nullptr); } -bool Bone::init(std::string_view name) +bool Bone::init(const std::string& name) { bool bRet = false; do @@ -416,7 +416,7 @@ void Bone::changeDisplayByIndex(int index, bool force) changeDisplayWithIndex(index, force); } -void Bone::changeDisplayByName(std::string_view name, bool force) +void Bone::changeDisplayByName(const std::string& name, bool force) { changeDisplayWithName(name, force); } @@ -426,7 +426,7 @@ void Bone::changeDisplayWithIndex(int index, bool force) _displayManager->changeDisplayWithIndex(index, force); } -void Bone::changeDisplayWithName(std::string_view name, bool force) +void Bone::changeDisplayWithName(const std::string& name, bool force) { _displayManager->changeDisplayWithName(name, force); } diff --git a/extensions/cocostudio/CCBone.h b/extensions/cocostudio/CCBone.h index 409a0a381e..bea21a95df 100644 --- a/extensions/cocostudio/CCBone.h +++ b/extensions/cocostudio/CCBone.h @@ -53,7 +53,7 @@ public: * @param name If name is not null, then set name to the bone's name * @return A initialized bone which is marked as "autorelease". */ - static Bone* create(std::string_view name); + static Bone* create(const std::string& name); public: /** @@ -75,7 +75,7 @@ public: * Initializes a Bone with the specified name * @param name Bone's name. */ - virtual bool init(std::string_view name); + virtual bool init(const std::string& name); /** * Add display and use displayData to init the display. @@ -95,10 +95,10 @@ public: void removeDisplay(int index); CC_DEPRECATED_ATTRIBUTE void changeDisplayByIndex(int index, bool force); - CC_DEPRECATED_ATTRIBUTE void changeDisplayByName(std::string_view name, bool force); + CC_DEPRECATED_ATTRIBUTE void changeDisplayByName(const std::string& name, bool force); void changeDisplayWithIndex(int index, bool force); - void changeDisplayWithName(std::string_view name, bool force); + void changeDisplayWithName(const std::string& name, bool force); /** * Add a child to this bone, and it will let this child call setParent(Bone *parent) function to set self to it's diff --git a/extensions/cocostudio/CCComAttribute.cpp b/extensions/cocostudio/CCComAttribute.cpp index f8c5381915..57cf1b0767 100644 --- a/extensions/cocostudio/CCComAttribute.cpp +++ b/extensions/cocostudio/CCComAttribute.cpp @@ -49,27 +49,27 @@ bool ComAttribute::init() return true; } -void ComAttribute::setInt(std::string_view key, int value) +void ComAttribute::setInt(const std::string& key, int value) { _dict[key] = cocos2d::Value(value); } -void ComAttribute::setFloat(std::string_view key, float value) +void ComAttribute::setFloat(const std::string& key, float value) { _dict[key] = cocos2d::Value(value); } -void ComAttribute::setBool(std::string_view key, bool value) +void ComAttribute::setBool(const std::string& key, bool value) { _dict[key] = cocos2d::Value(value); } -void ComAttribute::setString(std::string_view key, std::string_view value) +void ComAttribute::setString(const std::string& key, const std::string& value) { _dict[key] = cocos2d::Value(value); } -int ComAttribute::getInt(std::string_view key, int def) const +int ComAttribute::getInt(const std::string& key, int def) const { if (_dict.find(key) != _dict.end()) { @@ -77,15 +77,15 @@ int ComAttribute::getInt(std::string_view key, int def) const return v.asInt(); } - if (!DICTOOL->checkObjectExist_json(_doc, key.data())) + if (!DICTOOL->checkObjectExist_json(_doc, key.c_str())) { return def; } - return DICTOOL->getIntValue_json(_doc, key.data()); + return DICTOOL->getIntValue_json(_doc, key.c_str()); } -float ComAttribute::getFloat(std::string_view key, float def) const +float ComAttribute::getFloat(const std::string& key, float def) const { if (_dict.find(key) != _dict.end()) { @@ -93,14 +93,14 @@ float ComAttribute::getFloat(std::string_view key, float def) const return v.asFloat(); } - if (!DICTOOL->checkObjectExist_json(_doc, key.data())) + if (!DICTOOL->checkObjectExist_json(_doc, key.c_str())) { return def; } - return DICTOOL->getFloatValue_json(_doc, key.data()); + return DICTOOL->getFloatValue_json(_doc, key.c_str()); } -bool ComAttribute::getBool(std::string_view key, bool def) const +bool ComAttribute::getBool(const std::string& key, bool def) const { if (_dict.find(key) != _dict.end()) { @@ -108,15 +108,15 @@ bool ComAttribute::getBool(std::string_view key, bool def) const return v.asBool(); } - if (!DICTOOL->checkObjectExist_json(_doc, key.data())) + if (!DICTOOL->checkObjectExist_json(_doc, key.c_str())) { return def; } - return DICTOOL->getBooleanValue_json(_doc, key.data()); + return DICTOOL->getBooleanValue_json(_doc, key.c_str()); } -std::string ComAttribute::getString(std::string_view key, std::string_view def) const +std::string ComAttribute::getString(const std::string& key, const std::string& def) const { if (_dict.find(key) != _dict.end()) { @@ -124,12 +124,12 @@ std::string ComAttribute::getString(std::string_view key, std::string_view def) return v.asString(); } - if (!DICTOOL->checkObjectExist_json(_doc, key.data())) + if (!DICTOOL->checkObjectExist_json(_doc, key.c_str())) { - return std::string{def}; + return def; } - return DICTOOL->getStringValue_json(_doc, key.data()); + return DICTOOL->getStringValue_json(_doc, key.c_str()); } ComAttribute* ComAttribute::create() @@ -206,7 +206,7 @@ bool ComAttribute::serialize(void* r) return ret; } -bool ComAttribute::parse(std::string_view jsonFile) +bool ComAttribute::parse(const std::string& jsonFile) { bool ret = false; do diff --git a/extensions/cocostudio/CCComAttribute.h b/extensions/cocostudio/CCComAttribute.h index df368b8c46..1a47ff8d05 100644 --- a/extensions/cocostudio/CCComAttribute.h +++ b/extensions/cocostudio/CCComAttribute.h @@ -54,15 +54,15 @@ public: virtual bool init() override; virtual bool serialize(void* r) override; - void setInt(std::string_view key, int value); - void setFloat(std::string_view key, float value); - void setBool(std::string_view key, bool value); - void setString(std::string_view key, std::string_view value); - int getInt(std::string_view key, int def = 0) const; - float getFloat(std::string_view key, float def = 0.0f) const; - bool getBool(std::string_view key, bool def = false) const; - std::string getString(std::string_view key, std::string_view def = "") const; - bool parse(std::string_view jsonFile); + void setInt(const std::string& key, int value); + void setFloat(const std::string& key, float value); + void setBool(const std::string& key, bool value); + void setString(const std::string& key, const std::string& value); + int getInt(const std::string& key, int def = 0) const; + float getFloat(const std::string& key, float def = 0.0f) const; + bool getBool(const std::string& key, bool def = false) const; + std::string getString(const std::string& key, const std::string& def = "") const; + bool parse(const std::string& jsonFile); private: cocos2d::ValueMap _dict; diff --git a/extensions/cocostudio/CCComExtensionData.h b/extensions/cocostudio/CCComExtensionData.h index 9735491506..0c5dcb7de0 100644 --- a/extensions/cocostudio/CCComExtensionData.h +++ b/extensions/cocostudio/CCComExtensionData.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2015 cocos2d-x.org http://www.cocos2d-x.org @@ -69,7 +69,7 @@ public: static ComExtensionData* create(); virtual bool init() override; - virtual void setCustomProperty(std::string_view customProperty) { _customProperty = customProperty; } + virtual void setCustomProperty(const std::string& customProperty) { _customProperty = customProperty; } virtual std::string getCustomProperty() const { return _customProperty; }; virtual void setActionTag(int actionTag); diff --git a/extensions/cocostudio/CCComRender.cpp b/extensions/cocostudio/CCComRender.cpp index 74cf487a8b..ad2262cf8d 100644 --- a/extensions/cocostudio/CCComRender.cpp +++ b/extensions/cocostudio/CCComRender.cpp @@ -383,7 +383,7 @@ ComRender* ComRender::create(cocos2d::Node* node, const char* comName) return ret; } -bool ComRender::readJson(std::string_view fileName, rapidjson::Document& doc) +bool ComRender::readJson(const std::string& fileName, rapidjson::Document& doc) { bool ret = false; do diff --git a/extensions/cocostudio/CCComRender.h b/extensions/cocostudio/CCComRender.h index de0aaeebb1..83bc28e58f 100644 --- a/extensions/cocostudio/CCComRender.h +++ b/extensions/cocostudio/CCComRender.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -79,7 +79,7 @@ public: virtual ~ComRender(); private: - bool readJson(std::string_view fileName, rapidjson::Document& doc); + bool readJson(const std::string& fileName, rapidjson::Document& doc); cocos2d::Node* _render; }; diff --git a/extensions/cocostudio/CCDataReaderHelper.cpp b/extensions/cocostudio/CCDataReaderHelper.cpp index 59d2c7d51d..7cd5acea54 100644 --- a/extensions/cocostudio/CCDataReaderHelper.cpp +++ b/extensions/cocostudio/CCDataReaderHelper.cpp @@ -133,7 +133,7 @@ static const char* COLOR_INFO = "color"; static const char* CONFIG_FILE_PATH = "config_file_path"; static const char* CONTENT_SCALE = "content_scale"; -static std::string readFileContent(std::string_view filename, bool binary) +static std::string readFileContent(const std::string& filename, bool binary) { auto fs = FileUtils::getInstance(); std::string s; @@ -264,7 +264,7 @@ DataReaderHelper::~DataReaderHelper() _dataReaderHelper = nullptr; } -void DataReaderHelper::addDataFromFile(std::string_view filePath) +void DataReaderHelper::addDataFromFile(const std::string& filePath) { /* * Check if file is already added to ArmatureDataManager, if then return. @@ -276,15 +276,19 @@ void DataReaderHelper::addDataFromFile(std::string_view filePath) return; } } - _configFileList.push_back(std::string{filePath}); + _configFileList.push_back(filePath); //! find the base file path - std::string basefilePath; - size_t pos = filePath.find_last_of('/'); + std::string basefilePath = filePath; + size_t pos = basefilePath.find_last_of('/'); if (pos != std::string::npos) { - basefilePath = filePath.substr(0, pos + 1); + basefilePath = basefilePath.substr(0, pos + 1); + } + else + { + basefilePath = ""; } std::string fileExtension = cocos2d::FileUtils::getInstance()->getFileExtension(filePath); @@ -315,9 +319,9 @@ void DataReaderHelper::addDataFromFile(std::string_view filePath) } } -void DataReaderHelper::addDataFromFileAsync(std::string_view imagePath, - std::string_view plistPath, - std::string_view filePath, +void DataReaderHelper::addDataFromFileAsync(const std::string& imagePath, + const std::string& plistPath, + const std::string& filePath, Ref* target, SEL_SCHEDULE selector) { @@ -342,15 +346,19 @@ void DataReaderHelper::addDataFromFileAsync(std::string_view imagePath, return; } } - _configFileList.push_back(std::string{filePath}); + _configFileList.push_back(filePath); //! find the base file path - std::string basefilePath; - size_t pos = filePath.find_last_of('/'); + std::string basefilePath = filePath; + size_t pos = basefilePath.find_last_of('/'); if (pos != std::string::npos) { - basefilePath = filePath.substr(0, pos + 1); + basefilePath = basefilePath.substr(0, pos + 1); + } + else + { + basefilePath = ""; } // lazy init @@ -482,7 +490,7 @@ void DataReaderHelper::addDataAsyncCallBack(float /*dt*/) } } -void DataReaderHelper::removeConfigFile(std::string_view configFile) +void DataReaderHelper::removeConfigFile(const std::string& configFile) { auto it_end = _configFileList.end(); for (auto it = _configFileList.begin(); it != it_end; ++it) @@ -495,12 +503,10 @@ void DataReaderHelper::removeConfigFile(std::string_view configFile) } } -void DataReaderHelper::addDataFromCache(std::string_view pFileContent, DataInfo* dataInfo) +void DataReaderHelper::addDataFromCache(const std::string& pFileContent, DataInfo* dataInfo) { pugi::xml_document document; - pugi::xml_parse_result ret = document.load_buffer(pFileContent.data(), pFileContent.length()); - if (!ret) - return; + document.load_string(pFileContent.c_str()); auto root = document.document_element(); dataInfo->flashToolVersion = root.attribute(VERSION).as_float(); @@ -1110,15 +1116,15 @@ ContourData* DataReaderHelper::decodeContour(pugi::xml_node& contourXML, DataInf return contourData; } -void DataReaderHelper::addDataFromJsonCache(std::string_view fileContent, DataInfo* dataInfo) +void DataReaderHelper::addDataFromJsonCache(const std::string& fileContent, DataInfo* dataInfo) { rapidjson::Document json; - rapidjson::StringStream stream(fileContent.data()); + rapidjson::StringStream stream(fileContent.c_str()); if (fileContent.size() >= 3) { // Skip BOM if exists - const unsigned char* c = (const unsigned char*)fileContent.data(); + const unsigned char* c = (const unsigned char*)fileContent.c_str(); unsigned bom = c[0] | (c[1] << 8) | (c[2] << 16); if (bom == 0xBFBBEF) // UTF8 BOM diff --git a/extensions/cocostudio/CCDataReaderHelper.h b/extensions/cocostudio/CCDataReaderHelper.h index b3437f7cb6..aa511c27ab 100644 --- a/extensions/cocostudio/CCDataReaderHelper.h +++ b/extensions/cocostudio/CCDataReaderHelper.h @@ -114,16 +114,16 @@ public: */ ~DataReaderHelper(); - void addDataFromFile(std::string_view filePath); - void addDataFromFileAsync(std::string_view imagePath, - std::string_view plistPath, - std::string_view filePath, + void addDataFromFile(const std::string& filePath); + void addDataFromFileAsync(const std::string& imagePath, + const std::string& plistPath, + const std::string& filePath, cocos2d::Ref* target, cocos2d::SEL_SCHEDULE selector); void addDataAsyncCallBack(float dt); - void removeConfigFile(std::string_view configFile); + void removeConfigFile(const std::string& configFile); public: /** @@ -132,7 +132,7 @@ public: * * @param xmlPath The cache of the xml */ - static void addDataFromCache(std::string_view pFileContent, DataInfo* dataInfo = nullptr); + static void addDataFromCache(const std::string& pFileContent, DataInfo* dataInfo = nullptr); /** * Decode Armature Datas from xml export from Dragon Bone flash tool @@ -166,7 +166,7 @@ public: static ContourData* decodeContour(pugi::xml_node& contourXML, DataInfo* dataInfo); public: - static void addDataFromJsonCache(std::string_view fileContent, DataInfo* dataInfo = nullptr); + static void addDataFromJsonCache(const std::string& fileContent, DataInfo* dataInfo = nullptr); static ArmatureData* decodeArmature(const rapidjson::Value& json, DataInfo* dataInfo); static BoneData* decodeBone(const rapidjson::Value& json, DataInfo* dataInfo); diff --git a/extensions/cocostudio/CCDatas.cpp b/extensions/cocostudio/CCDatas.cpp index ef45d8bd45..ff8d44569d 100644 --- a/extensions/cocostudio/CCDatas.cpp +++ b/extensions/cocostudio/CCDatas.cpp @@ -136,18 +136,16 @@ Color4B BaseData::getColor() return Color4B(r, g, b, a); } -std::string DisplayData::changeDisplayToTexture(std::string_view displayName) +std::string DisplayData::changeDisplayToTexture(const std::string& displayName) { // remove .xxx - std::string textureName; - size_t startPos = displayName.find_last_of("."); + std::string textureName = displayName; + size_t startPos = textureName.find_last_of("."); if (startPos != std::string::npos) { - textureName.assign(displayName.data(), startPos); // textureName = textureName.erase(startPos); + textureName = textureName.erase(startPos); } - else - textureName = displayName; return textureName; } @@ -218,7 +216,7 @@ void ArmatureData::addBoneData(BoneData* boneData) boneDataDic.insert(boneData->name, boneData); } -BoneData* ArmatureData::getBoneData(std::string_view boneName) +BoneData* ArmatureData::getBoneData(const std::string& boneName) { return static_cast(boneDataDic.at(boneName)); } @@ -307,7 +305,7 @@ void MovementData::addMovementBoneData(MovementBoneData* movBoneData) movBoneDataDic.insert(movBoneData->name, movBoneData); } -MovementBoneData* MovementData::getMovementBoneData(std::string_view boneName) +MovementBoneData* MovementData::getMovementBoneData(const std::string& boneName) { return movBoneDataDic.at(boneName); } @@ -322,7 +320,7 @@ void AnimationData::addMovement(MovementData* movData) movementNames.push_back(movData->name); } -MovementData* AnimationData::getMovement(std::string_view movementName) +MovementData* AnimationData::getMovement(const std::string& movementName) { return movementDataDic.at(movementName); } diff --git a/extensions/cocostudio/CCDatas.h b/extensions/cocostudio/CCDatas.h index dc2d767526..08985516ec 100644 --- a/extensions/cocostudio/CCDatas.h +++ b/extensions/cocostudio/CCDatas.h @@ -140,7 +140,7 @@ class CCS_DLL DisplayData : public cocos2d::Ref public: CC_CREATE_NO_PARAM_NO_INIT(DisplayData) - static std::string changeDisplayToTexture(std::string_view displayName); + static std::string changeDisplayToTexture(const std::string& displayName); public: /** @@ -282,11 +282,11 @@ public: bool init(); void addBoneData(BoneData* boneData); - BoneData* getBoneData(std::string_view boneName); + BoneData* getBoneData(const std::string& boneName); public: std::string name; - cocos2d::StringMap boneDataDic; + cocos2d::Map boneDataDic; float dataVersion; }; @@ -409,7 +409,7 @@ public: ~MovementData(void); void addMovementBoneData(MovementBoneData* movBoneData); - MovementBoneData* getMovementBoneData(std::string_view boneName); + MovementBoneData* getMovementBoneData(const std::string& boneName); public: std::string name; @@ -443,10 +443,10 @@ public: /** * @brief save movement bone data - * @key std::string_view + * @key const std::string& * @value MovementBoneData * */ - cocos2d::StringMap movBoneDataDic; + cocos2d::Map movBoneDataDic; }; /** @@ -472,12 +472,12 @@ public: ~AnimationData(void); void addMovement(MovementData* movData); - MovementData* getMovement(std::string_view movementName); + MovementData* getMovement(const std::string& movementName); ssize_t getMovementCount(); public: std::string name; - cocos2d::StringMap movementDataDic; + cocos2d::Map movementDataDic; std::vector movementNames; }; diff --git a/extensions/cocostudio/CCDisplayManager.cpp b/extensions/cocostudio/CCDisplayManager.cpp index b6d07cc6fa..f5a4377d04 100644 --- a/extensions/cocostudio/CCDisplayManager.cpp +++ b/extensions/cocostudio/CCDisplayManager.cpp @@ -129,7 +129,7 @@ void DisplayManager::addDisplay(Node* display, int index) skin->setBone(_bone); displayData = SpriteDisplayData::create(); - DisplayFactory::initSpriteDisplay(_bone, decoDisplay, skin->getDisplayName().data(), skin); + DisplayFactory::initSpriteDisplay(_bone, decoDisplay, skin->getDisplayName().c_str(), skin); if (SpriteDisplayData* spriteDisplayData = (SpriteDisplayData*)decoDisplay->getDisplayData()) { @@ -239,7 +239,7 @@ void DisplayManager::changeDisplayWithIndex(int index, bool force) setCurrentDecorativeDisplay(decoDisplay); } -void DisplayManager::changeDisplayWithName(std::string_view name, bool force) +void DisplayManager::changeDisplayWithName(const std::string& name, bool force) { for (int i = 0; i < _decoDisplayList.size(); i++) { diff --git a/extensions/cocostudio/CCDisplayManager.h b/extensions/cocostudio/CCDisplayManager.h index f43fb13e56..1e32d8f7a7 100644 --- a/extensions/cocostudio/CCDisplayManager.h +++ b/extensions/cocostudio/CCDisplayManager.h @@ -80,7 +80,7 @@ public: * @deprecated, please use changeDisplayWithIndex and changeDisplayWithName */ CC_DEPRECATED_ATTRIBUTE void changeDisplayByIndex(int index, bool force); - CC_DEPRECATED_ATTRIBUTE void changeDisplayByName(std::string_view name, bool force); + CC_DEPRECATED_ATTRIBUTE void changeDisplayByName(const std::string& name, bool force); /** * Change display by index. You can just use this method to change display in the display list. @@ -93,7 +93,7 @@ public: * index edit in the flash every key frame. */ void changeDisplayWithIndex(int index, bool force); - void changeDisplayWithName(std::string_view name, bool force); + void changeDisplayWithName(const std::string& name, bool force); cocos2d::Node* getDisplayRenderNode() const; DisplayType getDisplayRenderNodeType() const; diff --git a/extensions/cocostudio/CCSGUIReader.cpp b/extensions/cocostudio/CCSGUIReader.cpp index 1edeaea008..0855bb102a 100644 --- a/extensions/cocostudio/CCSGUIReader.cpp +++ b/extensions/cocostudio/CCSGUIReader.cpp @@ -160,7 +160,7 @@ cocos2d::Size GUIReader::getFileDesignSize(const char* fileName) const return Size(w, h); } -void GUIReader::registerTypeAndCallBack(std::string_view classType, +void GUIReader::registerTypeAndCallBack(const std::string& classType, ObjectFactory::Instance ins, Ref* object, SEL_ParseEvent callBack) @@ -181,7 +181,7 @@ void GUIReader::registerTypeAndCallBack(std::string_view classType, } } -void GUIReader::registerTypeAndCallBack(std::string_view classType, +void GUIReader::registerTypeAndCallBack(const std::string& classType, ObjectFactory::InstanceFunc ins, Ref* object, SEL_ParseEvent callBack) @@ -309,9 +309,9 @@ std::string WidgetPropertiesReader::getWidgetReaderClassName(Widget* widget) return readerName; } -std::string WidgetPropertiesReader::getGUIClassName(std::string_view name) +std::string WidgetPropertiesReader::getGUIClassName(const std::string& name) { - std::string convertedClassName; + std::string convertedClassName = name; if (name == "Panel") { convertedClassName = "Layout"; @@ -336,13 +336,11 @@ std::string WidgetPropertiesReader::getGUIClassName(std::string_view name) { convertedClassName = "TextBMFont"; } - else - convertedClassName = name; return convertedClassName; } -cocos2d::ui::Widget* WidgetPropertiesReader::createGUI(std::string_view classname) +cocos2d::ui::Widget* WidgetPropertiesReader::createGUI(const std::string& classname) { std::string name = this->getGUIClassName(classname); @@ -351,7 +349,7 @@ cocos2d::ui::Widget* WidgetPropertiesReader::createGUI(std::string_view classnam return dynamic_cast(object); } -WidgetReaderProtocol* WidgetPropertiesReader::createWidgetReaderProtocol(std::string_view classname) +WidgetReaderProtocol* WidgetPropertiesReader::createWidgetReaderProtocol(const std::string& classname) { Ref* object = ObjectFactory::getInstance()->createObject(classname); @@ -428,10 +426,10 @@ Widget* GUIReader::widgetFromBinaryFile(const char* fileName) return widget; } -std::string WidgetPropertiesReader::getWidgetReaderClassName(std::string_view classname) +std::string WidgetPropertiesReader::getWidgetReaderClassName(const std::string& classname) { // create widget reader to parse properties of widget - std::string readerName; + std::string readerName = classname; if (readerName == "Panel") { readerName = "Layout"; @@ -456,8 +454,6 @@ std::string WidgetPropertiesReader::getWidgetReaderClassName(std::string_view cl { readerName = "TextBMFont"; } - else - readerName = classname; readerName.append("Reader"); return readerName; } @@ -1244,7 +1240,7 @@ void WidgetPropertiesReader0250::setPropsForAllWidgetFromJsonDictionary(WidgetRe const rapidjson::Value& /*options*/) {} -void WidgetPropertiesReader0250::setPropsForAllCustomWidgetFromJsonDictionary(std::string_view /*classType*/, +void WidgetPropertiesReader0250::setPropsForAllCustomWidgetFromJsonDictionary(const std::string& /*classType*/, cocos2d::ui::Widget* /*widget*/, const rapidjson::Value& /*customOptions*/) {} @@ -1546,7 +1542,7 @@ void WidgetPropertiesReader0300::setPropsForAllWidgetFromBinary(WidgetReaderProt reader->setPropsFromBinary(widget, cocoLoader, cocoNode); } -void WidgetPropertiesReader0300::setPropsForAllCustomWidgetFromBinary(std::string_view /*classType*/, +void WidgetPropertiesReader0300::setPropsForAllCustomWidgetFromBinary(const std::string& /*classType*/, cocos2d::ui::Widget* /*widget*/, CocoLoader* /*cocoLoader*/, stExpCocoNode* /*pCocoNode*/) @@ -1641,17 +1637,17 @@ void WidgetPropertiesReader0300::setPropsForAllWidgetFromJsonDictionary(WidgetRe reader->setPropsFromJsonDictionary(widget, options); } -void WidgetPropertiesReader0300::setPropsForAllCustomWidgetFromJsonDictionary(std::string_view classType, +void WidgetPropertiesReader0300::setPropsForAllCustomWidgetFromJsonDictionary(const std::string& classType, cocos2d::ui::Widget* widget, const rapidjson::Value& customOptions) { GUIReader* guiReader = GUIReader::getInstance(); - hlookup::string_map* object_map = guiReader->getParseObjectMap(); - Ref* object = (*object_map)[classType]; + std::map* object_map = guiReader->getParseObjectMap(); + Ref* object = (*object_map)[classType]; - hlookup::string_map* selector_map = guiReader->getParseCallBackMap(); - SEL_ParseEvent selector = (*selector_map)[classType]; + std::map* selector_map = guiReader->getParseCallBackMap(); + SEL_ParseEvent selector = (*selector_map)[classType]; if (object && selector) { diff --git a/extensions/cocostudio/CCSGUIReader.h b/extensions/cocostudio/CCSGUIReader.h index efec530634..5c277866cc 100644 --- a/extensions/cocostudio/CCSGUIReader.h +++ b/extensions/cocostudio/CCSGUIReader.h @@ -50,7 +50,7 @@ struct stExpCocoNode; #define kCCSVersion 1.0 -typedef void (cocos2d::Ref::*SEL_ParseEvent)(std::string_view, cocos2d::Ref*, const rapidjson::Value&); +typedef void (cocos2d::Ref::*SEL_ParseEvent)(const std::string&, cocos2d::Ref*, const rapidjson::Value&); #define parseselector(_SELECTOR) (SEL_ParseEvent)(&_SELECTOR) class CCS_DLL GUIReader : public cocos2d::Ref @@ -76,15 +76,15 @@ public: */ cocos2d::Size getFileDesignSize(const char* fileName) const; - void setFilePath(std::string_view strFilePath) { m_strFilePath = strFilePath; } - std::string_view getFilePath() const { return m_strFilePath; } + void setFilePath(const std::string& strFilePath) { m_strFilePath = strFilePath; } + const std::string& getFilePath() const { return m_strFilePath; } - void registerTypeAndCallBack(std::string_view classType, + void registerTypeAndCallBack(const std::string& classType, cocos2d::ObjectFactory::Instance ins, Ref* object, SEL_ParseEvent callBack); - void registerTypeAndCallBack(std::string_view classType, + void registerTypeAndCallBack(const std::string& classType, cocos2d::ObjectFactory::InstanceFunc ins, Ref* object, SEL_ParseEvent callBack); @@ -96,9 +96,9 @@ protected: std::string m_strFilePath; cocos2d::ValueMap _fileDesignSizes; - typedef hlookup::string_map ParseCallBackMap; + typedef std::map ParseCallBackMap; ParseCallBackMap _mapParseSelector; - typedef hlookup::string_map ParseObjectMap; + typedef std::map ParseObjectMap; ParseObjectMap _mapObject; public: @@ -118,7 +118,7 @@ public: cocos2d::ui::Widget* widget, const rapidjson::Value& options) = 0; - virtual void setPropsForAllCustomWidgetFromJsonDictionary(std::string_view classType, + virtual void setPropsForAllCustomWidgetFromJsonDictionary(const std::string& classType, cocos2d::ui::Widget* widget, const rapidjson::Value& customOptions) = 0; @@ -134,12 +134,12 @@ public: protected: void setAnchorPointForWidget(cocos2d::ui::Widget* widget, const rapidjson::Value& options); - std::string getWidgetReaderClassName(std::string_view classname); + std::string getWidgetReaderClassName(const std::string& classname); std::string getWidgetReaderClassName(cocos2d::ui::Widget* widget); - std::string getGUIClassName(std::string_view name); - cocos2d::ui::Widget* createGUI(std::string_view classname); - WidgetReaderProtocol* createWidgetReaderProtocol(std::string_view classname); + std::string getGUIClassName(const std::string& name); + cocos2d::ui::Widget* createGUI(const std::string& classname); + WidgetReaderProtocol* createWidgetReaderProtocol(const std::string& classname); protected: std::string m_strFilePath; @@ -189,7 +189,7 @@ public: virtual void setPropsForAllWidgetFromJsonDictionary(WidgetReaderProtocol* reader, cocos2d::ui::Widget* widget, const rapidjson::Value& options) override; - virtual void setPropsForAllCustomWidgetFromJsonDictionary(std::string_view classType, + virtual void setPropsForAllCustomWidgetFromJsonDictionary(const std::string& classType, cocos2d::ui::Widget* widget, const rapidjson::Value& customOptions) override; }; @@ -217,7 +217,7 @@ public: CocoLoader* cocoLoader, stExpCocoNode* pCocoNode) override; - virtual void setPropsForAllCustomWidgetFromBinary(std::string_view classType, + virtual void setPropsForAllCustomWidgetFromBinary(const std::string& classType, cocos2d::ui::Widget* widget, CocoLoader* cocoLoader, stExpCocoNode* pCocoNode); @@ -228,7 +228,7 @@ public: cocos2d::ui::Widget* widget, const rapidjson::Value& options) override; - virtual void setPropsForAllCustomWidgetFromJsonDictionary(std::string_view classType, + virtual void setPropsForAllCustomWidgetFromJsonDictionary(const std::string& classType, cocos2d::ui::Widget* widget, const rapidjson::Value& customOptions) override; }; diff --git a/extensions/cocostudio/CCSSceneReader.cpp b/extensions/cocostudio/CCSSceneReader.cpp index c93c80f393..477341309d 100644 --- a/extensions/cocostudio/CCSSceneReader.cpp +++ b/extensions/cocostudio/CCSSceneReader.cpp @@ -54,7 +54,7 @@ const char* SceneReader::sceneReaderVersion() } cocos2d::Node* SceneReader::createNodeWithSceneFile( - std::string_view fileName, + const std::string& fileName, AttachComponentType attachComponent /*= AttachComponentType::EMPTY_NODE*/) { std::string fileExtension = cocos2d::FileUtils::getInstance()->getFileExtension(fileName); @@ -161,12 +161,12 @@ cocos2d::Node* SceneReader::createNodeWithSceneFile( } else { - log("read file [%s] error!\n", fileName.data()); + log("read file [%s] error!\n", fileName.c_str()); } return nullptr; } -bool SceneReader::readJson(std::string_view fileName, rapidjson::Document& doc) +bool SceneReader::readJson(const std::string& fileName, rapidjson::Document& doc) { bool ret = false; do @@ -210,14 +210,14 @@ Node* SceneReader::nodeByTag(Node* parent, int tag) return _retNode; } -cocos2d::Component* SceneReader::createComponent(std::string_view classname) +cocos2d::Component* SceneReader::createComponent(const std::string& classname) { std::string name = this->getComponentClassName(classname); Ref* object = ObjectFactory::getInstance()->createObject(name); return dynamic_cast(object); } -std::string SceneReader::getComponentClassName(std::string_view name) +std::string SceneReader::getComponentClassName(const std::string& name) { std::string comName; if (name == "CCSprite" || name == "CCTMXTiledMap" || name == "CCParticleSystemQuad" || name == "CCArmature" || diff --git a/extensions/cocostudio/CCSSceneReader.h b/extensions/cocostudio/CCSSceneReader.h index 4cb2e599b2..90163ac7e5 100644 --- a/extensions/cocostudio/CCSSceneReader.h +++ b/extensions/cocostudio/CCSSceneReader.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. Copyright (c) 2021 Bytedance Inc. @@ -61,7 +61,7 @@ public: */ static void destroyInstance(); static const char* sceneReaderVersion(); - cocos2d::Node* createNodeWithSceneFile(std::string_view fileName, + cocos2d::Node* createNodeWithSceneFile(const std::string& fileName, AttachComponentType attachComponent = AttachComponentType::EMPTY_NODE); void setTarget(const std::function& selector); cocos2d::Node* getNodeByTag(int nTag); @@ -70,15 +70,15 @@ public: virtual ~SceneReader(); private: - std::string getComponentClassName(std::string_view name); + std::string getComponentClassName(const std::string& name); - cocos2d::Component* createComponent(std::string_view classname); + cocos2d::Component* createComponent(const std::string& classname); cocos2d::Node* createObject(const rapidjson::Value& dict, cocos2d::Node* parent, AttachComponentType attachComponent); void setPropertyFromJsonDict(const rapidjson::Value& dict, cocos2d::Node* node); - bool readJson(std::string_view fileName, rapidjson::Document& doc); + bool readJson(const std::string& fileName, rapidjson::Document& doc); cocos2d::Node* createObject(CocoLoader* cocoLoader, stExpCocoNode* cocoNode, diff --git a/extensions/cocostudio/CCSkin.cpp b/extensions/cocostudio/CCSkin.cpp index a532988362..253354a235 100644 --- a/extensions/cocostudio/CCSkin.cpp +++ b/extensions/cocostudio/CCSkin.cpp @@ -55,7 +55,7 @@ Skin* Skin::create() return nullptr; } -Skin* Skin::createWithSpriteFrameName(std::string_view pszSpriteFrameName) +Skin* Skin::createWithSpriteFrameName(const std::string& pszSpriteFrameName) { Skin* skin = new Skin(); if (skin->initWithSpriteFrameName(pszSpriteFrameName)) @@ -67,7 +67,7 @@ Skin* Skin::createWithSpriteFrameName(std::string_view pszSpriteFrameName) return nullptr; } -Skin* Skin::create(std::string_view pszFileName) +Skin* Skin::create(const std::string& pszFileName) { Skin* skin = new Skin(); if (skin->initWithFile(pszFileName)) @@ -81,7 +81,7 @@ Skin* Skin::create(std::string_view pszFileName) Skin::Skin() : _bone(nullptr), _armature(nullptr), _displayName(), _skinTransform(Mat4::IDENTITY) {} -bool Skin::initWithSpriteFrameName(std::string_view spriteFrameName) +bool Skin::initWithSpriteFrameName(const std::string& spriteFrameName) { CCAssert(spriteFrameName != "", ""); @@ -94,7 +94,7 @@ bool Skin::initWithSpriteFrameName(std::string_view spriteFrameName) } else { - CCLOG("Can't find CCSpriteFrame with %s. Please check your .plist file", spriteFrameName.data()); + CCLOG("Can't find CCSpriteFrame with %s. Please check your .plist file", spriteFrameName.c_str()); ret = false; } @@ -103,7 +103,7 @@ bool Skin::initWithSpriteFrameName(std::string_view spriteFrameName) return ret; } -bool Skin::initWithFile(std::string_view filename) +bool Skin::initWithFile(const std::string& filename) { bool ret = Sprite::initWithFile(filename); diff --git a/extensions/cocostudio/CCSkin.h b/extensions/cocostudio/CCSkin.h index f1b0fc40b1..74046b428a 100644 --- a/extensions/cocostudio/CCSkin.h +++ b/extensions/cocostudio/CCSkin.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -39,8 +39,8 @@ class CCS_DLL Skin : public cocos2d::Sprite { public: static Skin* create(); - static Skin* createWithSpriteFrameName(std::string_view pszSpriteFrameName); - static Skin* create(std::string_view pszFileName); + static Skin* createWithSpriteFrameName(const std::string& pszSpriteFrameName); + static Skin* create(const std::string& pszFileName); public: /** @@ -48,8 +48,8 @@ public: */ Skin(); - virtual bool initWithSpriteFrameName(std::string_view spriteFrameName) override; - virtual bool initWithFile(std::string_view filename) override; + virtual bool initWithSpriteFrameName(const std::string& spriteFrameName) override; + virtual bool initWithFile(const std::string& filename) override; void updateArmatureTransform(); void updateTransform() override; @@ -73,7 +73,7 @@ public: virtual void setBone(Bone* bone); virtual Bone* getBone() const; - virtual std::string_view getDisplayName() const { return _displayName; } + virtual const std::string& getDisplayName() const { return _displayName; } protected: BaseData _skinData; diff --git a/extensions/cocostudio/CCSpriteFrameCacheHelper.cpp b/extensions/cocostudio/CCSpriteFrameCacheHelper.cpp index 66f70f7552..ffa14bbaff 100644 --- a/extensions/cocostudio/CCSpriteFrameCacheHelper.cpp +++ b/extensions/cocostudio/CCSpriteFrameCacheHelper.cpp @@ -50,7 +50,7 @@ void SpriteFrameCacheHelper::purge() _spriteFrameCacheHelper = nullptr; } -void SpriteFrameCacheHelper::retainSpriteFrames(std::string_view plistPath) +void SpriteFrameCacheHelper::retainSpriteFrames(const std::string& plistPath) { auto it = _usingSpriteFrames.find(plistPath); if (it != _usingSpriteFrames.end()) @@ -72,7 +72,7 @@ void SpriteFrameCacheHelper::retainSpriteFrames(std::string_view plistPath) _usingSpriteFrames[plistPath] = vec; } -void SpriteFrameCacheHelper::releaseSpriteFrames(std::string_view plistPath) +void SpriteFrameCacheHelper::releaseSpriteFrames(const std::string& plistPath) { auto it = _usingSpriteFrames.find(plistPath); if (it == _usingSpriteFrames.end()) @@ -89,13 +89,13 @@ void SpriteFrameCacheHelper::releaseSpriteFrames(std::string_view plistPath) _usingSpriteFrames.erase(it); } -void SpriteFrameCacheHelper::removeSpriteFrameFromFile(std::string_view plistPath) +void SpriteFrameCacheHelper::removeSpriteFrameFromFile(const std::string& plistPath) { SpriteFrameCache::getInstance()->removeSpriteFramesFromFile(plistPath); releaseSpriteFrames(plistPath); } -void SpriteFrameCacheHelper::addSpriteFrameFromFile(std::string_view plistPath, std::string_view imagePath) +void SpriteFrameCacheHelper::addSpriteFrameFromFile(const std::string& plistPath, const std::string& imagePath) { SpriteFrameCache::getInstance()->addSpriteFramesWithFile(plistPath, imagePath); retainSpriteFrames(plistPath); diff --git a/extensions/cocostudio/CCSpriteFrameCacheHelper.h b/extensions/cocostudio/CCSpriteFrameCacheHelper.h index 8f168b5452..a24be27049 100644 --- a/extensions/cocostudio/CCSpriteFrameCacheHelper.h +++ b/extensions/cocostudio/CCSpriteFrameCacheHelper.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -60,17 +60,17 @@ public: /** * @brief Add sprite frame to CCSpriteFrameCache, it will save display name and it's relative image name */ - void addSpriteFrameFromFile(std::string_view plistPath, std::string_view imagePath); - void removeSpriteFrameFromFile(std::string_view plistPath); + void addSpriteFrameFromFile(const std::string& plistPath, const std::string& imagePath); + void removeSpriteFrameFromFile(const std::string& plistPath); private: - void retainSpriteFrames(std::string_view plistPath); - void releaseSpriteFrames(std::string_view plistPath); + void retainSpriteFrames(const std::string& plistPath); + void releaseSpriteFrames(const std::string& plistPath); SpriteFrameCacheHelper(); ~SpriteFrameCacheHelper(); - hlookup::string_map> _usingSpriteFrames; + std::map> _usingSpriteFrames; static SpriteFrameCacheHelper* _spriteFrameCacheHelper; }; diff --git a/extensions/cocostudio/CocosStudioExport.h b/extensions/cocostudio/CocosStudioExport.h index dcc448bf40..89e1929c0d 100644 --- a/extensions/cocostudio/CocosStudioExport.h +++ b/extensions/cocostudio/CocosStudioExport.h @@ -31,6 +31,4 @@ # define CCS_DLL #endif -#include "base/hlookup.h" - #endif /* __CCEXTENSIONEXPORT_H__*/ \ No newline at end of file diff --git a/extensions/cocostudio/FlatBuffersSerialize.cpp b/extensions/cocostudio/FlatBuffersSerialize.cpp index bdd839b6e0..1ca0006455 100644 --- a/extensions/cocostudio/FlatBuffersSerialize.cpp +++ b/extensions/cocostudio/FlatBuffersSerialize.cpp @@ -141,8 +141,8 @@ void FlatBuffersSerialize::deleteFlatBufferBuilder() } } -std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFile(std::string_view xmlFileName, - std::string_view flatbuffersFileName) +std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFile(const std::string& xmlFileName, + const std::string& flatbuffersFileName) { std::string inFullpath = FileUtils::getInstance()->fullPathForFilename(xmlFileName).c_str(); @@ -157,7 +157,7 @@ std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFile(std::string_vi } std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLBuffer(std::string& xmlBuffer, - std::string_view flatbuffersFileName) + const std::string& flatbuffersFileName) { // xml parse pugi::xml_document document; @@ -168,7 +168,7 @@ std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLBuffer(std::string& return ""; } -std::string FlatBuffersSerialize::serializeFlatBuffersWithOpaque(void* opaque, std::string_view flatbuffersFileName) +std::string FlatBuffersSerialize::serializeFlatBuffersWithOpaque(void* opaque, const std::string& flatbuffersFileName) { auto thiz = FlatBuffersSerialize::getInstance(); @@ -451,9 +451,9 @@ int FlatBuffersSerialize::getResourceType(std::string key) return 1; } -std::string FlatBuffersSerialize::getGUIClassName(std::string_view name) +std::string FlatBuffersSerialize::getGUIClassName(const std::string& name) { - std::string convertedClassName; + std::string convertedClassName = name; if (name == "Panel") { convertedClassName = "Layout"; @@ -478,8 +478,6 @@ std::string FlatBuffersSerialize::getGUIClassName(std::string_view name) { convertedClassName = "TextBMFont"; } - else - convertedClassName = name; return convertedClassName; } @@ -1233,7 +1231,7 @@ flatbuffers::Offset FlatBuffersSerialize::createEasingD } /* create flat buffers with XML */ -FlatBufferBuilder* FlatBuffersSerialize::createFlatBuffersWithXMLFileForSimulator(std::string_view xmlFileName) +FlatBufferBuilder* FlatBuffersSerialize::createFlatBuffersWithXMLFileForSimulator(const std::string& xmlFileName) { std::string inFullpath = FileUtils::getInstance()->fullPathForFilename(xmlFileName); @@ -1522,9 +1520,9 @@ Offset FlatBuffersSerialize::createProjectNodeOptionsForSimu } /* Serialize language XML file to Flat Buffers file. */ -std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFileForLanguageData(std::string_view xmlFilePath, - std::string_view flatBuffersFilePath, - std::string_view languageName) +std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFileForLanguageData(const std::string& xmlFilePath, + const std::string& flatBuffersFilePath, + const std::string& languageName) { // Read and parse XML data file. if (!FileUtils::getInstance()->isFileExist(xmlFilePath)) @@ -1562,7 +1560,7 @@ std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFileForLanguageData hasKeyReaded = true; } // Record corresponding text. - else if (languageName == childElement.name()) + else if (strcmp(languageName.c_str(), childElement.name()) == 0) { const char* langText = childElement.text().as_string(); if (langText && langText[0] != '\0') diff --git a/extensions/cocostudio/FlatBuffersSerialize.h b/extensions/cocostudio/FlatBuffersSerialize.h index 1e592e14e9..21582b2c62 100644 --- a/extensions/cocostudio/FlatBuffersSerialize.h +++ b/extensions/cocostudio/FlatBuffersSerialize.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org @@ -105,14 +105,15 @@ public: void deleteFlatBufferBuilder(); - std::string test(std::string_view xmlFileName, std::string_view flatbuffersFileName); + std::string test(const std::string& xmlFileName, const std::string& flatbuffersFileName); /* serialize flat buffers with XML */ - static std::string serializeFlatBuffersWithXMLFile(std::string_view xmlFileName, - std::string_view flatbuffersFileName); + static std::string serializeFlatBuffersWithXMLFile(const std::string& xmlFileName, + const std::string& flatbuffersFileName); /* x-studio spec: serialize flat buffers with XML buffer */ - static std::string serializeFlatBuffersWithXMLBuffer(std::string& xmlBuffer, std::string_view flatbuffersFileName); - static std::string serializeFlatBuffersWithOpaque(void* opaque, std::string_view flatbuffersFileName); + static std::string serializeFlatBuffersWithXMLBuffer(std::string& xmlBuffer, + const std::string& flatbuffersFileName); + static std::string serializeFlatBuffersWithOpaque(void* opaque, const std::string& flatbuffersFileName); // NodeTree flatbuffers::Offset createNodeTree(pugi::xml_node objectData, std::string classType); @@ -137,11 +138,11 @@ public: /**/ int getResourceType(std::string key); - std::string getGUIClassName(std::string_view name); + std::string getGUIClassName(const std::string& name); std::string getWidgetReaderClassName(cocos2d::ui::Widget* widget); /* create flat buffers with XML */ - flatbuffers::FlatBufferBuilder* createFlatBuffersWithXMLFileForSimulator(std::string_view xmlFileName); + flatbuffers::FlatBufferBuilder* createFlatBuffersWithXMLFileForSimulator(const std::string& xmlFileName); flatbuffers::Offset createNodeTreeForSimulator(pugi::xml_node objectData, std::string classType); flatbuffers::Offset createProjectNodeOptionsForSimulator( @@ -150,9 +151,9 @@ public: std::string getCsdVersion() { return _csdVersion; } /* Serialize language XML file to Flat Buffers file. */ - std::string serializeFlatBuffersWithXMLFileForLanguageData(std::string_view xmlFilePath, - std::string_view flatBuffersFilePath, - std::string_view languageName); + std::string serializeFlatBuffersWithXMLFileForLanguageData(const std::string& xmlFilePath, + const std::string& flatBuffersFilePath, + const std::string& languageName); public: std::vector> _textures; diff --git a/extensions/cocostudio/SpineSkeletonDataCache.h b/extensions/cocostudio/SpineSkeletonDataCache.h index 51a3e1de4a..317c64d06a 100644 --- a/extensions/cocostudio/SpineSkeletonDataCache.h +++ b/extensions/cocostudio/SpineSkeletonDataCache.h @@ -39,7 +39,7 @@ public: void removeAllUnusedData(void); public: - hlookup::string_map _cacheTable; + std::map _cacheTable; void (*_reportError)(const char* pszFormat, ...); }; @@ -76,7 +76,7 @@ public: void removeAllUnusedData(void); public: - hlookup::string_map _cacheTable; + std::map _cacheTable; void (*_reportError)(const char* pszFormat, ...); }; diff --git a/extensions/cocostudio/TriggerMng.cpp b/extensions/cocostudio/TriggerMng.cpp index 39ccd44571..0ac9a3181d 100644 --- a/extensions/cocostudio/TriggerMng.cpp +++ b/extensions/cocostudio/TriggerMng.cpp @@ -505,7 +505,7 @@ ArmatureMovementDispatcher::~ArmatureMovementDispatcher(void) void ArmatureMovementDispatcher::animationEvent(Armature* armature, MovementEventType movementType, - std::string_view movementID) + const std::string& movementID) { for (auto iter = _mapEventAnimation->begin(); iter != _mapEventAnimation->end(); ++iter) { diff --git a/extensions/cocostudio/TriggerMng.h b/extensions/cocostudio/TriggerMng.h index 1830a67fe9..30474d2a02 100644 --- a/extensions/cocostudio/TriggerMng.h +++ b/extensions/cocostudio/TriggerMng.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -46,7 +46,7 @@ public: public: void addAnimationEventCallBack(cocos2d::Ref* pTarget, SEL_MovementEventCallFunc mecf); void removeAnnimationEventCallBack(cocos2d::Ref* pTarget, SEL_MovementEventCallFunc mecf); - void animationEvent(Armature* armature, MovementEventType movementType, std::string_view movementID); + void animationEvent(Armature* armature, MovementEventType movementType, const std::string& movementID); private: std::unordered_map* _mapEventAnimation; diff --git a/extensions/cocostudio/WidgetCallBackHandlerProtocol.cpp b/extensions/cocostudio/WidgetCallBackHandlerProtocol.cpp index d51149ba9d..a8a6b59e7d 100644 --- a/extensions/cocostudio/WidgetCallBackHandlerProtocol.cpp +++ b/extensions/cocostudio/WidgetCallBackHandlerProtocol.cpp @@ -4,15 +4,15 @@ namespace cocostudio { WidgetCallBackHandlerProtocol::~WidgetCallBackHandlerProtocol() {} -cocos2d::ui::Widget::ccWidgetTouchCallback WidgetCallBackHandlerProtocol::onLocateTouchCallback(std::string_view) +cocos2d::ui::Widget::ccWidgetTouchCallback WidgetCallBackHandlerProtocol::onLocateTouchCallback(const std::string&) { return nullptr; } -cocos2d::ui::Widget::ccWidgetClickCallback WidgetCallBackHandlerProtocol::onLocateClickCallback(std::string_view) +cocos2d::ui::Widget::ccWidgetClickCallback WidgetCallBackHandlerProtocol::onLocateClickCallback(const std::string&) { return nullptr; } -cocos2d::ui::Widget::ccWidgetEventCallback WidgetCallBackHandlerProtocol::onLocateEventCallback(std::string_view) +cocos2d::ui::Widget::ccWidgetEventCallback WidgetCallBackHandlerProtocol::onLocateEventCallback(const std::string&) { return nullptr; } diff --git a/extensions/cocostudio/WidgetCallBackHandlerProtocol.h b/extensions/cocostudio/WidgetCallBackHandlerProtocol.h index dd423e63ba..aae843e00e 100644 --- a/extensions/cocostudio/WidgetCallBackHandlerProtocol.h +++ b/extensions/cocostudio/WidgetCallBackHandlerProtocol.h @@ -36,9 +36,9 @@ class CCS_DLL WidgetCallBackHandlerProtocol public: virtual ~WidgetCallBackHandlerProtocol(); - virtual cocos2d::ui::Widget::ccWidgetTouchCallback onLocateTouchCallback(std::string_view callBackName); - virtual cocos2d::ui::Widget::ccWidgetClickCallback onLocateClickCallback(std::string_view callBackName); - virtual cocos2d::ui::Widget::ccWidgetEventCallback onLocateEventCallback(std::string_view callBackName); + virtual cocos2d::ui::Widget::ccWidgetTouchCallback onLocateTouchCallback(const std::string& callBackName); + virtual cocos2d::ui::Widget::ccWidgetClickCallback onLocateClickCallback(const std::string& callBackName); + virtual cocos2d::ui::Widget::ccWidgetEventCallback onLocateEventCallback(const std::string& callBackName); }; } // namespace cocostudio diff --git a/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.cpp b/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.cpp index 9202f0824c..00861efbd7 100644 --- a/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.cpp +++ b/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.cpp @@ -145,7 +145,7 @@ void ArmatureNodeReader::setPropsWithFlatBuffers(cocos2d::Node* node, const flat #if defined(CC_BUILD_WITH_DRANGBONES) && CC_BUILD_WITH_DRANGBONES auto filep = filepath.rfind('.'); if (filep != std::string::npos && strcmp(&filepath[filep], ".json") == 0) - { // Currently, adjust by file ext, regard as DragonBones 4.5/5.0 + { // Currently, adjust by file ext, regard as DragonBones 4.5/5.0 // 4.5 texture info is fixed as texture.png, texture.json // 5.o texture info is _tex.json _tex.png auto sharedFactory = dragonBones::CCFactory::getFactory(); @@ -230,7 +230,7 @@ cocos2d::Node* ArmatureNodeReader::createNodeWithFlatBuffers(const flatbuffers:: return node; } -std::string ArmatureNodeReader::getArmatureName(std::string_view exporJsonPath) +std::string ArmatureNodeReader::getArmatureName(const std::string& exporJsonPath) { // FileUtils.getFileData(exporJsonPath, "r", size) // need read armature name in exportJsonPath size_t end = exporJsonPath.find_last_of("."); @@ -241,5 +241,5 @@ std::string ArmatureNodeReader::getArmatureName(std::string_view exporJsonPath) if (start == -1) start = 0; - return std::string{exporJsonPath.substr(start, end - start)}; + return exporJsonPath.substr(start, end - start); } diff --git a/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.h b/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.h index d37f2652ba..3f7ae420b0 100644 --- a/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.h +++ b/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2014 cocos2d-x.org http://www.cocos2d-x.org @@ -59,7 +59,7 @@ public: cocos2d::Node* createNodeWithFlatBuffers(const flatbuffers::Table* nodeOptions) override; private: - std::string getArmatureName(std::string_view exporJsonPath); + std::string getArmatureName(const std::string& exporJsonPath); }; #endif /* defined(__ARMATURENODEREADER_H_) */ diff --git a/extensions/cocostudio/WidgetReader/ImageViewReader/ImageViewReader.cpp b/extensions/cocostudio/WidgetReader/ImageViewReader/ImageViewReader.cpp index f015d67a9f..6e417fcca6 100644 --- a/extensions/cocostudio/WidgetReader/ImageViewReader/ImageViewReader.cpp +++ b/extensions/cocostudio/WidgetReader/ImageViewReader/ImageViewReader.cpp @@ -111,7 +111,7 @@ void ImageViewReader::setPropsFromJsonDictionary(Widget* widget, const rapidjson const rapidjson::Value& imageFileNameDic = DICTOOL->getSubDictionary_json(options, P_FileNameData); int imageFileNameType = DICTOOL->getIntValue_json(imageFileNameDic, P_ResourceType); - std::string_view imageFilePath = DICTOOL->getStringValue_json(imageFileNameDic, P_Path); + const std::string& imageFilePath = DICTOOL->getStringValue_json(imageFileNameDic, P_Path); if (!imageFilePath.empty()) { diff --git a/extensions/cocostudio/WidgetReader/NodeReaderProtocol.cpp b/extensions/cocostudio/WidgetReader/NodeReaderProtocol.cpp index 5af14ee111..24997d4a98 100644 --- a/extensions/cocostudio/WidgetReader/NodeReaderProtocol.cpp +++ b/extensions/cocostudio/WidgetReader/NodeReaderProtocol.cpp @@ -30,7 +30,7 @@ static cocos2d::Node* createArmatureNode() return cocostudio::Armature::create(); } -static cocos2d::ParticleSystemQuad* createParticleSystemQuad(std::string_view path) +static cocos2d::ParticleSystemQuad* createParticleSystemQuad(const std::string& path) { return cocos2d::ParticleSystemQuad::create(path); } @@ -56,13 +56,13 @@ namespace wext { bool (*onBeforeLoadObjectAsset)(cocos2d::Node*, cocos2d::ResourceData& assets, - int index /*= 0*/) = &onLoadObjectAssetDummy; + int index /*= 0*/) = &onLoadObjectAssetDummy; bool (*onAfterLoadObjectAsset)(cocos2d::Node*, cocos2d::ResourceData& assets, - int index /*= 0*/) = &onLoadObjectAssetDummy; -void (*onLoadSpriteFramesWithFile)(std::string& file) = nullptr; -void (*onNestingNodeLoading)(std::string_view filePath) = nullptr; -void (*onNestingNodeLoaded)(cocos2d::Node*, std::string_view filePath) = nullptr; + int index /*= 0*/) = &onLoadObjectAssetDummy; +void (*onLoadSpriteFramesWithFile)(std::string& file) = nullptr; +void (*onNestingNodeLoading)(const std::string& filePath) = nullptr; +void (*onNestingNodeLoaded)(cocos2d::Node*, const std::string& filePath) = nullptr; cocos2d::Node* (*aNode)(); cocos2d::ui::Widget* (*aWidget)(); cocos2d::Sprite* (*aSprite)(); @@ -79,7 +79,7 @@ cocos2d::ui::Layout* (*aLayout)(); cocos2d::ui::ScrollView* (*aScrollView)(); cocos2d::ui::ListView* (*aListView)(); cocos2d::ui::PageView* (*aPageView)(); -cocos2d::ParticleSystemQuad* (*aParticleSystemQuad)(std::string_view); +cocos2d::ParticleSystemQuad* (*aParticleSystemQuad)(const std::string&); cocos2d::Node* (*aArmatureNode)(); cocostudio::timeline::SkeletonNode* (*aSkeletonNode)(); cocostudio::timeline::BoneNode* (*aBoneNode)(); @@ -137,7 +137,7 @@ cocos2d::ResourceData cocos2d::wext::makeResourceData(const flatbuffers::Resourc return fileData; } -cocos2d::ResourceData cocos2d::wext::makeResourceData(std::string_view path, int type) +cocos2d::ResourceData cocos2d::wext::makeResourceData(const std::string& path, int type) { cocos2d::ResourceData fileData; fileData.file = path; diff --git a/extensions/cocostudio/WidgetReader/NodeReaderProtocol.h b/extensions/cocostudio/WidgetReader/NodeReaderProtocol.h index ad10606f44..7276307498 100644 --- a/extensions/cocostudio/WidgetReader/NodeReaderProtocol.h +++ b/extensions/cocostudio/WidgetReader/NodeReaderProtocol.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2014 cocos2d-x.org http://www.cocos2d-x.org @@ -141,7 +141,7 @@ CC_DLL extern APP_LOGERROR_FUNC getAppErrorLogFunc(); CCS_DLL extern void (*onLoadSpriteFramesWithFile)(std::string& file); CCS_DLL extern cocos2d::ResourceData makeResourceData(const flatbuffers::ResourceData* data); -CCS_DLL extern cocos2d::ResourceData makeResourceData(std::string_view path, int type = 0); +CCS_DLL extern cocos2d::ResourceData makeResourceData(const std::string& path, int type = 0); CCS_DLL extern cocos2d::ResourceData makeResourceData(std::string&& path, int type = 0); CCS_DLL extern void resetReaderAllHooks(); @@ -168,7 +168,7 @@ CCS_DLL extern cocos2d::ui::PageView* (*aPageView)(); CCS_DLL extern cocos2d::Node* (*aArmatureNode)(); CCS_DLL extern cocostudio::timeline::SkeletonNode* (*aSkeletonNode)(); CCS_DLL extern cocostudio::timeline::BoneNode* (*aBoneNode)(); -CCS_DLL extern cocos2d::ParticleSystemQuad* (*aParticleSystemQuad)(std::string_view); +CCS_DLL extern cocos2d::ParticleSystemQuad* (*aParticleSystemQuad)(const std::string&); CCS_DLL extern cocos2d::Node* (*aNestingNode)(std::string); ///// 3d objects ///// diff --git a/extensions/cocostudio/WidgetReader/TextAtlasReader/TextAtlasReader.cpp b/extensions/cocostudio/WidgetReader/TextAtlasReader/TextAtlasReader.cpp index 61e22265d9..161a86263c 100644 --- a/extensions/cocostudio/WidgetReader/TextAtlasReader/TextAtlasReader.cpp +++ b/extensions/cocostudio/WidgetReader/TextAtlasReader/TextAtlasReader.cpp @@ -97,7 +97,7 @@ void TextAtlasReader::setPropsFromJsonDictionary(Widget* widget, const rapidjson { WidgetReader::setPropsFromJsonDictionary(widget, options); - std::string_view jsonPath = GUIReader::getInstance()->getFilePath(); + std::string jsonPath = GUIReader::getInstance()->getFilePath(); TextAtlas* labelAtlas = static_cast(widget); // bool sv = DICTOOL->checkObjectExist_json(options, P_StringValue); @@ -112,7 +112,7 @@ void TextAtlasReader::setPropsFromJsonDictionary(Widget* widget, const rapidjson { case 0: { - std::string tp_c{jsonPath}; + std::string tp_c = jsonPath; const char* cmfPath = DICTOOL->getStringValue_json(cmftDic, P_Path); const char* cmf_tp = tp_c.append(cmfPath).c_str(); labelAtlas->setProperty(DICTOOL->getStringValue_json(options, P_StringValue, "12345678"), cmf_tp, diff --git a/extensions/cocostudio/WidgetReader/TextBMFontReader/TextBMFontReader.cpp b/extensions/cocostudio/WidgetReader/TextBMFontReader/TextBMFontReader.cpp index 3ee6d35727..fffff874b8 100644 --- a/extensions/cocostudio/WidgetReader/TextBMFontReader/TextBMFontReader.cpp +++ b/extensions/cocostudio/WidgetReader/TextBMFontReader/TextBMFontReader.cpp @@ -82,7 +82,7 @@ void TextBMFontReader::setPropsFromJsonDictionary(Widget* widget, const rapidjso { WidgetReader::setPropsFromJsonDictionary(widget, options); - std::string_view jsonPath = GUIReader::getInstance()->getFilePath(); + std::string jsonPath = GUIReader::getInstance()->getFilePath(); TextBMFont* labelBMFont = static_cast(widget); @@ -92,7 +92,7 @@ void TextBMFontReader::setPropsFromJsonDictionary(Widget* widget, const rapidjso { case 0: { - std::string tp_c{jsonPath}; + std::string tp_c = jsonPath; const char* cmfPath = DICTOOL->getStringValue_json(cmftDic, P_Path); const char* cmf_tp = tp_c.append(cmfPath).c_str(); labelBMFont->setFntFile(cmf_tp); diff --git a/extensions/cocostudio/WidgetReader/TextFieldReader/TextFieldReader.cpp b/extensions/cocostudio/WidgetReader/TextFieldReader/TextFieldReader.cpp index e63761291a..484dca151f 100644 --- a/extensions/cocostudio/WidgetReader/TextFieldReader/TextFieldReader.cpp +++ b/extensions/cocostudio/WidgetReader/TextFieldReader/TextFieldReader.cpp @@ -101,9 +101,9 @@ void TextFieldReader::setPropsFromJsonDictionary(Widget* widget, const rapidjson textField->setFontSize(DICTOOL->getIntValue_json(options, P_FontSize, 20)); - std::string fontFilePath{GUIReader::getInstance()->getFilePath()}; - auto fontName = DICTOOL->getStringValue_json(options, P_FontName, ""); - fontFilePath.append(fontName); + std::string jsonPath = GUIReader::getInstance()->getFilePath(); + std::string fontName = DICTOOL->getStringValue_json(options, P_FontName, ""); + std::string fontFilePath = jsonPath.append(fontName); if (FileUtils::getInstance()->isFileExist(fontFilePath)) textField->setFontName(fontFilePath); else diff --git a/extensions/cocostudio/WidgetReader/TextReader/TextReader.cpp b/extensions/cocostudio/WidgetReader/TextReader/TextReader.cpp index 05624cde11..a42748e5e2 100644 --- a/extensions/cocostudio/WidgetReader/TextReader/TextReader.cpp +++ b/extensions/cocostudio/WidgetReader/TextReader/TextReader.cpp @@ -57,7 +57,7 @@ void TextReader::setPropsFromBinary(cocos2d::ui::Widget* widget, CocoLoader* coc Text* label = static_cast(widget); - std::string binaryFilePath{GUIReader::getInstance()->getFilePath()}; + std::string binaryFilePath = GUIReader::getInstance()->getFilePath(); for (int i = 0; i < cocoNode->GetChildNum(); ++i) { @@ -96,7 +96,7 @@ void TextReader::setPropsFromJsonDictionary(Widget* widget, const rapidjson::Val { WidgetReader::setPropsFromJsonDictionary(widget, options); - std::string fontFilePath{GUIReader::getInstance()->getFilePath()}; + std::string jsonPath = GUIReader::getInstance()->getFilePath(); Text* label = static_cast(widget); bool touchScaleChangeAble = DICTOOL->getBooleanValue_json(options, P_TouchScaleEnable); @@ -106,9 +106,9 @@ void TextReader::setPropsFromJsonDictionary(Widget* widget, const rapidjson::Val label->setFontSize(DICTOOL->getIntValue_json(options, P_FontSize, 20)); - auto fontName = DICTOOL->getStringValue_json(options, P_FontName, ""); + std::string fontName = DICTOOL->getStringValue_json(options, P_FontName, ""); - fontFilePath.append(fontName); + std::string fontFilePath = jsonPath.append(fontName); if (FileUtils::getInstance()->isFileExist(fontFilePath)) { label->setFontName(fontFilePath); diff --git a/extensions/cocostudio/WidgetReader/WidgetReader.cpp b/extensions/cocostudio/WidgetReader/WidgetReader.cpp index 14dcd1be8d..e30e04d1c2 100644 --- a/extensions/cocostudio/WidgetReader/WidgetReader.cpp +++ b/extensions/cocostudio/WidgetReader/WidgetReader.cpp @@ -98,9 +98,9 @@ WidgetReader::WidgetReader() , _opacity(255) , _isAdaptScreen(false) { - valueToInt = [=](std::string_view str) -> int { return atoi(str.data()); }; + valueToInt = [=](const std::string& str) -> int { return atoi(str.c_str()); }; - valueToBool = [=](std::string_view str) -> bool { + valueToBool = [=](const std::string& str) -> bool { int intValue = valueToInt(str); if (1 == intValue) { @@ -112,7 +112,7 @@ WidgetReader::WidgetReader() } }; - valueToFloat = [=](std::string_view str) -> float { return utils::atof(str.data()); }; + valueToFloat = [=](const std::string& str) -> float { return utils::atof(str.c_str()); }; } WidgetReader::~WidgetReader() {} @@ -303,17 +303,17 @@ void WidgetReader::endSetBasicProperties(Widget* widget) } std::string WidgetReader::getResourcePath(const rapidjson::Value& dict, - std::string_view key, + const std::string& key, cocos2d::ui::Widget::TextureResType texType) { - std::string_view jsonPath = GUIReader::getInstance()->getFilePath(); - const char* imageFileName = DICTOOL->getStringValue_json(dict, key.data()); + std::string jsonPath = GUIReader::getInstance()->getFilePath(); + const char* imageFileName = DICTOOL->getStringValue_json(dict, key.c_str()); std::string imageFileName_tp; if (nullptr != imageFileName) { if (texType == ui::Widget::TextureResType::LOCAL) { - imageFileName_tp.append(jsonPath).append(imageFileName); + imageFileName_tp = jsonPath + imageFileName; } else if (texType == ui::Widget::TextureResType::PLIST) { @@ -339,14 +339,14 @@ std::string WidgetReader::getResourcePath(CocoLoader* cocoLoader, return ""; } - std::string_view binaryPath = GUIReader::getInstance()->getFilePath(); + std::string binaryPath = GUIReader::getInstance()->getFilePath(); std::string imageFileName_tp; if (!backgroundValue.empty()) { if (texType == ui::Widget::TextureResType::LOCAL) { - imageFileName_tp.append(binaryPath).append(backgroundValue); + imageFileName_tp = binaryPath + backgroundValue; } else if (texType == ui::Widget::TextureResType::PLIST) { @@ -940,19 +940,20 @@ Node* WidgetReader::createNodeWithFlatBuffers(const flatbuffers::Table* widgetOp return widget; } -std::string WidgetReader::getResourcePath(std::string_view path, cocos2d::ui::Widget::TextureResType texType) +std::string WidgetReader::getResourcePath(const std::string& path, cocos2d::ui::Widget::TextureResType texType) { - std::string_view filePath = GUIReader::getInstance()->getFilePath(); + std::string filePath = GUIReader::getInstance()->getFilePath(); + const char* imageFileName = path.c_str(); std::string imageFileName_tp; - if (!path.empty()) + if (nullptr != imageFileName && 0 != strcmp("", imageFileName)) { if (texType == ui::Widget::TextureResType::LOCAL) { - imageFileName_tp.append(filePath).append(path); + imageFileName_tp = filePath + imageFileName; } else if (texType == ui::Widget::TextureResType::PLIST) { - imageFileName_tp.assign(path); + imageFileName_tp = imageFileName; } else { diff --git a/extensions/cocostudio/WidgetReader/WidgetReader.h b/extensions/cocostudio/WidgetReader/WidgetReader.h index 0b9a86316b..fb5e60d3d9 100644 --- a/extensions/cocostudio/WidgetReader/WidgetReader.h +++ b/extensions/cocostudio/WidgetReader/WidgetReader.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2014 cocos2d-x.org http://www.cocos2d-x.org @@ -66,7 +66,7 @@ public: protected: std::string getResourcePath(const rapidjson::Value& dict, - std::string_view key, + const std::string& key, cocos2d::ui::Widget::TextureResType texType); void setAnchorPointForWidget(cocos2d::ui::Widget* widget, const rapidjson::Value& options); @@ -74,14 +74,14 @@ protected: stExpCocoNode* pCocoNode, cocos2d::ui::Widget::TextureResType texType); - std::string getResourcePath(std::string_view path, cocos2d::ui::Widget::TextureResType texType); + std::string getResourcePath(const std::string& path, cocos2d::ui::Widget::TextureResType texType); void beginSetBasicProperties(cocos2d::ui::Widget* widget); void endSetBasicProperties(cocos2d::ui::Widget* widget); - std::function valueToInt; - std::function valueToBool; - std::function valueToFloat; + std::function valueToInt; + std::function valueToBool; + std::function valueToFloat; float _sizePercentX; float _sizePercentY; diff --git a/extensions/fairygui/GTextInput.cpp b/extensions/fairygui/GTextInput.cpp index 902fc4be52..3a9117675b 100644 --- a/extensions/fairygui/GTextInput.cpp +++ b/extensions/fairygui/GTextInput.cpp @@ -122,7 +122,7 @@ void GTextInput::editBoxReturn(cocos2d::ui::EditBox * editBox) // dispatchEvent(UIEventType::Submit); } -void GTextInput::editBoxTextChanged(cocos2d::ui::EditBox* editBox, std::string_view /*text*/) +void GTextInput::editBoxTextChanged(cocos2d::ui::EditBox* editBox, const std::string& text) { _text.clear(); _text.append(_input->getText()); diff --git a/extensions/fairygui/GTextInput.h b/extensions/fairygui/GTextInput.h index 7741843e0c..8ce76371ce 100644 --- a/extensions/fairygui/GTextInput.h +++ b/extensions/fairygui/GTextInput.h @@ -36,7 +36,7 @@ protected: virtual void setTextFieldText() override; virtual void editBoxReturn(cocos2d::ui::EditBox* editBox) override; - virtual void editBoxTextChanged(cocos2d::ui::EditBox* editBox, std::string_view text) override; + virtual void editBoxTextChanged(cocos2d::ui::EditBox* editBox, const std::string& text) override; private: FUIInput* _input; diff --git a/extensions/fairygui/ScrollPane.cpp b/extensions/fairygui/ScrollPane.cpp index 7e25cbb043..f976666c30 100644 --- a/extensions/fairygui/ScrollPane.cpp +++ b/extensions/fairygui/ScrollPane.cpp @@ -722,13 +722,13 @@ void ScrollPane::changeContentSizeOnScrolling(float deltaWidth, float deltaHeigh if (deltaWidth != 0 && isRightmost) { _xPos = _overlapSize.width; - _container->setPositionX(-_xPos); + _container->setPositionX(_container->getPositionX() - _xPos); } if (deltaHeight != 0 && isBottom) { _yPos = _overlapSize.height; - _container->setPositionY2(-_yPos); + _container->setPositionY2(_container->getPositionY2() - _yPos); } } diff --git a/extensions/fairygui/UIPackage.cpp b/extensions/fairygui/UIPackage.cpp index bdd97c41d2..19e0ebb3dc 100644 --- a/extensions/fairygui/UIPackage.cpp +++ b/extensions/fairygui/UIPackage.cpp @@ -200,7 +200,7 @@ string UIPackage::getItemURL(const string& pkgName, const string& resName) return STD_STRING_EMPTY; } -PackageItem* UIPackage::getItemByURL(std::string_view url) +PackageItem* UIPackage::getItemByURL(const string& url) { if (url.size() == 0) return nullptr; @@ -214,22 +214,22 @@ PackageItem* UIPackage::getItemByURL(std::string_view url) { if (url.size() > 13) { - std::string pkgId{url.substr(5, 8)}; + string pkgId = url.substr(5, 8); UIPackage* pkg = getById(pkgId); if (pkg != nullptr) { - std::string srcId{url.substr(13)}; + string srcId = url.substr(13); return pkg->getItem(srcId); } } } else { - std::string pkgName{url.substr(pos1 + 2, pos2 - pos1 - 2)}; + string pkgName = url.substr(pos1 + 2, pos2 - pos1 - 2); UIPackage* pkg = getByName(pkgName); if (pkg != nullptr) { - std::string srcName{url.substr(pos2 + 1)}; + string srcName = url.substr(pos2 + 1); return pkg->getItemByName(srcName); } } @@ -274,7 +274,7 @@ void* UIPackage::getItemAsset(const std::string& pkgName, const std::string& res return nullptr; } -void* UIPackage::getItemAssetByURL(std::string_view url, PackageItemType type) +void* UIPackage::getItemAssetByURL(const std::string& url, PackageItemType type) { PackageItem* pi = UIPackage::getItemByURL(url); if (pi) diff --git a/extensions/fairygui/UIPackage.h b/extensions/fairygui/UIPackage.h index a2b0c754d4..041a86822a 100644 --- a/extensions/fairygui/UIPackage.h +++ b/extensions/fairygui/UIPackage.h @@ -25,10 +25,10 @@ public: static GObject* createObject(const std::string& pkgName, const std::string& resName); static GObject* createObjectFromURL(const std::string& url); static std::string getItemURL(const std::string& pkgName, const std::string& resName); - static PackageItem* getItemByURL(std::string_view url); + static PackageItem* getItemByURL(const std::string& url); static std::string normalizeURL(const std::string& url); static void* getItemAsset(const std::string& pkgName, const std::string& resName, PackageItemType type = PackageItemType::UNKNOWN); - static void* getItemAssetByURL(std::string_view url, PackageItemType type = PackageItemType::UNKNOWN); + static void* getItemAssetByURL(const std::string& url, PackageItemType type = PackageItemType::UNKNOWN); static cocos2d::Texture2D* getEmptyTexture() { return _emptyTexture; } const std::string& getId() const { return _id; } diff --git a/extensions/fairygui/display/FUIContainer.cpp b/extensions/fairygui/display/FUIContainer.cpp index 9676cf133e..3cd5ff0c97 100644 --- a/extensions/fairygui/display/FUIContainer.cpp +++ b/extensions/fairygui/display/FUIContainer.cpp @@ -496,14 +496,4 @@ void FUIContainer::visit(cocos2d::Renderer * renderer, const cocos2d::Mat4 & par Node::visit(renderer, parentTransform, parentFlags); } -void FUIContainer::setGlobalZOrder(float globalZOrder) -{ - Node::setGlobalZOrder(globalZOrder); - if (_stencilClippingSupport && _stencilClippingSupport->_stencil) - { - _stencilClippingSupport->_stencil->setGlobalZOrder(globalZOrder); - } -} - - NS_FGUI_END diff --git a/extensions/fairygui/display/FUIContainer.h b/extensions/fairygui/display/FUIContainer.h index 6e991b5ba5..8f9958e83d 100644 --- a/extensions/fairygui/display/FUIContainer.h +++ b/extensions/fairygui/display/FUIContainer.h @@ -77,7 +77,6 @@ public: void onExit() override; void visit(cocos2d::Renderer *renderer, const cocos2d::Mat4 &parentTransform, uint32_t parentFlags) override; void setCameraMask(unsigned short mask, bool applyChildren = true) override; - void setGlobalZOrder(float globalZOrder) override; GObject* gOwner; private: diff --git a/extensions/fairygui/display/FUILabel.cpp b/extensions/fairygui/display/FUILabel.cpp index 9917d986a3..173acf1e58 100644 --- a/extensions/fairygui/display/FUILabel.cpp +++ b/extensions/fairygui/display/FUILabel.cpp @@ -118,7 +118,7 @@ void FUILabel::applyTextFormat() disableEffect(LabelEffect::SHADOW); } -bool FUILabel::setBMFontFilePath(std::string_view bmfontFilePath, const Vec2& imageOffset, float fontSize) +bool FUILabel::setBMFontFilePath(const std::string& bmfontFilePath, const Vec2& imageOffset, float fontSize) { BitmapFont* bmFont = (BitmapFont*)UIPackage::getItemAssetByURL(bmfontFilePath, PackageItemType::FONT); if (bmFont == nullptr) diff --git a/extensions/fairygui/display/FUILabel.h b/extensions/fairygui/display/FUILabel.h index 6733431730..0f9448dff3 100644 --- a/extensions/fairygui/display/FUILabel.h +++ b/extensions/fairygui/display/FUILabel.h @@ -23,7 +23,7 @@ public: void setUnderlineColor(const cocos2d::Color3B& value); - virtual bool setBMFontFilePath(std::string_view bmfontFilePath, const cocos2d::Vec2& imageOffset = cocos2d::Vec2::ZERO, float fontSize = 0) override; + virtual bool setBMFontFilePath(const std::string& bmfontFilePath, const cocos2d::Vec2& imageOffset = cocos2d::Vec2::ZERO, float fontSize = 0) override; void setGrayed(bool value); protected: diff --git a/extensions/fairygui/display/FUIRichText.cpp b/extensions/fairygui/display/FUIRichText.cpp index e98495b7b0..8e41ead1aa 100644 --- a/extensions/fairygui/display/FUIRichText.cpp +++ b/extensions/fairygui/display/FUIRichText.cpp @@ -76,7 +76,7 @@ static float stripTrailingWhitespace(const std::vector& row) { if (!row.empty()) { if (auto label = dynamic_cast(row.back())) { const auto width = label->getContentSize().width; - std::string str{label->getString()}; + auto str = label->getString(); rtrim(str); if (label->getString() != str) { label->setString(str); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_3d_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_3d_auto.cpp index 6a9652abdc..73e05e7f3c 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_3d_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_3d_auto.cpp @@ -32,12 +32,12 @@ int lua_cocos2dx_3d_Animation3D_initWithFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Animation3D:initWithFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Animation3D:initWithFile"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Animation3D:initWithFile"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Animation3D:initWithFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Animation3D_initWithFile'", nullptr); @@ -172,8 +172,8 @@ int lua_cocos2dx_3d_Animation3D_create(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Animation3D:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Animation3D:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Animation3D_create'", nullptr); @@ -185,10 +185,10 @@ int lua_cocos2dx_3d_Animation3D_create(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Animation3D:create"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Animation3D:create"); + std::string arg0; + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Animation3D:create"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Animation3D:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Animation3D_create'", nullptr); @@ -1341,18 +1341,18 @@ int lua_cocos2dx_3d_TextureCube_create(lua_State* tolua_S) if (argc == 6) { - std::string_view arg0; - std::string_view arg1; - std::string_view arg2; - std::string_view arg3; - std::string_view arg4; - std::string_view arg5; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TextureCube:create"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.TextureCube:create"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.TextureCube:create"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "cc.TextureCube:create"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.TextureCube:create"); - ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "cc.TextureCube:create"); + std::string arg0; + std::string arg1; + std::string arg2; + std::string arg3; + std::string arg4; + std::string arg5; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TextureCube:create"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.TextureCube:create"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.TextureCube:create"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "cc.TextureCube:create"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.TextureCube:create"); + ok &= luaval_to_std_string(tolua_S, 7,&arg5, "cc.TextureCube:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_TextureCube_create'", nullptr); @@ -1641,8 +1641,8 @@ int lua_cocos2dx_3d_BillBoard_create(lua_State* tolua_S) { if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.BillBoard:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.BillBoard:create"); if (!ok) { break; } cocos2d::BillBoard* ret = cocos2d::BillBoard::create(arg0); object_to_luaval(tolua_S, "cc.BillBoard",(cocos2d::BillBoard*)ret); @@ -1654,8 +1654,8 @@ int lua_cocos2dx_3d_BillBoard_create(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.BillBoard:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.BillBoard:create"); if (!ok) { break; } cocos2d::BillBoard::Mode arg1; ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "cc.BillBoard:create"); @@ -1693,8 +1693,8 @@ int lua_cocos2dx_3d_BillBoard_create(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.BillBoard:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.BillBoard:create"); if (!ok) { break; } cocos2d::Rect arg1; ok &= luaval_to_rect(tolua_S, 3, &arg1, "cc.BillBoard:create"); @@ -1709,8 +1709,8 @@ int lua_cocos2dx_3d_BillBoard_create(lua_State* tolua_S) { if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.BillBoard:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.BillBoard:create"); if (!ok) { break; } cocos2d::Rect arg1; ok &= luaval_to_rect(tolua_S, 3, &arg1, "cc.BillBoard:create"); @@ -2071,8 +2071,8 @@ int lua_cocos2dx_3d_Mesh_getName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Mesh_getName'", nullptr); return 0; } - std::string_view ret = cobj->getName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Mesh:getName",argc, 0); @@ -2325,9 +2325,9 @@ int lua_cocos2dx_3d_Mesh_setName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Mesh:setName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Mesh:setName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Mesh_setName'", nullptr); @@ -2938,9 +2938,9 @@ int lua_cocos2dx_3d_Skeleton3D_getBoneByName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Skeleton3D:getBoneByName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Skeleton3D:getBoneByName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Skeleton3D_getBoneByName'", nullptr); @@ -3392,24 +3392,24 @@ int lua_cocos2dx_3d_Skybox_init(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 6) { - std::string_view arg0; - std::string_view arg1; - std::string_view arg2; - std::string_view arg3; - std::string_view arg4; - std::string_view arg5; + std::string arg0; + std::string arg1; + std::string arg2; + std::string arg3; + std::string arg4; + std::string arg5; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Skybox:init"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Skybox:init"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Skybox:init"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Skybox:init"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.Skybox:init"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.Skybox:init"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "cc.Skybox:init"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "cc.Skybox:init"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.Skybox:init"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.Skybox:init"); - ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "cc.Skybox:init"); + ok &= luaval_to_std_string(tolua_S, 7,&arg5, "cc.Skybox:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Skybox_init'", nullptr); @@ -3497,23 +3497,23 @@ int lua_cocos2dx_3d_Skybox_create(lua_State* tolua_S) { if (argc == 6) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Skybox:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Skybox:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Skybox:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Skybox:create"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.Skybox:create"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.Skybox:create"); if (!ok) { break; } - std::string_view arg3; - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "cc.Skybox:create"); + std::string arg3; + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "cc.Skybox:create"); if (!ok) { break; } - std::string_view arg4; - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.Skybox:create"); + std::string arg4; + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.Skybox:create"); if (!ok) { break; } - std::string_view arg5; - ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "cc.Skybox:create"); + std::string arg5; + ok &= luaval_to_std_string(tolua_S, 7,&arg5, "cc.Skybox:create"); if (!ok) { break; } cocos2d::Skybox* ret = cocos2d::Skybox::create(arg0, arg1, arg2, arg3, arg4, arg5); object_to_luaval(tolua_S, "cc.Skybox",(cocos2d::Skybox*)ret); @@ -3685,8 +3685,8 @@ int lua_cocos2dx_3d_Sprite3D_setTexture(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite3D:setTexture"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite3D:setTexture"); if (!ok) { break; } cobj->setTexture(arg0); @@ -4321,9 +4321,9 @@ int lua_cocos2dx_3d_Sprite3D_getAttachNode(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite3D:getAttachNode"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite3D:getAttachNode"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Sprite3D_getAttachNode'", nullptr); @@ -4532,9 +4532,9 @@ int lua_cocos2dx_3d_Sprite3D_removeAttachNode(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite3D:removeAttachNode"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite3D:removeAttachNode"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Sprite3D_removeAttachNode'", nullptr); @@ -4679,9 +4679,9 @@ int lua_cocos2dx_3d_Sprite3D_getMeshByName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite3D:getMeshByName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite3D:getMeshByName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Sprite3D_getMeshByName'", nullptr); @@ -4719,8 +4719,8 @@ int lua_cocos2dx_3d_Sprite3D_create(lua_State* tolua_S) { if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite3D:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite3D:create"); if (!ok) { break; } cocos2d::Sprite3D* ret = cocos2d::Sprite3D::create(arg0); object_to_luaval(tolua_S, "cc.Sprite3D",(cocos2d::Sprite3D*)ret); @@ -4742,11 +4742,11 @@ int lua_cocos2dx_3d_Sprite3D_create(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite3D:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite3D:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Sprite3D:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Sprite3D:create"); if (!ok) { break; } cocos2d::Sprite3D* ret = cocos2d::Sprite3D::create(arg0, arg1); object_to_luaval(tolua_S, "cc.Sprite3D",(cocos2d::Sprite3D*)ret); @@ -4832,9 +4832,9 @@ int lua_cocos2dx_3d_Sprite3DCache_removeSprite3DData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite3DCache:removeSprite3DData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite3DCache:removeSprite3DData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Sprite3DCache_removeSprite3DData'", nullptr); @@ -5092,8 +5092,8 @@ int lua_cocos2dx_3d_Sprite3DMaterial_createWithFilename(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite3DMaterial:createWithFilename"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite3DMaterial:createWithFilename"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Sprite3DMaterial_createWithFilename'", nullptr); @@ -5316,9 +5316,9 @@ int lua_cocos2dx_3d_Terrain_initHeightMap(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Terrain:initHeightMap"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Terrain:initHeightMap"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Terrain_initHeightMap'", nullptr); @@ -5567,9 +5567,9 @@ int lua_cocos2dx_3d_Terrain_resetHeightMap(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Terrain:resetHeightMap"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Terrain:resetHeightMap"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Terrain_resetHeightMap'", nullptr); @@ -6026,8 +6026,8 @@ int lua_cocos2dx_3d_Terrain_getTerrainSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Terrain_getTerrainSize'", nullptr); return 0; } - cocos2d::Vec2 ret = cobj->getTerrainSize(); - vec2_to_luaval(tolua_S, ret); + cocos2d::Size ret = cobj->getTerrainSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Terrain:getTerrainSize",argc, 0); @@ -6221,9 +6221,9 @@ int lua_cocos2dx_3d_Terrain_setLightMap(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Terrain:setLightMap"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Terrain:setLightMap"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Terrain_setLightMap'", nullptr); @@ -6494,9 +6494,9 @@ int lua_cocos2dx_3d_Bundle3D_load(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Bundle3D:load"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Bundle3D:load"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Bundle3D_load'", nullptr); @@ -6544,10 +6544,10 @@ int lua_cocos2dx_3d_Bundle3D_loadSkinData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::SkinData* arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Bundle3D:loadSkinData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Bundle3D:loadSkinData"); #pragma warning NO CONVERSION TO NATIVE FOR SkinData* ok = false; @@ -6747,10 +6747,10 @@ int lua_cocos2dx_3d_Bundle3D_loadAnimationData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::Animation3DData* arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Bundle3D:loadAnimationData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Bundle3D:loadAnimationData"); #pragma warning NO CONVERSION TO NATIVE FOR Animation3DData* ok = false; @@ -6790,8 +6790,8 @@ int lua_cocos2dx_3d_Bundle3D_parseSamplerAddressMode(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Bundle3D:parseSamplerAddressMode"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Bundle3D:parseSamplerAddressMode"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Bundle3D_parseSamplerAddressMode'", nullptr); @@ -6896,9 +6896,9 @@ int lua_cocos2dx_3d_Bundle3D_parseGLDataType(lua_State* tolua_S) if (argc == 2) { - std::string_view arg0; + std::string arg0; int arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Bundle3D:parseGLDataType"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Bundle3D:parseGLDataType"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "cc.Bundle3D:parseGLDataType"); if(!ok) { diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_audioengine_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_audioengine_auto.cpp index fbc51b0072..c468bc15a4 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_audioengine_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_audioengine_auto.cpp @@ -184,8 +184,8 @@ int lua_cocos2dx_audioengine_AudioEngine_uncache(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AudioEngine:uncache"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AudioEngine:uncache"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_audioengine_AudioEngine_uncache'", nullptr); @@ -607,8 +607,8 @@ int lua_cocos2dx_audioengine_AudioEngine_preload(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AudioEngine:preload"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AudioEngine:preload"); if (!ok) { break; } std::function arg1; do { @@ -627,8 +627,8 @@ int lua_cocos2dx_audioengine_AudioEngine_preload(lua_State* tolua_S) { if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AudioEngine:preload"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AudioEngine:preload"); if (!ok) { break; } cocos2d::AudioEngine::preload(arg0); lua_settop(tolua_S, 1); @@ -697,8 +697,8 @@ int lua_cocos2dx_audioengine_AudioEngine_play2d(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AudioEngine:play2d"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AudioEngine:play2d"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_audioengine_AudioEngine_play2d'", nullptr); @@ -710,9 +710,9 @@ int lua_cocos2dx_audioengine_AudioEngine_play2d(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; bool arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AudioEngine:play2d"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AudioEngine:play2d"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.AudioEngine:play2d"); if(!ok) { @@ -725,10 +725,10 @@ int lua_cocos2dx_audioengine_AudioEngine_play2d(lua_State* tolua_S) } if (argc == 3) { - std::string_view arg0; + std::string arg0; bool arg1; double arg2; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AudioEngine:play2d"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AudioEngine:play2d"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.AudioEngine:play2d"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.AudioEngine:play2d"); if(!ok) @@ -742,11 +742,11 @@ int lua_cocos2dx_audioengine_AudioEngine_play2d(lua_State* tolua_S) } if (argc == 4) { - std::string_view arg0; + std::string arg0; bool arg1; double arg2; const cocos2d::AudioProfile* arg3; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AudioEngine:play2d"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AudioEngine:play2d"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.AudioEngine:play2d"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.AudioEngine:play2d"); ok &= luaval_to_object(tolua_S, 5, "cc.AudioProfile",&arg3, "cc.AudioEngine:play2d"); @@ -1035,8 +1035,8 @@ int lua_cocos2dx_audioengine_AudioEngine_getProfile(lua_State* tolua_S) { if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AudioEngine:getProfile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AudioEngine:getProfile"); if (!ok) { break; } cocos2d::AudioProfile* ret = cocos2d::AudioEngine::getProfile(arg0); object_to_luaval(tolua_S, "cc.AudioProfile",(cocos2d::AudioProfile*)ret); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp index 8a8ea3665c..ea1bbd26b6 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp @@ -300,9 +300,9 @@ int lua_cocos2dx_Console_delCommand(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Console:delCommand"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Console:delCommand"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Console_delCommand'", nullptr); @@ -497,9 +497,9 @@ int lua_cocos2dx_Console_setBindAddress(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Console:setBindAddress"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Console:setBindAddress"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Console_setBindAddress'", nullptr); @@ -962,8 +962,8 @@ int lua_cocos2dx_ShaderCache_newVertexShaderModule(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccb.ShaderCache:newVertexShaderModule"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccb.ShaderCache:newVertexShaderModule"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ShaderCache_newVertexShaderModule'", nullptr); @@ -998,8 +998,8 @@ int lua_cocos2dx_ShaderCache_newFragmentShaderModule(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccb.ShaderCache:newFragmentShaderModule"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccb.ShaderCache:newFragmentShaderModule"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ShaderCache_newFragmentShaderModule'", nullptr); @@ -1648,8 +1648,8 @@ int lua_cocos2dx_Texture2D_initWithString(lua_State* tolua_S) std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.Texture2D:initWithString"); arg0 = arg0_tmp.c_str(); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); if (!ok) { break; } double arg2; @@ -1668,16 +1668,16 @@ int lua_cocos2dx_Texture2D_initWithString(lua_State* tolua_S) std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.Texture2D:initWithString"); arg0 = arg0_tmp.c_str(); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); if (!ok) { break; } double arg2; ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Texture2D:initWithString"); if (!ok) { break; } - cocos2d::Vec2 arg3; - ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); + cocos2d::Size arg3; + ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); if (!ok) { break; } bool ret = cobj->initWithString(arg0, arg1, arg2, arg3); @@ -1692,16 +1692,16 @@ int lua_cocos2dx_Texture2D_initWithString(lua_State* tolua_S) std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.Texture2D:initWithString"); arg0 = arg0_tmp.c_str(); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); if (!ok) { break; } double arg2; ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Texture2D:initWithString"); if (!ok) { break; } - cocos2d::Vec2 arg3; - ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); + cocos2d::Size arg3; + ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); if (!ok) { break; } cocos2d::TextHAlignment arg4; @@ -1720,16 +1720,16 @@ int lua_cocos2dx_Texture2D_initWithString(lua_State* tolua_S) std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.Texture2D:initWithString"); arg0 = arg0_tmp.c_str(); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); if (!ok) { break; } double arg2; ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Texture2D:initWithString"); if (!ok) { break; } - cocos2d::Vec2 arg3; - ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); + cocos2d::Size arg3; + ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); if (!ok) { break; } cocos2d::TextHAlignment arg4; @@ -1752,16 +1752,16 @@ int lua_cocos2dx_Texture2D_initWithString(lua_State* tolua_S) std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.Texture2D:initWithString"); arg0 = arg0_tmp.c_str(); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); if (!ok) { break; } double arg2; ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Texture2D:initWithString"); if (!ok) { break; } - cocos2d::Vec2 arg3; - ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); + cocos2d::Size arg3; + ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); if (!ok) { break; } cocos2d::TextHAlignment arg4; @@ -1788,16 +1788,16 @@ int lua_cocos2dx_Texture2D_initWithString(lua_State* tolua_S) std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.Texture2D:initWithString"); arg0 = arg0_tmp.c_str(); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); if (!ok) { break; } double arg2; ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Texture2D:initWithString"); if (!ok) { break; } - cocos2d::Vec2 arg3; - ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); + cocos2d::Size arg3; + ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); if (!ok) { break; } cocos2d::TextHAlignment arg4; @@ -2062,8 +2062,8 @@ int lua_cocos2dx_Texture2D_getContentSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Texture2D_getContentSize'", nullptr); return 0; } - cocos2d::Vec2 ret = cobj->getContentSize(); - vec2_to_luaval(tolua_S, ret); + cocos2d::Size ret = cobj->getContentSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Texture2D:getContentSize",argc, 0); @@ -2463,8 +2463,8 @@ int lua_cocos2dx_Texture2D_getContentSizeInPixels(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Texture2D_getContentSizeInPixels'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getContentSizeInPixels(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getContentSizeInPixels(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Texture2D:getContentSizeInPixels",argc, 0); @@ -4259,9 +4259,9 @@ int lua_cocos2dx_Component_setName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Component:setName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Component:setName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Component_setName'", nullptr); @@ -4555,8 +4555,8 @@ int lua_cocos2dx_Component_getName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Component_getName'", nullptr); return 0; } - std::string_view ret = cobj->getName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Component:getName",argc, 0); @@ -4759,8 +4759,8 @@ int lua_cocos2dx_Node_addChild(lua_State* tolua_S) ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "cc.Node:addChild"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.Node:addChild"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.Node:addChild"); if (!ok) { break; } cobj->addChild(arg0, arg1, arg2); @@ -4814,8 +4814,8 @@ int lua_cocos2dx_Node_removeComponent(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Node:removeComponent"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Node:removeComponent"); if (!ok) { break; } bool ret = cobj->removeComponent(arg0); @@ -5454,9 +5454,9 @@ int lua_cocos2dx_Node_getChildByName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Node:getChildByName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Node:getChildByName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Node_getChildByName'", nullptr); @@ -7147,8 +7147,8 @@ int lua_cocos2dx_Node_getName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Node_getName'", nullptr); return 0; } - std::string_view ret = cobj->getName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Node:getName",argc, 0); @@ -8525,9 +8525,9 @@ int lua_cocos2dx_Node_removeChildByName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Node:removeChildByName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Node:removeChildByName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Node_removeChildByName'", nullptr); @@ -8539,10 +8539,10 @@ int lua_cocos2dx_Node_removeChildByName(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; bool arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Node:removeChildByName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Node:removeChildByName"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.Node:removeChildByName"); if(!ok) @@ -8564,59 +8564,6 @@ int lua_cocos2dx_Node_removeChildByName(lua_State* tolua_S) return 0; } -int lua_cocos2dx_Node_resetChild(lua_State* tolua_S) -{ - int argc = 0; - cocos2d::Node* cobj = nullptr; - bool ok = true; - -#if COCOS2D_DEBUG >= 1 - tolua_Error tolua_err; -#endif - - -#if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"cc.Node",0,&tolua_err)) goto tolua_lerror; -#endif - - cobj = (cocos2d::Node*)tolua_tousertype(tolua_S,1,0); - -#if COCOS2D_DEBUG >= 1 - if (!cobj) - { - tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_Node_resetChild'", nullptr); - return 0; - } -#endif - - argc = lua_gettop(tolua_S)-1; - if (argc == 2) - { - cocos2d::Node* arg0; - bool arg1; - - ok &= luaval_to_object(tolua_S, 2, "cc.Node",&arg0, "cc.Node:resetChild"); - - ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.Node:resetChild"); - if(!ok) - { - tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Node_resetChild'", nullptr); - return 0; - } - cobj->resetChild(arg0, arg1); - lua_settop(tolua_S, 1); - return 1; - } - luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Node:resetChild",argc, 2); - return 0; - -#if COCOS2D_DEBUG >= 1 - tolua_lerror: - tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_Node_resetChild'.",&tolua_err); -#endif - - return 0; -} int lua_cocos2dx_Node_setScheduler(lua_State* tolua_S) { int argc = 0; @@ -8980,9 +8927,9 @@ int lua_cocos2dx_Node_setName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Node:setName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Node:setName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Node_setName'", nullptr); @@ -9914,9 +9861,9 @@ int lua_cocos2dx_Node_isScheduled(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Node:isScheduled"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Node:isScheduled"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Node_isScheduled'", nullptr); @@ -10508,9 +10455,9 @@ int lua_cocos2dx_Node_getComponent(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Node:getComponent"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Node:getComponent"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Node_getComponent'", nullptr); @@ -10563,8 +10510,8 @@ int lua_cocos2dx_Node_getContentSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Node_getContentSize'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getContentSize(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getContentSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Node:getContentSize",argc, 0); @@ -11993,7 +11940,6 @@ int lua_register_cocos2dx_Node(lua_State* tolua_S) tolua_function(tolua_S,"getPhysicsBody",lua_cocos2dx_Node_getPhysicsBody); tolua_function(tolua_S,"getAnchorPointInPoints",lua_cocos2dx_Node_getAnchorPointInPoints); tolua_function(tolua_S,"removeChildByName",lua_cocos2dx_Node_removeChildByName); - tolua_function(tolua_S,"resetChild",lua_cocos2dx_Node_resetChild); tolua_function(tolua_S,"setScheduler",lua_cocos2dx_Node_setScheduler); tolua_function(tolua_S,"stopAllActions",lua_cocos2dx_Node_stopAllActions); tolua_function(tolua_S,"getSkewX",lua_cocos2dx_Node_getSkewX); @@ -12457,9 +12403,9 @@ int lua_cocos2dx_Scene_initWithSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.Scene:initWithSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.Scene:initWithSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Scene_initWithSize'", nullptr); @@ -12543,8 +12489,8 @@ int lua_cocos2dx_Scene_createWithSize(lua_State* tolua_S) if (argc == 1) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.Scene:createWithSize"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.Scene:createWithSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Scene_createWithSize'", nullptr); @@ -13132,8 +13078,8 @@ int lua_cocos2dx_GLView_getViewName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GLView_getViewName'", nullptr); return 0; } - std::string_view ret = cobj->getViewName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getViewName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.GLView:getViewName",argc, 0); @@ -13276,8 +13222,8 @@ int lua_cocos2dx_GLView_getFrameSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GLView_getFrameSize'", nullptr); return 0; } - cocos2d::Vec2 ret = cobj->getFrameSize(); - vec2_to_luaval(tolua_S, ret); + cocos2d::Size ret = cobj->getFrameSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.GLView:getFrameSize",argc, 0); @@ -13561,8 +13507,8 @@ int lua_cocos2dx_GLView_getDesignResolutionSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GLView_getDesignResolutionSize'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getDesignResolutionSize(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getDesignResolutionSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.GLView:getDesignResolutionSize",argc, 0); @@ -13598,8 +13544,8 @@ int lua_cocos2dx_GLView_setIcon(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 1) { - std::vector arg0; - ok &= luaval_to_std_vector_string_view(tolua_S, 2, &arg0, "cc.GLView:setIcon"); + std::vector arg0; + ok &= luaval_to_std_vector_string(tolua_S, 2, &arg0, "cc.GLView:setIcon"); if (!ok) { break; } cobj->setIcon(arg0); @@ -13610,8 +13556,8 @@ int lua_cocos2dx_GLView_setIcon(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.GLView:setIcon"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.GLView:setIcon"); if (!ok) { break; } cobj->setIcon(arg0); @@ -14155,9 +14101,9 @@ int lua_cocos2dx_GLView_setViewName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.GLView:setViewName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.GLView:setViewName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GLView_setViewName'", nullptr); @@ -14257,8 +14203,8 @@ int lua_cocos2dx_GLView_getVisibleSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GLView_getVisibleSize'", nullptr); return 0; } - cocos2d::Vec2 ret = cobj->getVisibleSize(); - vec2_to_luaval(tolua_S, ret); + cocos2d::Size ret = cobj->getVisibleSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.GLView:getVisibleSize",argc, 0); @@ -14765,8 +14711,8 @@ int lua_cocos2dx_Director_getWinSizeInPixels(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Director_getWinSizeInPixels'", nullptr); return 0; } - cocos2d::Vec2 ret = cobj->getWinSizeInPixels(); - vec2_to_luaval(tolua_S, ret); + cocos2d::Size ret = cobj->getWinSizeInPixels(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Director:getWinSizeInPixels",argc, 0); @@ -15103,8 +15049,8 @@ int lua_cocos2dx_Director_getWinSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Director_getWinSize'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getWinSize(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getWinSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Director:getWinSize",argc, 0); @@ -16217,53 +16163,6 @@ int lua_cocos2dx_Director_isNextDeltaTimeZero(lua_State* tolua_S) return 0; } -int lua_cocos2dx_Director_isChildrenIndexerEnabled(lua_State* tolua_S) -{ - int argc = 0; - cocos2d::Director* cobj = nullptr; - bool ok = true; - -#if COCOS2D_DEBUG >= 1 - tolua_Error tolua_err; -#endif - - -#if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"cc.Director",0,&tolua_err)) goto tolua_lerror; -#endif - - cobj = (cocos2d::Director*)tolua_tousertype(tolua_S,1,0); - -#if COCOS2D_DEBUG >= 1 - if (!cobj) - { - tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_Director_isChildrenIndexerEnabled'", nullptr); - return 0; - } -#endif - - argc = lua_gettop(tolua_S)-1; - if (argc == 0) - { - if(!ok) - { - tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Director_isChildrenIndexerEnabled'", nullptr); - return 0; - } - bool ret = cobj->isChildrenIndexerEnabled(); - tolua_pushboolean(tolua_S,(bool)ret); - return 1; - } - luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Director:isChildrenIndexerEnabled",argc, 0); - return 0; - -#if COCOS2D_DEBUG >= 1 - tolua_lerror: - tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_Director_isChildrenIndexerEnabled'.",&tolua_err); -#endif - - return 0; -} int lua_cocos2dx_Director_setClearColor(lua_State* tolua_S) { int argc = 0; @@ -16655,56 +16554,6 @@ int lua_cocos2dx_Director_setNotificationNode(lua_State* tolua_S) return 0; } -int lua_cocos2dx_Director_setChildrenIndexerEnabled(lua_State* tolua_S) -{ - int argc = 0; - cocos2d::Director* cobj = nullptr; - bool ok = true; - -#if COCOS2D_DEBUG >= 1 - tolua_Error tolua_err; -#endif - - -#if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"cc.Director",0,&tolua_err)) goto tolua_lerror; -#endif - - cobj = (cocos2d::Director*)tolua_tousertype(tolua_S,1,0); - -#if COCOS2D_DEBUG >= 1 - if (!cobj) - { - tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_Director_setChildrenIndexerEnabled'", nullptr); - return 0; - } -#endif - - argc = lua_gettop(tolua_S)-1; - if (argc == 1) - { - bool arg0; - - ok &= luaval_to_boolean(tolua_S, 2,&arg0, "cc.Director:setChildrenIndexerEnabled"); - if(!ok) - { - tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Director_setChildrenIndexerEnabled'", nullptr); - return 0; - } - cobj->setChildrenIndexerEnabled(arg0); - lua_settop(tolua_S, 1); - return 1; - } - luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Director:setChildrenIndexerEnabled",argc, 1); - return 0; - -#if COCOS2D_DEBUG >= 1 - tolua_lerror: - tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_Director_setChildrenIndexerEnabled'.",&tolua_err); -#endif - - return 0; -} int lua_cocos2dx_Director_drawScene(lua_State* tolua_S) { int argc = 0; @@ -17273,8 +17122,8 @@ int lua_cocos2dx_Director_getVisibleSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Director_getVisibleSize'", nullptr); return 0; } - cocos2d::Vec2 ret = cobj->getVisibleSize(); - vec2_to_luaval(tolua_S, ret); + cocos2d::Size ret = cobj->getVisibleSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Director:getVisibleSize",argc, 0); @@ -17804,7 +17653,6 @@ int lua_register_cocos2dx_Director(lua_State* tolua_S) tolua_function(tolua_S,"popToSceneStackLevel",lua_cocos2dx_Director_popToSceneStackLevel); tolua_function(tolua_S,"resume",lua_cocos2dx_Director_resume); tolua_function(tolua_S,"isNextDeltaTimeZero",lua_cocos2dx_Director_isNextDeltaTimeZero); - tolua_function(tolua_S,"isChildrenIndexerEnabled",lua_cocos2dx_Director_isChildrenIndexerEnabled); tolua_function(tolua_S,"setClearColor",lua_cocos2dx_Director_setClearColor); tolua_function(tolua_S,"endToLua",lua_cocos2dx_Director_end); tolua_function(tolua_S,"setOpenGLView",lua_cocos2dx_Director_setOpenGLView); @@ -17813,7 +17661,6 @@ int lua_register_cocos2dx_Director(lua_State* tolua_S) tolua_function(tolua_S,"getTotalFrames",lua_cocos2dx_Director_getTotalFrames); tolua_function(tolua_S,"runWithScene",lua_cocos2dx_Director_runWithScene); tolua_function(tolua_S,"setNotificationNode",lua_cocos2dx_Director_setNotificationNode); - tolua_function(tolua_S,"setChildrenIndexerEnabled",lua_cocos2dx_Director_setChildrenIndexerEnabled); tolua_function(tolua_S,"drawScene",lua_cocos2dx_Director_drawScene); tolua_function(tolua_S,"restart",lua_cocos2dx_Director_restart); tolua_function(tolua_S,"popScene",lua_cocos2dx_Director_popScene); @@ -20677,9 +20524,9 @@ int lua_cocos2dx_Image_initWithImageFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Image:initWithImageFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Image:initWithImageFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Image_initWithImageFile'", nullptr); @@ -20962,9 +20809,9 @@ int lua_cocos2dx_Image_saveToFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Image:saveToFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Image:saveToFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Image_saveToFile'", nullptr); @@ -20976,10 +20823,10 @@ int lua_cocos2dx_Image_saveToFile(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; bool arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Image:saveToFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Image:saveToFile"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.Image:saveToFile"); if(!ok) @@ -21218,8 +21065,8 @@ int lua_cocos2dx_PolygonInfo_getFilename(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_PolygonInfo_getFilename'", nullptr); return 0; } - std::string_view ret = cobj->getFilename(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getFilename(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.PolygonInfo:getFilename",argc, 0); @@ -21354,9 +21201,9 @@ int lua_cocos2dx_PolygonInfo_setFilename(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.PolygonInfo:setFilename"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.PolygonInfo:setFilename"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_PolygonInfo_setFilename'", nullptr); @@ -21756,9 +21603,9 @@ int lua_cocos2dx_AutoPolygon_constructor(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AutoPolygon:AutoPolygon"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AutoPolygon:AutoPolygon"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_AutoPolygon_constructor'", nullptr); @@ -22029,8 +21876,8 @@ int lua_cocos2dx_SpriteFrame_getOriginalSizeInPixels(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrame_getOriginalSizeInPixels'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getOriginalSizeInPixels(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getOriginalSizeInPixels(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.SpriteFrame:getOriginalSizeInPixels",argc, 0); @@ -22071,9 +21918,9 @@ int lua_cocos2dx_SpriteFrame_setOriginalSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.SpriteFrame:setOriginalSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.SpriteFrame:setOriginalSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrame_setOriginalSize'", nullptr); @@ -22360,8 +22207,8 @@ int lua_cocos2dx_SpriteFrame_initWithTextureFilename(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 5) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrame:initWithTextureFilename"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrame:initWithTextureFilename"); if (!ok) { break; } cocos2d::Rect arg1; @@ -22376,8 +22223,8 @@ int lua_cocos2dx_SpriteFrame_initWithTextureFilename(lua_State* tolua_S) ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.SpriteFrame:initWithTextureFilename"); if (!ok) { break; } - cocos2d::Vec2 arg4; - ok &= luaval_to_vec2(tolua_S, 6, &arg4, "cc.SpriteFrame:initWithTextureFilename"); + cocos2d::Size arg4; + ok &= luaval_to_size(tolua_S, 6, &arg4, "cc.SpriteFrame:initWithTextureFilename"); if (!ok) { break; } bool ret = cobj->initWithTextureFilename(arg0, arg1, arg2, arg3, arg4); @@ -22388,8 +22235,8 @@ int lua_cocos2dx_SpriteFrame_initWithTextureFilename(lua_State* tolua_S) ok = true; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrame:initWithTextureFilename"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrame:initWithTextureFilename"); if (!ok) { break; } cocos2d::Rect arg1; @@ -22501,8 +22348,8 @@ int lua_cocos2dx_SpriteFrame_initWithTexture(lua_State* tolua_S) ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.SpriteFrame:initWithTexture"); if (!ok) { break; } - cocos2d::Vec2 arg4; - ok &= luaval_to_vec2(tolua_S, 6, &arg4, "cc.SpriteFrame:initWithTexture"); + cocos2d::Size arg4; + ok &= luaval_to_size(tolua_S, 6, &arg4, "cc.SpriteFrame:initWithTexture"); if (!ok) { break; } bool ret = cobj->initWithTexture(arg0, arg1, arg2, arg3, arg4); @@ -22570,8 +22417,8 @@ int lua_cocos2dx_SpriteFrame_getOriginalSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrame_getOriginalSize'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getOriginalSize(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getOriginalSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.SpriteFrame:getOriginalSize",argc, 0); @@ -22897,9 +22744,9 @@ int lua_cocos2dx_SpriteFrame_setOriginalSizeInPixels(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.SpriteFrame:setOriginalSizeInPixels"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.SpriteFrame:setOriginalSizeInPixels"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrame_setOriginalSizeInPixels'", nullptr); @@ -23078,8 +22925,8 @@ int lua_cocos2dx_SpriteFrame_create(lua_State* tolua_S) { if (argc == 5) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrame:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrame:create"); if (!ok) { break; } cocos2d::Rect arg1; ok &= luaval_to_rect(tolua_S, 3, &arg1, "cc.SpriteFrame:create"); @@ -23090,8 +22937,8 @@ int lua_cocos2dx_SpriteFrame_create(lua_State* tolua_S) cocos2d::Vec2 arg3; ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.SpriteFrame:create"); if (!ok) { break; } - cocos2d::Vec2 arg4; - ok &= luaval_to_vec2(tolua_S, 6, &arg4, "cc.SpriteFrame:create"); + cocos2d::Size arg4; + ok &= luaval_to_size(tolua_S, 6, &arg4, "cc.SpriteFrame:create"); if (!ok) { break; } cocos2d::SpriteFrame* ret = cocos2d::SpriteFrame::create(arg0, arg1, arg2, arg3, arg4); object_to_luaval(tolua_S, "cc.SpriteFrame",(cocos2d::SpriteFrame*)ret); @@ -23103,8 +22950,8 @@ int lua_cocos2dx_SpriteFrame_create(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrame:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrame:create"); if (!ok) { break; } cocos2d::Rect arg1; ok &= luaval_to_rect(tolua_S, 3, &arg1, "cc.SpriteFrame:create"); @@ -23153,8 +23000,8 @@ int lua_cocos2dx_SpriteFrame_createWithTexture(lua_State* tolua_S) cocos2d::Vec2 arg3; ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.SpriteFrame:createWithTexture"); if (!ok) { break; } - cocos2d::Vec2 arg4; - ok &= luaval_to_vec2(tolua_S, 6, &arg4, "cc.SpriteFrame:createWithTexture"); + cocos2d::Size arg4; + ok &= luaval_to_size(tolua_S, 6, &arg4, "cc.SpriteFrame:createWithTexture"); if (!ok) { break; } cocos2d::SpriteFrame* ret = cocos2d::SpriteFrame::createWithTexture(arg0, arg1, arg2, arg3, arg4); object_to_luaval(tolua_S, "cc.SpriteFrame",(cocos2d::SpriteFrame*)ret); @@ -24339,9 +24186,9 @@ int lua_cocos2dx_Animation_addSpriteFrameWithFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Animation:addSpriteFrameWithFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Animation:addSpriteFrameWithFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Animation_addSpriteFrameWithFile'", nullptr); @@ -31478,12 +31325,12 @@ int lua_cocos2dx_UserDefault_getStringForKey(lua_State* tolua_S) std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.UserDefault:getStringForKey"); arg0 = arg0_tmp.c_str(); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.UserDefault:getStringForKey"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.UserDefault:getStringForKey"); if (!ok) { break; } - std::string_view ret = cobj->getStringForKey(arg0, arg1); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + std::string ret = cobj->getStringForKey(arg0, arg1); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } }while(0); @@ -31494,8 +31341,8 @@ int lua_cocos2dx_UserDefault_getStringForKey(lua_State* tolua_S) std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.UserDefault:getStringForKey"); arg0 = arg0_tmp.c_str(); if (!ok) { break; } - std::string_view ret = cobj->getStringForKey(arg0); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + std::string ret = cobj->getStringForKey(arg0); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } }while(0); @@ -31539,11 +31386,11 @@ int lua_cocos2dx_UserDefault_setStringForKey(lua_State* tolua_S) if (argc == 2) { const char* arg0; - std::string_view arg1; + std::string arg1; std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.UserDefault:setStringForKey"); arg0 = arg0_tmp.c_str(); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.UserDefault:setStringForKey"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.UserDefault:setStringForKey"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_UserDefault_setStringForKey'", nullptr); @@ -31651,8 +31498,8 @@ int lua_cocos2dx_UserDefault_setEncryptEnabled(lua_State* tolua_S) if (argc == 3) { bool arg0; - std::string_view arg1; - std::string_view arg2; + cxx17::string_view arg1; + cxx17::string_view arg2; ok &= luaval_to_boolean(tolua_S, 2,&arg0, "cc.UserDefault:setEncryptEnabled"); @@ -31996,9 +31843,9 @@ int lua_cocos2dx_FileUtils_fullPathForFilename(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:fullPathForFilename"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:fullPathForFilename"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_fullPathForFilename'", nullptr); @@ -32041,8 +31888,8 @@ int lua_cocos2dx_FileUtils_getStringFromFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:getStringFromFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:getStringFromFile"); if (!ok) { break; } std::function arg1; @@ -32061,8 +31908,8 @@ int lua_cocos2dx_FileUtils_getStringFromFile(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:getStringFromFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:getStringFromFile"); if (!ok) { break; } std::string ret = cobj->getStringFromFile(arg0); @@ -32201,8 +32048,8 @@ int lua_cocos2dx_FileUtils_removeFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:removeFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:removeFile"); if (!ok) { break; } std::function arg1; @@ -32221,8 +32068,8 @@ int lua_cocos2dx_FileUtils_removeFile(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:removeFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:removeFile"); if (!ok) { break; } bool ret = cobj->removeFile(arg0); @@ -32269,10 +32116,10 @@ int lua_cocos2dx_FileUtils_listFilesRecursivelyAsync(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; std::function)> arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:listFilesRecursivelyAsync"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:listFilesRecursivelyAsync"); do { // Lambda binding for lua is not supported. @@ -32326,9 +32173,9 @@ int lua_cocos2dx_FileUtils_isAbsolutePath(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:isAbsolutePath"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:isAbsolutePath"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_isAbsolutePath'", nullptr); @@ -32371,16 +32218,16 @@ int lua_cocos2dx_FileUtils_renameFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 4) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:renameFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:renameFile"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:renameFile"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:renameFile"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.FileUtils:renameFile"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.FileUtils:renameFile"); if (!ok) { break; } std::function arg3; @@ -32399,16 +32246,16 @@ int lua_cocos2dx_FileUtils_renameFile(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:renameFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:renameFile"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:renameFile"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:renameFile"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.FileUtils:renameFile"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.FileUtils:renameFile"); if (!ok) { break; } bool ret = cobj->renameFile(arg0, arg1, arg2); @@ -32419,12 +32266,12 @@ int lua_cocos2dx_FileUtils_renameFile(lua_State* tolua_S) ok = true; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:renameFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:renameFile"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:renameFile"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:renameFile"); if (!ok) { break; } bool ret = cobj->renameFile(arg0, arg1); @@ -32435,12 +32282,12 @@ int lua_cocos2dx_FileUtils_renameFile(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:renameFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:renameFile"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:renameFile"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:renameFile"); if (!ok) { break; } std::function arg2; @@ -32542,9 +32389,9 @@ int lua_cocos2dx_FileUtils_loadFilenameLookupDictionaryFromFile(lua_State* tolua argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:loadFilenameLookupDictionaryFromFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:loadFilenameLookupDictionaryFromFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_loadFilenameLookupDictionaryFromFile'", nullptr); @@ -32639,9 +32486,9 @@ int lua_cocos2dx_FileUtils_getValueVectorFromFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:getValueVectorFromFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:getValueVectorFromFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_getValueVectorFromFile'", nullptr); @@ -32737,11 +32584,11 @@ int lua_cocos2dx_FileUtils_writeToFile(lua_State* tolua_S) if (argc == 2) { cocos2d::ValueMap arg0; - std::string_view arg1; + std::string arg1; ok &= luaval_to_ccvaluemap(tolua_S, 2, &arg0, "cc.FileUtils:writeToFile"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:writeToFile"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:writeToFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_writeToFile'", nullptr); @@ -32836,9 +32683,9 @@ int lua_cocos2dx_FileUtils_getNewFilename(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:getNewFilename"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:getNewFilename"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_getNewFilename'", nullptr); @@ -32886,9 +32733,9 @@ int lua_cocos2dx_FileUtils_listFiles(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:listFiles"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:listFiles"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_listFiles'", nullptr); @@ -32936,9 +32783,9 @@ int lua_cocos2dx_FileUtils_getValueMapFromFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:getValueMapFromFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:getValueMapFromFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_getValueMapFromFile'", nullptr); @@ -32981,8 +32828,8 @@ int lua_cocos2dx_FileUtils_getFileSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:getFileSize"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:getFileSize"); if (!ok) { break; } std::function arg1; @@ -33001,8 +32848,8 @@ int lua_cocos2dx_FileUtils_getFileSize(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:getFileSize"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:getFileSize"); if (!ok) { break; } long long ret = cobj->getFileSize(arg0); @@ -33097,8 +32944,8 @@ int lua_cocos2dx_FileUtils_removeDirectory(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:removeDirectory"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:removeDirectory"); if (!ok) { break; } std::function arg1; @@ -33117,8 +32964,8 @@ int lua_cocos2dx_FileUtils_removeDirectory(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:removeDirectory"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:removeDirectory"); if (!ok) { break; } bool ret = cobj->removeDirectory(arg0); @@ -33214,8 +33061,8 @@ int lua_cocos2dx_FileUtils_writeStringToFile(lua_State* tolua_S) ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:writeStringToFile"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:writeStringToFile"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:writeStringToFile"); if (!ok) { break; } std::function arg2; @@ -33234,12 +33081,12 @@ int lua_cocos2dx_FileUtils_writeStringToFile(lua_State* tolua_S) ok = true; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:writeStringToFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:writeStringToFile"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:writeStringToFile"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:writeStringToFile"); if (!ok) { break; } bool ret = cobj->writeStringToFile(arg0, arg1); @@ -33286,9 +33133,9 @@ int lua_cocos2dx_FileUtils_isFileExistInternal(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:isFileExistInternal"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:isFileExistInternal"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_isFileExistInternal'", nullptr); @@ -33386,9 +33233,9 @@ int lua_cocos2dx_FileUtils_addSearchResolutionsOrder(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:addSearchResolutionsOrder"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:addSearchResolutionsOrder"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_addSearchResolutionsOrder'", nullptr); @@ -33400,10 +33247,10 @@ int lua_cocos2dx_FileUtils_addSearchResolutionsOrder(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; bool arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:addSearchResolutionsOrder"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:addSearchResolutionsOrder"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.FileUtils:addSearchResolutionsOrder"); if(!ok) @@ -33453,9 +33300,9 @@ int lua_cocos2dx_FileUtils_addSearchPath(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:addSearchPath"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:addSearchPath"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_addSearchPath'", nullptr); @@ -33467,10 +33314,10 @@ int lua_cocos2dx_FileUtils_addSearchPath(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; bool arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:addSearchPath"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:addSearchPath"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.FileUtils:addSearchPath"); if(!ok) @@ -33519,8 +33366,8 @@ int lua_cocos2dx_FileUtils_writeValueVectorToFile(lua_State* tolua_S) ok &= luaval_to_ccvaluevector(tolua_S, 2, &arg0, "cc.FileUtils:writeValueVectorToFile"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:writeValueVectorToFile"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:writeValueVectorToFile"); if (!ok) { break; } std::function arg2; @@ -33543,8 +33390,8 @@ int lua_cocos2dx_FileUtils_writeValueVectorToFile(lua_State* tolua_S) ok &= luaval_to_ccvaluevector(tolua_S, 2, &arg0, "cc.FileUtils:writeValueVectorToFile"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:writeValueVectorToFile"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:writeValueVectorToFile"); if (!ok) { break; } bool ret = cobj->writeValueVectorToFile(arg0, arg1); @@ -33586,8 +33433,8 @@ int lua_cocos2dx_FileUtils_isFileExist(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:isFileExist"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:isFileExist"); if (!ok) { break; } std::function arg1; @@ -33606,8 +33453,8 @@ int lua_cocos2dx_FileUtils_isFileExist(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:isFileExist"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:isFileExist"); if (!ok) { break; } bool ret = cobj->isFileExist(arg0); @@ -33701,12 +33548,12 @@ int lua_cocos2dx_FileUtils_fullPathFromRelativeFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:fullPathFromRelativeFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:fullPathFromRelativeFile"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:fullPathFromRelativeFile"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:fullPathFromRelativeFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_fullPathFromRelativeFile'", nullptr); @@ -33754,9 +33601,9 @@ int lua_cocos2dx_FileUtils_isDirectoryExistInternal(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:isDirectoryExistInternal"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:isDirectoryExistInternal"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_isDirectoryExistInternal'", nullptr); @@ -33803,8 +33650,8 @@ int lua_cocos2dx_FileUtils_writeValueMapToFile(lua_State* tolua_S) ok &= luaval_to_ccvaluemap(tolua_S, 2, &arg0, "cc.FileUtils:writeValueMapToFile"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:writeValueMapToFile"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:writeValueMapToFile"); if (!ok) { break; } std::function arg2; @@ -33827,8 +33674,8 @@ int lua_cocos2dx_FileUtils_writeValueMapToFile(lua_State* tolua_S) ok &= luaval_to_ccvaluemap(tolua_S, 2, &arg0, "cc.FileUtils:writeValueMapToFile"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:writeValueMapToFile"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:writeValueMapToFile"); if (!ok) { break; } bool ret = cobj->writeValueMapToFile(arg0, arg1); @@ -33875,9 +33722,9 @@ int lua_cocos2dx_FileUtils_getFileExtension(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:getFileExtension"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:getFileExtension"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_getFileExtension'", nullptr); @@ -33925,9 +33772,9 @@ int lua_cocos2dx_FileUtils_setWritablePath(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:setWritablePath"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:setWritablePath"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_setWritablePath'", nullptr); @@ -34020,8 +33867,8 @@ int lua_cocos2dx_FileUtils_isDirectoryExist(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:isDirectoryExist"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:isDirectoryExist"); if (!ok) { break; } std::function arg1; @@ -34040,8 +33887,8 @@ int lua_cocos2dx_FileUtils_isDirectoryExist(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:isDirectoryExist"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:isDirectoryExist"); if (!ok) { break; } bool ret = cobj->isDirectoryExist(arg0); @@ -34088,9 +33935,9 @@ int lua_cocos2dx_FileUtils_setDefaultResourceRootPath(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:setDefaultResourceRootPath"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:setDefaultResourceRootPath"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_setDefaultResourceRootPath'", nullptr); @@ -34180,8 +34027,8 @@ int lua_cocos2dx_FileUtils_createDirectory(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:createDirectory"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:createDirectory"); if (!ok) { break; } std::function arg1; @@ -34200,8 +34047,8 @@ int lua_cocos2dx_FileUtils_createDirectory(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:createDirectory"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:createDirectory"); if (!ok) { break; } bool ret = cobj->createDirectory(arg0); @@ -34248,10 +34095,10 @@ int lua_cocos2dx_FileUtils_listFilesAsync(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; std::function)> arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:listFilesAsync"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:listFilesAsync"); do { // Lambda binding for lua is not supported. @@ -34352,10 +34199,10 @@ int lua_cocos2dx_FileUtils_listFilesRecursively(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; std::vector* arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:listFilesRecursively"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:listFilesRecursively"); ok &= luaval_to_object>(tolua_S, 3, "std::vector*",&arg1, "cc.FileUtils:listFilesRecursively"); if(!ok) @@ -34377,6 +34224,40 @@ int lua_cocos2dx_FileUtils_listFilesRecursively(lua_State* tolua_S) return 0; } +int lua_cocos2dx_FileUtils_destroyInstance(lua_State* tolua_S) +{ + int argc = 0; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertable(tolua_S,1,"cc.FileUtils",0,&tolua_err)) goto tolua_lerror; +#endif + + argc = lua_gettop(tolua_S) - 1; + + if (argc == 0) + { + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_destroyInstance'", nullptr); + return 0; + } + cocos2d::FileUtils::destroyInstance(); + lua_settop(tolua_S, 1); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "cc.FileUtils:destroyInstance",argc, 0); + return 0; +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_FileUtils_destroyInstance'.",&tolua_err); +#endif + return 0; +} int lua_cocos2dx_FileUtils_writeBinaryToFile(lua_State* tolua_S) { int argc = 0; @@ -34396,11 +34277,11 @@ int lua_cocos2dx_FileUtils_writeBinaryToFile(lua_State* tolua_S) { const void* arg0; unsigned int arg1; - std::string_view arg2; + std::string arg2; #pragma warning NO CONVERSION TO NATIVE FOR void* ok = false; ok &= luaval_to_uint32(tolua_S, 3,&arg1, "cc.FileUtils:writeBinaryToFile"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.FileUtils:writeBinaryToFile"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.FileUtils:writeBinaryToFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_writeBinaryToFile'", nullptr); @@ -34452,76 +34333,6 @@ int lua_cocos2dx_FileUtils_getInstance(lua_State* tolua_S) #endif return 0; } -int lua_cocos2dx_FileUtils_isAbsolutePathInternal(lua_State* tolua_S) -{ - int argc = 0; - bool ok = true; - -#if COCOS2D_DEBUG >= 1 - tolua_Error tolua_err; -#endif - -#if COCOS2D_DEBUG >= 1 - if (!tolua_isusertable(tolua_S,1,"cc.FileUtils",0,&tolua_err)) goto tolua_lerror; -#endif - - argc = lua_gettop(tolua_S) - 1; - - if (argc == 1) - { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:isAbsolutePathInternal"); - if(!ok) - { - tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_isAbsolutePathInternal'", nullptr); - return 0; - } - bool ret = cocos2d::FileUtils::isAbsolutePathInternal(arg0); - tolua_pushboolean(tolua_S,(bool)ret); - return 1; - } - luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "cc.FileUtils:isAbsolutePathInternal",argc, 1); - return 0; -#if COCOS2D_DEBUG >= 1 - tolua_lerror: - tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_FileUtils_isAbsolutePathInternal'.",&tolua_err); -#endif - return 0; -} -int lua_cocos2dx_FileUtils_destroyInstance(lua_State* tolua_S) -{ - int argc = 0; - bool ok = true; - -#if COCOS2D_DEBUG >= 1 - tolua_Error tolua_err; -#endif - -#if COCOS2D_DEBUG >= 1 - if (!tolua_isusertable(tolua_S,1,"cc.FileUtils",0,&tolua_err)) goto tolua_lerror; -#endif - - argc = lua_gettop(tolua_S) - 1; - - if (argc == 0) - { - if(!ok) - { - tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_destroyInstance'", nullptr); - return 0; - } - cocos2d::FileUtils::destroyInstance(); - lua_settop(tolua_S, 1); - return 1; - } - luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "cc.FileUtils:destroyInstance",argc, 0); - return 0; -#if COCOS2D_DEBUG >= 1 - tolua_lerror: - tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_FileUtils_destroyInstance'.",&tolua_err); -#endif - return 0; -} int lua_cocos2dx_FileUtils_getFileShortName(lua_State* tolua_S) { int argc = 0; @@ -34539,8 +34350,8 @@ int lua_cocos2dx_FileUtils_getFileShortName(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:getFileShortName"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:getFileShortName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_getFileShortName'", nullptr); @@ -34613,10 +34424,9 @@ int lua_register_cocos2dx_FileUtils(lua_State* tolua_S) tolua_function(tolua_S,"listFilesAsync",lua_cocos2dx_FileUtils_listFilesAsync); tolua_function(tolua_S,"getWritablePath",lua_cocos2dx_FileUtils_getWritablePath); tolua_function(tolua_S,"listFilesRecursively",lua_cocos2dx_FileUtils_listFilesRecursively); + tolua_function(tolua_S,"destroyInstance", lua_cocos2dx_FileUtils_destroyInstance); tolua_function(tolua_S,"writeBinaryToFile", lua_cocos2dx_FileUtils_writeBinaryToFile); tolua_function(tolua_S,"getInstance", lua_cocos2dx_FileUtils_getInstance); - tolua_function(tolua_S,"isAbsolutePathInternal", lua_cocos2dx_FileUtils_isAbsolutePathInternal); - tolua_function(tolua_S,"destroyInstance", lua_cocos2dx_FileUtils_destroyInstance); tolua_function(tolua_S,"getFileShortName", lua_cocos2dx_FileUtils_getFileShortName); tolua_endmodule(tolua_S); auto typeName = typeid(cocos2d::FileUtils).name(); // rtti is literal storage @@ -34677,8 +34487,8 @@ int lua_cocos2dx_EventCustom_getEventName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_EventCustom_getEventName'", nullptr); return 0; } - std::string_view ret = cobj->getEventName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getEventName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.EventCustom:getEventName",argc, 0); @@ -34706,9 +34516,9 @@ int lua_cocos2dx_EventCustom_constructor(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventCustom:EventCustom"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventCustom:EventCustom"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_EventCustom_constructor'", nullptr); @@ -35053,9 +34863,9 @@ int lua_cocos2dx_EventDispatcher_dispatchCustomEvent(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventDispatcher:dispatchCustomEvent"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventDispatcher:dispatchCustomEvent"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_EventDispatcher_dispatchCustomEvent'", nullptr); @@ -35067,10 +34877,10 @@ int lua_cocos2dx_EventDispatcher_dispatchCustomEvent(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; void* arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventDispatcher:dispatchCustomEvent"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventDispatcher:dispatchCustomEvent"); #pragma warning NO CONVERSION TO NATIVE FOR void* ok = false; @@ -35308,10 +35118,10 @@ int lua_cocos2dx_EventDispatcher_addCustomEventListener(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; std::function arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventDispatcher:addCustomEventListener"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventDispatcher:addCustomEventListener"); do { // Lambda binding for lua is not supported. @@ -35415,9 +35225,9 @@ int lua_cocos2dx_EventDispatcher_hasEventListener(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + cocos2d::EventListener::ListenerID arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventDispatcher:hasEventListener"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventDispatcher:hasEventListener"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_EventDispatcher_hasEventListener'", nullptr); @@ -35512,9 +35322,9 @@ int lua_cocos2dx_EventDispatcher_removeCustomEventListeners(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventDispatcher:removeCustomEventListeners"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventDispatcher:removeCustomEventListeners"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_EventDispatcher_removeCustomEventListeners'", nullptr); @@ -43563,11 +43373,11 @@ int lua_cocos2dx_GridAction_initWithDuration(lua_State* tolua_S) if (argc == 2) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.GridAction:initWithDuration"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.GridAction:initWithDuration"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.GridAction:initWithDuration"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GridAction_initWithDuration'", nullptr); @@ -44010,13 +43820,13 @@ int lua_cocos2dx_Waves3D_initWithDuration(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; unsigned int arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Waves3D:initWithDuration"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Waves3D:initWithDuration"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Waves3D:initWithDuration"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.Waves3D:initWithDuration"); @@ -44202,11 +44012,11 @@ int lua_cocos2dx_Waves3D_create(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; unsigned int arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Waves3D:create"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Waves3D:create"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Waves3D:create"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.Waves3D:create"); ok &= luaval_to_number(tolua_S, 5,&arg3, "cc.Waves3D:create"); if(!ok) @@ -44317,10 +44127,10 @@ int lua_cocos2dx_FlipX3D_initWithSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; double arg1; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.FlipX3D:initWithSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.FlipX3D:initWithSize"); ok &= luaval_to_number(tolua_S, 3,&arg1, "cc.FlipX3D:initWithSize"); if(!ok) @@ -44661,13 +44471,13 @@ int lua_cocos2dx_Lens3D_initWithDuration(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; cocos2d::Vec2 arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Lens3D:initWithDuration"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Lens3D:initWithDuration"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Lens3D:initWithDuration"); ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.Lens3D:initWithDuration"); @@ -44903,11 +44713,11 @@ int lua_cocos2dx_Lens3D_create(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; cocos2d::Vec2 arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Lens3D:create"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Lens3D:create"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Lens3D:create"); ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.Lens3D:create"); ok &= luaval_to_number(tolua_S, 5,&arg3, "cc.Lens3D:create"); if(!ok) @@ -45070,7 +44880,7 @@ int lua_cocos2dx_Ripple3D_initWithDuration(lua_State* tolua_S) if (argc == 6) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; cocos2d::Vec2 arg2; double arg3; unsigned int arg4; @@ -45078,7 +44888,7 @@ int lua_cocos2dx_Ripple3D_initWithDuration(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Ripple3D:initWithDuration"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Ripple3D:initWithDuration"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Ripple3D:initWithDuration"); ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.Ripple3D:initWithDuration"); @@ -45365,13 +45175,13 @@ int lua_cocos2dx_Ripple3D_create(lua_State* tolua_S) if (argc == 6) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; cocos2d::Vec2 arg2; double arg3; unsigned int arg4; double arg5; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Ripple3D:create"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Ripple3D:create"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Ripple3D:create"); ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.Ripple3D:create"); ok &= luaval_to_number(tolua_S, 5,&arg3, "cc.Ripple3D:create"); ok &= luaval_to_uint32(tolua_S, 6,&arg4, "cc.Ripple3D:create"); @@ -45487,13 +45297,13 @@ int lua_cocos2dx_Shaky3D_initWithDuration(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; int arg2; bool arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Shaky3D:initWithDuration"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Shaky3D:initWithDuration"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Shaky3D:initWithDuration"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.Shaky3D:initWithDuration"); @@ -45535,11 +45345,11 @@ int lua_cocos2dx_Shaky3D_create(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; int arg2; bool arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Shaky3D:create"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Shaky3D:create"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Shaky3D:create"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.Shaky3D:create"); ok &= luaval_to_boolean(tolua_S, 5,&arg3, "cc.Shaky3D:create"); if(!ok) @@ -45697,13 +45507,13 @@ int lua_cocos2dx_Liquid_initWithDuration(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; unsigned int arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Liquid:initWithDuration"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Liquid:initWithDuration"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Liquid:initWithDuration"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.Liquid:initWithDuration"); @@ -45889,11 +45699,11 @@ int lua_cocos2dx_Liquid_create(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; unsigned int arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Liquid:create"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Liquid:create"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Liquid:create"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.Liquid:create"); ok &= luaval_to_number(tolua_S, 5,&arg3, "cc.Liquid:create"); if(!ok) @@ -46055,7 +45865,7 @@ int lua_cocos2dx_Waves_initWithDuration(lua_State* tolua_S) if (argc == 6) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; unsigned int arg2; double arg3; bool arg4; @@ -46063,7 +45873,7 @@ int lua_cocos2dx_Waves_initWithDuration(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Waves:initWithDuration"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Waves:initWithDuration"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Waves:initWithDuration"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.Waves:initWithDuration"); @@ -46253,13 +46063,13 @@ int lua_cocos2dx_Waves_create(lua_State* tolua_S) if (argc == 6) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; unsigned int arg2; double arg3; bool arg4; bool arg5; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Waves:create"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Waves:create"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Waves:create"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.Waves:create"); ok &= luaval_to_number(tolua_S, 5,&arg3, "cc.Waves:create"); ok &= luaval_to_boolean(tolua_S, 6,&arg4, "cc.Waves:create"); @@ -46423,14 +46233,14 @@ int lua_cocos2dx_Twirl_initWithDuration(lua_State* tolua_S) if (argc == 5) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; cocos2d::Vec2 arg2; unsigned int arg3; double arg4; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Twirl:initWithDuration"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Twirl:initWithDuration"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Twirl:initWithDuration"); ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.Twirl:initWithDuration"); @@ -46715,12 +46525,12 @@ int lua_cocos2dx_Twirl_create(lua_State* tolua_S) if (argc == 5) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; cocos2d::Vec2 arg2; unsigned int arg3; double arg4; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Twirl:create"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Twirl:create"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Twirl:create"); ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.Twirl:create"); ok &= luaval_to_uint32(tolua_S, 5,&arg3, "cc.Twirl:create"); ok &= luaval_to_number(tolua_S, 6,&arg4, "cc.Twirl:create"); @@ -47709,9 +47519,9 @@ int lua_cocos2dx_PageTurn3D_create(lua_State* tolua_S) if (argc == 2) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.PageTurn3D:create"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.PageTurn3D:create"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.PageTurn3D:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_PageTurn3D_create'", nullptr); @@ -48083,13 +47893,13 @@ int lua_cocos2dx_ShakyTiles3D_initWithDuration(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; int arg2; bool arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.ShakyTiles3D:initWithDuration"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.ShakyTiles3D:initWithDuration"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.ShakyTiles3D:initWithDuration"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.ShakyTiles3D:initWithDuration"); @@ -48131,11 +47941,11 @@ int lua_cocos2dx_ShakyTiles3D_create(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; int arg2; bool arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.ShakyTiles3D:create"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.ShakyTiles3D:create"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.ShakyTiles3D:create"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.ShakyTiles3D:create"); ok &= luaval_to_boolean(tolua_S, 5,&arg3, "cc.ShakyTiles3D:create"); if(!ok) @@ -48243,13 +48053,13 @@ int lua_cocos2dx_ShatteredTiles3D_initWithDuration(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; int arg2; bool arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.ShatteredTiles3D:initWithDuration"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.ShatteredTiles3D:initWithDuration"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.ShatteredTiles3D:initWithDuration"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.ShatteredTiles3D:initWithDuration"); @@ -48291,11 +48101,11 @@ int lua_cocos2dx_ShatteredTiles3D_create(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; int arg2; bool arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.ShatteredTiles3D:create"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.ShatteredTiles3D:create"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.ShatteredTiles3D:create"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.ShatteredTiles3D:create"); ok &= luaval_to_boolean(tolua_S, 5,&arg3, "cc.ShatteredTiles3D:create"); if(!ok) @@ -48403,12 +48213,12 @@ int lua_cocos2dx_ShuffleTiles_initWithDuration(lua_State* tolua_S) if (argc == 3) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; unsigned int arg2; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.ShuffleTiles:initWithDuration"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.ShuffleTiles:initWithDuration"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.ShuffleTiles:initWithDuration"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.ShuffleTiles:initWithDuration"); if(!ok) @@ -48458,16 +48268,16 @@ int lua_cocos2dx_ShuffleTiles_getDelta(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.ShuffleTiles:getDelta"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.ShuffleTiles:getDelta"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ShuffleTiles_getDelta'", nullptr); return 0; } - cocos2d::Vec2 ret = cobj->getDelta(arg0); - vec2_to_luaval(tolua_S, ret); + cocos2d::Size ret = cobj->getDelta(arg0); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.ShuffleTiles:getDelta",argc, 1); @@ -48498,10 +48308,10 @@ int lua_cocos2dx_ShuffleTiles_create(lua_State* tolua_S) if (argc == 3) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; unsigned int arg2; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.ShuffleTiles:create"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.ShuffleTiles:create"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.ShuffleTiles:create"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.ShuffleTiles:create"); if(!ok) { @@ -48761,10 +48571,10 @@ int lua_cocos2dx_FadeOutTRTiles_testFunc(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; double arg1; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.FadeOutTRTiles:testFunc"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.FadeOutTRTiles:testFunc"); ok &= luaval_to_number(tolua_S, 3,&arg1, "cc.FadeOutTRTiles:testFunc"); if(!ok) @@ -48804,9 +48614,9 @@ int lua_cocos2dx_FadeOutTRTiles_create(lua_State* tolua_S) if (argc == 2) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.FadeOutTRTiles:create"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.FadeOutTRTiles:create"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.FadeOutTRTiles:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FadeOutTRTiles_create'", nullptr); @@ -48904,9 +48714,9 @@ int lua_cocos2dx_FadeOutBLTiles_create(lua_State* tolua_S) if (argc == 2) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.FadeOutBLTiles:create"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.FadeOutBLTiles:create"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.FadeOutBLTiles:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FadeOutBLTiles_create'", nullptr); @@ -49000,9 +48810,9 @@ int lua_cocos2dx_FadeOutUpTiles_create(lua_State* tolua_S) if (argc == 2) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.FadeOutUpTiles:create"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.FadeOutUpTiles:create"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.FadeOutUpTiles:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FadeOutUpTiles_create'", nullptr); @@ -49096,9 +48906,9 @@ int lua_cocos2dx_FadeOutDownTiles_create(lua_State* tolua_S) if (argc == 2) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.FadeOutDownTiles:create"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.FadeOutDownTiles:create"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.FadeOutDownTiles:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FadeOutDownTiles_create'", nullptr); @@ -49303,12 +49113,12 @@ int lua_cocos2dx_TurnOffTiles_initWithDuration(lua_State* tolua_S) if (argc == 3) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; unsigned int arg2; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.TurnOffTiles:initWithDuration"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.TurnOffTiles:initWithDuration"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.TurnOffTiles:initWithDuration"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.TurnOffTiles:initWithDuration"); if(!ok) @@ -49351,8 +49161,8 @@ int lua_cocos2dx_TurnOffTiles_create(lua_State* tolua_S) double arg0; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.TurnOffTiles:create"); if (!ok) { break; } - cocos2d::Vec2 arg1; - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.TurnOffTiles:create"); + cocos2d::Size arg1; + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.TurnOffTiles:create"); if (!ok) { break; } unsigned int arg2; ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.TurnOffTiles:create"); @@ -49370,8 +49180,8 @@ int lua_cocos2dx_TurnOffTiles_create(lua_State* tolua_S) double arg0; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.TurnOffTiles:create"); if (!ok) { break; } - cocos2d::Vec2 arg1; - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.TurnOffTiles:create"); + cocos2d::Size arg1; + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.TurnOffTiles:create"); if (!ok) { break; } cocos2d::TurnOffTiles* ret = cocos2d::TurnOffTiles::create(arg0, arg1); object_to_luaval(tolua_S, "cc.TurnOffTiles",(cocos2d::TurnOffTiles*)ret); @@ -49527,13 +49337,13 @@ int lua_cocos2dx_WavesTiles3D_initWithDuration(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; unsigned int arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.WavesTiles3D:initWithDuration"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.WavesTiles3D:initWithDuration"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.WavesTiles3D:initWithDuration"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.WavesTiles3D:initWithDuration"); @@ -49719,11 +49529,11 @@ int lua_cocos2dx_WavesTiles3D_create(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; unsigned int arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.WavesTiles3D:create"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.WavesTiles3D:create"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.WavesTiles3D:create"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.WavesTiles3D:create"); ok &= luaval_to_number(tolua_S, 5,&arg3, "cc.WavesTiles3D:create"); if(!ok) @@ -49885,13 +49695,13 @@ int lua_cocos2dx_JumpTiles3D_initWithDuration(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; unsigned int arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.JumpTiles3D:initWithDuration"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.JumpTiles3D:initWithDuration"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.JumpTiles3D:initWithDuration"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.JumpTiles3D:initWithDuration"); @@ -50077,11 +49887,11 @@ int lua_cocos2dx_JumpTiles3D_create(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; unsigned int arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.JumpTiles3D:create"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.JumpTiles3D:create"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.JumpTiles3D:create"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.JumpTiles3D:create"); ok &= luaval_to_number(tolua_S, 5,&arg3, "cc.JumpTiles3D:create"); if(!ok) @@ -50493,13 +50303,13 @@ int lua_cocos2dx_ActionTween_initWithDuration(lua_State* tolua_S) if (argc == 4) { double arg0; - std::string_view arg1; + std::string arg1; double arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.ActionTween:initWithDuration"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.ActionTween:initWithDuration"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.ActionTween:initWithDuration"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.ActionTween:initWithDuration"); @@ -50541,11 +50351,11 @@ int lua_cocos2dx_ActionTween_create(lua_State* tolua_S) if (argc == 4) { double arg0; - std::string_view arg1; + std::string arg1; double arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.ActionTween:create"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.ActionTween:create"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.ActionTween:create"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.ActionTween:create"); ok &= luaval_to_number(tolua_S, 5,&arg3, "cc.ActionTween:create"); if(!ok) @@ -50661,12 +50471,12 @@ int lua_cocos2dx_AtlasNode_initWithTileFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 4) { - std::string_view arg0; + std::string arg0; int arg1; int arg2; int arg3; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AtlasNode:initWithTileFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AtlasNode:initWithTileFile"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "cc.AtlasNode:initWithTileFile"); @@ -51156,11 +50966,11 @@ int lua_cocos2dx_AtlasNode_create(lua_State* tolua_S) if (argc == 4) { - std::string_view arg0; + std::string arg0; int arg1; int arg2; int arg3; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AtlasNode:create"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AtlasNode:create"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "cc.AtlasNode:create"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.AtlasNode:create"); ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "cc.AtlasNode:create"); @@ -52004,13 +51814,13 @@ int lua_cocos2dx_DrawNode_drawLine(lua_State* tolua_S) { cocos2d::Vec2 arg0; cocos2d::Vec2 arg1; - cocos2d::Color4B arg2; + cocos2d::Color4F arg2; ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.DrawNode:drawLine"); ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.DrawNode:drawLine"); - ok &=luaval_to_color4b(tolua_S, 4, &arg2, "cc.DrawNode:drawLine"); + ok &=luaval_to_color4f(tolua_S, 4, &arg2, "cc.DrawNode:drawLine"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_DrawNode_drawLine'", nullptr); @@ -52119,8 +51929,8 @@ int lua_cocos2dx_DrawNode_drawRect(lua_State* tolua_S) ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.DrawNode:drawRect"); if (!ok) { break; } - cocos2d::Color4B arg4; - ok &=luaval_to_color4b(tolua_S, 6, &arg4, "cc.DrawNode:drawRect"); + cocos2d::Color4F arg4; + ok &=luaval_to_color4f(tolua_S, 6, &arg4, "cc.DrawNode:drawRect"); if (!ok) { break; } cobj->drawRect(arg0, arg1, arg2, arg3, arg4); @@ -52139,8 +51949,8 @@ int lua_cocos2dx_DrawNode_drawRect(lua_State* tolua_S) ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.DrawNode:drawRect"); if (!ok) { break; } - cocos2d::Color4B arg2; - ok &=luaval_to_color4b(tolua_S, 4, &arg2, "cc.DrawNode:drawRect"); + cocos2d::Color4F arg2; + ok &=luaval_to_color4f(tolua_S, 4, &arg2, "cc.DrawNode:drawRect"); if (!ok) { break; } cobj->drawRect(arg0, arg1, arg2); @@ -52206,8 +52016,8 @@ int lua_cocos2dx_DrawNode_drawSolidCircle(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 7,&arg5, "cc.DrawNode:drawSolidCircle"); if (!ok) { break; } - cocos2d::Color4B arg6; - ok &=luaval_to_color4b(tolua_S, 8, &arg6, "cc.DrawNode:drawSolidCircle"); + cocos2d::Color4F arg6; + ok &=luaval_to_color4f(tolua_S, 8, &arg6, "cc.DrawNode:drawSolidCircle"); if (!ok) { break; } cobj->drawSolidCircle(arg0, arg1, arg2, arg3, arg4, arg5, arg6); @@ -52242,16 +52052,16 @@ int lua_cocos2dx_DrawNode_drawSolidCircle(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 7,&arg5, "cc.DrawNode:drawSolidCircle"); if (!ok) { break; } - cocos2d::Color4B arg6; - ok &=luaval_to_color4b(tolua_S, 8, &arg6, "cc.DrawNode:drawSolidCircle"); + cocos2d::Color4F arg6; + ok &=luaval_to_color4f(tolua_S, 8, &arg6, "cc.DrawNode:drawSolidCircle"); if (!ok) { break; } double arg7; ok &= luaval_to_number(tolua_S, 9,&arg7, "cc.DrawNode:drawSolidCircle"); if (!ok) { break; } - cocos2d::Color4B arg8; - ok &=luaval_to_color4b(tolua_S, 10, &arg8, "cc.DrawNode:drawSolidCircle"); + cocos2d::Color4F arg8; + ok &=luaval_to_color4f(tolua_S, 10, &arg8, "cc.DrawNode:drawSolidCircle"); if (!ok) { break; } cobj->drawSolidCircle(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); @@ -52278,8 +52088,8 @@ int lua_cocos2dx_DrawNode_drawSolidCircle(lua_State* tolua_S) ok &= luaval_to_uint32(tolua_S, 5,&arg3, "cc.DrawNode:drawSolidCircle"); if (!ok) { break; } - cocos2d::Color4B arg4; - ok &=luaval_to_color4b(tolua_S, 6, &arg4, "cc.DrawNode:drawSolidCircle"); + cocos2d::Color4F arg4; + ok &=luaval_to_color4f(tolua_S, 6, &arg4, "cc.DrawNode:drawSolidCircle"); if (!ok) { break; } cobj->drawSolidCircle(arg0, arg1, arg2, arg3, arg4); @@ -52378,13 +52188,13 @@ int lua_cocos2dx_DrawNode_drawDot(lua_State* tolua_S) { cocos2d::Vec2 arg0; double arg1; - cocos2d::Color4B arg2; + cocos2d::Color4F arg2; ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.DrawNode:drawDot"); ok &= luaval_to_number(tolua_S, 3,&arg1, "cc.DrawNode:drawDot"); - ok &=luaval_to_color4b(tolua_S, 4, &arg2, "cc.DrawNode:drawDot"); + ok &=luaval_to_color4f(tolua_S, 4, &arg2, "cc.DrawNode:drawDot"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_DrawNode_drawDot'", nullptr); @@ -52435,7 +52245,7 @@ int lua_cocos2dx_DrawNode_drawSegment(lua_State* tolua_S) cocos2d::Vec2 arg0; cocos2d::Vec2 arg1; double arg2; - cocos2d::Color4B arg3; + cocos2d::Color4F arg3; ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.DrawNode:drawSegment"); @@ -52443,7 +52253,7 @@ int lua_cocos2dx_DrawNode_drawSegment(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.DrawNode:drawSegment"); - ok &=luaval_to_color4b(tolua_S, 5, &arg3, "cc.DrawNode:drawSegment"); + ok &=luaval_to_color4f(tolua_S, 5, &arg3, "cc.DrawNode:drawSegment"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_DrawNode_drawSegment'", nullptr); @@ -52553,8 +52363,8 @@ int lua_cocos2dx_DrawNode_drawCircle(lua_State* tolua_S) ok &= luaval_to_boolean(tolua_S, 6,&arg4, "cc.DrawNode:drawCircle"); if (!ok) { break; } - cocos2d::Color4B arg5; - ok &=luaval_to_color4b(tolua_S, 7, &arg5, "cc.DrawNode:drawCircle"); + cocos2d::Color4F arg5; + ok &=luaval_to_color4f(tolua_S, 7, &arg5, "cc.DrawNode:drawCircle"); if (!ok) { break; } cobj->drawCircle(arg0, arg1, arg2, arg3, arg4, arg5); @@ -52593,8 +52403,8 @@ int lua_cocos2dx_DrawNode_drawCircle(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 8,&arg6, "cc.DrawNode:drawCircle"); if (!ok) { break; } - cocos2d::Color4B arg7; - ok &=luaval_to_color4b(tolua_S, 9, &arg7, "cc.DrawNode:drawCircle"); + cocos2d::Color4F arg7; + ok &=luaval_to_color4f(tolua_S, 9, &arg7, "cc.DrawNode:drawCircle"); if (!ok) { break; } cobj->drawCircle(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); @@ -52645,7 +52455,7 @@ int lua_cocos2dx_DrawNode_drawQuadBezier(lua_State* tolua_S) cocos2d::Vec2 arg1; cocos2d::Vec2 arg2; unsigned int arg3; - cocos2d::Color4B arg4; + cocos2d::Color4F arg4; ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.DrawNode:drawQuadBezier"); @@ -52655,7 +52465,7 @@ int lua_cocos2dx_DrawNode_drawQuadBezier(lua_State* tolua_S) ok &= luaval_to_uint32(tolua_S, 5,&arg3, "cc.DrawNode:drawQuadBezier"); - ok &=luaval_to_color4b(tolua_S, 6, &arg4, "cc.DrawNode:drawQuadBezier"); + ok &=luaval_to_color4f(tolua_S, 6, &arg4, "cc.DrawNode:drawQuadBezier"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_DrawNode_drawQuadBezier'", nullptr); @@ -52706,7 +52516,7 @@ int lua_cocos2dx_DrawNode_drawTriangle(lua_State* tolua_S) cocos2d::Vec2 arg0; cocos2d::Vec2 arg1; cocos2d::Vec2 arg2; - cocos2d::Color4B arg3; + cocos2d::Color4F arg3; ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.DrawNode:drawTriangle"); @@ -52714,7 +52524,7 @@ int lua_cocos2dx_DrawNode_drawTriangle(lua_State* tolua_S) ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.DrawNode:drawTriangle"); - ok &=luaval_to_color4b(tolua_S, 5, &arg3, "cc.DrawNode:drawTriangle"); + ok &=luaval_to_color4f(tolua_S, 5, &arg3, "cc.DrawNode:drawTriangle"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_DrawNode_drawTriangle'", nullptr); @@ -52861,13 +52671,13 @@ int lua_cocos2dx_DrawNode_drawSolidRect(lua_State* tolua_S) { cocos2d::Vec2 arg0; cocos2d::Vec2 arg1; - cocos2d::Color4B arg2; + cocos2d::Color4F arg2; ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.DrawNode:drawSolidRect"); ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.DrawNode:drawSolidRect"); - ok &=luaval_to_color4b(tolua_S, 4, &arg2, "cc.DrawNode:drawSolidRect"); + ok &=luaval_to_color4f(tolua_S, 4, &arg2, "cc.DrawNode:drawSolidRect"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_DrawNode_drawSolidRect'", nullptr); @@ -52964,13 +52774,13 @@ int lua_cocos2dx_DrawNode_drawPoint(lua_State* tolua_S) { cocos2d::Vec2 arg0; double arg1; - cocos2d::Color4B arg2; + cocos2d::Color4F arg2; ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.DrawNode:drawPoint"); ok &= luaval_to_number(tolua_S, 3,&arg1, "cc.DrawNode:drawPoint"); - ok &=luaval_to_color4b(tolua_S, 4, &arg2, "cc.DrawNode:drawPoint"); + ok &=luaval_to_color4f(tolua_S, 4, &arg2, "cc.DrawNode:drawPoint"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_DrawNode_drawPoint'", nullptr); @@ -53070,7 +52880,7 @@ int lua_cocos2dx_DrawNode_drawCubicBezier(lua_State* tolua_S) cocos2d::Vec2 arg2; cocos2d::Vec2 arg3; unsigned int arg4; - cocos2d::Color4B arg5; + cocos2d::Color4F arg5; ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.DrawNode:drawCubicBezier"); @@ -53082,7 +52892,7 @@ int lua_cocos2dx_DrawNode_drawCubicBezier(lua_State* tolua_S) ok &= luaval_to_uint32(tolua_S, 6,&arg4, "cc.DrawNode:drawCubicBezier"); - ok &=luaval_to_color4b(tolua_S, 7, &arg5, "cc.DrawNode:drawCubicBezier"); + ok &=luaval_to_color4f(tolua_S, 7, &arg5, "cc.DrawNode:drawCubicBezier"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_DrawNode_drawCubicBezier'", nullptr); @@ -53343,11 +53153,11 @@ int lua_cocos2dx_Label_enableShadow(lua_State* tolua_S) if (argc == 2) { cocos2d::Color4B arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; ok &=luaval_to_color4b(tolua_S, 2, &arg0, "cc.Label:enableShadow"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Label:enableShadow"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Label:enableShadow"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Label_enableShadow'", nullptr); @@ -53360,12 +53170,12 @@ int lua_cocos2dx_Label_enableShadow(lua_State* tolua_S) if (argc == 3) { cocos2d::Color4B arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; int arg2; ok &=luaval_to_color4b(tolua_S, 2, &arg0, "cc.Label:enableShadow"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Label:enableShadow"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Label:enableShadow"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.Label:enableShadow"); if(!ok) @@ -53520,8 +53330,8 @@ int lua_cocos2dx_Label_getString(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Label_getString'", nullptr); return 0; } - std::string_view ret = cobj->getString(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getString(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Label:getString",argc, 0); @@ -54144,8 +53954,8 @@ int lua_cocos2dx_Label_getShadowOffset(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Label_getShadowOffset'", nullptr); return 0; } - cocos2d::Vec2 ret = cobj->getShadowOffset(); - vec2_to_luaval(tolua_S, ret); + cocos2d::Size ret = cobj->getShadowOffset(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Label:getShadowOffset",argc, 0); @@ -54283,9 +54093,9 @@ int lua_cocos2dx_Label_setString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setString"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Label_setString'", nullptr); @@ -54333,9 +54143,9 @@ int lua_cocos2dx_Label_setSystemFontName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setSystemFontName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setSystemFontName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Label_setSystemFontName'", nullptr); @@ -54472,8 +54282,8 @@ int lua_cocos2dx_Label_setBMFontFilePath(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); if (!ok) { break; } cocos2d::Rect arg1; @@ -54492,8 +54302,8 @@ int lua_cocos2dx_Label_setBMFontFilePath(lua_State* tolua_S) ok = true; do{ if (argc == 4) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); if (!ok) { break; } cocos2d::Rect arg1; @@ -54516,8 +54326,8 @@ int lua_cocos2dx_Label_setBMFontFilePath(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); if (!ok) { break; } bool ret = cobj->setBMFontFilePath(arg0); @@ -54528,8 +54338,8 @@ int lua_cocos2dx_Label_setBMFontFilePath(lua_State* tolua_S) ok = true; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); if (!ok) { break; } double arg1; @@ -54544,12 +54354,12 @@ int lua_cocos2dx_Label_setBMFontFilePath(lua_State* tolua_S) ok = true; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:setBMFontFilePath"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:setBMFontFilePath"); if (!ok) { break; } bool ret = cobj->setBMFontFilePath(arg0, arg1); @@ -54560,12 +54370,12 @@ int lua_cocos2dx_Label_setBMFontFilePath(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:setBMFontFilePath"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:setBMFontFilePath"); if (!ok) { break; } double arg2; @@ -54615,8 +54425,8 @@ int lua_cocos2dx_Label_initWithTTF(lua_State* tolua_S) ok &= luaval_to_ttfconfig(tolua_S, 2, &arg0, "cc.Label:initWithTTF"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); if (!ok) { break; } bool ret = cobj->initWithTTF(arg0, arg1); @@ -54631,8 +54441,8 @@ int lua_cocos2dx_Label_initWithTTF(lua_State* tolua_S) ok &= luaval_to_ttfconfig(tolua_S, 2, &arg0, "cc.Label:initWithTTF"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); if (!ok) { break; } cocos2d::TextHAlignment arg2; @@ -54651,8 +54461,8 @@ int lua_cocos2dx_Label_initWithTTF(lua_State* tolua_S) ok &= luaval_to_ttfconfig(tolua_S, 2, &arg0, "cc.Label:initWithTTF"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); if (!ok) { break; } cocos2d::TextHAlignment arg2; @@ -54671,12 +54481,12 @@ int lua_cocos2dx_Label_initWithTTF(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:initWithTTF"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:initWithTTF"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); if (!ok) { break; } double arg2; @@ -54691,20 +54501,20 @@ int lua_cocos2dx_Label_initWithTTF(lua_State* tolua_S) ok = true; do{ if (argc == 4) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:initWithTTF"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:initWithTTF"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); if (!ok) { break; } double arg2; ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Label:initWithTTF"); if (!ok) { break; } - cocos2d::Vec2 arg3; - ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Label:initWithTTF"); + cocos2d::Size arg3; + ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Label:initWithTTF"); if (!ok) { break; } bool ret = cobj->initWithTTF(arg0, arg1, arg2, arg3); @@ -54715,20 +54525,20 @@ int lua_cocos2dx_Label_initWithTTF(lua_State* tolua_S) ok = true; do{ if (argc == 5) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:initWithTTF"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:initWithTTF"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); if (!ok) { break; } double arg2; ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Label:initWithTTF"); if (!ok) { break; } - cocos2d::Vec2 arg3; - ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Label:initWithTTF"); + cocos2d::Size arg3; + ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Label:initWithTTF"); if (!ok) { break; } cocos2d::TextHAlignment arg4; @@ -54743,20 +54553,20 @@ int lua_cocos2dx_Label_initWithTTF(lua_State* tolua_S) ok = true; do{ if (argc == 6) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:initWithTTF"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:initWithTTF"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); if (!ok) { break; } double arg2; ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Label:initWithTTF"); if (!ok) { break; } - cocos2d::Vec2 arg3; - ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Label:initWithTTF"); + cocos2d::Size arg3; + ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Label:initWithTTF"); if (!ok) { break; } cocos2d::TextHAlignment arg4; @@ -55476,8 +55286,8 @@ int lua_cocos2dx_Label_setCharMap(lua_State* tolua_S) ok = true; do{ if (argc == 4) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setCharMap"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setCharMap"); if (!ok) { break; } int arg1; @@ -55500,8 +55310,8 @@ int lua_cocos2dx_Label_setCharMap(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setCharMap"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setCharMap"); if (!ok) { break; } bool ret = cobj->setCharMap(arg0); @@ -55553,8 +55363,8 @@ int lua_cocos2dx_Label_getDimensions(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Label_getDimensions'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getDimensions(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getDimensions(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Label:getDimensions",argc, 0); @@ -55650,8 +55460,8 @@ int lua_cocos2dx_Label_getSystemFontName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Label_getSystemFontName'", nullptr); return 0; } - std::string_view ret = cobj->getSystemFontName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getSystemFontName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Label:getSystemFontName",argc, 0); @@ -56567,8 +56377,8 @@ int lua_cocos2dx_Label_getBMFontFilePath(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Label_getBMFontFilePath'", nullptr); return 0; } - std::string_view ret = cobj->getBMFontFilePath(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getBMFontFilePath(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Label:getBMFontFilePath",argc, 0); @@ -56946,11 +56756,11 @@ int lua_cocos2dx_Label_createWithBMFont(lua_State* tolua_S) { if (argc == 6) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); if (!ok) { break; } cocos2d::TextHAlignment arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.Label:createWithBMFont"); @@ -56974,11 +56784,11 @@ int lua_cocos2dx_Label_createWithBMFont(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); if (!ok) { break; } cocos2d::Label* ret = cocos2d::Label::createWithBMFont(arg0, arg1); object_to_luaval(tolua_S, "cc.Label",(cocos2d::Label*)ret); @@ -56990,11 +56800,11 @@ int lua_cocos2dx_Label_createWithBMFont(lua_State* tolua_S) { if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); if (!ok) { break; } cocos2d::TextHAlignment arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.Label:createWithBMFont"); @@ -57009,11 +56819,11 @@ int lua_cocos2dx_Label_createWithBMFont(lua_State* tolua_S) { if (argc == 4) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); if (!ok) { break; } cocos2d::TextHAlignment arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.Label:createWithBMFont"); @@ -57031,11 +56841,11 @@ int lua_cocos2dx_Label_createWithBMFont(lua_State* tolua_S) { if (argc == 5) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); if (!ok) { break; } cocos2d::TextHAlignment arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.Label:createWithBMFont"); @@ -57043,8 +56853,8 @@ int lua_cocos2dx_Label_createWithBMFont(lua_State* tolua_S) int arg3; ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "cc.Label:createWithBMFont"); if (!ok) { break; } - std::string_view arg4; - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.Label:createWithBMFont"); + std::string arg4; + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.Label:createWithBMFont"); if (!ok) { break; } cocos2d::Label* ret = cocos2d::Label::createWithBMFont(arg0, arg1, arg2, arg3, arg4); object_to_luaval(tolua_S, "cc.Label",(cocos2d::Label*)ret); @@ -57134,8 +56944,8 @@ int lua_cocos2dx_Label_createWithCharMap(lua_State* tolua_S) { if (argc == 4) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithCharMap"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithCharMap"); if (!ok) { break; } int arg1; ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "cc.Label:createWithCharMap"); @@ -57156,8 +56966,8 @@ int lua_cocos2dx_Label_createWithCharMap(lua_State* tolua_S) { if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithCharMap"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithCharMap"); if (!ok) { break; } cocos2d::Label* ret = cocos2d::Label::createWithCharMap(arg0); object_to_luaval(tolua_S, "cc.Label",(cocos2d::Label*)ret); @@ -57190,11 +57000,11 @@ int lua_cocos2dx_Label_createWithSystemFont(lua_State* tolua_S) if (argc == 3) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; double arg2; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithSystemFont"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:createWithSystemFont"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithSystemFont"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:createWithSystemFont"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Label:createWithSystemFont"); if(!ok) { @@ -57207,14 +57017,14 @@ int lua_cocos2dx_Label_createWithSystemFont(lua_State* tolua_S) } if (argc == 4) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; double arg2; - cocos2d::Vec2 arg3; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithSystemFont"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:createWithSystemFont"); + cocos2d::Size arg3; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithSystemFont"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:createWithSystemFont"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Label:createWithSystemFont"); - ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Label:createWithSystemFont"); + ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Label:createWithSystemFont"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Label_createWithSystemFont'", nullptr); @@ -57226,15 +57036,15 @@ int lua_cocos2dx_Label_createWithSystemFont(lua_State* tolua_S) } if (argc == 5) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; double arg2; - cocos2d::Vec2 arg3; + cocos2d::Size arg3; cocos2d::TextHAlignment arg4; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithSystemFont"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:createWithSystemFont"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithSystemFont"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:createWithSystemFont"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Label:createWithSystemFont"); - ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Label:createWithSystemFont"); + ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Label:createWithSystemFont"); ok &= luaval_to_int32(tolua_S, 6,(int *)&arg4, "cc.Label:createWithSystemFont"); if(!ok) { @@ -57247,16 +57057,16 @@ int lua_cocos2dx_Label_createWithSystemFont(lua_State* tolua_S) } if (argc == 6) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; double arg2; - cocos2d::Vec2 arg3; + cocos2d::Size arg3; cocos2d::TextHAlignment arg4; cocos2d::TextVAlignment arg5; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithSystemFont"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:createWithSystemFont"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithSystemFont"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:createWithSystemFont"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Label:createWithSystemFont"); - ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Label:createWithSystemFont"); + ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Label:createWithSystemFont"); ok &= luaval_to_int32(tolua_S, 6,(int *)&arg4, "cc.Label:createWithSystemFont"); ok &= luaval_to_int32(tolua_S, 7,(int *)&arg5, "cc.Label:createWithSystemFont"); if(!ok) @@ -57396,9 +57206,9 @@ int lua_cocos2dx_LabelAtlas_setString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.LabelAtlas:setString"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.LabelAtlas:setString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_LabelAtlas_setString'", nullptr); @@ -57441,12 +57251,12 @@ int lua_cocos2dx_LabelAtlas_initWithString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.LabelAtlas:initWithString"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.LabelAtlas:initWithString"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.LabelAtlas:initWithString"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.LabelAtlas:initWithString"); if (!ok) { break; } bool ret = cobj->initWithString(arg0, arg1); @@ -57457,12 +57267,12 @@ int lua_cocos2dx_LabelAtlas_initWithString(lua_State* tolua_S) ok = true; do{ if (argc == 5) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.LabelAtlas:initWithString"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.LabelAtlas:initWithString"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.LabelAtlas:initWithString"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.LabelAtlas:initWithString"); if (!ok) { break; } int arg2; @@ -57485,8 +57295,8 @@ int lua_cocos2dx_LabelAtlas_initWithString(lua_State* tolua_S) ok = true; do{ if (argc == 5) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.LabelAtlas:initWithString"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.LabelAtlas:initWithString"); if (!ok) { break; } cocos2d::Texture2D* arg1; @@ -57554,8 +57364,8 @@ int lua_cocos2dx_LabelAtlas_getString(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_LabelAtlas_getString'", nullptr); return 0; } - std::string_view ret = cobj->getString(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getString(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.LabelAtlas:getString",argc, 0); @@ -57586,11 +57396,11 @@ int lua_cocos2dx_LabelAtlas_create(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.LabelAtlas:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.LabelAtlas:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.LabelAtlas:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.LabelAtlas:create"); if (!ok) { break; } cocos2d::LabelAtlas* ret = cocos2d::LabelAtlas::create(arg0, arg1); object_to_luaval(tolua_S, "cc.LabelAtlas",(cocos2d::LabelAtlas*)ret); @@ -57602,11 +57412,11 @@ int lua_cocos2dx_LabelAtlas_create(lua_State* tolua_S) { if (argc == 5) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.LabelAtlas:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.LabelAtlas:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.LabelAtlas:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.LabelAtlas:create"); if (!ok) { break; } int arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.LabelAtlas:create"); @@ -57627,8 +57437,8 @@ int lua_cocos2dx_LabelAtlas_create(lua_State* tolua_S) { if (argc == 5) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.LabelAtlas:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.LabelAtlas:create"); if (!ok) { break; } cocos2d::Texture2D* arg1; ok &= luaval_to_object(tolua_S, 3, "cc.Texture2D",&arg1, "cc.LabelAtlas:create"); @@ -60862,8 +60672,8 @@ int lua_cocos2dx_MenuItemLabel_getString(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_MenuItemLabel_getString'", nullptr); return 0; } - std::string_view ret = cobj->getString(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + std::string ret = cobj->getString(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.MenuItemLabel:getString",argc, 0); @@ -60951,9 +60761,9 @@ int lua_cocos2dx_MenuItemLabel_setString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.MenuItemLabel:setString"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.MenuItemLabel:setString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_MenuItemLabel_setString'", nullptr); @@ -61219,16 +61029,16 @@ int lua_cocos2dx_MenuItemAtlasFont_initWithString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 6) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; int arg2; int arg3; int32_t arg4; std::function arg5; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.MenuItemAtlasFont:initWithString"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.MenuItemAtlasFont:initWithString"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.MenuItemAtlasFont:initWithString"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.MenuItemAtlasFont:initWithString"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.MenuItemAtlasFont:initWithString"); @@ -61351,8 +61161,8 @@ int lua_cocos2dx_MenuItemFont_getFontNameObj(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_MenuItemFont_getFontNameObj'", nullptr); return 0; } - std::string_view ret = cobj->getFontNameObj(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getFontNameObj(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.MenuItemFont:getFontNameObj",argc, 0); @@ -61393,9 +61203,9 @@ int lua_cocos2dx_MenuItemFont_setFontNameObj(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.MenuItemFont:setFontNameObj"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.MenuItemFont:setFontNameObj"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_MenuItemFont_setFontNameObj'", nullptr); @@ -61443,10 +61253,10 @@ int lua_cocos2dx_MenuItemFont_initWithString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; std::function arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.MenuItemFont:initWithString"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.MenuItemFont:initWithString"); do { // Lambda binding for lua is not supported. @@ -61586,8 +61396,8 @@ int lua_cocos2dx_MenuItemFont_setFontName(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.MenuItemFont:setFontName"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.MenuItemFont:setFontName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_MenuItemFont_setFontName'", nullptr); @@ -61661,8 +61471,8 @@ int lua_cocos2dx_MenuItemFont_getFontName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_MenuItemFont_getFontName'", nullptr); return 0; } - std::string_view ret = cocos2d::MenuItemFont::getFontName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cocos2d::MenuItemFont::getFontName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "cc.MenuItemFont:getFontName",argc, 0); @@ -62565,16 +62375,16 @@ int lua_cocos2dx_MenuItemImage_initWithNormalImage(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 4) { - std::string_view arg0; - std::string_view arg1; - std::string_view arg2; + std::string arg0; + std::string arg1; + std::string arg2; std::function arg3; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.MenuItemImage:initWithNormalImage"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.MenuItemImage:initWithNormalImage"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.MenuItemImage:initWithNormalImage"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.MenuItemImage:initWithNormalImage"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.MenuItemImage:initWithNormalImage"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.MenuItemImage:initWithNormalImage"); do { // Lambda binding for lua is not supported. @@ -63973,8 +63783,8 @@ int lua_cocos2dx_MotionStreak_initWithFade(lua_State* tolua_S) ok &= luaval_to_color3b(tolua_S, 5, &arg3, "cc.MotionStreak:initWithFade"); if (!ok) { break; } - std::string_view arg4; - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.MotionStreak:initWithFade"); + std::string arg4; + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.MotionStreak:initWithFade"); if (!ok) { break; } bool ret = cobj->initWithFade(arg0, arg1, arg2, arg3, arg4); @@ -64148,8 +63958,8 @@ int lua_cocos2dx_MotionStreak_create(lua_State* tolua_S) cocos2d::Color3B arg3; ok &= luaval_to_color3b(tolua_S, 5, &arg3, "cc.MotionStreak:create"); if (!ok) { break; } - std::string_view arg4; - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.MotionStreak:create"); + std::string arg4; + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.MotionStreak:create"); if (!ok) { break; } cocos2d::MotionStreak* ret = cocos2d::MotionStreak::create(arg0, arg1, arg2, arg3, arg4); object_to_luaval(tolua_S, "cc.MotionStreak",(cocos2d::MotionStreak*)ret); @@ -64866,10 +64676,10 @@ int lua_cocos2dx_ParticleBatchNode_initWithFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; int arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.ParticleBatchNode:initWithFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.ParticleBatchNode:initWithFile"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "cc.ParticleBatchNode:initWithFile"); if(!ok) @@ -65208,8 +65018,8 @@ int lua_cocos2dx_ParticleBatchNode_create(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.ParticleBatchNode:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.ParticleBatchNode:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ParticleBatchNode_create'", nullptr); @@ -65221,9 +65031,9 @@ int lua_cocos2dx_ParticleBatchNode_create(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; int arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.ParticleBatchNode:create"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.ParticleBatchNode:create"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "cc.ParticleBatchNode:create"); if(!ok) { @@ -68266,8 +68076,8 @@ int lua_cocos2dx_ParticleSystem_getResourceFile(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ParticleSystem_getResourceFile'", nullptr); return 0; } - std::string_view ret = cobj->getResourceFile(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getResourceFile(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.ParticleSystem:getResourceFile",argc, 0); @@ -69184,9 +68994,9 @@ int lua_cocos2dx_ParticleSystem_initWithFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.ParticleSystem:initWithFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.ParticleSystem:initWithFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ParticleSystem_initWithFile'", nullptr); @@ -70388,8 +70198,8 @@ int lua_cocos2dx_ParticleSystem_initWithDictionary(lua_State* tolua_S) ok &= luaval_to_ccvaluemap(tolua_S, 2, &arg0, "cc.ParticleSystem:initWithDictionary"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.ParticleSystem:initWithDictionary"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.ParticleSystem:initWithDictionary"); if (!ok) { break; } bool ret = cobj->initWithDictionary(arg0, arg1); @@ -70772,8 +70582,8 @@ int lua_cocos2dx_ParticleSystem_create(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.ParticleSystem:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.ParticleSystem:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ParticleSystem_create'", nullptr); @@ -71198,8 +71008,8 @@ int lua_cocos2dx_ParticleSystemQuad_create(lua_State* tolua_S) { if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.ParticleSystemQuad:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.ParticleSystemQuad:create"); if (!ok) { break; } cocos2d::ParticleSystemQuad* ret = cocos2d::ParticleSystemQuad::create(arg0); object_to_luaval(tolua_S, "cc.ParticleSystemQuad",(cocos2d::ParticleSystemQuad*)ret); @@ -75175,8 +74985,8 @@ int lua_cocos2dx_Sprite_setSpriteFrame(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite:setSpriteFrame"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite:setSpriteFrame"); if (!ok) { break; } cobj->setSpriteFrame(arg0); @@ -75230,8 +75040,8 @@ int lua_cocos2dx_Sprite_setTexture(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite:setTexture"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite:setTexture"); if (!ok) { break; } cobj->setTexture(arg0); @@ -75472,10 +75282,10 @@ int lua_cocos2dx_Sprite_setDisplayFrameWithAnimationName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; unsigned int arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite:setDisplayFrameWithAnimationName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite:setDisplayFrameWithAnimationName"); ok &= luaval_to_uint32(tolua_S, 3,&arg1, "cc.Sprite:setDisplayFrameWithAnimationName"); if(!ok) @@ -75766,8 +75576,8 @@ int lua_cocos2dx_Sprite_setTextureRect(lua_State* tolua_S) ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.Sprite:setTextureRect"); if (!ok) { break; } - cocos2d::Vec2 arg2; - ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.Sprite:setTextureRect"); + cocos2d::Size arg2; + ok &= luaval_to_size(tolua_S, 4, &arg2, "cc.Sprite:setTextureRect"); if (!ok) { break; } cobj->setTextureRect(arg0, arg1, arg2); @@ -75826,9 +75636,9 @@ int lua_cocos2dx_Sprite_initWithSpriteFrameName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite:initWithSpriteFrameName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite:initWithSpriteFrameName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Sprite_initWithSpriteFrameName'", nullptr); @@ -76369,8 +76179,8 @@ int lua_cocos2dx_Sprite_getResourceName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Sprite_getResourceName'", nullptr); return 0; } - std::string_view ret = cobj->getResourceName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getResourceName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Sprite:getResourceName",argc, 0); @@ -76773,8 +76583,8 @@ int lua_cocos2dx_Sprite_initWithFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite:initWithFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite:initWithFile"); if (!ok) { break; } cocos2d::Rect arg1; @@ -76789,8 +76599,8 @@ int lua_cocos2dx_Sprite_initWithFile(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite:initWithFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite:initWithFile"); if (!ok) { break; } bool ret = cobj->initWithFile(arg0); @@ -77187,8 +76997,8 @@ int lua_cocos2dx_Sprite_createWithSpriteFrameName(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite:createWithSpriteFrameName"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite:createWithSpriteFrameName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Sprite_createWithSpriteFrameName'", nullptr); @@ -77758,8 +77568,8 @@ int lua_cocos2dx_RenderTexture_saveToFileAsNonPMA(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 4) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFileAsNonPMA"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFileAsNonPMA"); if (!ok) { break; } cocos2d::Image::Format arg1; @@ -77770,7 +77580,7 @@ int lua_cocos2dx_RenderTexture_saveToFileAsNonPMA(lua_State* tolua_S) ok &= luaval_to_boolean(tolua_S, 4,&arg2, "cc.RenderTexture:saveToFileAsNonPMA"); if (!ok) { break; } - std::function arg3; + std::function arg3; do { // Lambda binding for lua is not supported. assert(false); @@ -77786,8 +77596,8 @@ int lua_cocos2dx_RenderTexture_saveToFileAsNonPMA(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFileAsNonPMA"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFileAsNonPMA"); if (!ok) { break; } bool ret = cobj->saveToFileAsNonPMA(arg0); @@ -77798,8 +77608,8 @@ int lua_cocos2dx_RenderTexture_saveToFileAsNonPMA(lua_State* tolua_S) ok = true; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFileAsNonPMA"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFileAsNonPMA"); if (!ok) { break; } bool arg1; @@ -77814,15 +77624,15 @@ int lua_cocos2dx_RenderTexture_saveToFileAsNonPMA(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFileAsNonPMA"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFileAsNonPMA"); if (!ok) { break; } bool arg1; ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.RenderTexture:saveToFileAsNonPMA"); if (!ok) { break; } - std::function arg2; + std::function arg2; do { // Lambda binding for lua is not supported. assert(false); @@ -78016,8 +77826,8 @@ int lua_cocos2dx_RenderTexture_saveToFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); if (!ok) { break; } cocos2d::Image::Format arg1; @@ -78032,8 +77842,8 @@ int lua_cocos2dx_RenderTexture_saveToFile(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); if (!ok) { break; } cocos2d::Image::Format arg1; @@ -78052,8 +77862,8 @@ int lua_cocos2dx_RenderTexture_saveToFile(lua_State* tolua_S) ok = true; do{ if (argc == 4) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); if (!ok) { break; } cocos2d::Image::Format arg1; @@ -78064,7 +77874,7 @@ int lua_cocos2dx_RenderTexture_saveToFile(lua_State* tolua_S) ok &= luaval_to_boolean(tolua_S, 4,&arg2, "cc.RenderTexture:saveToFile"); if (!ok) { break; } - std::function arg3; + std::function arg3; do { // Lambda binding for lua is not supported. assert(false); @@ -78080,8 +77890,8 @@ int lua_cocos2dx_RenderTexture_saveToFile(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); if (!ok) { break; } bool ret = cobj->saveToFile(arg0); @@ -78092,8 +77902,8 @@ int lua_cocos2dx_RenderTexture_saveToFile(lua_State* tolua_S) ok = true; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); if (!ok) { break; } bool arg1; @@ -78108,15 +77918,15 @@ int lua_cocos2dx_RenderTexture_saveToFile(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); if (!ok) { break; } bool arg1; ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.RenderTexture:saveToFile"); if (!ok) { break; } - std::function arg2; + std::function arg2; do { // Lambda binding for lua is not supported. assert(false); @@ -82247,9 +82057,9 @@ int lua_cocos2dx_TransitionFadeTR_actionWithSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.TransitionFadeTR:actionWithSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.TransitionFadeTR:actionWithSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TransitionFadeTR_actionWithSize'", nullptr); @@ -82683,9 +82493,9 @@ int lua_cocos2dx_TransitionPageTurn_actionWithSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.TransitionPageTurn:actionWithSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.TransitionPageTurn:actionWithSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TransitionPageTurn_actionWithSize'", nullptr); @@ -85477,18 +85287,18 @@ int lua_cocos2dx_CameraBackgroundBrush_createSkyboxBrush(lua_State* tolua_S) if (argc == 6) { - std::string_view arg0; - std::string_view arg1; - std::string_view arg2; - std::string_view arg3; - std::string_view arg4; - std::string_view arg5; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CameraBackgroundBrush:createSkyboxBrush"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.CameraBackgroundBrush:createSkyboxBrush"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.CameraBackgroundBrush:createSkyboxBrush"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "cc.CameraBackgroundBrush:createSkyboxBrush"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.CameraBackgroundBrush:createSkyboxBrush"); - ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "cc.CameraBackgroundBrush:createSkyboxBrush"); + std::string arg0; + std::string arg1; + std::string arg2; + std::string arg3; + std::string arg4; + std::string arg5; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CameraBackgroundBrush:createSkyboxBrush"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.CameraBackgroundBrush:createSkyboxBrush"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.CameraBackgroundBrush:createSkyboxBrush"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "cc.CameraBackgroundBrush:createSkyboxBrush"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.CameraBackgroundBrush:createSkyboxBrush"); + ok &= luaval_to_std_string(tolua_S, 7,&arg5, "cc.CameraBackgroundBrush:createSkyboxBrush"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_CameraBackgroundBrush_createSkyboxBrush'", nullptr); @@ -86254,23 +86064,23 @@ int lua_cocos2dx_CameraBackgroundSkyBoxBrush_create(lua_State* tolua_S) { if (argc == 6) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CameraBackgroundSkyBoxBrush:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CameraBackgroundSkyBoxBrush:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.CameraBackgroundSkyBoxBrush:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.CameraBackgroundSkyBoxBrush:create"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.CameraBackgroundSkyBoxBrush:create"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.CameraBackgroundSkyBoxBrush:create"); if (!ok) { break; } - std::string_view arg3; - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "cc.CameraBackgroundSkyBoxBrush:create"); + std::string arg3; + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "cc.CameraBackgroundSkyBoxBrush:create"); if (!ok) { break; } - std::string_view arg4; - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.CameraBackgroundSkyBoxBrush:create"); + std::string arg4; + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.CameraBackgroundSkyBoxBrush:create"); if (!ok) { break; } - std::string_view arg5; - ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "cc.CameraBackgroundSkyBoxBrush:create"); + std::string arg5; + ok &= luaval_to_std_string(tolua_S, 7,&arg5, "cc.CameraBackgroundSkyBoxBrush:create"); if (!ok) { break; } cocos2d::CameraBackgroundSkyBoxBrush* ret = cocos2d::CameraBackgroundSkyBoxBrush::create(arg0, arg1, arg2, arg3, arg4, arg5); object_to_luaval(tolua_S, "cc.CameraBackgroundSkyBoxBrush",(cocos2d::CameraBackgroundSkyBoxBrush*)ret); @@ -86377,9 +86187,9 @@ int lua_cocos2dx_GridBase_setGridSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.GridBase:setGridSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.GridBase:setGridSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GridBase_setGridSize'", nullptr); @@ -86717,8 +86527,8 @@ int lua_cocos2dx_GridBase_getGridSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GridBase_getGridSize'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getGridSize(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getGridSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.GridBase:getGridSize",argc, 0); @@ -87139,8 +86949,8 @@ int lua_cocos2dx_GridBase_initWithSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.GridBase:initWithSize"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.GridBase:initWithSize"); if (!ok) { break; } cocos2d::Rect arg1; @@ -87155,8 +86965,8 @@ int lua_cocos2dx_GridBase_initWithSize(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.GridBase:initWithSize"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.GridBase:initWithSize"); if (!ok) { break; } bool ret = cobj->initWithSize(arg0); @@ -87167,8 +86977,8 @@ int lua_cocos2dx_GridBase_initWithSize(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.GridBase:initWithSize"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.GridBase:initWithSize"); if (!ok) { break; } cocos2d::Texture2D* arg1; @@ -87187,8 +86997,8 @@ int lua_cocos2dx_GridBase_initWithSize(lua_State* tolua_S) ok = true; do{ if (argc == 4) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.GridBase:initWithSize"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.GridBase:initWithSize"); if (!ok) { break; } cocos2d::Texture2D* arg1; @@ -87568,8 +87378,8 @@ int lua_cocos2dx_Grid3D_create(lua_State* tolua_S) { if (argc == 2) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.Grid3D:create"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.Grid3D:create"); if (!ok) { break; } cocos2d::Rect arg1; ok &= luaval_to_rect(tolua_S, 3, &arg1, "cc.Grid3D:create"); @@ -87584,8 +87394,8 @@ int lua_cocos2dx_Grid3D_create(lua_State* tolua_S) { if (argc == 1) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.Grid3D:create"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.Grid3D:create"); if (!ok) { break; } cocos2d::Grid3D* ret = cocos2d::Grid3D::create(arg0); object_to_luaval(tolua_S, "cc.Grid3D",(cocos2d::Grid3D*)ret); @@ -87597,8 +87407,8 @@ int lua_cocos2dx_Grid3D_create(lua_State* tolua_S) { if (argc == 3) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.Grid3D:create"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.Grid3D:create"); if (!ok) { break; } cocos2d::Texture2D* arg1; ok &= luaval_to_object(tolua_S, 3, "cc.Texture2D",&arg1, "cc.Grid3D:create"); @@ -87616,8 +87426,8 @@ int lua_cocos2dx_Grid3D_create(lua_State* tolua_S) { if (argc == 4) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.Grid3D:create"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.Grid3D:create"); if (!ok) { break; } cocos2d::Texture2D* arg1; ok &= luaval_to_object(tolua_S, 3, "cc.Texture2D",&arg1, "cc.Grid3D:create"); @@ -87720,8 +87530,8 @@ int lua_cocos2dx_TiledGrid3D_create(lua_State* tolua_S) { if (argc == 2) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.TiledGrid3D:create"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.TiledGrid3D:create"); if (!ok) { break; } cocos2d::Rect arg1; ok &= luaval_to_rect(tolua_S, 3, &arg1, "cc.TiledGrid3D:create"); @@ -87736,8 +87546,8 @@ int lua_cocos2dx_TiledGrid3D_create(lua_State* tolua_S) { if (argc == 1) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.TiledGrid3D:create"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.TiledGrid3D:create"); if (!ok) { break; } cocos2d::TiledGrid3D* ret = cocos2d::TiledGrid3D::create(arg0); object_to_luaval(tolua_S, "cc.TiledGrid3D",(cocos2d::TiledGrid3D*)ret); @@ -87749,8 +87559,8 @@ int lua_cocos2dx_TiledGrid3D_create(lua_State* tolua_S) { if (argc == 3) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.TiledGrid3D:create"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.TiledGrid3D:create"); if (!ok) { break; } cocos2d::Texture2D* arg1; ok &= luaval_to_object(tolua_S, 3, "cc.Texture2D",&arg1, "cc.TiledGrid3D:create"); @@ -87768,8 +87578,8 @@ int lua_cocos2dx_TiledGrid3D_create(lua_State* tolua_S) { if (argc == 4) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.TiledGrid3D:create"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.TiledGrid3D:create"); if (!ok) { break; } cocos2d::Texture2D* arg1; ok &= luaval_to_object(tolua_S, 3, "cc.Texture2D",&arg1, "cc.TiledGrid3D:create"); @@ -90110,9 +89920,9 @@ int lua_cocos2dx_Material_setName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Material:setName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Material:setName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Material_setName'", nullptr); @@ -90351,9 +90161,9 @@ int lua_cocos2dx_Material_setTechnique(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Material:setTechnique"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Material:setTechnique"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Material_setTechnique'", nullptr); @@ -90401,9 +90211,9 @@ int lua_cocos2dx_Material_getTechniqueByName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Material:getTechniqueByName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Material:getTechniqueByName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Material_getTechniqueByName'", nullptr); @@ -90537,8 +90347,8 @@ int lua_cocos2dx_Material_createWithFilename(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Material:createWithFilename"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Material:createWithFilename"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Material_createWithFilename'", nullptr); @@ -91057,9 +90867,9 @@ int lua_cocos2dx_Pass_setName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Pass:setName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Pass:setName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Pass_setName'", nullptr); @@ -91112,8 +90922,8 @@ int lua_cocos2dx_Pass_getName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Pass_getName'", nullptr); return 0; } - std::string_view ret = cobj->getName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Pass:getName",argc, 0); @@ -93800,11 +93610,11 @@ int lua_cocos2dx_Renderer_checkVisibility(lua_State* tolua_S) if (argc == 2) { cocos2d::Mat4 arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; ok &= luaval_to_mat4(tolua_S, 2, &arg0, "cc.Renderer:checkVisibility"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Renderer:checkVisibility"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Renderer:checkVisibility"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Renderer_checkVisibility'", nullptr); @@ -94951,9 +94761,9 @@ int lua_cocos2dx_TextureCache_reloadTexture(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TextureCache:reloadTexture"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TextureCache:reloadTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TextureCache_reloadTexture'", nullptr); @@ -95048,9 +94858,9 @@ int lua_cocos2dx_TextureCache_removeTextureForKey(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TextureCache:removeTextureForKey"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TextureCache:removeTextureForKey"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TextureCache_removeTextureForKey'", nullptr); @@ -95238,8 +95048,8 @@ int lua_cocos2dx_TextureCache_addImage(lua_State* tolua_S) ok &= luaval_to_object(tolua_S, 2, "cc.Image",&arg0, "cc.TextureCache:addImage"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.TextureCache:addImage"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.TextureCache:addImage"); if (!ok) { break; } cocos2d::Texture2D* ret = cobj->addImage(arg0, arg1); @@ -95250,8 +95060,8 @@ int lua_cocos2dx_TextureCache_addImage(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TextureCache:addImage"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TextureCache:addImage"); if (!ok) { break; } cocos2d::Texture2D* ret = cobj->addImage(arg0); @@ -95298,9 +95108,9 @@ int lua_cocos2dx_TextureCache_unbindImageAsync(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TextureCache:unbindImageAsync"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TextureCache:unbindImageAsync"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TextureCache_unbindImageAsync'", nullptr); @@ -95348,9 +95158,9 @@ int lua_cocos2dx_TextureCache_getTextureForKey(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TextureCache:getTextureForKey"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TextureCache:getTextureForKey"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TextureCache_getTextureForKey'", nullptr); @@ -95448,12 +95258,12 @@ int lua_cocos2dx_TextureCache_renameTextureWithKey(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TextureCache:renameTextureWithKey"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TextureCache:renameTextureWithKey"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.TextureCache:renameTextureWithKey"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.TextureCache:renameTextureWithKey"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TextureCache_renameTextureWithKey'", nullptr); @@ -95634,8 +95444,8 @@ int lua_cocos2dx_TextureCache_setETC1AlphaFileSuffix(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TextureCache:setETC1AlphaFileSuffix"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TextureCache:setETC1AlphaFileSuffix"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TextureCache_setETC1AlphaFileSuffix'", nullptr); @@ -96131,9 +95941,9 @@ int lua_cocos2dx_Application_openURL(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Application:openURL"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Application:openURL"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Application_openURL'", nullptr); @@ -96327,9 +96137,9 @@ int lua_cocos2dx_GLViewImpl_createWithRect(lua_State* tolua_S) if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::Rect arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.GLViewImpl:createWithRect"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.GLViewImpl:createWithRect"); ok &= luaval_to_rect(tolua_S, 3, &arg1, "cc.GLViewImpl:createWithRect"); if(!ok) { @@ -96342,10 +96152,10 @@ int lua_cocos2dx_GLViewImpl_createWithRect(lua_State* tolua_S) } if (argc == 3) { - std::string_view arg0; + std::string arg0; cocos2d::Rect arg1; double arg2; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.GLViewImpl:createWithRect"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.GLViewImpl:createWithRect"); ok &= luaval_to_rect(tolua_S, 3, &arg1, "cc.GLViewImpl:createWithRect"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.GLViewImpl:createWithRect"); if(!ok) @@ -96382,8 +96192,8 @@ int lua_cocos2dx_GLViewImpl_create(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.GLViewImpl:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.GLViewImpl:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GLViewImpl_create'", nullptr); @@ -96418,8 +96228,8 @@ int lua_cocos2dx_GLViewImpl_createWithFullScreen(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.GLViewImpl:createWithFullScreen"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.GLViewImpl:createWithFullScreen"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GLViewImpl_createWithFullScreen'", nullptr); @@ -96487,9 +96297,9 @@ int lua_cocos2dx_AnimationCache_getAnimation(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AnimationCache:getAnimation"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AnimationCache:getAnimation"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_AnimationCache_getAnimation'", nullptr); @@ -96538,11 +96348,11 @@ int lua_cocos2dx_AnimationCache_addAnimation(lua_State* tolua_S) if (argc == 2) { cocos2d::Animation* arg0; - std::string_view arg1; + std::string arg1; ok &= luaval_to_object(tolua_S, 2, "cc.Animation",&arg0, "cc.AnimationCache:addAnimation"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.AnimationCache:addAnimation"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.AnimationCache:addAnimation"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_AnimationCache_addAnimation'", nullptr); @@ -96638,11 +96448,11 @@ int lua_cocos2dx_AnimationCache_addAnimationsWithDictionary(lua_State* tolua_S) if (argc == 2) { cocos2d::ValueMap arg0; - std::string_view arg1; + std::string arg1; ok &= luaval_to_ccvaluemap(tolua_S, 2, &arg0, "cc.AnimationCache:addAnimationsWithDictionary"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.AnimationCache:addAnimationsWithDictionary"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.AnimationCache:addAnimationsWithDictionary"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_AnimationCache_addAnimationsWithDictionary'", nullptr); @@ -96690,9 +96500,9 @@ int lua_cocos2dx_AnimationCache_removeAnimation(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AnimationCache:removeAnimation"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AnimationCache:removeAnimation"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_AnimationCache_removeAnimation'", nullptr); @@ -96740,9 +96550,9 @@ int lua_cocos2dx_AnimationCache_addAnimationsWithFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AnimationCache:addAnimationsWithFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AnimationCache:addAnimationsWithFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_AnimationCache_addAnimationsWithFile'", nullptr); @@ -97746,9 +97556,9 @@ int lua_cocos2dx_SpriteBatchNode_initWithFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteBatchNode:initWithFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteBatchNode:initWithFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteBatchNode_initWithFile'", nullptr); @@ -97760,10 +97570,10 @@ int lua_cocos2dx_SpriteBatchNode_initWithFile(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; ssize_t arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteBatchNode:initWithFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteBatchNode:initWithFile"); ok &= luaval_to_ssize_t(tolua_S, 3, &arg1, "cc.SpriteBatchNode:initWithFile"); if(!ok) @@ -98002,8 +97812,8 @@ int lua_cocos2dx_SpriteBatchNode_create(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteBatchNode:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteBatchNode:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteBatchNode_create'", nullptr); @@ -98015,9 +97825,9 @@ int lua_cocos2dx_SpriteBatchNode_create(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; ssize_t arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteBatchNode:create"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteBatchNode:create"); ok &= luaval_to_ssize_t(tolua_S, 3, &arg1, "cc.SpriteBatchNode:create"); if(!ok) { @@ -98214,9 +98024,9 @@ int lua_cocos2dx_SpriteFrameCache_reloadTexture(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:reloadTexture"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:reloadTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrameCache_reloadTexture'", nullptr); @@ -98315,11 +98125,11 @@ int lua_cocos2dx_SpriteFrameCache_addSpriteFrame(lua_State* tolua_S) if (argc == 2) { cocos2d::SpriteFrame* arg0; - std::string_view arg1; + std::string arg1; ok &= luaval_to_object(tolua_S, 2, "cc.SpriteFrame",&arg0, "cc.SpriteFrameCache:addSpriteFrame"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.SpriteFrameCache:addSpriteFrame"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.SpriteFrameCache:addSpriteFrame"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrameCache_addSpriteFrame'", nullptr); @@ -98367,9 +98177,9 @@ int lua_cocos2dx_SpriteFrameCache_findFrame(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:findFrame"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:findFrame"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrameCache_findFrame'", nullptr); @@ -98412,12 +98222,12 @@ int lua_cocos2dx_SpriteFrameCache_addSpriteFramesWithFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.SpriteFrameCache:addSpriteFramesWithFile"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.SpriteFrameCache:addSpriteFramesWithFile"); if (!ok) { break; } cobj->addSpriteFramesWithFile(arg0, arg1); @@ -98428,12 +98238,12 @@ int lua_cocos2dx_SpriteFrameCache_addSpriteFramesWithFile(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.SpriteFrameCache:addSpriteFramesWithFile"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.SpriteFrameCache:addSpriteFramesWithFile"); if (!ok) { break; } unsigned int arg2; @@ -98448,8 +98258,8 @@ int lua_cocos2dx_SpriteFrameCache_addSpriteFramesWithFile(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); if (!ok) { break; } cobj->addSpriteFramesWithFile(arg0); @@ -98460,8 +98270,8 @@ int lua_cocos2dx_SpriteFrameCache_addSpriteFramesWithFile(lua_State* tolua_S) ok = true; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); if (!ok) { break; } unsigned int arg1; @@ -98476,8 +98286,8 @@ int lua_cocos2dx_SpriteFrameCache_addSpriteFramesWithFile(lua_State* tolua_S) ok = true; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); if (!ok) { break; } cocos2d::Texture2D* arg1; @@ -98492,8 +98302,8 @@ int lua_cocos2dx_SpriteFrameCache_addSpriteFramesWithFile(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); if (!ok) { break; } cocos2d::Texture2D* arg1; @@ -98548,9 +98358,9 @@ int lua_cocos2dx_SpriteFrameCache_getSpriteFrameByName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:getSpriteFrameByName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:getSpriteFrameByName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrameCache_getSpriteFrameByName'", nullptr); @@ -98654,9 +98464,9 @@ int lua_cocos2dx_SpriteFrameCache_removeSpriteFramesFromFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:removeSpriteFramesFromFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:removeSpriteFramesFromFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrameCache_removeSpriteFramesFromFile'", nullptr); @@ -98895,9 +98705,9 @@ int lua_cocos2dx_SpriteFrameCache_removeSpriteFramesFromFileContent(lua_State* t argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:removeSpriteFramesFromFileContent"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:removeSpriteFramesFromFileContent"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrameCache_removeSpriteFramesFromFileContent'", nullptr); @@ -98945,9 +98755,9 @@ int lua_cocos2dx_SpriteFrameCache_removeSpriteFrameByName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:removeSpriteFrameByName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:removeSpriteFrameByName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrameCache_removeSpriteFrameByName'", nullptr); @@ -98995,9 +98805,9 @@ int lua_cocos2dx_SpriteFrameCache_eraseFrame(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:eraseFrame"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:eraseFrame"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrameCache_eraseFrame'", nullptr); @@ -99045,9 +98855,9 @@ int lua_cocos2dx_SpriteFrameCache_isSpriteFramesWithFileLoaded(lua_State* tolua_ argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:isSpriteFramesWithFileLoaded"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:isSpriteFramesWithFileLoaded"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrameCache_isSpriteFramesWithFileLoaded'", nullptr); @@ -99504,9 +99314,9 @@ int lua_cocos2dx_TMXObjectGroup_getProperty(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXObjectGroup:getProperty"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXObjectGroup:getProperty"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXObjectGroup_getProperty'", nullptr); @@ -99601,9 +99411,9 @@ int lua_cocos2dx_TMXObjectGroup_getObject(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXObjectGroup:getObject"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXObjectGroup:getObject"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXObjectGroup_getObject'", nullptr); @@ -99698,9 +99508,9 @@ int lua_cocos2dx_TMXObjectGroup_setGroupName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXObjectGroup:setGroupName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXObjectGroup:setGroupName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXObjectGroup_setGroupName'", nullptr); @@ -99800,8 +99610,8 @@ int lua_cocos2dx_TMXObjectGroup_getGroupName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXObjectGroup_getGroupName'", nullptr); return 0; } - std::string_view ret = cobj->getGroupName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getGroupName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.TMXObjectGroup:getGroupName",argc, 0); @@ -100273,9 +100083,9 @@ int lua_cocos2dx_TMXMapInfo_setCurrentString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXMapInfo:setCurrentString"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXMapInfo:setCurrentString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_setCurrentString'", nullptr); @@ -100370,9 +100180,9 @@ int lua_cocos2dx_TMXMapInfo_setTileSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.TMXMapInfo:setTileSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.TMXMapInfo:setTileSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_setTileSize'", nullptr); @@ -100567,9 +100377,9 @@ int lua_cocos2dx_TMXMapInfo_parseXMLFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXMapInfo:parseXMLFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXMapInfo:parseXMLFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_parseXMLFile'", nullptr); @@ -100664,9 +100474,9 @@ int lua_cocos2dx_TMXMapInfo_setTMXFileName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXMapInfo:setTMXFileName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXMapInfo:setTMXFileName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_setTMXFileName'", nullptr); @@ -100714,9 +100524,9 @@ int lua_cocos2dx_TMXMapInfo_parseXMLString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXMapInfo:parseXMLString"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXMapInfo:parseXMLString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_parseXMLString'", nullptr); @@ -100908,9 +100718,9 @@ int lua_cocos2dx_TMXMapInfo_initWithTMXFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXMapInfo:initWithTMXFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXMapInfo:initWithTMXFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_initWithTMXFile'", nullptr); @@ -101102,12 +100912,12 @@ int lua_cocos2dx_TMXMapInfo_initWithXML(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXMapInfo:initWithXML"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXMapInfo:initWithXML"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.TMXMapInfo:initWithXML"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.TMXMapInfo:initWithXML"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_initWithXML'", nullptr); @@ -101257,8 +101067,8 @@ int lua_cocos2dx_TMXMapInfo_getTileSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_getTileSize'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getTileSize(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getTileSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.TMXMapInfo:getTileSize",argc, 0); @@ -101398,8 +101208,8 @@ int lua_cocos2dx_TMXMapInfo_getExternalTilesetFileName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_getExternalTilesetFileName'", nullptr); return 0; } - std::string_view ret = cobj->getExternalTilesetFileName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getExternalTilesetFileName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.TMXMapInfo:getExternalTilesetFileName",argc, 0); @@ -101492,8 +101302,8 @@ int lua_cocos2dx_TMXMapInfo_getTMXFileName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_getTMXFileName'", nullptr); return 0; } - std::string_view ret = cobj->getTMXFileName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getTMXFileName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.TMXMapInfo:getTMXFileName",argc, 0); @@ -101734,9 +101544,9 @@ int lua_cocos2dx_TMXMapInfo_setMapSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.TMXMapInfo:setMapSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.TMXMapInfo:setMapSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_setMapSize'", nullptr); @@ -101789,8 +101599,8 @@ int lua_cocos2dx_TMXMapInfo_getCurrentString(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_getCurrentString'", nullptr); return 0; } - std::string_view ret = cobj->getCurrentString(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getCurrentString(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.TMXMapInfo:getCurrentString",argc, 0); @@ -101936,8 +101746,8 @@ int lua_cocos2dx_TMXMapInfo_getMapSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_getMapSize'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getMapSize(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getMapSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.TMXMapInfo:getMapSize",argc, 0); @@ -102161,8 +101971,8 @@ int lua_cocos2dx_TMXMapInfo_create(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXMapInfo:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXMapInfo:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_create'", nullptr); @@ -102197,10 +102007,10 @@ int lua_cocos2dx_TMXMapInfo_createWithXML(lua_State* tolua_S) if (argc == 2) { - std::string_view arg0; - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXMapInfo:createWithXML"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.TMXMapInfo:createWithXML"); + std::string arg0; + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXMapInfo:createWithXML"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.TMXMapInfo:createWithXML"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_createWithXML'", nullptr); @@ -102344,14 +102154,14 @@ int lua_cocos2dx_TileMapAtlas_initWithTileFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 4) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; int arg2; int arg3; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TileMapAtlas:initWithTileFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TileMapAtlas:initWithTileFile"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.TileMapAtlas:initWithTileFile"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.TileMapAtlas:initWithTileFile"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.TileMapAtlas:initWithTileFile"); @@ -102542,12 +102352,12 @@ int lua_cocos2dx_TileMapAtlas_create(lua_State* tolua_S) if (argc == 4) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; int arg2; int arg3; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TileMapAtlas:create"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.TileMapAtlas:create"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TileMapAtlas:create"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.TileMapAtlas:create"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.TileMapAtlas:create"); ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "cc.TileMapAtlas:create"); if(!ok) @@ -102912,8 +102722,8 @@ int lua_cocos2dx_FastTMXLayer_getLayerSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXLayer_getLayerSize'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getLayerSize(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getLayerSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.FastTMXLayer:getLayerSize",argc, 0); @@ -102954,9 +102764,9 @@ int lua_cocos2dx_FastTMXLayer_setMapTileSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.FastTMXLayer:setMapTileSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.FastTMXLayer:setMapTileSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXLayer_setMapTileSize'", nullptr); @@ -103101,9 +102911,9 @@ int lua_cocos2dx_FastTMXLayer_setLayerName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FastTMXLayer:setLayerName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FastTMXLayer:setLayerName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXLayer_setLayerName'", nullptr); @@ -103423,8 +103233,8 @@ int lua_cocos2dx_FastTMXLayer_getMapTileSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXLayer_getMapTileSize'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getMapTileSize(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getMapTileSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.FastTMXLayer:getMapTileSize",argc, 0); @@ -103465,9 +103275,9 @@ int lua_cocos2dx_FastTMXLayer_getProperty(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FastTMXLayer:getProperty"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FastTMXLayer:getProperty"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXLayer_getProperty'", nullptr); @@ -103515,9 +103325,9 @@ int lua_cocos2dx_FastTMXLayer_setLayerSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.FastTMXLayer:setLayerSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.FastTMXLayer:setLayerSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXLayer_setLayerSize'", nullptr); @@ -103570,8 +103380,8 @@ int lua_cocos2dx_FastTMXLayer_getLayerName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXLayer_getLayerName'", nullptr); return 0; } - std::string_view ret = cobj->getLayerName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getLayerName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.FastTMXLayer:getLayerName",argc, 0); @@ -104471,9 +104281,9 @@ int lua_cocos2dx_FastTMXTiledMap_getProperty(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:getProperty"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:getProperty"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_getProperty'", nullptr); @@ -104521,9 +104331,9 @@ int lua_cocos2dx_FastTMXTiledMap_setMapSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.FastTMXTiledMap:setMapSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.FastTMXTiledMap:setMapSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_setMapSize'", nullptr); @@ -104571,9 +104381,9 @@ int lua_cocos2dx_FastTMXTiledMap_getObjectGroup(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:getObjectGroup"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:getObjectGroup"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_getObjectGroup'", nullptr); @@ -104626,8 +104436,8 @@ int lua_cocos2dx_FastTMXTiledMap_getResourceFile(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_getResourceFile'", nullptr); return 0; } - std::string_view ret = cobj->getResourceFile(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getResourceFile(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.FastTMXTiledMap:getResourceFile",argc, 0); @@ -104762,9 +104572,9 @@ int lua_cocos2dx_FastTMXTiledMap_initWithTMXFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:initWithTMXFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:initWithTMXFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_initWithTMXFile'", nullptr); @@ -104817,8 +104627,8 @@ int lua_cocos2dx_FastTMXTiledMap_getTileSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_getTileSize'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getTileSize(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getTileSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.FastTMXTiledMap:getTileSize",argc, 0); @@ -104864,8 +104674,8 @@ int lua_cocos2dx_FastTMXTiledMap_getMapSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_getMapSize'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getMapSize(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getMapSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.FastTMXTiledMap:getMapSize",argc, 0); @@ -104956,12 +104766,12 @@ int lua_cocos2dx_FastTMXTiledMap_initWithXML(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:initWithXML"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:initWithXML"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FastTMXTiledMap:initWithXML"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FastTMXTiledMap:initWithXML"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_initWithXML'", nullptr); @@ -105106,9 +104916,9 @@ int lua_cocos2dx_FastTMXTiledMap_setTileSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.FastTMXTiledMap:setTileSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.FastTMXTiledMap:setTileSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_setTileSize'", nullptr); @@ -105206,9 +105016,9 @@ int lua_cocos2dx_FastTMXTiledMap_getLayer(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:getLayer"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:getLayer"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_getLayer'", nullptr); @@ -105342,8 +105152,8 @@ int lua_cocos2dx_FastTMXTiledMap_create(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_create'", nullptr); @@ -105378,10 +105188,10 @@ int lua_cocos2dx_FastTMXTiledMap_createWithXML(lua_State* tolua_S) if (argc == 2) { - std::string_view arg0; - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:createWithXML"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FastTMXTiledMap:createWithXML"); + std::string arg0; + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:createWithXML"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FastTMXTiledMap:createWithXML"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_createWithXML'", nullptr); @@ -106026,8 +105836,8 @@ int lua_cocos2dx_MotionStreak3D_initWithFade(lua_State* tolua_S) ok &= luaval_to_color3b(tolua_S, 5, &arg3, "cc.MotionStreak3D:initWithFade"); if (!ok) { break; } - std::string_view arg4; - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.MotionStreak3D:initWithFade"); + std::string arg4; + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.MotionStreak3D:initWithFade"); if (!ok) { break; } bool ret = cobj->initWithFade(arg0, arg1, arg2, arg3, arg4); @@ -106201,8 +106011,8 @@ int lua_cocos2dx_MotionStreak3D_create(lua_State* tolua_S) cocos2d::Color3B arg3; ok &= luaval_to_color3b(tolua_S, 5, &arg3, "cc.MotionStreak3D:create"); if (!ok) { break; } - std::string_view arg4; - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.MotionStreak3D:create"); + std::string arg4; + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.MotionStreak3D:create"); if (!ok) { break; } cocos2d::MotionStreak3D* ret = cocos2d::MotionStreak3D::create(arg0, arg1, arg2, arg3, arg4); object_to_luaval(tolua_S, "cc.MotionStreak3D",(cocos2d::MotionStreak3D*)ret); @@ -106403,8 +106213,8 @@ int lua_cocos2dx_ComponentLua_create(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.ComponentLua:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.ComponentLua:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ComponentLua_create'", nullptr); @@ -106437,9 +106247,9 @@ int lua_cocos2dx_ComponentLua_constructor(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.ComponentLua:ComponentLua"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.ComponentLua:ComponentLua"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ComponentLua_constructor'", nullptr); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_auto.hpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_auto.hpp index d7b8e611d9..3e1cc6c6fe 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_auto.hpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_auto.hpp @@ -2328,10 +2328,6 @@ int register_all_cocos2dx(lua_State* tolua_S); - - - - diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_backend_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_backend_auto.cpp index 2523bad860..57a704777b 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_backend_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_backend_auto.cpp @@ -572,8 +572,8 @@ int lua_cocos2dx_backend_Program_getFragmentShader(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_backend_Program_getFragmentShader'", nullptr); return 0; } - std::string_view ret = cobj->getFragmentShader(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getFragmentShader(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccb.Program:getFragmentShader",argc, 0); @@ -671,8 +671,8 @@ int lua_cocos2dx_backend_Program_getUniformLocation(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccb.Program:getUniformLocation"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccb.Program:getUniformLocation"); if (!ok) { break; } cocos2d::backend::UniformLocation ret = cobj->getUniformLocation(arg0); @@ -771,7 +771,7 @@ int lua_cocos2dx_backend_Program_getActiveAttributes(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_backend_Program_getActiveAttributes'", nullptr); return 0; } - tsl::robin_map ret = cobj->getActiveAttributes(); + std::unordered_map ret = cobj->getActiveAttributes(); program_activeattrs_to_luaval(tolua_S, ret); return 1; } @@ -820,8 +820,8 @@ int lua_cocos2dx_backend_Program_getAttributeLocation(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccb.Program:getAttributeLocation"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccb.Program:getAttributeLocation"); if (!ok) { break; } int ret = cobj->getAttributeLocation(arg0); @@ -873,8 +873,8 @@ int lua_cocos2dx_backend_Program_getVertexShader(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_backend_Program_getVertexShader'", nullptr); return 0; } - std::string_view ret = cobj->getVertexShader(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getVertexShader(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccb.Program:getVertexShader",argc, 0); @@ -1125,13 +1125,13 @@ int lua_cocos2dx_backend_VertexLayout_setAttribute(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 5) { - std::string_view arg0; + std::string arg0; unsigned int arg1; cocos2d::backend::VertexFormat arg2; unsigned int arg3; bool arg4; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccb.VertexLayout:setAttribute"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccb.VertexLayout:setAttribute"); ok &= luaval_to_uint32(tolua_S, 3,&arg1, "ccb.VertexLayout:setAttribute"); @@ -1293,8 +1293,8 @@ int lua_cocos2dx_backend_ProgramState_setTexture(lua_State* tolua_S) ok &= luaval_to_uniformLocation(tolua_S, 2, arg0, "ccb.ProgramState:setTexture"); if (!ok) { break; } - int arg1; - ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccb.ProgramState:setTexture"); + unsigned short arg1; + ok &= luaval_to_ushort(tolua_S, 3, &arg1, "ccb.ProgramState:setTexture"); if (!ok) { break; } cocos2d::backend::TextureBackend* arg2; @@ -1325,12 +1325,12 @@ int lua_cocos2dx_backend_ProgramState_setTexture(lua_State* tolua_S) ok &= luaval_to_uniformLocation(tolua_S, 2, arg0, "ccb.ProgramState:setTexture"); if (!ok) { break; } - int arg1; - ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccb.ProgramState:setTexture"); + unsigned short arg1; + ok &= luaval_to_ushort(tolua_S, 3, &arg1, "ccb.ProgramState:setTexture"); if (!ok) { break; } - int arg2; - ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "ccb.ProgramState:setTexture"); + unsigned short arg2; + ok &= luaval_to_ushort(tolua_S, 4, &arg2, "ccb.ProgramState:setTexture"); if (!ok) { break; } cocos2d::backend::TextureBackend* arg3; @@ -1489,12 +1489,12 @@ int lua_cocos2dx_backend_ProgramState_setParameterAutoBinding(lua_State* tolua_S argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccb.ProgramState:setParameterAutoBinding"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccb.ProgramState:setParameterAutoBinding"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccb.ProgramState:setParameterAutoBinding"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccb.ProgramState:setParameterAutoBinding"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_backend_ProgramState_setParameterAutoBinding'", nullptr); @@ -1643,8 +1643,8 @@ int lua_cocos2dx_backend_ProgramState_getAttributeLocation(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccb.ProgramState:getAttributeLocation"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccb.ProgramState:getAttributeLocation"); if (!ok) { break; } int ret = cobj->getAttributeLocation(arg0); @@ -2992,12 +2992,12 @@ int lua_cocos2dx_backend_Device_newProgram(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccb.Device:newProgram"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccb.Device:newProgram"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccb.Device:newProgram"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccb.Device:newProgram"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_backend_Device_newProgram'", nullptr); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_controller_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_controller_auto.cpp index 589c61ad7f..de4305f33e 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_controller_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_controller_auto.cpp @@ -90,8 +90,8 @@ int lua_cocos2dx_controller_Controller_getDeviceName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_controller_Controller_getDeviceName'", nullptr); return 0; } - std::string_view ret = cobj->getDeviceName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getDeviceName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Controller:getDeviceName",argc, 0); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_csloader_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_csloader_auto.cpp index 30343b1ce5..fd903bb404 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_csloader_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_csloader_auto.cpp @@ -31,9 +31,9 @@ int lua_cocos2dx_csloader_CSLoader_createNodeFromJson(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CSLoader:createNodeFromJson"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CSLoader:createNodeFromJson"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_csloader_CSLoader_createNodeFromJson'", nullptr); @@ -81,9 +81,9 @@ int lua_cocos2dx_csloader_CSLoader_createNodeWithFlatBuffersFile(lua_State* tolu argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CSLoader:createNodeWithFlatBuffersFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CSLoader:createNodeWithFlatBuffersFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_csloader_CSLoader_createNodeWithFlatBuffersFile'", nullptr); @@ -131,9 +131,9 @@ int lua_cocos2dx_csloader_CSLoader_loadNodeWithFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CSLoader:loadNodeWithFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CSLoader:loadNodeWithFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_csloader_CSLoader_loadNodeWithFile'", nullptr); @@ -181,14 +181,14 @@ int lua_cocos2dx_csloader_CSLoader_bindCallback(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 4) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; cocos2d::ui::Widget* arg2; cocos2d::Node* arg3; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CSLoader:bindCallback"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CSLoader:bindCallback"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.CSLoader:bindCallback"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.CSLoader:bindCallback"); ok &= luaval_to_object(tolua_S, 4, "ccui.Widget",&arg2, "cc.CSLoader:bindCallback"); @@ -337,9 +337,9 @@ int lua_cocos2dx_csloader_CSLoader_loadNodeWithContent(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CSLoader:loadNodeWithContent"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CSLoader:loadNodeWithContent"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_csloader_CSLoader_loadNodeWithContent'", nullptr); @@ -531,9 +531,9 @@ int lua_cocos2dx_csloader_CSLoader_createNodeWithFlatBuffersForSimulator(lua_Sta argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CSLoader:createNodeWithFlatBuffersForSimulator"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CSLoader:createNodeWithFlatBuffersForSimulator"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_csloader_CSLoader_createNodeWithFlatBuffersForSimulator'", nullptr); @@ -605,8 +605,8 @@ int lua_cocos2dx_csloader_CSLoader_createNodeWithVisibleSize(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CSLoader:createNodeWithVisibleSize"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CSLoader:createNodeWithVisibleSize"); if (!ok) { break; } std::function arg1; do { @@ -625,8 +625,8 @@ int lua_cocos2dx_csloader_CSLoader_createNodeWithVisibleSize(lua_State* tolua_S) { if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CSLoader:createNodeWithVisibleSize"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CSLoader:createNodeWithVisibleSize"); if (!ok) { break; } cocos2d::Node* ret = cocos2d::CSLoader::createNodeWithVisibleSize(arg0); object_to_luaval(tolua_S, "cc.Node",(cocos2d::Node*)ret); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_extension_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_extension_auto.cpp index 0daaca8566..bd14221311 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_extension_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_extension_auto.cpp @@ -471,8 +471,8 @@ int lua_cocos2dx_extension_AssetsManager_getVersion(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_AssetsManager_getVersion'", nullptr); return 0; } - std::string_view ret = cobj->getVersion(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + std::string ret = cobj->getVersion(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.AssetsManager:getVersion",argc, 0); @@ -1158,11 +1158,11 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 3) { - std::string_view arg0; + std::string arg0; cocos2d::extension::AssetsManagerEx* arg1; cocos2d::extension::EventAssetsManagerEx::EventCode arg2; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); ok &= luaval_to_object(tolua_S, 3, "cc.AssetsManagerEx",&arg1, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); @@ -1181,12 +1181,12 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) } if (argc == 4) { - std::string_view arg0; + std::string arg0; cocos2d::extension::AssetsManagerEx* arg1; cocos2d::extension::EventAssetsManagerEx::EventCode arg2; double arg3; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); ok &= luaval_to_object(tolua_S, 3, "cc.AssetsManagerEx",&arg1, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); @@ -1207,13 +1207,13 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) } if (argc == 5) { - std::string_view arg0; + std::string arg0; cocos2d::extension::AssetsManagerEx* arg1; cocos2d::extension::EventAssetsManagerEx::EventCode arg2; double arg3; double arg4; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); ok &= luaval_to_object(tolua_S, 3, "cc.AssetsManagerEx",&arg1, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); @@ -1236,14 +1236,14 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) } if (argc == 6) { - std::string_view arg0; + std::string arg0; cocos2d::extension::AssetsManagerEx* arg1; cocos2d::extension::EventAssetsManagerEx::EventCode arg2; double arg3; double arg4; - std::string_view arg5; + std::string arg5; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); ok &= luaval_to_object(tolua_S, 3, "cc.AssetsManagerEx",&arg1, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); @@ -1253,7 +1253,7 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 6,&arg4, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); - ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string(tolua_S, 7,&arg5, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_EventAssetsManagerEx_constructor'", nullptr); @@ -1268,15 +1268,15 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) } if (argc == 7) { - std::string_view arg0; + std::string arg0; cocos2d::extension::AssetsManagerEx* arg1; cocos2d::extension::EventAssetsManagerEx::EventCode arg2; double arg3; double arg4; - std::string_view arg5; - std::string_view arg6; + std::string arg5; + std::string arg6; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); ok &= luaval_to_object(tolua_S, 3, "cc.AssetsManagerEx",&arg1, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); @@ -1286,9 +1286,9 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 6,&arg4, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); - ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string(tolua_S, 7,&arg5, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); - ok &= luaval_to_std_string_view(tolua_S, 8,&arg6, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string(tolua_S, 8,&arg6, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_EventAssetsManagerEx_constructor'", nullptr); @@ -1303,16 +1303,16 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) } if (argc == 8) { - std::string_view arg0; + std::string arg0; cocos2d::extension::AssetsManagerEx* arg1; cocos2d::extension::EventAssetsManagerEx::EventCode arg2; double arg3; double arg4; - std::string_view arg5; - std::string_view arg6; + std::string arg5; + std::string arg6; int arg7; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); ok &= luaval_to_object(tolua_S, 3, "cc.AssetsManagerEx",&arg1, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); @@ -1322,9 +1322,9 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 6,&arg4, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); - ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string(tolua_S, 7,&arg5, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); - ok &= luaval_to_std_string_view(tolua_S, 8,&arg6, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string(tolua_S, 8,&arg6, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); ok &= luaval_to_int32(tolua_S, 9,(int *)&arg7, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); if(!ok) @@ -1341,17 +1341,17 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) } if (argc == 9) { - std::string_view arg0; + std::string arg0; cocos2d::extension::AssetsManagerEx* arg1; cocos2d::extension::EventAssetsManagerEx::EventCode arg2; double arg3; double arg4; - std::string_view arg5; - std::string_view arg6; + std::string arg5; + std::string arg6; int arg7; int arg8; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); ok &= luaval_to_object(tolua_S, 3, "cc.AssetsManagerEx",&arg1, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); @@ -1361,9 +1361,9 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 6,&arg4, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); - ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string(tolua_S, 7,&arg5, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); - ok &= luaval_to_std_string_view(tolua_S, 8,&arg6, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string(tolua_S, 8,&arg6, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); ok &= luaval_to_int32(tolua_S, 9,(int *)&arg7, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); @@ -1451,8 +1451,8 @@ int lua_cocos2dx_extension_Manifest_getManifestFileUrl(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_Manifest_getManifestFileUrl'", nullptr); return 0; } - std::string_view ret = cobj->getManifestFileUrl(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getManifestFileUrl(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Manifest:getManifestFileUrl",argc, 0); @@ -1592,8 +1592,8 @@ int lua_cocos2dx_extension_Manifest_getPackageUrl(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_Manifest_getPackageUrl'", nullptr); return 0; } - std::string_view ret = cobj->getPackageUrl(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getPackageUrl(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Manifest:getPackageUrl",argc, 0); @@ -1639,8 +1639,8 @@ int lua_cocos2dx_extension_Manifest_getVersion(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_Manifest_getVersion'", nullptr); return 0; } - std::string_view ret = cobj->getVersion(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getVersion(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Manifest:getVersion",argc, 0); @@ -1686,8 +1686,8 @@ int lua_cocos2dx_extension_Manifest_getVersionFileUrl(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_Manifest_getVersionFileUrl'", nullptr); return 0; } - std::string_view ret = cobj->getVersionFileUrl(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getVersionFileUrl(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Manifest:getVersionFileUrl",argc, 0); @@ -1942,7 +1942,7 @@ int lua_cocos2dx_extension_AssetsManagerEx_setVerifyCallback(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::function arg0; + std::function arg0; do { // Lambda binding for lua is not supported. @@ -2001,8 +2001,8 @@ int lua_cocos2dx_extension_AssetsManagerEx_getStoragePath(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_AssetsManagerEx_getStoragePath'", nullptr); return 0; } - std::string_view ret = cobj->getStoragePath(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getStoragePath(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.AssetsManagerEx:getStoragePath",argc, 0); @@ -2090,7 +2090,7 @@ int lua_cocos2dx_extension_AssetsManagerEx_setVersionCompareHandle(lua_State* to argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::function arg0; + std::function arg0; do { // Lambda binding for lua is not supported. @@ -2324,10 +2324,10 @@ int lua_cocos2dx_extension_AssetsManagerEx_create(lua_State* tolua_S) if (argc == 2) { - std::string_view arg0; - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AssetsManagerEx:create"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.AssetsManagerEx:create"); + std::string arg0; + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AssetsManagerEx:create"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.AssetsManagerEx:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_AssetsManagerEx_create'", nullptr); @@ -2360,12 +2360,12 @@ int lua_cocos2dx_extension_AssetsManagerEx_constructor(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AssetsManagerEx:AssetsManagerEx"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AssetsManagerEx:AssetsManagerEx"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.AssetsManagerEx:AssetsManagerEx"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.AssetsManagerEx:AssetsManagerEx"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_AssetsManagerEx_constructor'", nullptr); @@ -3604,9 +3604,9 @@ int lua_cocos2dx_extension_PUParticleSystem3D_initWithFilePath(lua_State* tolua_ argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:initWithFilePath"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:initWithFilePath"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_PUParticleSystem3D_initWithFilePath'", nullptr); @@ -3845,12 +3845,12 @@ int lua_cocos2dx_extension_PUParticleSystem3D_initWithFilePathAndMaterialPath(lu argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:initWithFilePathAndMaterialPath"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:initWithFilePathAndMaterialPath"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.PUParticleSystem3D:initWithFilePathAndMaterialPath"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.PUParticleSystem3D:initWithFilePathAndMaterialPath"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_PUParticleSystem3D_initWithFilePathAndMaterialPath'", nullptr); @@ -3950,8 +3950,8 @@ int lua_cocos2dx_extension_PUParticleSystem3D_getMaterialName(lua_State* tolua_S tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_PUParticleSystem3D_getMaterialName'", nullptr); return 0; } - std::string_view ret = cobj->getMaterialName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getMaterialName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.PUParticleSystem3D:getMaterialName",argc, 0); @@ -4821,9 +4821,9 @@ int lua_cocos2dx_extension_PUParticleSystem3D_setMaterialName(lua_State* tolua_S argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:setMaterialName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:setMaterialName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_PUParticleSystem3D_setMaterialName'", nullptr); @@ -5403,9 +5403,9 @@ int lua_cocos2dx_extension_PUParticleSystem3D_initSystem(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:initSystem"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:initSystem"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_PUParticleSystem3D_initSystem'", nullptr); @@ -5641,8 +5641,8 @@ int lua_cocos2dx_extension_PUParticleSystem3D_create(lua_State* tolua_S) { if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:create"); if (!ok) { break; } cocos2d::PUParticleSystem3D* ret = cocos2d::PUParticleSystem3D::create(arg0); object_to_luaval(tolua_S, "cc.PUParticleSystem3D",(cocos2d::PUParticleSystem3D*)ret); @@ -5664,11 +5664,11 @@ int lua_cocos2dx_extension_PUParticleSystem3D_create(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.PUParticleSystem3D:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.PUParticleSystem3D:create"); if (!ok) { break; } cocos2d::PUParticleSystem3D* ret = cocos2d::PUParticleSystem3D::create(arg0, arg1); object_to_luaval(tolua_S, "cc.PUParticleSystem3D",(cocos2d::PUParticleSystem3D*)ret); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_navmesh_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_navmesh_auto.cpp index abb3bf630a..61117700c3 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_navmesh_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_navmesh_auto.cpp @@ -1424,8 +1424,8 @@ int lua_cocos2dx_navmesh_NavMeshAgent_getNavMeshAgentComponentName(lua_State* to tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_navmesh_NavMeshAgent_getNavMeshAgentComponentName'", nullptr); return 0; } - std::string_view ret = cocos2d::NavMeshAgent::getNavMeshAgentComponentName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cocos2d::NavMeshAgent::getNavMeshAgentComponentName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "cc.NavMeshAgent:getNavMeshAgentComponentName",argc, 0); @@ -1958,8 +1958,8 @@ int lua_cocos2dx_navmesh_NavMeshObstacle_getNavMeshObstacleComponentName(lua_Sta tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_navmesh_NavMeshObstacle_getNavMeshObstacleComponentName'", nullptr); return 0; } - std::string_view ret = cocos2d::NavMeshObstacle::getNavMeshObstacleComponentName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cocos2d::NavMeshObstacle::getNavMeshObstacleComponentName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "cc.NavMeshObstacle:getNavMeshObstacleComponentName",argc, 0); @@ -2450,10 +2450,10 @@ int lua_cocos2dx_navmesh_NavMesh_create(lua_State* tolua_S) if (argc == 2) { - std::string_view arg0; - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.NavMesh:create"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.NavMesh:create"); + std::string arg0; + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.NavMesh:create"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.NavMesh:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_navmesh_NavMesh_create'", nullptr); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_physics_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_physics_auto.cpp index 79c3f641c7..5d72cd0e8e 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_physics_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_physics_auto.cpp @@ -1930,8 +1930,8 @@ int lua_cocos2dx_physics_PhysicsShapeBox_getSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_physics_PhysicsShapeBox_getSize'", nullptr); return 0; } - cocos2d::Vec2 ret = cobj->getSize(); - vec2_to_luaval(tolua_S, ret); + cocos2d::Size ret = cobj->getSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.PhysicsShapeBox:getSize",argc, 0); @@ -1961,8 +1961,8 @@ int lua_cocos2dx_physics_PhysicsShapeBox_create(lua_State* tolua_S) if (argc == 1) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsShapeBox:create"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsShapeBox:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_physics_PhysicsShapeBox_create'", nullptr); @@ -1974,9 +1974,9 @@ int lua_cocos2dx_physics_PhysicsShapeBox_create(lua_State* tolua_S) } if (argc == 2) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; cocos2d::PhysicsMaterial arg1; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsShapeBox:create"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsShapeBox:create"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsShapeBox:create"); if(!ok) { @@ -1989,10 +1989,10 @@ int lua_cocos2dx_physics_PhysicsShapeBox_create(lua_State* tolua_S) } if (argc == 3) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; cocos2d::PhysicsMaterial arg1; cocos2d::Vec2 arg2; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsShapeBox:create"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsShapeBox:create"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsShapeBox:create"); ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.PhysicsShapeBox:create"); if(!ok) @@ -2006,11 +2006,11 @@ int lua_cocos2dx_physics_PhysicsShapeBox_create(lua_State* tolua_S) } if (argc == 4) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; cocos2d::PhysicsMaterial arg1; cocos2d::Vec2 arg2; double arg3; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsShapeBox:create"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsShapeBox:create"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsShapeBox:create"); ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.PhysicsShapeBox:create"); ok &= luaval_to_number(tolua_S, 5,&arg3, "cc.PhysicsShapeBox:create"); @@ -2326,8 +2326,8 @@ int lua_cocos2dx_physics_PhysicsShapeEdgeBox_create(lua_State* tolua_S) if (argc == 1) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsShapeEdgeBox:create"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsShapeEdgeBox:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_physics_PhysicsShapeEdgeBox_create'", nullptr); @@ -2339,9 +2339,9 @@ int lua_cocos2dx_physics_PhysicsShapeEdgeBox_create(lua_State* tolua_S) } if (argc == 2) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; cocos2d::PhysicsMaterial arg1; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsShapeEdgeBox:create"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsShapeEdgeBox:create"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsShapeEdgeBox:create"); if(!ok) { @@ -2354,10 +2354,10 @@ int lua_cocos2dx_physics_PhysicsShapeEdgeBox_create(lua_State* tolua_S) } if (argc == 3) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; cocos2d::PhysicsMaterial arg1; double arg2; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsShapeEdgeBox:create"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsShapeEdgeBox:create"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsShapeEdgeBox:create"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.PhysicsShapeEdgeBox:create"); if(!ok) @@ -2371,11 +2371,11 @@ int lua_cocos2dx_physics_PhysicsShapeEdgeBox_create(lua_State* tolua_S) } if (argc == 4) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; cocos2d::PhysicsMaterial arg1; double arg2; cocos2d::Vec2 arg3; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsShapeEdgeBox:create"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsShapeEdgeBox:create"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsShapeEdgeBox:create"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.PhysicsShapeEdgeBox:create"); ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.PhysicsShapeEdgeBox:create"); @@ -5515,8 +5515,8 @@ int lua_cocos2dx_physics_PhysicsBody_createBox(lua_State* tolua_S) if (argc == 1) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsBody:createBox"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsBody:createBox"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_physics_PhysicsBody_createBox'", nullptr); @@ -5528,9 +5528,9 @@ int lua_cocos2dx_physics_PhysicsBody_createBox(lua_State* tolua_S) } if (argc == 2) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; cocos2d::PhysicsMaterial arg1; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsBody:createBox"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsBody:createBox"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsBody:createBox"); if(!ok) { @@ -5543,10 +5543,10 @@ int lua_cocos2dx_physics_PhysicsBody_createBox(lua_State* tolua_S) } if (argc == 3) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; cocos2d::PhysicsMaterial arg1; cocos2d::Vec2 arg2; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsBody:createBox"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsBody:createBox"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsBody:createBox"); ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.PhysicsBody:createBox"); if(!ok) @@ -5718,8 +5718,8 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgeBox(lua_State* tolua_S) if (argc == 1) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsBody:createEdgeBox"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsBody:createEdgeBox"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_physics_PhysicsBody_createEdgeBox'", nullptr); @@ -5731,9 +5731,9 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgeBox(lua_State* tolua_S) } if (argc == 2) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; cocos2d::PhysicsMaterial arg1; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsBody:createEdgeBox"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsBody:createEdgeBox"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsBody:createEdgeBox"); if(!ok) { @@ -5746,10 +5746,10 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgeBox(lua_State* tolua_S) } if (argc == 3) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; cocos2d::PhysicsMaterial arg1; double arg2; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsBody:createEdgeBox"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsBody:createEdgeBox"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsBody:createEdgeBox"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.PhysicsBody:createEdgeBox"); if(!ok) @@ -5763,11 +5763,11 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgeBox(lua_State* tolua_S) } if (argc == 4) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; cocos2d::PhysicsMaterial arg1; double arg2; cocos2d::Vec2 arg3; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsBody:createEdgeBox"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsBody:createEdgeBox"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsBody:createEdgeBox"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.PhysicsBody:createEdgeBox"); ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.PhysicsBody:createEdgeBox"); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp index 1887d9bfb8..35b2be46df 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp @@ -3232,8 +3232,8 @@ int lua_cocos2dx_studio_DisplayData_changeDisplayToTexture(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.DisplayData:changeDisplayToTexture"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.DisplayData:changeDisplayToTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_DisplayData_changeDisplayToTexture'", nullptr); @@ -4039,9 +4039,9 @@ int lua_cocos2dx_studio_ArmatureData_getBoneData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureData:getBoneData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureData:getBoneData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureData_getBoneData'", nullptr); @@ -4569,9 +4569,9 @@ int lua_cocos2dx_studio_MovementData_getMovementBoneData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.MovementData:getMovementBoneData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.MovementData:getMovementBoneData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_MovementData_getMovementBoneData'", nullptr); @@ -4763,9 +4763,9 @@ int lua_cocos2dx_studio_AnimationData_getMovement(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.AnimationData:getMovement"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.AnimationData:getMovement"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_AnimationData_getMovement'", nullptr); @@ -6407,10 +6407,10 @@ int lua_cocos2dx_studio_DisplayManager_changeDisplayWithName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; bool arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.DisplayManager:changeDisplayWithName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.DisplayManager:changeDisplayWithName"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "ccs.DisplayManager:changeDisplayWithName"); if(!ok) @@ -7577,9 +7577,9 @@ int lua_cocos2dx_studio_Bone_init(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Bone:init"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Bone:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_Bone_init'", nullptr); @@ -8031,10 +8031,10 @@ int lua_cocos2dx_studio_Bone_changeDisplayWithName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; bool arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Bone:changeDisplayWithName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Bone:changeDisplayWithName"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "ccs.Bone:changeDisplayWithName"); if(!ok) @@ -8465,8 +8465,8 @@ int lua_cocos2dx_studio_Bone_create(lua_State* tolua_S) { if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Bone:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Bone:create"); if (!ok) { break; } cocostudio::Bone* ret = cocostudio::Bone::create(arg0); object_to_luaval(tolua_S, "ccs.Bone",(cocostudio::Bone*)ret); @@ -8712,9 +8712,9 @@ int lua_cocos2dx_studio_ArmatureAnimation_play(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureAnimation:play"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureAnimation:play"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureAnimation_play'", nullptr); @@ -8726,10 +8726,10 @@ int lua_cocos2dx_studio_ArmatureAnimation_play(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; int arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureAnimation:play"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureAnimation:play"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccs.ArmatureAnimation:play"); if(!ok) @@ -8743,11 +8743,11 @@ int lua_cocos2dx_studio_ArmatureAnimation_play(lua_State* tolua_S) } if (argc == 3) { - std::string_view arg0; + std::string arg0; int arg1; int arg2; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureAnimation:play"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureAnimation:play"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccs.ArmatureAnimation:play"); @@ -9558,9 +9558,9 @@ int lua_cocos2dx_studio_ArmatureDataManager_removeAnimationData(lua_State* tolua argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:removeAnimationData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:removeAnimationData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_removeAnimationData'", nullptr); @@ -9608,10 +9608,10 @@ int lua_cocos2dx_studio_ArmatureDataManager_addArmatureData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; cocostudio::ArmatureData* arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addArmatureData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addArmatureData"); ok &= luaval_to_object(tolua_S, 3, "ccs.ArmatureData",&arg1, "ccs.ArmatureDataManager:addArmatureData"); if(!ok) @@ -9625,15 +9625,15 @@ int lua_cocos2dx_studio_ArmatureDataManager_addArmatureData(lua_State* tolua_S) } if (argc == 3) { - std::string_view arg0; + std::string arg0; cocostudio::ArmatureData* arg1; - std::string_view arg2; + std::string arg2; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addArmatureData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addArmatureData"); ok &= luaval_to_object(tolua_S, 3, "ccs.ArmatureData",&arg1, "ccs.ArmatureDataManager:addArmatureData"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addArmatureData"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addArmatureData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_addArmatureData'", nullptr); @@ -9676,16 +9676,16 @@ int lua_cocos2dx_studio_ArmatureDataManager_addArmatureFileInfo(lua_State* tolua argc = lua_gettop(tolua_S)-1; do{ if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addArmatureFileInfo"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addArmatureFileInfo"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.ArmatureDataManager:addArmatureFileInfo"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.ArmatureDataManager:addArmatureFileInfo"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addArmatureFileInfo"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addArmatureFileInfo"); if (!ok) { break; } cobj->addArmatureFileInfo(arg0, arg1, arg2); @@ -9696,8 +9696,8 @@ int lua_cocos2dx_studio_ArmatureDataManager_addArmatureFileInfo(lua_State* tolua ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addArmatureFileInfo"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addArmatureFileInfo"); if (!ok) { break; } cobj->addArmatureFileInfo(arg0); @@ -9744,9 +9744,9 @@ int lua_cocos2dx_studio_ArmatureDataManager_removeArmatureFileInfo(lua_State* to argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:removeArmatureFileInfo"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:removeArmatureFileInfo"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_removeArmatureFileInfo'", nullptr); @@ -9799,7 +9799,7 @@ int lua_cocos2dx_studio_ArmatureDataManager_getTextureDatas(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_getTextureDatas'", nullptr); return 0; } - const cocos2d::Map& ret = cobj->getTextureDatas(); + const cocos2d::Map& ret = cobj->getTextureDatas(); ccmap_string_key_to_luaval(tolua_S, ret); return 1; } @@ -9841,9 +9841,9 @@ int lua_cocos2dx_studio_ArmatureDataManager_getTextureData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:getTextureData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:getTextureData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_getTextureData'", nullptr); @@ -9891,9 +9891,9 @@ int lua_cocos2dx_studio_ArmatureDataManager_getArmatureData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:getArmatureData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:getArmatureData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_getArmatureData'", nullptr); @@ -9941,9 +9941,9 @@ int lua_cocos2dx_studio_ArmatureDataManager_getAnimationData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:getAnimationData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:getAnimationData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_getAnimationData'", nullptr); @@ -9991,10 +9991,10 @@ int lua_cocos2dx_studio_ArmatureDataManager_addAnimationData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; cocostudio::AnimationData* arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addAnimationData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addAnimationData"); ok &= luaval_to_object(tolua_S, 3, "ccs.AnimationData",&arg1, "ccs.ArmatureDataManager:addAnimationData"); if(!ok) @@ -10008,15 +10008,15 @@ int lua_cocos2dx_studio_ArmatureDataManager_addAnimationData(lua_State* tolua_S) } if (argc == 3) { - std::string_view arg0; + std::string arg0; cocostudio::AnimationData* arg1; - std::string_view arg2; + std::string arg2; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addAnimationData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addAnimationData"); ok &= luaval_to_object(tolua_S, 3, "ccs.AnimationData",&arg1, "ccs.ArmatureDataManager:addAnimationData"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addAnimationData"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addAnimationData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_addAnimationData'", nullptr); @@ -10111,9 +10111,9 @@ int lua_cocos2dx_studio_ArmatureDataManager_removeArmatureData(lua_State* tolua_ argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:removeArmatureData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:removeArmatureData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_removeArmatureData'", nullptr); @@ -10166,7 +10166,7 @@ int lua_cocos2dx_studio_ArmatureDataManager_getArmatureDatas(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_getArmatureDatas'", nullptr); return 0; } - const cocos2d::Map& ret = cobj->getArmatureDatas(); + const cocos2d::Map& ret = cobj->getArmatureDatas(); ccmap_string_key_to_luaval(tolua_S, ret); return 1; } @@ -10208,9 +10208,9 @@ int lua_cocos2dx_studio_ArmatureDataManager_addRelativeData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addRelativeData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addRelativeData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_addRelativeData'", nullptr); @@ -10258,9 +10258,9 @@ int lua_cocos2dx_studio_ArmatureDataManager_removeTextureData(lua_State* tolua_S argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:removeTextureData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:removeTextureData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_removeTextureData'", nullptr); @@ -10308,9 +10308,9 @@ int lua_cocos2dx_studio_ArmatureDataManager_getRelativeData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:getRelativeData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:getRelativeData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_getRelativeData'", nullptr); @@ -10358,10 +10358,10 @@ int lua_cocos2dx_studio_ArmatureDataManager_addTextureData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; cocostudio::TextureData* arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addTextureData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addTextureData"); ok &= luaval_to_object(tolua_S, 3, "ccs.TextureData",&arg1, "ccs.ArmatureDataManager:addTextureData"); if(!ok) @@ -10375,15 +10375,15 @@ int lua_cocos2dx_studio_ArmatureDataManager_addTextureData(lua_State* tolua_S) } if (argc == 3) { - std::string_view arg0; + std::string arg0; cocostudio::TextureData* arg1; - std::string_view arg2; + std::string arg2; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addTextureData"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addTextureData"); ok &= luaval_to_object(tolua_S, 3, "ccs.TextureData",&arg1, "ccs.ArmatureDataManager:addTextureData"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addTextureData"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addTextureData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_addTextureData'", nullptr); @@ -10436,7 +10436,7 @@ int lua_cocos2dx_studio_ArmatureDataManager_getAnimationDatas(lua_State* tolua_S tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_getAnimationDatas'", nullptr); return 0; } - const cocos2d::Map& ret = cobj->getAnimationDatas(); + const cocos2d::Map& ret = cobj->getAnimationDatas(); ccmap_string_key_to_luaval(tolua_S, ret); return 1; } @@ -10525,12 +10525,12 @@ int lua_cocos2dx_studio_ArmatureDataManager_addSpriteFrameFromFile(lua_State* to argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_addSpriteFrameFromFile'", nullptr); @@ -10542,15 +10542,15 @@ int lua_cocos2dx_studio_ArmatureDataManager_addSpriteFrameFromFile(lua_State* to } if (argc == 3) { - std::string_view arg0; - std::string_view arg1; - std::string_view arg2; + std::string arg0; + std::string arg1; + std::string arg2; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_addSpriteFrameFromFile'", nullptr); @@ -10706,9 +10706,9 @@ int lua_cocos2dx_studio_Armature_getBone(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Armature:getBone"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Armature:getBone"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_Armature_getBone'", nullptr); @@ -10757,11 +10757,11 @@ int lua_cocos2dx_studio_Armature_changeBoneParent(lua_State* tolua_S) if (argc == 2) { cocostudio::Bone* arg0; - std::string_view arg1; + std::string arg1; ok &= luaval_to_object(tolua_S, 2, "ccs.Bone",&arg0, "ccs.Armature:changeBoneParent"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.Armature:changeBoneParent"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.Armature:changeBoneParent"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_Armature_changeBoneParent'", nullptr); @@ -11198,8 +11198,8 @@ int lua_cocos2dx_studio_Armature_init(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Armature:init"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Armature:init"); if (!ok) { break; } cocostudio::Bone* arg1; @@ -11214,8 +11214,8 @@ int lua_cocos2dx_studio_Armature_init(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Armature:init"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Armature:init"); if (!ok) { break; } bool ret = cobj->init(arg0); @@ -11460,11 +11460,11 @@ int lua_cocos2dx_studio_Armature_addBone(lua_State* tolua_S) if (argc == 2) { cocostudio::Bone* arg0; - std::string_view arg1; + std::string arg1; ok &= luaval_to_object(tolua_S, 2, "ccs.Bone",&arg0, "ccs.Armature:addBone"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.Armature:addBone"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.Armature:addBone"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_Armature_addBone'", nullptr); @@ -11755,7 +11755,7 @@ int lua_cocos2dx_studio_Armature_getBoneDic(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_Armature_getBoneDic'", nullptr); return 0; } - const cocos2d::Map& ret = cobj->getBoneDic(); + const cocos2d::Map& ret = cobj->getBoneDic(); ccmap_string_key_to_luaval(tolua_S, ret); return 1; } @@ -11787,8 +11787,8 @@ int lua_cocos2dx_studio_Armature_create(lua_State* tolua_S) { if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Armature:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Armature:create"); if (!ok) { break; } cocostudio::Armature* ret = cocostudio::Armature::create(arg0); object_to_luaval(tolua_S, "ccs.Armature",(cocostudio::Armature*)ret); @@ -11810,8 +11810,8 @@ int lua_cocos2dx_studio_Armature_create(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Armature:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Armature:create"); if (!ok) { break; } cocostudio::Bone* arg1; ok &= luaval_to_object(tolua_S, 3, "ccs.Bone",&arg1, "ccs.Armature:create"); @@ -12037,8 +12037,8 @@ int lua_cocos2dx_studio_Skin_getDisplayName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_Skin_getDisplayName'", nullptr); return 0; } - std::string_view ret = cobj->getDisplayName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getDisplayName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccs.Skin:getDisplayName",argc, 0); @@ -12166,8 +12166,8 @@ int lua_cocos2dx_studio_Skin_create(lua_State* tolua_S) { if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Skin:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Skin:create"); if (!ok) { break; } cocostudio::Skin* ret = cocostudio::Skin::create(arg0); object_to_luaval(tolua_S, "ccs.Skin",(cocostudio::Skin*)ret); @@ -12210,8 +12210,8 @@ int lua_cocos2dx_studio_Skin_createWithSpriteFrameName(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Skin:createWithSpriteFrameName"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Skin:createWithSpriteFrameName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_Skin_createWithSpriteFrameName'", nullptr); @@ -12321,9 +12321,9 @@ int lua_cocos2dx_studio_ComAttribute_getFloat(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:getFloat"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:getFloat"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ComAttribute_getFloat'", nullptr); @@ -12335,10 +12335,10 @@ int lua_cocos2dx_studio_ComAttribute_getFloat(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; double arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:getFloat"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:getFloat"); ok &= luaval_to_number(tolua_S, 3,&arg1, "ccs.ComAttribute:getFloat"); if(!ok) @@ -12388,9 +12388,9 @@ int lua_cocos2dx_studio_ComAttribute_getString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:getString"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:getString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ComAttribute_getString'", nullptr); @@ -12402,12 +12402,12 @@ int lua_cocos2dx_studio_ComAttribute_getString(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:getString"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:getString"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.ComAttribute:getString"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.ComAttribute:getString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ComAttribute_getString'", nullptr); @@ -12455,10 +12455,10 @@ int lua_cocos2dx_studio_ComAttribute_setFloat(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; double arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:setFloat"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:setFloat"); ok &= luaval_to_number(tolua_S, 3,&arg1, "ccs.ComAttribute:setFloat"); if(!ok) @@ -12508,12 +12508,12 @@ int lua_cocos2dx_studio_ComAttribute_setString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:setString"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:setString"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.ComAttribute:setString"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.ComAttribute:setString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ComAttribute_setString'", nullptr); @@ -12561,9 +12561,9 @@ int lua_cocos2dx_studio_ComAttribute_getBool(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:getBool"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:getBool"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ComAttribute_getBool'", nullptr); @@ -12575,10 +12575,10 @@ int lua_cocos2dx_studio_ComAttribute_getBool(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; bool arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:getBool"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:getBool"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "ccs.ComAttribute:getBool"); if(!ok) @@ -12628,10 +12628,10 @@ int lua_cocos2dx_studio_ComAttribute_setInt(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; int arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:setInt"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:setInt"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccs.ComAttribute:setInt"); if(!ok) @@ -12681,9 +12681,9 @@ int lua_cocos2dx_studio_ComAttribute_parse(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:parse"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:parse"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ComAttribute_parse'", nullptr); @@ -12731,9 +12731,9 @@ int lua_cocos2dx_studio_ComAttribute_getInt(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:getInt"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:getInt"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ComAttribute_getInt'", nullptr); @@ -12745,10 +12745,10 @@ int lua_cocos2dx_studio_ComAttribute_getInt(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; int arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:getInt"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:getInt"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccs.ComAttribute:getInt"); if(!ok) @@ -12798,10 +12798,10 @@ int lua_cocos2dx_studio_ComAttribute_setBool(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; bool arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:setBool"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:setBool"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "ccs.ComAttribute:setBool"); if(!ok) @@ -14785,9 +14785,9 @@ int lua_cocos2dx_studio_GUIReader_setFilePath(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.GUIReader:setFilePath"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.GUIReader:setFilePath"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_GUIReader_setFilePath'", nullptr); @@ -14890,8 +14890,8 @@ int lua_cocos2dx_studio_GUIReader_getFilePath(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_GUIReader_getFilePath'", nullptr); return 0; } - std::string_view ret = cobj->getFilePath(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getFilePath(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccs.GUIReader:getFilePath",argc, 0); @@ -15180,9 +15180,9 @@ int lua_cocos2dx_studio_SceneReader_createNodeWithSceneFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.SceneReader:createNodeWithSceneFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.SceneReader:createNodeWithSceneFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_SceneReader_createNodeWithSceneFile'", nullptr); @@ -15194,10 +15194,10 @@ int lua_cocos2dx_studio_SceneReader_createNodeWithSceneFile(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocostudio::SceneReader::AttachComponentType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.SceneReader:createNodeWithSceneFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.SceneReader:createNodeWithSceneFile"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccs.SceneReader:createNodeWithSceneFile"); if(!ok) @@ -15472,9 +15472,9 @@ int lua_cocos2dx_studio_ActionTimelineCache_createActionFromJson(lua_State* tolu argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createActionFromJson"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createActionFromJson"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_createActionFromJson'", nullptr); @@ -15522,9 +15522,9 @@ int lua_cocos2dx_studio_ActionTimelineCache_createActionWithFlatBuffersFile(lua_ argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createActionWithFlatBuffersFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createActionWithFlatBuffersFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_createActionWithFlatBuffersFile'", nullptr); @@ -15572,9 +15572,9 @@ int lua_cocos2dx_studio_ActionTimelineCache_loadAnimationActionWithFlatBuffersFi argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:loadAnimationActionWithFlatBuffersFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:loadAnimationActionWithFlatBuffersFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_loadAnimationActionWithFlatBuffersFile'", nullptr); @@ -15622,12 +15622,12 @@ int lua_cocos2dx_studio_ActionTimelineCache_createActionFromContent(lua_State* t argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createActionFromContent"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createActionFromContent"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.ActionTimelineCache:createActionFromContent"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.ActionTimelineCache:createActionFromContent"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_createActionFromContent'", nullptr); @@ -15769,12 +15769,12 @@ int lua_cocos2dx_studio_ActionTimelineCache_loadAnimationActionWithContent(lua_S argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:loadAnimationActionWithContent"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:loadAnimationActionWithContent"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.ActionTimelineCache:loadAnimationActionWithContent"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.ActionTimelineCache:loadAnimationActionWithContent"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_loadAnimationActionWithContent'", nullptr); @@ -15822,9 +15822,9 @@ int lua_cocos2dx_studio_ActionTimelineCache_loadAnimationActionWithFile(lua_Stat argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:loadAnimationActionWithFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:loadAnimationActionWithFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_loadAnimationActionWithFile'", nullptr); @@ -15872,9 +15872,9 @@ int lua_cocos2dx_studio_ActionTimelineCache_removeAction(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:removeAction"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:removeAction"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_removeAction'", nullptr); @@ -15922,9 +15922,9 @@ int lua_cocos2dx_studio_ActionTimelineCache_createActionWithFlatBuffersForSimula argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createActionWithFlatBuffersForSimulator"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createActionWithFlatBuffersForSimulator"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_createActionWithFlatBuffersForSimulator'", nullptr); @@ -15995,8 +15995,8 @@ int lua_cocos2dx_studio_ActionTimelineCache_createAction(lua_State* tolua_S) if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createAction"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createAction"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_createAction'", nullptr); @@ -17029,8 +17029,8 @@ int lua_cocos2dx_studio_TextureFrame_getTextureName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_TextureFrame_getTextureName'", nullptr); return 0; } - std::string_view ret = cobj->getTextureName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + std::string ret = cobj->getTextureName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccs.TextureFrame:getTextureName",argc, 0); @@ -19147,9 +19147,9 @@ int lua_cocos2dx_studio_InnerActionFrame_setAnimationName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.InnerActionFrame:setAnimationName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.InnerActionFrame:setAnimationName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_InnerActionFrame_setAnimationName'", nullptr); @@ -19783,8 +19783,8 @@ int lua_cocos2dx_studio_EventFrame_getEvent(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_EventFrame_getEvent'", nullptr); return 0; } - std::string_view ret = cobj->getEvent(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + std::string ret = cobj->getEvent(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccs.EventFrame:getEvent",argc, 0); @@ -22120,9 +22120,9 @@ int lua_cocos2dx_studio_ActionTimeline_getAnimationInfo(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimeline:getAnimationInfo"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimeline:getAnimationInfo"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimeline_getAnimationInfo'", nullptr); @@ -22218,12 +22218,12 @@ int lua_cocos2dx_studio_ActionTimeline_addFrameEndCallFunc(lua_State* tolua_S) if (argc == 3) { int arg0; - std::string_view arg1; + std::string arg1; std::function arg2; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccs.ActionTimeline:addFrameEndCallFunc"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.ActionTimeline:addFrameEndCallFunc"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.ActionTimeline:addFrameEndCallFunc"); do { // Lambda binding for lua is not supported. @@ -22721,9 +22721,9 @@ int lua_cocos2dx_studio_ActionTimeline_IsAnimationInfoExists(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimeline:IsAnimationInfoExists"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimeline:IsAnimationInfoExists"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimeline_IsAnimationInfoExists'", nullptr); @@ -23016,11 +23016,11 @@ int lua_cocos2dx_studio_ActionTimeline_removeFrameEndCallFunc(lua_State* tolua_S if (argc == 2) { int arg0; - std::string_view arg1; + std::string arg1; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccs.ActionTimeline:removeFrameEndCallFunc"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.ActionTimeline:removeFrameEndCallFunc"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.ActionTimeline:removeFrameEndCallFunc"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimeline_removeFrameEndCallFunc'", nullptr); @@ -23916,8 +23916,8 @@ int lua_cocos2dx_studio_BoneNode_displaySkin(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.BoneNode:displaySkin"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.BoneNode:displaySkin"); if (!ok) { break; } bool arg1; @@ -24605,9 +24605,9 @@ int lua_cocos2dx_studio_SkeletonNode_getBoneNode(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.SkeletonNode:getBoneNode"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.SkeletonNode:getBoneNode"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_SkeletonNode_getBoneNode'", nullptr); @@ -24650,8 +24650,8 @@ int lua_cocos2dx_studio_SkeletonNode_changeSkins(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.SkeletonNode:changeSkins"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.SkeletonNode:changeSkins"); if (!ok) { break; } cobj->changeSkins(arg0); @@ -24662,7 +24662,7 @@ int lua_cocos2dx_studio_SkeletonNode_changeSkins(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - tsl::robin_map arg0; + std::map arg0; ok &= luaval_to_std_map_string_string(tolua_S, 2, &arg0, "ccs.SkeletonNode:changeSkins"); if (!ok) { break; } @@ -24711,7 +24711,7 @@ int lua_cocos2dx_studio_SkeletonNode_addSkinGroup(lua_State* tolua_S) if (argc == 2) { std::string arg0; - tsl::robin_map arg1; + std::map arg1; ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.SkeletonNode:addSkinGroup"); @@ -24768,7 +24768,7 @@ int lua_cocos2dx_studio_SkeletonNode_getAllSubBonesMap(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_SkeletonNode_getAllSubBonesMap'", nullptr); return 0; } - const cocos2d::Map& ret = cobj->getAllSubBonesMap(); + const cocos2d::Map& ret = cobj->getAllSubBonesMap(); ccmap_string_key_to_luaval(tolua_S, ret); return 1; } @@ -25050,9 +25050,9 @@ int lua_cocos2dx_studio_ComExtensionData_setCustomProperty(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComExtensionData:setCustomProperty"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComExtensionData:setCustomProperty"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ComExtensionData_setCustomProperty'", nullptr); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp index c6176f00c0..31cef92257 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp @@ -559,9 +559,9 @@ int lua_cocos2dx_ui_RelativeLayoutParameter_setRelativeToWidgetName(lua_State* t argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RelativeLayoutParameter:setRelativeToWidgetName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RelativeLayoutParameter:setRelativeToWidgetName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RelativeLayoutParameter_setRelativeToWidgetName'", nullptr); @@ -614,8 +614,8 @@ int lua_cocos2dx_ui_RelativeLayoutParameter_getRelativeName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RelativeLayoutParameter_getRelativeName'", nullptr); return 0; } - std::string_view ret = cobj->getRelativeName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getRelativeName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.RelativeLayoutParameter:getRelativeName",argc, 0); @@ -661,8 +661,8 @@ int lua_cocos2dx_ui_RelativeLayoutParameter_getRelativeToWidgetName(lua_State* t tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RelativeLayoutParameter_getRelativeToWidgetName'", nullptr); return 0; } - std::string_view ret = cobj->getRelativeToWidgetName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getRelativeToWidgetName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.RelativeLayoutParameter:getRelativeToWidgetName",argc, 0); @@ -703,9 +703,9 @@ int lua_cocos2dx_ui_RelativeLayoutParameter_setRelativeName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RelativeLayoutParameter:setRelativeName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RelativeLayoutParameter:setRelativeName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RelativeLayoutParameter_setRelativeName'", nullptr); @@ -1003,8 +1003,8 @@ int lua_cocos2dx_ui_Widget_getCustomSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Widget_getCustomSize'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getCustomSize(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getCustomSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Widget:getCustomSize",argc, 0); @@ -1142,9 +1142,9 @@ int lua_cocos2dx_ui_Widget_setCallbackName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Widget:setCallbackName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Widget:setCallbackName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Widget_setCallbackName'", nullptr); @@ -1488,8 +1488,8 @@ int lua_cocos2dx_ui_Widget_getLayoutSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Widget_getLayoutSize'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getLayoutSize(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getLayoutSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Widget:getLayoutSize",argc, 0); @@ -1682,8 +1682,8 @@ int lua_cocos2dx_ui_Widget_getVirtualRendererSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Widget_getVirtualRendererSize'", nullptr); return 0; } - cocos2d::Vec2 ret = cobj->getVirtualRendererSize(); - vec2_to_luaval(tolua_S, ret); + cocos2d::Size ret = cobj->getVirtualRendererSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Widget:getVirtualRendererSize",argc, 0); @@ -2208,8 +2208,8 @@ int lua_cocos2dx_ui_Widget_getCallbackName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Widget_getCallbackName'", nullptr); return 0; } - std::string_view ret = cobj->getCallbackName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getCallbackName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Widget:getCallbackName",argc, 0); @@ -3274,8 +3274,8 @@ int lua_cocos2dx_ui_Widget_updateSizeAndPosition(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 1) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.Widget:updateSizeAndPosition"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.Widget:updateSizeAndPosition"); if (!ok) { break; } cobj->updateSizeAndPosition(arg0); @@ -3482,8 +3482,8 @@ int lua_cocos2dx_ui_Widget_getCallbackType(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Widget_getCallbackType'", nullptr); return 0; } - std::string_view ret = cobj->getCallbackType(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getCallbackType(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Widget:getCallbackType",argc, 0); @@ -3974,9 +3974,9 @@ int lua_cocos2dx_ui_Widget_setCallbackType(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Widget:setCallbackType"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Widget:setCallbackType"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Widget_setCallbackType'", nullptr); @@ -4929,9 +4929,9 @@ int lua_cocos2dx_ui_Layout_setBackGroundImage(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Layout:setBackGroundImage"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Layout:setBackGroundImage"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Layout_setBackGroundImage'", nullptr); @@ -4943,10 +4943,10 @@ int lua_cocos2dx_ui_Layout_setBackGroundImage(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Layout:setBackGroundImage"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Layout:setBackGroundImage"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.Layout:setBackGroundImage"); if(!ok) @@ -5633,8 +5633,8 @@ int lua_cocos2dx_ui_Layout_getBackGroundImageTextureSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Layout_getBackGroundImageTextureSize'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getBackGroundImageTextureSize(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getBackGroundImageTextureSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Layout:getBackGroundImageTextureSize",argc, 0); @@ -6132,8 +6132,8 @@ int lua_cocos2dx_ui_Button_getNormalTextureSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_getNormalTextureSize'", nullptr); return 0; } - cocos2d::Vec2 ret = cobj->getNormalTextureSize(); - vec2_to_luaval(tolua_S, ret); + cocos2d::Size ret = cobj->getNormalTextureSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Button:getNormalTextureSize",argc, 0); @@ -6179,8 +6179,8 @@ int lua_cocos2dx_ui_Button_getTitleText(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_getTitleText'", nullptr); return 0; } - std::string_view ret = cobj->getTitleText(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + std::string ret = cobj->getTitleText(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Button:getTitleText",argc, 0); @@ -6991,9 +6991,9 @@ int lua_cocos2dx_ui_Button_loadTextureDisabled(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:loadTextureDisabled"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:loadTextureDisabled"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_loadTextureDisabled'", nullptr); @@ -7005,10 +7005,10 @@ int lua_cocos2dx_ui_Button_loadTextureDisabled(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:loadTextureDisabled"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:loadTextureDisabled"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.Button:loadTextureDisabled"); if(!ok) @@ -7058,9 +7058,9 @@ int lua_cocos2dx_ui_Button_init(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:init"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_init'", nullptr); @@ -7072,12 +7072,12 @@ int lua_cocos2dx_ui_Button_init(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:init"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:init"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Button:init"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Button:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_init'", nullptr); @@ -7089,15 +7089,15 @@ int lua_cocos2dx_ui_Button_init(lua_State* tolua_S) } if (argc == 3) { - std::string_view arg0; - std::string_view arg1; - std::string_view arg2; + std::string arg0; + std::string arg1; + std::string arg2; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:init"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:init"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Button:init"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Button:init"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.Button:init"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.Button:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_init'", nullptr); @@ -7109,16 +7109,16 @@ int lua_cocos2dx_ui_Button_init(lua_State* tolua_S) } if (argc == 4) { - std::string_view arg0; - std::string_view arg1; - std::string_view arg2; + std::string arg0; + std::string arg1; + std::string arg2; cocos2d::ui::Widget::TextureResType arg3; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:init"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:init"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Button:init"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Button:init"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.Button:init"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.Button:init"); ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "ccui.Button:init"); if(!ok) @@ -7168,9 +7168,9 @@ int lua_cocos2dx_ui_Button_setTitleText(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:setTitleText"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:setTitleText"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_setTitleText'", nullptr); @@ -7268,9 +7268,9 @@ int lua_cocos2dx_ui_Button_loadTexturePressed(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:loadTexturePressed"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:loadTexturePressed"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_loadTexturePressed'", nullptr); @@ -7282,10 +7282,10 @@ int lua_cocos2dx_ui_Button_loadTexturePressed(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:loadTexturePressed"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:loadTexturePressed"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.Button:loadTexturePressed"); if(!ok) @@ -7335,9 +7335,9 @@ int lua_cocos2dx_ui_Button_setTitleFontName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:setTitleFontName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:setTitleFontName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_setTitleFontName'", nullptr); @@ -7538,12 +7538,12 @@ int lua_cocos2dx_ui_Button_loadTextures(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:loadTextures"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Button:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Button:loadTextures"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_loadTextures'", nullptr); @@ -7555,15 +7555,15 @@ int lua_cocos2dx_ui_Button_loadTextures(lua_State* tolua_S) } if (argc == 3) { - std::string_view arg0; - std::string_view arg1; - std::string_view arg2; + std::string arg0; + std::string arg1; + std::string arg2; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:loadTextures"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Button:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Button:loadTextures"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.Button:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.Button:loadTextures"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_loadTextures'", nullptr); @@ -7575,16 +7575,16 @@ int lua_cocos2dx_ui_Button_loadTextures(lua_State* tolua_S) } if (argc == 4) { - std::string_view arg0; - std::string_view arg1; - std::string_view arg2; + std::string arg0; + std::string arg1; + std::string arg2; cocos2d::ui::Widget::TextureResType arg3; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:loadTextures"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Button:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Button:loadTextures"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.Button:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.Button:loadTextures"); ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "ccui.Button:loadTextures"); if(!ok) @@ -7681,9 +7681,9 @@ int lua_cocos2dx_ui_Button_loadTextureNormal(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:loadTextureNormal"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:loadTextureNormal"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_loadTextureNormal'", nullptr); @@ -7695,10 +7695,10 @@ int lua_cocos2dx_ui_Button_loadTextureNormal(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:loadTextureNormal"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:loadTextureNormal"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.Button:loadTextureNormal"); if(!ok) @@ -7991,8 +7991,8 @@ int lua_cocos2dx_ui_Button_getTitleFontName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_getTitleFontName'", nullptr); return 0; } - std::string_view ret = cobj->getTitleFontName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + std::string ret = cobj->getTitleFontName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Button:getTitleFontName",argc, 0); @@ -8170,8 +8170,8 @@ int lua_cocos2dx_ui_Button_create(lua_State* tolua_S) { if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:create"); if (!ok) { break; } cocos2d::ui::Button* ret = cocos2d::ui::Button::create(arg0); object_to_luaval(tolua_S, "ccui.Button",(cocos2d::ui::Button*)ret); @@ -8183,11 +8183,11 @@ int lua_cocos2dx_ui_Button_create(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Button:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Button:create"); if (!ok) { break; } cocos2d::ui::Button* ret = cocos2d::ui::Button::create(arg0, arg1); object_to_luaval(tolua_S, "ccui.Button",(cocos2d::ui::Button*)ret); @@ -8199,14 +8199,14 @@ int lua_cocos2dx_ui_Button_create(lua_State* tolua_S) { if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Button:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Button:create"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.Button:create"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.Button:create"); if (!ok) { break; } cocos2d::ui::Button* ret = cocos2d::ui::Button::create(arg0, arg1, arg2); object_to_luaval(tolua_S, "ccui.Button",(cocos2d::ui::Button*)ret); @@ -8218,14 +8218,14 @@ int lua_cocos2dx_ui_Button_create(lua_State* tolua_S) { if (argc == 4) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Button:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Button:create"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.Button:create"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.Button:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg3; ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "ccui.Button:create"); @@ -8508,9 +8508,9 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureBackGroundSelected(lua_State* argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGroundSelected"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGroundSelected"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_AbstractCheckButton_loadTextureBackGroundSelected'", nullptr); @@ -8522,10 +8522,10 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureBackGroundSelected(lua_State* } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGroundSelected"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGroundSelected"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.AbstractCheckButton:loadTextureBackGroundSelected"); if(!ok) @@ -8575,9 +8575,9 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureBackGroundDisabled(lua_State* argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGroundDisabled"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGroundDisabled"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_AbstractCheckButton_loadTextureBackGroundDisabled'", nullptr); @@ -8589,10 +8589,10 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureBackGroundDisabled(lua_State* } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGroundDisabled"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGroundDisabled"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.AbstractCheckButton:loadTextureBackGroundDisabled"); if(!ok) @@ -8880,9 +8880,9 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureFrontCross(lua_State* tolua_S argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureFrontCross"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureFrontCross"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_AbstractCheckButton_loadTextureFrontCross'", nullptr); @@ -8894,10 +8894,10 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureFrontCross(lua_State* tolua_S } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureFrontCross"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureFrontCross"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.AbstractCheckButton:loadTextureFrontCross"); if(!ok) @@ -9041,21 +9041,21 @@ int lua_cocos2dx_ui_AbstractCheckButton_init(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 5) { - std::string_view arg0; - std::string_view arg1; - std::string_view arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg0; + std::string arg1; + std::string arg2; + std::string arg3; + std::string arg4; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:init"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.AbstractCheckButton:init"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.AbstractCheckButton:init"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.AbstractCheckButton:init"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.AbstractCheckButton:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_AbstractCheckButton_init'", nullptr); @@ -9067,22 +9067,22 @@ int lua_cocos2dx_ui_AbstractCheckButton_init(lua_State* tolua_S) } if (argc == 6) { - std::string_view arg0; - std::string_view arg1; - std::string_view arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg0; + std::string arg1; + std::string arg2; + std::string arg3; + std::string arg4; cocos2d::ui::Widget::TextureResType arg5; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:init"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.AbstractCheckButton:init"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.AbstractCheckButton:init"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.AbstractCheckButton:init"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.AbstractCheckButton:init"); ok &= luaval_to_int32(tolua_S, 7,(int *)&arg5, "ccui.AbstractCheckButton:init"); if(!ok) @@ -9179,21 +9179,21 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextures(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 5) { - std::string_view arg0; - std::string_view arg1; - std::string_view arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg0; + std::string arg1; + std::string arg2; + std::string arg3; + std::string arg4; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextures"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.AbstractCheckButton:loadTextures"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.AbstractCheckButton:loadTextures"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.AbstractCheckButton:loadTextures"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.AbstractCheckButton:loadTextures"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_AbstractCheckButton_loadTextures'", nullptr); @@ -9205,22 +9205,22 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextures(lua_State* tolua_S) } if (argc == 6) { - std::string_view arg0; - std::string_view arg1; - std::string_view arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg0; + std::string arg1; + std::string arg2; + std::string arg3; + std::string arg4; cocos2d::ui::Widget::TextureResType arg5; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextures"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.AbstractCheckButton:loadTextures"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.AbstractCheckButton:loadTextures"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.AbstractCheckButton:loadTextures"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.AbstractCheckButton:loadTextures"); ok &= luaval_to_int32(tolua_S, 7,(int *)&arg5, "ccui.AbstractCheckButton:loadTextures"); if(!ok) @@ -9411,9 +9411,9 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureBackGround(lua_State* tolua_S argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGround"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGround"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_AbstractCheckButton_loadTextureBackGround'", nullptr); @@ -9425,10 +9425,10 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureBackGround(lua_State* tolua_S } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGround"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGround"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.AbstractCheckButton:loadTextureBackGround"); if(!ok) @@ -9528,9 +9528,9 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureFrontCrossDisabled(lua_State* argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureFrontCrossDisabled"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureFrontCrossDisabled"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_AbstractCheckButton_loadTextureFrontCrossDisabled'", nullptr); @@ -9542,10 +9542,10 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureFrontCrossDisabled(lua_State* } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureFrontCrossDisabled"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureFrontCrossDisabled"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.AbstractCheckButton:loadTextureFrontCrossDisabled"); if(!ok) @@ -9679,20 +9679,20 @@ int lua_cocos2dx_ui_CheckBox_create(lua_State* tolua_S) { if (argc == 5) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.CheckBox:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.CheckBox:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.CheckBox:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.CheckBox:create"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.CheckBox:create"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.CheckBox:create"); if (!ok) { break; } - std::string_view arg3; - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.CheckBox:create"); + std::string arg3; + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.CheckBox:create"); if (!ok) { break; } - std::string_view arg4; - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.CheckBox:create"); + std::string arg4; + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.CheckBox:create"); if (!ok) { break; } cocos2d::ui::CheckBox* ret = cocos2d::ui::CheckBox::create(arg0, arg1, arg2, arg3, arg4); object_to_luaval(tolua_S, "ccui.CheckBox",(cocos2d::ui::CheckBox*)ret); @@ -9704,20 +9704,20 @@ int lua_cocos2dx_ui_CheckBox_create(lua_State* tolua_S) { if (argc == 6) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.CheckBox:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.CheckBox:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.CheckBox:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.CheckBox:create"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.CheckBox:create"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.CheckBox:create"); if (!ok) { break; } - std::string_view arg3; - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.CheckBox:create"); + std::string arg3; + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.CheckBox:create"); if (!ok) { break; } - std::string_view arg4; - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.CheckBox:create"); + std::string arg4; + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.CheckBox:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg5; ok &= luaval_to_int32(tolua_S, 7,(int *)&arg5, "ccui.CheckBox:create"); @@ -9742,11 +9742,11 @@ int lua_cocos2dx_ui_CheckBox_create(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.CheckBox:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.CheckBox:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.CheckBox:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.CheckBox:create"); if (!ok) { break; } cocos2d::ui::CheckBox* ret = cocos2d::ui::CheckBox::create(arg0, arg1); object_to_luaval(tolua_S, "ccui.CheckBox",(cocos2d::ui::CheckBox*)ret); @@ -9758,11 +9758,11 @@ int lua_cocos2dx_ui_CheckBox_create(lua_State* tolua_S) { if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.CheckBox:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.CheckBox:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.CheckBox:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.CheckBox:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "ccui.CheckBox:create"); @@ -9947,20 +9947,20 @@ int lua_cocos2dx_ui_RadioButton_create(lua_State* tolua_S) { if (argc == 5) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RadioButton:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RadioButton:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.RadioButton:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.RadioButton:create"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.RadioButton:create"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.RadioButton:create"); if (!ok) { break; } - std::string_view arg3; - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RadioButton:create"); + std::string arg3; + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RadioButton:create"); if (!ok) { break; } - std::string_view arg4; - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RadioButton:create"); + std::string arg4; + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RadioButton:create"); if (!ok) { break; } cocos2d::ui::RadioButton* ret = cocos2d::ui::RadioButton::create(arg0, arg1, arg2, arg3, arg4); object_to_luaval(tolua_S, "ccui.RadioButton",(cocos2d::ui::RadioButton*)ret); @@ -9972,20 +9972,20 @@ int lua_cocos2dx_ui_RadioButton_create(lua_State* tolua_S) { if (argc == 6) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RadioButton:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RadioButton:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.RadioButton:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.RadioButton:create"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.RadioButton:create"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.RadioButton:create"); if (!ok) { break; } - std::string_view arg3; - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RadioButton:create"); + std::string arg3; + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RadioButton:create"); if (!ok) { break; } - std::string_view arg4; - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RadioButton:create"); + std::string arg4; + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RadioButton:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg5; ok &= luaval_to_int32(tolua_S, 7,(int *)&arg5, "ccui.RadioButton:create"); @@ -10010,11 +10010,11 @@ int lua_cocos2dx_ui_RadioButton_create(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RadioButton:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RadioButton:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.RadioButton:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.RadioButton:create"); if (!ok) { break; } cocos2d::ui::RadioButton* ret = cocos2d::ui::RadioButton::create(arg0, arg1); object_to_luaval(tolua_S, "ccui.RadioButton",(cocos2d::ui::RadioButton*)ret); @@ -10026,11 +10026,11 @@ int lua_cocos2dx_ui_RadioButton_create(lua_State* tolua_S) { if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RadioButton:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RadioButton:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.RadioButton:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.RadioButton:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "ccui.RadioButton:create"); @@ -10873,9 +10873,9 @@ int lua_cocos2dx_ui_ImageView_loadTexture(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.ImageView:loadTexture"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.ImageView:loadTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_ImageView_loadTexture'", nullptr); @@ -10887,10 +10887,10 @@ int lua_cocos2dx_ui_ImageView_loadTexture(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.ImageView:loadTexture"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.ImageView:loadTexture"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.ImageView:loadTexture"); if(!ok) @@ -10990,9 +10990,9 @@ int lua_cocos2dx_ui_ImageView_init(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.ImageView:init"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.ImageView:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_ImageView_init'", nullptr); @@ -11004,10 +11004,10 @@ int lua_cocos2dx_ui_ImageView_init(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.ImageView:init"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.ImageView:init"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.ImageView:init"); if(!ok) @@ -11338,8 +11338,8 @@ int lua_cocos2dx_ui_ImageView_create(lua_State* tolua_S) { if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.ImageView:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.ImageView:create"); if (!ok) { break; } cocos2d::ui::ImageView* ret = cocos2d::ui::ImageView::create(arg0); object_to_luaval(tolua_S, "ccui.ImageView",(cocos2d::ui::ImageView*)ret); @@ -11351,8 +11351,8 @@ int lua_cocos2dx_ui_ImageView_create(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.ImageView:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.ImageView:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg1; ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.ImageView:create"); @@ -11538,11 +11538,11 @@ int lua_cocos2dx_ui_Text_enableShadow(lua_State* tolua_S) if (argc == 2) { cocos2d::Color4B arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; ok &=luaval_to_color4b(tolua_S, 2, &arg0, "ccui.Text:enableShadow"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "ccui.Text:enableShadow"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "ccui.Text:enableShadow"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Text_enableShadow'", nullptr); @@ -11555,12 +11555,12 @@ int lua_cocos2dx_ui_Text_enableShadow(lua_State* tolua_S) if (argc == 3) { cocos2d::Color4B arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; int arg2; ok &=luaval_to_color4b(tolua_S, 2, &arg0, "ccui.Text:enableShadow"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "ccui.Text:enableShadow"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "ccui.Text:enableShadow"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "ccui.Text:enableShadow"); if(!ok) @@ -11662,8 +11662,8 @@ int lua_cocos2dx_ui_Text_getString(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Text_getString'", nullptr); return 0; } - std::string_view ret = cobj->getString(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getString(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Text:getString",argc, 0); @@ -11946,9 +11946,9 @@ int lua_cocos2dx_ui_Text_setFontName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Text:setFontName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Text:setFontName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Text_setFontName'", nullptr); @@ -12051,8 +12051,8 @@ int lua_cocos2dx_ui_Text_getShadowOffset(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Text_getShadowOffset'", nullptr); return 0; } - cocos2d::Vec2 ret = cobj->getShadowOffset(); - vec2_to_luaval(tolua_S, ret); + cocos2d::Size ret = cobj->getShadowOffset(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Text:getShadowOffset",argc, 0); @@ -12093,9 +12093,9 @@ int lua_cocos2dx_ui_Text_setString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Text:setString"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Text:setString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Text_setString'", nullptr); @@ -12190,13 +12190,13 @@ int lua_cocos2dx_ui_Text_init(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 3) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; double arg2; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Text:init"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Text:init"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Text:init"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Text:init"); ok &= luaval_to_number(tolua_S, 4,&arg2, "ccui.Text:init"); if(!ok) @@ -12345,8 +12345,8 @@ int lua_cocos2dx_ui_Text_getFontName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Text_getFontName'", nullptr); return 0; } - std::string_view ret = cobj->getFontName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getFontName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Text:getFontName",argc, 0); @@ -12387,9 +12387,9 @@ int lua_cocos2dx_ui_Text_setTextAreaSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.Text:setTextAreaSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.Text:setTextAreaSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Text_setTextAreaSize'", nullptr); @@ -12489,8 +12489,8 @@ int lua_cocos2dx_ui_Text_getAutoRenderSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Text_getAutoRenderSize'", nullptr); return 0; } - cocos2d::Vec2 ret = cobj->getAutoRenderSize(); - vec2_to_luaval(tolua_S, ret); + cocos2d::Size ret = cobj->getAutoRenderSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Text:getAutoRenderSize",argc, 0); @@ -13135,8 +13135,8 @@ int lua_cocos2dx_ui_Text_getTextAreaSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Text_getTextAreaSize'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getTextAreaSize(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getTextAreaSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Text:getTextAreaSize",argc, 0); @@ -13217,11 +13217,11 @@ int lua_cocos2dx_ui_Text_create(lua_State* tolua_S) { if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Text:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Text:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Text:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Text:create"); if (!ok) { break; } double arg2; ok &= luaval_to_number(tolua_S, 4,&arg2, "ccui.Text:create"); @@ -13457,8 +13457,8 @@ int lua_cocos2dx_ui_TextAtlas_getString(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextAtlas_getString'", nullptr); return 0; } - std::string_view ret = cobj->getString(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getString(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.TextAtlas:getString",argc, 0); @@ -13499,9 +13499,9 @@ int lua_cocos2dx_ui_TextAtlas_setString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextAtlas:setString"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextAtlas:setString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextAtlas_setString'", nullptr); @@ -13596,21 +13596,21 @@ int lua_cocos2dx_ui_TextAtlas_setProperty(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 5) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; int arg2; int arg3; - std::string_view arg4; + std::string arg4; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextAtlas:setProperty"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextAtlas:setProperty"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.TextAtlas:setProperty"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.TextAtlas:setProperty"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "ccui.TextAtlas:setProperty"); ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "ccui.TextAtlas:setProperty"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.TextAtlas:setProperty"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.TextAtlas:setProperty"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextAtlas_setProperty'", nullptr); @@ -13695,11 +13695,11 @@ int lua_cocos2dx_ui_TextAtlas_create(lua_State* tolua_S) { if (argc == 5) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextAtlas:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextAtlas:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.TextAtlas:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.TextAtlas:create"); if (!ok) { break; } int arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "ccui.TextAtlas:create"); @@ -13707,8 +13707,8 @@ int lua_cocos2dx_ui_TextAtlas_create(lua_State* tolua_S) int arg3; ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "ccui.TextAtlas:create"); if (!ok) { break; } - std::string_view arg4; - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.TextAtlas:create"); + std::string arg4; + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.TextAtlas:create"); if (!ok) { break; } cocos2d::ui::TextAtlas* ret = cocos2d::ui::TextAtlas::create(arg0, arg1, arg2, arg3, arg4); object_to_luaval(tolua_S, "ccui.TextAtlas",(cocos2d::ui::TextAtlas*)ret); @@ -13911,9 +13911,9 @@ int lua_cocos2dx_ui_LoadingBar_loadTexture(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.LoadingBar:loadTexture"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.LoadingBar:loadTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_LoadingBar_loadTexture'", nullptr); @@ -13925,10 +13925,10 @@ int lua_cocos2dx_ui_LoadingBar_loadTexture(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.LoadingBar:loadTexture"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.LoadingBar:loadTexture"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.LoadingBar:loadTexture"); if(!ok) @@ -14353,8 +14353,8 @@ int lua_cocos2dx_ui_LoadingBar_create(lua_State* tolua_S) { if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.LoadingBar:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.LoadingBar:create"); if (!ok) { break; } cocos2d::ui::LoadingBar* ret = cocos2d::ui::LoadingBar::create(arg0); object_to_luaval(tolua_S, "ccui.LoadingBar",(cocos2d::ui::LoadingBar*)ret); @@ -14366,8 +14366,8 @@ int lua_cocos2dx_ui_LoadingBar_create(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.LoadingBar:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.LoadingBar:create"); if (!ok) { break; } double arg1; ok &= luaval_to_number(tolua_S, 3,&arg1, "ccui.LoadingBar:create"); @@ -14392,8 +14392,8 @@ int lua_cocos2dx_ui_LoadingBar_create(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.LoadingBar:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.LoadingBar:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg1; ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.LoadingBar:create"); @@ -14408,8 +14408,8 @@ int lua_cocos2dx_ui_LoadingBar_create(lua_State* tolua_S) { if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.LoadingBar:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.LoadingBar:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg1; ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.LoadingBar:create"); @@ -15418,9 +15418,9 @@ int lua_cocos2dx_ui_ScrollView_setInnerContainerSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.ScrollView:setInnerContainerSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.ScrollView:setInnerContainerSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_ScrollView_setInnerContainerSize'", nullptr); @@ -17473,8 +17473,8 @@ int lua_cocos2dx_ui_ScrollView_getInnerContainerSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_ScrollView_getInnerContainerSize'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getInnerContainerSize(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getInnerContainerSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.ScrollView:getInnerContainerSize",argc, 0); @@ -20115,9 +20115,9 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTextureNormal(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextureNormal"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextureNormal"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Slider_loadSlidBallTextureNormal'", nullptr); @@ -20129,10 +20129,10 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTextureNormal(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextureNormal"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextureNormal"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.Slider:loadSlidBallTextureNormal"); if(!ok) @@ -20182,9 +20182,9 @@ int lua_cocos2dx_ui_Slider_loadProgressBarTexture(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadProgressBarTexture"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadProgressBarTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Slider_loadProgressBarTexture'", nullptr); @@ -20196,10 +20196,10 @@ int lua_cocos2dx_ui_Slider_loadProgressBarTexture(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadProgressBarTexture"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadProgressBarTexture"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.Slider:loadProgressBarTexture"); if(!ok) @@ -20537,9 +20537,9 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTextures(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextures"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextures"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Slider_loadSlidBallTextures'", nullptr); @@ -20551,12 +20551,12 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTextures(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextures"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextures"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Slider:loadSlidBallTextures"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Slider:loadSlidBallTextures"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Slider_loadSlidBallTextures'", nullptr); @@ -20568,15 +20568,15 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTextures(lua_State* tolua_S) } if (argc == 3) { - std::string_view arg0; - std::string_view arg1; - std::string_view arg2; + std::string arg0; + std::string arg1; + std::string arg2; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextures"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextures"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Slider:loadSlidBallTextures"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Slider:loadSlidBallTextures"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.Slider:loadSlidBallTextures"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.Slider:loadSlidBallTextures"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Slider_loadSlidBallTextures'", nullptr); @@ -20588,16 +20588,16 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTextures(lua_State* tolua_S) } if (argc == 4) { - std::string_view arg0; - std::string_view arg1; - std::string_view arg2; + std::string arg0; + std::string arg1; + std::string arg2; cocos2d::ui::Widget::TextureResType arg3; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextures"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextures"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Slider:loadSlidBallTextures"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Slider:loadSlidBallTextures"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.Slider:loadSlidBallTextures"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.Slider:loadSlidBallTextures"); ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "ccui.Slider:loadSlidBallTextures"); if(!ok) @@ -20798,9 +20798,9 @@ int lua_cocos2dx_ui_Slider_loadBarTexture(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadBarTexture"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadBarTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Slider_loadBarTexture'", nullptr); @@ -20812,10 +20812,10 @@ int lua_cocos2dx_ui_Slider_loadBarTexture(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadBarTexture"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadBarTexture"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.Slider:loadBarTexture"); if(!ok) @@ -21100,9 +21100,9 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTexturePressed(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTexturePressed"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTexturePressed"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Slider_loadSlidBallTexturePressed'", nullptr); @@ -21114,10 +21114,10 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTexturePressed(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTexturePressed"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTexturePressed"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.Slider:loadSlidBallTexturePressed"); if(!ok) @@ -21455,9 +21455,9 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTextureDisabled(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextureDisabled"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextureDisabled"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Slider_loadSlidBallTextureDisabled'", nullptr); @@ -21469,10 +21469,10 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTextureDisabled(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextureDisabled"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextureDisabled"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.Slider:loadSlidBallTextureDisabled"); if(!ok) @@ -21609,11 +21609,11 @@ int lua_cocos2dx_ui_Slider_create(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Slider:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Slider:create"); if (!ok) { break; } cocos2d::ui::Slider* ret = cocos2d::ui::Slider::create(arg0, arg1); object_to_luaval(tolua_S, "ccui.Slider",(cocos2d::ui::Slider*)ret); @@ -21625,11 +21625,11 @@ int lua_cocos2dx_ui_Slider_create(lua_State* tolua_S) { if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Slider:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Slider:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "ccui.Slider:create"); @@ -21911,8 +21911,8 @@ int lua_cocos2dx_ui_TextField_getString(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_getString'", nullptr); return 0; } - std::string_view ret = cobj->getString(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getString(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.TextField:getString",argc, 0); @@ -22102,8 +22102,8 @@ int lua_cocos2dx_ui_TextField_getPlaceHolder(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_getPlaceHolder'", nullptr); return 0; } - std::string_view ret = cobj->getPlaceHolder(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getPlaceHolder(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.TextField:getPlaceHolder",argc, 0); @@ -22191,9 +22191,9 @@ int lua_cocos2dx_ui_TextField_setFontName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextField:setFontName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextField:setFontName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_setFontName'", nullptr); @@ -22338,9 +22338,9 @@ int lua_cocos2dx_ui_TextField_setString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextField:setString"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextField:setString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_setString'", nullptr); @@ -22591,8 +22591,8 @@ int lua_cocos2dx_ui_TextField_getFontName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_getFontName'", nullptr); return 0; } - std::string_view ret = cobj->getFontName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getFontName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.TextField:getFontName",argc, 0); @@ -22633,9 +22633,9 @@ int lua_cocos2dx_ui_TextField_setTextAreaSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.TextField:setTextAreaSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.TextField:setTextAreaSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_setTextAreaSize'", nullptr); @@ -22782,8 +22782,8 @@ int lua_cocos2dx_ui_TextField_getAutoRenderSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_getAutoRenderSize'", nullptr); return 0; } - cocos2d::Vec2 ret = cobj->getAutoRenderSize(); - vec2_to_luaval(tolua_S, ret); + cocos2d::Size ret = cobj->getAutoRenderSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.TextField:getAutoRenderSize",argc, 0); @@ -23262,9 +23262,9 @@ int lua_cocos2dx_ui_TextField_setPlaceHolder(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextField:setPlaceHolder"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextField:setPlaceHolder"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_setPlaceHolder'", nullptr); @@ -23911,9 +23911,9 @@ int lua_cocos2dx_ui_TextField_setTouchSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.TextField:setTouchSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.TextField:setTouchSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_setTouchSize'", nullptr); @@ -23966,8 +23966,8 @@ int lua_cocos2dx_ui_TextField_getTouchSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_getTouchSize'", nullptr); return 0; } - cocos2d::Vec2 ret = cobj->getTouchSize(); - vec2_to_luaval(tolua_S, ret); + cocos2d::Size ret = cobj->getTouchSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.TextField:getTouchSize",argc, 0); @@ -23998,11 +23998,11 @@ int lua_cocos2dx_ui_TextField_create(lua_State* tolua_S) { if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextField:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextField:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.TextField:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.TextField:create"); if (!ok) { break; } int arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "ccui.TextField:create"); @@ -24249,8 +24249,8 @@ int lua_cocos2dx_ui_TextBMFont_getString(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextBMFont_getString'", nullptr); return 0; } - std::string_view ret = cobj->getString(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getString(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.TextBMFont:getString",argc, 0); @@ -24291,9 +24291,9 @@ int lua_cocos2dx_ui_TextBMFont_setString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextBMFont:setString"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextBMFont:setString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextBMFont_setString'", nullptr); @@ -24388,9 +24388,9 @@ int lua_cocos2dx_ui_TextBMFont_setFntFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextBMFont:setFntFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextBMFont:setFntFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextBMFont_setFntFile'", nullptr); @@ -24475,11 +24475,11 @@ int lua_cocos2dx_ui_TextBMFont_create(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextBMFont:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextBMFont:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.TextBMFont:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.TextBMFont:create"); if (!ok) { break; } cocos2d::ui::TextBMFont* ret = cocos2d::ui::TextBMFont::create(arg0, arg1); object_to_luaval(tolua_S, "ccui.TextBMFont",(cocos2d::ui::TextBMFont*)ret); @@ -25880,9 +25880,9 @@ int lua_cocos2dx_ui_PageView_setIndicatorIndexNodesTexture(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.PageView:setIndicatorIndexNodesTexture"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.PageView:setIndicatorIndexNodesTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_PageView_setIndicatorIndexNodesTexture'", nullptr); @@ -25894,10 +25894,10 @@ int lua_cocos2dx_ui_PageView_setIndicatorIndexNodesTexture(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.PageView:setIndicatorIndexNodesTexture"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.PageView:setIndicatorIndexNodesTexture"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.PageView:setIndicatorIndexNodesTexture"); if(!ok) @@ -26287,10 +26287,10 @@ int lua_cocos2dx_ui_Helper_getSubStringOfUTF8String(lua_State* tolua_S) if (argc == 3) { - std::string_view arg0; + std::string arg0; unsigned int arg1; unsigned int arg2; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Helper:getSubStringOfUTF8String"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Helper:getSubStringOfUTF8String"); ok &= luaval_to_uint32(tolua_S, 3,&arg1, "ccui.Helper:getSubStringOfUTF8String"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "ccui.Helper:getSubStringOfUTF8String"); if(!ok) @@ -26438,9 +26438,9 @@ int lua_cocos2dx_ui_Helper_seekWidgetByName(lua_State* tolua_S) if (argc == 2) { cocos2d::ui::Widget* arg0; - std::string_view arg1; + std::string arg1; ok &= luaval_to_object(tolua_S, 2, "ccui.Widget",&arg0, "ccui.Helper:seekWidgetByName"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Helper:seekWidgetByName"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Helper:seekWidgetByName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Helper_seekWidgetByName'", nullptr); @@ -26514,9 +26514,9 @@ int lua_cocos2dx_ui_Helper_restrictCapInsetRect(lua_State* tolua_S) if (argc == 2) { cocos2d::Rect arg0; - cocos2d::Vec2 arg1; + cocos2d::Size arg1; ok &= luaval_to_rect(tolua_S, 2, &arg0, "ccui.Helper:restrictCapInsetRect"); - ok &= luaval_to_vec2(tolua_S, 3, &arg1, "ccui.Helper:restrictCapInsetRect"); + ok &= luaval_to_size(tolua_S, 3, &arg1, "ccui.Helper:restrictCapInsetRect"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Helper_restrictCapInsetRect'", nullptr); @@ -26844,11 +26844,11 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; double arg5; unsigned int arg6; - std::string_view arg7; + std::string arg7; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:init"); @@ -26856,15 +26856,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:init"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:init"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementText_init'", nullptr); @@ -26879,11 +26879,11 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; double arg5; unsigned int arg6; - std::string_view arg7; + std::string arg7; cocos2d::Color3B arg8; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:init"); @@ -26892,15 +26892,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:init"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:init"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:init"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:init"); if(!ok) @@ -26917,11 +26917,11 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; double arg5; unsigned int arg6; - std::string_view arg7; + std::string arg7; cocos2d::Color3B arg8; int arg9; @@ -26931,15 +26931,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:init"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:init"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:init"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:init"); @@ -26958,11 +26958,11 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; double arg5; unsigned int arg6; - std::string_view arg7; + std::string arg7; cocos2d::Color3B arg8; int arg9; cocos2d::Color3B arg10; @@ -26973,15 +26973,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:init"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:init"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:init"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:init"); @@ -27002,15 +27002,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; double arg5; unsigned int arg6; - std::string_view arg7; + std::string arg7; cocos2d::Color3B arg8; int arg9; cocos2d::Color3B arg10; - cocos2d::Vec2 arg11; + cocos2d::Size arg11; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:init"); @@ -27018,15 +27018,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:init"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:init"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:init"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:init"); @@ -27034,7 +27034,7 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_color3b(tolua_S, 12, &arg10, "ccui.RichElementText:init"); - ok &= luaval_to_vec2(tolua_S, 13, &arg11, "ccui.RichElementText:init"); + ok &= luaval_to_size(tolua_S, 13, &arg11, "ccui.RichElementText:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementText_init'", nullptr); @@ -27049,15 +27049,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; double arg5; unsigned int arg6; - std::string_view arg7; + std::string arg7; cocos2d::Color3B arg8; int arg9; cocos2d::Color3B arg10; - cocos2d::Vec2 arg11; + cocos2d::Size arg11; int arg12; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:init"); @@ -27066,15 +27066,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:init"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:init"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:init"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:init"); @@ -27082,7 +27082,7 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_color3b(tolua_S, 12, &arg10, "ccui.RichElementText:init"); - ok &= luaval_to_vec2(tolua_S, 13, &arg11, "ccui.RichElementText:init"); + ok &= luaval_to_size(tolua_S, 13, &arg11, "ccui.RichElementText:init"); ok &= luaval_to_int32(tolua_S, 14,(int *)&arg12, "ccui.RichElementText:init"); if(!ok) @@ -27099,15 +27099,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; double arg5; unsigned int arg6; - std::string_view arg7; + std::string arg7; cocos2d::Color3B arg8; int arg9; cocos2d::Color3B arg10; - cocos2d::Vec2 arg11; + cocos2d::Size arg11; int arg12; cocos2d::Color3B arg13; @@ -27117,15 +27117,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:init"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:init"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:init"); - ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:init"); + ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:init"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:init"); @@ -27133,7 +27133,7 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_color3b(tolua_S, 12, &arg10, "ccui.RichElementText:init"); - ok &= luaval_to_vec2(tolua_S, 13, &arg11, "ccui.RichElementText:init"); + ok &= luaval_to_size(tolua_S, 13, &arg11, "ccui.RichElementText:init"); ok &= luaval_to_int32(tolua_S, 14,(int *)&arg12, "ccui.RichElementText:init"); @@ -27177,14 +27177,14 @@ int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; double arg5; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create"); if(!ok) { @@ -27200,15 +27200,15 @@ int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; double arg5; unsigned int arg6; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:create"); if(!ok) @@ -27225,19 +27225,19 @@ int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; double arg5; unsigned int arg6; - std::string_view arg7; + std::string arg7; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementText_create'", nullptr); @@ -27252,20 +27252,20 @@ int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; double arg5; unsigned int arg6; - std::string_view arg7; + std::string arg7; cocos2d::Color3B arg8; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:create"); if(!ok) { @@ -27281,21 +27281,21 @@ int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; double arg5; unsigned int arg6; - std::string_view arg7; + std::string arg7; cocos2d::Color3B arg8; int arg9; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:create"); ok &= luaval_to_int32(tolua_S, 11,(int *)&arg9, "ccui.RichElementText:create"); if(!ok) @@ -27312,22 +27312,22 @@ int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; double arg5; unsigned int arg6; - std::string_view arg7; + std::string arg7; cocos2d::Color3B arg8; int arg9; cocos2d::Color3B arg10; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:create"); ok &= luaval_to_int32(tolua_S, 11,(int *)&arg9, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 12, &arg10, "ccui.RichElementText:create"); @@ -27345,27 +27345,27 @@ int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; double arg5; unsigned int arg6; - std::string_view arg7; + std::string arg7; cocos2d::Color3B arg8; int arg9; cocos2d::Color3B arg10; - cocos2d::Vec2 arg11; + cocos2d::Size arg11; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:create"); ok &= luaval_to_int32(tolua_S, 11,(int *)&arg9, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 12, &arg10, "ccui.RichElementText:create"); - ok &= luaval_to_vec2(tolua_S, 13, &arg11, "ccui.RichElementText:create"); + ok &= luaval_to_size(tolua_S, 13, &arg11, "ccui.RichElementText:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementText_create'", nullptr); @@ -27380,28 +27380,28 @@ int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; double arg5; unsigned int arg6; - std::string_view arg7; + std::string arg7; cocos2d::Color3B arg8; int arg9; cocos2d::Color3B arg10; - cocos2d::Vec2 arg11; + cocos2d::Size arg11; int arg12; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:create"); ok &= luaval_to_int32(tolua_S, 11,(int *)&arg9, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 12, &arg10, "ccui.RichElementText:create"); - ok &= luaval_to_vec2(tolua_S, 13, &arg11, "ccui.RichElementText:create"); + ok &= luaval_to_size(tolua_S, 13, &arg11, "ccui.RichElementText:create"); ok &= luaval_to_int32(tolua_S, 14,(int *)&arg12, "ccui.RichElementText:create"); if(!ok) { @@ -27417,29 +27417,29 @@ int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; double arg5; unsigned int arg6; - std::string_view arg7; + std::string arg7; cocos2d::Color3B arg8; int arg9; cocos2d::Color3B arg10; - cocos2d::Vec2 arg11; + cocos2d::Size arg11; int arg12; cocos2d::Color3B arg13; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:create"); - ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:create"); + ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:create"); ok &= luaval_to_int32(tolua_S, 11,(int *)&arg9, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 12, &arg10, "ccui.RichElementText:create"); - ok &= luaval_to_vec2(tolua_S, 13, &arg11, "ccui.RichElementText:create"); + ok &= luaval_to_size(tolua_S, 13, &arg11, "ccui.RichElementText:create"); ok &= luaval_to_int32(tolua_S, 14,(int *)&arg12, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 15, &arg13, "ccui.RichElementText:create"); if(!ok) @@ -27599,7 +27599,7 @@ int lua_cocos2dx_ui_RichElementImage_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; + std::string arg3; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementImage:init"); @@ -27607,7 +27607,7 @@ int lua_cocos2dx_ui_RichElementImage_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementImage:init"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementImage:init"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementImage:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementImage_init'", nullptr); @@ -27622,8 +27622,8 @@ int lua_cocos2dx_ui_RichElementImage_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementImage:init"); @@ -27631,9 +27631,9 @@ int lua_cocos2dx_ui_RichElementImage_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementImage:init"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementImage:init"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementImage:init"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementImage:init"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementImage:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementImage_init'", nullptr); @@ -27648,8 +27648,8 @@ int lua_cocos2dx_ui_RichElementImage_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; cocos2d::ui::Widget::TextureResType arg5; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementImage:init"); @@ -27658,9 +27658,9 @@ int lua_cocos2dx_ui_RichElementImage_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementImage:init"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementImage:init"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementImage:init"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementImage:init"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementImage:init"); ok &= luaval_to_int32(tolua_S, 7,(int *)&arg5, "ccui.RichElementImage:init"); if(!ok) @@ -27760,9 +27760,9 @@ int lua_cocos2dx_ui_RichElementImage_setUrl(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichElementImage:setUrl"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichElementImage:setUrl"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementImage_setUrl'", nullptr); @@ -27802,11 +27802,11 @@ int lua_cocos2dx_ui_RichElementImage_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; + std::string arg3; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementImage:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementImage:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementImage:create"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementImage:create"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementImage:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementImage_create'", nullptr); @@ -27821,13 +27821,13 @@ int lua_cocos2dx_ui_RichElementImage_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementImage:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementImage:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementImage:create"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementImage:create"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementImage:create"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementImage:create"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementImage:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementImage_create'", nullptr); @@ -27842,14 +27842,14 @@ int lua_cocos2dx_ui_RichElementImage_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string_view arg3; - std::string_view arg4; + std::string arg3; + std::string arg4; cocos2d::ui::Widget::TextureResType arg5; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementImage:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementImage:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementImage:create"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementImage:create"); - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementImage:create"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementImage:create"); + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementImage:create"); ok &= luaval_to_int32(tolua_S, 7,(int *)&arg5, "ccui.RichElementImage:create"); if(!ok) { @@ -28630,13 +28630,13 @@ int lua_cocos2dx_ui_RichText_setAnchorTextShadow(lua_State* tolua_S) { bool arg0; cocos2d::Color3B arg1; - cocos2d::Vec2 arg2; + cocos2d::Size arg2; ok &= luaval_to_boolean(tolua_S, 2,&arg0, "ccui.RichText:setAnchorTextShadow"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichText:setAnchorTextShadow"); - ok &= luaval_to_vec2(tolua_S, 4, &arg2, "ccui.RichText:setAnchorTextShadow"); + ok &= luaval_to_size(tolua_S, 4, &arg2, "ccui.RichText:setAnchorTextShadow"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichText_setAnchorTextShadow'", nullptr); @@ -28650,14 +28650,14 @@ int lua_cocos2dx_ui_RichText_setAnchorTextShadow(lua_State* tolua_S) { bool arg0; cocos2d::Color3B arg1; - cocos2d::Vec2 arg2; + cocos2d::Size arg2; int arg3; ok &= luaval_to_boolean(tolua_S, 2,&arg0, "ccui.RichText:setAnchorTextShadow"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichText:setAnchorTextShadow"); - ok &= luaval_to_vec2(tolua_S, 4, &arg2, "ccui.RichText:setAnchorTextShadow"); + ok &= luaval_to_size(tolua_S, 4, &arg2, "ccui.RichText:setAnchorTextShadow"); ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "ccui.RichText:setAnchorTextShadow"); if(!ok) @@ -28754,9 +28754,9 @@ int lua_cocos2dx_ui_RichText_setAnchorFontColor(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichText:setAnchorFontColor"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichText:setAnchorFontColor"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichText_setAnchorFontColor'", nullptr); @@ -28804,9 +28804,9 @@ int lua_cocos2dx_ui_RichText_setFontFace(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichText:setFontFace"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichText:setFontFace"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichText_setFontFace'", nullptr); @@ -29165,10 +29165,10 @@ int lua_cocos2dx_ui_RichText_initWithXML(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ValueMap arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichText:initWithXML"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichText:initWithXML"); ok &= luaval_to_ccvaluemap(tolua_S, 3, &arg1, "ccui.RichText:initWithXML"); if(!ok) @@ -29182,11 +29182,11 @@ int lua_cocos2dx_ui_RichText_initWithXML(lua_State* tolua_S) } if (argc == 3) { - std::string_view arg0; + std::string arg0; cocos2d::ValueMap arg1; - std::function arg2; + std::function arg2; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichText:initWithXML"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichText:initWithXML"); ok &= luaval_to_ccvaluemap(tolua_S, 3, &arg1, "ccui.RichText:initWithXML"); @@ -29383,9 +29383,9 @@ int lua_cocos2dx_ui_RichText_openUrl(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichText:openUrl"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichText:openUrl"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichText_openUrl'", nullptr); @@ -29480,9 +29480,9 @@ int lua_cocos2dx_ui_RichText_setFontColor(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichText:setFontColor"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichText:setFontColor"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichText_setFontColor'", nullptr); @@ -30169,8 +30169,8 @@ int lua_cocos2dx_ui_RichText_getAnchorTextShadowOffset(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichText_getAnchorTextShadowOffset'", nullptr); return 0; } - cocos2d::Vec2 ret = cobj->getAnchorTextShadowOffset(); - vec2_to_luaval(tolua_S, ret); + cocos2d::Size ret = cobj->getAnchorTextShadowOffset(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.RichText:getAnchorTextShadowOffset",argc, 0); @@ -30546,9 +30546,9 @@ int lua_cocos2dx_ui_RichText_color3BWithString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichText:color3BWithString"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichText:color3BWithString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichText_color3BWithString'", nullptr); @@ -30619,9 +30619,9 @@ int lua_cocos2dx_ui_RichText_createWithXML(lua_State* tolua_S) if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ValueMap arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichText:createWithXML"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichText:createWithXML"); ok &= luaval_to_ccvaluemap(tolua_S, 3, &arg1, "ccui.RichText:createWithXML"); if(!ok) { @@ -30634,10 +30634,10 @@ int lua_cocos2dx_ui_RichText_createWithXML(lua_State* tolua_S) } if (argc == 3) { - std::string_view arg0; + std::string arg0; cocos2d::ValueMap arg1; - std::function arg2; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichText:createWithXML"); + std::function arg2; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichText:createWithXML"); ok &= luaval_to_ccvaluemap(tolua_S, 3, &arg1, "ccui.RichText:createWithXML"); do { // Lambda binding for lua is not supported. @@ -30794,9 +30794,9 @@ int lua_cocos2dx_ui_HBox_initWithSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.HBox:initWithSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.HBox:initWithSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_HBox_initWithSize'", nullptr); @@ -30834,8 +30834,8 @@ int lua_cocos2dx_ui_HBox_create(lua_State* tolua_S) { if (argc == 1) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.HBox:create"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.HBox:create"); if (!ok) { break; } cocos2d::ui::HBox* ret = cocos2d::ui::HBox::create(arg0); object_to_luaval(tolua_S, "ccui.HBox",(cocos2d::ui::HBox*)ret); @@ -30948,9 +30948,9 @@ int lua_cocos2dx_ui_VBox_initWithSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.VBox:initWithSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.VBox:initWithSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_VBox_initWithSize'", nullptr); @@ -30988,8 +30988,8 @@ int lua_cocos2dx_ui_VBox_create(lua_State* tolua_S) { if (argc == 1) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.VBox:create"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.VBox:create"); if (!ok) { break; } cocos2d::ui::VBox* ret = cocos2d::ui::VBox::create(arg0); object_to_luaval(tolua_S, "ccui.VBox",(cocos2d::ui::VBox*)ret); @@ -31102,9 +31102,9 @@ int lua_cocos2dx_ui_RelativeBox_initWithSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.RelativeBox:initWithSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.RelativeBox:initWithSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RelativeBox_initWithSize'", nullptr); @@ -31142,8 +31142,8 @@ int lua_cocos2dx_ui_RelativeBox_create(lua_State* tolua_S) { if (argc == 1) { - cocos2d::Vec2 arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.RelativeBox:create"); + cocos2d::Size arg0; + ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.RelativeBox:create"); if (!ok) { break; } cocos2d::ui::RelativeBox* ret = cocos2d::ui::RelativeBox::create(arg0); object_to_luaval(tolua_S, "ccui.RelativeBox",(cocos2d::ui::RelativeBox*)ret); @@ -31267,8 +31267,8 @@ int lua_cocos2dx_ui_Scale9Sprite_updateWithSprite(lua_State* tolua_S) ok &= luaval_to_vec2(tolua_S, 5, &arg3, "ccui.Scale9Sprite:updateWithSprite"); if (!ok) { break; } - cocos2d::Vec2 arg4; - ok &= luaval_to_vec2(tolua_S, 6, &arg4, "ccui.Scale9Sprite:updateWithSprite"); + cocos2d::Size arg4; + ok &= luaval_to_size(tolua_S, 6, &arg4, "ccui.Scale9Sprite:updateWithSprite"); if (!ok) { break; } cocos2d::Rect arg5; @@ -31540,10 +31540,10 @@ int lua_cocos2dx_ui_Scale9Sprite_initWithSpriteFrameName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::Rect arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Scale9Sprite:initWithSpriteFrameName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Scale9Sprite:initWithSpriteFrameName"); ok &= luaval_to_rect(tolua_S, 3, &arg1, "ccui.Scale9Sprite:initWithSpriteFrameName"); if(!ok) @@ -31795,8 +31795,8 @@ int lua_cocos2dx_ui_Scale9Sprite_init(lua_State* tolua_S) ok &= luaval_to_vec2(tolua_S, 5, &arg3, "ccui.Scale9Sprite:init"); if (!ok) { break; } - cocos2d::Vec2 arg4; - ok &= luaval_to_vec2(tolua_S, 6, &arg4, "ccui.Scale9Sprite:init"); + cocos2d::Size arg4; + ok &= luaval_to_size(tolua_S, 6, &arg4, "ccui.Scale9Sprite:init"); if (!ok) { break; } cocos2d::Rect arg5; @@ -31847,9 +31847,9 @@ int lua_cocos2dx_ui_Scale9Sprite_setPreferredSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.Scale9Sprite:setPreferredSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.Scale9Sprite:setPreferredSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Scale9Sprite_setPreferredSize'", nullptr); @@ -32337,8 +32337,8 @@ int lua_cocos2dx_ui_Scale9Sprite_getOriginalSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Scale9Sprite_getOriginalSize'", nullptr); return 0; } - cocos2d::Vec2 ret = cobj->getOriginalSize(); - vec2_to_luaval(tolua_S, ret); + cocos2d::Size ret = cobj->getOriginalSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Scale9Sprite:getOriginalSize",argc, 0); @@ -32378,8 +32378,8 @@ int lua_cocos2dx_ui_Scale9Sprite_initWithFile(lua_State* tolua_S) ok &= luaval_to_rect(tolua_S, 2, &arg0, "ccui.Scale9Sprite:initWithFile"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Scale9Sprite:initWithFile"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Scale9Sprite:initWithFile"); if (!ok) { break; } bool ret = cobj->initWithFile(arg0, arg1); @@ -32390,8 +32390,8 @@ int lua_cocos2dx_ui_Scale9Sprite_initWithFile(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Scale9Sprite:initWithFile"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Scale9Sprite:initWithFile"); if (!ok) { break; } cocos2d::Rect arg1; @@ -32601,8 +32601,8 @@ int lua_cocos2dx_ui_Scale9Sprite_getPreferredSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Scale9Sprite_getPreferredSize'", nullptr); return 0; } - cocos2d::Vec2 ret = cobj->getPreferredSize(); - vec2_to_luaval(tolua_S, ret); + cocos2d::Size ret = cobj->getPreferredSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Scale9Sprite:getPreferredSize",argc, 0); @@ -32780,8 +32780,8 @@ int lua_cocos2dx_ui_Scale9Sprite_create(lua_State* tolua_S) { if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Scale9Sprite:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Scale9Sprite:create"); if (!ok) { break; } cocos2d::Rect arg1; ok &= luaval_to_rect(tolua_S, 3, &arg1, "ccui.Scale9Sprite:create"); @@ -32812,8 +32812,8 @@ int lua_cocos2dx_ui_Scale9Sprite_create(lua_State* tolua_S) cocos2d::Rect arg0; ok &= luaval_to_rect(tolua_S, 2, &arg0, "ccui.Scale9Sprite:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Scale9Sprite:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Scale9Sprite:create"); if (!ok) { break; } cocos2d::ui::Scale9Sprite* ret = cocos2d::ui::Scale9Sprite::create(arg0, arg1); object_to_luaval(tolua_S, "ccui.Scale9Sprite",(cocos2d::ui::Scale9Sprite*)ret); @@ -32825,8 +32825,8 @@ int lua_cocos2dx_ui_Scale9Sprite_create(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Scale9Sprite:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Scale9Sprite:create"); if (!ok) { break; } cocos2d::Rect arg1; ok &= luaval_to_rect(tolua_S, 3, &arg1, "ccui.Scale9Sprite:create"); @@ -32841,8 +32841,8 @@ int lua_cocos2dx_ui_Scale9Sprite_create(lua_State* tolua_S) { if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Scale9Sprite:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Scale9Sprite:create"); if (!ok) { break; } cocos2d::ui::Scale9Sprite* ret = cocos2d::ui::Scale9Sprite::create(arg0); object_to_luaval(tolua_S, "ccui.Scale9Sprite",(cocos2d::ui::Scale9Sprite*)ret); @@ -32876,8 +32876,8 @@ int lua_cocos2dx_ui_Scale9Sprite_createWithSpriteFrameName(lua_State* tolua_S) { if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Scale9Sprite:createWithSpriteFrameName"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Scale9Sprite:createWithSpriteFrameName"); if (!ok) { break; } cocos2d::Rect arg1; ok &= luaval_to_rect(tolua_S, 3, &arg1, "ccui.Scale9Sprite:createWithSpriteFrameName"); @@ -32892,8 +32892,8 @@ int lua_cocos2dx_ui_Scale9Sprite_createWithSpriteFrameName(lua_State* tolua_S) { if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Scale9Sprite:createWithSpriteFrameName"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Scale9Sprite:createWithSpriteFrameName"); if (!ok) { break; } cocos2d::ui::Scale9Sprite* ret = cocos2d::ui::Scale9Sprite::createWithSpriteFrameName(arg0); object_to_luaval(tolua_S, "ccui.Scale9Sprite",(cocos2d::ui::Scale9Sprite*)ret); @@ -33431,8 +33431,8 @@ int lua_cocos2dx_ui_EditBox_initWithSizeAndBackgroundSprite(lua_State* tolua_S) ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:initWithSizeAndBackgroundSprite"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndBackgroundSprite"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndBackgroundSprite"); if (!ok) { break; } bool ret = cobj->initWithSizeAndBackgroundSprite(arg0, arg1); @@ -33447,8 +33447,8 @@ int lua_cocos2dx_ui_EditBox_initWithSizeAndBackgroundSprite(lua_State* tolua_S) ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:initWithSizeAndBackgroundSprite"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndBackgroundSprite"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndBackgroundSprite"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg2; @@ -34012,9 +34012,9 @@ int lua_cocos2dx_ui_EditBox_loadTextureDisabled(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.EditBox:loadTextureDisabled"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.EditBox:loadTextureDisabled"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_EditBox_loadTextureDisabled'", nullptr); @@ -34026,10 +34026,10 @@ int lua_cocos2dx_ui_EditBox_loadTextureDisabled(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.EditBox:loadTextureDisabled"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.EditBox:loadTextureDisabled"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.EditBox:loadTextureDisabled"); if(!ok) @@ -34532,9 +34532,9 @@ int lua_cocos2dx_ui_EditBox_loadTexturePressed(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.EditBox:loadTexturePressed"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.EditBox:loadTexturePressed"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_EditBox_loadTexturePressed'", nullptr); @@ -34546,10 +34546,10 @@ int lua_cocos2dx_ui_EditBox_loadTexturePressed(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.EditBox:loadTexturePressed"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.EditBox:loadTexturePressed"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.EditBox:loadTexturePressed"); if(!ok) @@ -34694,11 +34694,11 @@ int lua_cocos2dx_ui_EditBox_initWithSizeAndTexture(lua_State* tolua_S) if (argc == 2) { cocos2d::Size arg0; - std::string_view arg1; + std::string arg1; ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:initWithSizeAndTexture"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndTexture"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_EditBox_initWithSizeAndTexture'", nullptr); @@ -34711,14 +34711,14 @@ int lua_cocos2dx_ui_EditBox_initWithSizeAndTexture(lua_State* tolua_S) if (argc == 3) { cocos2d::Size arg0; - std::string_view arg1; - std::string_view arg2; + std::string arg1; + std::string arg2; ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:initWithSizeAndTexture"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndTexture"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndTexture"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.EditBox:initWithSizeAndTexture"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.EditBox:initWithSizeAndTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_EditBox_initWithSizeAndTexture'", nullptr); @@ -34731,17 +34731,17 @@ int lua_cocos2dx_ui_EditBox_initWithSizeAndTexture(lua_State* tolua_S) if (argc == 4) { cocos2d::Size arg0; - std::string_view arg1; - std::string_view arg2; - std::string_view arg3; + std::string arg1; + std::string arg2; + std::string arg3; ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:initWithSizeAndTexture"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndTexture"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndTexture"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.EditBox:initWithSizeAndTexture"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.EditBox:initWithSizeAndTexture"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.EditBox:initWithSizeAndTexture"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.EditBox:initWithSizeAndTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_EditBox_initWithSizeAndTexture'", nullptr); @@ -34754,18 +34754,18 @@ int lua_cocos2dx_ui_EditBox_initWithSizeAndTexture(lua_State* tolua_S) if (argc == 5) { cocos2d::Size arg0; - std::string_view arg1; - std::string_view arg2; - std::string_view arg3; + std::string arg1; + std::string arg2; + std::string arg3; cocos2d::ui::Widget::TextureResType arg4; ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:initWithSizeAndTexture"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndTexture"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndTexture"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.EditBox:initWithSizeAndTexture"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.EditBox:initWithSizeAndTexture"); - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.EditBox:initWithSizeAndTexture"); + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.EditBox:initWithSizeAndTexture"); ok &= luaval_to_int32(tolua_S, 6,(int *)&arg4, "ccui.EditBox:initWithSizeAndTexture"); if(!ok) @@ -35003,12 +35003,12 @@ int lua_cocos2dx_ui_EditBox_loadTextures(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.EditBox:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.EditBox:loadTextures"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:loadTextures"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_EditBox_loadTextures'", nullptr); @@ -35020,15 +35020,15 @@ int lua_cocos2dx_ui_EditBox_loadTextures(lua_State* tolua_S) } if (argc == 3) { - std::string_view arg0; - std::string_view arg1; - std::string_view arg2; + std::string arg0; + std::string arg1; + std::string arg2; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.EditBox:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.EditBox:loadTextures"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:loadTextures"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.EditBox:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.EditBox:loadTextures"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_EditBox_loadTextures'", nullptr); @@ -35040,16 +35040,16 @@ int lua_cocos2dx_ui_EditBox_loadTextures(lua_State* tolua_S) } if (argc == 4) { - std::string_view arg0; - std::string_view arg1; - std::string_view arg2; + std::string arg0; + std::string arg1; + std::string arg2; cocos2d::ui::Widget::TextureResType arg3; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.EditBox:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.EditBox:loadTextures"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:loadTextures"); - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.EditBox:loadTextures"); + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.EditBox:loadTextures"); ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "ccui.EditBox:loadTextures"); if(!ok) @@ -35249,9 +35249,9 @@ int lua_cocos2dx_ui_EditBox_loadTextureNormal(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.EditBox:loadTextureNormal"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.EditBox:loadTextureNormal"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_EditBox_loadTextureNormal'", nullptr); @@ -35263,10 +35263,10 @@ int lua_cocos2dx_ui_EditBox_loadTextureNormal(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; + std::string arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.EditBox:loadTextureNormal"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.EditBox:loadTextureNormal"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.EditBox:loadTextureNormal"); if(!ok) @@ -35709,8 +35709,8 @@ int lua_cocos2dx_ui_EditBox_create(lua_State* tolua_S) cocos2d::Size arg0; ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "ccui.EditBox:create"); @@ -35785,8 +35785,8 @@ int lua_cocos2dx_ui_EditBox_create(lua_State* tolua_S) cocos2d::Size arg0; ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:create"); if (!ok) { break; } cocos2d::ui::EditBox* ret = cocos2d::ui::EditBox::create(arg0, arg1); object_to_luaval(tolua_S, "ccui.EditBox",(cocos2d::ui::EditBox*)ret); @@ -35801,11 +35801,11 @@ int lua_cocos2dx_ui_EditBox_create(lua_State* tolua_S) cocos2d::Size arg0; ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:create"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.EditBox:create"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.EditBox:create"); if (!ok) { break; } cocos2d::ui::EditBox* ret = cocos2d::ui::EditBox::create(arg0, arg1, arg2); object_to_luaval(tolua_S, "ccui.EditBox",(cocos2d::ui::EditBox*)ret); @@ -35820,14 +35820,14 @@ int lua_cocos2dx_ui_EditBox_create(lua_State* tolua_S) cocos2d::Size arg0; ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:create"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.EditBox:create"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.EditBox:create"); if (!ok) { break; } - std::string_view arg3; - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.EditBox:create"); + std::string arg3; + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.EditBox:create"); if (!ok) { break; } cocos2d::ui::EditBox* ret = cocos2d::ui::EditBox::create(arg0, arg1, arg2, arg3); object_to_luaval(tolua_S, "ccui.EditBox",(cocos2d::ui::EditBox*)ret); @@ -35842,14 +35842,14 @@ int lua_cocos2dx_ui_EditBox_create(lua_State* tolua_S) cocos2d::Size arg0; ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:create"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.EditBox:create"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.EditBox:create"); if (!ok) { break; } - std::string_view arg3; - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.EditBox:create"); + std::string arg3; + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.EditBox:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg4; ok &= luaval_to_int32(tolua_S, 6,(int *)&arg4, "ccui.EditBox:create"); @@ -36352,8 +36352,8 @@ int lua_cocos2dx_ui_LayoutComponent_getSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_LayoutComponent_getSize'", nullptr); return 0; } - const cocos2d::Vec2& ret = cobj->getSize(); - vec2_to_luaval(tolua_S, ret); + const cocos2d::Size& ret = cobj->getSize(); + size_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.LayoutComponent:getSize",argc, 0); @@ -38331,9 +38331,9 @@ int lua_cocos2dx_ui_LayoutComponent_setSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Vec2 arg0; + cocos2d::Size arg0; - ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.LayoutComponent:setSize"); + ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.LayoutComponent:setSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_LayoutComponent_setSize'", nullptr); @@ -38611,8 +38611,8 @@ int lua_cocos2dx_ui_TabHeader_getTitleText(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TabHeader_getTitleText'", nullptr); return 0; } - std::string_view ret = cobj->getTitleText(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + std::string ret = cobj->getTitleText(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.TabHeader:getTitleText",argc, 0); @@ -38703,9 +38703,9 @@ int lua_cocos2dx_ui_TabHeader_setTitleFontName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TabHeader:setTitleFontName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TabHeader:setTitleFontName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TabHeader_setTitleFontName'", nullptr); @@ -38805,8 +38805,8 @@ int lua_cocos2dx_ui_TabHeader_getTitleFontName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TabHeader_getTitleFontName'", nullptr); return 0; } - std::string_view ret = cobj->getTitleFontName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + std::string ret = cobj->getTitleFontName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.TabHeader:getTitleFontName",argc, 0); @@ -38941,9 +38941,9 @@ int lua_cocos2dx_ui_TabHeader_setTitleText(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TabHeader:setTitleText"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TabHeader:setTitleText"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TabHeader_setTitleText'", nullptr); @@ -39031,14 +39031,14 @@ int lua_cocos2dx_ui_TabHeader_create(lua_State* tolua_S) { if (argc == 3) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TabHeader:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TabHeader:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.TabHeader:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.TabHeader:create"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.TabHeader:create"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.TabHeader:create"); if (!ok) { break; } cocos2d::ui::TabHeader* ret = cocos2d::ui::TabHeader::create(arg0, arg1, arg2); object_to_luaval(tolua_S, "ccui.TabHeader",(cocos2d::ui::TabHeader*)ret); @@ -39050,14 +39050,14 @@ int lua_cocos2dx_ui_TabHeader_create(lua_State* tolua_S) { if (argc == 4) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TabHeader:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TabHeader:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.TabHeader:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.TabHeader:create"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.TabHeader:create"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.TabHeader:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg3; ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "ccui.TabHeader:create"); @@ -39082,23 +39082,23 @@ int lua_cocos2dx_ui_TabHeader_create(lua_State* tolua_S) { if (argc == 6) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TabHeader:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TabHeader:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.TabHeader:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.TabHeader:create"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.TabHeader:create"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.TabHeader:create"); if (!ok) { break; } - std::string_view arg3; - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.TabHeader:create"); + std::string arg3; + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.TabHeader:create"); if (!ok) { break; } - std::string_view arg4; - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.TabHeader:create"); + std::string arg4; + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.TabHeader:create"); if (!ok) { break; } - std::string_view arg5; - ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "ccui.TabHeader:create"); + std::string arg5; + ok &= luaval_to_std_string(tolua_S, 7,&arg5, "ccui.TabHeader:create"); if (!ok) { break; } cocos2d::ui::TabHeader* ret = cocos2d::ui::TabHeader::create(arg0, arg1, arg2, arg3, arg4, arg5); object_to_luaval(tolua_S, "ccui.TabHeader",(cocos2d::ui::TabHeader*)ret); @@ -39110,23 +39110,23 @@ int lua_cocos2dx_ui_TabHeader_create(lua_State* tolua_S) { if (argc == 7) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TabHeader:create"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TabHeader:create"); if (!ok) { break; } - std::string_view arg1; - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.TabHeader:create"); + std::string arg1; + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.TabHeader:create"); if (!ok) { break; } - std::string_view arg2; - ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.TabHeader:create"); + std::string arg2; + ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.TabHeader:create"); if (!ok) { break; } - std::string_view arg3; - ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.TabHeader:create"); + std::string arg3; + ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.TabHeader:create"); if (!ok) { break; } - std::string_view arg4; - ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.TabHeader:create"); + std::string arg4; + ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.TabHeader:create"); if (!ok) { break; } - std::string_view arg5; - ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "ccui.TabHeader:create"); + std::string arg5; + ok &= luaval_to_std_string(tolua_S, 7,&arg5, "ccui.TabHeader:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg6; ok &= luaval_to_int32(tolua_S, 8,(int *)&arg6, "ccui.TabHeader:create"); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_video_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_video_auto.cpp index eecb3ef9a9..d01c83a464 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_video_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_video_auto.cpp @@ -36,8 +36,8 @@ int lua_cocos2dx_video_VideoPlayer_getFileName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_video_VideoPlayer_getFileName'", nullptr); return 0; } - std::string_view ret = cobj->getFileName(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getFileName(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.VideoPlayer:getFileName",argc, 0); @@ -83,8 +83,8 @@ int lua_cocos2dx_video_VideoPlayer_getURL(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_video_VideoPlayer_getURL'", nullptr); return 0; } - std::string_view ret = cobj->getURL(); - lua_pushlstring(tolua_S,ret.data(),ret.length()); + const std::string& ret = cobj->getURL(); + lua_pushlstring(tolua_S,ret.c_str(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.VideoPlayer:getURL",argc, 0); @@ -366,9 +366,9 @@ int lua_cocos2dx_video_VideoPlayer_setFileName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.VideoPlayer:setFileName"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.VideoPlayer:setFileName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_video_VideoPlayer_setFileName'", nullptr); @@ -416,9 +416,9 @@ int lua_cocos2dx_video_VideoPlayer_setURL(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.VideoPlayer:setURL"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.VideoPlayer:setURL"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_video_VideoPlayer_setURL'", nullptr); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_webview_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_webview_auto.cpp index 378f246d86..887d6cf0ac 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_webview_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_webview_auto.cpp @@ -128,9 +128,9 @@ int lua_cocos2dx_webview_WebView_loadHTMLString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.WebView:loadHTMLString"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.WebView:loadHTMLString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_webview_WebView_loadHTMLString'", nullptr); @@ -142,12 +142,12 @@ int lua_cocos2dx_webview_WebView_loadHTMLString(lua_State* tolua_S) } if (argc == 2) { - std::string_view arg0; - std::string_view arg1; + std::string arg0; + std::string arg1; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.WebView:loadHTMLString"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.WebView:loadHTMLString"); - ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.WebView:loadHTMLString"); + ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.WebView:loadHTMLString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_webview_WebView_loadHTMLString'", nullptr); @@ -339,9 +339,9 @@ int lua_cocos2dx_webview_WebView_loadFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.WebView:loadFile"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.WebView:loadFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_webview_WebView_loadFile'", nullptr); @@ -384,8 +384,8 @@ int lua_cocos2dx_webview_WebView_loadURL(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.WebView:loadURL"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.WebView:loadURL"); if (!ok) { break; } bool arg1; @@ -400,8 +400,8 @@ int lua_cocos2dx_webview_WebView_loadURL(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string_view arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.WebView:loadURL"); + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.WebView:loadURL"); if (!ok) { break; } cobj->loadURL(arg0); @@ -498,9 +498,9 @@ int lua_cocos2dx_webview_WebView_evaluateJS(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.WebView:evaluateJS"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.WebView:evaluateJS"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_webview_WebView_evaluateJS'", nullptr); @@ -830,9 +830,9 @@ int lua_cocos2dx_webview_WebView_setJavascriptInterfaceScheme(lua_State* tolua_S argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string_view arg0; + std::string arg0; - ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.WebView:setJavascriptInterfaceScheme"); + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.WebView:setJavascriptInterfaceScheme"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_webview_WebView_setJavascriptInterfaceScheme'", nullptr); diff --git a/extensions/scripting/lua-bindings/manual/CCComponentLua.cpp b/extensions/scripting/lua-bindings/manual/CCComponentLua.cpp index 31560146ef..1118e57d2d 100644 --- a/extensions/scripting/lua-bindings/manual/CCComponentLua.cpp +++ b/extensions/scripting/lua-bindings/manual/CCComponentLua.cpp @@ -41,7 +41,7 @@ const std::string ComponentLua::UPDATE = "update"; namespace { -void adjustScriptFileName(std::string_view& scriptFileName, std::string& holder) +void adjustScriptFileName(std::string& scriptFileName) { assert(scriptFileName.size() > 4); @@ -54,26 +54,22 @@ void adjustScriptFileName(std::string_view& scriptFileName, std::string& holder) // xxx.lua -> xxx.luac or // xxx.luac -> xxx.lua - holder = scriptFileName; - if (holder.compare(holder.size() - luaSuffix.size(), luaSuffix.size(), luaSuffix) == 0) - holder.replace(holder.size() - luaSuffix.size(), luaSuffix.size(), luacSuffix); + if (scriptFileName.compare(scriptFileName.size() - luaSuffix.size(), luaSuffix.size(), luaSuffix) == 0) + scriptFileName.replace(scriptFileName.size() - luaSuffix.size(), luaSuffix.size(), luacSuffix); else - holder.replace(holder.size() - luacSuffix.size(), luacSuffix.size(), luaSuffix); - - scriptFileName = holder; + scriptFileName.replace(scriptFileName.size() - luacSuffix.size(), luacSuffix.size(), luaSuffix); } } // namespace int ComponentLua::_index = 0; -ComponentLua* ComponentLua::create(std::string_view scriptFileName) +ComponentLua* ComponentLua::create(const std::string& scriptFileName) { CC_ASSERT(!scriptFileName.empty()); initClass(); - std::string holder; - adjustScriptFileName(scriptFileName, holder); + adjustScriptFileName(const_cast(scriptFileName)); auto componentLua = new ComponentLua(scriptFileName); if (componentLua) { @@ -83,7 +79,7 @@ ComponentLua* ComponentLua::create(std::string_view scriptFileName) return componentLua; } -ComponentLua::ComponentLua(std::string_view scriptFileName) +ComponentLua::ComponentLua(const std::string& scriptFileName) : _scriptFileName(scriptFileName), _table(nullptr), _strIndex("") { _succeedLoadingScript = loadAndExecuteScript(); @@ -138,18 +134,18 @@ void ComponentLua::onExit() } } -bool ComponentLua::getLuaFunction(std::string_view functionName) +bool ComponentLua::getLuaFunction(const std::string& functionName) { lua_State* l = LuaEngine::getInstance()->getLuaStack()->getLuaState(); - lua_pushstring(l, KEY_COMPONENT); // stack: "component" - lua_rawget(l, LUA_REGISTRYINDEX); // stack: table_of_component - lua_pushstring(l, _strIndex.c_str()); // stack: table_of_component strIndex - lua_rawget(l, -2); // stack: table_of_component table_of_this - lua_pushlstring(l, functionName.data(), functionName.length()); // stack: table_of_component table_of_this "update" - lua_rawget(l, -2); // stack: table_of_component table_of_this table_of_this["update"] - lua_remove(l, -2); // stack: table_of_component table_of_this["update"] - lua_remove(l, -2); // stack: table_of_this["update"] + lua_pushstring(l, KEY_COMPONENT); // stack: "component" + lua_rawget(l, LUA_REGISTRYINDEX); // stack: table_of_component + lua_pushstring(l, _strIndex.c_str()); // stack: table_of_component strIndex + lua_rawget(l, -2); // stack: table_of_component table_of_this + lua_pushstring(l, functionName.c_str()); // stack: table_of_component table_of_this "update" + lua_rawget(l, -2); // stack: table_of_component table_of_this table_of_this["update"] + lua_remove(l, -2); // stack: table_of_component table_of_this["update"] + lua_remove(l, -2); // stack: table_of_this["update"] int type = lua_type(l, -1); // if (type != LUA_TFUNCTION) diff --git a/extensions/scripting/lua-bindings/manual/CCComponentLua.h b/extensions/scripting/lua-bindings/manual/CCComponentLua.h index 5f17a086d3..4a2425987b 100644 --- a/extensions/scripting/lua-bindings/manual/CCComponentLua.h +++ b/extensions/scripting/lua-bindings/manual/CCComponentLua.h @@ -34,9 +34,9 @@ NS_CC_BEGIN class ComponentLua : public Component { public: - static ComponentLua* create(std::string_view scriptFileName); + static ComponentLua* create(const std::string& scriptFileName); - ComponentLua(std::string_view scriptFileName); + ComponentLua(const std::string& scriptFileName); /** * This function is used to be invoked from lua side to get the corresponding script object of this component. */ @@ -52,7 +52,7 @@ private: bool loadAndExecuteScript(); void getUserData(); void storeLuaTable(); - bool getLuaFunction(std::string_view functionName); + bool getLuaFunction(const std::string& functionName); void removeLuaTable(); static void initClass(); diff --git a/extensions/scripting/lua-bindings/manual/CCLuaEngine.cpp b/extensions/scripting/lua-bindings/manual/CCLuaEngine.cpp index 1e84539953..c474533f3c 100644 --- a/extensions/scripting/lua-bindings/manual/CCLuaEngine.cpp +++ b/extensions/scripting/lua-bindings/manual/CCLuaEngine.cpp @@ -174,7 +174,7 @@ int LuaEngine::reallocateScriptHandler(int nHandler) return nRet; } -bool LuaEngine::parseConfig(ConfigType type, std::string_view str) +bool LuaEngine::parseConfig(ConfigType type, const std::string& str) { lua_getglobal(_stack->getLuaState(), "__onParseConfig"); if (!lua_isfunction(_stack->getLuaState(), -1)) @@ -185,7 +185,7 @@ bool LuaEngine::parseConfig(ConfigType type, std::string_view str) } _stack->pushInt((int)type); - _stack->pushString(str.data(), str.length()); + _stack->pushString(str.c_str()); return _stack->executeFunction(2); } diff --git a/extensions/scripting/lua-bindings/manual/CCLuaEngine.h b/extensions/scripting/lua-bindings/manual/CCLuaEngine.h index 233543b72f..dbaf44d04c 100644 --- a/extensions/scripting/lua-bindings/manual/CCLuaEngine.h +++ b/extensions/scripting/lua-bindings/manual/CCLuaEngine.h @@ -188,7 +188,7 @@ public: * @return if __onParseConfig function exist in the Lua, it return the value that _stack->executeFunction returns * otherwise return false. */ - virtual bool parseConfig(ConfigType type, std::string_view str) override; + virtual bool parseConfig(ConfigType type, const std::string& str) override; /** * When some events triggered in the c++ also needs to pass on to lua to handle, we could call this function to send diff --git a/extensions/scripting/lua-bindings/manual/CCLuaStack.cpp b/extensions/scripting/lua-bindings/manual/CCLuaStack.cpp index aef8cb7076..1160d1ab9a 100644 --- a/extensions/scripting/lua-bindings/manual/CCLuaStack.cpp +++ b/extensions/scripting/lua-bindings/manual/CCLuaStack.cpp @@ -294,9 +294,9 @@ void LuaStack::pushBoolean(bool boolValue) lua_pushboolean(_state, boolValue); } -void LuaStack::pushString(std::string_view stringValue) +void LuaStack::pushString(const char* stringValue) { - lua_pushlstring(_state, stringValue.data(), stringValue.length()); + lua_pushstring(_state, stringValue); } void LuaStack::pushString(const char* stringValue, int length) @@ -331,7 +331,7 @@ void LuaStack::pushLuaValue(const LuaValue& value) } else if (type == LuaValueTypeString) { - return pushString(value.stringValue()); + return pushString(value.stringValue().c_str()); } else if (type == LuaValueTypeDict) { @@ -343,7 +343,7 @@ void LuaStack::pushLuaValue(const LuaValue& value) } else if (type == LuaValueTypeObject) { - pushObject(value.ccobjectValue(), value.getObjectTypename().data()); + pushObject(value.ccobjectValue(), value.getObjectTypename().c_str()); } } @@ -352,9 +352,9 @@ void LuaStack::pushLuaValueDict(const LuaValueDict& dict) lua_newtable(_state); /* L: table */ for (LuaValueDictIterator it = dict.begin(); it != dict.end(); ++it) { - lua_pushlstring(_state, it->first.c_str(), it->first.length()); /* L: table key */ - pushLuaValue(it->second); /* L: table key value */ - lua_rawset(_state, -3); /* table.key = value, L: table */ + lua_pushstring(_state, it->first.c_str()); /* L: table key */ + pushLuaValue(it->second); /* L: table key value */ + lua_rawset(_state, -3); /* table.key = value, L: table */ } } diff --git a/extensions/scripting/lua-bindings/manual/CCLuaStack.h b/extensions/scripting/lua-bindings/manual/CCLuaStack.h index e55313b03f..cd01e56d8f 100644 --- a/extensions/scripting/lua-bindings/manual/CCLuaStack.h +++ b/extensions/scripting/lua-bindings/manual/CCLuaStack.h @@ -184,7 +184,7 @@ public: * * @param stringValue a pointer point to a zero-terminated string stringValue. */ - virtual void pushString(std::string_view stringValue); + virtual void pushString(const char* stringValue); /** * Pushes the string pointed to by stringValue with size length onto the stack. diff --git a/extensions/scripting/lua-bindings/manual/CCLuaValue.cpp b/extensions/scripting/lua-bindings/manual/CCLuaValue.cpp index 6e2112c5e1..6bb23e16e1 100644 --- a/extensions/scripting/lua-bindings/manual/CCLuaValue.cpp +++ b/extensions/scripting/lua-bindings/manual/CCLuaValue.cpp @@ -60,7 +60,7 @@ const LuaValue LuaValue::stringValue(const char* stringValue) return value; } -const LuaValue LuaValue::stringValue(std::string_view stringValue) +const LuaValue LuaValue::stringValue(const std::string& stringValue) { LuaValue value; value._type = LuaValueTypeString; @@ -94,9 +94,9 @@ const LuaValue LuaValue::ccobjectValue(Ref* ccobjectValue, const char* objectTyp return value; } -const LuaValue LuaValue::ccobjectValue(Ref* ccobjectValue, std::string_view objectTypename) +const LuaValue LuaValue::ccobjectValue(Ref* ccobjectValue, const std::string& objectTypename) { - return LuaValue::ccobjectValue(ccobjectValue, objectTypename.data()); + return LuaValue::ccobjectValue(ccobjectValue, objectTypename.c_str()); } LuaValue::LuaValue(const LuaValue& rhs) diff --git a/extensions/scripting/lua-bindings/manual/CCLuaValue.h b/extensions/scripting/lua-bindings/manual/CCLuaValue.h index 8b918263e1..0997bdbf43 100644 --- a/extensions/scripting/lua-bindings/manual/CCLuaValue.h +++ b/extensions/scripting/lua-bindings/manual/CCLuaValue.h @@ -135,7 +135,7 @@ public: * @param stringValue a std::string object. * @return a LuaValue object. */ - static const LuaValue stringValue(std::string_view stringValue); + static const LuaValue stringValue(const std::string& stringValue); /** * Construct a LuaValue object by a LuaValueDict value. @@ -169,7 +169,7 @@ public: * @param objectTypename a std::string object represent the typename of object. * @return a LuaValue object. */ - static const LuaValue ccobjectValue(Ref* ccobjectValue, std::string_view objectTypename); + static const LuaValue ccobjectValue(Ref* ccobjectValue, const std::string& objectTypename); /** * Default constructor of LuaValue. @@ -204,7 +204,7 @@ public: * * @return the reference of _ccobjectType. */ - std::string_view getObjectTypename() const { return *_ccobjectType; } + const std::string& getObjectTypename() const { return *_ccobjectType; } /** * Get the int value of LuaValue object. @@ -232,7 +232,7 @@ public: * * @return the reference about string value. */ - std::string_view stringValue() const { return *_field.stringValue; } + const std::string& stringValue() const { return *_field.stringValue; } /** * Get the LuaValueDict value of LuaValue object. diff --git a/extensions/scripting/lua-bindings/manual/LuaBasicConversions.cpp b/extensions/scripting/lua-bindings/manual/LuaBasicConversions.cpp index a17f5ee6a7..eba25e98e1 100644 --- a/extensions/scripting/lua-bindings/manual/LuaBasicConversions.cpp +++ b/extensions/scripting/lua-bindings/manual/LuaBasicConversions.cpp @@ -1564,47 +1564,6 @@ bool luaval_to_std_vector_string(lua_State* L, int lo, std::vector* return ok; } -bool luaval_to_std_vector_string_view(lua_State* L, int lo, std::vector* ret, const char* funcName) -{ - if (nullptr == L || nullptr == ret || lua_gettop(L) < lo) - return false; - - tolua_Error tolua_err; - bool ok = true; - if (!tolua_istable(L, lo, 0, &tolua_err)) - { -#if COCOS2D_DEBUG >= 1 - luaval_to_native_err(L, "#ferror:", &tolua_err, funcName); -#endif - ok = false; - } - - if (ok) - { - size_t len = lua_objlen(L, lo); - std::string_view value = ""; - for (size_t i = 0; i < len; i++) - { - lua_pushnumber(L, i + 1); - lua_gettable(L, lo); - if (lua_isstring(L, -1)) - { - ok = luaval_to_std_string_view(L, -1, &value); - if (ok) - ret->push_back(value); - } - else - { - CCASSERT(false, "string type is needed"); - } - - lua_pop(L, 1); - } - } - - return ok; -} - bool luaval_to_std_vector_int(lua_State* L, int lo, std::vector* ret, const char* funcName) { if (nullptr == L || nullptr == ret || lua_gettop(L) < lo) @@ -2443,7 +2402,7 @@ void ccvalue_to_luaval(lua_State* L, const cocos2d::Value& inValue) lua_pushinteger(L, obj.asInt64()); break; case Value::Type::STRING: - lua_pushstring(L, obj.asStringRef().data()); + lua_pushstring(L, obj.asStringRef().c_str()); break; case Value::Type::VECTOR: ccvaluevector_to_luaval(L, obj.asValueVector()); @@ -2568,7 +2527,7 @@ void ccvaluemapintkey_to_luaval(lua_State* L, const cocos2d::ValueMapIntKey& inV case Value::Type::STRING: { lua_pushstring(L, key.c_str()); - lua_pushstring(L, obj.asStringRef().data()); + lua_pushstring(L, obj.asStringRef().c_str()); lua_rawset(L, -3); } break; @@ -2766,10 +2725,10 @@ void ccvector_std_string_to_luaval(lua_State* L, const std::vector& int index = 1; - for (std::string_view value : inValue) + for (const std::string& value : inValue) { lua_pushnumber(L, (lua_Number)index); - lua_pushlstring(L, value.data(), value.length()); + lua_pushstring(L, value.c_str()); lua_rawset(L, -3); ++index; } @@ -2899,7 +2858,10 @@ void std_map_string_string_to_luaval(lua_State* L, const std::map* ret, const char* funcName) +bool luaval_to_std_map_string_string(lua_State* L, + int lo, + std::map* ret, + const char* funcName) { if (nullptr == L || nullptr == ret || lua_gettop(L) < lo) return false; @@ -2918,15 +2880,15 @@ bool luaval_to_std_map_string_string(lua_State* L, int lo, hlookup::string_mapemplace(key, value); // (*ret)[key] = value; + (*ret)[key] = value; } } else @@ -3060,7 +3022,8 @@ void uniformLocation_to_luaval(lua_State* L, const cocos2d::backend::UniformLoca lua_rawset(L, -3); } -void program_activeattrs_to_luaval(lua_State* L, const hlookup::string_map& attrs) +void program_activeattrs_to_luaval(lua_State* L, + const std::unordered_map& attrs) { if (L == nullptr) return; diff --git a/extensions/scripting/lua-bindings/manual/LuaBasicConversions.h b/extensions/scripting/lua-bindings/manual/LuaBasicConversions.h index d6665b5a70..a754959def 100644 --- a/extensions/scripting/lua-bindings/manual/LuaBasicConversions.h +++ b/extensions/scripting/lua-bindings/manual/LuaBasicConversions.h @@ -594,11 +594,6 @@ CC_LUA_DLL bool luaval_to_std_vector_string(lua_State* L, std::vector* ret, const char* funcName = ""); -CC_LUA_DLL bool luaval_to_std_vector_string_view(lua_State* L, - int lo, - std::vector* ret, - const char* funcName = ""); - /** * Get a pointer points to a std::vector from a Lua array table in the stack. * @@ -875,7 +870,7 @@ extern bool luaval_to_std_vector_vec3(lua_State* L, int lo, std::vector* ret, + std::map* ret, const char* funcName); /**@}**/ @@ -1145,7 +1140,7 @@ void ccvector_to_luaval(lua_State* L, const cocos2d::Vector& inValue) * @param v a cocos2d::Map object. */ template -void ccmap_string_key_to_luaval(lua_State* L, const cocos2d::StringMap& v) +void ccmap_string_key_to_luaval(lua_State* L, const cocos2d::Map& v) { lua_newtable(L); @@ -1154,8 +1149,8 @@ void ccmap_string_key_to_luaval(lua_State* L, const cocos2d::StringMap& v) for (auto iter = v.begin(); iter != v.end(); ++iter) { - auto& key = iter->first; - T obj = iter->second; + std::string key = iter->first; + T obj = iter->second; if (nullptr != dynamic_cast(obj)) { auto name = reinterpret_cast(typeid(*obj).name()); @@ -1365,8 +1360,9 @@ CC_LUA_DLL bool luaval_to_uniformLocation(lua_State* L, */ CC_LUA_DLL void uniformLocation_to_luaval(lua_State* L, const cocos2d::backend::UniformLocation& desc); -CC_LUA_DLL void program_activeattrs_to_luaval(lua_State* L, - const hlookup::string_map& map); +CC_LUA_DLL void program_activeattrs_to_luaval( + lua_State* L, + const std::unordered_map& map); // end group /// @} diff --git a/extensions/scripting/lua-bindings/manual/audioengine/lua_cocos2dx_audioengine_manual.cpp b/extensions/scripting/lua-bindings/manual/audioengine/lua_cocos2dx_audioengine_manual.cpp index a43793b275..7274d48664 100644 --- a/extensions/scripting/lua-bindings/manual/audioengine/lua_cocos2dx_audioengine_manual.cpp +++ b/extensions/scripting/lua-bindings/manual/audioengine/lua_cocos2dx_audioengine_manual.cpp @@ -269,11 +269,11 @@ int lua_cocos2dx_audioengine_AudioEngine_setFinishCallback(lua_State* tolua_S) LUA_FUNCTION handler = (toluafix_ref_function(tolua_S, 3, 0)); - cocos2d::AudioEngine::setFinishCallback(arg0, [=](int audioID, std::string_view filePath) { + cocos2d::AudioEngine::setFinishCallback(arg0, [=](int audioID, std::string filePath) { LuaStack* stack = LuaEngine::getInstance()->getLuaStack(); stack->pushInt(audioID); - stack->pushString(filePath); + stack->pushString(filePath.c_str()); stack->executeFunctionByHandler(handler, 2); diff --git a/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.cpp b/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.cpp index 1b8eb8f218..963f1d2e15 100644 --- a/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.cpp +++ b/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.cpp @@ -4546,7 +4546,7 @@ EventListenerAcceleration* LuaEventListenerAcceleration::create() return eventAcceleration; } -EventListenerCustom* LuaEventListenerCustom::create(std::string_view eventName) +EventListenerCustom* LuaEventListenerCustom::create(const std::string& eventName) { EventListenerCustom* eventCustom = new EventListenerCustom(); if (eventCustom->init(eventName, [=](EventCustom* event) { @@ -6109,12 +6109,12 @@ static int lua_cocos2dx_Console_addCommand(lua_State* tolua_S) handler = (toluafix_ref_function(tolua_S, 3, 0)); ScriptHandlerMgr::getInstance()->addCustomHandler((void*)cobj, handler); - Console::Command outValue = {name, help, [=](int fd, std::string_view args) { + Console::Command outValue = {name, help, [=](int fd, const std::string& args) { auto stack = LuaEngine::getInstance()->getLuaStack(); auto Ls = stack->getLuaState(); // lua-callback, the third param; tolua_pushnumber(Ls, fd); - tolua_pushstring(Ls, args.data()); + tolua_pushstring(Ls, args.c_str()); stack->executeFunctionByHandler(handler, 2); }}; @@ -6928,7 +6928,7 @@ int lua_cocos2dx_get_PolygonInfo_filename(lua_State* tolua_S) return 0; } #endif - tolua_pushstring(tolua_S, cobj->getFilename().data()); + tolua_pushcppstring(tolua_S, cobj->getFilename()); return 1; #if COCOS2D_DEBUG >= 1 @@ -7430,11 +7430,11 @@ static int tolua_cocos2d_utils_captureScreen(lua_State* tolua_S) LUA_FUNCTION handler = toluafix_ref_function(tolua_S, 2, 0); std::string fileName = tolua_tocppstring(tolua_S, 3, ""); cocos2d::utils::captureScreen( - [=](bool succeed, std::string_view name) { + [=](bool succeed, const std::string& name) { auto stack = LuaEngine::getInstance()->getLuaStack(); auto Ls = stack->getLuaState(); tolua_pushboolean(Ls, succeed); - tolua_pushstring(Ls, name.data()); + tolua_pushstring(Ls, name.c_str()); stack->executeFunctionByHandler(handler, 2); toluafix_remove_function_by_refid(tolua_S, handler); }, diff --git a/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.hpp b/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.hpp index d8ab149f92..ffca5eacff 100644 --- a/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.hpp +++ b/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.hpp @@ -44,7 +44,7 @@ NS_CC_BEGIN class LuaEventListenerCustom { public: - static EventListenerCustom* create(std::string_view eventName); + static EventListenerCustom* create(const std::string& eventName); }; class LuaEventListenerAcceleration diff --git a/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.cpp b/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.cpp index 3fa250fdb6..be047e4b4b 100644 --- a/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.cpp +++ b/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.cpp @@ -85,7 +85,7 @@ void CustomGUIReader::init(std::string& className, int createFunc, int setPropsF (*callbackMap)[className] = parseselector(CustomGUIReader::setCustomProps); } -void CustomGUIReader::setCustomProps(std::string_view classType, +void CustomGUIReader::setCustomProps(const std::string& classType, cocos2d::Ref* widget, const rapidjson::Value& customOptions) { @@ -96,7 +96,7 @@ void CustomGUIReader::setCustomProps(std::string_view classType, customOptions.Accept(writer); auto stack = LuaEngine::getInstance()->getLuaStack(); - stack->pushString(classType); + stack->pushString(classType.c_str(), static_cast(classType.size())); stack->pushObject(widget, "cc.Ref"); stack->pushString(buffer.GetString(), static_cast(buffer.GetSize())); stack->executeFunctionByHandler(_setPropsFunc, 3); diff --git a/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.h b/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.h index 9c331a16fd..79c4ab3ec7 100644 --- a/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.h +++ b/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.h @@ -43,7 +43,7 @@ public: Ref* createInstance(); - void setCustomProps(std::string_view classType, cocos2d::Ref* widget, const rapidjson::Value& customOptions); + void setCustomProps(const std::string& classType, cocos2d::Ref* widget, const rapidjson::Value& customOptions); private: std::string _className; diff --git a/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.cpp b/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.cpp index 27e19dbf39..d063179bed 100644 --- a/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.cpp +++ b/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.cpp @@ -112,10 +112,11 @@ static int lua_cocos2dx_ArmatureAnimation_setMovementEventCallFunc(lua_State* L) ScriptHandlerMgr::HandlerType::ARMATURE_EVENT); self->setMovementEventCallFunc( - [=](Armature* armature, MovementEventType movementType, std::string_view movementID) { + [=](Armature* armature, MovementEventType movementType, const std::string& movementID) { if (0 != handler) { - LuaArmatureMovementEventData movementData(armature, (int)movementType, movementID); + std::string strMovementID = movementID; + LuaArmatureMovementEventData movementData(armature, (int)movementType, strMovementID); LuaArmatureWrapperEventData wrapperData( LuaArmatureWrapperEventData::LuaArmatureWrapperEventType::MOVEMENT_EVENT, (void*)&movementData); @@ -187,22 +188,22 @@ static int lua_cocos2dx_ArmatureAnimation_setFrameEventCallFunc(lua_State* L) ScriptHandlerMgr::getInstance()->addObjectHandler((void*)wrapper, handler, ScriptHandlerMgr::HandlerType::ARMATURE_EVENT); - self->setFrameEventCallFunc( - [=](cocostudio::Bone* bone, std::string_view frameEventName, int originFrameIndex, int currentFrameIndex) { - if (0 != handler) - { - std::string strFrameEventName(frameEventName); + self->setFrameEventCallFunc([=](cocostudio::Bone* bone, const std::string& frameEventName, int originFrameIndex, + int currentFrameIndex) { + if (0 != handler) + { + std::string strFrameEventName(frameEventName); - LuaArmatureFrameEventData frameData(bone, frameEventName, originFrameIndex, currentFrameIndex); + LuaArmatureFrameEventData frameData(bone, frameEventName, originFrameIndex, currentFrameIndex); - LuaArmatureWrapperEventData wrapperData( - LuaArmatureWrapperEventData::LuaArmatureWrapperEventType::FRAME_EVENT, (void*)&frameData); + LuaArmatureWrapperEventData wrapperData( + LuaArmatureWrapperEventData::LuaArmatureWrapperEventType::FRAME_EVENT, (void*)&frameData); - BasicScriptData data((void*)vec.at(0), (void*)&wrapperData); + BasicScriptData data((void*)vec.at(0), (void*)&wrapperData); - LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::ARMATURE_EVENT, (void*)&data); - } - }); + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::ARMATURE_EVENT, (void*)&data); + } + }); return 0; } diff --git a/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.hpp b/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.hpp index 422d717d84..afd08dc0e5 100644 --- a/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.hpp +++ b/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.hpp @@ -78,7 +78,7 @@ struct LuaArmatureMovementEventData int movementType; std::string movementID; - LuaArmatureMovementEventData(cocos2d::Ref* _objTarget, int _movementType,std::string_view _movementID):objTarget(_objTarget),movementType(_movementType),movementID(_movementID) + LuaArmatureMovementEventData(cocos2d::Ref* _objTarget, int _movementType,const std::string& _movementID):objTarget(_objTarget),movementType(_movementType),movementID(_movementID) { } }; @@ -90,7 +90,7 @@ struct LuaArmatureFrameEventData int originFrameIndex; int currentFrameIndex; - LuaArmatureFrameEventData( cocos2d::Ref* _objTarget, std::string_view _frameEventName, int _originFrameIndex, int _currentFrameIndex):objTarget(_objTarget), frameEventName(_frameEventName),originFrameIndex(_originFrameIndex), currentFrameIndex(_currentFrameIndex) + LuaArmatureFrameEventData( cocos2d::Ref* _objTarget, const std::string& _frameEventName, int _originFrameIndex, int _currentFrameIndex):objTarget(_objTarget), frameEventName(_frameEventName),originFrameIndex(_originFrameIndex), currentFrameIndex(_currentFrameIndex) { } }; diff --git a/extensions/scripting/lua-bindings/manual/network/lua_downloader.cpp b/extensions/scripting/lua-bindings/manual/network/lua_downloader.cpp index ba66c3442b..179eb45bf0 100644 --- a/extensions/scripting/lua-bindings/manual/network/lua_downloader.cpp +++ b/extensions/scripting/lua-bindings/manual/network/lua_downloader.cpp @@ -270,26 +270,27 @@ static int lua_downloader_setOnTaskError(lua_State* L) luaL_argcheck(L, lua_isfunction(L, 2), 2, "should be a function"); saveCallback(L, d, "setOnTaskError"); - d->setOnTaskError([d, L](const DownloadTask& task, int errorCode, int errorCodeInternal, std::string_view errorSt) { - int ret = getCallback(L, d, "setOnTaskError"); // stack callbackfn - if (ret) - { - pushTaskTable(L, task); // stack callbackfn, task - lua_pushnumber(L, errorCode); - lua_pushnumber(L, errorCodeInternal); - lua_pushlstring(L, errorSt.data(), errorSt.length()); - if (lua_pcall(L, 4, 0, 0) != 0) + d->setOnTaskError( + [d, L](const DownloadTask& task, int errorCode, int errorCodeInternal, const std::string& errorSt) { + int ret = getCallback(L, d, "setOnTaskError"); // stack callbackfn + if (ret) + { + pushTaskTable(L, task); // stack callbackfn, task + lua_pushnumber(L, errorCode); + lua_pushnumber(L, errorCodeInternal); + lua_pushstring(L, errorSt.c_str()); + if (lua_pcall(L, 4, 0, 0) != 0) + { + lua_pop(L, 1); // remove callback or nil + luaL_error(L, "cc.Downloader.setOnTaskError invoke callback error!"); + return; + } + } + else { lua_pop(L, 1); // remove callback or nil - luaL_error(L, "cc.Downloader.setOnTaskError invoke callback error!"); - return; } - } - else - { - lua_pop(L, 1); // remove callback or nil - } - }); + }); return 0; } diff --git a/extensions/scripting/lua-bindings/manual/network/lua_xml_http_request.cpp b/extensions/scripting/lua-bindings/manual/network/lua_xml_http_request.cpp index dce4f0d92a..b6b942c6e7 100644 --- a/extensions/scripting/lua-bindings/manual/network/lua_xml_http_request.cpp +++ b/extensions/scripting/lua-bindings/manual/network/lua_xml_http_request.cpp @@ -76,16 +76,16 @@ public: inline int getReadyState() const { return _readyState; } inline cocos2d::network::HttpRequest* getHttpRequest() const { return _httpRequest; } - inline std::string_view getStatusText() const { return _statusText; } + inline const std::string& getStatusText() const { return _statusText; } inline void setStatus(int status) { _status = status; } inline int getStatus() { return _status; } - inline std::string_view getUrl() { return _url; } - inline void setUrl(std::string_view url) { _url = url; } + inline const std::string& getUrl() { return _url; } + inline void setUrl(const std::string& url) { _url = url; } - inline std::string_view getMethod() const { return _meth; } - inline void setMethod(std::string_view meth) { _meth = meth; } + inline const std::string& getMethod() const { return _meth; } + inline void setMethod(const std::string& meth) { _meth = meth; } inline void setAsync(bool isAsync) { _isAsync = isAsync; } inline void setIsNetWork(bool isNetWork) { _isNetwork = isNetWork; } @@ -621,8 +621,7 @@ static int lua_get_XMLHttpRequest_statusText(lua_State* L) } #endif - auto statusText = self->getStatusText(); - lua_pushlstring(L, statusText.data(), statusText.length()); + lua_pushstring(L, self->getStatusText().c_str()); return 1; diff --git a/extensions/scripting/lua-bindings/manual/platform/ios/CCLuaObjcBridge.mm b/extensions/scripting/lua-bindings/manual/platform/ios/CCLuaObjcBridge.mm index b50ec4d916..f28f8b47b2 100644 --- a/extensions/scripting/lua-bindings/manual/platform/ios/CCLuaObjcBridge.mm +++ b/extensions/scripting/lua-bindings/manual/platform/ios/CCLuaObjcBridge.mm @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -22,12 +22,13 @@ THE SOFTWARE. ****************************************************************************/ + #include "scripting/lua-bindings/manual/platform/ios/CCLuaObjcBridge.h" #include NS_CC_BEGIN -void LuaObjcBridge::luaopen_luaoc(lua_State* L) +void LuaObjcBridge::luaopen_luaoc(lua_State *L) { s_luaState = L; lua_newtable(L); @@ -37,36 +38,39 @@ void LuaObjcBridge::luaopen_luaoc(lua_State* L) lua_setglobal(L, "LuaObjcBridge"); } -static void luaTableToObjcDictionary(lua_State* L, NSMutableDictionary* dict, NSString* key) -{ - NSMutableDictionary* dict2 = [[NSMutableDictionary alloc] init]; - lua_pushnil(L); - while (lua_next(L, -2)) - { - NSString* key2 = [NSString stringWithCString:lua_tostring(L, -2) encoding:NSUTF8StringEncoding]; +static void luaTableToObjcDictionary(lua_State *L, NSMutableDictionary *dict,NSString *key){ + NSMutableDictionary *dict2 = [[NSMutableDictionary alloc] init]; + lua_pushnil(L); + while(lua_next(L, -2)) + { + NSString *key2 = [NSString stringWithCString:lua_tostring(L, -2) encoding:NSUTF8StringEncoding]; + switch (lua_type(L, -1)) { - case LUA_TNUMBER: - [dict2 setObject:[NSNumber numberWithFloat:lua_tonumber(L, -1)] forKey:key2]; - break; - - case LUA_TBOOLEAN: - [dict2 setObject:[NSNumber numberWithBool:lua_toboolean(L, -1)] forKey:key2]; - break; - - case LUA_TSTRING: - [dict2 setObject:[NSString stringWithCString:lua_tostring(L, -1) encoding:NSUTF8StringEncoding] - forKey:key2]; - break; - case LUA_TTABLE: - luaTableToObjcDictionary(L, dict2, key2); - break; + case LUA_TNUMBER: + [dict2 setObject:[NSNumber numberWithFloat:lua_tonumber(L, -1)] forKey:key2]; + break; + + case LUA_TBOOLEAN: + [dict2 setObject:[NSNumber numberWithBool:lua_toboolean(L, -1)] forKey:key2]; + break; + + case LUA_TSTRING: + [dict2 setObject:[NSString stringWithCString:lua_tostring(L, -1) encoding:NSUTF8StringEncoding] + forKey:key2]; + break; + case LUA_TTABLE: + luaTableToObjcDictionary(L, dict2, key2); + break; } - lua_pop(L, 1); + lua_pop(L,1); } - + + [dict setObject:dict2 forKey:key]; + + } /** @@ -74,24 +78,24 @@ static void luaTableToObjcDictionary(lua_State* L, NSMutableDictionary* dict, NS methodName args */ -int LuaObjcBridge::callObjcStaticMethod(lua_State* L) +int LuaObjcBridge::callObjcStaticMethod(lua_State *L) { if (lua_gettop(L) != 3 || !lua_isstring(L, -3) || !lua_isstring(L, -2)) { - lua_pushboolean(L, 0); - lua_pushinteger(L, kLuaBridgeErrorInvalidParameters); - return 2; + lua_pushboolean(L, 0); + lua_pushinteger(L, kLuaBridgeErrorInvalidParameters); + return 2; } - - const char* className = lua_tostring(L, -3); - const char* methodName = lua_tostring(L, -2); + + const char *className = lua_tostring(L, -3); + const char *methodName = lua_tostring(L, -2); if (!className || !methodName) { lua_pushboolean(L, 0); lua_pushinteger(L, kLuaBridgeErrorInvalidParameters); return 2; } - + Class targetClass = NSClassFromString([NSString stringWithCString:className encoding:NSUTF8StringEncoding]); if (!targetClass) { @@ -99,14 +103,14 @@ int LuaObjcBridge::callObjcStaticMethod(lua_State* L) lua_pushinteger(L, kLuaBridgeErrorClassNotFound); return 2; } - + SEL methodSel; bool hasArguments = lua_istable(L, -1); if (hasArguments) { - NSString* methodName_ = [NSString stringWithCString:methodName encoding:NSUTF8StringEncoding]; - methodName_ = [NSString stringWithFormat:@"%@:", methodName_]; - methodSel = NSSelectorFromString(methodName_); + NSString *methodName_ = [NSString stringWithCString:methodName encoding:NSUTF8StringEncoding]; + methodName_ = [NSString stringWithFormat:@"%@:", methodName_]; + methodSel = NSSelectorFromString(methodName_); } else { @@ -118,59 +122,58 @@ int LuaObjcBridge::callObjcStaticMethod(lua_State* L) lua_pushinteger(L, kLuaBridgeErrorMethodNotFound); return 2; } - - NSMethodSignature* methodSig = [targetClass methodSignatureForSelector:(SEL)methodSel]; + + NSMethodSignature *methodSig = [targetClass methodSignatureForSelector:(SEL)methodSel]; if (methodSig == nil) { lua_pushboolean(L, 0); lua_pushinteger(L, kLuaBridgeErrorMethodSignature); return 2; } - - @try - { - NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:methodSig]; + + @try { + NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig]; [invocation setTarget:targetClass]; [invocation setSelector:methodSel]; NSUInteger returnLength = [methodSig methodReturnLength]; - const char* returnType = [methodSig methodReturnType]; - + const char *returnType = [methodSig methodReturnType]; + if (hasArguments) { - NSMutableDictionary* dict = [NSMutableDictionary dictionary]; + NSMutableDictionary *dict = [NSMutableDictionary dictionary]; lua_pushnil(L); while (lua_next(L, -2)) { - NSString* key = [NSString stringWithCString:lua_tostring(L, -2) encoding:NSUTF8StringEncoding]; - + NSString *key = [NSString stringWithCString:lua_tostring(L, -2) encoding:NSUTF8StringEncoding]; + switch (lua_type(L, -1)) { - case LUA_TNUMBER: - [dict setObject:[NSNumber numberWithFloat:lua_tonumber(L, -1)] forKey:key]; - break; - - case LUA_TBOOLEAN: - [dict setObject:[NSNumber numberWithBool:lua_toboolean(L, -1)] forKey:key]; - break; - - case LUA_TSTRING: - [dict setObject:[NSString stringWithCString:lua_tostring(L, -1) encoding:NSUTF8StringEncoding] - forKey:key]; - break; - - case LUA_TTABLE: - luaTableToObjcDictionary(L, dict, key); - break; - - case LUA_TFUNCTION: - int functionId = retainLuaFunction(L, -1, NULL); - [dict setObject:[NSNumber numberWithInt:functionId] forKey:key]; - break; + case LUA_TNUMBER: + [dict setObject:[NSNumber numberWithFloat:lua_tonumber(L, -1)] forKey:key]; + break; + + case LUA_TBOOLEAN: + [dict setObject:[NSNumber numberWithBool:lua_toboolean(L, -1)] forKey:key]; + break; + + case LUA_TSTRING: + [dict setObject:[NSString stringWithCString:lua_tostring(L, -1) encoding:NSUTF8StringEncoding] + forKey:key]; + break; + + case LUA_TTABLE: + luaTableToObjcDictionary(L, dict, key); + break; + + case LUA_TFUNCTION: + int functionId = retainLuaFunction(L, -1, NULL); + [dict setObject:[NSNumber numberWithInt:functionId] forKey:key]; + break; } - + lua_pop(L, 1); } - + [invocation setArgument:&dict atIndex:2]; [invocation invoke]; } @@ -178,7 +181,7 @@ int LuaObjcBridge::callObjcStaticMethod(lua_State* L) { [invocation invoke]; } - + lua_pushboolean(L, 1); if (returnLength > 0) { @@ -188,19 +191,19 @@ int LuaObjcBridge::callObjcStaticMethod(lua_State* L) [invocation getReturnValue:&ret]; pushValue(L, ret); } - else if (strcmp(returnType, @encode(BOOL)) == 0) // BOOL + else if (strcmp(returnType, @encode(BOOL)) == 0) // BOOL { char ret; [invocation getReturnValue:&ret]; lua_pushboolean(L, ret); } - else if (strcmp(returnType, @encode(int)) == 0) // int + else if (strcmp(returnType, @encode(int)) == 0) // int { int ret; [invocation getReturnValue:&ret]; lua_pushinteger(L, ret); } - else if (strcmp(returnType, @encode(float)) == 0) // float + else if (strcmp(returnType, @encode(float)) == 0) // float { float ret; [invocation getReturnValue:&ret]; @@ -218,16 +221,16 @@ int LuaObjcBridge::callObjcStaticMethod(lua_State* L) } return 2; } - @catch (NSException* exception) + @catch (NSException *exception) { NSLog(@"EXCEPTION THROW: %@", exception); lua_pushboolean(L, 0); lua_pushinteger(L, kLuaBridgeErrorExceptionOccurred); - return 2; + return 2; } } -void LuaObjcBridge::pushValue(lua_State* L, void* val) +void LuaObjcBridge::pushValue(lua_State *L, void *val) { id oval = (id)val; if (oval == nil) @@ -236,8 +239,8 @@ void LuaObjcBridge::pushValue(lua_State* L, void* val) } else if ([oval isKindOfClass:[NSNumber class]]) { - NSNumber* number = (NSNumber*)oval; - const char* numberType = [number objCType]; + NSNumber *number = (NSNumber *)oval; + const char *numberType = [number objCType]; if (strcmp(numberType, @encode(BOOL)) == 0) { lua_pushboolean(L, [number boolValue]); @@ -258,15 +261,15 @@ void LuaObjcBridge::pushValue(lua_State* L, void* val) else if ([oval isKindOfClass:[NSDictionary class]]) { lua_newtable(L); - + for (id key in oval) { - const char* key_ = [[NSString stringWithFormat:@"%@", key] cStringUsingEncoding:NSUTF8StringEncoding]; + const char *key_ = [[NSString stringWithFormat:@"%@", key] cStringUsingEncoding:NSUTF8StringEncoding]; lua_pushstring(L, key_); pushValue(L, [oval objectForKey:key]); lua_rawset(L, -3); } - + return; } else diff --git a/extensions/scripting/lua-bindings/manual/ui/lua_cocos2dx_webview_manual.cpp b/extensions/scripting/lua-bindings/manual/ui/lua_cocos2dx_webview_manual.cpp index 88fc10209c..a9d616e842 100644 --- a/extensions/scripting/lua-bindings/manual/ui/lua_cocos2dx_webview_manual.cpp +++ b/extensions/scripting/lua-bindings/manual/ui/lua_cocos2dx_webview_manual.cpp @@ -63,8 +63,8 @@ static int lua_cocos2dx_WebView_setOnShouldStartLoading(lua_State* L) #endif LUA_FUNCTION handler = (toluafix_ref_function(L, 2, 0)); - std::function callback = - [L, handler](ui::WebView* sender, std::string_view url) -> bool { + std::function callback = + [L, handler](ui::WebView* sender, const std::string& url) -> bool { toluafix_pushusertype_ccobject(L, sender->_ID, &(sender->_luaID), (void*)sender, "ccui.WebView"); tolua_pushcppstring(L, url); return LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(handler, 2); @@ -118,13 +118,13 @@ static int lua_cocos2dx_WebView_setOnDidFinishLoading(lua_State* L) } #endif - LUA_FUNCTION handler = (toluafix_ref_function(L, 2, 0)); - std::function callback = [L, handler](ui::WebView* sender, - std::string_view url) { - toluafix_pushusertype_ccobject(L, sender->_ID, &(sender->_luaID), (void*)sender, "ccui.WebView"); - tolua_pushcppstring(L, url); - LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(handler, 2); - }; + LUA_FUNCTION handler = (toluafix_ref_function(L, 2, 0)); + std::function callback = + [L, handler](ui::WebView* sender, const std::string& url) { + toluafix_pushusertype_ccobject(L, sender->_ID, &(sender->_luaID), (void*)sender, "ccui.WebView"); + tolua_pushcppstring(L, url); + LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(handler, 2); + }; ScriptHandlerMgr::getInstance()->addCustomHandler((void*)self, handler); self->setOnDidFinishLoading(callback); @@ -173,13 +173,13 @@ static int lua_cocos2dx_WebView_setOnDidFailLoading(lua_State* L) } #endif - LUA_FUNCTION handler = (toluafix_ref_function(L, 2, 0)); - std::function callback = [L, handler](ui::WebView* sender, - std::string_view url) { - toluafix_pushusertype_ccobject(L, sender->_ID, &(sender->_luaID), (void*)sender, "ccui.WebView"); - tolua_pushcppstring(L, url); - LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(handler, 2); - }; + LUA_FUNCTION handler = (toluafix_ref_function(L, 2, 0)); + std::function callback = + [L, handler](ui::WebView* sender, const std::string& url) { + toluafix_pushusertype_ccobject(L, sender->_ID, &(sender->_luaID), (void*)sender, "ccui.WebView"); + tolua_pushcppstring(L, url); + LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(handler, 2); + }; ScriptHandlerMgr::getInstance()->addCustomHandler((void*)self, handler); self->setOnDidFailLoading(callback); diff --git a/templates/cpp-template-default/CMakeLists.txt b/templates/cpp-template-default/CMakeLists.txt index 04bebd1d1c..210f150ede 100644 --- a/templates/cpp-template-default/CMakeLists.txt +++ b/templates/cpp-template-default/CMakeLists.txt @@ -133,14 +133,15 @@ set(all_code_files ) if(NOT ANDROID) add_executable(${APP_NAME} ${all_code_files}) - target_link_libraries(${APP_NAME} ${ADXE_LUA_LIB}) else() add_library(${APP_NAME} SHARED ${all_code_files}) - # whole archive ${ADXE_LUA_LIB} to make sure JNI_Onload can be invoke from java - target_link_libraries(${APP_NAME} -Wl,--whole-archive ${ADXE_LUA_LIB} -Wl,--no-whole-archive) + add_subdirectory(${ADXE_ROOT_PATH}/cocos/platform/android ${ENGINE_BINARY_PATH}/cocos/platform) + target_link_libraries(${APP_NAME} -Wl,--whole-archive cpp_android_spec -Wl,--no-whole-archive) + config_android_shared_libs("org.cocos2dx.lib" "${CMAKE_CURRENT_SOURCE_DIR}/proj.android/app/src") endif() +target_link_libraries(${APP_NAME} ${ADXE_CORE_LIB}) target_include_directories(${APP_NAME} PRIVATE Classes PRIVATE ${ADXE_ROOT_PATH}/cocos/audio/include/ diff --git a/templates/cpp-template-default/Classes/AppDelegate.cpp b/templates/cpp-template-default/Classes/AppDelegate.cpp index 0119494ae1..9e7d6a6d68 100644 --- a/templates/cpp-template-default/Classes/AppDelegate.cpp +++ b/templates/cpp-template-default/Classes/AppDelegate.cpp @@ -3,17 +3,17 @@ Copyright (c) 2021 Bytedance Inc. https://adxe.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 @@ -29,19 +29,23 @@ #define USE_AUDIO_ENGINE 1 #if USE_AUDIO_ENGINE -# include "audio/include/AudioEngine.h" +#include "audio/include/AudioEngine.h" #endif USING_NS_CC; static cocos2d::Size designResolutionSize = cocos2d::Size(1280, 720); -static cocos2d::Size smallResolutionSize = cocos2d::Size(480, 320); +static cocos2d::Size smallResolutionSize = cocos2d::Size(480, 320); static cocos2d::Size mediumResolutionSize = cocos2d::Size(1024, 768); -static cocos2d::Size largeResolutionSize = cocos2d::Size(2048, 1536); +static cocos2d::Size largeResolutionSize = cocos2d::Size(2048, 1536); -AppDelegate::AppDelegate() {} +AppDelegate::AppDelegate() +{ +} -AppDelegate::~AppDelegate() {} +AppDelegate::~AppDelegate() +{ +} // if you want a different context, modify the value of glContextAttrs // it will affect all platforms @@ -53,24 +57,20 @@ void AppDelegate::initGLContextAttrs() GLView::setGLContextAttrs(glContextAttrs); } -// if you want to use the package manager to install more packages, +// if you want to use the package manager to install more packages, // don't modify or remove this function static int register_all_packages() { - return 0; // flag for packages manager + return 0; //flag for packages manager } -bool AppDelegate::applicationDidFinishLaunching() -{ +bool AppDelegate::applicationDidFinishLaunching() { // initialize director auto director = Director::getInstance(); - auto glview = director->getOpenGLView(); - if (!glview) - { -#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || \ - (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) - glview = GLViewImpl::createWithRect( - "HelloCpp", cocos2d::Rect(0, 0, designResolutionSize.width, designResolutionSize.height)); + auto glview = director->getOpenGLView(); + if(!glview) { +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) + glview = GLViewImpl::createWithRect("HelloCpp", cocos2d::Rect(0, 0, designResolutionSize.width, designResolutionSize.height)); #else glview = GLViewImpl::create("HelloCpp"); #endif @@ -84,26 +84,22 @@ bool AppDelegate::applicationDidFinishLaunching() director->setAnimationInterval(1.0f / 60); // Set the design resolution - glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, - ResolutionPolicy::NO_BORDER); + glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::NO_BORDER); auto frameSize = glview->getFrameSize(); // if the frame's height is larger than the height of medium size. if (frameSize.height > mediumResolutionSize.height) - { - director->setContentScaleFactor(MIN(largeResolutionSize.height / designResolutionSize.height, - largeResolutionSize.width / designResolutionSize.width)); + { + director->setContentScaleFactor(MIN(largeResolutionSize.height/designResolutionSize.height, largeResolutionSize.width/designResolutionSize.width)); } // if the frame's height is larger than the height of small size. else if (frameSize.height > smallResolutionSize.height) - { - director->setContentScaleFactor(MIN(mediumResolutionSize.height / designResolutionSize.height, - mediumResolutionSize.width / designResolutionSize.width)); + { + director->setContentScaleFactor(MIN(mediumResolutionSize.height/designResolutionSize.height, mediumResolutionSize.width/designResolutionSize.width)); } // if the frame's height is smaller than the height of medium size. else - { - director->setContentScaleFactor(MIN(smallResolutionSize.height / designResolutionSize.height, - smallResolutionSize.width / designResolutionSize.width)); + { + director->setContentScaleFactor(MIN(smallResolutionSize.height/designResolutionSize.height, smallResolutionSize.width/designResolutionSize.width)); } register_all_packages(); @@ -118,8 +114,7 @@ bool AppDelegate::applicationDidFinishLaunching() } // This function will be called when the app is inactive. Note, when receiving a phone call it is invoked. -void AppDelegate::applicationDidEnterBackground() -{ +void AppDelegate::applicationDidEnterBackground() { Director::getInstance()->stopAnimation(); #if USE_AUDIO_ENGINE @@ -128,8 +123,7 @@ void AppDelegate::applicationDidEnterBackground() } // this function will be called when the app is active again -void AppDelegate::applicationWillEnterForeground() -{ +void AppDelegate::applicationWillEnterForeground() { Director::getInstance()->startAnimation(); #if USE_AUDIO_ENGINE diff --git a/templates/cpp-template-default/Classes/AppDelegate.h b/templates/cpp-template-default/Classes/AppDelegate.h index 0ce2aaaa5b..41d860f5de 100644 --- a/templates/cpp-template-default/Classes/AppDelegate.h +++ b/templates/cpp-template-default/Classes/AppDelegate.h @@ -3,17 +3,17 @@ Copyright (c) 2021 Bytedance Inc. https://adxe.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 @@ -23,8 +23,8 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef _APP_DELEGATE_H_ -#define _APP_DELEGATE_H_ +#ifndef _APP_DELEGATE_H_ +#define _APP_DELEGATE_H_ #include "cocos2d.h" @@ -33,7 +33,7 @@ Private inheritance here hides part of interface from Director. */ -class AppDelegate : private cocos2d::Application +class AppDelegate : private cocos2d::Application { public: AppDelegate(); @@ -61,4 +61,5 @@ public: void applicationWillEnterForeground() override; }; -#endif // _APP_DELEGATE_H_ +#endif // _APP_DELEGATE_H_ + diff --git a/templates/cpp-template-default/Classes/HelloWorldScene.cpp b/templates/cpp-template-default/Classes/HelloWorldScene.cpp index 5ad976f977..620e41e866 100644 --- a/templates/cpp-template-default/Classes/HelloWorldScene.cpp +++ b/templates/cpp-template-default/Classes/HelloWorldScene.cpp @@ -48,8 +48,8 @@ bool HelloWorld::init() auto visibleSize = Director::getInstance()->getVisibleSize(); auto origin = Director::getInstance()->getVisibleOrigin(); - auto safeArea = Director::getInstance()->getSafeAreaRect(); - auto safeOrigin = safeArea.origin; + auto safeArea = Director::getInstance()->getSafeAreaRect(); + auto safeOrigin = safeArea.origin; ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program @@ -97,7 +97,7 @@ bool HelloWorld::init() } // add "HelloWorld" splash screen" - auto sprite = Sprite::create("HelloWorld.png"sv); + auto sprite = Sprite::create("HelloWorld.png"); if (sprite == nullptr) { problemLoading("'HelloWorld.png'"); diff --git a/templates/cpp-template-default/Classes/HelloWorldScene.h b/templates/cpp-template-default/Classes/HelloWorldScene.h index 894b4e0dd8..c77c79b593 100644 --- a/templates/cpp-template-default/Classes/HelloWorldScene.h +++ b/templates/cpp-template-default/Classes/HelloWorldScene.h @@ -3,17 +3,17 @@ Copyright (c) 2021 Bytedance Inc. https://adxe.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 @@ -37,4 +37,4 @@ public: void menuCloseCallback(Ref* sender); }; -#endif // __HELLOWORLD_SCENE_H__ +#endif // __HELLOWORLD_SCENE_H__ diff --git a/templates/cpp-template-default/proj.android/app/jni/hellocpp/main.cpp b/templates/cpp-template-default/proj.android/app/jni/hellocpp/main.cpp index ccd4757e4c..6cab47cbb3 100644 --- a/templates/cpp-template-default/proj.android/app/jni/hellocpp/main.cpp +++ b/templates/cpp-template-default/proj.android/app/jni/hellocpp/main.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -29,16 +29,14 @@ #include "AppDelegate.h" -#define LOG_TAG "main" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) +#define LOG_TAG "main" +#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) -namespace -{ +namespace { std::unique_ptr appDelegate; } -void cocos_android_app_init(JNIEnv* env) -{ +void cocos_android_app_init(JNIEnv* env) { LOGD("cocos_android_app_init"); appDelegate.reset(new AppDelegate()); } diff --git a/templates/cpp-template-default/proj.ios_mac/ios/AppController.h b/templates/cpp-template-default/proj.ios_mac/ios/AppController.h index aeb65f5085..f0e78b7763 100644 --- a/templates/cpp-template-default/proj.ios_mac/ios/AppController.h +++ b/templates/cpp-template-default/proj.ios_mac/ios/AppController.h @@ -2,19 +2,19 @@ Copyright (c) 2010-2013 cocos2d-x.org Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -29,8 +29,10 @@ @class RootViewController; @interface AppController : NSObject { + } @property(nonatomic, readonly) RootViewController* viewController; @end + diff --git a/templates/cpp-template-default/proj.ios_mac/ios/AppController.mm b/templates/cpp-template-default/proj.ios_mac/ios/AppController.mm index 2dafa17d40..edcd92178a 100644 --- a/templates/cpp-template-default/proj.ios_mac/ios/AppController.mm +++ b/templates/cpp-template-default/proj.ios_mac/ios/AppController.mm @@ -2,19 +2,19 @@ Copyright (c) 2010-2013 cocos2d-x.org Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -39,29 +39,29 @@ // cocos2d application instance static AppDelegate s_sharedApplication; -- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions -{ - - cocos2d::Application* app = cocos2d::Application::getInstance(); - +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { + + cocos2d::Application *app = cocos2d::Application::getInstance(); + // Initialize the GLView attributes app->initGLContextAttrs(); cocos2d::GLViewImpl::convertAttrs(); - + // Override point for customization after application launch. // Add the view controller's view to the window and display. - window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; + window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; // Use RootViewController to manage CCEAGLView - _viewController = [[RootViewController alloc] init]; + _viewController = [[RootViewController alloc]init]; _viewController.wantsFullScreenLayout = YES; + // Set RootViewController to window - if ([[UIDevice currentDevice].systemVersion floatValue] < 6.0) + if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) { // warning: addSubView doesn't work on iOS6 - [window addSubview:_viewController.view]; + [window addSubview: _viewController.view]; } else { @@ -72,91 +72,82 @@ static AppDelegate s_sharedApplication; [window makeKeyAndVisible]; [[UIApplication sharedApplication] setStatusBarHidden:true]; - - // Launching the app with the arguments -NSAllowsDefaultLineBreakStrategy NO to force back to the old behavior. - if ([[UIDevice currentDevice].systemVersion floatValue] >= 13.0f) + + //Launching the app with the arguments -NSAllowsDefaultLineBreakStrategy NO to force back to the old behavior. + if ( [[UIDevice currentDevice].systemVersion floatValue] >= 13.0f) { [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"NSAllowsDefaultLineBreakStrategy"]; } - + // IMPORTANT: Setting the GLView should be done after creating the RootViewController - cocos2d::GLView* glview = cocos2d::GLViewImpl::createWithEAGLView((__bridge void*)_viewController.view); + cocos2d::GLView *glview = cocos2d::GLViewImpl::createWithEAGLView((__bridge void *)_viewController.view); cocos2d::Director::getInstance()->setOpenGLView(glview); - - // run the cocos2d-x game scene + + //run the cocos2d-x game scene app->run(); return YES; } -- (void)applicationWillResignActive:(UIApplication*)application -{ + +- (void)applicationWillResignActive:(UIApplication *)application { /* - Sent when the application is about to move from active to inactive state. This can occur for certain types of - temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and - it begins the transition to the background state. Use this method to pause ongoing tasks, disable timers, and - throttle down OpenGL ES frame rates. Games should use this method to pause the game. + Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. */ // We don't need to call this method any more. It will interrupt user defined game pause&resume logic /* cocos2d::Director::getInstance()->pause(); */ } -- (void)applicationDidBecomeActive:(UIApplication*)application -{ +- (void)applicationDidBecomeActive:(UIApplication *)application { /* - Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was - previously in the background, optionally refresh the user interface. + Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. */ // We don't need to call this method any more. It will interrupt user defined game pause&resume logic /* cocos2d::Director::getInstance()->resume(); */ } -- (void)applicationDidEnterBackground:(UIApplication*)application -{ +- (void)applicationDidEnterBackground:(UIApplication *)application { /* - Use this method to release shared resources, save user data, invalidate timers, and store enough application state - information to restore your application to its current state in case it is terminated later. If your application - supports background execution, called instead of applicationWillTerminate: when the user quits. + Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + If your application supports background execution, called instead of applicationWillTerminate: when the user quits. */ cocos2d::Application::getInstance()->applicationDidEnterBackground(); } -- (void)applicationWillEnterForeground:(UIApplication*)application -{ +- (void)applicationWillEnterForeground:(UIApplication *)application { /* - Called as part of transition from the background to the inactive state: here you can undo many of the changes made - on entering the background. + Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background. */ cocos2d::Application::getInstance()->applicationWillEnterForeground(); } -- (void)applicationWillTerminate:(UIApplication*)application -{ +- (void)applicationWillTerminate:(UIApplication *)application { /* Called when the application is about to terminate. See also applicationDidEnterBackground:. */ } + #pragma mark - #pragma mark Memory management -- (void)applicationDidReceiveMemoryWarning:(UIApplication*)application -{ +- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { /* - Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) - later. + Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. */ } + #if __has_feature(objc_arc) #else -- (void)dealloc -{ +- (void)dealloc { [window release]; [_viewController release]; [super dealloc]; } #endif + @end diff --git a/templates/cpp-template-default/proj.ios_mac/ios/RootViewController.h b/templates/cpp-template-default/proj.ios_mac/ios/RootViewController.h index 06c3b05562..ed4046d6fa 100644 --- a/templates/cpp-template-default/proj.ios_mac/ios/RootViewController.h +++ b/templates/cpp-template-default/proj.ios_mac/ios/RootViewController.h @@ -26,8 +26,10 @@ #import + @interface RootViewController : UIViewController { + } -- (BOOL)prefersStatusBarHidden; +- (BOOL) prefersStatusBarHidden; @end diff --git a/templates/cpp-template-default/proj.ios_mac/ios/RootViewController.mm b/templates/cpp-template-default/proj.ios_mac/ios/RootViewController.mm index 8eaf237db9..a4c37af784 100644 --- a/templates/cpp-template-default/proj.ios_mac/ios/RootViewController.mm +++ b/templates/cpp-template-default/proj.ios_mac/ios/RootViewController.mm @@ -28,11 +28,11 @@ #import "cocos2d.h" #import "platform/ios/CCEAGLView-ios.h" + @implementation RootViewController /* - // The designated initializer. Override if you create the controller programmatically and want to perform -customization that is not appropriate for viewDidLoad. + // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { // Custom initialization @@ -42,89 +42,81 @@ customization that is not appropriate for viewDidLoad. */ // Implement loadView to create a view hierarchy programmatically, without using a nib. -- (void)loadView -{ +- (void)loadView { // Initialize the CCEAGLView - CCEAGLView* eaglView = [CCEAGLView viewWithFrame:[UIScreen mainScreen].bounds - pixelFormat:(__bridge NSString*)cocos2d::GLViewImpl::_pixelFormat - depthFormat:cocos2d::GLViewImpl::_depthFormat - preserveBackbuffer:NO - sharegroup:nil - multiSampling:cocos2d::GLViewImpl::_multisamplingCount > 0 ? YES : NO - numberOfSamples:cocos2d::GLViewImpl::_multisamplingCount]; - + CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [UIScreen mainScreen].bounds + pixelFormat: (__bridge NSString *)cocos2d::GLViewImpl::_pixelFormat + depthFormat: cocos2d::GLViewImpl::_depthFormat + preserveBackbuffer: NO + sharegroup: nil + multiSampling: cocos2d::GLViewImpl::_multisamplingCount > 0 ? YES : NO + numberOfSamples: cocos2d::GLViewImpl::_multisamplingCount ]; + // Enable or disable multiple touches [eaglView setMultipleTouchEnabled:NO]; - + // Set EAGLView as view of RootViewController self.view = eaglView; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. -- (void)viewDidLoad -{ +- (void)viewDidLoad { [super viewDidLoad]; } -- (void)viewWillAppear:(BOOL)animated -{ +- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } -- (void)viewDidDisappear:(BOOL)animated -{ +- (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } + // For ios6, use supportedInterfaceOrientations & shouldAutorotate instead #ifdef __IPHONE_6_0 -- (NSUInteger)supportedInterfaceOrientations -{ +- (NSUInteger) supportedInterfaceOrientations{ return UIInterfaceOrientationMaskAllButUpsideDown; } #endif -- (BOOL)shouldAutorotate -{ +- (BOOL) shouldAutorotate { return YES; } -- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation -{ +- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; auto glview = cocos2d::Director::getInstance()->getOpenGLView(); if (glview) { - CCEAGLView* eaglview = (__bridge CCEAGLView*)glview->getEAGLView(); + CCEAGLView *eaglview = (__bridge CCEAGLView *)glview->getEAGLView(); if (eaglview) { CGSize s = CGSizeMake([eaglview getWidth], [eaglview getHeight]); - cocos2d::Application::getInstance()->applicationScreenSizeChanged((int)s.width, (int)s.height); + cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height); } } } -// fix not hide status on ios7 -- (BOOL)prefersStatusBarHidden -{ +//fix not hide status on ios7 +- (BOOL)prefersStatusBarHidden { return YES; } // Controls the application's preferred home indicator auto-hiding when this view controller is shown. -- (BOOL)prefersHomeIndicatorAutoHidden -{ +- (BOOL)prefersHomeIndicatorAutoHidden { return YES; } -- (void)didReceiveMemoryWarning -{ +- (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } + @end diff --git a/templates/cpp-template-default/proj.ios_mac/mac/main.cpp b/templates/cpp-template-default/proj.ios_mac/mac/main.cpp index 44045f8feb..ed8ee7c15c 100644 --- a/templates/cpp-template-default/proj.ios_mac/mac/main.cpp +++ b/templates/cpp-template-default/proj.ios_mac/mac/main.cpp @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2010 cocos2d-x.org Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -28,7 +28,7 @@ USING_NS_CC; -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { AppDelegate app; return Application::getInstance()->run(); diff --git a/templates/cpp-template-default/proj.linux/main.cpp b/templates/cpp-template-default/proj.linux/main.cpp index 3cbdb2bc35..2bd3032f78 100644 --- a/templates/cpp-template-default/proj.linux/main.cpp +++ b/templates/cpp-template-default/proj.linux/main.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -31,7 +31,7 @@ USING_NS_CC; -int main(int argc, char** argv) +int main(int argc, char **argv) { // create the application instance AppDelegate app; diff --git a/templates/cpp-template-default/proj.win32/main.cpp b/templates/cpp-template-default/proj.win32/main.cpp index 636fa57f07..c3c5dc6fd4 100644 --- a/templates/cpp-template-default/proj.win32/main.cpp +++ b/templates/cpp-template-default/proj.win32/main.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -28,7 +28,10 @@ USING_NS_CC; -int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) +int WINAPI _tWinMain(HINSTANCE hInstance, + HINSTANCE hPrevInstance, + LPTSTR lpCmdLine, + int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); diff --git a/templates/cpp-template-default/proj.win32/main.h b/templates/cpp-template-default/proj.win32/main.h index 64d684e652..13b6f36fd2 100644 --- a/templates/cpp-template-default/proj.win32/main.h +++ b/templates/cpp-template-default/proj.win32/main.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -25,7 +25,7 @@ #ifndef __MAIN_H__ #define __MAIN_H__ -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include @@ -34,4 +34,4 @@ // C RunTime Header Files #include "platform/CCStdC.h" -#endif // __MAIN_H__ +#endif // __MAIN_H__ diff --git a/templates/cpp-template-default/proj.win32/resource.h b/templates/cpp-template-default/proj.win32/resource.h index da3599c69c..6f4e11f03d 100644 --- a/templates/cpp-template-default/proj.win32/resource.h +++ b/templates/cpp-template-default/proj.win32/resource.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,18 +27,18 @@ // Used by game.RC // -#define IDS_PROJNAME 100 -#define IDR_TESTJS 100 +#define IDS_PROJNAME 100 +#define IDR_TESTJS 100 -#define ID_FILE_NEW_WINDOW 32771 +#define ID_FILE_NEW_WINDOW 32771 // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED -# ifndef APSTUDIO_READONLY_SYMBOLS -# define _APS_NEXT_RESOURCE_VALUE 201 -# define _APS_NEXT_CONTROL_VALUE 1000 -# define _APS_NEXT_SYMED_VALUE 101 -# define _APS_NEXT_COMMAND_VALUE 32775 -# endif +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 201 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 32775 +#endif #endif diff --git a/templates/lua-template-default/CMakeLists.txt b/templates/lua-template-default/CMakeLists.txt index b5559c79d4..c2f896ee00 100644 --- a/templates/lua-template-default/CMakeLists.txt +++ b/templates/lua-template-default/CMakeLists.txt @@ -132,16 +132,17 @@ set(APP_SRC ${GAME_HEADER} ${GAME_SOURCE}) # mark app complie info and libs info if(NOT ANDROID) add_executable(${APP_NAME} ${APP_SRC}) - target_link_libraries(${APP_NAME} ${ADXE_LUA_LIB}) else() add_library(${APP_NAME} SHARED ${APP_SRC}) + add_subdirectory(${ADXE_ROOT_PATH}/cocos/platform/android ${ENGINE_BINARY_PATH}/cocos/platform) + target_link_libraries(${APP_NAME} -Wl,--whole-archive cpp_android_spec -Wl,--no-whole-archive) add_subdirectory(${ADXE_ROOT_PATH}/extensions/scripting/lua-bindings/proj.android ${ENGINE_BINARY_PATH}/cocos/lua-android) target_link_libraries(${APP_NAME} -Wl,--whole-archive lua_android_spec -Wl,--no-whole-archive) - # whole archive ${ADXE_LUA_LIB} to make sure JNI_Onload can be invoke from java - target_link_libraries(${APP_NAME} -Wl,--whole-archive ${ADXE_LUA_LIB} -Wl,--whole-archive) + config_android_shared_libs("org.cocos2dx.lib" "${CMAKE_CURRENT_SOURCE_DIR}/frameworks/runtime-src/proj.android/app/src") endif() +target_link_libraries(${APP_NAME} ${ADXE_LUA_LIB}) target_include_directories(${APP_NAME} PRIVATE ${RUNTIME_SRC_ROOT}/Classes) # mark app resources, resource will be copy auto after mark diff --git a/templates/lua-template-default/frameworks/runtime-src/Classes/AppDelegate.cpp b/templates/lua-template-default/frameworks/runtime-src/Classes/AppDelegate.cpp index abbab833fd..b0542eff32 100644 --- a/templates/lua-template-default/frameworks/runtime-src/Classes/AppDelegate.cpp +++ b/templates/lua-template-default/frameworks/runtime-src/Classes/AppDelegate.cpp @@ -3,17 +3,17 @@ Copyright (c) 2021 Bytedance Inc. https://adxe.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 @@ -31,31 +31,35 @@ #define USE_AUDIO_ENGINE 1 #if USE_AUDIO_ENGINE -# include "audio/include/AudioEngine.h" +#include "audio/include/AudioEngine.h" #endif USING_NS_CC; using namespace std; -AppDelegate::AppDelegate() {} +AppDelegate::AppDelegate() +{ +} -AppDelegate::~AppDelegate() {} +AppDelegate::~AppDelegate() +{ +} // if you want a different context, modify the value of glContextAttrs // it will affect all platforms void AppDelegate::initGLContextAttrs() { // set OpenGL context attributes: red,green,blue,alpha,depth,stencil,multisamplesCount - GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8, 0}; + GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8, 0 }; GLView::setGLContextAttrs(glContextAttrs); } -// if you want to use the package manager to install more packages, +// if you want to use the package manager to install more packages, // don't modify or remove this function static int register_all_packages() { - return 0; // flag for packages manager + return 0; //flag for packages manager } bool AppDelegate::applicationDidFinishLaunching() @@ -72,12 +76,12 @@ bool AppDelegate::applicationDidFinishLaunching() register_all_packages(); LuaStack* stack = engine->getLuaStack(); - - // register custom function - // LuaStack* stack = engine->getLuaStack(); - // register_custom_function(stack->getLuaState()); - - stack->addSearchPath("src"); + + //register custom function + //LuaStack* stack = engine->getLuaStack(); + //register_custom_function(stack->getLuaState()); + + stack->addSearchPath("src"); FileUtils::getInstance()->addSearchPath("res"); if (engine->executeString("require 'main'")) { diff --git a/templates/lua-template-default/frameworks/runtime-src/Classes/AppDelegate.h b/templates/lua-template-default/frameworks/runtime-src/Classes/AppDelegate.h index 53d04ceced..c5a12ae3d6 100644 --- a/templates/lua-template-default/frameworks/runtime-src/Classes/AppDelegate.h +++ b/templates/lua-template-default/frameworks/runtime-src/Classes/AppDelegate.h @@ -3,17 +3,17 @@ Copyright (c) 2021 Bytedance Inc. https://adxe.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 @@ -32,7 +32,7 @@ Private inheritance here hides part of interface from Director. */ -class AppDelegate : private cocos2d::Application +class AppDelegate : private cocos2d::Application { public: AppDelegate(); diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.android/app/jni/hellolua/main.cpp b/templates/lua-template-default/frameworks/runtime-src/proj.android/app/jni/hellolua/main.cpp index ccd4757e4c..6cab47cbb3 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.android/app/jni/hellolua/main.cpp +++ b/templates/lua-template-default/frameworks/runtime-src/proj.android/app/jni/hellolua/main.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -29,16 +29,14 @@ #include "AppDelegate.h" -#define LOG_TAG "main" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) +#define LOG_TAG "main" +#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) -namespace -{ +namespace { std::unique_ptr appDelegate; } -void cocos_android_app_init(JNIEnv* env) -{ +void cocos_android_app_init(JNIEnv* env) { LOGD("cocos_android_app_init"); appDelegate.reset(new AppDelegate()); } diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.h b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.h index aeb65f5085..f0e78b7763 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.h +++ b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.h @@ -2,19 +2,19 @@ Copyright (c) 2010-2013 cocos2d-x.org Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -29,8 +29,10 @@ @class RootViewController; @interface AppController : NSObject { + } @property(nonatomic, readonly) RootViewController* viewController; @end + diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm index 2dafa17d40..8116adeba9 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm +++ b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm @@ -2,19 +2,19 @@ Copyright (c) 2010-2013 cocos2d-x.org Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -39,29 +39,29 @@ // cocos2d application instance static AppDelegate s_sharedApplication; -- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions -{ - - cocos2d::Application* app = cocos2d::Application::getInstance(); - +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { + + cocos2d::Application *app = cocos2d::Application::getInstance(); + // Initialize the GLView attributes app->initGLContextAttrs(); cocos2d::GLViewImpl::convertAttrs(); - + // Override point for customization after application launch. // Add the view controller's view to the window and display. - window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; + window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; // Use RootViewController to manage CCEAGLView - _viewController = [[RootViewController alloc] init]; + _viewController = [[RootViewController alloc]init]; _viewController.wantsFullScreenLayout = YES; + // Set RootViewController to window - if ([[UIDevice currentDevice].systemVersion floatValue] < 6.0) + if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) { // warning: addSubView doesn't work on iOS6 - [window addSubview:_viewController.view]; + [window addSubview: _viewController.view]; } else { @@ -73,90 +73,81 @@ static AppDelegate s_sharedApplication; [[UIApplication sharedApplication] setStatusBarHidden:true]; - // Launching the app with the arguments -NSAllowsDefaultLineBreakStrategy NO to force back to the old behavior. - if ([[UIDevice currentDevice].systemVersion floatValue] >= 13.0f) + //Launching the app with the arguments -NSAllowsDefaultLineBreakStrategy NO to force back to the old behavior. + if ( [[UIDevice currentDevice].systemVersion floatValue] >= 13.0f) { [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"NSAllowsDefaultLineBreakStrategy"]; } - + // IMPORTANT: Setting the GLView should be done after creating the RootViewController - cocos2d::GLView* glview = cocos2d::GLViewImpl::createWithEAGLView((__bridge void*)_viewController.view); + cocos2d::GLView *glview = cocos2d::GLViewImpl::createWithEAGLView((__bridge void *)_viewController.view); cocos2d::Director::getInstance()->setOpenGLView(glview); - - // run the cocos2d-x game scene + + //run the cocos2d-x game scene app->run(); return YES; } -- (void)applicationWillResignActive:(UIApplication*)application -{ + +- (void)applicationWillResignActive:(UIApplication *)application { /* - Sent when the application is about to move from active to inactive state. This can occur for certain types of - temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and - it begins the transition to the background state. Use this method to pause ongoing tasks, disable timers, and - throttle down OpenGL ES frame rates. Games should use this method to pause the game. + Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. */ // We don't need to call this method any more. It will interrupt user defined game pause&resume logic /* cocos2d::Director::getInstance()->pause(); */ } -- (void)applicationDidBecomeActive:(UIApplication*)application -{ +- (void)applicationDidBecomeActive:(UIApplication *)application { /* - Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was - previously in the background, optionally refresh the user interface. + Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. */ // We don't need to call this method any more. It will interrupt user defined game pause&resume logic /* cocos2d::Director::getInstance()->resume(); */ } -- (void)applicationDidEnterBackground:(UIApplication*)application -{ +- (void)applicationDidEnterBackground:(UIApplication *)application { /* - Use this method to release shared resources, save user data, invalidate timers, and store enough application state - information to restore your application to its current state in case it is terminated later. If your application - supports background execution, called instead of applicationWillTerminate: when the user quits. + Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + If your application supports background execution, called instead of applicationWillTerminate: when the user quits. */ cocos2d::Application::getInstance()->applicationDidEnterBackground(); } -- (void)applicationWillEnterForeground:(UIApplication*)application -{ +- (void)applicationWillEnterForeground:(UIApplication *)application { /* - Called as part of transition from the background to the inactive state: here you can undo many of the changes made - on entering the background. + Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background. */ cocos2d::Application::getInstance()->applicationWillEnterForeground(); } -- (void)applicationWillTerminate:(UIApplication*)application -{ +- (void)applicationWillTerminate:(UIApplication *)application { /* Called when the application is about to terminate. See also applicationDidEnterBackground:. */ } + #pragma mark - #pragma mark Memory management -- (void)applicationDidReceiveMemoryWarning:(UIApplication*)application -{ +- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { /* - Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) - later. + Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. */ } + #if __has_feature(objc_arc) #else -- (void)dealloc -{ +- (void)dealloc { [window release]; [_viewController release]; [super dealloc]; } #endif + @end diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.h b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.h index 06c3b05562..ed4046d6fa 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.h +++ b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.h @@ -26,8 +26,10 @@ #import + @interface RootViewController : UIViewController { + } -- (BOOL)prefersStatusBarHidden; +- (BOOL) prefersStatusBarHidden; @end diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.mm b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.mm index 1210e485cc..37144e420f 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.mm +++ b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.mm @@ -28,11 +28,11 @@ #import "cocos2d.h" #import "platform/ios/CCEAGLView-ios.h" + @implementation RootViewController /* - // The designated initializer. Override if you create the controller programmatically and want to perform -customization that is not appropriate for viewDidLoad. + // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { // Custom initialization @@ -42,89 +42,81 @@ customization that is not appropriate for viewDidLoad. */ // Implement loadView to create a view hierarchy programmatically, without using a nib. -- (void)loadView -{ +- (void)loadView { // Initialize the CCEAGLView - CCEAGLView* eaglView = [CCEAGLView viewWithFrame:[UIScreen mainScreen].bounds - pixelFormat:(__bridge NSString*)cocos2d::GLViewImpl::_pixelFormat - depthFormat:cocos2d::GLViewImpl::_depthFormat - preserveBackbuffer:NO - sharegroup:nil - multiSampling:NO - numberOfSamples:0]; - + CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [UIScreen mainScreen].bounds + pixelFormat: (__bridge NSString *)cocos2d::GLViewImpl::_pixelFormat + depthFormat: cocos2d::GLViewImpl::_depthFormat + preserveBackbuffer: NO + sharegroup: nil + multiSampling: NO + numberOfSamples: 0 ]; + // Enable or disable multiple touches [eaglView setMultipleTouchEnabled:NO]; - + // Set EAGLView as view of RootViewController self.view = eaglView; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. -- (void)viewDidLoad -{ +- (void)viewDidLoad { [super viewDidLoad]; } -- (void)viewWillAppear:(BOOL)animated -{ +- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } -- (void)viewDidDisappear:(BOOL)animated -{ +- (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } + // For ios6, use supportedInterfaceOrientations & shouldAutorotate instead #ifdef __IPHONE_6_0 -- (NSUInteger)supportedInterfaceOrientations -{ +- (NSUInteger) supportedInterfaceOrientations{ return UIInterfaceOrientationMaskAllButUpsideDown; } #endif -- (BOOL)shouldAutorotate -{ +- (BOOL) shouldAutorotate { return YES; } -- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation -{ +- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; auto glview = cocos2d::Director::getInstance()->getOpenGLView(); if (glview) { - CCEAGLView* eaglview = (__bridge CCEAGLView*)glview->getEAGLView(); + CCEAGLView *eaglview = (__bridge CCEAGLView *)glview->getEAGLView(); if (eaglview) { CGSize s = CGSizeMake([eaglview getWidth], [eaglview getHeight]); - cocos2d::Application::getInstance()->applicationScreenSizeChanged((int)s.width, (int)s.height); + cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height); } } } -// fix not hide status on ios7 -- (BOOL)prefersStatusBarHidden -{ +//fix not hide status on ios7 +- (BOOL)prefersStatusBarHidden { return YES; } // Controls the application's preferred home indicator auto-hiding when this view controller is shown. -- (BOOL)prefersHomeIndicatorAutoHidden -{ +- (BOOL)prefersHomeIndicatorAutoHidden { return YES; } -- (void)didReceiveMemoryWarning -{ +- (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } + @end diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/mac/main.cpp b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/mac/main.cpp index 371a2b4fcc..cd6c3e8cdc 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/mac/main.cpp +++ b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/mac/main.cpp @@ -4,8 +4,9 @@ USING_NS_CC; -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { AppDelegate app; return Application::getInstance()->run(); } + diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.linux/main.cpp b/templates/lua-template-default/frameworks/runtime-src/proj.linux/main.cpp index c03ce74184..042c94fef6 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.linux/main.cpp +++ b/templates/lua-template-default/frameworks/runtime-src/proj.linux/main.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -32,7 +32,7 @@ USING_NS_CC; -int main(int argc, char** argv) +int main(int argc, char **argv) { // create the application instance AppDelegate app; diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.win32/main.cpp b/templates/lua-template-default/frameworks/runtime-src/proj.win32/main.cpp index 0aa2a83d78..88ab9a2856 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.win32/main.cpp +++ b/templates/lua-template-default/frameworks/runtime-src/proj.win32/main.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -30,7 +30,10 @@ USING_NS_CC; // uncomment below line, open debug console #define USE_WIN32_CONSOLE -int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) +int WINAPI _tWinMain(HINSTANCE hInstance, + HINSTANCE hPrevInstance, + LPTSTR lpCmdLine, + int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.win32/main.h b/templates/lua-template-default/frameworks/runtime-src/proj.win32/main.h index d262f80bb8..7943814d12 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.win32/main.h +++ b/templates/lua-template-default/frameworks/runtime-src/proj.win32/main.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -24,7 +24,7 @@ #pragma once -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include @@ -32,3 +32,4 @@ // C RunTime Header Files #include "platform/CCStdC.h" + diff --git a/tests/cpp-tests/CMakeLists.txt b/tests/cpp-tests/CMakeLists.txt index f8ed4d4781..3e73a2fa57 100644 --- a/tests/cpp-tests/CMakeLists.txt +++ b/tests/cpp-tests/CMakeLists.txt @@ -524,14 +524,16 @@ set(all_code_files if(NOT ANDROID) add_executable(${APP_NAME} ${all_code_files}) - target_link_libraries(${APP_NAME} ${ADXE_CORE_LIB}) else() add_library(${APP_NAME} SHARED ${all_code_files}) - # whole archive ${ADXE_LUA_LIB} to make sure JNI_Onload can be invoke from java - target_link_libraries(${APP_NAME} -Wl,--whole-archive ${ADXE_CORE_LIB} -Wl,--no-whole-archive) + add_subdirectory(${ADXE_ROOT_PATH}/cocos/platform/android ${ENGINE_BINARY_PATH}/cocos/platform) + target_link_libraries(${APP_NAME} -Wl,--whole-archive cpp_android_spec -Wl,--no-whole-archive) + config_android_shared_libs("org.cocos2dx.lib" "${CMAKE_CURRENT_SOURCE_DIR}/proj.android/app/src") endif() +target_link_libraries(${APP_NAME} ${ADXE_CORE_LIB}) + target_include_directories(${APP_NAME} PRIVATE Classes ) diff --git a/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.cpp b/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.cpp index d4be38fbee..e7a86cd63a 100644 --- a/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.cpp +++ b/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -28,12 +28,12 @@ USING_NS_CC; -enum +enum { kTagNode, kTagGrossini, kTagSequence, -}; +}; ActionManagerTests::ActionManagerTests() { @@ -53,9 +53,13 @@ ActionManagerTests::ActionManagerTests() // //------------------------------------------------------------------ -ActionManagerTest::ActionManagerTest() {} +ActionManagerTest::ActionManagerTest() +{ +} -ActionManagerTest::~ActionManagerTest() {} +ActionManagerTest::~ActionManagerTest() +{ +} std::string ActionManagerTest::title() const { @@ -77,23 +81,30 @@ void CrashTest::onEnter() ActionManagerTest::onEnter(); auto child = Sprite::create(s_pathGrossini); - child->setPosition(VisibleRect::center()); + child->setPosition( VisibleRect::center() ); addChild(child, 1, kTagGrossini); - // Sum of all action's duration is 1.5 second. + //Sum of all action's duration is 1.5 second. child->runAction(RotateBy::create(1.5f, 90)); - child->runAction(Sequence::create(DelayTime::create(1.4f), FadeOut::create(1.1f), nullptr)); - - // After 1.5 second, self will be removed. - child->runAction(Sequence::create(DelayTime::create(1.4f), - CallFunc::create(CC_CALLBACK_0(CrashTest::removeThis, this)), nullptr)); + child->runAction(Sequence::create( + DelayTime::create(1.4f), + FadeOut::create(1.1f), + nullptr) + ); + + //After 1.5 second, self will be removed. + child->runAction(Sequence::create( + DelayTime::create(1.4f), + CallFunc::create( CC_CALLBACK_0(CrashTest::removeThis,this)), + nullptr) + ); } void CrashTest::removeThis() { auto child = getChildByTag(kTagGrossini); child->removeChild(child, true); - + getTestSuite()->enterNextTest(); } @@ -115,19 +126,22 @@ void LogicTest::onEnter() addChild(grossini, 0, 2); grossini->setPosition(VisibleRect::center()); - grossini->runAction(Sequence::create(MoveBy::create(1, Vec2(150.0f, 0.0f)), - CallFuncN::create(CC_CALLBACK_1(LogicTest::bugMe, this)), nullptr)); + grossini->runAction( Sequence::create( + MoveBy::create(1, Vec2(150.0f,0.0f)), + CallFuncN::create(CC_CALLBACK_1(LogicTest::bugMe,this)), + nullptr) + ); } void LogicTest::bugMe(Node* node) { - node->stopAllActions(); // After this stop next action not working, if remove this stop everything is working + node->stopAllActions(); //After this stop next action not working, if remove this stop everything is working node->runAction(ScaleTo::create(2, 2)); } std::string LogicTest::subtitle() const { - return "Logic test"; + return "Logic test"; } //------------------------------------------------------------------ @@ -143,30 +157,32 @@ void PauseTest::onEnter() // otherwise the paused action will be resumed at 'onEnter' time // ActionManagerTest::onEnter(); + auto l = Label::createWithTTF("After 5 seconds grossini should move", "fonts/Thonburi.ttf", 16.0f); addChild(l); - l->setPosition(VisibleRect::center().x, VisibleRect::top().y - 75); - + l->setPosition(VisibleRect::center().x, VisibleRect::top().y-75); + + // // Also, this test MUST be done, after [super onEnter] // auto grossini = Sprite::create(s_pathGrossini); addChild(grossini, 0, kTagGrossini); - grossini->setPosition(VisibleRect::center()); - - auto action = MoveBy::create(1, Vec2(150.0f, 0.0f)); + grossini->setPosition(VisibleRect::center() ); + + auto action = MoveBy::create(1, Vec2(150.0f,0.0f)); auto director = Director::getInstance(); director->getActionManager()->addAction(action, grossini, true); - schedule(CC_SCHEDULE_SELECTOR(PauseTest::unpause), 3); + schedule( CC_SCHEDULE_SELECTOR(PauseTest::unpause), 3); } void PauseTest::unpause(float dt) { - unschedule(CC_SCHEDULE_SELECTOR(PauseTest::unpause)); - auto node = getChildByTag(kTagGrossini); + unschedule( CC_SCHEDULE_SELECTOR(PauseTest::unpause) ); + auto node = getChildByTag( kTagGrossini ); auto director = Director::getInstance(); director->getActionManager()->resumeTarget(node); } @@ -189,13 +205,13 @@ void StopActionTest::onEnter() addChild(l); l->setPosition(VisibleRect::center().x, VisibleRect::top().y - 75); - auto pMove = MoveBy::create(2, Vec2(200.0f, 0.0f)); - auto pCallback = CallFunc::create(CC_CALLBACK_0(StopActionTest::stopAction, this)); + auto pMove = MoveBy::create(2, Vec2(200.0f, 0.0f)); + auto pCallback = CallFunc::create(CC_CALLBACK_0(StopActionTest::stopAction,this)); auto pSequence = Sequence::create(pMove, pCallback, nullptr); pSequence->setTag(kTagSequence); auto pChild = Sprite::create(s_pathGrossini); - pChild->setPosition(VisibleRect::center()); + pChild->setPosition( VisibleRect::center() ); addChild(pChild, 1, kTagGrossini); pChild->runAction(pSequence); @@ -220,30 +236,29 @@ std::string StopActionTest::subtitle() const void StopAllActionsTest::onEnter() { ActionManagerTest::onEnter(); - - auto l = - Label::createWithTTF("Should stop scale & move after 4 seconds but keep rotate", "fonts/Thonburi.ttf", 16.0f); + + auto l = Label::createWithTTF("Should stop scale & move after 4 seconds but keep rotate", "fonts/Thonburi.ttf", 16.0f); addChild(l); - l->setPosition(Vec2(VisibleRect::center().x, VisibleRect::top().y - 75)); - - auto pMove1 = MoveBy::create(2, Vec2(200.0f, 0.0f)); - auto pMove2 = MoveBy::create(2, Vec2(-200.0f, 0.0f)); + l->setPosition( Vec2(VisibleRect::center().x, VisibleRect::top().y - 75) ); + + auto pMove1 = MoveBy::create(2, Vec2(200.0f, 0.0f)); + auto pMove2 = MoveBy::create(2, Vec2(-200.0f, 0.0f)); auto pSequenceMove = Sequence::createWithTwoActions(pMove1, pMove2); - auto pRepeatMove = RepeatForever::create(pSequenceMove); + auto pRepeatMove = RepeatForever::create(pSequenceMove); pRepeatMove->setTag(kTagSequence); - - auto pScale1 = ScaleBy::create(2, 1.5f); - auto pScale2 = ScaleBy::create(2, 1.0f / 1.5f); + + auto pScale1 = ScaleBy::create(2, 1.5f); + auto pScale2 = ScaleBy::create(2, 1.0f/1.5f); auto pSequenceScale = Sequence::createWithTwoActions(pScale1, pScale2); - auto pRepeatScale = RepeatForever::create(pSequenceScale); + auto pRepeatScale = RepeatForever::create(pSequenceScale); pRepeatScale->setTag(kTagSequence); - - auto pRotate = RotateBy::create(2, 360); + + auto pRotate = RotateBy::create(2, 360); auto pRepeatRotate = RepeatForever::create(pRotate); - + auto pChild = Sprite::create(s_pathGrossini); - pChild->setPosition(VisibleRect::center()); - + pChild->setPosition( VisibleRect::center() ); + addChild(pChild, 1, kTagGrossini); pChild->runAction(pRepeatMove); pChild->runAction(pRepeatScale); @@ -262,6 +277,7 @@ std::string StopAllActionsTest::subtitle() const return "Stop All Action Test"; } + //------------------------------------------------------------------ // // ResumeTest @@ -298,7 +314,7 @@ void ResumeTest::resumeGrossini(float time) this->unschedule(CC_SCHEDULE_SELECTOR(ResumeTest::resumeGrossini)); auto pGrossini = getChildByTag(kTagGrossini); - auto director = Director::getInstance(); + auto director = Director::getInstance(); director->getActionManager()->resumeTarget(pGrossini); } @@ -311,29 +327,28 @@ void StopActionsByFlagsTest::onEnter() { ActionManagerTest::onEnter(); - auto l = - Label::createWithTTF("Should stop scale & move after 4 seconds but keep rotate", "fonts/Thonburi.ttf", 16.0f); + auto l = Label::createWithTTF("Should stop scale & move after 4 seconds but keep rotate", "fonts/Thonburi.ttf", 16.0f); addChild(l); - l->setPosition(Vec2(VisibleRect::center().x, VisibleRect::top().y - 75)); + l->setPosition( Vec2(VisibleRect::center().x, VisibleRect::top().y - 75) ); - auto pMove1 = MoveBy::create(2, Vec2(200.0f, 0.0f)); - auto pMove2 = MoveBy::create(2, Vec2(-200.0f, 0.0f)); + auto pMove1 = MoveBy::create(2, Vec2(200.0f, 0.0f)); + auto pMove2 = MoveBy::create(2, Vec2(-200.0f, 0.0f)); auto pSequenceMove = Sequence::createWithTwoActions(pMove1, pMove2); - auto pRepeatMove = RepeatForever::create(pSequenceMove); + auto pRepeatMove = RepeatForever::create(pSequenceMove); pRepeatMove->setFlags(kMoveFlag | kRepeatForeverFlag); - auto pScale1 = ScaleBy::create(2, 1.5f); - auto pScale2 = ScaleBy::create(2, 1.0f / 1.5f); + auto pScale1 = ScaleBy::create(2, 1.5f); + auto pScale2 = ScaleBy::create(2, 1.0f/1.5f); auto pSequenceScale = Sequence::createWithTwoActions(pScale1, pScale2); - auto pRepeatScale = RepeatForever::create(pSequenceScale); + auto pRepeatScale = RepeatForever::create(pSequenceScale); pRepeatScale->setFlags(kScaleFlag | kRepeatForeverFlag); - auto pRotate = RotateBy::create(2, 360); + auto pRotate = RotateBy::create(2, 360); auto pRepeatRotate = RepeatForever::create(pRotate); pRepeatRotate->setFlags(kRotateFlag | kRepeatForeverFlag); auto pChild = Sprite::create(s_pathGrossini); - pChild->setPosition(VisibleRect::center()); + pChild->setPosition( VisibleRect::center() ); addChild(pChild, 1, kTagGrossini); pChild->runAction(pRepeatMove); @@ -358,11 +373,17 @@ std::string StopActionsByFlagsTest::subtitle() const // Issue14050Test // //------------------------------------------------------------------ -class SpriteIssue14050 : public Sprite +class SpriteIssue14050: public Sprite { public: - SpriteIssue14050() { log("SpriteIssue14050::constructor"); } - virtual ~SpriteIssue14050() { log("SpriteIssue14050::destructor"); } + SpriteIssue14050() + { + log("SpriteIssue14050::constructor"); + } + virtual ~SpriteIssue14050() + { + log("SpriteIssue14050::destructor"); + } }; void Issue14050Test::onEnter() diff --git a/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.h b/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.h index d4fd6b9a6f..eb7f7528c1 100644 --- a/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.h +++ b/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,7 +34,7 @@ class ActionManagerTest : public TestCase protected: cocos2d::TextureAtlas* _atlas; - std::string _title; + std::string _title; public: ActionManagerTest(); @@ -112,13 +112,11 @@ public: virtual std::string subtitle() const override; virtual void onEnter() override; void stopAction(float time); - protected: - const unsigned int kMoveFlag = 0x01; - const unsigned int kScaleFlag = 0x02; - const unsigned int kRotateFlag = 0x04; - const unsigned int kRepeatForeverFlag = 0x08; // You don't need this for the test, but it's for demonstration how - // to activate several flags on an action. + const unsigned int kMoveFlag = 0x01; + const unsigned int kScaleFlag = 0x02; + const unsigned int kRotateFlag = 0x04; + const unsigned int kRepeatForeverFlag = 0x08; // You don't need this for the test, but it's for demonstration how to activate several flags on an action. }; class Issue14050Test : public ActionManagerTest @@ -128,7 +126,6 @@ public: virtual std::string subtitle() const override; virtual void onEnter() override; - protected: }; diff --git a/tests/cpp-tests/Classes/ActionsEaseTest/ActionsEaseTest.cpp b/tests/cpp-tests/Classes/ActionsEaseTest/ActionsEaseTest.cpp index c10e571f3e..29c9bc3d99 100644 --- a/tests/cpp-tests/Classes/ActionsEaseTest/ActionsEaseTest.cpp +++ b/tests/cpp-tests/Classes/ActionsEaseTest/ActionsEaseTest.cpp @@ -29,13 +29,13 @@ USING_NS_CC; -enum -{ +enum { kTagAction1 = 1, kTagAction2 = 2, - kTagSlider = 1, + kTagSlider = 1, }; + //------------------------------------------------------------------ // // SpriteDemo @@ -44,33 +44,34 @@ enum void EaseSpriteDemo::centerSprites(unsigned int numberOfSprites) { auto s = Director::getInstance()->getWinSize(); - - if (numberOfSprites == 0) + + if( numberOfSprites == 0 ) { _tamara->setVisible(false); _kathia->setVisible(false); _grossini->setVisible(false); } - else if (numberOfSprites == 1) + else if ( numberOfSprites == 1 ) { _tamara->setVisible(false); _kathia->setVisible(false); - _grossini->setPosition(s.width / 2, s.height / 2); + _grossini->setPosition(s.width/2, s.height/2); } - else if (numberOfSprites == 2) + else if( numberOfSprites == 2 ) { - _kathia->setPosition(s.width / 3, s.height / 2); - _tamara->setPosition(2 * s.width / 3, s.height / 2); + _kathia->setPosition(s.width/3, s.height/2); + _tamara->setPosition(2*s.width/3, s.height/2); _grossini->setVisible(false); } - else if (numberOfSprites == 3) + else if( numberOfSprites == 3 ) { - _grossini->setPosition(s.width / 2, s.height / 2); - _tamara->setPosition(s.width / 4, s.height / 2); - _kathia->setPosition(3 * s.width / 4, s.height / 2); + _grossini->setPosition(s.width/2, s.height/2); + _tamara->setPosition(s.width/4, s.height/2); + _kathia->setPosition(3 * s.width/4, s.height/2); } } + //------------------------------------------------------------------ // // SpriteEase @@ -80,22 +81,23 @@ void EaseSpriteDemo::centerSprites(unsigned int numberOfSprites) void SpriteEase::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130,0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseIn::create(move->clone(), 2.5f); + + auto move_ease_in = EaseIn::create(move->clone(), 2.5f); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseOut::create(move->clone(), 2.5f); + + auto move_ease_out = EaseOut::create(move->clone(), 2.5f); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - + + auto a2 = _grossini->runAction(RepeatForever::create(seq1)); a2->setTag(1); @@ -108,6 +110,7 @@ void SpriteEase::onEnter() schedule(CC_SCHEDULE_SELECTOR(SpriteEase::testStopAction), 6.25f); } + void SpriteEase::testStopAction(float dt) { unschedule(CC_SCHEDULE_SELECTOR(SpriteEase::testStopAction)); @@ -121,6 +124,7 @@ std::string SpriteEase::subtitle() const return "EaseIn - EaseOut - Stop"; } + //------------------------------------------------------------------ // // SpriteEaseInOut @@ -131,29 +135,30 @@ void SpriteEaseInOut::onEnter() { EaseSpriteDemo::onEnter(); - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); - // id move_back = move->reverse(); - - auto move_ease_inout1 = EaseInOut::create(move->clone(), 0.65f); + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); +// id move_back = move->reverse(); + + auto move_ease_inout1 = EaseInOut::create(move->clone(), 0.65f); auto move_ease_inout_back1 = move_ease_inout1->reverse(); - - auto move_ease_inout2 = EaseInOut::create(move->clone(), 1.35f); + + auto move_ease_inout2 = EaseInOut::create(move->clone(), 1.35f); auto move_ease_inout_back2 = move_ease_inout2->reverse(); - auto move_ease_inout3 = EaseInOut::create(move->clone(), 1.0f); + auto move_ease_inout3 = EaseInOut::create(move->clone(), 1.0f); auto move_ease_inout_back3 = move_ease_inout3->reverse(); - + auto delay = DelayTime::create(0.25f); - auto seq1 = Sequence::create(move_ease_inout1, delay, move_ease_inout_back1, delay->clone(), nullptr); - auto seq2 = Sequence::create(move_ease_inout2, delay->clone(), move_ease_inout_back2, delay->clone(), nullptr); - auto seq3 = Sequence::create(move_ease_inout3, delay->clone(), move_ease_inout_back3, delay->clone(), nullptr); - + auto seq1 = Sequence::create( move_ease_inout1, delay, move_ease_inout_back1, delay->clone(), nullptr); + auto seq2 = Sequence::create( move_ease_inout2, delay->clone(), move_ease_inout_back2, delay->clone(), nullptr); + auto seq3 = Sequence::create( move_ease_inout3, delay->clone(), move_ease_inout_back3, delay->clone(), nullptr); + _tamara->runAction(RepeatForever::create(seq1)); _kathia->runAction(RepeatForever::create(seq2)); _grossini->runAction(RepeatForever::create(seq3)); } + std::string SpriteEaseInOut::subtitle() const { return "EaseInOut and rates"; @@ -168,27 +173,29 @@ std::string SpriteEaseInOut::subtitle() const void SpriteEaseExponential::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseExponentialIn::create(move->clone()); + + auto move_ease_in = EaseExponentialIn::create(move->clone()); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseExponentialOut::create(move->clone()); + + auto move_ease_out = EaseExponentialOut::create(move->clone()); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); + - _grossini->runAction(RepeatForever::create(seq1)); - _tamara->runAction(RepeatForever::create(seq2)); - _kathia->runAction(RepeatForever::create(seq3)); + _grossini->runAction( RepeatForever::create(seq1)); + _tamara->runAction( RepeatForever::create(seq2)); + _kathia->runAction( RepeatForever::create(seq3)); } + std::string SpriteEaseExponential::subtitle() const { return "ExpIn - ExpOut actions"; @@ -203,23 +210,25 @@ void SpriteEaseExponentialInOut::onEnter() { EaseSpriteDemo::onEnter(); - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease = EaseExponentialInOut::create(move->clone()); - auto move_ease_back = move_ease->reverse(); //--> reverse() - + + auto move_ease = EaseExponentialInOut::create(move->clone() ); + auto move_ease_back = move_ease->reverse(); //--> reverse() + auto delay = DelayTime::create(0.25f); - - auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); - auto seq2 = Sequence::create(move_ease, delay, move_ease_back, delay->clone(), nullptr); - + + auto seq1 = Sequence::create( move, delay, move_back, delay->clone(), nullptr); + auto seq2 = Sequence::create( move_ease, delay, move_ease_back, delay->clone(), nullptr); + this->positionForTwo(); + + _grossini->runAction( RepeatForever::create(seq1)); + _tamara->runAction( RepeatForever::create(seq2)); - _grossini->runAction(RepeatForever::create(seq1)); - _tamara->runAction(RepeatForever::create(seq2)); } + std::string SpriteEaseExponentialInOut::subtitle() const { return "EaseExponentialInOut action"; @@ -234,26 +243,29 @@ void SpriteEaseSine::onEnter() { EaseSpriteDemo::onEnter(); - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseSineIn::create(move->clone()); + + auto move_ease_in = EaseSineIn::create(move->clone() ); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseSineOut::create(move->clone()); + + auto move_ease_out = EaseSineOut::create(move->clone() ); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); + + + _grossini->runAction( RepeatForever::create(seq1)); + _tamara->runAction( RepeatForever::create(seq2)); + _kathia->runAction( RepeatForever::create(seq3)); - _grossini->runAction(RepeatForever::create(seq1)); - _tamara->runAction(RepeatForever::create(seq2)); - _kathia->runAction(RepeatForever::create(seq3)); } + std::string SpriteEaseSine::subtitle() const { return "EaseSineIn - EaseSineOut"; @@ -268,23 +280,24 @@ void SpriteEaseSineInOut::onEnter() { EaseSpriteDemo::onEnter(); - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease = EaseSineInOut::create(move->clone()); + + auto move_ease = EaseSineInOut::create(move->clone() ); auto move_ease_back = move_ease->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease, delay->clone(), move_ease_back, delay->clone(), nullptr); this->positionForTwo(); - _grossini->runAction(RepeatForever::create(seq1)); - _tamara->runAction(RepeatForever::create(seq2)); + _grossini->runAction( RepeatForever::create(seq1)); + _tamara->runAction( RepeatForever::create(seq2)); } + std::string SpriteEaseSineInOut::subtitle() const { return "EaseSineInOut action"; @@ -298,27 +311,28 @@ std::string SpriteEaseSineInOut::subtitle() const void SpriteEaseElastic::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseElasticIn::create(move->clone()); + + auto move_ease_in = EaseElasticIn::create(move->clone() ); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseElasticOut::create(move->clone()); + + auto move_ease_out = EaseElasticOut::create(move->clone() ); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - - _grossini->runAction(RepeatForever::create(seq1)); - _tamara->runAction(RepeatForever::create(seq2)); - _kathia->runAction(RepeatForever::create(seq3)); + + _grossini->runAction( RepeatForever::create(seq1)); + _tamara->runAction( RepeatForever::create(seq2)); + _kathia->runAction( RepeatForever::create(seq3)); } + std::string SpriteEaseElastic::subtitle() const { return "Elastic In - Out actions"; @@ -333,34 +347,36 @@ std::string SpriteEaseElastic::subtitle() const void SpriteEaseElasticInOut::onEnter() { EaseSpriteDemo::onEnter(); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); - - auto move_ease_inout1 = EaseElasticInOut::create(move->clone(), 0.3f); + auto move_ease_inout1 = EaseElasticInOut::create(move->clone(), 0.3f); auto move_ease_inout_back1 = move_ease_inout1->reverse(); - - auto move_ease_inout2 = EaseElasticInOut::create(move->clone(), 0.45f); + + auto move_ease_inout2 = EaseElasticInOut::create(move->clone(), 0.45f); auto move_ease_inout_back2 = move_ease_inout2->reverse(); - - auto move_ease_inout3 = EaseElasticInOut::create(move->clone(), 0.6f); + + auto move_ease_inout3 = EaseElasticInOut::create(move->clone(), 0.6f); auto move_ease_inout_back3 = move_ease_inout3->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move_ease_inout1, delay, move_ease_inout_back1, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_inout2, delay->clone(), move_ease_inout_back2, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_inout3, delay->clone(), move_ease_inout_back3, delay->clone(), nullptr); - - _tamara->runAction(RepeatForever::create(seq1)); - _kathia->runAction(RepeatForever::create(seq2)); - _grossini->runAction(RepeatForever::create(seq3)); + + _tamara->runAction( RepeatForever::create(seq1)); + _kathia->runAction( RepeatForever::create(seq2)); + _grossini->runAction( RepeatForever::create(seq3)); } + std::string SpriteEaseElasticInOut::subtitle() const { return "EaseElasticInOut action"; } + //------------------------------------------------------------------ // // SpriteEaseBounce @@ -370,32 +386,34 @@ std::string SpriteEaseElasticInOut::subtitle() const void SpriteEaseBounce::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseBounceIn::create(move->clone()); + + auto move_ease_in = EaseBounceIn::create(move->clone() ); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseBounceOut::create(move->clone()); + + auto move_ease_out = EaseBounceOut::create(move->clone() ); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - - _grossini->runAction(RepeatForever::create(seq1)); - _tamara->runAction(RepeatForever::create(seq2)); - _kathia->runAction(RepeatForever::create(seq3)); + + _grossini->runAction( RepeatForever::create(seq1)); + _tamara->runAction( RepeatForever::create(seq2)); + _kathia->runAction( RepeatForever::create(seq3)); } + std::string SpriteEaseBounce::subtitle() const { return "Bounce In - Out actions"; } + //------------------------------------------------------------------ // // SpriteEaseBounceInOut @@ -406,23 +424,24 @@ void SpriteEaseBounceInOut::onEnter() { EaseSpriteDemo::onEnter(); - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease = EaseBounceInOut::create(move->clone()); + + auto move_ease = EaseBounceInOut::create(move->clone() ); auto move_ease_back = move_ease->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease, delay->clone(), move_ease_back, delay->clone(), nullptr); - + this->positionForTwo(); - - _grossini->runAction(RepeatForever::create(seq1)); - _tamara->runAction(RepeatForever::create(seq2)); + + _grossini->runAction( RepeatForever::create(seq1)); + _tamara->runAction( RepeatForever::create(seq2)); } + std::string SpriteEaseBounceInOut::subtitle() const { return "EaseBounceInOut action"; @@ -437,27 +456,28 @@ std::string SpriteEaseBounceInOut::subtitle() const void SpriteEaseBack::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseBackIn::create(move->clone()); + + auto move_ease_in = EaseBackIn::create(move->clone()); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseBackOut::create(move->clone()); + + auto move_ease_out = EaseBackOut::create( move->clone()); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - + _grossini->runAction(RepeatForever::create(seq1)); _tamara->runAction(RepeatForever::create(seq2)); - _kathia->runAction(RepeatForever::create(seq3)); + _kathia->runAction(RepeatForever::create(seq3)); } + std::string SpriteEaseBack::subtitle() const { return "Back In - Out actions"; @@ -472,24 +492,25 @@ std::string SpriteEaseBack::subtitle() const void SpriteEaseBackInOut::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease = EaseBackInOut::create(move->clone()); + + auto move_ease = EaseBackInOut::create(move->clone() ); auto move_ease_back = move_ease->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease, delay->clone(), move_ease_back, delay->clone(), nullptr); - + this->positionForTwo(); - - _grossini->runAction(RepeatForever::create(seq1)); - _tamara->runAction(RepeatForever::create(seq2)); + + _grossini->runAction( RepeatForever::create(seq1)); + _tamara->runAction( RepeatForever::create(seq2)); } + std::string SpriteEaseBackInOut::subtitle() const { return "EaseBackInOut action"; @@ -504,52 +525,55 @@ std::string SpriteEaseBackInOut::subtitle() const void SpriteEaseBezier::onEnter() { EaseSpriteDemo::onEnter(); - + auto s = Director::getInstance()->getWinSize(); - + // // startPosition can be any coordinate, but since the movement // is relative to the Bezier curve, make it (0,0) // - + centerSprites(3); - + // sprite 1 ccBezierConfig bezier; - bezier.controlPoint_1 = Vec2(0.0f, s.height / 2); - bezier.controlPoint_2 = Vec2(300.0f, -s.height / 2); - bezier.endPosition = Vec2(300.0f, 100.0f); - - auto bezierForward = BezierBy::create(3, bezier); + bezier.controlPoint_1 = Vec2(0.0f, s.height/2); + bezier.controlPoint_2 = Vec2(300.0f, -s.height/2); + bezier.endPosition = Vec2(300.0f,100.0f); + + auto bezierForward = BezierBy::create(3, bezier); auto bezierEaseForward = EaseBezierAction::create(bezierForward); bezierEaseForward->setBezierParamer(0.5f, 0.5f, 1.0f, 1.0f); - + auto bezierEaseBack = bezierEaseForward->reverse(); - auto rep = RepeatForever::create(Sequence::create(bezierEaseForward, bezierEaseBack, nullptr)); - + auto rep = RepeatForever::create(Sequence::create( bezierEaseForward, bezierEaseBack, nullptr)); + + // sprite 2 - _tamara->setPosition(80, 160); - ccBezierConfig bezier2; - bezier2.controlPoint_1 = Vec2(100.0f, s.height / 2); - bezier2.controlPoint_2 = Vec2(200.0f, -s.height / 2); - bezier2.endPosition = Vec2(240.0f, 160.0f); - - auto bezierTo1 = BezierTo::create(2, bezier2); + _tamara->setPosition(80,160); + ccBezierConfig bezier2; + bezier2.controlPoint_1 = Vec2(100.0f, s.height/2); + bezier2.controlPoint_2 = Vec2(200.0f, -s.height/2); + bezier2.endPosition = Vec2(240.0f,160.0f); + + auto bezierTo1 = BezierTo::create(2, bezier2); auto bezierEaseTo1 = EaseBezierAction::create(bezierTo1); bezierEaseTo1->setBezierParamer(0.5f, 0.5f, 1.0f, 1.0f); - + // sprite 3 - _kathia->setPosition(400.0f, 160.0f); - auto bezierTo2 = BezierTo::create(2, bezier2); + _kathia->setPosition(400.0f,160.0f); + auto bezierTo2 = BezierTo::create(2, bezier2); auto bezierEaseTo2 = EaseBezierAction::create(bezierTo2); bezierEaseTo2->setBezierParamer(0.0f, 0.5f, -5.0f, 1.0f); - _grossini->runAction(rep); + + _grossini->runAction( rep); _tamara->runAction(bezierEaseTo1); _kathia->runAction(bezierEaseTo2); + } -std::string SpriteEaseBezier::subtitle() const +std::string SpriteEaseBezier::subtitle()const { return "SpriteEaseBezier action"; } @@ -563,25 +587,25 @@ std::string SpriteEaseBezier::subtitle() const void SpriteEaseQuadratic::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseQuadraticActionIn::create(move->clone()); + + auto move_ease_in = EaseQuadraticActionIn::create(move->clone() ); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseQuadraticActionOut::create(move->clone()); + + auto move_ease_out = EaseQuadraticActionOut::create(move->clone() ); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - - _grossini->runAction(RepeatForever::create(seq1)); - _tamara->runAction(RepeatForever::create(seq2)); - _kathia->runAction(RepeatForever::create(seq3)); + + _grossini->runAction( RepeatForever::create(seq1)); + _tamara->runAction( RepeatForever::create(seq2)); + _kathia->runAction( RepeatForever::create(seq3)); } std::string SpriteEaseQuadratic::subtitle() const @@ -598,29 +622,30 @@ std::string SpriteEaseQuadratic::subtitle() const void SpriteEaseQuadraticInOut::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease = EaseQuadraticActionInOut::create(move->clone()); + + auto move_ease = EaseQuadraticActionInOut::create(move->clone() ); auto move_ease_back = move_ease->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease, delay->clone(), move_ease_back, delay->clone(), nullptr); - + this->positionForTwo(); - - _grossini->runAction(RepeatForever::create(seq1)); - _tamara->runAction(RepeatForever::create(seq2)); + + _grossini->runAction( RepeatForever::create(seq1)); + _tamara->runAction( RepeatForever::create(seq2)); } -std::string SpriteEaseQuadraticInOut::subtitle() const +std::string SpriteEaseQuadraticInOut::subtitle()const { return "SpriteEaseQuadraticInOut action"; } + //------------------------------------------------------------------ // // SpriteEaseQuartic @@ -630,28 +655,28 @@ std::string SpriteEaseQuadraticInOut::subtitle() const void SpriteEaseQuartic::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseQuarticActionIn::create(move->clone()); + + auto move_ease_in = EaseQuarticActionIn::create(move->clone() ); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseQuarticActionOut::create(move->clone()); + + auto move_ease_out = EaseQuarticActionOut::create(move->clone() ); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - - _grossini->runAction(RepeatForever::create(seq1)); - _tamara->runAction(RepeatForever::create(seq2)); - _kathia->runAction(RepeatForever::create(seq3)); + + _grossini->runAction( RepeatForever::create(seq1)); + _tamara->runAction( RepeatForever::create(seq2)); + _kathia->runAction( RepeatForever::create(seq3)); } -std::string SpriteEaseQuartic::subtitle() const +std::string SpriteEaseQuartic::subtitle()const { return "SpriteEaseQuartic action"; } @@ -665,25 +690,25 @@ std::string SpriteEaseQuartic::subtitle() const void SpriteEaseQuarticInOut::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease = EaseQuarticActionInOut::create(move->clone()); + + auto move_ease = EaseQuarticActionInOut::create(move->clone() ); auto move_ease_back = move_ease->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease, delay->clone(), move_ease_back, delay->clone(), nullptr); - + this->positionForTwo(); - - _grossini->runAction(RepeatForever::create(seq1)); - _tamara->runAction(RepeatForever::create(seq2)); + + _grossini->runAction( RepeatForever::create(seq1)); + _tamara->runAction( RepeatForever::create(seq2)); } -std::string SpriteEaseQuarticInOut::subtitle() const +std::string SpriteEaseQuarticInOut::subtitle()const { return "SpriteEaseQuarticInOut action"; } @@ -697,32 +722,33 @@ std::string SpriteEaseQuarticInOut::subtitle() const void SpriteEaseQuintic::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseQuinticActionIn::create(move->clone()); + + auto move_ease_in = EaseQuinticActionIn::create(move->clone() ); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseQuinticActionOut::create(move->clone()); + + auto move_ease_out = EaseQuinticActionOut::create(move->clone() ); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - - _grossini->runAction(RepeatForever::create(seq1)); - _tamara->runAction(RepeatForever::create(seq2)); - _kathia->runAction(RepeatForever::create(seq3)); + + _grossini->runAction( RepeatForever::create(seq1)); + _tamara->runAction( RepeatForever::create(seq2)); + _kathia->runAction( RepeatForever::create(seq3)); } -std::string SpriteEaseQuintic::subtitle() const +std::string SpriteEaseQuintic::subtitle()const { return "SpriteEaseQuintic action"; } + //------------------------------------------------------------------ // // SpriteEaseQuinticInOut @@ -732,25 +758,25 @@ std::string SpriteEaseQuintic::subtitle() const void SpriteEaseQuinticInOut::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease = EaseQuinticActionInOut::create(move->clone()); + + auto move_ease = EaseQuinticActionInOut::create(move->clone() ); auto move_ease_back = move_ease->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease, delay->clone(), move_ease_back, delay->clone(), nullptr); - + this->positionForTwo(); - - _grossini->runAction(RepeatForever::create(seq1)); - _tamara->runAction(RepeatForever::create(seq2)); + + _grossini->runAction( RepeatForever::create(seq1)); + _tamara->runAction( RepeatForever::create(seq2)); } -std::string SpriteEaseQuinticInOut::subtitle() const +std::string SpriteEaseQuinticInOut::subtitle()const { return "SpriteEaseQuinticInOut action"; } @@ -764,32 +790,33 @@ std::string SpriteEaseQuinticInOut::subtitle() const void SpriteEaseCircle::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseCircleActionIn::create(move->clone()); + + auto move_ease_in = EaseCircleActionIn::create(move->clone() ); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseCircleActionOut::create(move->clone()); + + auto move_ease_out = EaseCircleActionOut::create(move->clone() ); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - - _grossini->runAction(RepeatForever::create(seq1)); - _tamara->runAction(RepeatForever::create(seq2)); - _kathia->runAction(RepeatForever::create(seq3)); + + _grossini->runAction( RepeatForever::create(seq1)); + _tamara->runAction( RepeatForever::create(seq2)); + _kathia->runAction( RepeatForever::create(seq3)); } -std::string SpriteEaseCircle::subtitle() const +std::string SpriteEaseCircle::subtitle()const { return "SpriteEaseCircle action"; } + //------------------------------------------------------------------ // // SpriteEaseCircleInOut @@ -799,25 +826,25 @@ std::string SpriteEaseCircle::subtitle() const void SpriteEaseCircleInOut::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease = EaseCircleActionInOut::create(move->clone()); + + auto move_ease = EaseCircleActionInOut::create(move->clone() ); auto move_ease_back = move_ease->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease, delay->clone(), move_ease_back, delay->clone(), nullptr); - + this->positionForTwo(); - - _grossini->runAction(RepeatForever::create(seq1)); - _tamara->runAction(RepeatForever::create(seq2)); + + _grossini->runAction( RepeatForever::create(seq1)); + _tamara->runAction( RepeatForever::create(seq2)); } -std::string SpriteEaseCircleInOut::subtitle() const +std::string SpriteEaseCircleInOut::subtitle()const { return "SpriteEaseCircleInOut action"; } @@ -831,32 +858,33 @@ std::string SpriteEaseCircleInOut::subtitle() const void SpriteEaseCubic::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseCubicActionIn::create(move->clone()); + + auto move_ease_in = EaseCubicActionIn::create(move->clone() ); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseCubicActionOut::create(move->clone()); + + auto move_ease_out = EaseCubicActionOut::create(move->clone() ); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - - _grossini->runAction(RepeatForever::create(seq1)); - _tamara->runAction(RepeatForever::create(seq2)); - _kathia->runAction(RepeatForever::create(seq3)); + + _grossini->runAction( RepeatForever::create(seq1)); + _tamara->runAction( RepeatForever::create(seq2)); + _kathia->runAction( RepeatForever::create(seq3)); } -std::string SpriteEaseCubic::subtitle() const +std::string SpriteEaseCubic::subtitle()const { return "SpriteEaseCubic action"; } + //------------------------------------------------------------------ // // SpriteEaseCubicInOut @@ -866,25 +894,25 @@ std::string SpriteEaseCubic::subtitle() const void SpriteEaseCubicInOut::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease = EaseCubicActionInOut::create(move->clone()); + + auto move_ease = EaseCubicActionInOut::create(move->clone() ); auto move_ease_back = move_ease->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease, delay->clone(), move_ease_back, delay->clone(), nullptr); - + this->positionForTwo(); - - _grossini->runAction(RepeatForever::create(seq1)); - _tamara->runAction(RepeatForever::create(seq2)); + + _grossini->runAction( RepeatForever::create(seq1)); + _tamara->runAction( RepeatForever::create(seq2)); } -std::string SpriteEaseCubicInOut::title() const +std::string SpriteEaseCubicInOut::title()const { return "SpriteEaseCubicInOut action"; } @@ -897,43 +925,43 @@ std::string SpriteEaseCubicInOut::title() const void SpeedTest::onEnter() { EaseSpriteDemo::onEnter(); - + auto s = Director::getInstance()->getWinSize(); // rotate and jump - auto jump1 = JumpBy::create(4.0f, Vec2(-s.width + 80, 0.0f), 100.0f, 4); + auto jump1 = JumpBy::create(4.0f, Vec2(-s.width+80, 0.0f), 100.0f, 4); auto jump2 = jump1->reverse(); - auto rot1 = RotateBy::create(4.0f, 360 * 2.0f); - auto rot2 = rot1->reverse(); - + auto rot1 = RotateBy::create(4.0f, 360*2.0f); + auto rot2 = rot1->reverse(); + auto seq3_1 = Sequence::create(jump2, jump1, nullptr); - auto seq3_2 = Sequence::create(rot1, rot2, nullptr); - auto spawn = Spawn::create(seq3_1, seq3_2, nullptr); + auto seq3_2 = Sequence::create( rot1, rot2, nullptr); + auto spawn = Spawn::create(seq3_1, seq3_2, nullptr); auto action = Speed::create(RepeatForever::create(spawn), 1.0f); action->setTag(kTagAction1); - + auto action2 = action->clone(); auto action3 = action->clone(); action2->setTag(kTagAction1); action3->setTag(kTagAction1); - + _grossini->runAction(action2); _tamara->runAction(action3); _kathia->runAction(action); - - this->schedule(CC_SCHEDULE_SELECTOR(SpeedTest::altertime), 1.0f); //:@selector(altertime:) interval:1.0f]; + + this->schedule(CC_SCHEDULE_SELECTOR(SpeedTest::altertime), 1.0f);//:@selector(altertime:) interval:1.0f]; } void SpeedTest::altertime(float dt) -{ +{ auto action1 = static_cast(_grossini->getActionByTag(kTagAction1)); auto action2 = static_cast(_tamara->getActionByTag(kTagAction1)); auto action3 = static_cast(_kathia->getActionByTag(kTagAction1)); - - action1->setSpeed(CCRANDOM_MINUS1_1() * 2); - action2->setSpeed(CCRANDOM_MINUS1_1() * 2); - action3->setSpeed(CCRANDOM_MINUS1_1() * 2); + + action1->setSpeed( CCRANDOM_MINUS1_1() * 2 ); + action2->setSpeed( CCRANDOM_MINUS1_1() * 2 ); + action3->setSpeed( CCRANDOM_MINUS1_1() * 2 ); } std::string SpeedTest::subtitle() const @@ -975,7 +1003,9 @@ ActionsEaseTests::ActionsEaseTests() ADD_TEST_CASE(SpeedTest); } -EaseSpriteDemo::EaseSpriteDemo() {} +EaseSpriteDemo::EaseSpriteDemo() +{ +} EaseSpriteDemo::~EaseSpriteDemo() { @@ -985,14 +1015,13 @@ EaseSpriteDemo::~EaseSpriteDemo() } void EaseSpriteDemo::positionForTwo() -{ - _grossini->setPosition(VisibleRect::left().x + 60, - VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height * 1 / 5); - _tamara->setPosition(VisibleRect::left().x + 60, - VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height * 4 / 5); +{ + _grossini->setPosition(VisibleRect::left().x+60, VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height*1/5); + _tamara->setPosition(VisibleRect::left().x+60, VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height*4/5); _kathia->setVisible(false); } + std::string EaseSpriteDemo::subtitle() const { return "No title"; @@ -1003,21 +1032,15 @@ void EaseSpriteDemo::onEnter() TestCase::onEnter(); // Or you can create an sprite using a filename. PNG and BMP files are supported. - _grossini = Sprite::create(s_pathGrossini); - _grossini->retain(); - _tamara = Sprite::create(s_pathSister1); - _tamara->retain(); - _kathia = Sprite::create(s_pathSister2); - _kathia->retain(); + _grossini = Sprite::create(s_pathGrossini); _grossini->retain(); + _tamara = Sprite::create(s_pathSister1); _tamara->retain(); + _kathia = Sprite::create(s_pathSister2); _kathia->retain(); + + addChild( _grossini, 3); + addChild( _kathia, 2); + addChild( _tamara, 1); - addChild(_grossini, 3); - addChild(_kathia, 2); - addChild(_tamara, 1); - - _grossini->setPosition(VisibleRect::left().x + 60, - VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height * 1 / 5); - _kathia->setPosition(VisibleRect::left().x + 60, - VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height * 2.5f / 5); - _tamara->setPosition(VisibleRect::left().x + 60, - VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height * 4 / 5); + _grossini->setPosition(VisibleRect::left().x + 60, VisibleRect::bottom().y+VisibleRect::getVisibleRect().size.height*1/5); + _kathia->setPosition(VisibleRect::left().x + 60, VisibleRect::bottom().y+VisibleRect::getVisibleRect().size.height*2.5f/5); + _tamara->setPosition(VisibleRect::left().x + 60, VisibleRect::bottom().y+VisibleRect::getVisibleRect().size.height*4/5); } diff --git a/tests/cpp-tests/Classes/ActionsEaseTest/ActionsEaseTest.h b/tests/cpp-tests/Classes/ActionsEaseTest/ActionsEaseTest.h index 2676595bb0..1fe1f577f2 100644 --- a/tests/cpp-tests/Classes/ActionsEaseTest/ActionsEaseTest.h +++ b/tests/cpp-tests/Classes/ActionsEaseTest/ActionsEaseTest.h @@ -34,11 +34,11 @@ DEFINE_TEST_SUITE(ActionsEaseTests); class EaseSpriteDemo : public TestCase { protected: - cocos2d::Sprite* _grossini; - cocos2d::Sprite* _tamara; - cocos2d::Sprite* _kathia; + cocos2d::Sprite* _grossini; + cocos2d::Sprite* _tamara; + cocos2d::Sprite* _kathia; - std::string _title; + std::string _title; public: EaseSpriteDemo(); @@ -46,7 +46,7 @@ public: virtual std::string subtitle() const override; virtual void onEnter() override; - + void centerSprites(unsigned int numberOfSprites); void positionForTwo(); @@ -225,6 +225,7 @@ public: virtual std::string subtitle() const override; }; + class SpriteEaseCircle : public EaseSpriteDemo { public: @@ -271,4 +272,5 @@ public: void altertime(float dt); }; + #endif diff --git a/tests/cpp-tests/Classes/ActionsProgressTest/ActionsProgressTest.cpp b/tests/cpp-tests/Classes/ActionsProgressTest/ActionsProgressTest.cpp index 6d57077326..f1f2f2cba0 100644 --- a/tests/cpp-tests/Classes/ActionsProgressTest/ActionsProgressTest.cpp +++ b/tests/cpp-tests/Classes/ActionsProgressTest/ActionsProgressTest.cpp @@ -45,9 +45,13 @@ ActionsProgressTests::ActionsProgressTests() // SpriteDemo // //------------------------------------------------------------------ -SpriteDemo::SpriteDemo() {} +SpriteDemo::SpriteDemo() +{ +} -SpriteDemo::~SpriteDemo() {} +SpriteDemo::~SpriteDemo() +{ +} std::string SpriteDemo::title() const { @@ -58,7 +62,7 @@ void SpriteDemo::onEnter() { TestCase::onEnter(); - auto background = LayerColor::create(Color4B(255, 0, 0, 255)); + auto background = LayerColor::create(Color4B(255,0,0,255)); addChild(background, -10); } @@ -70,25 +74,25 @@ void SpriteDemo::onEnter() void SpriteProgressToRadial::onEnter() { SpriteDemo::onEnter(); - + auto s = Director::getInstance()->getWinSize(); auto to1 = Sequence::createWithTwoActions(ProgressTo::create(2, 100), ProgressTo::create(0, 0)); auto to2 = Sequence::createWithTwoActions(ProgressTo::create(2, 100), ProgressTo::create(0, 0)); auto left = ProgressTimer::create(Sprite::create(s_pathSister1)); - left->setType(ProgressTimer::Type::RADIAL); + left->setType( ProgressTimer::Type::RADIAL ); addChild(left); - left->setPosition(100, s.height / 2); - left->runAction(RepeatForever::create(to1)); - + left->setPosition(100, s.height/2); + left->runAction( RepeatForever::create(to1)); + auto right = ProgressTimer::create(Sprite::create(s_pathBlock)); right->setType(ProgressTimer::Type::RADIAL); // Makes the ridial CCW right->setReverseDirection(true); addChild(right); - right->setPosition(s.width - 100, s.height / 2); - right->runAction(RepeatForever::create(to2)); + right->setPosition(s.width-100, s.height/2); + right->runAction( RepeatForever::create(to2)); } std::string SpriteProgressToRadial::subtitle() const @@ -105,22 +109,22 @@ std::string SpriteProgressToRadial::subtitle() const void SpriteProgressToHorizontal::onEnter() { SpriteDemo::onEnter(); - + auto s = Director::getInstance()->getWinSize(); - + auto to1 = Sequence::createWithTwoActions(ProgressTo::create(2, 100), ProgressTo::create(0, 0)); auto to2 = Sequence::createWithTwoActions(ProgressTo::create(2, 100), ProgressTo::create(0, 0)); - + auto left = ProgressTimer::create(Sprite::create(s_pathSister1)); left->setType(ProgressTimer::Type::BAR); // Setup for a bar starting from the left since the midpoint is 0 for the x - left->setMidpoint(Vec2(0.0f, 0.0f)); + left->setMidpoint(Vec2(0.0f,0.0f)); // Setup for a horizontal bar since the bar change rate is 0 for y meaning no vertical change left->setBarChangeRate(Vec2(1.0f, 0.0f)); addChild(left); - left->setPosition(100, s.height / 2); - left->runAction(RepeatForever::create(to1)); - + left->setPosition(100, s.height/2); + left->runAction( RepeatForever::create(to1)); + auto right = ProgressTimer::create(Sprite::create(s_pathSister2)); right->setType(ProgressTimer::Type::BAR); // Setup for a bar starting from the left since the midpoint is 1 for the x @@ -128,8 +132,8 @@ void SpriteProgressToHorizontal::onEnter() // Setup for a horizontal bar since the bar change rate is 0 for y meaning no vertical change right->setBarChangeRate(Vec2(1.0f, 0.0f)); addChild(right); - right->setPosition(s.width - 100, s.height / 2); - right->runAction(RepeatForever::create(to2)); + right->setPosition(s.width-100, s.height/2); + right->runAction( RepeatForever::create(to2)); } std::string SpriteProgressToHorizontal::subtitle() const @@ -145,23 +149,23 @@ std::string SpriteProgressToHorizontal::subtitle() const void SpriteProgressToVertical::onEnter() { SpriteDemo::onEnter(); - + auto s = Director::getInstance()->getWinSize(); - + auto to1 = Sequence::createWithTwoActions(ProgressTo::create(2, 100), ProgressTo::create(0, 0)); auto to2 = Sequence::createWithTwoActions(ProgressTo::create(2, 100), ProgressTo::create(0, 0)); - + auto left = ProgressTimer::create(Sprite::create(s_pathSister1)); left->setType(ProgressTimer::Type::BAR); // Setup for a bar starting from the bottom since the midpoint is 0 for the y - left->setMidpoint(Vec2(0.0f, 0.0f)); + left->setMidpoint(Vec2(0.0f,0.0f)); // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change left->setBarChangeRate(Vec2(0.0f, 1.0f)); addChild(left); - left->setPosition(100, s.height / 2); - left->runAction(RepeatForever::create(to1)); - + left->setPosition(100, s.height/2); + left->runAction( RepeatForever::create(to1)); + auto right = ProgressTimer::create(Sprite::create(s_pathSister2)); right->setType(ProgressTimer::Type::BAR); // Setup for a bar starting from the bottom since the midpoint is 0 for the y @@ -169,8 +173,8 @@ void SpriteProgressToVertical::onEnter() // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change right->setBarChangeRate(Vec2(0, 1)); addChild(right); - right->setPosition(s.width - 100, s.height / 2); - right->runAction(RepeatForever::create(to2)); + right->setPosition(s.width-100, s.height/2); + right->runAction( RepeatForever::create(to2)); } std::string SpriteProgressToVertical::subtitle() const @@ -192,28 +196,28 @@ void SpriteProgressToRadialMidpointChanged::onEnter() auto action = Sequence::createWithTwoActions(ProgressTo::create(2, 100), ProgressTo::create(0, 0)); /** - * Our image on the left should be a radial progress indicator, clockwise - */ + * Our image on the left should be a radial progress indicator, clockwise + */ auto left = ProgressTimer::create(Sprite::create(s_pathBlock)); left->setType(ProgressTimer::Type::RADIAL); addChild(left); left->setMidpoint(Vec2(0.25f, 0.75f)); - left->setPosition(100, s.height / 2); + left->setPosition(100, s.height/2); left->runAction(RepeatForever::create(action->clone())); /** - * Our image on the left should be a radial progress indicator, counter clockwise - */ + * Our image on the left should be a radial progress indicator, counter clockwise + */ auto right = ProgressTimer::create(Sprite::create(s_pathBlock)); right->setType(ProgressTimer::Type::RADIAL); right->setMidpoint(Vec2(0.75f, 0.25f)); /** - * Note the reverse property (default=NO) is only added to the right image. That's how - * we get a counter clockwise progress. - */ + * Note the reverse property (default=NO) is only added to the right image. That's how + * we get a counter clockwise progress. + */ addChild(right); - right->setPosition(s.width - 100, s.height / 2); + right->setPosition(s.width-100, s.height/2); right->runAction(RepeatForever::create(action->clone())); } @@ -243,7 +247,7 @@ void SpriteProgressBarVarious::onEnter() // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change left->setBarChangeRate(Vec2(1.0f, 0.0f)); addChild(left); - left->setPosition(100, s.height / 2); + left->setPosition(100, s.height/2); left->runAction(RepeatForever::create(to->clone())); auto middle = ProgressTimer::create(Sprite::create(s_pathSister2)); @@ -251,9 +255,9 @@ void SpriteProgressBarVarious::onEnter() // Setup for a bar starting from the bottom since the midpoint is 0 for the y middle->setMidpoint(Vec2(0.5f, 0.5f)); // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change - middle->setBarChangeRate(Vec2(1, 1)); + middle->setBarChangeRate(Vec2(1,1)); addChild(middle); - middle->setPosition(s.width / 2, s.height / 2); + middle->setPosition(s.width/2, s.height/2); middle->runAction(RepeatForever::create(to->clone())); auto right = ProgressTimer::create(Sprite::create(s_pathSister2)); @@ -263,7 +267,7 @@ void SpriteProgressBarVarious::onEnter() // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change right->setBarChangeRate(Vec2(0, 1)); addChild(right); - right->setPosition(s.width - 100, s.height / 2); + right->setPosition(s.width-100, s.height/2); right->runAction(RepeatForever::create(to->clone())); } @@ -283,10 +287,14 @@ void SpriteProgressBarTintAndFade::onEnter() auto s = Director::getInstance()->getWinSize(); - auto to = Sequence::createWithTwoActions(ProgressTo::create(6, 100), ProgressTo::create(0, 0)); - auto tint = Sequence::create(TintTo::create(1, 255, 0, 0), TintTo::create(1, 0, 255, 0), - TintTo::create(1, 0, 0, 255), nullptr); - auto fade = Sequence::create(FadeTo::create(1.0f, 0), FadeTo::create(1.0f, 255), nullptr); + auto to = Sequence::createWithTwoActions(ProgressTo::create(6, 100), ProgressTo::create(0, 0)); + auto tint = Sequence::create(TintTo::create(1, 255, 0, 0), + TintTo::create(1, 0, 255, 0), + TintTo::create(1, 0, 0, 255), + nullptr); + auto fade = Sequence::create(FadeTo::create(1.0f, 0), + FadeTo::create(1.0f, 255), + nullptr); auto left = ProgressTimer::create(Sprite::create(s_pathSister1)); left->setType(ProgressTimer::Type::BAR); @@ -296,7 +304,7 @@ void SpriteProgressBarTintAndFade::onEnter() // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change left->setBarChangeRate(Vec2(1.0f, 0.0f)); addChild(left); - left->setPosition(100, s.height / 2); + left->setPosition(100, s.height/2); left->runAction(RepeatForever::create(to->clone())); left->runAction(RepeatForever::create(tint->clone())); @@ -309,7 +317,7 @@ void SpriteProgressBarTintAndFade::onEnter() // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change middle->setBarChangeRate(Vec2(1, 1)); addChild(middle); - middle->setPosition(s.width / 2, s.height / 2); + middle->setPosition(s.width/2, s.height/2); middle->runAction(RepeatForever::create(to->clone())); middle->runAction(RepeatForever::create(fade->clone())); @@ -322,9 +330,9 @@ void SpriteProgressBarTintAndFade::onEnter() // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change right->setBarChangeRate(Vec2(0, 1)); addChild(right); - right->setPosition(s.width - 100, s.height / 2); + right->setPosition(s.width-100, s.height/2); right->runAction(RepeatForever::create(to->clone())); - right->runAction(RepeatForever::create(tint->clone())); + right->runAction(RepeatForever::create(tint->clone())); right->runAction(RepeatForever::create(fade->clone())); right->addChild(Label::createWithTTF("Tint and Fade", "fonts/Marker Felt.ttf", 20.0f)); @@ -357,7 +365,7 @@ void SpriteProgressWithSpriteFrame::onEnter() // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change left->setBarChangeRate(Vec2(1.0f, 0.0f)); addChild(left); - left->setPosition(100, s.height / 2); + left->setPosition(100, s.height/2); left->runAction(RepeatForever::create(to->clone())); auto middle = ProgressTimer::create(Sprite::createWithSpriteFrameName("grossini_dance_02.png")); @@ -367,7 +375,7 @@ void SpriteProgressWithSpriteFrame::onEnter() // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change middle->setBarChangeRate(Vec2(1, 1)); addChild(middle); - middle->setPosition(s.width / 2, s.height / 2); + middle->setPosition(s.width/2, s.height/2); middle->runAction(RepeatForever::create(to->clone())); auto right = ProgressTimer::create(Sprite::createWithSpriteFrameName("grossini_dance_03.png")); @@ -377,7 +385,7 @@ void SpriteProgressWithSpriteFrame::onEnter() // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change right->setBarChangeRate(Vec2(0, 1)); addChild(right); - right->setPosition(s.width - 100, s.height / 2); + right->setPosition(s.width-100, s.height/2); right->runAction(RepeatForever::create(to->clone())); } diff --git a/tests/cpp-tests/Classes/ActionsProgressTest/ActionsProgressTest.h b/tests/cpp-tests/Classes/ActionsProgressTest/ActionsProgressTest.h index 5fffe2bb32..336fabd2f3 100644 --- a/tests/cpp-tests/Classes/ActionsProgressTest/ActionsProgressTest.h +++ b/tests/cpp-tests/Classes/ActionsProgressTest/ActionsProgressTest.h @@ -104,4 +104,4 @@ public: virtual std::string subtitle() const override; }; -#endif // _ACTIONS__PROGRESS_TEST_H_ +#endif // _ACTIONS__PROGRESS_TEST_H_ diff --git a/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp b/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp index 23f6b817cd..03a32b70be 100644 --- a/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp +++ b/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp @@ -1,28 +1,28 @@ -/**************************************************************************** -Copyright (c) 2012 cocos2d-x.org -Copyright (c) 2013-2016 Chukong Technologies Inc. -Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + /**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -http://www.cocos2d-x.org + http://www.cocos2d-x.org -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + 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 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. -****************************************************************************/ + 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 "ActionsTest.h" #include "../testResource.h" @@ -110,7 +110,7 @@ void ActionsDemo::onEnter() _grossini = Sprite::create(s_pathGrossini); _grossini->retain(); - _tamara = Sprite::create(s_pathSister1); + _tamara = Sprite::create(s_pathSister1); _tamara->retain(); _kathia = Sprite::create(s_pathSister2); @@ -120,12 +120,9 @@ void ActionsDemo::onEnter() addChild(_tamara, 2); addChild(_kathia, 3); - _grossini->setPosition(VisibleRect::center().x, - VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height / 3); - _tamara->setPosition(VisibleRect::center().x, - VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height * 2 / 3); - _kathia->setPosition(VisibleRect::center().x, - VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height / 2); + _grossini->setPosition(VisibleRect::center().x, VisibleRect::bottom().y+VisibleRect::getVisibleRect().size.height/3); + _tamara->setPosition(VisibleRect::center().x, VisibleRect::bottom().y+VisibleRect::getVisibleRect().size.height*2/3); + _kathia->setPosition(VisibleRect::center().x, VisibleRect::bottom().y+VisibleRect::getVisibleRect().size.height/2); } void ActionsDemo::onExit() @@ -141,29 +138,29 @@ void ActionsDemo::centerSprites(unsigned int numberOfSprites) { auto s = Director::getInstance()->getWinSize(); - if (numberOfSprites == 0) + if( numberOfSprites == 0 ) { _tamara->setVisible(false); _kathia->setVisible(false); _grossini->setVisible(false); - } - else if (numberOfSprites == 1) + } + else if ( numberOfSprites == 1 ) { _tamara->setVisible(false); _kathia->setVisible(false); - _grossini->setPosition(s.width / 2, s.height / 2); + _grossini->setPosition(s.width/2, s.height/2); } - else if (numberOfSprites == 2) - { - _kathia->setPosition(s.width / 3, s.height / 2); - _tamara->setPosition(2 * s.width / 3, s.height / 2); + else if( numberOfSprites == 2 ) + { + _kathia->setPosition(s.width/3, s.height/2); + _tamara->setPosition(2*s.width/3, s.height/2); _grossini->setVisible(false); - } - else if (numberOfSprites == 3) + } + else if( numberOfSprites == 3 ) { - _grossini->setPosition(s.width / 2, s.height / 2); - _tamara->setPosition(s.width / 4, s.height / 2); - _kathia->setPosition(3 * s.width / 4, s.height / 2); + _grossini->setPosition(s.width/2, s.height/2); + _tamara->setPosition(s.width/4, s.height/2); + _kathia->setPosition(3 * s.width/4, s.height/2); } } @@ -171,23 +168,23 @@ void ActionsDemo::alignSpritesLeft(unsigned int numberOfSprites) { auto s = Director::getInstance()->getWinSize(); - if (numberOfSprites == 1) + if( numberOfSprites == 1 ) { _tamara->setVisible(false); _kathia->setVisible(false); - _grossini->setPosition(60, s.height / 2); - } - else if (numberOfSprites == 2) + _grossini->setPosition(60, s.height/2); + } + else if( numberOfSprites == 2 ) + { + _kathia->setPosition(60, s.height/3); + _tamara->setPosition(60, 2*s.height/3); + _grossini->setVisible( false ); + } + else if( numberOfSprites == 3 ) { - _kathia->setPosition(60, s.height / 3); - _tamara->setPosition(60, 2 * s.height / 3); - _grossini->setVisible(false); - } - else if (numberOfSprites == 3) - { - _grossini->setPosition(60, s.height / 2); - _tamara->setPosition(60, 2 * s.height / 3); - _kathia->setPosition(60, s.height / 3); + _grossini->setPosition(60, s.height/2); + _tamara->setPosition(60, 2*s.height/3); + _kathia->setPosition(60, s.height/3); } } @@ -204,13 +201,13 @@ void ActionMove::onEnter() auto s = Director::getInstance()->getWinSize(); - auto actionTo = MoveTo::create(2, Vec2(s.width - 40, s.height - 40)); - auto actionBy = MoveBy::create(2, Vec2(80.0f, 80.0f)); + auto actionTo = MoveTo::create(2, Vec2(s.width-40, s.height-40)); + auto actionBy = MoveBy::create(2, Vec2(80.0f,80.0f)); auto actionByBack = actionBy->reverse(); - _tamara->runAction(actionTo); - _grossini->runAction(Sequence::create(actionBy, actionByBack, nullptr)); - _kathia->runAction(MoveTo::create(1, Vec2(40.0f, 40.0f))); + _tamara->runAction( actionTo); + _grossini->runAction( Sequence::create(actionBy, actionByBack, nullptr)); + _kathia->runAction(MoveTo::create(1, Vec2(40.0f,40.0f))); } std::string ActionMove::subtitle() const @@ -226,18 +223,18 @@ std::string ActionMove::subtitle() const void ActionMove3D::onEnter() { ActionsDemo::onEnter(); - + centerSprites(3); - + auto s = Director::getInstance()->getWinSize(); - - _tamara->setPosition3D(Vec3(s.width - 40, s.height - 40, 0.0f)); + + _tamara->setPosition3D(Vec3(s.width-40, s.height-40, 0.0f)); _kathia->setPosition3D(Vec3(40.0f, 40.0f, 0.0f)); - - auto actionTo = MoveTo::create(2, Vec3(s.width - 40, s.height - 40, -100.0f)); - auto actionBy = MoveBy::create(2, Vec3(80.0f, 80.0f, -100.0f)); + + auto actionTo = MoveTo::create(2, Vec3(s.width-40, s.height-40, -100.0f)); + auto actionBy = MoveBy::create(2, Vec3(80.0f, 80.0f, -100.0f)); auto actionByBack = actionBy->reverse(); - + _tamara->runAction(actionTo); _grossini->runAction(Sequence::create(actionBy, actionByBack, nullptr)); _kathia->runAction(MoveTo::create(1, Vec3(40.0f, 40.0f, -100.0f))); @@ -259,13 +256,13 @@ void ActionScale::onEnter() centerSprites(3); - auto actionTo = ScaleTo::create(2.0f, 0.5f); - auto actionBy = ScaleBy::create(2.0f, 1.0f, 10.0f); + auto actionTo = ScaleTo::create(2.0f, 0.5f); + auto actionBy = ScaleBy::create(2.0f, 1.0f, 10.0f); auto actionBy2 = ScaleBy::create(2.0f, 5.0f, 1.0f); - _grossini->runAction(actionTo); - _tamara->runAction(Sequence::create(actionBy, actionBy->reverse(), nullptr)); - _kathia->runAction(Sequence::create(actionBy2, actionBy2->reverse(), nullptr)); + _grossini->runAction( actionTo); + _tamara->runAction( Sequence::create(actionBy, actionBy->reverse(), nullptr)); + _kathia->runAction( Sequence::create(actionBy2, actionBy2->reverse(), nullptr)); } std::string ActionScale::subtitle() const @@ -284,10 +281,10 @@ void ActionSkew::onEnter() centerSprites(3); - auto actionTo = SkewTo::create(2, 37.2f, -37.2f); + auto actionTo = SkewTo::create(2, 37.2f, -37.2f); auto actionToBack = SkewTo::create(2, 0, 0); - auto actionBy = SkewBy::create(2, 0.0f, -90.0f); - auto actionBy2 = SkewBy::create(2, 45.0f, 45.0f); + auto actionBy = SkewBy::create(2, 0.0f, -90.0f); + auto actionBy2 = SkewBy::create(2, 45.0f, 45.0f); auto actionByBack = actionBy->reverse(); _tamara->runAction(Sequence::create(actionTo, actionToBack, nullptr)); @@ -308,17 +305,17 @@ void ActionRotationalSkew::onEnter() this->centerSprites(3); - auto actionTo = RotateTo::create(2, 180, 180); + auto actionTo = RotateTo::create(2, 180, 180); auto actionToBack = RotateTo::create(2, 0, 0); - auto actionBy = RotateBy::create(2, 0.0f, 360); + auto actionBy = RotateBy::create(2, 0.0f, 360); auto actionByBack = actionBy->reverse(); - auto actionBy2 = RotateBy::create(2, 360, 0); + auto actionBy2 = RotateBy::create(2, 360, 0); auto actionBy2Back = actionBy2->reverse(); - _tamara->runAction(Sequence::create(actionBy, actionByBack, nullptr)); - _grossini->runAction(Sequence::create(actionTo, actionToBack, nullptr)); - _kathia->runAction(Sequence::create(actionBy2, actionBy2Back, nullptr)); + _tamara->runAction( Sequence::create(actionBy, actionByBack, nullptr) ); + _grossini->runAction( Sequence::create(actionTo, actionToBack, nullptr) ); + _kathia->runAction( Sequence::create(actionBy2, actionBy2Back, nullptr) ); } std::string ActionRotationalSkew::subtitle() const @@ -326,7 +323,9 @@ std::string ActionRotationalSkew::subtitle() const return "RotationalSkewTo / RotationalSkewBy"; } -// ActionRotationalSkewVSStandardSkew + + +//ActionRotationalSkewVSStandardSkew void ActionRotationalSkewVSStandardSkew::onEnter() { ActionsDemo::onEnter(); @@ -339,33 +338,33 @@ void ActionRotationalSkewVSStandardSkew::onEnter() Size boxSize(100.0f, 100.0f); - auto box = LayerColor::create(Color4B(255, 255, 0, 255)); - box->setAnchorPoint(Vec2(0.5f, 0.5f)); - box->setContentSize(boxSize); + auto box = LayerColor::create(Color4B(255,255,0,255)); + box->setAnchorPoint(Vec2(0.5f,0.5f)); + box->setContentSize( boxSize ); box->setIgnoreAnchorPointForPosition(false); - box->setPosition(s.width / 2, s.height - 100 - box->getContentSize().height / 2); + box->setPosition(s.width/2, s.height - 100 - box->getContentSize().height/2); this->addChild(box); auto label = Label::createWithTTF("Standard cocos2d Skew", "fonts/Marker Felt.ttf", 16.0f); - label->setPosition(s.width / 2, s.height - 100 + label->getContentSize().height); + label->setPosition(s.width/2, s.height - 100 + label->getContentSize().height); this->addChild(label); - auto actionTo = SkewBy::create(2, 360, 0); + auto actionTo = SkewBy::create(2, 360, 0); auto actionToBack = SkewBy::create(2, -360, 0); box->runAction(Sequence::create(actionTo, actionToBack, nullptr)); - box = LayerColor::create(Color4B(255, 255, 0, 255)); - box->setAnchorPoint(Vec2(0.5f, 0.5f)); + box = LayerColor::create(Color4B(255,255,0,255)); + box->setAnchorPoint(Vec2(0.5f,0.5f)); box->setContentSize(boxSize); box->setIgnoreAnchorPointForPosition(false); - box->setPosition(s.width / 2, s.height - 250 - box->getContentSize().height / 2); + box->setPosition(s.width/2, s.height - 250 - box->getContentSize().height/2); this->addChild(box); label = Label::createWithTTF("Rotational Skew", "fonts/Marker Felt.ttf", 16.0f); - label->setPosition(s.width / 2, s.height - 250 + label->getContentSize().height / 2); + label->setPosition(s.width/2, s.height - 250 + label->getContentSize().height/2); this->addChild(label); - auto actionTo2 = RotateBy::create(2, 360, 0); + auto actionTo2 = RotateBy::create(2, 360, 0); auto actionToBack2 = RotateBy::create(2, -360, 0); box->runAction(Sequence::create(actionTo2, actionToBack2, nullptr)); } @@ -391,7 +390,7 @@ void ActionSkewRotateScale::onEnter() box->setContentSize(boxSize); static float markrside = 10.0f; - auto uL = LayerColor::create(Color4B(255, 0, 0, 255)); + auto uL = LayerColor::create(Color4B(255, 0, 0, 255)); box->addChild(uL); uL->setContentSize(Size(markrside, markrside)); uL->setPosition(0.f, boxSize.height - markrside); @@ -404,13 +403,13 @@ void ActionSkewRotateScale::onEnter() uR->setAnchorPoint(Vec2(0.0f, 0.0f)); addChild(box); - auto actionTo = SkewTo::create(2, 0.f, 2.f); - auto rotateTo = RotateTo::create(2, 61.0f); + auto actionTo = SkewTo::create(2, 0.f, 2.f); + auto rotateTo = RotateTo::create(2, 61.0f); auto actionScaleTo = ScaleTo::create(2, -0.44f, 0.47f); auto actionScaleToBack = ScaleTo::create(2, 1.0f, 1.0f); - auto rotateToBack = RotateTo::create(2, 0); - auto actionToBack = SkewTo::create(2, 0, 0); + auto rotateToBack = RotateTo::create(2, 0); + auto actionToBack = SkewTo::create(2, 0, 0); box->runAction(Sequence::create(actionTo, actionToBack, nullptr)); box->runAction(Sequence::create(rotateTo, rotateToBack, nullptr)); @@ -433,16 +432,16 @@ void ActionRotate::onEnter() centerSprites(3); - auto actionTo = RotateTo::create(2, 45); - auto actionTo2 = RotateTo::create(2, -45); - auto actionTo0 = RotateTo::create(2, 0); - _tamara->runAction(Sequence::create(actionTo, actionTo0, nullptr)); + auto actionTo = RotateTo::create( 2, 45); + auto actionTo2 = RotateTo::create( 2, -45); + auto actionTo0 = RotateTo::create(2 , 0); + _tamara->runAction( Sequence::create(actionTo, actionTo0, nullptr)); - auto actionBy = RotateBy::create(2, 360); + auto actionBy = RotateBy::create(2 , 360); auto actionByBack = actionBy->reverse(); - _grossini->runAction(Sequence::create(actionBy, actionByBack, nullptr)); + _grossini->runAction( Sequence::create(actionBy, actionByBack, nullptr)); - _kathia->runAction(Sequence::create(actionTo2, actionTo0->clone(), nullptr)); + _kathia->runAction( Sequence::create(actionTo2, actionTo0->clone(), nullptr)); } std::string ActionRotate::subtitle() const @@ -463,11 +462,11 @@ void ActionRotateBy3D::onEnter() auto actionBy1 = RotateBy::create(4, Vec3(360.0f, 0.0f, 0.0f)); auto actionBy2 = RotateBy::create(4, Vec3(0.0f, 360.0f, 0.0f)); - auto actionBy3 = RotateBy::create(4, Vec3(0.0f, 0.0f, 360.0f)); + auto actionBy3 = RotateBy::create(4 ,Vec3(0.0f, 0.0f, 360.0f)); - _tamara->runAction(Sequence::create(actionBy1, actionBy1->reverse(), nullptr)); - _grossini->runAction(Sequence::create(actionBy2, actionBy2->reverse(), nullptr)); - _kathia->runAction(Sequence::create(actionBy3, actionBy3->reverse(), nullptr)); + _tamara->runAction( Sequence::create(actionBy1, actionBy1->reverse(), nullptr)); + _grossini->runAction( Sequence::create(actionBy2, actionBy2->reverse(), nullptr)); + _kathia->runAction( Sequence::create(actionBy3, actionBy3->reverse(), nullptr)); } std::string ActionRotateBy3D::subtitle() const @@ -486,14 +485,14 @@ void ActionJump::onEnter() centerSprites(3); - auto actionTo = JumpTo::create(2, Vec2(300, 300), 50, 4); - auto actionBy = JumpBy::create(2, Vec2(300, 0), 50, 4); - auto actionUp = JumpBy::create(2, Vec2(0, 0), 80, 4); + auto actionTo = JumpTo::create(2, Vec2(300,300), 50, 4); + auto actionBy = JumpBy::create(2, Vec2(300,0), 50, 4); + auto actionUp = JumpBy::create(2, Vec2(0,0), 80, 4); auto actionByBack = actionBy->reverse(); - _tamara->runAction(actionTo); - _grossini->runAction(Sequence::create(actionBy, actionByBack, nullptr)); - _kathia->runAction(RepeatForever::create(actionUp)); + _tamara->runAction( actionTo); + _grossini->runAction( Sequence::create(actionBy, actionByBack, nullptr)); + _kathia->runAction( RepeatForever::create(actionUp)); } std::string ActionJump::subtitle() const { @@ -520,30 +519,32 @@ void ActionBezier::onEnter() // sprite 1 ccBezierConfig bezier; - bezier.controlPoint_1 = Vec2(0.0f, s.height / 2); - bezier.controlPoint_2 = Vec2(300.0f, -s.height / 2); - bezier.endPosition = Vec2(300.0f, 100.0f); + bezier.controlPoint_1 = Vec2(0.0f, s.height/2); + bezier.controlPoint_2 = Vec2(300.0f, -s.height/2); + bezier.endPosition = Vec2(300.0f,100.0f); auto bezierForward = BezierBy::create(3, bezier); - auto bezierBack = bezierForward->reverse(); - auto rep = RepeatForever::create(Sequence::create(bezierForward, bezierBack, nullptr)); + auto bezierBack = bezierForward->reverse(); + auto rep = RepeatForever::create(Sequence::create( bezierForward, bezierBack, nullptr)); + // sprite 2 - _tamara->setPosition(80, 160); - ccBezierConfig bezier2; - bezier2.controlPoint_1 = Vec2(100.0f, s.height / 2); - bezier2.controlPoint_2 = Vec2(200.0f, -s.height / 2); - bezier2.endPosition = Vec2(240.0f, 160.0f); + _tamara->setPosition(80,160); + ccBezierConfig bezier2; + bezier2.controlPoint_1 = Vec2(100.0f, s.height/2); + bezier2.controlPoint_2 = Vec2(200.0f, -s.height/2); + bezier2.endPosition = Vec2(240.0f,160.0f); - auto bezierTo1 = BezierTo::create(2, bezier2); + auto bezierTo1 = BezierTo::create(2, bezier2); // sprite 3 - _kathia->setPosition(400, 160); + _kathia->setPosition(400,160); auto bezierTo2 = BezierTo::create(2, bezier2); - _grossini->runAction(rep); + _grossini->runAction( rep); _tamara->runAction(bezierTo1); _kathia->runAction(bezierTo2); + } std::string ActionBezier::subtitle() const @@ -565,11 +566,11 @@ void ActionBlink::onEnter() auto action1 = Blink::create(2, 10); auto action2 = Blink::create(2, 5); - _tamara->runAction(action1); + _tamara->runAction( action1); _kathia->runAction(action2); } -std::string ActionBlink::subtitle() const +std::string ActionBlink::subtitle() const { return "Blink"; } @@ -585,22 +586,22 @@ void ActionFade::onEnter() centerSprites(2); - _tamara->setOpacity(0); - auto action1 = FadeIn::create(1.0f); + _tamara->setOpacity( 0 ); + auto action1 = FadeIn::create(1.0f); auto action1Back = action1->reverse(); - auto action2 = FadeOut::create(1.0f); - auto action2Back = action2->reverse(); - auto action2BackReverse = action2Back->reverse(); + auto action2 = FadeOut::create(1.0f); + auto action2Back = action2->reverse(); + auto action2BackReverse = action2Back->reverse(); auto action2BackReverseReverse = action2BackReverse->reverse(); _tamara->setOpacity(122); - _tamara->runAction(Sequence::create(action1, action1Back, nullptr)); + _tamara->runAction( Sequence::create( action1, action1Back, nullptr)); _kathia->setOpacity(122); - _kathia->runAction(Sequence::create(action2, action2Back, action2BackReverse, action2BackReverseReverse, nullptr)); + _kathia->runAction( Sequence::create( action2, action2Back,action2BackReverse,action2BackReverseReverse, nullptr)); } -std::string ActionFade::subtitle() const +std::string ActionFade::subtitle() const { return "FadeIn / FadeOut"; } @@ -617,15 +618,15 @@ void ActionTint::onEnter() centerSprites(2); - auto action1 = TintTo::create(2, 255, 0, 255); - auto action2 = TintBy::create(2, -127, -255, -127); + auto action1 = TintTo::create(2, 255, 0, 255); + auto action2 = TintBy::create(2, -127, -255, -127); auto action2Back = action2->reverse(); - _tamara->runAction(action1); - _kathia->runAction(Sequence::create(action2, action2Back, nullptr)); + _tamara->runAction( action1); + _kathia->runAction( Sequence::create( action2, action2Back, nullptr)); } -std::string ActionTint::subtitle() const +std::string ActionTint::subtitle() const { return "TintTo / TintBy"; } @@ -645,7 +646,7 @@ void ActionAnimate::onEnter() // Manual animation // auto animation = Animation::create(); - for (int i = 1; i < 15; i++) + for( int i=1;i<15;i++) { char szName[100] = {0}; sprintf(szName, "Images/grossini_dance_%02d.png", i); @@ -657,7 +658,7 @@ void ActionAnimate::onEnter() auto action = Animate::create(animation); _grossini->runAction(Sequence::create(action, action->reverse(), nullptr)); - + // // File animation // @@ -669,10 +670,10 @@ void ActionAnimate::onEnter() auto action2 = Animate::create(animation2); _tamara->runAction(Sequence::create(action2, action2->reverse(), nullptr)); - _frameDisplayedListener = EventListenerCustom::create(AnimationFrameDisplayedNotification, [](EventCustom* event) { + _frameDisplayedListener = EventListenerCustom::create(AnimationFrameDisplayedNotification, [](EventCustom * event){ auto userData = static_cast(event->getUserData()); - - log("target %p with data %s", userData->target, Value(userData->userInfo).getDescription().c_str()); + + log("target %p with data %s", userData->target, Value(userData->userInfo).getDescription().c_str()); }); _eventDispatcher->addEventListenerWithFixedPriority(_frameDisplayedListener, -1); @@ -684,6 +685,7 @@ void ActionAnimate::onEnter() auto animation3 = animation2->clone(); animation3->setLoops(4); + auto action3 = Animate::create(animation3); _kathia->runAction(action3); } @@ -715,7 +717,10 @@ void ActionSequence::onEnter() alignSpritesLeft(1); - auto action = Sequence::create(MoveBy::create(2, Vec2(240.0f, 0.0f)), RotateBy::create(2, 540), nullptr); + auto action = Sequence::create( + MoveBy::create( 2, Vec2(240.0f,0.0f)), + RotateBy::create( 2, 540), + nullptr); _grossini->runAction(action); } @@ -739,37 +744,40 @@ void ActionSequence2::onEnter() _grossini->setVisible(false); auto action = Sequence::create( - Place::create(Vec2(200.0f, 200.0f)), Show::create(), MoveBy::create(1, Vec2(100.0f, 0.0f)), - CallFunc::create(CC_CALLBACK_0(ActionSequence2::callback1, this)), - CallFunc::create(CC_CALLBACK_0(ActionSequence2::callback2, this, _grossini)), - CallFunc::create(CC_CALLBACK_0(ActionSequence2::callback3, this, _grossini, 0xbebabeba)), nullptr); + Place::create(Vec2(200.0f,200.0f)), + Show::create(), + MoveBy::create(1, Vec2(100.0f,0.0f)), + CallFunc::create( CC_CALLBACK_0(ActionSequence2::callback1,this)), + CallFunc::create( CC_CALLBACK_0(ActionSequence2::callback2,this,_grossini)), + CallFunc::create( CC_CALLBACK_0(ActionSequence2::callback3,this,_grossini,0xbebabeba)), + nullptr); _grossini->runAction(action); } void ActionSequence2::callback1() { - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto label = Label::createWithTTF("callback 1 called", "fonts/Marker Felt.ttf", 16.0f); - label->setPosition(s.width / 4 * 1, s.height / 2); + label->setPosition(s.width/4*1,s.height/2); addChild(label); } void ActionSequence2::callback2(Node* sender) { - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto label = Label::createWithTTF("callback 2 called", "fonts/Marker Felt.ttf", 16.0f); - label->setPosition(s.width / 4 * 2, s.height / 2); + label->setPosition(s.width/4*2,s.height/2); addChild(label); } void ActionSequence2::callback3(Node* sender, int32_t data) { - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto label = Label::createWithTTF("callback 3 called", "fonts/Marker Felt.ttf", 16.0f); - label->setPosition(s.width / 4 * 3, s.height / 2); + label->setPosition(s.width/4*3,s.height/2); addChild(label); } @@ -791,7 +799,7 @@ void ActionSequence3::onEnter() alignSpritesLeft(1); // Uses Array API - auto action1 = MoveBy::create(2, Vec2(240.0f, 0.0f)); + auto action1 = MoveBy::create(2, Vec2(240.0f,0.0f)); auto action2 = RotateBy::create(2, 540); auto action3 = action1->reverse(); auto action4 = action2->reverse(); @@ -821,8 +829,10 @@ void ActionCallFuncN::onEnter() centerSprites(1); - auto action = Sequence::create(MoveBy::create(2.0f, Vec2(150.0f, 0.0f)), - CallFuncN::create(CC_CALLBACK_1(ActionCallFuncN::callback, this)), nullptr); + auto action = Sequence::create( + MoveBy::create(2.0f, Vec2(150.0f,0.0f)), + CallFuncN::create( CC_CALLBACK_1(ActionCallFuncN::callback, this)), + nullptr); _grossini->runAction(action); } @@ -837,9 +847,9 @@ std::string ActionCallFuncN::subtitle() const return "Grossini should jump after moving"; } -void ActionCallFuncN::callback(Node* sender) +void ActionCallFuncN::callback(Node* sender ) { - auto a = JumpBy::create(5, Vec2(0, 0), 100, 5); + auto a = JumpBy::create(5, Vec2(0,0), 100, 5); sender->runAction(a); } //------------------------------------------------------------------ @@ -855,8 +865,9 @@ void ActionCallFuncND::onEnter() centerSprites(1); auto action = Sequence::create( - MoveBy::create(2.0f, Vec2(200.0f, 0.0f)), - CallFuncN::create(CC_CALLBACK_1(ActionCallFuncND::doRemoveFromParentAndCleanup, this, true)), nullptr); + MoveBy::create(2.0f, Vec2(200.0f,0.0f)), + CallFuncN::create( CC_CALLBACK_1(ActionCallFuncND::doRemoveFromParentAndCleanup, this, true)), + nullptr); _grossini->runAction(action); } @@ -887,59 +898,66 @@ void ActionCallFunction::onEnter() centerSprites(3); - auto action1 = Sequence::create( - MoveBy::create(2, Vec2(200.0f, 0.0f)), CallFunc::create(std::bind(&ActionCallFunction::callback1, this)), - CallFunc::create( - // lambda - [&]() { - auto s = Director::getInstance()->getWinSize(); - auto label = Label::createWithTTF("called:lambda callback", "fonts/Marker Felt.ttf", 16.0f); - label->setPosition(s.width / 4 * 1, s.height / 2 - 40); - this->addChild(label); - }), - nullptr); - auto action2 = - Sequence::create(ScaleBy::create(2, 2), FadeOut::create(2), - CallFunc::create(std::bind(&ActionCallFunction::callback2, this, _tamara)), nullptr); + auto action1 = Sequence::create( + MoveBy::create(2, Vec2(200.0f,0.0f)), + CallFunc::create( std::bind(&ActionCallFunction::callback1, this) ), + CallFunc::create( + // lambda + [&](){ + auto s = Director::getInstance()->getWinSize(); + auto label = Label::createWithTTF("called:lambda callback", "fonts/Marker Felt.ttf", 16.0f); + label->setPosition(s.width/4*1,s.height/2-40); + this->addChild(label); + } ), + nullptr); - auto action3 = - Sequence::create(RotateBy::create(3, 360), FadeOut::create(2), - CallFunc::create(std::bind(&ActionCallFunction::callback3, this, _kathia, 42)), nullptr); + auto action2 = Sequence::create( + ScaleBy::create(2 , 2), + FadeOut::create(2), + CallFunc::create( std::bind(&ActionCallFunction::callback2, this, _tamara) ), + nullptr); + + auto action3 = Sequence::create( + RotateBy::create(3 , 360), + FadeOut::create(2), + CallFunc::create( std::bind(&ActionCallFunction::callback3, this, _kathia, 42) ), + nullptr); _grossini->runAction(action1); _tamara->runAction(action2); _kathia->runAction(action3); } + void ActionCallFunction::callback1() { - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto label = Label::createWithTTF("callback 1 called", "fonts/Marker Felt.ttf", 16.0f); - label->setPosition(s.width / 4 * 1, s.height / 2); + label->setPosition(s.width/4*1,s.height/2); addChild(label); } void ActionCallFunction::callback2(Node* sender) { - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto label = Label::createWithTTF("callback 2 called", "fonts/Marker Felt.ttf", 16.0f); - label->setPosition(s.width / 4 * 2, s.height / 2); + label->setPosition(s.width/4*2,s.height/2); addChild(label); - CCLOG("sender is: %p", sender); + CCLOG("sender is: %p", sender); } void ActionCallFunction::callback3(Node* sender, int32_t data) { - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto label = Label::createWithTTF("callback 3 called", "fonts/Marker Felt.ttf", 16.0f); - label->setPosition(s.width / 4 * 3, s.height / 2); + label->setPosition(s.width/4*3,s.height/2); addChild(label); - CCLOG("target is: %p, data is: %d", sender, data); + CCLOG("target is: %p, data is: %d", sender, data); } std::string ActionCallFunction::subtitle() const @@ -958,7 +976,10 @@ void ActionSpawn::onEnter() alignSpritesLeft(1); - auto action = Spawn::create(JumpBy::create(2, Vec2(300, 0), 50, 4), RotateBy::create(2, 720), nullptr); + auto action = Spawn::create( + JumpBy::create(2, Vec2(300,0), 50, 4), + RotateBy::create( 2, 720), + nullptr); _grossini->runAction(action); } @@ -980,8 +1001,8 @@ void ActionSpawn2::onEnter() alignSpritesLeft(1); - auto action1 = JumpBy::create(2, Vec2(300, 0), 50, 4); - auto action2 = RotateBy::create(2, 720); + auto action1 = JumpBy::create(2, Vec2(300,0), 50, 4); + auto action2 = RotateBy::create( 2, 720); Vector array; array.pushBack(action1); @@ -1007,16 +1028,17 @@ void ActionRepeatForever::onEnter() centerSprites(1); - auto action = - Sequence::create(DelayTime::create(1), - CallFunc::create(std::bind(&ActionRepeatForever::repeatForever, this, _grossini)), nullptr); + auto action = Sequence::create( + DelayTime::create(1), + CallFunc::create( std::bind( &ActionRepeatForever::repeatForever, this, _grossini) ), + nullptr); _grossini->runAction(action); } void ActionRepeatForever::repeatForever(Node* sender) { - auto repeat = RepeatForever::create(RotateBy::create(1.0f, 360)); + auto repeat = RepeatForever::create( RotateBy::create(1.0f, 360) ); sender->runAction(repeat); } @@ -1026,6 +1048,7 @@ std::string ActionRepeatForever::subtitle() const return "CallFuncN + RepeatForever"; } + //------------------------------------------------------------------ // // ActionRotateToRepeat @@ -1037,11 +1060,11 @@ void ActionRotateToRepeat::onEnter() centerSprites(2); - auto act1 = RotateTo::create(1, 90); - auto act2 = RotateTo::create(1, 0); - auto seq = Sequence::create(act1, act2, nullptr); - auto rep1 = RepeatForever::create(seq); - auto rep2 = Repeat::create(seq->clone(), 10); + auto act1 = RotateTo::create(1, 90); + auto act2 = RotateTo::create(1, 0); + auto seq = Sequence::create(act1, act2, nullptr); + auto rep1 = RepeatForever::create(seq); + auto rep2 = Repeat::create( seq->clone(), 10); _tamara->runAction(rep1); _kathia->runAction(rep2); @@ -1063,8 +1086,8 @@ void ActionReverse::onEnter() alignSpritesLeft(1); - auto jump = JumpBy::create(2, Vec2(300, 0), 50, 4); - auto action = Sequence::create(jump, jump->reverse(), nullptr); + auto jump = JumpBy::create(2, Vec2(300,0), 50, 4); + auto action = Sequence::create( jump, jump->reverse(), nullptr); _grossini->runAction(action); } @@ -1074,6 +1097,7 @@ std::string ActionReverse::subtitle() const return "Reverse an action"; } + //------------------------------------------------------------------ // // ActionDelayTime @@ -1085,8 +1109,8 @@ void ActionDelayTime::onEnter() alignSpritesLeft(1); - auto move = MoveBy::create(1, Vec2(150.0f, 0.0f)); - auto action = Sequence::create(move, DelayTime::create(2), move, nullptr); + auto move = MoveBy::create(1, Vec2(150.0f,0.0f)); + auto action = Sequence::create( move, DelayTime::create(2), move, nullptr); _grossini->runAction(action); } @@ -1096,6 +1120,7 @@ std::string ActionDelayTime::subtitle() const return "DelayTime: m + delay + m"; } + //------------------------------------------------------------------ // // ActionReverseSequence @@ -1107,10 +1132,10 @@ void ActionReverseSequence::onEnter() alignSpritesLeft(1); - auto move1 = MoveBy::create(1, Vec2(250.0f, 0.0f)); - auto move2 = MoveBy::create(1, Vec2(0.0f, 50.0f)); - auto seq = Sequence::create(move1, move2, move1->reverse(), nullptr); - auto action = Sequence::create(seq, seq->reverse(), nullptr); + auto move1 = MoveBy::create(1, Vec2(250.0f,0.0f)); + auto move2 = MoveBy::create(1, Vec2(0.0f,50.0f)); + auto seq = Sequence::create( move1, move2, move1->reverse(), nullptr); + auto action = Sequence::create( seq, seq->reverse(), nullptr); _grossini->runAction(action); } @@ -1120,6 +1145,7 @@ std::string ActionReverseSequence::subtitle() const return "Reverse a sequence"; } + //------------------------------------------------------------------ // // ActionReverseSequence2 @@ -1131,25 +1157,27 @@ void ActionReverseSequence2::onEnter() alignSpritesLeft(2); + // Test: // Sequence should work both with IntervalAction and InstantActions - auto move1 = MoveBy::create(1, Vec2(250.0f, 0.0f)); - auto move2 = MoveBy::create(1, Vec2(0.0f, 50.0f)); - auto tog1 = ToggleVisibility::create(); - auto tog2 = ToggleVisibility::create(); - auto seq = Sequence::create(move1, tog1, move2, tog2, move1->reverse(), nullptr); - auto action = Repeat::create(Sequence::create(seq, seq->reverse(), nullptr), 3); + auto move1 = MoveBy::create(1, Vec2(250.0f,0.0f)); + auto move2 = MoveBy::create(1, Vec2(0.0f,50.0f)); + auto tog1 = ToggleVisibility::create(); + auto tog2 = ToggleVisibility::create(); + auto seq = Sequence::create( move1, tog1, move2, tog2, move1->reverse(), nullptr); + auto action = Repeat::create(Sequence::create( seq, seq->reverse(), nullptr), 3); + // Test: // Also test that the reverse of Hide is Show, and vice-versa _kathia->runAction(action); - auto move_tamara = MoveBy::create(1, Vec2(100.0f, 0.0f)); - auto move_tamara2 = MoveBy::create(1, Vec2(50.0f, 0.0f)); - auto hide = Hide::create(); - auto seq_tamara = Sequence::create(move_tamara, hide, move_tamara2, nullptr); - auto seq_back = seq_tamara->reverse(); - _tamara->runAction(Sequence::create(seq_tamara, seq_back, nullptr)); + auto move_tamara = MoveBy::create(1, Vec2(100.0f,0.0f)); + auto move_tamara2 = MoveBy::create(1, Vec2(50.0f,0.0f)); + auto hide = Hide::create(); + auto seq_tamara = Sequence::create( move_tamara, hide, move_tamara2, nullptr); + auto seq_back = seq_tamara->reverse(); + _tamara->runAction( Sequence::create( seq_tamara, seq_back, nullptr)); } std::string ActionReverseSequence2::subtitle() const { @@ -1167,9 +1195,14 @@ void ActionRepeat::onEnter() alignSpritesLeft(2); - auto a1 = MoveBy::create(1, Vec2(150.0f, 0.0f)); - auto action1 = Repeat::create(Sequence::create(Place::create(Vec2(60.0f, 60.0f)), a1, nullptr), 3); - auto action2 = RepeatForever::create(Sequence::create(a1->clone(), a1->reverse(), nullptr)); + + auto a1 = MoveBy::create(1, Vec2(150.0f,0.0f)); + auto action1 = Repeat::create( + Sequence::create( Place::create(Vec2(60.0f,60.0f)), a1, nullptr) , + 3); + auto action2 = RepeatForever::create( + Sequence::create(a1->clone(), a1->reverse(), nullptr) + ); _kathia->runAction(action1); _tamara->runAction(action2); @@ -1192,32 +1225,41 @@ void ActionOrbit::onEnter() Director::getInstance()->setProjection(Director::Projection::_2D); centerSprites(3); - auto orbit1 = OrbitCamera::create(2, 1, 0, 0, 180, 0, 0); - auto action1 = Sequence::create(orbit1, orbit1->reverse(), nullptr); + auto orbit1 = OrbitCamera::create(2,1, 0, 0, 180, 0, 0); + auto action1 = Sequence::create( + orbit1, + orbit1->reverse(), + nullptr); - auto orbit2 = OrbitCamera::create(2, 1, 0, 0, 180, -45, 0); - auto action2 = Sequence::create(orbit2, orbit2->reverse(), nullptr); + auto orbit2 = OrbitCamera::create(2,1, 0, 0, 180, -45, 0); + auto action2 = Sequence::create( + orbit2, + orbit2->reverse(), + nullptr); - auto orbit3 = OrbitCamera::create(2, 1, 0, 0, 180, 90, 0); - auto action3 = Sequence::create(orbit3, orbit3->reverse(), nullptr); + auto orbit3 = OrbitCamera::create(2,1, 0, 0, 180, 90, 0); + auto action3 = Sequence::create( + orbit3, + orbit3->reverse(), + nullptr); _kathia->runAction(RepeatForever::create(action1)); _tamara->runAction(RepeatForever::create(action2)); _grossini->runAction(RepeatForever::create(action3)); - auto move = MoveBy::create(3, Vec2(100.0f, -100.0f)); + auto move = MoveBy::create(3, Vec2(100.0f,-100.0f)); auto move_back = move->reverse(); - auto seq = Sequence::create(move, move_back, nullptr); - auto rfe = RepeatForever::create(seq); + auto seq = Sequence::create(move, move_back, nullptr); + auto rfe = RepeatForever::create(seq); _kathia->runAction(rfe); - _tamara->runAction(rfe->clone()); - _grossini->runAction(rfe->clone()); + _tamara->runAction(rfe->clone() ); + _grossini->runAction( rfe->clone() ); } void ActionOrbit::onExit() { ActionsDemo::onExit(); - + Director::getInstance()->setProjection(Director::Projection::DEFAULT); } @@ -1239,19 +1281,19 @@ void ActionFollow::onEnter() auto s = Director::getInstance()->getWinSize(); DrawNode* drawNode = DrawNode::create(); - float x = s.width * 2 - 100; - float y = s.height; - - Vec2 vertices[] = {Vec2(5.0f, 5.0f), Vec2(x - 5, 5.0f), Vec2(x - 5, y - 5), Vec2(5.0f, y - 5)}; - drawNode->drawPoly(vertices, 4, true, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); - + float x = s.width*2 - 100; + float y = s.height; + + Vec2 vertices[] = { Vec2(5.0f,5.0f), Vec2(x-5,5.0f), Vec2(x-5,y-5), Vec2(5.0f,y-5) }; + drawNode->drawPoly(vertices, 4, true, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); + this->addChild(drawNode); _grossini->setPosition(-200.0f, s.height / 2); - auto move = MoveBy::create(2, Vec2(s.width * 3, 0.0f)); + auto move = MoveBy::create(2, Vec2(s.width * 3, 0.0f)); auto move_back = move->reverse(); - auto seq = Sequence::create(move, move_back, nullptr); - auto rep = RepeatForever::create(seq); + auto seq = Sequence::create(move, move_back, nullptr); + auto rep = RepeatForever::create(seq); _grossini->runAction(rep); @@ -1271,32 +1313,31 @@ std::string ActionFollow::subtitle() const void ActionFollowWithOffset::onEnter() { ActionsDemo::onEnter(); - + centerSprites(1); auto s = Director::getInstance()->getWinSize(); - + DrawNode* drawNode = DrawNode::create(); - float x = s.width * 2 - 100; - float y = s.height; - - Vec2 vertices[] = {Vec2(5.0f, 5.0f), Vec2(x - 5, 5.0f), Vec2(x - 5, y - 5), Vec2(5.0f, y - 5)}; - drawNode->drawPoly(vertices, 4, true, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); - + float x = s.width*2 - 100; + float y = s.height; + + Vec2 vertices[] = { Vec2(5.0f,5.0f), Vec2(x-5,5.0f), Vec2(x-5,y-5), Vec2(5.0f,y-5) }; + drawNode->drawPoly(vertices, 4, true, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); + this->addChild(drawNode); - + _grossini->setPosition(-200, s.height / 2); - auto move = MoveBy::create(2, Vec2(s.width * 3, 1.0f)); + auto move = MoveBy::create(2, Vec2(s.width * 3, 1.0f)); auto move_back = move->reverse(); - auto seq = Sequence::create(move, move_back, nullptr); - auto rep = RepeatForever::create(seq); - + auto seq = Sequence::create(move, move_back, nullptr); + auto rep = RepeatForever::create(seq); + _grossini->runAction(rep); - - // sample offset values set - float verticalOffset = -900; + + //sample offset values set + float verticalOffset = -900; float horizontalOffset = 200; - this->runAction(Follow::createWithOffset(_grossini, horizontalOffset, verticalOffset, - Rect(0.0f, 0.0f, s.width * 2 - 100, s.height))); + this->runAction(Follow::createWithOffset(_grossini, horizontalOffset,verticalOffset,Rect(0.0f, 0.0f, s.width * 2 - 100, s.height))); } std::string ActionFollowWithOffset::subtitle() const @@ -1304,20 +1345,22 @@ std::string ActionFollowWithOffset::subtitle() const return "Follow action with horizontal and vertical offset"; } + void ActionTargeted::onEnter() { ActionsDemo::onEnter(); centerSprites(2); - auto jump1 = JumpBy::create(2, Vec2::ZERO, 100, 3); + + auto jump1 = JumpBy::create(2,Vec2::ZERO,100,3); auto jump2 = jump1->clone(); - auto rot1 = RotateBy::create(1, 360); - auto rot2 = rot1->clone(); + auto rot1 = RotateBy::create(1, 360); + auto rot2 = rot1->clone(); auto t1 = TargetedAction::create(_kathia, jump2); auto t2 = TargetedAction::create(_kathia, rot2); - auto seq = Sequence::create(jump1, t1, rot1, t2, nullptr); + auto seq = Sequence::create(jump1, t1, rot1, t2, nullptr); auto always = RepeatForever::create(seq); _tamara->runAction(always); @@ -1333,22 +1376,24 @@ std::string ActionTargeted::subtitle() const return "Action that runs on another target. Useful for sequences"; } + void ActionTargetedReverse::onEnter() { ActionsDemo::onEnter(); centerSprites(2); - - auto jump1 = JumpBy::create(2, Vec2::ZERO, 100, 3); + + + auto jump1 = JumpBy::create(2,Vec2::ZERO,100,3); auto jump2 = jump1->clone(); - auto rot1 = RotateBy::create(1, 360); - auto rot2 = rot1->clone(); - + auto rot1 = RotateBy::create(1, 360); + auto rot2 = rot1->clone(); + auto t1 = TargetedAction::create(_kathia, jump2); auto t2 = TargetedAction::create(_kathia, rot2); - - auto seq = Sequence::create(jump1, t1->reverse(), rot1, t2->reverse(), nullptr); + + auto seq = Sequence::create(jump1, t1->reverse(), rot1, t2->reverse(), nullptr); auto always = RepeatForever::create(seq); - + _tamara->runAction(always); } @@ -1367,15 +1412,15 @@ std::string ActionTargetedReverse::subtitle() const void ActionStacked::onEnter() { ActionsDemo::onEnter(); - + this->centerSprites(0); - - auto listener = EventListenerTouchAllAtOnce::create(); + + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesEnded = CC_CALLBACK_2(ActionStacked::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - + auto s = Director::getInstance()->getWinSize(); - this->addNewSpriteWithCoords(Vec2(s.width / 2, s.height / 2)); + this->addNewSpriteWithCoords(Vec2(s.width/2, s.height/2)); } void ActionStacked::addNewSpriteWithCoords(Vec2 p) @@ -1383,28 +1428,27 @@ void ActionStacked::addNewSpriteWithCoords(Vec2 p) int idx = static_cast(CCRANDOM_0_1() * 1400 / 100); float w = 85.0f; float h = 121.0f; - float x = (idx % 5) * w; - float y = (idx / 5) * h; - - auto sprite = Sprite::create("Images/grossini_dance_atlas.png", Rect(x, y, w, h)); - + float x = (idx%5) * w; + float y = (idx/5) * h; + + auto sprite = Sprite::create("Images/grossini_dance_atlas.png", Rect(x,y,w,h)); + sprite->setPosition(p); this->addChild(sprite); - + this->runActionsInSprite(sprite); } -void ActionStacked::runActionsInSprite(Sprite* sprite) +void ActionStacked::runActionsInSprite(Sprite *sprite) { // override me } void ActionStacked::onTouchesEnded(const std::vector& touches, Event* event) { - for (auto& touch : touches) - { + for ( auto &touch: touches ) { auto location = touch->getLocation(); - addNewSpriteWithCoords(location); + addNewSpriteWithCoords( location ); } } @@ -1420,17 +1464,26 @@ std::string ActionStacked::subtitle() const // ActionMoveStacked -void ActionMoveStacked::runActionsInSprite(Sprite* sprite) + +void ActionMoveStacked::runActionsInSprite(Sprite *sprite) { - sprite->runAction(RepeatForever::create(Sequence::create(MoveBy::create(0.05f, Vec2(10.0f, 10.0f)), - MoveBy::create(0.05f, Vec2(-10.0f, -10.0f)), nullptr))); - - auto action = MoveBy::create(2.0f, Vec2(400.0f, 0.0f)); + sprite->runAction( + RepeatForever::create( + Sequence::create( + MoveBy::create(0.05f, Vec2(10.0f,10.0f)), + MoveBy::create(0.05f, Vec2(-10.0f,-10.0f)), + nullptr))); + + auto action = MoveBy::create(2.0f, Vec2(400.0f,0.0f)); auto action_back = action->reverse(); - - sprite->runAction(RepeatForever::create(Sequence::create(action, action_back, nullptr))); + + sprite->runAction( + RepeatForever::create( + Sequence::create(action, action_back, nullptr) + )); } + std::string ActionMoveStacked::title() const { return "Stacked MoveBy/To actions"; @@ -1438,15 +1491,22 @@ std::string ActionMoveStacked::title() const // ActionMoveJumpStacked -void ActionMoveJumpStacked::runActionsInSprite(Sprite* sprite) +void ActionMoveJumpStacked::runActionsInSprite(Sprite *sprite) { - sprite->runAction(RepeatForever::create( - Sequence::create(MoveBy::create(0.05f, Vec2(10, 2)), MoveBy::create(0.05f, Vec2(-10, -2)), nullptr))); - - auto jump = JumpBy::create(2.0f, Vec2(400, 0), 100, 5); + sprite->runAction( + RepeatForever::create( + Sequence::create( + MoveBy::create(0.05f, Vec2(10,2)), + MoveBy::create(0.05f, Vec2(-10,-2)), + nullptr))); + + auto jump = JumpBy::create(2.0f, Vec2(400,0), 100, 5); auto jump_back = jump->reverse(); - - sprite->runAction(RepeatForever::create(Sequence::create(jump, jump_back, nullptr))); + + sprite->runAction( + RepeatForever::create( + Sequence::create(jump, jump_back, nullptr) + )); } std::string ActionMoveJumpStacked::title() const @@ -1456,24 +1516,28 @@ std::string ActionMoveJumpStacked::title() const // ActionMoveBezierStacked -void ActionMoveBezierStacked::runActionsInSprite(Sprite* sprite) +void ActionMoveBezierStacked::runActionsInSprite(Sprite *sprite) { auto s = Director::getInstance()->getWinSize(); - + // sprite 1 ccBezierConfig bezier; - bezier.controlPoint_1 = Vec2(0.0f, s.height / 2); - bezier.controlPoint_2 = Vec2(300.0f, -s.height / 2); - bezier.endPosition = Vec2(300.0f, 100.0f); - + bezier.controlPoint_1 = Vec2(0.0f, s.height/2); + bezier.controlPoint_2 = Vec2(300.0f, -s.height/2); + bezier.endPosition = Vec2(300.0f,100.0f); + auto bezierForward = BezierBy::create(3, bezier); - auto bezierBack = bezierForward->reverse(); - auto seq = Sequence::create(bezierForward, bezierBack, nullptr); - auto rep = RepeatForever::create(seq); + auto bezierBack = bezierForward->reverse(); + auto seq = Sequence::create(bezierForward, bezierBack, nullptr); + auto rep = RepeatForever::create(seq); sprite->runAction(rep); - - sprite->runAction(RepeatForever::create(Sequence::create(MoveBy::create(0.05f, Vec2(10.0f, 0.0f)), - MoveBy::create(0.05f, Vec2(-10.0f, 0.0f)), nullptr))); + + sprite->runAction( + RepeatForever::create( + Sequence::create( + MoveBy::create(0.05f, Vec2(10.0f,0.0f)), + MoveBy::create(0.05f, Vec2(-10.0f,0.0f)), + nullptr))); } std::string ActionMoveBezierStacked::title() const @@ -1481,81 +1545,92 @@ std::string ActionMoveBezierStacked::title() const return "Stacked Move + Bezier actions"; } + // ActionCatmullRomStacked void ActionCatmullRomStacked::onEnter() { ActionsDemo::onEnter(); - + this->centerSprites(2); - + auto s = Director::getInstance()->getWinSize(); - + // // sprite 1 (By) // // startPosition can be any coordinate, but since the movement // is relative to the Catmull Rom curve, it is better to start with (0,0). // - - _tamara->setPosition(50, 50); - + + _tamara->setPosition(50,50); + auto array = PointArray::create(20); - - array->addControlPoint(Vec2(0.0f, 0.0f)); - array->addControlPoint(Vec2(80.0f, 80.0f)); - array->addControlPoint(Vec2(s.width - 80, 80.0f)); - array->addControlPoint(Vec2(s.width - 80, s.height - 80.0f)); - array->addControlPoint(Vec2(80.0f, s.height - 80.0f)); - array->addControlPoint(Vec2(80.0f, 80.0f)); - array->addControlPoint(Vec2(s.width / 2, s.height / 2)); - - auto action = CatmullRomBy::create(3, array); + + array->addControlPoint(Vec2(0.0f,0.0f)); + array->addControlPoint(Vec2(80.0f,80.0f)); + array->addControlPoint(Vec2(s.width-80,80.0f)); + array->addControlPoint(Vec2(s.width-80,s.height-80.0f)); + array->addControlPoint(Vec2(80.0f,s.height-80.0f)); + array->addControlPoint(Vec2(80.0f,80.0f)); + array->addControlPoint(Vec2(s.width/2, s.height/2)); + + auto action = CatmullRomBy::create(3, array); auto reverse = action->reverse(); - + auto seq = Sequence::create(action, reverse, nullptr); - + _tamara->runAction(seq); - - _tamara->runAction(RepeatForever::create(Sequence::create(MoveBy::create(0.05f, Vec2(10.0f, 0.0f)), - MoveBy::create(0.05f, Vec2(-10.0f, 0.0f)), nullptr))); - + + _tamara->runAction( + RepeatForever::create( + Sequence::create( + MoveBy::create(0.05f, Vec2(10.0f,0.0f)), + MoveBy::create(0.05f, Vec2(-10.0f,0.0f)), + nullptr))); + auto drawNode1 = DrawNode::create(); - drawNode1->setPosition(Vec2(50.0f, 50.0f)); + drawNode1->setPosition(Vec2(50.0f,50.0f)); drawNode1->drawCatmullRom(array, 50, Color4F(1.0f, 1.0f, 0.0f, 0.5f)); this->addChild(drawNode1); - + // // sprite 2 (To) // // The startPosition is not important here, because it uses a "To" action. // The initial position will be the 1st point of the Catmull Rom path // - + auto array2 = PointArray::create(20); - - array2->addControlPoint(Vec2(s.width / 2, 30.0f)); - array2->addControlPoint(Vec2(s.width - 80, 30.0f)); - array2->addControlPoint(Vec2(s.width - 80.0f, s.height - 80.0f)); - array2->addControlPoint(Vec2(s.width / 2, s.height - 80.0f)); - array2->addControlPoint(Vec2(s.width / 2, 30.0f)); - - auto action2 = CatmullRomTo::create(3, array2); + + array2->addControlPoint(Vec2(s.width/2, 30.0f)); + array2->addControlPoint(Vec2(s.width-80,30.0f)); + array2->addControlPoint(Vec2(s.width-80.0f,s.height-80.0f)); + array2->addControlPoint(Vec2(s.width/2,s.height-80.0f)); + array2->addControlPoint(Vec2(s.width/2, 30.0f)); + + auto action2 = CatmullRomTo::create(3, array2); auto reverse2 = action2->reverse(); - + auto seq2 = Sequence::create(action2, reverse2, nullptr); - + _kathia->runAction(seq2); - - _kathia->runAction(RepeatForever::create(Sequence::create(MoveBy::create(0.05f, Vec2(10.0f, 0.0f)), - MoveBy::create(0.05f, Vec2(-10.0f, 0.0f)), nullptr))); - + + _kathia->runAction( + RepeatForever::create( + Sequence::create( + MoveBy::create(0.05f, Vec2(10.0f,0.0f)), + MoveBy::create(0.05f, Vec2(-10.0f,0.0f)), + nullptr))); + auto drawNode2 = DrawNode::create(); drawNode2->drawCatmullRom(array2, 50, Color4F(1.0, 0.0, 0.0, 0.5)); this->addChild(drawNode2); } -ActionCatmullRomStacked::~ActionCatmullRomStacked() {} +ActionCatmullRomStacked::~ActionCatmullRomStacked() +{ +} std::string ActionCatmullRomStacked::title() const { @@ -1567,71 +1642,83 @@ std::string ActionCatmullRomStacked::subtitle() const return "MoveBy + CatmullRom at the same time in the same sprite"; } + // ActionCardinalSplineStacked void ActionCardinalSplineStacked::onEnter() { ActionsDemo::onEnter(); - + this->centerSprites(2); - + auto s = Director::getInstance()->getWinSize(); - + auto array = PointArray::create(20); - + array->addControlPoint(Vec2(0.0f, 0.0f)); - array->addControlPoint(Vec2(s.width / 2 - 30, 0.0f)); - array->addControlPoint(Vec2(s.width / 2 - 30, s.height - 80.0f)); - array->addControlPoint(Vec2(0.0f, s.height - 80.0f)); + array->addControlPoint(Vec2(s.width/2-30,0.0f)); + array->addControlPoint(Vec2(s.width/2-30,s.height-80.0f)); + array->addControlPoint(Vec2(0.0f, s.height-80.0f)); array->addControlPoint(Vec2(0.0f, 0.0f)); - + + // // sprite 1 (By) // // Spline with no tension (tension==0) // - auto action = CardinalSplineBy::create(3, array, 0); + auto action = CardinalSplineBy::create(3, array, 0); auto reverse = action->reverse(); - + auto seq = Sequence::create(action, reverse, nullptr); - - _tamara->setPosition(50, 50); + + _tamara->setPosition(50,50); _tamara->runAction(seq); - - _tamara->runAction(RepeatForever::create(Sequence::create(MoveBy::create(0.05f, Vec2(10.0f, 0.0f)), - MoveBy::create(0.05f, Vec2(-10.0f, 0.0f)), nullptr))); - + + _tamara->runAction( + RepeatForever::create( + Sequence::create( + MoveBy::create(0.05f, Vec2(10.0f,0.0f)), + MoveBy::create(0.05f, Vec2(-10.0f,0.0f)), + nullptr))); + auto drawNode1 = DrawNode::create(); - drawNode1->setPosition(Vec2(50.0f, 50.0f)); + drawNode1->setPosition(Vec2(50.0f,50.0f)); drawNode1->drawCardinalSpline(array, 0, 100, Color4F(1.0f, 0.0f, 1.0f, 1.0f)); this->addChild(drawNode1); - + // // sprite 2 (By) // // Spline with high tension (tension==1) // - - auto* action2 = CardinalSplineBy::create(3, array, 1); + + auto *action2 = CardinalSplineBy::create(3, array, 1); auto reverse2 = action2->reverse(); - + auto seq2 = Sequence::create(action2, reverse2, nullptr); - - _kathia->setPosition(s.width / 2, 50); - + + _kathia->setPosition(s.width/2,50); + _kathia->runAction(seq2); - - _kathia->runAction(RepeatForever::create(Sequence::create(MoveBy::create(0.05f, Vec2(10.0f, 0.0f)), - MoveBy::create(0.05f, Vec2(-10.0f, 0.0f)), nullptr))); - + + _kathia->runAction( + RepeatForever::create( + Sequence::create( + MoveBy::create(0.05f, Vec2(10.0f,0.0f)), + MoveBy::create(0.05f, Vec2(-10.0f,0.0f)), + nullptr))); + auto drawNode2 = DrawNode::create(); - drawNode2->setPosition(Vec2(s.width / 2, 50.0f)); + drawNode2->setPosition(Vec2(s.width/2,50.0f)); drawNode2->drawCardinalSpline(array, 1, 100, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); this->addChild(drawNode2); } -ActionCardinalSplineStacked::~ActionCardinalSplineStacked() {} +ActionCardinalSplineStacked::~ActionCardinalSplineStacked() +{ +} std::string ActionCardinalSplineStacked::title() const { @@ -1653,12 +1740,11 @@ void Issue1305::onEnter() _spriteTmp->runAction(CallFunc::create(std::bind(&Issue1305::log, this, _spriteTmp))); _spriteTmp->retain(); - scheduleOnce( - [&](float dt) { - _spriteTmp->setPosition(250, 250); - addChild(_spriteTmp); - }, - 2, "update_key"); + scheduleOnce([&](float dt) { + _spriteTmp->setPosition(250,250); + addChild(_spriteTmp); + },2 ,"update_key"); + } void Issue1305::log(Node* sender) @@ -1689,10 +1775,10 @@ void Issue1305_2::onEnter() centerSprites(0); auto spr = Sprite::create("Images/grossini.png"); - spr->setPosition(200, 200); + spr->setPosition(200,200); addChild(spr); - auto act1 = MoveBy::create(2, Vec2(0.0f, 100.0f)); + auto act1 = MoveBy::create(2 ,Vec2(0.0f, 100.0f)); /* c++ can't support block, so we use CallFuncN instead. id act2 = [CallBlock actionWithBlock:^{ NSLog(@"1st block"); @@ -1711,18 +1797,19 @@ void Issue1305_2::onEnter() }); */ - auto act2 = CallFunc::create(std::bind(&Issue1305_2::printLog1, this)); + auto act2 = CallFunc::create( std::bind( &Issue1305_2::printLog1, this)); auto act3 = MoveBy::create(2, Vec2(0.0f, -100.0f)); - auto act4 = CallFunc::create(std::bind(&Issue1305_2::printLog2, this)); + auto act4 = CallFunc::create( std::bind( &Issue1305_2::printLog2, this)); auto act5 = MoveBy::create(2, Vec2(100.0f, -100.0f)); - auto act6 = CallFunc::create(std::bind(&Issue1305_2::printLog3, this)); + auto act6 = CallFunc::create( std::bind( &Issue1305_2::printLog3, this)); auto act7 = MoveBy::create(2, Vec2(-100.0f, 0.0f)); - auto act8 = CallFunc::create(std::bind(&Issue1305_2::printLog4, this)); + auto act8 = CallFunc::create( std::bind( &Issue1305_2::printLog4, this)); auto actF = Sequence::create(act1, act2, act3, act4, act5, act6, act7, act8, nullptr); // [spr runAction:actF); - Director::getInstance()->getActionManager()->addAction(actF, spr, false); + Director::getInstance()->getActionManager()->addAction(actF ,spr, false); + } void Issue1305_2::printLog1() @@ -1805,6 +1892,7 @@ std::string Issue1288_2::subtitle() const return "Sprite should move 100 pixels, and stay there"; } + void Issue1327::onEnter() { ActionsDemo::onEnter(); @@ -1814,15 +1902,15 @@ void Issue1327::onEnter() spr->setPosition(100, 100); addChild(spr); - auto act1 = CallFunc::create(std::bind(&Issue1327::logSprRotation, this, spr)); + auto act1 = CallFunc::create( std::bind(&Issue1327::logSprRotation, this, spr)); auto act2 = RotateBy::create(0.25, 45); - auto act3 = CallFunc::create(std::bind(&Issue1327::logSprRotation, this, spr)); + auto act3 = CallFunc::create( std::bind(&Issue1327::logSprRotation, this, spr)); auto act4 = RotateBy::create(0.25, 45); - auto act5 = CallFunc::create(std::bind(&Issue1327::logSprRotation, this, spr)); + auto act5 = CallFunc::create( std::bind(&Issue1327::logSprRotation, this, spr)); auto act6 = RotateBy::create(0.25, 45); - auto act7 = CallFunc::create(std::bind(&Issue1327::logSprRotation, this, spr)); + auto act7 = CallFunc::create( std::bind(&Issue1327::logSprRotation, this, spr)); auto act8 = RotateBy::create(0.25, 45); - auto act9 = CallFunc::create(std::bind(&Issue1327::logSprRotation, this, spr)); + auto act9 = CallFunc::create( std::bind(&Issue1327::logSprRotation, this, spr)); auto actF = Sequence::create(act1, act2, act3, act4, act5, act6, act7, act8, act9, nullptr); spr->runAction(actF); @@ -1843,7 +1931,7 @@ void Issue1327::logSprRotation(Sprite* sender) log("%f", sender->getRotation()); } -// Issue1398 +//Issue1398 void Issue1398::incrementInteger() { _testInteger++; @@ -1859,14 +1947,16 @@ void Issue1398::onEnter() log("testInt = %d", _testInteger); this->runAction( - Sequence::create(CallFunc::create(std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"1")), - CallFunc::create(std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"2")), - CallFunc::create(std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"3")), - CallFunc::create(std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"4")), - CallFunc::create(std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"5")), - CallFunc::create(std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"6")), - CallFunc::create(std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"7")), - CallFunc::create(std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"8")), nullptr)); + Sequence::create( + CallFunc::create( std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"1")), + CallFunc::create( std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"2")), + CallFunc::create( std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"3")), + CallFunc::create( std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"4")), + CallFunc::create( std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"5")), + CallFunc::create( std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"6")), + CallFunc::create( std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"7")), + CallFunc::create( std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"8")), + nullptr)); } void Issue1398::incrementIntegerCallback(void* data) @@ -1889,16 +1979,22 @@ void Issue2599::onEnter() { ActionsDemo::onEnter(); this->centerSprites(0); - + _count = 0; log("before: count = %d", _count); - + log("start count up 50 times using Repeat action"); - auto delay = 1.0f / 50; + auto delay = 1.0f / 50; auto repeatAction = Repeat::create( - Sequence::createWithTwoActions(CallFunc::create([&]() { this->_count++; }), DelayTime::create(delay)), 50); - this->runAction(Sequence::createWithTwoActions( - repeatAction, CallFunc::create([&]() { log("after: count = %d", this->_count); }))); + Sequence::createWithTwoActions( + CallFunc::create([&](){ this->_count++; }), + DelayTime::create(delay)), + 50); + this->runAction( + Sequence::createWithTwoActions( + repeatAction, + CallFunc::create([&]() { log("after: count = %d", this->_count); }) + )); } std::string Issue2599::subtitle() const @@ -1916,22 +2012,22 @@ std::string Issue2599::title() const void ActionCatmullRom::onEnter() { ActionsDemo::onEnter(); - + this->centerSprites(2); - + auto s = Director::getInstance()->getWinSize(); - + // // sprite 1 (By) // // startPosition can be any coordinate, but since the movement // is relative to the Catmull Rom curve, it is better to start with (0,0). // - + _tamara->setPosition(50, 50); - + auto array = PointArray::create(20); - + array->addControlPoint(Vec2(0.0f, 0.0f)); array->addControlPoint(Vec2(80.0f, 80.0f)); array->addControlPoint(Vec2(s.width - 80, 80.0f)); @@ -1939,47 +2035,49 @@ void ActionCatmullRom::onEnter() array->addControlPoint(Vec2(80.0f, s.height - 80.0f)); array->addControlPoint(Vec2(80.0f, 80.0f)); array->addControlPoint(Vec2(s.width / 2, s.height / 2)); - - auto action = CatmullRomBy::create(3, array); + + auto action = CatmullRomBy::create(3, array); auto reverse = action->reverse(); - + auto seq = Sequence::create(action, reverse, nullptr); - + _tamara->runAction(seq); - + auto drawNode1 = DrawNode::create(); - drawNode1->setPosition(Vec2(50.0f, 50.0f)); + drawNode1->setPosition(Vec2(50.0f,50.0f)); drawNode1->drawCatmullRom(array, 50, Color4F(1.0f, 0.0f, 1.0f, 1.0f)); this->addChild(drawNode1); - + // // sprite 2 (To) // // The startPosition is not important here, because it uses a "To" action. // The initial position will be the 1st point of the Catmull Rom path - // - + // + auto array2 = PointArray::create(20); - + array2->addControlPoint(Vec2(s.width / 2, 30.0f)); - array2->addControlPoint(Vec2(s.width - 80, 30.0f)); + array2->addControlPoint(Vec2(s.width -80, 30.0f)); array2->addControlPoint(Vec2(s.width - 80, s.height - 80)); array2->addControlPoint(Vec2(s.width / 2, s.height - 80)); array2->addControlPoint(Vec2(s.width / 2, 30.0f)); - - auto action2 = CatmullRomTo::create(3, array2); + + auto action2 = CatmullRomTo::create(3, array2); auto reverse2 = action2->reverse(); - + auto seq2 = Sequence::create(action2, reverse2, nullptr); - + _kathia->runAction(seq2); - + auto drawNode2 = DrawNode::create(); drawNode2->drawCatmullRom(array2, 50, Color4F(0.0f, 1.0f, 1.0f, 1.0f)); this->addChild(drawNode2); } -ActionCatmullRom::~ActionCatmullRom() {} +ActionCatmullRom::~ActionCatmullRom() +{ +} std::string ActionCatmullRom::title() const { @@ -1996,59 +2094,61 @@ std::string ActionCatmullRom::subtitle() const void ActionCardinalSpline::onEnter() { ActionsDemo::onEnter(); - + this->centerSprites(2); - + auto s = Director::getInstance()->getWinSize(); - + auto array = PointArray::create(20); - + array->addControlPoint(Vec2(0.0f, 0.0f)); - array->addControlPoint(Vec2(s.width / 2 - 30, 0.0f)); - array->addControlPoint(Vec2(s.width / 2 - 30, s.height - 80)); - array->addControlPoint(Vec2(0.0f, s.height - 80)); + array->addControlPoint(Vec2(s.width/2-30, 0.0f)); + array->addControlPoint(Vec2(s.width/2-30, s.height-80)); + array->addControlPoint(Vec2(0.0f, s.height-80)); array->addControlPoint(Vec2(0.0f, 0.0f)); - + // // sprite 1 (By) // // Spline with no tension (tension==0) // - - auto action = CardinalSplineBy::create(3, array, 0); + + auto action = CardinalSplineBy::create(3, array, 0); auto reverse = action->reverse(); - + auto seq = Sequence::create(action, reverse, nullptr); - + _tamara->setPosition(50, 50); _tamara->runAction(seq); - + auto drawNode1 = DrawNode::create(); - drawNode1->setPosition(Vec2(50.0f, 50.0f)); + drawNode1->setPosition(Vec2(50.0f,50.0f)); drawNode1->drawCardinalSpline(array, 0, 100, Color4F(1.0f, 0.0f, 1.0f, 1.0f)); this->addChild(drawNode1); - + // // sprite 2 (By) // // Spline with high tension (tension==1) // - - auto action2 = CardinalSplineBy::create(3, array, 1); + + auto action2 = CardinalSplineBy::create(3, array, 1); auto reverse2 = action2->reverse(); - + auto seq2 = Sequence::create(action2, reverse2, nullptr); - - _kathia->setPosition(s.width / 2, 50); + + _kathia->setPosition(s.width/2, 50); _kathia->runAction(seq2); - + auto drawNode2 = DrawNode::create(); - drawNode2->setPosition(Vec2(s.width / 2, 50.0f)); + drawNode2->setPosition(Vec2(s.width/2, 50.0f)); drawNode2->drawCardinalSpline(array, 1, 100, Color4F(1.0f, 0.0f, 1.0f, 1.0f)); this->addChild(drawNode2); } -ActionCardinalSpline::~ActionCardinalSpline() {} +ActionCardinalSpline::~ActionCardinalSpline() +{ +} std::string ActionCardinalSpline::title() const { @@ -2063,37 +2163,41 @@ std::string ActionCardinalSpline::subtitle() const /** PauseResumeActions */ -PauseResumeActions::PauseResumeActions() {} +PauseResumeActions::PauseResumeActions() +{ -PauseResumeActions::~PauseResumeActions() {} +} + +PauseResumeActions::~PauseResumeActions() +{ + +} void PauseResumeActions::onEnter() { ActionsDemo::onEnter(); - + this->centerSprites(3); - + _tamara->runAction(RepeatForever::create(RotateBy::create(3.0f, 360.0f))); _grossini->runAction(RepeatForever::create(RotateBy::create(3.0f, -360.0f))); _kathia->runAction(RepeatForever::create(RotateBy::create(3.0f, 360.0f))); + + this->schedule([&](float dt){ + log("Pausing"); + auto director = Director::getInstance(); - this->schedule( - [&](float dt) { - log("Pausing"); - auto director = Director::getInstance(); + _pausedTargets = director->getActionManager()->pauseAllRunningActions(); + } + ,3 ,false ,0 ,"pause_key"); - _pausedTargets = director->getActionManager()->pauseAllRunningActions(); - }, - 3, false, 0, "pause_key"); - - this->schedule( - [&](float dt) { - log("Resuming"); - auto director = Director::getInstance(); - director->getActionManager()->resumeTargets(_pausedTargets); - _pausedTargets.clear(); - }, - 5, false, 0, "resume_key"); + this->schedule([&](float dt) { + log("Resuming"); + auto director = Director::getInstance(); + director->getActionManager()->resumeTargets(_pausedTargets); + _pausedTargets.clear(); + } + ,5 ,false ,0, "resume_key"); } std::string PauseResumeActions::title() const @@ -2109,11 +2213,11 @@ std::string PauseResumeActions::subtitle() const //------------------------------------------------------------------ // // ActionResize -// Works on all nodes where setContentSize is effective. +// Works on all nodes where setContentSize is effective. // But it's mostly useful for nodes where 9-slice is enabled // //------------------------------------------------------------------ -void ActionResize::onEnter() +void ActionResize::onEnter() { ActionsDemo::onEnter(); @@ -2123,13 +2227,10 @@ void ActionResize::onEnter() Size widgetSize = getContentSize(); - Text* alert = Text::create( - "ImageView Content ResizeTo ResizeBy action. \nTop: ResizeTo/ResizeBy on a 9-slice ImageView \nBottom: " - "ScaleTo/ScaleBy on a 9-slice ImageView (for comparison)", - "fonts/Marker Felt.ttf", 14); + Text* alert = Text::create("ImageView Content ResizeTo ResizeBy action. \nTop: ResizeTo/ResizeBy on a 9-slice ImageView \nBottom: ScaleTo/ScaleBy on a 9-slice ImageView (for comparison)", "fonts/Marker Felt.ttf", 14); alert->setColor(Color3B(159, 168, 176)); - alert->setPosition( - Vec2(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getContentSize().height * 1.125f)); + alert->setPosition(Vec2(widgetSize.width / 2.0f, + widgetSize.height / 2.0f - alert->getContentSize().height * 1.125f)); addChild(alert); @@ -2138,13 +2239,14 @@ void ActionResize::onEnter() ImageView* imageViewResize = ImageView::create("cocosui/buttonHighlighted.png"); imageViewResize->setScale9Enabled(true); imageViewResize->setContentSize(Size(50.0f, 40.0f)); - imageViewResize->setPosition(Vec2((widgetSize.width / 2.0f) + offset.x, (widgetSize.height / 2.0f) + offset.y)); + imageViewResize->setPosition(Vec2((widgetSize.width / 2.0f) + offset.x, + (widgetSize.height / 2.0f) + offset.y)); auto resizeDown = cocos2d::ResizeTo::create(2.8f, Size(50.0f, 40.0f)); - auto resizeUp = cocos2d::ResizeTo::create(2.8f, Size(300.0f, 40.0f)); + auto resizeUp = cocos2d::ResizeTo::create(2.8f, Size(300.0f, 40.0f)); auto resizeByDown = cocos2d::ResizeBy::create(1.8f, Size(0.0f, -30.0f)); - auto resizeByUp = cocos2d::ResizeBy::create(1.8f, Size(0.0f, 30.0f)); + auto resizeByUp = cocos2d::ResizeBy::create(1.8f, Size(0.0f, 30.0f)); addChild(imageViewResize); auto rep = RepeatForever::create(Sequence::create(resizeUp, resizeDown, resizeByDown, resizeByUp, nullptr)); imageViewResize->runAction(rep); @@ -2153,20 +2255,20 @@ void ActionResize::onEnter() ImageView* imageViewScale = ImageView::create("cocosui/buttonHighlighted.png"); imageViewScale->setScale9Enabled(true); imageViewScale->setContentSize(Size(50.0f, 40.0f)); - imageViewScale->setPosition(Vec2(widgetSize.width / 2.0f, widgetSize.height / 2.0f)); + imageViewScale->setPosition(Vec2(widgetSize.width / 2.0f, + widgetSize.height / 2.0f)); auto scaleDownScale = cocos2d::ScaleTo::create(2.8f, 1.0f); - auto scaleUpScale = cocos2d::ScaleTo::create(2.8f, 6.0f, 1.0f); + auto scaleUpScale = cocos2d::ScaleTo::create(2.8f, 6.0f, 1.0f); auto scaleByDownScale = cocos2d::ScaleBy::create(1.8f, 1.0f, 0.25f); - auto scaleByUpScale = cocos2d::ScaleBy::create(1.8f, 1.0f, 4.0f); + auto scaleByUpScale = cocos2d::ScaleBy::create(1.8f, 1.0f, 4.0f); addChild(imageViewScale); - auto rep2 = RepeatForever::create( - Sequence::create(scaleUpScale, scaleDownScale, scaleByDownScale, scaleByUpScale, nullptr)); + auto rep2 = RepeatForever::create(Sequence::create(scaleUpScale, scaleDownScale, scaleByDownScale, scaleByUpScale, nullptr)); imageViewScale->runAction(rep2); } -std::string ActionResize::subtitle() const +std::string ActionResize::subtitle() const { return "ResizeTo / ResizeBy"; } @@ -2178,19 +2280,23 @@ std::string ActionResize::subtitle() const //------------------------------------------------------------------ void ActionRemoveSelf::onEnter() { - ActionsDemo::onEnter(); + ActionsDemo::onEnter(); - alignSpritesLeft(1); + alignSpritesLeft(1); - auto action = Sequence::create(MoveBy::create(2, Vec2(240.0f, 0.0f)), RotateBy::create(2, 540), - ScaleTo::create(1, 0.1f), RemoveSelf::create(), nullptr); + auto action = Sequence::create( + MoveBy::create( 2, Vec2(240.0f,0.0f)), + RotateBy::create( 2, 540), + ScaleTo::create(1,0.1f), + RemoveSelf::create(), + nullptr); - _grossini->runAction(action); + _grossini->runAction(action); } std::string ActionRemoveSelf::subtitle() const { - return "Sequence: Move + Rotate + Scale + RemoveSelf"; + return "Sequence: Move + Rotate + Scale + RemoveSelf"; } //------------------------------------------------------------------ @@ -2206,28 +2312,31 @@ void ActionFloatTest::onEnter() auto s = Director::getInstance()->getWinSize(); - // create float action with duration and from to value, using lambda function we can easily animate any property of - // the Node. - auto actionFloat = ActionFloat::create(2.f, 0, 3, [this](float value) { _tamara->setScale(value); }); + // create float action with duration and from to value, using lambda function we can easily animate any property of the Node. + auto actionFloat = ActionFloat::create(2.f, 0, 3, [this](float value) { + _tamara->setScale(value); + }); float grossiniY = _grossini->getPositionY(); - auto actionFloat1 = - ActionFloat::create(3.f, grossiniY, grossiniY + 50, [this](float value) { _grossini->setPositionY(value); }); + auto actionFloat1 = ActionFloat::create(3.f, grossiniY, grossiniY + 50, [this](float value) { + _grossini->setPositionY(value); + }); - auto actionFloat2 = ActionFloat::create(3.f, 3, 1, [this](float value) { _kathia->setScale(value); }); + auto actionFloat2 = ActionFloat::create(3.f, 3, 1, [this] (float value) { + _kathia->setScale(value); + }); _tamara->runAction(actionFloat); _grossini->runAction(actionFloat1); _kathia->runAction(actionFloat2); } -void Issue14936_1::onEnter() -{ +void Issue14936_1::onEnter() { ActionsDemo::onEnter(); centerSprites(0); - auto origin = cocos2d::Director::getInstance()->getVisibleOrigin(); + auto origin = cocos2d::Director::getInstance()->getVisibleOrigin(); auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize(); _count = 0; @@ -2236,7 +2345,7 @@ void Issue14936_1::onEnter() counterLabel->setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2); addChild(counterLabel); - auto func = CallFunc::create([this, counterLabel] { + auto func = CallFunc::create([this, counterLabel]{ _count++; std::ostringstream os; os << _count; @@ -2246,20 +2355,18 @@ void Issue14936_1::onEnter() runAction(Spawn::create(func, func, nullptr)); } -std::string Issue14936_1::subtitle() const -{ +std::string Issue14936_1::subtitle() const { return "Counter should be equal 2"; } -void Issue14936_2::onEnter() -{ +void Issue14936_2::onEnter() { ActionsDemo::onEnter(); centerSprites(0); - auto origin = cocos2d::Director::getInstance()->getVisibleOrigin(); + auto origin = cocos2d::Director::getInstance()->getVisibleOrigin(); auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize(); - _count = 0; + _count = 0; auto counterLabel = Label::createWithTTF("0", "fonts/Marker Felt.ttf", 16.0f); counterLabel->setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2); addChild(counterLabel); @@ -2274,18 +2381,15 @@ void Issue14936_2::onEnter() runAction(Sequence::create(TargetedAction::create(this, func), DelayTime::create(0.2f), nullptr)); } -std::string Issue14936_2::subtitle() const -{ +std::string Issue14936_2::subtitle() const { return "Counter should be equal 1"; } -std::string Issue14936_2::title() const -{ +std::string Issue14936_2::title() const { return "Issue 14936 - Sequence"; } -std::string Issue14936_1::title() const -{ +std::string Issue14936_1::title() const { return "Issue 14936 - Action Interval"; } @@ -2294,6 +2398,8 @@ std::string ActionFloatTest::subtitle() const return "ActionFloat"; } + + //------------------------------------------------------------------ // // SequenceWithFinalInstant @@ -2304,31 +2410,36 @@ void SequenceWithFinalInstant::onEnter() TestCase::onEnter(); _manager = new cocos2d::ActionManager(); - + _target = cocos2d::Node::create(); - _target->setActionManager(_manager); + _target->setActionManager( _manager ); _target->retain(); _target->onEnter(); - bool called(false); - const auto f([&called]() -> void { - cocos2d::log("Callback called."); - called = true; - }); - + bool called( false ); + const auto f + ( [ &called ]() -> void + { + cocos2d::log("Callback called."); + called = true; + } ); + const auto action = - cocos2d::Sequence::create(cocos2d::DelayTime::create(0.05f), cocos2d::CallFunc::create(f), nullptr); + cocos2d::Sequence::create + (cocos2d::DelayTime::create(0.05f), + cocos2d::CallFunc::create(f), + nullptr); _target->runAction(action); _manager->update(0); _manager->update(0.05f - FLT_EPSILON); - if (action->isDone() && !called) + if ( action->isDone() && !called ) assert(false); - + _manager->update(FLT_EPSILON); - if (action->isDone() && !called) + if ( action->isDone() && !called ) assert(false); } @@ -2354,46 +2465,54 @@ std::string SequenceWithFinalInstant::subtitle() const void Issue18003::onEnter() { TestCase::onEnter(); - + _manager = new ActionManager(); - + _target = Node::create(); _target->setActionManager(_manager); _target->retain(); _target->onEnter(); - + // instant action + interval action - - const auto f([]() -> void { - // do nothing - }); - - auto action = Sequence::create(CallFunc::create(f), DelayTime::create(1), nullptr); - + + const auto f + ( []() -> void + { + // do nothing + }); + + auto action = Sequence::create(CallFunc::create(f), + DelayTime::create(1), + nullptr); + _target->runAction(action); _manager->update(0); _manager->update(2); - + assert(action->isDone()); - + _target->stopAction(action); - + // instant action + instant action - action = Sequence::create(CallFunc::create(f), CallFunc::create(f), nullptr); + action = Sequence::create(CallFunc::create(f), + CallFunc::create(f), + nullptr); _target->runAction(action); _manager->update(0); _manager->update(1); assert(action->isDone()); _target->stopAction(action); - + // interval action + instant action - action = Sequence::create(DelayTime::create(1), CallFunc::create(f), nullptr); + action = Sequence::create(DelayTime::create(1), + CallFunc::create(f), + nullptr); _target->runAction(action); _manager->update(0); _manager->update(2); assert(action->isDone()); _target->stopAction(action); - + // interval action + interval action action = Sequence::create(DelayTime::create(1), DelayTime::create(1), nullptr); _target->runAction(action); diff --git a/tests/cpp-tests/Classes/ActionsTest/ActionsTest.h b/tests/cpp-tests/Classes/ActionsTest/ActionsTest.h index 1252de4f9d..12b16ed6a1 100644 --- a/tests/cpp-tests/Classes/ActionsTest/ActionsTest.h +++ b/tests/cpp-tests/Classes/ActionsTest/ActionsTest.h @@ -34,10 +34,9 @@ DEFINE_TEST_SUITE(ActionsTests); class ActionsDemo : public TestCase { protected: - cocos2d::Sprite* _grossini; - cocos2d::Sprite* _tamara; - cocos2d::Sprite* _kathia; - + cocos2d::Sprite* _grossini; + cocos2d::Sprite* _tamara; + cocos2d::Sprite* _kathia; public: virtual void onEnter() override; virtual void onExit() override; @@ -60,7 +59,7 @@ class ActionMove3D : public ActionsDemo { public: CREATE_FUNC(ActionMove3D); - + virtual void onEnter() override; virtual std::string subtitle() const override; }; @@ -182,7 +181,7 @@ public: virtual void onExit() override; virtual std::string title() const override; virtual std::string subtitle() const override; - + private: cocos2d::EventListenerCustom* _frameDisplayedListener; }; @@ -296,8 +295,8 @@ class ActionRemoveSelf : public ActionsDemo public: CREATE_FUNC(ActionRemoveSelf); - virtual void onEnter() override; - virtual std::string subtitle() const override; + virtual void onEnter() override; + virtual std::string subtitle() const override; }; class ActionRepeatForever : public ActionsDemo @@ -355,6 +354,7 @@ public: void callback3(Node* pTarget, int32_t data); }; + class ActionFollow : public ActionsDemo { public: @@ -366,10 +366,10 @@ public: class ActionFollowWithOffset : public ActionsDemo { - + public: CREATE_FUNC(ActionFollowWithOffset); - + virtual void onEnter() override; virtual std::string subtitle() const override; }; @@ -466,7 +466,6 @@ public: void log(Node* sender); virtual std::string title() const override; virtual std::string subtitle() const override; - private: cocos2d::Sprite* _spriteTmp; }; @@ -526,7 +525,6 @@ public: virtual void onEnter() override; virtual std::string subtitle() const override; virtual std::string title() const override; - private: int _testInteger; }; @@ -535,11 +533,10 @@ class Issue2599 : public ActionsDemo { public: CREATE_FUNC(Issue2599); - + virtual void onEnter() override; virtual std::string subtitle() const override; virtual std::string title() const override; - private: int _count; }; @@ -550,7 +547,7 @@ public: CREATE_FUNC(ActionCatmullRom); ~ActionCatmullRom(); - + virtual void onEnter() override; virtual std::string subtitle() const override; virtual std::string title() const override; @@ -562,7 +559,7 @@ public: CREATE_FUNC(ActionCardinalSpline); ~ActionCardinalSpline(); - + virtual void onEnter() override; virtual std::string subtitle() const override; virtual std::string title() const override; @@ -577,13 +574,12 @@ public: virtual ~PauseResumeActions(); virtual void onEnter() override; virtual std::string subtitle() const override; - virtual std::string title() const override; - + virtual std::string title() const override; private: cocos2d::Vector _pausedTargets; }; -class ActionResize : public ActionsDemo +class ActionResize : public ActionsDemo { public: CREATE_FUNC(ActionResize); @@ -609,7 +605,6 @@ public: virtual void onEnter() override; virtual std::string subtitle() const override; virtual std::string title() const override; - private: int _count; }; @@ -622,7 +617,6 @@ public: virtual void onEnter() override; virtual std::string subtitle() const override; virtual std::string title() const override; - private: int _count; }; @@ -631,28 +625,30 @@ class SequenceWithFinalInstant : public ActionsDemo { public: CREATE_FUNC(SequenceWithFinalInstant); - + virtual std::string subtitle() const override; virtual void onEnter() override; virtual void onExit() override; - + private: cocos2d::ActionManager* _manager; cocos2d::Node* _target; + }; class Issue18003 : public ActionsDemo { public: CREATE_FUNC(Issue18003); - + virtual std::string subtitle() const override; virtual void onEnter() override; virtual void onExit() override; - + private: cocos2d::ActionManager* _manager; cocos2d::Node* _target; + }; #endif diff --git a/tests/cpp-tests/Classes/AppDelegate.cpp b/tests/cpp-tests/Classes/AppDelegate.cpp index e606394e20..6dda030726 100644 --- a/tests/cpp-tests/Classes/AppDelegate.cpp +++ b/tests/cpp-tests/Classes/AppDelegate.cpp @@ -36,18 +36,21 @@ USING_NS_CC; // Enable log on Debug version #ifndef NDEBUG -# define COCOS2D_DEBUG 1 +#define COCOS2D_DEBUG 1 #else -# define COCOS2D_DEBUG 0 +#define COCOS2D_DEBUG 0 #endif -AppDelegate::AppDelegate() : _testController(nullptr) {} +AppDelegate::AppDelegate() +: _testController(nullptr) +{ +} AppDelegate::~AppDelegate() { - // SimpleAudioEngine::end(); - // TODO: minggo - // cocostudio::ArmatureDataManager::destroyInstance(); + //SimpleAudioEngine::end(); + //TODO: minggo + // cocostudio::ArmatureDataManager::destroyInstance(); } // if you want a different context, modify the value of glContextAttrs @@ -72,42 +75,42 @@ bool AppDelegate::applicationDidFinishLaunching() // initialize director auto director = Director::getInstance(); - auto glview = director->getOpenGLView(); - if (!glview) - { + auto glview = director->getOpenGLView(); + if (!glview) { std::string title = "Cpp Tests"; #ifndef NDEBUG title += " *Debug*", #endif - glview = GLViewImpl::createWithRect(title, Rect(0, 0, resourceSize.width, resourceSize.height)); + glview = GLViewImpl::createWithRect(title, Rect(0, 0, resourceSize.width, resourceSize.height)); director->setOpenGLView(glview); } - + director->setDisplayStats(true); director->setAnimationInterval(1.0f / 60); auto screenSize = glview->getFrameSize(); + auto fileUtils = FileUtils::getInstance(); std::vector searchPaths; - + if (screenSize.height > 320) { searchPaths.push_back("hd"); searchPaths.push_back("ccs-res/hd"); searchPaths.push_back("ccs-res"); searchPaths.push_back("Manifests"); - director->setContentScaleFactor(resourceSize.height / designSize.height); + director->setContentScaleFactor(resourceSize.height/designSize.height); searchPaths.push_back("hd/ActionTimeline"); } else { searchPaths.push_back("ccs-res"); - + searchPaths.push_back("ActionTimeline"); } - + fileUtils->setSearchPaths(searchPaths); glview->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::NO_BORDER); @@ -126,9 +129,9 @@ void AppDelegate::applicationDidEnterBackground() { if (_testController) { - // _testController->onEnterBackground(); +// _testController->onEnterBackground(); } - + Director::getInstance()->stopAnimation(); } @@ -137,8 +140,8 @@ void AppDelegate::applicationWillEnterForeground() { if (_testController) { - // _testController->onEnterForeground(); +// _testController->onEnterForeground(); } - + Director::getInstance()->startAnimation(); } diff --git a/tests/cpp-tests/Classes/AppDelegate.h b/tests/cpp-tests/Classes/AppDelegate.h index ee34105f56..6a7ff311ec 100644 --- a/tests/cpp-tests/Classes/AppDelegate.h +++ b/tests/cpp-tests/Classes/AppDelegate.h @@ -24,8 +24,8 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef _APP_DELEGATE_H_ -#define _APP_DELEGATE_H_ +#ifndef _APP_DELEGATE_H_ +#define _APP_DELEGATE_H_ #include "cocos2d.h" @@ -35,7 +35,7 @@ class TestController; Private inheritance here hides part of interface from Director. */ -class AppDelegate : private cocos2d::Application +class AppDelegate : private cocos2d::Application { public: AppDelegate(); @@ -66,4 +66,5 @@ private: TestController* _testController; }; -#endif // _APP_DELEGATE_H_ +#endif // _APP_DELEGATE_H_ + diff --git a/tests/cpp-tests/Classes/BaseTest.cpp b/tests/cpp-tests/Classes/BaseTest.cpp index 04856b009b..30fbd9671f 100644 --- a/tests/cpp-tests/Classes/BaseTest.cpp +++ b/tests/cpp-tests/Classes/BaseTest.cpp @@ -32,9 +32,17 @@ USING_NS_CC_EXT; #define TABEL_LABEL_TAG 1024 -TestBase::TestBase() : _parentTest(nullptr), _isTestList(false) {} +TestBase::TestBase() +: _parentTest(nullptr) +, _isTestList(false) +{ -TestBase::~TestBase() {} +} + +TestBase::~TestBase() +{ + +} void TestBase::backsUpOneLevel() { @@ -45,7 +53,7 @@ void TestBase::backsUpOneLevel() } } -// TestList +//TestList class TestCustomTableView : public TableView { public: @@ -60,8 +68,8 @@ public: return table; } - - virtual void onTouchEnded(Touch* touch, Event* event) override + + virtual void onTouchEnded(Touch *touch, Event *event) override { if (!this->isVisible()) { @@ -72,7 +80,7 @@ public: { auto label = (Label*)_touchedCell->getChildByTag(TABEL_LABEL_TAG); - Rect bbox = label->getBoundingBox(); + Rect bbox = label->getBoundingBox(); bbox.origin = _touchedCell->convertToWorldSpace(bbox.origin); if (bbox.containsPoint(touch->getLocation()) && _tableViewDelegate != nullptr) @@ -87,10 +95,10 @@ public: ScrollView::onTouchEnded(touch, event); } - void onMouseScroll(Event* event) + void onMouseScroll(Event *event) { auto mouseEvent = static_cast(event); - float moveY = mouseEvent->getScrollY() * 20; + float moveY = mouseEvent->getScrollY() * 20; auto minOffset = this->minContainerOffset(); auto maxOffset = this->maxContainerOffset(); @@ -112,7 +120,7 @@ public: protected: TestCustomTableView() { - auto mouseListener = EventListenerMouse::create(); + auto mouseListener = EventListenerMouse::create(); mouseListener->onMouseScroll = CC_CALLBACK_1(TestCustomTableView::onMouseScroll, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener, this); } @@ -120,28 +128,25 @@ protected: TestList::TestList() { - _isTestList = true; + _isTestList = true; _shouldRestoreTableOffset = false; } -TestList::~TestList() -{ +TestList::~TestList() { deatchTableView(); } -void TestList::deatchTableView() -{ +void TestList::deatchTableView() { if (_tableView) _tableView->setDataSource(nullptr); CC_SAFE_RELEASE_NULL(_tableView); } -void TestList::addTest(std::string_view testName, std::function callback) +void TestList::addTest(const std::string& testName, std::function callback) { if (!testName.empty()) { - _childTestNames.emplace_back( - StringUtils::format("%d:%s", static_cast(_childTestNames.size() + 1), testName.data())); + _childTestNames.emplace_back(StringUtils::format("%d", static_cast(_childTestNames.size() + 1)) + ":" + testName); _testCallbacks.emplace_back(callback); } } @@ -151,24 +156,24 @@ void TestList::runThisTest() _cellTouchEnabled = true; /* Restore default window and design size - * Note: We should change frame and design size before your new scene create - * otherwise, the layout will incorrect - */ - - GLViewImpl* glview = (GLViewImpl*)Director::getInstance()->getOpenGLView(); -#if defined(CC_PLATFORM_PC) + * Note: We should change frame and design size before your new scene create + * otherwise, the layout will incorrect + */ + + GLViewImpl* glview = (GLViewImpl*) Director::getInstance()->getOpenGLView(); + #if defined(CC_PLATFORM_PC) Size resourceSize(960, 640); glview->setWindowed(resourceSize.width, resourceSize.height); -#endif - + #endif + Size designSize(480, 320); glview->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::NO_BORDER); auto director = Director::getInstance(); - auto scene = Scene::create(); + auto scene = Scene::create(); auto visibleSize = director->getVisibleSize(); - auto origin = director->getVisibleOrigin(); + auto origin = director->getVisibleOrigin(); deatchTableView(); _tableView = TestCustomTableView::create(this, Size(400, visibleSize.height)); _tableView->retain(); @@ -186,12 +191,12 @@ void TestList::runThisTest() if (_parentTest) { - // Add back button. + //Add back button. TTFConfig ttfConfig("fonts/arial.ttf", 20); auto label = Label::createWithTTF(ttfConfig, "Back"); auto menuItem = MenuItemLabel::create(label, std::bind(&TestBase::backsUpOneLevel, this)); - auto menu = Menu::create(menuItem, nullptr); + auto menu = Menu::create(menuItem, nullptr); menu->setPosition(Vec2::ZERO); menuItem->setPosition(Vec2(VisibleRect::right().x - 50, VisibleRect::bottom().y + 25)); @@ -200,17 +205,18 @@ void TestList::runThisTest() } else { - // Add close and "Start AutoTest" button. - auto closeItem = MenuItemImage::create(s_pathClose, s_pathClose, [](Ref* sender) { + //Add close and "Start AutoTest" button. + auto closeItem = MenuItemImage::create(s_pathClose, s_pathClose, [](Ref* sender){ TestController::getInstance()->stopAutoTest(); TestController::destroyInstance(); Director::getInstance()->end(); }); closeItem->setPosition(VisibleRect::right().x - 30, VisibleRect::top().y - 30); - auto autoTestLabel = Label::createWithTTF("Start AutoTest", "fonts/arial.ttf", 16); - auto autoTestItem = - MenuItemLabel::create(autoTestLabel, [&](Ref* sender) { TestController::getInstance()->startAutoTest(); }); + auto autoTestLabel = Label::createWithTTF("Start AutoTest","fonts/arial.ttf",16); + auto autoTestItem = MenuItemLabel::create(autoTestLabel, [&](Ref* sender){ + TestController::getInstance()->startAutoTest(); + }); autoTestItem->setPosition(Vec2(VisibleRect::left().x + 60, VisibleRect::bottom().y + 50)); auto menu = Menu::create(closeItem, autoTestItem, nullptr); @@ -231,9 +237,9 @@ void TestList::tableCellTouched(TableView* table, TableViewCell* cell) auto test = _testCallbacks[index](); if (test->getChildTestCount() > 0) { - _tableOffset = table->getContentOffset(); + _tableOffset = table->getContentOffset(); _shouldRestoreTableOffset = true; - _cellTouchEnabled = false; + _cellTouchEnabled = false; test->setTestParent(this); test->runThisTest(); } @@ -245,12 +251,12 @@ void TestList::tableCellTouched(TableView* table, TableViewCell* cell) } } -TableViewCell* TestList::tableCellAtIndex(TableView* table, ssize_t idx) +TableViewCell* TestList::tableCellAtIndex(TableView *table, ssize_t idx) { auto cell = table->dequeueCell(); if (!cell) { - cell = TableViewCell::create(); + cell = TableViewCell::create(); auto label = Label::createWithTTF(_childTestNames[idx], "fonts/arial.ttf", 20.0f); label->setTag(TABEL_LABEL_TAG); label->setPosition(200, 15); @@ -265,18 +271,18 @@ TableViewCell* TestList::tableCellAtIndex(TableView* table, ssize_t idx) return cell; } -Size TestList::tableCellSizeForIndex(TableView* table, ssize_t idx) +Size TestList::tableCellSizeForIndex(TableView *table, ssize_t idx) { return Size(400, 30); } -ssize_t TestList::numberOfCellsInTableView(TableView* table) +ssize_t TestList::numberOfCellsInTableView(TableView *table) { return _childTestNames.size(); } -// TestSuite -void TestSuite::addTestCase(std::string_view testName, std::function callback) +//TestSuite +void TestSuite::addTestCase(const std::string& testName, std::function callback) { if (!testName.empty() && callback) { @@ -288,7 +294,7 @@ void TestSuite::addTestCase(std::string_view testName, std::function c static TestCase* getTestCase(Scene* scene) { auto transitionScene = dynamic_cast(scene); - TestCase* testCase = nullptr; + TestCase* testCase = nullptr; if (transitionScene) { testCase = dynamic_cast(transitionScene->getInScene()); @@ -308,8 +314,8 @@ void TestSuite::runThisTest() TestController::getInstance()->setCurrTestSuite(this); _currTestIndex = 0; - auto scene = _testCallbacks[0](); - auto testCase = getTestCase(scene); + auto scene = _testCallbacks[0](); + auto testCase = getTestCase(scene); testCase->setTestSuite(this); testCase->setTestCaseName(_childTestNames[_currTestIndex]); Director::getInstance()->replaceScene(scene); @@ -318,7 +324,7 @@ void TestSuite::runThisTest() void TestSuite::restartCurrTest() { - auto scene = _testCallbacks[_currTestIndex](); + auto scene = _testCallbacks[_currTestIndex](); auto testCase = getTestCase(scene); testCase->setTestSuite(this); testCase->setTestCaseName(_childTestNames[_currTestIndex]); @@ -330,7 +336,7 @@ void TestSuite::enterNextTest() { _currTestIndex = (_currTestIndex + 1) % _childTestNames.size(); - auto scene = _testCallbacks[_currTestIndex](); + auto scene = _testCallbacks[_currTestIndex](); auto testCase = getTestCase(scene); testCase->setTestSuite(this); testCase->setTestCaseName(_childTestNames[_currTestIndex]); @@ -349,7 +355,7 @@ void TestSuite::enterPreviousTest() _currTestIndex = (int)_childTestNames.size() - 1; } - auto scene = _testCallbacks[_currTestIndex](); + auto scene = _testCallbacks[_currTestIndex](); auto testCase = getTestCase(scene); testCase->setTestSuite(this); testCase->setTestCaseName(_childTestNames[_currTestIndex]); @@ -357,20 +363,22 @@ void TestSuite::enterPreviousTest() Director::getInstance()->replaceScene(scene); } -// TestCase +//TestCase TestCase::TestCase() - : _priorTestItem(nullptr) - , _restartTestItem(nullptr) - , _nextTestItem(nullptr) - , _titleLabel(nullptr) - , _subtitleLabel(nullptr) - , _testSuite(nullptr) - , _runTime(0.0f) +: _priorTestItem(nullptr) +, _restartTestItem(nullptr) +, _nextTestItem(nullptr) +, _titleLabel(nullptr) +, _subtitleLabel(nullptr) +, _testSuite(nullptr) +, _runTime(0.0f) { SpriteFrameCache::getInstance()->removeUnusedSpriteFrames(); Director::getInstance()->getTextureCache()->removeUnusedTextures(); - this->schedule([&](float dt) { _runTime += dt; }, "AccumulatedTimeUse"); + this->schedule([&](float dt){ + _runTime += dt; + }, "AccumulatedTimeUse"); } TestCase::~TestCase() @@ -414,31 +422,27 @@ bool TestCase::init() _titleLabel = Label::createWithTTF(ttfConfig, title()); addChild(_titleLabel, 9999); _titleLabel->setPosition(VisibleRect::center().x, VisibleRect::top().y - 30); - + ttfConfig.fontSize = 16; - _subtitleLabel = Label::createWithTTF(ttfConfig, subtitle()); + _subtitleLabel = Label::createWithTTF(ttfConfig, subtitle()); _subtitleLabel->setMaxLineWidth(VisibleRect::getVisibleRect().size.width); addChild(_subtitleLabel, 9999); _subtitleLabel->setPosition(VisibleRect::center().x, VisibleRect::top().y - 60); - + _priorTestItem = MenuItemImage::create(s_pathB1, s_pathB2, CC_CALLBACK_1(TestCase::priorTestCallback, this)); - _restartTestItem = - MenuItemImage::create(s_pathR1, s_pathR2, CC_CALLBACK_1(TestCase::restartTestCallback, this)); + _restartTestItem = MenuItemImage::create(s_pathR1, s_pathR2, CC_CALLBACK_1(TestCase::restartTestCallback, this)); _nextTestItem = MenuItemImage::create(s_pathF1, s_pathF2, CC_CALLBACK_1(TestCase::nextTestCallback, this)); - + ttfConfig.fontSize = 20; - auto backLabel = Label::createWithTTF(ttfConfig, "Back"); - auto backItem = MenuItemLabel::create(backLabel, CC_CALLBACK_1(TestCase::onBackCallback, this)); + auto backLabel = Label::createWithTTF(ttfConfig, "Back"); + auto backItem = MenuItemLabel::create(backLabel, CC_CALLBACK_1(TestCase::onBackCallback, this)); auto menu = Menu::create(_priorTestItem, _restartTestItem, _nextTestItem, backItem, nullptr); menu->setPosition(Vec2::ZERO); - _priorTestItem->setPosition(VisibleRect::center().x - _restartTestItem->getContentSize().width * 2, - VisibleRect::bottom().y + _restartTestItem->getContentSize().height / 2); - _restartTestItem->setPosition(VisibleRect::center().x, - VisibleRect::bottom().y + _restartTestItem->getContentSize().height / 2); - _nextTestItem->setPosition(VisibleRect::center().x + _restartTestItem->getContentSize().width * 2, - VisibleRect::bottom().y + _restartTestItem->getContentSize().height / 2); + _priorTestItem->setPosition(VisibleRect::center().x - _restartTestItem->getContentSize().width * 2, VisibleRect::bottom().y + _restartTestItem->getContentSize().height / 2); + _restartTestItem->setPosition(VisibleRect::center().x, VisibleRect::bottom().y + _restartTestItem->getContentSize().height / 2); + _nextTestItem->setPosition(VisibleRect::center().x + _restartTestItem->getContentSize().width * 2, VisibleRect::bottom().y + _restartTestItem->getContentSize().height / 2); backItem->setPosition(Vec2(VisibleRect::right().x - 50, VisibleRect::bottom().y + 25)); addChild(menu, 9999); @@ -460,8 +464,7 @@ void TestCase::onEnter() if (_testSuite) { - _titleLabel->setString(StringUtils::format("%d", static_cast(_testSuite->getCurrTestIndex() + 1)) + ":" + - title()); + _titleLabel->setString(StringUtils::format("%d", static_cast(_testSuite->getCurrTestIndex() + 1)) + ":" + title()); } else { diff --git a/tests/cpp-tests/Classes/BaseTest.h b/tests/cpp-tests/Classes/BaseTest.h index 526b4d16d5..b7824a917c 100644 --- a/tests/cpp-tests/Classes/BaseTest.h +++ b/tests/cpp-tests/Classes/BaseTest.h @@ -47,7 +47,7 @@ public: /** For testing whether test case not crash.*/ ROBUSTNESS, /** - * For check the correctness of regular test cases. + * For check the correctness of regular test cases. * A test case passes only if the actual output equal to the expected output. */ UNIT, @@ -67,6 +67,7 @@ public: /** Returns the time the test case needs.*/ virtual float getDuration() const; + /** Returns the expected output.*/ virtual std::string getExpectedOutput() const { return ""; } /** Returns the actual output.*/ @@ -90,14 +91,15 @@ public: /** * You should NEVER call this method, unless you know what you are doing. */ - void setTestCaseName(std::string_view name) { _testCaseName = name; } + void setTestCaseName(const std::string& name) { _testCaseName = name; } std::string getTestCaseName() const { return _testCaseName; } const cocos2d::Label* getSubtitleLable() const { return _subtitleLabel; } const cocos2d::MenuItemImage* getRestartTestItem() const { return _restartTestItem; } virtual void onEnter() override; - CC_CONSTRUCTOR_ACCESS : virtual bool init() override; +CC_CONSTRUCTOR_ACCESS: + virtual bool init() override; protected: cocos2d::MenuItemImage* _priorTestItem; @@ -136,14 +138,13 @@ public: ssize_t getChildTestCount() { return _childTestNames.size(); } /** - * You should NEVER call this method. - */ + * You should NEVER call this method. + */ void setTestParent(TestBase* parent) { _parentTest = parent; } TestBase* getTestParent() { return _parentTest; } - void setTestName(std::string_view testName) { _testName = testName; } + void setTestName(const std::string& testName) { _testName = testName; } std::string getTestName() const { return _testName; } - protected: TestBase(); @@ -156,13 +157,13 @@ protected: class TestController; /** - * TestSuite correspond to a group of test cases. - * @note Each test case should add to a TestSuite object. - */ +* TestSuite correspond to a group of test cases. +* @note Each test case should add to a TestSuite object. +*/ class TestSuite : public TestBase { public: - void addTestCase(std::string_view testName, std::function callback); + void addTestCase(const std::string& testName, std::function callback); virtual void restartCurrTest(); virtual void enterNextTest(); @@ -183,30 +184,26 @@ class TestCustomTableView; /** * An instance of TestList is a means for displaying hierarchical lists of TestSuite. */ -class TestList : public TestBase, - public cocos2d::extension::TableViewDataSource, - public cocos2d::extension::TableViewDelegate +class TestList : public TestBase, public cocos2d::extension::TableViewDataSource, public cocos2d::extension::TableViewDelegate { public: TestList(); ~TestList(); - void addTest(std::string_view testName, std::function callback); + void addTest(const std::string& testName, std::function callback); virtual void runThisTest() override; - virtual void tableCellTouched(cocos2d::extension::TableView* table, - cocos2d::extension::TableViewCell* cell) override; - virtual cocos2d::extension::TableViewCell* tableCellAtIndex(cocos2d::extension::TableView* table, - ssize_t idx) override; - virtual cocos2d::Size tableCellSizeForIndex(cocos2d::extension::TableView* table, ssize_t idx) override; - virtual ssize_t numberOfCellsInTableView(cocos2d::extension::TableView* table) override; - virtual void scrollViewDidScroll(cocos2d::extension::ScrollView* view) override {} - virtual void scrollViewDidZoom(cocos2d::extension::ScrollView* view) override {} + virtual void tableCellTouched(cocos2d::extension::TableView* table, cocos2d::extension::TableViewCell* cell) override; + virtual cocos2d::extension::TableViewCell* tableCellAtIndex(cocos2d::extension::TableView *table, ssize_t idx) override; + virtual cocos2d::Size tableCellSizeForIndex(cocos2d::extension::TableView *table, ssize_t idx) override; + virtual ssize_t numberOfCellsInTableView(cocos2d::extension::TableView *table) override; + + virtual void scrollViewDidScroll(cocos2d::extension::ScrollView* view) override{} + virtual void scrollViewDidZoom(cocos2d::extension::ScrollView* view) override{} void deatchTableView(); - private: std::vector> _testCallbacks; bool _cellTouchEnabled; @@ -216,40 +213,32 @@ private: TestCustomTableView* _tableView{}; }; -#define ADD_TEST(__className__) addTest(#__className__, []() { return new __className__; }); -#define ADD_TEST_CASE(__className__) addTestCase(#__className__, []() { return __className__::create(); }); +#define ADD_TEST(__className__) addTest( #__className__, [](){ return new __className__;} ); -#define DEFINE_TEST_LIST(__className__) \ - class __className__ : public TestList \ - { \ - public: \ - __className__(); \ - } +#define ADD_TEST_CASE(__className__) addTestCase( #__className__, [](){ return __className__::create();} ); + +#define DEFINE_TEST_LIST(__className__) class __className__ : public TestList { public: __className__();} + +#define DEFINE_TEST_SUITE(__className__) class __className__ : public TestSuite { public: __className__();} -#define DEFINE_TEST_SUITE(__className__) \ - class __className__ : public TestSuite \ - { \ - public: \ - __className__(); \ - } /** * BaseTest is retained for compatibility with older versions. - * @warning It should soon be removed. + * @warning It should soon be removed. */ class BaseTest : public cocos2d::Layer { public: virtual std::string title() const { return ""; } - virtual std::string subtitle() const { return ""; } + virtual std::string subtitle() const{ return ""; } virtual void restartCallback(cocos2d::Ref* sender) {} - virtual void nextCallback(cocos2d::Ref* sender) {} - virtual void backCallback(cocos2d::Ref* sender) {} + virtual void nextCallback(cocos2d::Ref* sender){} + virtual void backCallback(cocos2d::Ref* sender){} - virtual void onEnter() override {} - virtual void onExit() override {} + virtual void onEnter() override{} + virtual void onExit() override{} }; #endif /* defined(_CPPTESTS_BASETEST_H__) */ diff --git a/tests/cpp-tests/Classes/BillBoardTest/BillBoardTest.cpp b/tests/cpp-tests/Classes/BillBoardTest/BillBoardTest.cpp index 0e7953a735..49b908ab22 100644 --- a/tests/cpp-tests/Classes/BillBoardTest/BillBoardTest.cpp +++ b/tests/cpp-tests/Classes/BillBoardTest/BillBoardTest.cpp @@ -2,19 +2,19 @@ Copyright (c) 2012 cocos2d-x.org Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,6 +34,7 @@ USING_NS_CC; USING_NS_CC_EXT; using namespace cocos2d::ui; + BillBoardTests::BillBoardTests() { ADD_TEST_CASE(BillBoardRotationTest); @@ -48,48 +49,51 @@ BillBoardTests::BillBoardTests() BillBoardRotationTest::BillBoardRotationTest() { auto root = Sprite3D::create(); - root->setPositionNormalized(Vec2(0.5f, 0.25f)); + root->setPositionNormalized(Vec2(0.5f,0.25f)); addChild(root); - + auto model = Sprite3D::create("Sprite3DTest/orc.c3b"); model->setScale(5); - model->setRotation3D(Vec3(0.0f, 180.0f, 0.0f)); + model->setRotation3D(Vec3(0.0f,180.0f,0.0f)); root->addChild(model); - + auto bill = BillBoard::create(); bill->setPosition(0, 120); root->addChild(bill); - + auto sp = Sprite::create("Images/SpookyPeas.png"); sp->setScale(2); bill->addChild(sp); - + auto lbl = Label::create(); lbl->setPosition(0.0f, 30.0f); lbl->setString("+100"); bill->addChild(lbl); - - auto r = RotateBy::create(10, Vec3(0.0f, 360.0f, 0.0f)); + + auto r = RotateBy::create(10, Vec3(0.0f,360.0f,0.0f)); auto rp = RepeatForever::create(r); root->runAction(rp); - - auto jump = JumpBy::create(1, Vec2(0.0f, 0.0f), 30, 1); + + auto jump = JumpBy::create(1, Vec2(0.0f, 0.0f), 30, 1); auto scale = ScaleBy::create(2.f, 2.f, 2.f, 0.1f); - auto seq = Sequence::create(jump, scale, NULL); - + auto seq = Sequence::create(jump,scale, NULL); + auto rot = RotateBy::create(2, Vec3(-90.0f, 0.0f, 0.0f)); - auto act = Spawn::create(seq, rot, NULL); - + auto act = Spawn::create(seq, rot,NULL); + auto scale2 = scale->reverse(); - auto rot2 = rot->reverse(); - auto act2 = Spawn::create(scale2, rot2, NULL); - - auto seq2 = Sequence::create(act, act2, NULL); + auto rot2 = rot->reverse(); + auto act2 = Spawn::create(scale2, rot2, NULL); + + auto seq2 = Sequence::create(act, act2, NULL); auto repeat = RepeatForever::create(seq2); model->runAction(repeat); } -BillBoardRotationTest::~BillBoardRotationTest() {} +BillBoardRotationTest::~BillBoardRotationTest() +{ + +} std::string BillBoardRotationTest::title() const { @@ -106,37 +110,38 @@ std::string BillBoardRotationTest::subtitle() const // Billboard Rendering Test // //------------------------------------------------------------------ -BillBoardTest::BillBoardTest() : _camera(nullptr) +BillBoardTest::BillBoardTest() +: _camera(nullptr) { - // Create touch listener - auto listener = EventListenerTouchAllAtOnce::create(); + //Create touch listener + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesMoved = CC_CALLBACK_2(BillBoardTest::onTouchesMoved, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - - auto layer3D = Layer::create(); - addChild(layer3D, 0); + + auto layer3D=Layer::create(); + addChild(layer3D,0); _layerBillBoard = layer3D; - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); if (_camera == nullptr) { - _camera = Camera::createPerspective(60, (float)s.width / s.height, 1, 500); + _camera=Camera::createPerspective(60, (float)s.width/s.height, 1, 500); _camera->setCameraFlag(CameraFlag::USER1); _layerBillBoard->addChild(_camera); } - // Create rotating billboards + //Create rotating billboards std::string imgs[3] = {"Images/Icon.png", "Images/r2.png"}; for (unsigned int i = 0; i < 4; ++i) { - Layer* layer = Layer::create(); + Layer *layer = Layer::create(); auto billboard = BillBoard::create(imgs[(unsigned int)(CCRANDOM_0_1() * 1 + 0.5f)]); billboard->setScale(0.5f); - billboard->setPosition3D(Vec3(0.0f, 0.0f, CCRANDOM_MINUS1_1() * 150.0f)); + billboard->setPosition3D(Vec3(0.0f, 0.0f, CCRANDOM_MINUS1_1() * 150.0f)); billboard->setOpacity(static_cast(CCRANDOM_0_1() * 128 + 128)); _billboards.push_back(billboard); layer->addChild(billboard); _layerBillBoard->addChild(layer); - layer->runAction(RepeatForever::create(RotateBy::create(CCRANDOM_0_1() * 10, Vec3(0.0f, 45.0f, 0.0f)))); + layer->runAction( RepeatForever::create( RotateBy::create( CCRANDOM_0_1() * 10, Vec3(0.0f, 45.0f, 0.0f) ) ) ); } { @@ -153,64 +158,62 @@ BillBoardTest::BillBoardTest() : _camera(nullptr) auto sprite3d = Sprite3D::create("Sprite3DTest/orc.c3t"); sprite3d->setScale(2.0f); sprite3d->addChild(billboard); - sprite3d->runAction(RepeatForever::create(RotateBy::create(10.0f, Vec3(0.0f, 360.0f, 0.0f)))); + sprite3d->runAction( RepeatForever::create( RotateBy::create( 10.0f, Vec3(0.0f, 360.0f, 0.0f) ) ) ); _layerBillBoard->addChild(sprite3d); } - addNewBillBoardWithCoords(Vec3(20.0f, 5.0f, 0.0f)); - addNewBillBoardWithCoords(Vec3(60.0f, 5.0f, 0.0f)); - addNewBillBoardWithCoords(Vec3(100.0f, 5.0f, 0.0f)); - addNewBillBoardWithCoords(Vec3(140.0f, 5.0f, 0.0f)); - addNewBillBoardWithCoords(Vec3(180.0f, 5.0f, 0.0f)); - - addNewAniBillBoardWithCoords(Vec3(-20.0f, 0.0f, 0.0f)); - addNewAniBillBoardWithCoords(Vec3(-60.0f, 0.0f, 0.0f)); - addNewAniBillBoardWithCoords(Vec3(-100.0f, 0.0f, 0.0f)); - addNewAniBillBoardWithCoords(Vec3(-140.0f, 0.0f, 0.0f)); - addNewAniBillBoardWithCoords(Vec3(-180.0f, 0.0f, 0.0f)); - + addNewBillBoardWithCoords(Vec3(20.0f,5.0f,0.0f)); + addNewBillBoardWithCoords(Vec3(60.0f,5.0f,0.0f)); + addNewBillBoardWithCoords(Vec3(100.0f,5.0f,0.0f)); + addNewBillBoardWithCoords(Vec3(140.0f,5.0f,0.0f)); + addNewBillBoardWithCoords(Vec3(180.0f,5.0f,0.0f)); + + addNewAniBillBoardWithCoords(Vec3(-20.0f,0.0f,0.0f)); + addNewAniBillBoardWithCoords(Vec3(-60.0f,0.0f,0.0f)); + addNewAniBillBoardWithCoords(Vec3(-100.0f,0.0f,0.0f)); + addNewAniBillBoardWithCoords(Vec3(-140.0f,0.0f,0.0f)); + addNewAniBillBoardWithCoords(Vec3(-180.0f,0.0f,0.0f)); + _camera->setPosition3D(Vec3(0.0f, 100.0f, 230.0f)); - _camera->lookAt(Vec3(0, 0, 0), Vec3(0.0f, 1.0f, 0.0f)); + _camera->lookAt(Vec3(0,0,0), Vec3(0.0f,1.0f,0.0f)); TTFConfig ttfConfig("fonts/arial.ttf", 16); - auto label1 = Label::createWithTTF(ttfConfig, "rotate+"); - auto menuItem1 = MenuItemLabel::create(label1, CC_CALLBACK_1(BillBoardTest::rotateCameraCallback, this, 10)); - auto label2 = Label::createWithTTF(ttfConfig, "rotate-"); - auto menuItem2 = MenuItemLabel::create(label2, CC_CALLBACK_1(BillBoardTest::rotateCameraCallback, this, -10)); - auto menu = Menu::create(menuItem1, menuItem2, nullptr); + auto label1 = Label::createWithTTF(ttfConfig,"rotate+"); + auto menuItem1 = MenuItemLabel::create(label1, CC_CALLBACK_1(BillBoardTest::rotateCameraCallback,this,10)); + auto label2 = Label::createWithTTF(ttfConfig,"rotate-"); + auto menuItem2 = MenuItemLabel::create(label2, CC_CALLBACK_1(BillBoardTest::rotateCameraCallback,this,-10)); + auto menu = Menu::create(menuItem1, menuItem2, nullptr); menu->setPosition(Vec2::ZERO); - menuItem1->setPosition(Vec2(s.width - 80, VisibleRect::top().y - 160)); - menuItem2->setPosition(Vec2(s.width - 80, VisibleRect::top().y - 190)); + menuItem1->setPosition( Vec2( s.width-80, VisibleRect::top().y-160) ); + menuItem2->setPosition( Vec2( s.width-80, VisibleRect::top().y-190) ); addChild(menu, 0); _layerBillBoard->setCameraMask(2); - - label1 = Label::createWithTTF(ttfConfig, "Point Oriented"); - menuItem1 = MenuItemLabel::create(label1, CC_CALLBACK_1(BillBoardTest::menuCallback_orientedPoint, this)); - label2 = Label::createWithTTF(ttfConfig, "Plane Oriented"); - menuItem2 = MenuItemLabel::create(label2, CC_CALLBACK_1(BillBoardTest::menuCallback_orientedPlane, this)); - menuItem1->setPosition(Vec2(s.width - 80, VisibleRect::top().y - 100)); - menuItem2->setPosition(Vec2(s.width - 80, VisibleRect::top().y - 130)); - + + label1 = Label::createWithTTF(ttfConfig,"Point Oriented"); + menuItem1 = MenuItemLabel::create(label1,CC_CALLBACK_1(BillBoardTest::menuCallback_orientedPoint,this) ); + label2 = Label::createWithTTF(ttfConfig,"Plane Oriented"); + menuItem2 = MenuItemLabel::create(label2,CC_CALLBACK_1(BillBoardTest::menuCallback_orientedPlane,this) ); + menuItem1->setPosition( Vec2( s.width-80, VisibleRect::top().y-100) ); + menuItem2->setPosition( Vec2( s.width-80, VisibleRect::top().y-130) ); + menu = Menu::create(menuItem1, menuItem2, nullptr); - menu->setPosition(Vec2(0, 0)); + menu->setPosition(Vec2(0,0)); this->addChild(menu, 10); menuCallback_orientedPoint(nullptr); - + schedule(CC_SCHEDULE_SELECTOR(BillBoardTest::update)); } void BillBoardTest::menuCallback_orientedPoint(Ref* sender) { - for (auto& billboard : _billboards) - { + for (auto& billboard : _billboards) { billboard->setMode(BillBoard::Mode::VIEW_POINT_ORIENTED); } } void BillBoardTest::menuCallback_orientedPlane(Ref* sender) { - for (auto& billboard : _billboards) - { + for (auto& billboard : _billboards) { billboard->setMode(BillBoard::Mode::VIEW_PLANE_ORIENTED); } } @@ -239,7 +242,7 @@ void BillBoardTest::addNewBillBoardWithCoords(Vec3 p) billboard->setScale(0.5f); billboard->setPosition3D(Vec3(p.x, p.y, -150.0f + 30 * i)); billboard->setOpacity(static_cast(CCRANDOM_0_1() * 128 + 128)); - + _layerBillBoard->addChild(billboard); _billboards.push_back(billboard); } @@ -250,11 +253,11 @@ void BillBoardTest::addNewAniBillBoardWithCoords(Vec3 p) { auto billboardAni = BillBoard::create("Images/grossini.png"); billboardAni->setScale(0.5f); - billboardAni->setPosition3D(Vec3(p.x, p.y, -150.0f + 30 * i)); + billboardAni->setPosition3D(Vec3(p.x, p.y, -150.0f + 30 * i)); _layerBillBoard->addChild(billboardAni); auto animation = Animation::create(); - for (int i = 1; i < 15; i++) + for( int i=1;i<15;i++) { char szName1[100] = {0}; sprintf(szName1, "Images/grossini_dance_%02d.png", i); @@ -270,35 +273,37 @@ void BillBoardTest::addNewAniBillBoardWithCoords(Vec3 p) _billboards.push_back(billboardAni); } } -void BillBoardTest::update(float dt) {} +void BillBoardTest::update(float dt) +{ +} void BillBoardTest::onTouchesMoved(const std::vector& touches, Event* event) { - if (touches.size() == 1) + if(touches.size()==1) { - auto touch = touches[0]; - auto location = touch->getLocation(); + auto touch = touches[0]; + auto location = touch->getLocation(); auto PreviousLocation = touch->getPreviousLocation(); - Point newPos = PreviousLocation - location; + Point newPos = PreviousLocation - location; Vec3 cameraDir; Vec3 cameraRightDir; _camera->getNodeToWorldTransform().getForwardVector(&cameraDir); cameraDir.normalize(); - cameraDir.y = 0; + cameraDir.y=0; _camera->getNodeToWorldTransform().getRightVector(&cameraRightDir); cameraRightDir.normalize(); - cameraRightDir.y = 0; - Vec3 cameraPos = _camera->getPosition3D(); - cameraPos += cameraDir * newPos.y * 0.5; - cameraPos += cameraRightDir * newPos.x * 0.5; - _camera->setPosition3D(cameraPos); + cameraRightDir.y=0; + Vec3 cameraPos= _camera->getPosition3D(); + cameraPos+=cameraDir*newPos.y*0.5; + cameraPos+=cameraRightDir*newPos.x*0.5; + _camera->setPosition3D(cameraPos); } } -void BillBoardTest::rotateCameraCallback(Ref* sender, float value) +void BillBoardTest::rotateCameraCallback(Ref* sender,float value) { - Vec3 rotation3D = _camera->getRotation3D(); - rotation3D.y += value; + Vec3 rotation3D= _camera->getRotation3D(); + rotation3D.y+= value; _camera->setRotation3D(rotation3D); } diff --git a/tests/cpp-tests/Classes/BillBoardTest/BillBoardTest.h b/tests/cpp-tests/Classes/BillBoardTest/BillBoardTest.h index 7290910651..d537790897 100644 --- a/tests/cpp-tests/Classes/BillBoardTest/BillBoardTest.h +++ b/tests/cpp-tests/Classes/BillBoardTest/BillBoardTest.h @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2013 cocos2d-x.org Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -29,11 +29,10 @@ #include "../BaseTest.h" #include -namespace cocos2d -{ -class BillBoard; -class Camera; -} // namespace cocos2d +namespace cocos2d { + class BillBoard; + class Camera; +} class BillBoardRotationTest : public TestCase { @@ -43,7 +42,7 @@ public: virtual ~BillBoardRotationTest(); virtual std::string title() const override; virtual std::string subtitle() const override; - + protected: }; @@ -58,15 +57,15 @@ public: virtual void update(float dt) override; void addNewBillBoardWithCoords(cocos2d::Vec3 p); void addNewAniBillBoardWithCoords(cocos2d::Vec3 p); - void rotateCameraCallback(cocos2d::Ref* sender, float value); + void rotateCameraCallback(cocos2d::Ref* sender,float value); void onTouchesMoved(const std::vector& touches, cocos2d::Event* event); - + void menuCallback_orientedPoint(cocos2d::Ref* sender); void menuCallback_orientedPlane(cocos2d::Ref* sender); - + protected: - cocos2d::Camera* _camera; - cocos2d::Layer* _layerBillBoard; + cocos2d::Camera* _camera; + cocos2d::Layer* _layerBillBoard; std::vector _billboards; }; diff --git a/tests/cpp-tests/Classes/Box2DTest/Box2dTest.cpp b/tests/cpp-tests/Classes/Box2DTest/Box2dTest.cpp index 1461f85058..52f3a16bd4 100644 --- a/tests/cpp-tests/Classes/Box2DTest/Box2dTest.cpp +++ b/tests/cpp-tests/Classes/Box2DTest/Box2dTest.cpp @@ -29,16 +29,18 @@ #include "renderer/CCRenderer.h" #include "renderer/CCCustomCommand.h" + + USING_NS_CC; USING_NS_CC_EXT; #define PTM_RATIO 32 -enum -{ +enum { kTagParentNode = 1, }; + Box2DTests::Box2DTests() { ADD_TEST_CASE(Box2DTest); @@ -49,6 +51,7 @@ std::string Box2DTest::title() const return "Box2D - Basic"; } + bool Box2DTest::init() { if (!TestCase::init()) @@ -57,34 +60,35 @@ bool Box2DTest::init() } auto dispatcher = Director::getInstance()->getEventDispatcher(); - auto touchListener = EventListenerTouchAllAtOnce::create(); + auto touchListener = EventListenerTouchAllAtOnce::create(); touchListener->onTouchesEnded = CC_CALLBACK_2(Box2DTest::onTouchesEnded, this); dispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); + // init physics this->initPhysics(); // create reset button this->createResetButton(); - // Set up sprite + //Set up sprite #if 1 // Use batch node. Faster - auto parent = SpriteBatchNode::create("Images/blocks.png", 100); + auto parent = SpriteBatchNode::create("Images/blocks.png", 100); _spriteTexture = parent->getTexture(); #else // doesn't use batch node. Slower _spriteTexture = Director::getInstance()->getTextureCache()->addImage("Images/blocks.png"); - auto parent = Node::create(); + auto parent = Node::create(); #endif addChild(parent, 0, kTagParentNode); + addNewSpriteAtPosition(VisibleRect::center()); - auto label = Label::createWithTTF("Tap screen add boxes.\nSome objects be only visible with debug on.", - "fonts/Marker Felt.ttf", 12.0f); + auto label = Label::createWithTTF("Tap screen add boxes.\nSome objects be only visible with debug on.", "fonts/Marker Felt.ttf", 12.0f); addChild(label, 0); label->setColor(Color3B(0, 0, 255)); - label->setPosition(VisibleRect::center().x - 50, VisibleRect::top().y - 60); + label->setPosition(VisibleRect::center().x-50, VisibleRect::top().y - 60); // menu for debug layer MenuItemFont::setFontSize(18); @@ -103,19 +107,26 @@ bool Box2DTest::init() return true; } -Box2DTest::Box2DTest() : _spriteTexture(nullptr), world(nullptr) {} +Box2DTest::Box2DTest() + : _spriteTexture(nullptr) + , world(nullptr) +{ + +} Box2DTest::~Box2DTest() { CC_SAFE_DELETE(world); } + void Box2DTest::toggleDebugCallback(Ref* sender) { showDebugDraw = !showDebugDraw; - drawBox2D->clear(); + drawBox2D->clear(); } + void Box2DTest::initPhysics() { b2Vec2 gravity; @@ -129,7 +140,7 @@ void Box2DTest::initPhysics() // Define the ground body. b2BodyDef groundBodyDef; - groundBodyDef.position.Set(0, 0); // bottom-left corner + groundBodyDef.position.Set(0, 0); // bottom-left corner // Call the body factory which allocates memory for the ground body // from a pool and creates the ground box shape (also from a pool). @@ -140,25 +151,22 @@ void Box2DTest::initPhysics() b2EdgeShape groundBox; // bottom - groundBox.SetTwoSided(b2Vec2(VisibleRect::leftBottom().x / PTM_RATIO, VisibleRect::leftBottom().y / PTM_RATIO), - b2Vec2(VisibleRect::rightBottom().x / PTM_RATIO, VisibleRect::rightBottom().y / PTM_RATIO)); + groundBox.SetTwoSided(b2Vec2(VisibleRect::leftBottom().x / PTM_RATIO, VisibleRect::leftBottom().y / PTM_RATIO), b2Vec2(VisibleRect::rightBottom().x / PTM_RATIO, VisibleRect::rightBottom().y / PTM_RATIO)); groundBody->CreateFixture(&groundBox, 0); // top - groundBox.SetTwoSided(b2Vec2(VisibleRect::leftTop().x / PTM_RATIO, VisibleRect::leftTop().y / PTM_RATIO), - b2Vec2(VisibleRect::rightTop().x / PTM_RATIO, VisibleRect::rightTop().y / PTM_RATIO)); + groundBox.SetTwoSided(b2Vec2(VisibleRect::leftTop().x / PTM_RATIO, VisibleRect::leftTop().y / PTM_RATIO), b2Vec2(VisibleRect::rightTop().x / PTM_RATIO, VisibleRect::rightTop().y / PTM_RATIO)); groundBody->CreateFixture(&groundBox, 0); // left - groundBox.SetTwoSided(b2Vec2(VisibleRect::leftTop().x / PTM_RATIO, VisibleRect::leftTop().y / PTM_RATIO), - b2Vec2(VisibleRect::leftBottom().x / PTM_RATIO, VisibleRect::leftBottom().y / PTM_RATIO)); + groundBox.SetTwoSided(b2Vec2(VisibleRect::leftTop().x / PTM_RATIO, VisibleRect::leftTop().y / PTM_RATIO), b2Vec2(VisibleRect::leftBottom().x / PTM_RATIO, VisibleRect::leftBottom().y / PTM_RATIO)); groundBody->CreateFixture(&groundBox, 0); // right - groundBox.SetTwoSided(b2Vec2(VisibleRect::rightBottom().x / PTM_RATIO, VisibleRect::rightBottom().y / PTM_RATIO), - b2Vec2(VisibleRect::rightTop().x / PTM_RATIO, VisibleRect::rightTop().y / PTM_RATIO)); + groundBox.SetTwoSided(b2Vec2(VisibleRect::rightBottom().x / PTM_RATIO, VisibleRect::rightBottom().y / PTM_RATIO), b2Vec2(VisibleRect::rightTop().x / PTM_RATIO, VisibleRect::rightTop().y / PTM_RATIO)); groundBody->CreateFixture(&groundBox, 0); + // Small triangle b2Vec2 vertices[3]; vertices[0].Set(-1.0f, 0.0f); @@ -169,7 +177,7 @@ void Box2DTest::initPhysics() polygon.Set(vertices, 3); b2FixtureDef triangleShapeDef; - triangleShapeDef.shape = &polygon; + triangleShapeDef.shape = &polygon; triangleShapeDef.density = 1.0f; b2BodyDef triangleBodyDef; @@ -194,7 +202,7 @@ void Box2DTest::initPhysics() polygon.SetAsBox(1.0f, 0.5f); b2FixtureDef boxShapeDef; - boxShapeDef.shape = &polygon; + boxShapeDef.shape = &polygon; boxShapeDef.density = 1.0f; b2BodyDef boxBodyDef; @@ -216,7 +224,7 @@ void Box2DTest::initPhysics() circle.m_radius = 1.0f; b2FixtureDef circleShapeDef; - circleShapeDef.shape = &circle; + circleShapeDef.shape = &circle; circleShapeDef.density = 1.0f; b2BodyDef circleBodyDef; @@ -239,15 +247,16 @@ void Box2DTest::initPhysics() flags += 0 * b2Draw::e_aabbBit; flags += 0 * b2Draw::e_centerOfMassBit; g_debugDraw.SetFlags(flags); - g_debugDraw.mRatio = PTM_RATIO; - g_debugDraw.debugNodeOffset = {0, 0}; + g_debugDraw.mRatio = PTM_RATIO; + g_debugDraw.debugNodeOffset = { 0, 0 }; world->SetDebugDraw(&g_debugDraw); } void Box2DTest::createResetButton() { - auto reset = MenuItemImage::create("Images/r1.png", "Images/r2.png", - [&](Ref* sender) { getTestSuite()->restartCurrTest(); }); + auto reset = MenuItemImage::create("Images/r1.png", "Images/r2.png", [&](Ref* sender) { + getTestSuite()->restartCurrTest(); + }); auto menu = Menu::create(reset, nullptr); @@ -260,7 +269,7 @@ void Box2DTest::addNewSpriteAtPosition(Vec2 p) CCLOG("Add sprite %0.2f x %02.f", p.x, p.y); // Define the dynamic body. - // Set up a 1m squared box in the physics world + //Set up a 1m squared box in the physics world b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; bodyDef.position.Set(p.x / PTM_RATIO, p.y / PTM_RATIO); @@ -271,21 +280,21 @@ void Box2DTest::addNewSpriteAtPosition(Vec2 p) // Define another box shape for our dynamic body. b2PolygonShape dynamicBox; - dynamicBox.SetAsBox(.5f, .5f); // These are mid points for our 1m box + dynamicBox.SetAsBox(.5f, .5f);//These are mid points for our 1m box // Define the dynamic body fixture. b2FixtureDef fixtureDef; - fixtureDef.shape = &dynamicBox; - fixtureDef.density = 1.0f; + fixtureDef.shape = &dynamicBox; + fixtureDef.density = 1.0f; fixtureDef.friction = 0.3f; body->CreateFixture(&fixtureDef); auto parent = this->getChildByTag(kTagParentNode); - // We have a 64x64 sprite sheet with 4 different 32x32 images. The following code is - // just randomly picking one of the images - int idx = (CCRANDOM_0_1() > .5 ? 0 : 1); - int idy = (CCRANDOM_0_1() > .5 ? 0 : 1); + //We have a 64x64 sprite sheet with 4 different 32x32 images. The following code is + //just randomly picking one of the images + int idx = (CCRANDOM_0_1() > .5 ? 0 : 1); + int idy = (CCRANDOM_0_1() > .5 ? 0 : 1); auto sprite = PhysicsSpriteBox2D::createWithTexture(_spriteTexture, Rect(32 * idx, 32 * idy, 32, 32)); parent->addChild(sprite); sprite->setB2Body(body); @@ -295,10 +304,10 @@ void Box2DTest::addNewSpriteAtPosition(Vec2 p) void Box2DTest::update(float dt) { - // It is recommended that a fixed time step is used with Box2D for stability - // of the simulation, however, we are using a variable time step here. - // You need to make an informed choice, the following URL is useful - // http://gafferongames.com/game-physics/fix-your-timestep/ + //It is recommended that a fixed time step is used with Box2D for stability + //of the simulation, however, we are using a variable time step here. + //You need to make an informed choice, the following URL is useful + //http://gafferongames.com/game-physics/fix-your-timestep/ int velocityIterations = 8; int positionIterations = 1; @@ -307,17 +316,19 @@ void Box2DTest::update(float dt) // generally best to keep the time step and iterations fixed. world->Step(dt, velocityIterations, positionIterations); + // Debug draw if (showDebugDraw) { drawBox2D->clear(); world->DebugDraw(); } + } void Box2DTest::onTouchesEnded(const std::vector& touches, Event* event) { - // Add a new body/atlas sprite at the touched location + //Add a new body/atlas sprite at the touched location for (auto& touch : touches) { diff --git a/tests/cpp-tests/Classes/Box2DTest/Box2dTest.h b/tests/cpp-tests/Classes/Box2DTest/Box2dTest.h index f11f92fe08..d98406d746 100644 --- a/tests/cpp-tests/Classes/Box2DTest/Box2dTest.h +++ b/tests/cpp-tests/Classes/Box2DTest/Box2dTest.h @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. Copyright (c) 2021 @aismann; Peter Eismann, Germany; dreifrankensoft - + 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 @@ -33,6 +33,7 @@ DEFINE_TEST_SUITE(Box2DTests); + class Box2DTest : public TestCase { public: @@ -60,6 +61,6 @@ private: cocos2d::DrawNode* drawBox2D; cocos2d::extension::PhysicsDebugNodeBox2D g_debugDraw; bool showDebugDraw = true; -}; +} ; #endif \ No newline at end of file diff --git a/tests/cpp-tests/Classes/Box2DTestBed/Box2DTestBed.cpp b/tests/cpp-tests/Classes/Box2DTestBed/Box2DTestBed.cpp index 76c03de9ff..1b95100a08 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/Box2DTestBed.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/Box2DTestBed.cpp @@ -34,9 +34,8 @@ USING_NS_CC; USING_NS_CC_EXT; -enum -{ - kTagParentNode = 1, +enum { + kTagParentNode = 1, }; Settings settings; @@ -44,31 +43,34 @@ cocos2d::Label* labelDebugDraw; enum { - kTagBox2DNode, + kTagBox2DNode, }; -TestEntry g_testEntries[MAX_TESTS] = {{nullptr}}; -int g_testCount = 0; + +TestEntry g_testEntries[MAX_TESTS] = { {nullptr} }; +int g_testCount = 0; int RegisterTest(const char* category, const char* name, TestCreateFcn* fcn) { - int index = g_testCount; - if (index < MAX_TESTS) - { - g_testEntries[index] = {category, name, fcn}; - ++g_testCount; - return index; - } + int index = g_testCount; + if (index < MAX_TESTS) + { + g_testEntries[index] = { category, name, fcn }; + ++g_testCount; + return index; + } - return -1; + return -1; } Box2DTestBedTests::Box2DTestBedTests() { - for (int entryId = 0; entryId < g_testCount; ++entryId) - { - addTestCase(g_testEntries[entryId].name, [entryId]() { return Box2DTestBed::createWithEntryID(entryId); }); - } + for (int entryId = 0; entryId < g_testCount; ++entryId) + { + addTestCase(g_testEntries[entryId].name, [entryId]() { + return Box2DTestBed::createWithEntryID(entryId); + }); + } } //------------------------------------------------------------------ @@ -77,202 +79,205 @@ Box2DTestBedTests::Box2DTestBedTests() // //------------------------------------------------------------------ -Box2DTestBed::Box2DTestBed() {} +Box2DTestBed::Box2DTestBed() +{ +} Box2DTestBed::~Box2DTestBed() { - Layer::_eventDispatcher->removeEventListener(_touchListener); + Layer::_eventDispatcher->removeEventListener(_touchListener); } Box2DTestBed* Box2DTestBed::createWithEntryID(int entryId) { - auto layer = new Box2DTestBed(); - layer->initWithEntryID(entryId); - // layer->autorelease(); + auto layer = new Box2DTestBed(); + layer->initWithEntryID(entryId); +// layer->autorelease(); - return layer; + return layer; } bool Box2DTestBed::initWithEntryID(int entryId) { - if (!TestCase::init()) - { - return false; - } - auto director = Director::getInstance(); - Vec2 visibleOrigin = director->getVisibleOrigin(); - Size visibleSize = director->getVisibleSize(); + if (!TestCase::init()) + { + return false; + } + auto director = Director::getInstance(); + Vec2 visibleOrigin = director->getVisibleOrigin(); + Size visibleSize = director->getVisibleSize(); - m_entryID = entryId; + m_entryID = entryId; - m_entry = g_testEntries + entryId; - m_test = m_entry->createFcn(); + m_entry = g_testEntries + entryId; + m_test = m_entry->createFcn(); - debugDrawNode = g_debugDraw.GetDrawNode(); - m_test->debugDrawNode = debugDrawNode; - m_test->g_debugDraw = g_debugDraw; + debugDrawNode = g_debugDraw.GetDrawNode(); + m_test->debugDrawNode = debugDrawNode; + m_test->g_debugDraw = g_debugDraw; - TestCase::addChild(debugDrawNode, 100); + TestCase::addChild(debugDrawNode, 100); - // init physics - this->initPhysics(); + // init physics + this->initPhysics(); - auto label = Label::createWithTTF(m_entry->name, "fonts/arial.ttf", 28); - TestCase::addChild(label, 1); - label->setPosition(visibleOrigin.x + visibleSize.width / 2, visibleOrigin.y + visibleSize.height - 50); + auto label = Label::createWithTTF(m_entry->name, "fonts/arial.ttf", 28); + TestCase::addChild(label, 1); + label->setPosition(visibleOrigin.x + visibleSize.width / 2, visibleOrigin.y + visibleSize.height - 50); - // Adds touch event listener - _touchListener = EventListenerTouchOneByOne::create(); - _touchListener->setSwallowTouches(true); - _touchListener->onTouchBegan = CC_CALLBACK_2(Box2DTestBed::onTouchBegan, this); - _touchListener->onTouchMoved = CC_CALLBACK_2(Box2DTestBed::onTouchMoved, this); - _touchListener->onTouchEnded = CC_CALLBACK_2(Box2DTestBed::onTouchEnded, this); - TestCase::_eventDispatcher->addEventListenerWithFixedPriority(_touchListener, 10); + // Adds touch event listener + _touchListener = EventListenerTouchOneByOne::create(); + _touchListener->setSwallowTouches(true); + _touchListener->onTouchBegan = CC_CALLBACK_2(Box2DTestBed::onTouchBegan, this); + _touchListener->onTouchMoved = CC_CALLBACK_2(Box2DTestBed::onTouchMoved, this); + _touchListener->onTouchEnded = CC_CALLBACK_2(Box2DTestBed::onTouchEnded, this); + TestCase::_eventDispatcher->addEventListenerWithFixedPriority(_touchListener,10); - // Adds Keyboard event listener - _keyboardListener = EventListenerKeyboard::create(); - _keyboardListener->onKeyPressed = CC_CALLBACK_2(Box2DTestBed::onKeyPressed, this); - _keyboardListener->onKeyReleased = CC_CALLBACK_2(Box2DTestBed::onKeyReleased, this); - TestCase::_eventDispatcher->addEventListenerWithFixedPriority(_keyboardListener, 11); + // Adds Keyboard event listener + _keyboardListener = EventListenerKeyboard::create(); + _keyboardListener->onKeyPressed = CC_CALLBACK_2(Box2DTestBed::onKeyPressed, this); + _keyboardListener->onKeyReleased = CC_CALLBACK_2(Box2DTestBed::onKeyReleased, this); + TestCase::_eventDispatcher->addEventListenerWithFixedPriority(_keyboardListener,11); - auto _mouseListener = EventListenerMouse::create(); - _mouseListener->onMouseMove = CC_CALLBACK_1(Box2DTestBed::onMouseMove, this); - _mouseListener->onMouseUp = CC_CALLBACK_1(Box2DTestBed::onMouseUp, this); - _mouseListener->onMouseDown = CC_CALLBACK_1(Box2DTestBed::onMouseDown, this); - _mouseListener->onMouseScroll = CC_CALLBACK_1(Box2DTestBed::onMouseScroll, this); - TestCase::_eventDispatcher->addEventListenerWithFixedPriority(_mouseListener, 12); + auto _mouseListener = EventListenerMouse::create(); + _mouseListener->onMouseMove = CC_CALLBACK_1(Box2DTestBed::onMouseMove, this); + _mouseListener->onMouseUp = CC_CALLBACK_1(Box2DTestBed::onMouseUp, this); + _mouseListener->onMouseDown = CC_CALLBACK_1(Box2DTestBed::onMouseDown, this); + _mouseListener->onMouseScroll = CC_CALLBACK_1(Box2DTestBed::onMouseScroll, this); + TestCase::_eventDispatcher->addEventListenerWithFixedPriority(_mouseListener, 12); - // Demo messageString - labelDebugDraw = Label::createWithTTF("TEST", "fonts/arial.ttf", 8.0f); - labelDebugDraw->setAnchorPoint(Vec2(0, 1)); - labelDebugDraw->setPosition(VisibleRect::left().x, VisibleRect::top().y - 10); - labelDebugDraw->setColor(Color3B::WHITE); - TestCase::addChild(labelDebugDraw, 100); + // Demo messageString + labelDebugDraw = Label::createWithTTF("TEST", "fonts/arial.ttf", 8.0f); + labelDebugDraw->setAnchorPoint(Vec2(0, 1)); + labelDebugDraw->setPosition(VisibleRect::left().x, VisibleRect::top().y - 10); + labelDebugDraw->setColor(Color3B::WHITE); + TestCase::addChild(labelDebugDraw, 100); - TestCase::scheduleUpdate(); + TestCase::scheduleUpdate(); - return true; + return true; } bool Box2DTestBed::onTouchBegan(Touch* touch, Event* event) { - auto location = touch->getLocation() - g_debugDraw.debugNodeOffset; - b2Vec2 pos = {location.x / g_debugDraw.mRatio, location.y / g_debugDraw.mRatio}; - return m_test->MouseDown(pos); + auto location = touch->getLocation() - g_debugDraw.debugNodeOffset; + b2Vec2 pos = { location.x / g_debugDraw.mRatio, location.y / g_debugDraw.mRatio }; + return m_test->MouseDown(pos); } void Box2DTestBed::onTouchMoved(Touch* touch, Event* event) { - auto location = touch->getLocation() - g_debugDraw.debugNodeOffset; - b2Vec2 pos = {location.x / g_debugDraw.mRatio, location.y / g_debugDraw.mRatio}; - m_test->MouseMove(pos); + auto location = touch->getLocation() - g_debugDraw.debugNodeOffset; + b2Vec2 pos = { location.x / g_debugDraw.mRatio, location.y / g_debugDraw.mRatio }; + m_test->MouseMove(pos); } void Box2DTestBed::onTouchEnded(Touch* touch, Event* event) { - auto location = touch->getLocation() - g_debugDraw.debugNodeOffset; - b2Vec2 pos = {location.x / g_debugDraw.mRatio, location.y / g_debugDraw.mRatio}; - m_test->MouseUp(pos); + auto location = touch->getLocation() - g_debugDraw.debugNodeOffset; + b2Vec2 pos = { location.x / g_debugDraw.mRatio, location.y / g_debugDraw.mRatio }; + m_test->MouseUp(pos); } void Box2DTestBed::onKeyPressed(EventKeyboard::KeyCode code, Event* event) { - CCLOG("onKeyPressed, keycode: %d", static_cast(code)); - m_test->Keyboard((static_cast(code) - 59)); // its a bad hack! + CCLOG("onKeyPressed, keycode: %d", static_cast(code)); + m_test->Keyboard((static_cast(code) - 59)); // its a bad hack! } void Box2DTestBed::onKeyReleased(EventKeyboard::KeyCode code, Event* event) { - CCLOG("onKeyPressed, keycode: %d", static_cast(code)); - m_test->KeyboardUp((static_cast(code) - 59)); // its a bad hack! + CCLOG("onKeyPressed, keycode: %d", static_cast(code)); + m_test->KeyboardUp((static_cast(code) - 59)); // its a bad hack! + } void Box2DTestBed::onMouseDown(Event* event) { - EventMouse* e = (EventMouse*)event; - switch (e->getMouseButton()) - { - button[(int)EventMouse::MouseButton::BUTTON_LEFT] = false; - button[(int)EventMouse::MouseButton::BUTTON_RIGHT] = false; - button[(int)EventMouse::MouseButton::BUTTON_MIDDLE] = false; - case EventMouse::MouseButton::BUTTON_LEFT: - button[(int)EventMouse::MouseButton::BUTTON_LEFT] = true; - break; - case EventMouse::MouseButton::BUTTON_RIGHT: - button[(int)EventMouse::MouseButton::BUTTON_RIGHT] = true; - break; - case EventMouse::MouseButton::BUTTON_MIDDLE: - button[(int)EventMouse::MouseButton::BUTTON_MIDDLE] = true; - break; - } + EventMouse* e = (EventMouse*)event; + switch (e->getMouseButton()) + { + button[(int)EventMouse::MouseButton::BUTTON_LEFT] = false; + button[(int)EventMouse::MouseButton::BUTTON_RIGHT] = false; + button[(int)EventMouse::MouseButton::BUTTON_MIDDLE] = false; + case EventMouse::MouseButton::BUTTON_LEFT: + button[(int)EventMouse::MouseButton::BUTTON_LEFT] = true; + break; + case EventMouse::MouseButton::BUTTON_RIGHT: + button[(int)EventMouse::MouseButton::BUTTON_RIGHT] = true; + break; + case EventMouse::MouseButton::BUTTON_MIDDLE: + button[(int)EventMouse::MouseButton::BUTTON_MIDDLE] = true; + break; + } } void Box2DTestBed::onMouseUp(Event* event) { - button[(int)EventMouse::MouseButton::BUTTON_LEFT] = false; - button[(int)EventMouse::MouseButton::BUTTON_RIGHT] = false; - button[(int)EventMouse::MouseButton::BUTTON_MIDDLE] = false; + button[(int)EventMouse::MouseButton::BUTTON_LEFT] = false; + button[(int)EventMouse::MouseButton::BUTTON_RIGHT] = false; + button[(int)EventMouse::MouseButton::BUTTON_MIDDLE] = false; } void Box2DTestBed::onMouseMove(Event* event) { - EventMouse* e = (EventMouse*)event; - pos = {e->getCursorX() / g_debugDraw.mRatio, e->getCursorY() / g_debugDraw.mRatio}; + EventMouse* e = (EventMouse*)event; + pos = { e->getCursorX() / g_debugDraw.mRatio , e->getCursorY() / g_debugDraw.mRatio }; - if (button[(int)EventMouse::MouseButton::BUTTON_RIGHT]) - { - (pos.x > oldPos.x) ? g_debugDraw.debugNodeOffset.x += 4 : g_debugDraw.debugNodeOffset.x -= 4; - (pos.y < oldPos.y) ? g_debugDraw.debugNodeOffset.y -= 2 : g_debugDraw.debugNodeOffset.y += 2; - } - oldPos = pos; + if (button[(int)EventMouse::MouseButton::BUTTON_RIGHT]) + { + (pos.x > oldPos.x) ? g_debugDraw.debugNodeOffset.x += 4 : g_debugDraw.debugNodeOffset.x -= 4; + (pos.y < oldPos.y) ? g_debugDraw.debugNodeOffset.y -= 2 : g_debugDraw.debugNodeOffset.y += 2; + } + oldPos = pos; } void Box2DTestBed::onMouseScroll(Event* event) { - EventMouse* e = (EventMouse*)event; - g_debugDraw.mRatio += e->getScrollY(); + EventMouse* e = (EventMouse*)event; + g_debugDraw.mRatio += e->getScrollY(); } void Box2DTestBed::onEnter() { - Scene::onEnter(); - ImGuiEXT::getInstance()->addFont(FileUtils::getInstance()->fullPathForFilename("fonts/arial.ttf")); - ImGuiEXT::getInstance()->addRenderLoop("#im01", CC_CALLBACK_0(Box2DTestBed::onDrawImGui, this), this); + Scene::onEnter(); + ImGuiEXT::getInstance()->addFont(FileUtils::getInstance()->fullPathForFilename("fonts/arial.ttf")); + ImGuiEXT::getInstance()->addRenderLoop("#im01", CC_CALLBACK_0(Box2DTestBed::onDrawImGui, this), this); } void Box2DTestBed::onExit() { - Scene::onExit(); - ImGuiEXT::getInstance()->removeRenderLoop("#im01"); + Scene::onExit(); + ImGuiEXT::getInstance()->removeRenderLoop("#im01"); } void Box2DTestBed::update(float dt) { - // Debug draw - m_test->debugString = ""; - labelDebugDraw->setString(""); - debugDrawNode->clear(); - m_test->Step(settings); - m_test->m_world->DebugDraw(); + // Debug draw + m_test->debugString = ""; + labelDebugDraw->setString(""); + debugDrawNode->clear(); + m_test->Step(settings); + m_test->m_world->DebugDraw(); } void Box2DTestBed::initPhysics() { - uint32 flags = 0; - flags += 1 * b2Draw::e_shapeBit; - flags += 1 * b2Draw::e_jointBit; - flags += 0 * b2Draw::e_aabbBit; - flags += 0 * b2Draw::e_centerOfMassBit; - g_debugDraw.SetFlags(flags); - g_debugDraw.mRatio = 8; - m_test->m_world->SetDebugDraw(&g_debugDraw); - m_test->g_debugDraw = g_debugDraw; - g_debugDraw.debugNodeOffset = {250, 70}; - m_test->g_debugDraw.debugNodeOffset = g_debugDraw.debugNodeOffset; + uint32 flags = 0; + flags += 1 * b2Draw::e_shapeBit; + flags += 1 * b2Draw::e_jointBit; + flags += 0 * b2Draw::e_aabbBit; + flags += 0 * b2Draw::e_centerOfMassBit; + g_debugDraw.SetFlags(flags); + g_debugDraw.mRatio = 8; + m_test->m_world->SetDebugDraw(&g_debugDraw); + m_test->g_debugDraw = g_debugDraw; + g_debugDraw.debugNodeOffset = { 250, 70 }; + m_test->g_debugDraw.debugNodeOffset = g_debugDraw.debugNodeOffset; - settings.m_hertz = 60; + settings.m_hertz = 60; } void Box2DTestBed::onDrawImGui() { - m_test->UpdateUI(); + m_test->UpdateUI(); } \ No newline at end of file diff --git a/tests/cpp-tests/Classes/Box2DTestBed/Box2DTestBed.h b/tests/cpp-tests/Classes/Box2DTestBed/Box2DTestBed.h index 40fd878467..ef82f8bdf8 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/Box2DTestBed.h +++ b/tests/cpp-tests/Classes/Box2DTestBed/Box2DTestBed.h @@ -31,14 +31,15 @@ DEFINE_TEST_SUITE(Box2DTestBedTests); + class Test; typedef Test* TestCreateFcn(); struct TestEntry { - const char* category; - const char* name; - TestCreateFcn* createFcn; + const char* category; + const char* name; + TestCreateFcn* createFcn; }; #define MAX_TESTS 256 @@ -49,53 +50,55 @@ int RegisterTest(const char* category, const char* name, TestCreateFcn* fcn); class Box2DTestBed : public TestCase, cocos2d::Layer { public: - static Box2DTestBed* createWithEntryID(int entryId); + static Box2DTestBed* createWithEntryID(int entryId); - Box2DTestBed(); - virtual ~Box2DTestBed(); + Box2DTestBed(); + virtual ~Box2DTestBed(); - void onEnter() override; - void onExit() override; + void onEnter() override; + void onExit() override; - void onDrawImGui(); + void onDrawImGui(); - void initPhysics(); - void update(float dt) override; + void initPhysics(); + void update(float dt) override; - void createResetButton(); + void createResetButton(); - bool initWithEntryID(int entryId); + bool initWithEntryID(int entryId); - bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event); - void onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event); - void onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event); + bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event); + void onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event); + void onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event); - void onKeyPressed(cocos2d::EventKeyboard::KeyCode code, cocos2d::Event* event); - void onKeyReleased(cocos2d::EventKeyboard::KeyCode code, cocos2d::Event* event); + void onKeyPressed(cocos2d::EventKeyboard::KeyCode code, cocos2d::Event* event); + void onKeyReleased(cocos2d::EventKeyboard::KeyCode code, cocos2d::Event* event); - void onMouseDown(cocos2d::Event* event); - void onMouseUp(cocos2d::Event* event); - void onMouseMove(cocos2d::Event* event); - void onMouseScroll(cocos2d::Event* event); + void onMouseDown(cocos2d::Event* event); + void onMouseUp(cocos2d::Event* event); + void onMouseMove(cocos2d::Event* event); + void onMouseScroll(cocos2d::Event* event); - cocos2d::EventListenerTouchOneByOne* _touchListener; - cocos2d::EventListenerKeyboard* _keyboardListener; + cocos2d::EventListenerTouchOneByOne* _touchListener; + cocos2d::EventListenerKeyboard* _keyboardListener; - TestEntry* m_entry; - Test* m_test; - int m_entryID; + TestEntry* m_entry; + Test* m_test; + int m_entryID; private: - b2World* world; - cocos2d::Texture2D* _spriteTexture; - b2Vec2 pos; - b2Vec2 oldPos; - bool button[2]; + b2World* world; + cocos2d::Texture2D* _spriteTexture; + + b2Vec2 pos; + b2Vec2 oldPos; + bool button[2]; + + // Debug stuff + cocos2d::DrawNode* debugDrawNode; + cocos2d::extension::PhysicsDebugNodeBox2D g_debugDraw; - // Debug stuff - cocos2d::DrawNode* debugDrawNode; - cocos2d::extension::PhysicsDebugNodeBox2D g_debugDraw; }; #endif diff --git a/tests/cpp-tests/Classes/Box2DTestBed/Test.cpp b/tests/cpp-tests/Classes/Box2DTestBed/Test.cpp index 1c60abf385..5d88954b27 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/Test.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/Test.cpp @@ -1,20 +1,20 @@ /* - * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - */ +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ #include "tests/test.h" #include "tests/settings.h" @@ -31,476 +31,471 @@ USING_NS_CC_EXT; extern cocos2d::Label* labelDebugDraw; #endif -void DestructionListener::SayGoodbye(b2Joint* joint) +void DestructionListener::SayGoodbye(b2Joint * joint) { - if (test->m_mouseJoint == joint) - { - test->m_mouseJoint = NULL; - } - else - { - test->JointDestroyed(joint); - } + if (test->m_mouseJoint == joint) + { + test->m_mouseJoint = NULL; + } + else + { + test->JointDestroyed(joint); + } } Test::Test() { - b2Vec2 gravity; - gravity.Set(0.0f, -10.0f); - m_world = new b2World(gravity); - m_bomb = NULL; - m_textLine = 30; - m_textIncrement = 13; - m_mouseJoint = NULL; - m_pointCount = 0; + b2Vec2 gravity; + gravity.Set(0.0f, -10.0f); + m_world = new b2World(gravity); + m_bomb = NULL; + m_textLine = 30; + m_textIncrement = 13; + m_mouseJoint = NULL; + m_pointCount = 0; - m_destructionListener.test = this; - m_world->SetDestructionListener(&m_destructionListener); - m_world->SetContactListener(this); - m_world->SetDebugDraw(&g_debugDraw); + m_destructionListener.test = this; + m_world->SetDestructionListener(&m_destructionListener); + m_world->SetContactListener(this); + m_world->SetDebugDraw(&g_debugDraw); - m_bombSpawning = false; + m_bombSpawning = false; - m_stepCount = 0; + m_stepCount = 0; - b2BodyDef bodyDef; - m_groundBody = m_world->CreateBody(&bodyDef); + b2BodyDef bodyDef; + m_groundBody = m_world->CreateBody(&bodyDef); - memset(&m_maxProfile, 0, sizeof(b2Profile)); - memset(&m_totalProfile, 0, sizeof(b2Profile)); + memset(&m_maxProfile, 0, sizeof(b2Profile)); + memset(&m_totalProfile, 0, sizeof(b2Profile)); } Test::~Test() { - // By deleting the world, we delete the bomb, mouse joint, etc. - delete m_world; - m_world = NULL; + // By deleting the world, we delete the bomb, mouse joint, etc. + delete m_world; + m_world = NULL; } -void Test::PreSolve(b2Contact* contact, const b2Manifold* oldManifold) +void Test::PreSolve(b2Contact * contact, const b2Manifold * oldManifold) { - const b2Manifold* manifold = contact->GetManifold(); + const b2Manifold* manifold = contact->GetManifold(); - if (manifold->pointCount == 0) - { - return; - } + if (manifold->pointCount == 0) + { + return; + } - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); - b2PointState state1[b2_maxManifoldPoints], state2[b2_maxManifoldPoints]; - b2GetPointStates(state1, state2, oldManifold, manifold); + b2PointState state1[b2_maxManifoldPoints], state2[b2_maxManifoldPoints]; + b2GetPointStates(state1, state2, oldManifold, manifold); - b2WorldManifold worldManifold; - contact->GetWorldManifold(&worldManifold); + b2WorldManifold worldManifold; + contact->GetWorldManifold(&worldManifold); - for (int32 i = 0; i < manifold->pointCount && m_pointCount < k_maxContactPoints; ++i) - { - ContactPoint* cp = m_points + m_pointCount; - cp->fixtureA = fixtureA; - cp->fixtureB = fixtureB; - cp->position = worldManifold.points[i]; - cp->normal = worldManifold.normal; - cp->state = state2[i]; - cp->normalImpulse = manifold->points[i].normalImpulse; - cp->tangentImpulse = manifold->points[i].tangentImpulse; - cp->separation = worldManifold.separations[i]; - ++m_pointCount; - } + for (int32 i = 0; i < manifold->pointCount && m_pointCount < k_maxContactPoints; ++i) + { + ContactPoint* cp = m_points + m_pointCount; + cp->fixtureA = fixtureA; + cp->fixtureB = fixtureB; + cp->position = worldManifold.points[i]; + cp->normal = worldManifold.normal; + cp->state = state2[i]; + cp->normalImpulse = manifold->points[i].normalImpulse; + cp->tangentImpulse = manifold->points[i].tangentImpulse; + cp->separation = worldManifold.separations[i]; + ++m_pointCount; + } } void Test::DrawTitle(const char* string) { - DrawString(5, 5, string); - m_textLine = int32(26.0f); + DrawString(5, 5, string); + m_textLine = int32(26.0f); } class QueryCallback : public b2QueryCallback { public: - QueryCallback(const b2Vec2& point) - { - m_point = point; - m_fixture = NULL; - } + QueryCallback(const b2Vec2& point) + { + m_point = point; + m_fixture = NULL; + } - bool ReportFixture(b2Fixture* fixture) override - { - b2Body* body = fixture->GetBody(); - if (body->GetType() == b2_dynamicBody) - { - bool inside = fixture->TestPoint(m_point); - if (inside) - { - m_fixture = fixture; + bool ReportFixture(b2Fixture* fixture) override + { + b2Body* body = fixture->GetBody(); + if (body->GetType() == b2_dynamicBody) + { + bool inside = fixture->TestPoint(m_point); + if (inside) + { + m_fixture = fixture; - // We are done, terminate the query. - return false; - } - } + // We are done, terminate the query. + return false; + } + } - // Continue the query. - return true; - } + // Continue the query. + return true; + } - b2Vec2 m_point; - b2Fixture* m_fixture; + b2Vec2 m_point; + b2Fixture* m_fixture; }; -bool Test::MouseDown(const b2Vec2& p) +bool Test::MouseDown(const b2Vec2 & p) { - m_mouseWorld = p; + m_mouseWorld = p; - if (m_mouseJoint != NULL) - { - return false; - } + if (m_mouseJoint != NULL) + { + return false; + } - // Make a small box. - b2AABB aabb; - b2Vec2 d; - d.Set(0.001f, 0.001f); - aabb.lowerBound = p - d; - aabb.upperBound = p + d; + // Make a small box. + b2AABB aabb; + b2Vec2 d; + d.Set(0.001f, 0.001f); + aabb.lowerBound = p - d; + aabb.upperBound = p + d; - // Query the world for overlapping shapes. - QueryCallback callback(p); - m_world->QueryAABB(&callback, aabb); + // Query the world for overlapping shapes. + QueryCallback callback(p); + m_world->QueryAABB(&callback, aabb); - if (callback.m_fixture) - { - float frequencyHz = 5.0f; - float dampingRatio = 0.7f; + if (callback.m_fixture) + { + float frequencyHz = 5.0f; + float dampingRatio = 0.7f; - b2Body* body = callback.m_fixture->GetBody(); - b2MouseJointDef jd; - jd.bodyA = m_groundBody; - jd.bodyB = body; - jd.target = p; - jd.maxForce = 1000.0f * body->GetMass(); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + b2Body* body = callback.m_fixture->GetBody(); + b2MouseJointDef jd; + jd.bodyA = m_groundBody; + jd.bodyB = body; + jd.target = p; + jd.maxForce = 1000.0f * body->GetMass(); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_mouseJoint = (b2MouseJoint*)m_world->CreateJoint(&jd); - body->SetAwake(true); - return true; - } - return false; + m_mouseJoint = (b2MouseJoint*)m_world->CreateJoint(&jd); + body->SetAwake(true); + return true; + } + return false; } -void Test::SpawnBomb(const b2Vec2& worldPt) +void Test::SpawnBomb(const b2Vec2 & worldPt) { - m_bombSpawnPoint = worldPt; - m_bombSpawning = true; + m_bombSpawnPoint = worldPt; + m_bombSpawning = true; } -void Test::CompleteBombSpawn(const b2Vec2& p) +void Test::CompleteBombSpawn(const b2Vec2 & p) { - if (m_bombSpawning == false) - { - return; - } + if (m_bombSpawning == false) + { + return; + } - const float multiplier = 30.0f; - b2Vec2 vel = m_bombSpawnPoint - p; - vel *= multiplier; - LaunchBomb(m_bombSpawnPoint, vel); - m_bombSpawning = false; + const float multiplier = 30.0f; + b2Vec2 vel = m_bombSpawnPoint - p; + vel *= multiplier; + LaunchBomb(m_bombSpawnPoint, vel); + m_bombSpawning = false; } -void Test::ShiftMouseDown(const b2Vec2& p) +void Test::ShiftMouseDown(const b2Vec2 & p) { - m_mouseWorld = p; + m_mouseWorld = p; - if (m_mouseJoint != NULL) - { - return; - } + if (m_mouseJoint != NULL) + { + return; + } - SpawnBomb(p); + SpawnBomb(p); } -void Test::MouseUp(const b2Vec2& p) +void Test::MouseUp(const b2Vec2 & p) { - if (m_mouseJoint) - { - m_world->DestroyJoint(m_mouseJoint); - m_mouseJoint = NULL; - } + if (m_mouseJoint) + { + m_world->DestroyJoint(m_mouseJoint); + m_mouseJoint = NULL; + } - if (m_bombSpawning) - { - CompleteBombSpawn(p); - } + if (m_bombSpawning) + { + CompleteBombSpawn(p); + } } -void Test::MouseMove(const b2Vec2& p) +void Test::MouseMove(const b2Vec2 & p) { - m_mouseWorld = p; + m_mouseWorld = p; - if (m_mouseJoint) - { - m_mouseJoint->SetTarget(p); - } + if (m_mouseJoint) + { + m_mouseJoint->SetTarget(p); + } } void Test::LaunchBomb() { - b2Vec2 p(RandomFloat(-15.0f, 15.0f), 30.0f); - b2Vec2 v = -5.0f * p; - LaunchBomb(p, v); + b2Vec2 p(RandomFloat(-15.0f, 15.0f), 30.0f); + b2Vec2 v = -5.0f * p; + LaunchBomb(p, v); } -void Test::LaunchBomb(const b2Vec2& position, const b2Vec2& velocity) +void Test::LaunchBomb(const b2Vec2 & position, const b2Vec2 & velocity) { - if (m_bomb) - { - m_world->DestroyBody(m_bomb); - m_bomb = NULL; - } + if (m_bomb) + { + m_world->DestroyBody(m_bomb); + m_bomb = NULL; + } - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = position; - bd.bullet = true; - m_bomb = m_world->CreateBody(&bd); - m_bomb->SetLinearVelocity(velocity); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = position; + bd.bullet = true; + m_bomb = m_world->CreateBody(&bd); + m_bomb->SetLinearVelocity(velocity); - b2CircleShape circle; - circle.m_radius = 0.3f; + b2CircleShape circle; + circle.m_radius = 0.3f; - b2FixtureDef fd; - fd.shape = &circle; - fd.density = 20.0f; - fd.restitution = 0.0f; + b2FixtureDef fd; + fd.shape = &circle; + fd.density = 20.0f; + fd.restitution = 0.0f; - b2Vec2 minV = position - b2Vec2(0.3f, 0.3f); - b2Vec2 maxV = position + b2Vec2(0.3f, 0.3f); + b2Vec2 minV = position - b2Vec2(0.3f, 0.3f); + b2Vec2 maxV = position + b2Vec2(0.3f, 0.3f); - b2AABB aabb; - aabb.lowerBound = minV; - aabb.upperBound = maxV; + b2AABB aabb; + aabb.lowerBound = minV; + aabb.upperBound = maxV; - m_bomb->CreateFixture(&fd); + m_bomb->CreateFixture(&fd); } void Test::Step(Settings& settings) { - float timeStep = settings.m_hertz > 0.0f ? 1.0f / settings.m_hertz : float(0.0f); + float timeStep = settings.m_hertz > 0.0f ? 1.0f / settings.m_hertz : float(0.0f); - if (settings.m_pause) - { - if (settings.m_singleStep) - { - settings.m_singleStep = 0; - } - else - { - timeStep = 0.0f; - } + if (settings.m_pause) + { + if (settings.m_singleStep) + { + settings.m_singleStep = 0; + } + else + { + timeStep = 0.0f; + } - DrawString(5, m_textLine, "****PAUSED****"); - } + DrawString(5, m_textLine, "****PAUSED****"); + + } - uint32 flags = 0; - flags += settings.m_drawShapes * b2Draw::e_shapeBit; - flags += settings.m_drawJoints * b2Draw::e_jointBit; - flags += settings.m_drawAABBs * b2Draw::e_aabbBit; - flags += settings.m_drawCOMs * b2Draw::e_centerOfMassBit; - g_debugDraw.SetFlags(flags); + uint32 flags = 0; + flags += settings.m_drawShapes * b2Draw::e_shapeBit; + flags += settings.m_drawJoints * b2Draw::e_jointBit; + flags += settings.m_drawAABBs * b2Draw::e_aabbBit; + flags += settings.m_drawCOMs * b2Draw::e_centerOfMassBit; + g_debugDraw.SetFlags(flags); - m_world->SetAllowSleeping(settings.m_enableSleep); - m_world->SetWarmStarting(settings.m_enableWarmStarting); - m_world->SetContinuousPhysics(settings.m_enableContinuous); - m_world->SetSubStepping(settings.m_enableSubStepping); + m_world->SetAllowSleeping(settings.m_enableSleep); + m_world->SetWarmStarting(settings.m_enableWarmStarting); + m_world->SetContinuousPhysics(settings.m_enableContinuous); + m_world->SetSubStepping(settings.m_enableSubStepping); - m_pointCount = 0; + m_pointCount = 0; - m_world->Step(timeStep, settings.m_velocityIterations, settings.m_positionIterations); + m_world->Step(timeStep, settings.m_velocityIterations, settings.m_positionIterations); - m_world->DebugDraw(); + m_world->DebugDraw(); - if (timeStep > 0.0f) - { - ++m_stepCount; - } + if (timeStep > 0.0f) + { + ++m_stepCount; + } - if (settings.m_drawStats) - { - int32 bodyCount = m_world->GetBodyCount(); - int32 contactCount = m_world->GetContactCount(); - int32 jointCount = m_world->GetJointCount(); - DrawString(5, m_textLine, "bodies/contacts/joints = %d/%d/%d", bodyCount, contactCount, jointCount); + if (settings.m_drawStats) + { + int32 bodyCount = m_world->GetBodyCount(); + int32 contactCount = m_world->GetContactCount(); + int32 jointCount = m_world->GetJointCount(); + DrawString(5, m_textLine, "bodies/contacts/joints = %d/%d/%d", bodyCount, contactCount, jointCount); + - int32 proxyCount = m_world->GetProxyCount(); - int32 height = m_world->GetTreeHeight(); - int32 balance = m_world->GetTreeBalance(); - float quality = m_world->GetTreeQuality(); - DrawString(5, m_textLine, "proxies/height/balance/quality = %d/%d/%d/%g", proxyCount, height, balance, quality); - } + int32 proxyCount = m_world->GetProxyCount(); + int32 height = m_world->GetTreeHeight(); + int32 balance = m_world->GetTreeBalance(); + float quality = m_world->GetTreeQuality(); + DrawString(5, m_textLine, "proxies/height/balance/quality = %d/%d/%d/%g", proxyCount, height, balance, quality); + + } - // Track maximum profile times - { - const b2Profile& p = m_world->GetProfile(); - m_maxProfile.step = b2Max(m_maxProfile.step, p.step); - m_maxProfile.collide = b2Max(m_maxProfile.collide, p.collide); - m_maxProfile.solve = b2Max(m_maxProfile.solve, p.solve); - m_maxProfile.solveInit = b2Max(m_maxProfile.solveInit, p.solveInit); - m_maxProfile.solveVelocity = b2Max(m_maxProfile.solveVelocity, p.solveVelocity); - m_maxProfile.solvePosition = b2Max(m_maxProfile.solvePosition, p.solvePosition); - m_maxProfile.solveTOI = b2Max(m_maxProfile.solveTOI, p.solveTOI); - m_maxProfile.broadphase = b2Max(m_maxProfile.broadphase, p.broadphase); + // Track maximum profile times + { + const b2Profile& p = m_world->GetProfile(); + m_maxProfile.step = b2Max(m_maxProfile.step, p.step); + m_maxProfile.collide = b2Max(m_maxProfile.collide, p.collide); + m_maxProfile.solve = b2Max(m_maxProfile.solve, p.solve); + m_maxProfile.solveInit = b2Max(m_maxProfile.solveInit, p.solveInit); + m_maxProfile.solveVelocity = b2Max(m_maxProfile.solveVelocity, p.solveVelocity); + m_maxProfile.solvePosition = b2Max(m_maxProfile.solvePosition, p.solvePosition); + m_maxProfile.solveTOI = b2Max(m_maxProfile.solveTOI, p.solveTOI); + m_maxProfile.broadphase = b2Max(m_maxProfile.broadphase, p.broadphase); - m_totalProfile.step += p.step; - m_totalProfile.collide += p.collide; - m_totalProfile.solve += p.solve; - m_totalProfile.solveInit += p.solveInit; - m_totalProfile.solveVelocity += p.solveVelocity; - m_totalProfile.solvePosition += p.solvePosition; - m_totalProfile.solveTOI += p.solveTOI; - m_totalProfile.broadphase += p.broadphase; - } + m_totalProfile.step += p.step; + m_totalProfile.collide += p.collide; + m_totalProfile.solve += p.solve; + m_totalProfile.solveInit += p.solveInit; + m_totalProfile.solveVelocity += p.solveVelocity; + m_totalProfile.solvePosition += p.solvePosition; + m_totalProfile.solveTOI += p.solveTOI; + m_totalProfile.broadphase += p.broadphase; + } - if (settings.m_drawProfile) - { - const b2Profile& p = m_world->GetProfile(); + if (settings.m_drawProfile) + { + const b2Profile& p = m_world->GetProfile(); - b2Profile aveProfile; - memset(&aveProfile, 0, sizeof(b2Profile)); - if (m_stepCount > 0) - { - float scale = 1.0f / m_stepCount; - aveProfile.step = scale * m_totalProfile.step; - aveProfile.collide = scale * m_totalProfile.collide; - aveProfile.solve = scale * m_totalProfile.solve; - aveProfile.solveInit = scale * m_totalProfile.solveInit; - aveProfile.solveVelocity = scale * m_totalProfile.solveVelocity; - aveProfile.solvePosition = scale * m_totalProfile.solvePosition; - aveProfile.solveTOI = scale * m_totalProfile.solveTOI; - aveProfile.broadphase = scale * m_totalProfile.broadphase; - } + b2Profile aveProfile; + memset(&aveProfile, 0, sizeof(b2Profile)); + if (m_stepCount > 0) + { + float scale = 1.0f / m_stepCount; + aveProfile.step = scale * m_totalProfile.step; + aveProfile.collide = scale * m_totalProfile.collide; + aveProfile.solve = scale * m_totalProfile.solve; + aveProfile.solveInit = scale * m_totalProfile.solveInit; + aveProfile.solveVelocity = scale * m_totalProfile.solveVelocity; + aveProfile.solvePosition = scale * m_totalProfile.solvePosition; + aveProfile.solveTOI = scale * m_totalProfile.solveTOI; + aveProfile.broadphase = scale * m_totalProfile.broadphase; + } - DrawString(5, m_textLine, "step [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.step, aveProfile.step, - m_maxProfile.step); - DrawString(5, m_textLine, "collide [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.collide, aveProfile.collide, - m_maxProfile.collide); - DrawString(5, m_textLine, "solve [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solve, aveProfile.solve, - m_maxProfile.solve); - DrawString(5, m_textLine, "solve init [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveInit, aveProfile.solveInit, - m_maxProfile.solveInit); - DrawString(5, m_textLine, "solve velocity [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveVelocity, - aveProfile.solveVelocity, m_maxProfile.solveVelocity); - DrawString(5, m_textLine, "solve position [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solvePosition, - aveProfile.solvePosition, m_maxProfile.solvePosition); - DrawString(5, m_textLine, "solveTOI [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveTOI, aveProfile.solveTOI, - m_maxProfile.solveTOI); - DrawString(5, m_textLine, "broad-phase [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.broadphase, - aveProfile.broadphase, m_maxProfile.broadphase); - } + DrawString(5, m_textLine, "step [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.step, aveProfile.step, m_maxProfile.step); + DrawString(5, m_textLine, "collide [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.collide, aveProfile.collide, m_maxProfile.collide); + DrawString(5, m_textLine, "solve [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solve, aveProfile.solve, m_maxProfile.solve); + DrawString(5, m_textLine, "solve init [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveInit, aveProfile.solveInit, m_maxProfile.solveInit); + DrawString(5, m_textLine, "solve velocity [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveVelocity, aveProfile.solveVelocity, m_maxProfile.solveVelocity); + DrawString(5, m_textLine, "solve position [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solvePosition, aveProfile.solvePosition, m_maxProfile.solvePosition); + DrawString(5, m_textLine, "solveTOI [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveTOI, aveProfile.solveTOI, m_maxProfile.solveTOI); + DrawString(5, m_textLine, "broad-phase [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.broadphase, aveProfile.broadphase, m_maxProfile.broadphase); + } - if (m_bombSpawning) - { - b2Color c; - c.Set(0.0f, 0.0f, 1.0f); - g_debugDraw.DrawPoint(m_bombSpawnPoint, 4.0f, c); + if (m_bombSpawning) + { + b2Color c; + c.Set(0.0f, 0.0f, 1.0f); + g_debugDraw.DrawPoint(m_bombSpawnPoint, 4.0f, c); - c.Set(0.8f, 0.8f, 0.8f); - g_debugDraw.DrawSegment(m_mouseWorld, m_bombSpawnPoint, c); - } + c.Set(0.8f, 0.8f, 0.8f); + g_debugDraw.DrawSegment(m_mouseWorld, m_bombSpawnPoint, c); + } - if (settings.m_drawContactPoints) - { - const float k_impulseScale = 0.1f; - const float k_axisScale = 0.3f; + if (settings.m_drawContactPoints) + { + const float k_impulseScale = 0.1f; + const float k_axisScale = 0.3f; - for (int32 i = 0; i < m_pointCount; ++i) - { - ContactPoint* point = m_points + i; + for (int32 i = 0; i < m_pointCount; ++i) + { + ContactPoint* point = m_points + i; - if (point->state == b2_addState) - { - // Add - g_debugDraw.DrawPoint(point->position, 10.0f, b2Color(0.3f, 0.95f, 0.3f)); - } - else if (point->state == b2_persistState) - { - // Persist - g_debugDraw.DrawPoint(point->position, 5.0f, b2Color(0.3f, 0.3f, 0.95f)); - } + if (point->state == b2_addState) + { + // Add + g_debugDraw.DrawPoint(point->position, 10.0f, b2Color(0.3f, 0.95f, 0.3f)); + } + else if (point->state == b2_persistState) + { + // Persist + g_debugDraw.DrawPoint(point->position, 5.0f, b2Color(0.3f, 0.3f, 0.95f)); + } - if (settings.m_drawContactNormals == 1) - { - b2Vec2 p1 = point->position; - b2Vec2 p2 = p1 + k_axisScale * point->normal; - g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.9f)); - } - else if (settings.m_drawContactImpulse == 1) - { - b2Vec2 p1 = point->position; - b2Vec2 p2 = p1 + k_impulseScale * point->normalImpulse * point->normal; - g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f)); - } + if (settings.m_drawContactNormals == 1) + { + b2Vec2 p1 = point->position; + b2Vec2 p2 = p1 + k_axisScale * point->normal; + g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.9f)); + } + else if (settings.m_drawContactImpulse == 1) + { + b2Vec2 p1 = point->position; + b2Vec2 p2 = p1 + k_impulseScale * point->normalImpulse * point->normal; + g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f)); + } - if (settings.m_drawFrictionImpulse == 1) - { - b2Vec2 tangent = b2Cross(point->normal, 1.0f); - b2Vec2 p1 = point->position; - b2Vec2 p2 = p1 + k_impulseScale * point->tangentImpulse * tangent; - g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f)); - } - } - } + if (settings.m_drawFrictionImpulse == 1) + { + b2Vec2 tangent = b2Cross(point->normal, 1.0f); + b2Vec2 p1 = point->position; + b2Vec2 p2 = p1 + k_impulseScale * point->tangentImpulse * tangent; + g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f)); + } + } + } } -void Test::ShiftOrigin(const b2Vec2& newOrigin) +void Test::ShiftOrigin(const b2Vec2 & newOrigin) { - m_world->ShiftOrigin(newOrigin); + m_world->ShiftOrigin(newOrigin); } void Test::initShader(void) { - // initShader is unsupported + // initShader is unsupported } void Test::DrawString(int x, int y, const char* fmt, ...) { #if defined(CC_PLATFORM_PC) - debugString.append(std::string(fmt)); - debugString.append("\n"); - labelDebugDraw->setString(debugString); - // labelDebugDraw->setPosition(x, y); + debugString.append(std::string(fmt)); + debugString.append("\n"); + labelDebugDraw->setString(debugString); + // labelDebugDraw->setPosition(x, y); #endif } void Test::DrawString(const b2Vec2& pw, const char* fmt, ...) { #if defined(CC_PLATFORM_PC) - debugString.append(std::string(fmt)); - debugString.append("\n"); - labelDebugDraw->setString(debugString); - // labelDebugDraw->setPosition(pw.x, pw.y); + debugString.append(std::string(fmt)); + debugString.append("\n"); + labelDebugDraw->setString(debugString); + // labelDebugDraw->setPosition(pw.x, pw.y); #endif } + + void Test::DrawAABB(b2AABB* aabb, const b2Color& color) { - b2Vec2 p1 = aabb->lowerBound; - b2Vec2 p2 = b2Vec2(aabb->upperBound.x, aabb->lowerBound.y); - b2Vec2 p3 = aabb->upperBound; - b2Vec2 p4 = b2Vec2(aabb->lowerBound.x, aabb->upperBound.y); + b2Vec2 p1 = aabb->lowerBound; + b2Vec2 p2 = b2Vec2(aabb->upperBound.x, aabb->lowerBound.y); + b2Vec2 p3 = aabb->upperBound; + b2Vec2 p4 = b2Vec2(aabb->lowerBound.x, aabb->upperBound.y); - Vec2 verts[] = { - Vec2(p1.x * g_debugDraw.mRatio, p1.y * g_debugDraw.mRatio) + g_debugDraw.debugNodeOffset, - Vec2(p2.x * g_debugDraw.mRatio, p2.y * g_debugDraw.mRatio) + g_debugDraw.debugNodeOffset, - Vec2(p3.x * g_debugDraw.mRatio, p3.y * g_debugDraw.mRatio) + g_debugDraw.debugNodeOffset, - Vec2(p4.x * g_debugDraw.mRatio, p4.y * g_debugDraw.mRatio) + g_debugDraw.debugNodeOffset, - }; - debugDrawNode->drawPolygon(verts, sizeof(verts) / sizeof(verts[0]), - Color4F(color.r / 2, color.g / 2, color.b / 2, 0), 0.4f, - Color4F(color.r, color.g, color.b, color.a)); + Vec2 verts[] = { + Vec2(p1.x * g_debugDraw.mRatio, p1.y * g_debugDraw.mRatio) + g_debugDraw.debugNodeOffset , + Vec2(p2.x * g_debugDraw.mRatio, p2.y * g_debugDraw.mRatio) + g_debugDraw.debugNodeOffset , + Vec2(p3.x * g_debugDraw.mRatio, p3.y * g_debugDraw.mRatio) + g_debugDraw.debugNodeOffset , + Vec2(p4.x * g_debugDraw.mRatio, p4.y * g_debugDraw.mRatio) + g_debugDraw.debugNodeOffset , + }; + debugDrawNode->drawPolygon(verts, sizeof(verts) / sizeof(verts[0]), Color4F(color.r / 2, color.g / 2, color.b / 2, 0), 0.4f, Color4F(color.r, color.g, color.b, color.a)); } void Test::Flush() { - // Flush is unsupported + // Flush is unsupported } \ No newline at end of file diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/add_pair.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/add_pair.cpp index 4465d35f3e..ceccbf8ca2 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/add_pair.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/add_pair.cpp @@ -25,43 +25,47 @@ class AddPair : public Test { public: - AddPair() - { - m_world->SetGravity(b2Vec2(0.0f, 0.0f)); - { - b2CircleShape shape; - shape.m_p.SetZero(); - shape.m_radius = 0.1f; - float minX = -6.0f; - float maxX = 0.0f; - float minY = 4.0f; - float maxY = 6.0f; + AddPair() + { + m_world->SetGravity(b2Vec2(0.0f,0.0f)); + { + b2CircleShape shape; + shape.m_p.SetZero(); + shape.m_radius = 0.1f; - for (int32 i = 0; i < 400; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = b2Vec2(RandomFloat(minX, maxX), RandomFloat(minY, maxY)); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 0.01f); - } - } + float minX = -6.0f; + float maxX = 0.0f; + float minY = 4.0f; + float maxY = 6.0f; + + for (int32 i = 0; i < 400; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = b2Vec2(RandomFloat(minX,maxX),RandomFloat(minY,maxY)); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 0.01f); + } + } + + { + b2PolygonShape shape; + shape.SetAsBox(1.5f, 1.5f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-40.0f,5.0f); + bd.bullet = true; + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 1.0f); + body->SetLinearVelocity(b2Vec2(10.0f, 0.0f)); + } + } - { - b2PolygonShape shape; - shape.SetAsBox(1.5f, 1.5f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-40.0f, 5.0f); - bd.bullet = true; - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 1.0f); - body->SetLinearVelocity(b2Vec2(10.0f, 0.0f)); - } - } - - static Test* Create() { return new AddPair; } + static Test* Create() + { + return new AddPair; + } }; static int testIndex = RegisterTest("Benchmark", "Add Pair", AddPair::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/apply_force.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/apply_force.cpp index 51239f60e2..40fc7e1dec 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/apply_force.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/apply_force.cpp @@ -28,172 +28,176 @@ class ApplyForce : public Test { public: - ApplyForce() - { - m_world->SetGravity(b2Vec2(0.0f, 0.0f)); + ApplyForce() + { + m_world->SetGravity(b2Vec2(0.0f, 0.0f)); - const float k_restitution = 0.4f; + const float k_restitution = 0.4f; - b2Body* ground; - { - b2BodyDef bd; - bd.position.Set(0.0f, 20.0f); - ground = m_world->CreateBody(&bd); + b2Body* ground; + { + b2BodyDef bd; + bd.position.Set(0.0f, 20.0f); + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; + b2EdgeShape shape; - b2FixtureDef sd; - sd.shape = &shape; - sd.density = 0.0f; - sd.restitution = k_restitution; + b2FixtureDef sd; + sd.shape = &shape; + sd.density = 0.0f; + sd.restitution = k_restitution; - // Left vertical - shape.SetTwoSided(b2Vec2(-20.0f, -20.0f), b2Vec2(-20.0f, 20.0f)); - ground->CreateFixture(&sd); + // Left vertical + shape.SetTwoSided(b2Vec2(-20.0f, -20.0f), b2Vec2(-20.0f, 20.0f)); + ground->CreateFixture(&sd); - // Right vertical - shape.SetTwoSided(b2Vec2(20.0f, -20.0f), b2Vec2(20.0f, 20.0f)); - ground->CreateFixture(&sd); + // Right vertical + shape.SetTwoSided(b2Vec2(20.0f, -20.0f), b2Vec2(20.0f, 20.0f)); + ground->CreateFixture(&sd); - // Top horizontal - shape.SetTwoSided(b2Vec2(-20.0f, 20.0f), b2Vec2(20.0f, 20.0f)); - ground->CreateFixture(&sd); + // Top horizontal + shape.SetTwoSided(b2Vec2(-20.0f, 20.0f), b2Vec2(20.0f, 20.0f)); + ground->CreateFixture(&sd); - // Bottom horizontal - shape.SetTwoSided(b2Vec2(-20.0f, -20.0f), b2Vec2(20.0f, -20.0f)); - ground->CreateFixture(&sd); - } + // Bottom horizontal + shape.SetTwoSided(b2Vec2(-20.0f, -20.0f), b2Vec2(20.0f, -20.0f)); + ground->CreateFixture(&sd); + } - { - b2Transform xf1; - xf1.q.Set(0.3524f * b2_pi); - xf1.p = xf1.q.GetXAxis(); + { + b2Transform xf1; + xf1.q.Set(0.3524f * b2_pi); + xf1.p = xf1.q.GetXAxis(); - b2Vec2 vertices[3]; - vertices[0] = b2Mul(xf1, b2Vec2(-1.0f, 0.0f)); - vertices[1] = b2Mul(xf1, b2Vec2(1.0f, 0.0f)); - vertices[2] = b2Mul(xf1, b2Vec2(0.0f, 0.5f)); + b2Vec2 vertices[3]; + vertices[0] = b2Mul(xf1, b2Vec2(-1.0f, 0.0f)); + vertices[1] = b2Mul(xf1, b2Vec2(1.0f, 0.0f)); + vertices[2] = b2Mul(xf1, b2Vec2(0.0f, 0.5f)); + + b2PolygonShape poly1; + poly1.Set(vertices, 3); - b2PolygonShape poly1; - poly1.Set(vertices, 3); + b2FixtureDef sd1; + sd1.shape = &poly1; + sd1.density = 2.0f; - b2FixtureDef sd1; - sd1.shape = &poly1; - sd1.density = 2.0f; + b2Transform xf2; + xf2.q.Set(-0.3524f * b2_pi); + xf2.p = -xf2.q.GetXAxis(); - b2Transform xf2; - xf2.q.Set(-0.3524f * b2_pi); - xf2.p = -xf2.q.GetXAxis(); + vertices[0] = b2Mul(xf2, b2Vec2(-1.0f, 0.0f)); + vertices[1] = b2Mul(xf2, b2Vec2(1.0f, 0.0f)); + vertices[2] = b2Mul(xf2, b2Vec2(0.0f, 0.5f)); + + b2PolygonShape poly2; + poly2.Set(vertices, 3); - vertices[0] = b2Mul(xf2, b2Vec2(-1.0f, 0.0f)); - vertices[1] = b2Mul(xf2, b2Vec2(1.0f, 0.0f)); - vertices[2] = b2Mul(xf2, b2Vec2(0.0f, 0.5f)); + b2FixtureDef sd2; + sd2.shape = &poly2; + sd2.density = 2.0f; - b2PolygonShape poly2; - poly2.Set(vertices, 3); + b2BodyDef bd; + bd.type = b2_dynamicBody; - b2FixtureDef sd2; - sd2.shape = &poly2; - sd2.density = 2.0f; + bd.position.Set(0.0f, 3.0); + bd.angle = b2_pi; + bd.allowSleep = false; + m_body = m_world->CreateBody(&bd); + m_body->CreateFixture(&sd1); + m_body->CreateFixture(&sd2); - b2BodyDef bd; - bd.type = b2_dynamicBody; + float gravity = 10.0f; + float I = m_body->GetInertia(); + float mass = m_body->GetMass(); - bd.position.Set(0.0f, 3.0); - bd.angle = b2_pi; - bd.allowSleep = false; - m_body = m_world->CreateBody(&bd); - m_body->CreateFixture(&sd1); - m_body->CreateFixture(&sd2); + // Compute an effective radius that can be used to + // set the max torque for a friction joint + // For a circle: I = 0.5 * m * r * r ==> r = sqrt(2 * I / m) + float radius = b2Sqrt(2.0f * I / mass); - float gravity = 10.0f; - float I = m_body->GetInertia(); - float mass = m_body->GetMass(); + b2FrictionJointDef jd; + jd.bodyA = ground; + jd.bodyB = m_body; + jd.localAnchorA.SetZero(); + jd.localAnchorB = m_body->GetLocalCenter(); + jd.collideConnected = true; + jd.maxForce = 0.5f * mass * gravity; + jd.maxTorque = 0.2f * mass * radius * gravity; - // Compute an effective radius that can be used to - // set the max torque for a friction joint - // For a circle: I = 0.5 * m * r * r ==> r = sqrt(2 * I / m) - float radius = b2Sqrt(2.0f * I / mass); + m_world->CreateJoint(&jd); + } - b2FrictionJointDef jd; - jd.bodyA = ground; - jd.bodyB = m_body; - jd.localAnchorA.SetZero(); - jd.localAnchorB = m_body->GetLocalCenter(); - jd.collideConnected = true; - jd.maxForce = 0.5f * mass * gravity; - jd.maxTorque = 0.2f * mass * radius * gravity; + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); - m_world->CreateJoint(&jd); - } + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + fd.friction = 0.3f; - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); + for (int i = 0; i < 10; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - fd.friction = 0.3f; + bd.position.Set(0.0f, 7.0f + 1.54f * i); + b2Body* body = m_world->CreateBody(&bd); - for (int i = 0; i < 10; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; + body->CreateFixture(&fd); - bd.position.Set(0.0f, 7.0f + 1.54f * i); - b2Body* body = m_world->CreateBody(&bd); + float gravity = 10.0f; + float I = body->GetInertia(); + float mass = body->GetMass(); - body->CreateFixture(&fd); + // For a circle: I = 0.5 * m * r * r ==> r = sqrt(2 * I / m) + float radius = b2Sqrt(2.0f * I / mass); - float gravity = 10.0f; - float I = body->GetInertia(); - float mass = body->GetMass(); + b2FrictionJointDef jd; + jd.localAnchorA.SetZero(); + jd.localAnchorB.SetZero(); + jd.bodyA = ground; + jd.bodyB = body; + jd.collideConnected = true; + jd.maxForce = mass * gravity; + jd.maxTorque = 0.1f * mass * radius * gravity; - // For a circle: I = 0.5 * m * r * r ==> r = sqrt(2 * I / m) - float radius = b2Sqrt(2.0f * I / mass); + m_world->CreateJoint(&jd); + } + } + } - b2FrictionJointDef jd; - jd.localAnchorA.SetZero(); - jd.localAnchorB.SetZero(); - jd.bodyA = ground; - jd.bodyB = body; - jd.collideConnected = true; - jd.maxForce = mass * gravity; - jd.maxTorque = 0.1f * mass * radius * gravity; + void Step(Settings& settings) override + { + DrawString(5, m_textLine, "Forward (W), Turn (A) and (D)"); + - m_world->CreateJoint(&jd); - } - } - } + //if (glfwGetKey(g_mainWindow, GLFW_KEY_W) == GLFW_PRESS) + //{ + // b2Vec2 f = m_body->GetWorldVector(b2Vec2(0.0f, -50.0f)); + // b2Vec2 p = m_body->GetWorldPoint(b2Vec2(0.0f, 3.0f)); + // m_body->ApplyForce(f, p, true); + //} - void Step(Settings& settings) override - { - DrawString(5, m_textLine, "Forward (W), Turn (A) and (D)"); + //if (glfwGetKey(g_mainWindow, GLFW_KEY_A) == GLFW_PRESS) + //{ + // m_body->ApplyTorque(10.0f, true); + //} - // if (glfwGetKey(g_mainWindow, GLFW_KEY_W) == GLFW_PRESS) - //{ - // b2Vec2 f = m_body->GetWorldVector(b2Vec2(0.0f, -50.0f)); - // b2Vec2 p = m_body->GetWorldPoint(b2Vec2(0.0f, 3.0f)); - // m_body->ApplyForce(f, p, true); - // } + //if (glfwGetKey(g_mainWindow, GLFW_KEY_D) == GLFW_PRESS) + //{ + // m_body->ApplyTorque(-10.0f, true); + //} - // if (glfwGetKey(g_mainWindow, GLFW_KEY_A) == GLFW_PRESS) - //{ - // m_body->ApplyTorque(10.0f, true); - // } + Test::Step(settings); + } - // if (glfwGetKey(g_mainWindow, GLFW_KEY_D) == GLFW_PRESS) - //{ - // m_body->ApplyTorque(-10.0f, true); - // } + static Test* Create() + { + return new ApplyForce; + } - Test::Step(settings); - } - - static Test* Create() { return new ApplyForce; } - - b2Body* m_body; + b2Body* m_body; }; static int testIndex = RegisterTest("Forces", "Apply Force", ApplyForce::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/body_types.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/body_types.cpp index 0de1079826..055d279578 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/body_types.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/body_types.cpp @@ -25,134 +25,139 @@ class BodyTypes : public Test { public: - BodyTypes() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + BodyTypes() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); - b2FixtureDef fd; - fd.shape = &shape; + b2FixtureDef fd; + fd.shape = &shape; - ground->CreateFixture(&fd); - } + ground->CreateFixture(&fd); + } - // Define attachment - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 3.0f); - m_attachment = m_world->CreateBody(&bd); + // Define attachment + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 3.0f); + m_attachment = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(0.5f, 2.0f); - m_attachment->CreateFixture(&shape, 2.0f); - } + b2PolygonShape shape; + shape.SetAsBox(0.5f, 2.0f); + m_attachment->CreateFixture(&shape, 2.0f); + } - // Define platform - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-4.0f, 5.0f); - m_platform = m_world->CreateBody(&bd); + // Define platform + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-4.0f, 5.0f); + m_platform = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(0.5f, 4.0f, b2Vec2(4.0f, 0.0f), 0.5f * b2_pi); + b2PolygonShape shape; + shape.SetAsBox(0.5f, 4.0f, b2Vec2(4.0f, 0.0f), 0.5f * b2_pi); - b2FixtureDef fd; - fd.shape = &shape; - fd.friction = 0.6f; - fd.density = 2.0f; - m_platform->CreateFixture(&fd); + b2FixtureDef fd; + fd.shape = &shape; + fd.friction = 0.6f; + fd.density = 2.0f; + m_platform->CreateFixture(&fd); - b2RevoluteJointDef rjd; - rjd.Initialize(m_attachment, m_platform, b2Vec2(0.0f, 5.0f)); - rjd.maxMotorTorque = 50.0f; - rjd.enableMotor = true; - m_world->CreateJoint(&rjd); + b2RevoluteJointDef rjd; + rjd.Initialize(m_attachment, m_platform, b2Vec2(0.0f, 5.0f)); + rjd.maxMotorTorque = 50.0f; + rjd.enableMotor = true; + m_world->CreateJoint(&rjd); - b2PrismaticJointDef pjd; - pjd.Initialize(ground, m_platform, b2Vec2(0.0f, 5.0f), b2Vec2(1.0f, 0.0f)); + b2PrismaticJointDef pjd; + pjd.Initialize(ground, m_platform, b2Vec2(0.0f, 5.0f), b2Vec2(1.0f, 0.0f)); - pjd.maxMotorForce = 1000.0f; - pjd.enableMotor = true; - pjd.lowerTranslation = -10.0f; - pjd.upperTranslation = 10.0f; - pjd.enableLimit = true; + pjd.maxMotorForce = 1000.0f; + pjd.enableMotor = true; + pjd.lowerTranslation = -10.0f; + pjd.upperTranslation = 10.0f; + pjd.enableLimit = true; - m_world->CreateJoint(&pjd); + m_world->CreateJoint(&pjd); - m_speed = 3.0f; - } + m_speed = 3.0f; + } - // Create a payload - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 8.0f); - b2Body* body = m_world->CreateBody(&bd); + // Create a payload + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 8.0f); + b2Body* body = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(0.75f, 0.75f); + b2PolygonShape shape; + shape.SetAsBox(0.75f, 0.75f); - b2FixtureDef fd; - fd.shape = &shape; - fd.friction = 0.6f; - fd.density = 2.0f; + b2FixtureDef fd; + fd.shape = &shape; + fd.friction = 0.6f; + fd.density = 2.0f; - body->CreateFixture(&fd); - } - } + body->CreateFixture(&fd); + } + } - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_D: - m_platform->SetType(b2_dynamicBody); - break; + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_D: + m_platform->SetType(b2_dynamicBody); + break; - case GLFW_KEY_S: - m_platform->SetType(b2_staticBody); - break; + case GLFW_KEY_S: + m_platform->SetType(b2_staticBody); + break; - case GLFW_KEY_K: - m_platform->SetType(b2_kinematicBody); - m_platform->SetLinearVelocity(b2Vec2(-m_speed, 0.0f)); - m_platform->SetAngularVelocity(0.0f); - break; - } - } + case GLFW_KEY_K: + m_platform->SetType(b2_kinematicBody); + m_platform->SetLinearVelocity(b2Vec2(-m_speed, 0.0f)); + m_platform->SetAngularVelocity(0.0f); + break; + } + } - void Step(Settings& settings) override - { - // Drive the kinematic body. - if (m_platform->GetType() == b2_kinematicBody) - { - b2Vec2 p = m_platform->GetTransform().p; - b2Vec2 v = m_platform->GetLinearVelocity(); + void Step(Settings& settings) override + { + // Drive the kinematic body. + if (m_platform->GetType() == b2_kinematicBody) + { + b2Vec2 p = m_platform->GetTransform().p; + b2Vec2 v = m_platform->GetLinearVelocity(); - if ((p.x < -10.0f && v.x < 0.0f) || (p.x > 10.0f && v.x > 0.0f)) - { - v.x = -v.x; - m_platform->SetLinearVelocity(v); - } - } + if ((p.x < -10.0f && v.x < 0.0f) || + (p.x > 10.0f && v.x > 0.0f)) + { + v.x = -v.x; + m_platform->SetLinearVelocity(v); + } + } - Test::Step(settings); + Test::Step(settings); - DrawString(5, m_textLine, "Keys: (d) dynamic, (s) static, (k) kinematic"); - } + DrawString(5, m_textLine, "Keys: (d) dynamic, (s) static, (k) kinematic"); + + } - static Test* Create() { return new BodyTypes; } + static Test* Create() + { + return new BodyTypes; + } - b2Body* m_attachment; - b2Body* m_platform; - float m_speed; + b2Body* m_attachment; + b2Body* m_platform; + float m_speed; }; static int testIndex = RegisterTest("Examples", "Body Types", BodyTypes::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/box_stack.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/box_stack.cpp index 463d399b7f..10da577cbc 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/box_stack.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/box_stack.cpp @@ -27,144 +27,148 @@ extern B2_API bool g_blockSolve; class BoxStack : public Test { public: - enum - { - e_columnCount = 1, - e_rowCount = 15 - // e_columnCount = 1, - // e_rowCount = 1 - }; - BoxStack() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + enum + { + e_columnCount = 1, + e_rowCount = 15 + //e_columnCount = 1, + //e_rowCount = 1 + }; - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); + BoxStack() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - shape.SetTwoSided(b2Vec2(20.0f, 0.0f), b2Vec2(20.0f, 20.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); - float xs[5] = {0.0f, -10.0f, -5.0f, 5.0f, 10.0f}; + shape.SetTwoSided(b2Vec2(20.0f, 0.0f), b2Vec2(20.0f, 20.0f)); + ground->CreateFixture(&shape, 0.0f); + } - for (int32 j = 0; j < e_columnCount; ++j) - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); + float xs[5] = {0.0f, -10.0f, -5.0f, 5.0f, 10.0f}; - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - fd.friction = 0.3f; + for (int32 j = 0; j < e_columnCount; ++j) + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); - for (int i = 0; i < e_rowCount; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + fd.friction = 0.3f; - int32 n = j * e_rowCount + i; - b2Assert(n < e_rowCount * e_columnCount); - m_indices[n] = n; - bd.userData.pointer = n; + for (int i = 0; i < e_rowCount; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; - float x = 0.0f; - // float x = RandomFloat(-0.02f, 0.02f); - // float x = i % 2 == 0 ? -0.01f : 0.01f; - bd.position.Set(xs[j] + x, 0.55f + 1.1f * i); - b2Body* body = m_world->CreateBody(&bd); + int32 n = j * e_rowCount + i; + b2Assert(n < e_rowCount * e_columnCount); + m_indices[n] = n; + bd.userData.pointer = n; - m_bodies[n] = body; + float x = 0.0f; + //float x = RandomFloat(-0.02f, 0.02f); + //float x = i % 2 == 0 ? -0.01f : 0.01f; + bd.position.Set(xs[j] + x, 0.55f + 1.1f * i); + b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - } - } + m_bodies[n] = body; - m_bullet = NULL; - } + body->CreateFixture(&fd); + } + } - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_COMMA: - if (m_bullet != NULL) - { - m_world->DestroyBody(m_bullet); - m_bullet = NULL; - } + m_bullet = NULL; + } - { - b2CircleShape shape; - shape.m_radius = 0.25f; + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_COMMA: + if (m_bullet != NULL) + { + m_world->DestroyBody(m_bullet); + m_bullet = NULL; + } - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.restitution = 0.05f; + { + b2CircleShape shape; + shape.m_radius = 0.25f; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.bullet = true; - bd.position.Set(-31.0f, 5.0f); + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.restitution = 0.05f; - m_bullet = m_world->CreateBody(&bd); - m_bullet->CreateFixture(&fd); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.bullet = true; + bd.position.Set(-31.0f, 5.0f); - m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f)); - } - break; + m_bullet = m_world->CreateBody(&bd); + m_bullet->CreateFixture(&fd); + m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f)); + } + break; + case GLFW_KEY_B: g_blockSolve = !g_blockSolve; break; - } - } + } + } - void Step(Settings& settings) override - { - Test::Step(settings); - DrawString(5, m_textLine, "Press: (,) to launch a bullet."); + void Step(Settings& settings) override + { + Test::Step(settings); + DrawString(5, m_textLine, "Press: (,) to launch a bullet."); + + DrawString(5, m_textLine, "Blocksolve = %d", g_blockSolve); + if (m_stepCount == 300) + { + if (m_bullet != NULL) + { + m_world->DestroyBody(m_bullet); + m_bullet = NULL; + } - DrawString(5, m_textLine, "Blocksolve = %d", g_blockSolve); - if (m_stepCount == 300) - { - if (m_bullet != NULL) - { - m_world->DestroyBody(m_bullet); - m_bullet = NULL; - } + { + b2CircleShape shape; + shape.m_radius = 0.25f; - { - b2CircleShape shape; - shape.m_radius = 0.25f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.restitution = 0.05f; - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.restitution = 0.05f; + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.bullet = true; + bd.position.Set(-31.0f, 5.0f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.bullet = true; - bd.position.Set(-31.0f, 5.0f); + m_bullet = m_world->CreateBody(&bd); + m_bullet->CreateFixture(&fd); - m_bullet = m_world->CreateBody(&bd); - m_bullet->CreateFixture(&fd); + m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f)); + } + } + } - m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f)); - } - } - } + static Test* Create() + { + return new BoxStack; + } - static Test* Create() { return new BoxStack; } - - b2Body* m_bullet; - b2Body* m_bodies[e_rowCount * e_columnCount]; - int32 m_indices[e_rowCount * e_columnCount]; + b2Body* m_bullet; + b2Body* m_bodies[e_rowCount * e_columnCount]; + int32 m_indices[e_rowCount * e_columnCount]; }; static int testIndex = RegisterTest("Stacking", "Boxes", BoxStack::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/breakable.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/breakable.cpp index 1128a56ef4..136244a49d 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/breakable.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/breakable.cpp @@ -26,129 +26,133 @@ class Breakable : public Test { public: - enum - { - e_count = 7 - }; - Breakable() - { - // Ground body - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + enum + { + e_count = 7 + }; - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + Breakable() + { + // Ground body + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - // Breakable dynamic body - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 40.0f); - bd.angle = 0.25f * b2_pi; - m_body1 = m_world->CreateBody(&bd); + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - m_shape1.SetAsBox(0.5f, 0.5f, b2Vec2(-0.5f, 0.0f), 0.0f); - m_piece1 = m_body1->CreateFixture(&m_shape1, 1.0f); + // Breakable dynamic body + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 40.0f); + bd.angle = 0.25f * b2_pi; + m_body1 = m_world->CreateBody(&bd); - m_shape2.SetAsBox(0.5f, 0.5f, b2Vec2(0.5f, 0.0f), 0.0f); - m_piece2 = m_body1->CreateFixture(&m_shape2, 1.0f); - } + m_shape1.SetAsBox(0.5f, 0.5f, b2Vec2(-0.5f, 0.0f), 0.0f); + m_piece1 = m_body1->CreateFixture(&m_shape1, 1.0f); - m_break = false; - m_broke = false; - } + m_shape2.SetAsBox(0.5f, 0.5f, b2Vec2(0.5f, 0.0f), 0.0f); + m_piece2 = m_body1->CreateFixture(&m_shape2, 1.0f); + } - void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) override - { - if (m_broke) - { - // The body already broke. - return; - } + m_break = false; + m_broke = false; + } - // Should the body break? - int32 count = contact->GetManifold()->pointCount; + void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) override + { + if (m_broke) + { + // The body already broke. + return; + } - float maxImpulse = 0.0f; - for (int32 i = 0; i < count; ++i) - { - maxImpulse = b2Max(maxImpulse, impulse->normalImpulses[i]); - } + // Should the body break? + int32 count = contact->GetManifold()->pointCount; - if (maxImpulse > 40.0f) - { - // Flag the body for breaking. - m_break = true; - } - } + float maxImpulse = 0.0f; + for (int32 i = 0; i < count; ++i) + { + maxImpulse = b2Max(maxImpulse, impulse->normalImpulses[i]); + } - void Break() - { - // Create two bodies from one. - b2Body* body1 = m_piece1->GetBody(); - b2Vec2 center = body1->GetWorldCenter(); + if (maxImpulse > 40.0f) + { + // Flag the body for breaking. + m_break = true; + } + } - body1->DestroyFixture(m_piece2); - m_piece2 = NULL; + void Break() + { + // Create two bodies from one. + b2Body* body1 = m_piece1->GetBody(); + b2Vec2 center = body1->GetWorldCenter(); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = body1->GetPosition(); - bd.angle = body1->GetAngle(); + body1->DestroyFixture(m_piece2); + m_piece2 = NULL; - b2Body* body2 = m_world->CreateBody(&bd); - m_piece2 = body2->CreateFixture(&m_shape2, 1.0f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = body1->GetPosition(); + bd.angle = body1->GetAngle(); - // Compute consistent velocities for new bodies based on - // cached velocity. - b2Vec2 center1 = body1->GetWorldCenter(); - b2Vec2 center2 = body2->GetWorldCenter(); + b2Body* body2 = m_world->CreateBody(&bd); + m_piece2 = body2->CreateFixture(&m_shape2, 1.0f); - b2Vec2 velocity1 = m_velocity + b2Cross(m_angularVelocity, center1 - center); - b2Vec2 velocity2 = m_velocity + b2Cross(m_angularVelocity, center2 - center); + // Compute consistent velocities for new bodies based on + // cached velocity. + b2Vec2 center1 = body1->GetWorldCenter(); + b2Vec2 center2 = body2->GetWorldCenter(); + + b2Vec2 velocity1 = m_velocity + b2Cross(m_angularVelocity, center1 - center); + b2Vec2 velocity2 = m_velocity + b2Cross(m_angularVelocity, center2 - center); - body1->SetAngularVelocity(m_angularVelocity); - body1->SetLinearVelocity(velocity1); + body1->SetAngularVelocity(m_angularVelocity); + body1->SetLinearVelocity(velocity1); - body2->SetAngularVelocity(m_angularVelocity); - body2->SetLinearVelocity(velocity2); - } + body2->SetAngularVelocity(m_angularVelocity); + body2->SetLinearVelocity(velocity2); + } - void Step(Settings& settings) override - { - if (m_break) - { - Break(); - m_broke = true; - m_break = false; - } + void Step(Settings& settings) override + { + if (m_break) + { + Break(); + m_broke = true; + m_break = false; + } - // Cache velocities to improve movement on breakage. - if (m_broke == false) - { - m_velocity = m_body1->GetLinearVelocity(); - m_angularVelocity = m_body1->GetAngularVelocity(); - } + // Cache velocities to improve movement on breakage. + if (m_broke == false) + { + m_velocity = m_body1->GetLinearVelocity(); + m_angularVelocity = m_body1->GetAngularVelocity(); + } - Test::Step(settings); - } + Test::Step(settings); + } - static Test* Create() { return new Breakable; } + static Test* Create() + { + return new Breakable; + } - b2Body* m_body1; - b2Vec2 m_velocity; - float m_angularVelocity; - b2PolygonShape m_shape1; - b2PolygonShape m_shape2; - b2Fixture* m_piece1; - b2Fixture* m_piece2; + b2Body* m_body1; + b2Vec2 m_velocity; + float m_angularVelocity; + b2PolygonShape m_shape1; + b2PolygonShape m_shape2; + b2Fixture* m_piece1; + b2Fixture* m_piece2; - bool m_broke; - bool m_break; + bool m_broke; + bool m_break; }; static int testIndex = RegisterTest("Examples", "Breakable", Breakable::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/bridge.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/bridge.cpp index 69bfab2cf1..d397a607da 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/bridge.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/bridge.cpp @@ -25,100 +25,104 @@ class Bridge : public Test { public: - enum - { - e_count = 30 - }; - Bridge() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + enum + { + e_count = 30 + }; - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + Bridge() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.125f); + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.friction = 0.2f; + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.125f); - b2RevoluteJointDef jd; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.friction = 0.2f; - b2Body* prevBody = ground; - for (int32 i = 0; i < e_count; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-14.5f + 1.0f * i, 5.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); + b2RevoluteJointDef jd; - b2Vec2 anchor(-15.0f + 1.0f * i, 5.0f); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); + b2Body* prevBody = ground; + for (int32 i = 0; i < e_count; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-14.5f + 1.0f * i, 5.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); - if (i == (e_count >> 1)) - { - m_middle = body; - } - prevBody = body; - } + b2Vec2 anchor(-15.0f + 1.0f * i, 5.0f); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); - b2Vec2 anchor(-15.0f + 1.0f * e_count, 5.0f); - jd.Initialize(prevBody, ground, anchor); - m_world->CreateJoint(&jd); - } + if (i == (e_count >> 1)) + { + m_middle = body; + } + prevBody = body; + } - for (int32 i = 0; i < 2; ++i) - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.5f, 0.0f); - vertices[1].Set(0.5f, 0.0f); - vertices[2].Set(0.0f, 1.5f); + b2Vec2 anchor(-15.0f + 1.0f * e_count, 5.0f); + jd.Initialize(prevBody, ground, anchor); + m_world->CreateJoint(&jd); + } - b2PolygonShape shape; - shape.Set(vertices, 3); + for (int32 i = 0; i < 2; ++i) + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.5f, 0.0f); + vertices[1].Set(0.5f, 0.0f); + vertices[2].Set(0.0f, 1.5f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; + b2PolygonShape shape; + shape.Set(vertices, 3); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-8.0f + 8.0f * i, 12.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - } + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; - for (int32 i = 0; i < 3; ++i) - { - b2CircleShape shape; - shape.m_radius = 0.5f; + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-8.0f + 8.0f * i, 12.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + } - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; + for (int32 i = 0; i < 3; ++i) + { + b2CircleShape shape; + shape.m_radius = 0.5f; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-6.0f + 6.0f * i, 10.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - } - } + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; - static Test* Create() { return new Bridge; } + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-6.0f + 6.0f * i, 10.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + } + } - b2Body* m_middle; + static Test* Create() + { + return new Bridge; + } + + b2Body* m_middle; }; static int testIndex = RegisterTest("Joints", "Bridge", Bridge::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/bullet_test.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/bullet_test.cpp index 945887da6f..0ff1800f28 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/bullet_test.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/bullet_test.cpp @@ -25,108 +25,115 @@ class BulletTest : public Test { public: - BulletTest() - { - { - b2BodyDef bd; - bd.position.Set(0.0f, 0.0f); - b2Body* body = m_world->CreateBody(&bd); - b2EdgeShape edge; + BulletTest() + { + { + b2BodyDef bd; + bd.position.Set(0.0f, 0.0f); + b2Body* body = m_world->CreateBody(&bd); - edge.SetTwoSided(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); - body->CreateFixture(&edge, 0.0f); + b2EdgeShape edge; - b2PolygonShape shape; - shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f); - body->CreateFixture(&shape, 0.0f); - } + edge.SetTwoSided(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); + body->CreateFixture(&edge, 0.0f); - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 4.0f); + b2PolygonShape shape; + shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f); + body->CreateFixture(&shape, 0.0f); + } - b2PolygonShape box; - box.SetAsBox(2.0f, 0.1f); + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 4.0f); - m_body = m_world->CreateBody(&bd); - m_body->CreateFixture(&box, 1.0f); + b2PolygonShape box; + box.SetAsBox(2.0f, 0.1f); - box.SetAsBox(0.25f, 0.25f); + m_body = m_world->CreateBody(&bd); + m_body->CreateFixture(&box, 1.0f); - // m_x = RandomFloat(-1.0f, 1.0f); - m_x = 0.20352793f; - bd.position.Set(m_x, 10.0f); - bd.bullet = true; + box.SetAsBox(0.25f, 0.25f); - m_bullet = m_world->CreateBody(&bd); - m_bullet->CreateFixture(&box, 100.0f); + //m_x = RandomFloat(-1.0f, 1.0f); + m_x = 0.20352793f; + bd.position.Set(m_x, 10.0f); + bd.bullet = true; - m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); - } - } + m_bullet = m_world->CreateBody(&bd); + m_bullet->CreateFixture(&box, 100.0f); - void Launch() - { - m_body->SetTransform(b2Vec2(0.0f, 4.0f), 0.0f); - m_body->SetLinearVelocity(b2Vec2_zero); - m_body->SetAngularVelocity(0.0f); + m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); + } + } - m_x = RandomFloat(-1.0f, 1.0f); - m_bullet->SetTransform(b2Vec2(m_x, 10.0f), 0.0f); - m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); - m_bullet->SetAngularVelocity(0.0f); + void Launch() + { + m_body->SetTransform(b2Vec2(0.0f, 4.0f), 0.0f); + m_body->SetLinearVelocity(b2Vec2_zero); + m_body->SetAngularVelocity(0.0f); - extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; - extern B2_API int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters; - extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; + m_x = RandomFloat(-1.0f, 1.0f); + m_bullet->SetTransform(b2Vec2(m_x, 10.0f), 0.0f); + m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); + m_bullet->SetAngularVelocity(0.0f); - b2_gjkCalls = 0; - b2_gjkIters = 0; - b2_gjkMaxIters = 0; + extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; + extern B2_API int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters; + extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; - b2_toiCalls = 0; - b2_toiIters = 0; - b2_toiMaxIters = 0; - b2_toiRootIters = 0; - b2_toiMaxRootIters = 0; - } + b2_gjkCalls = 0; + b2_gjkIters = 0; + b2_gjkMaxIters = 0; - void Step(Settings& settings) override - { - Test::Step(settings); + b2_toiCalls = 0; + b2_toiIters = 0; + b2_toiMaxIters = 0; + b2_toiRootIters = 0; + b2_toiMaxRootIters = 0; + } - extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; - extern B2_API int32 b2_toiCalls, b2_toiIters; - extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; + void Step(Settings& settings) override + { + Test::Step(settings); - if (b2_gjkCalls > 0) - { - DrawString(5, m_textLine, "gjk calls = %d, ave gjk iters = %3.1f, max gjk iters = %d", b2_gjkCalls, - b2_gjkIters / float(b2_gjkCalls), b2_gjkMaxIters); - } + extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; + extern B2_API int32 b2_toiCalls, b2_toiIters; + extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; - if (b2_toiCalls > 0) - { - DrawString(5, m_textLine, "toi calls = %d, ave toi iters = %3.1f, max toi iters = %d", b2_toiCalls, - b2_toiIters / float(b2_toiCalls), b2_toiMaxRootIters); + if (b2_gjkCalls > 0) + { + DrawString(5, m_textLine, "gjk calls = %d, ave gjk iters = %3.1f, max gjk iters = %d", + b2_gjkCalls, b2_gjkIters / float(b2_gjkCalls), b2_gjkMaxIters); + + } - DrawString(5, m_textLine, "ave toi root iters = %3.1f, max toi root iters = %d", - b2_toiRootIters / float(b2_toiCalls), b2_toiMaxRootIters); - } + if (b2_toiCalls > 0) + { + DrawString(5, m_textLine, "toi calls = %d, ave toi iters = %3.1f, max toi iters = %d", + b2_toiCalls, b2_toiIters / float(b2_toiCalls), b2_toiMaxRootIters); + - if (m_stepCount % 60 == 0) - { - Launch(); - } - } + DrawString(5, m_textLine, "ave toi root iters = %3.1f, max toi root iters = %d", + b2_toiRootIters / float(b2_toiCalls), b2_toiMaxRootIters); + + } - static Test* Create() { return new BulletTest; } + if (m_stepCount % 60 == 0) + { + Launch(); + } + } - b2Body* m_body; - b2Body* m_bullet; - float m_x; + static Test* Create() + { + return new BulletTest; + } + + b2Body* m_body; + b2Body* m_bullet; + float m_x; }; static int testIndex = RegisterTest("Continuous", "Bullet Test", BulletTest::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/cantilever.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/cantilever.cpp index 8a9ffce0b7..e54717b76b 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/cantilever.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/cantilever.cpp @@ -29,186 +29,190 @@ class Cantilever : public Test { public: - enum - { - e_count = 8 - }; - Cantilever() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + enum + { + e_count = 8 + }; - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + Cantilever() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.125f); + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.125f); - b2WeldJointDef jd; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; - b2Body* prevBody = ground; - for (int32 i = 0; i < e_count; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-14.5f + 1.0f * i, 5.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); + b2WeldJointDef jd; - b2Vec2 anchor(-15.0f + 1.0f * i, 5.0f); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); + b2Body* prevBody = ground; + for (int32 i = 0; i < e_count; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-14.5f + 1.0f * i, 5.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); - prevBody = body; - } - } + b2Vec2 anchor(-15.0f + 1.0f * i, 5.0f); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); - { - b2PolygonShape shape; - shape.SetAsBox(1.0f, 0.125f); + prevBody = body; + } + } - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; + { + b2PolygonShape shape; + shape.SetAsBox(1.0f, 0.125f); - b2WeldJointDef jd; - float frequencyHz = 5.0f; - float dampingRatio = 0.7f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; - b2Body* prevBody = ground; - for (int32 i = 0; i < 3; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-14.0f + 2.0f * i, 15.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); + b2WeldJointDef jd; + float frequencyHz = 5.0f; + float dampingRatio = 0.7f; - b2Vec2 anchor(-15.0f + 2.0f * i, 15.0f); - jd.Initialize(prevBody, body, anchor); - b2AngularStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_world->CreateJoint(&jd); + b2Body* prevBody = ground; + for (int32 i = 0; i < 3; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-14.0f + 2.0f * i, 15.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); - prevBody = body; - } - } + b2Vec2 anchor(-15.0f + 2.0f * i, 15.0f); + jd.Initialize(prevBody, body, anchor); + b2AngularStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_world->CreateJoint(&jd); - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.125f); + prevBody = body; + } + } - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.125f); - b2WeldJointDef jd; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; - b2Body* prevBody = ground; - for (int32 i = 0; i < e_count; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-4.5f + 1.0f * i, 5.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); + b2WeldJointDef jd; - if (i > 0) - { - b2Vec2 anchor(-5.0f + 1.0f * i, 5.0f); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); - } + b2Body* prevBody = ground; + for (int32 i = 0; i < e_count; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-4.5f + 1.0f * i, 5.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); - prevBody = body; - } - } + if (i > 0) + { + b2Vec2 anchor(-5.0f + 1.0f * i, 5.0f); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); + } - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.125f); + prevBody = body; + } + } - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.125f); - b2WeldJointDef jd; - float frequencyHz = 8.0f; - float dampingRatio = 0.7f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; - b2Body* prevBody = ground; - for (int32 i = 0; i < e_count; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(5.5f + 1.0f * i, 10.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); + b2WeldJointDef jd; + float frequencyHz = 8.0f; + float dampingRatio = 0.7f; - if (i > 0) - { - b2Vec2 anchor(5.0f + 1.0f * i, 10.0f); - jd.Initialize(prevBody, body, anchor); + b2Body* prevBody = ground; + for (int32 i = 0; i < e_count; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(5.5f + 1.0f * i, 10.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); - b2AngularStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, prevBody, body); + if (i > 0) + { + b2Vec2 anchor(5.0f + 1.0f * i, 10.0f); + jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); - } + b2AngularStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, prevBody, body); - prevBody = body; - } - } + m_world->CreateJoint(&jd); + } - for (int32 i = 0; i < 2; ++i) - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.5f, 0.0f); - vertices[1].Set(0.5f, 0.0f); - vertices[2].Set(0.0f, 1.5f); + prevBody = body; + } + } - b2PolygonShape shape; - shape.Set(vertices, 3); + for (int32 i = 0; i < 2; ++i) + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.5f, 0.0f); + vertices[1].Set(0.5f, 0.0f); + vertices[2].Set(0.0f, 1.5f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; + b2PolygonShape shape; + shape.Set(vertices, 3); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-8.0f + 8.0f * i, 12.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - } + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; - for (int32 i = 0; i < 2; ++i) - { - b2CircleShape shape; - shape.m_radius = 0.5f; + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-8.0f + 8.0f * i, 12.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + } - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; + for (int32 i = 0; i < 2; ++i) + { + b2CircleShape shape; + shape.m_radius = 0.5f; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-6.0f + 6.0f * i, 10.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - } - } + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; - static Test* Create() { return new Cantilever; } + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-6.0f + 6.0f * i, 10.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + } + } - b2Body* m_middle; + static Test* Create() + { + return new Cantilever; + } + + b2Body* m_middle; }; static int testIndex = RegisterTest("Joints", "Cantilever", Cantilever::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/car.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/car.cpp index c8bd9f0875..63179b0526 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/car.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/car.cpp @@ -30,257 +30,261 @@ USING_NS_CC_EXT; class Car : public Test { public: - Car() - { - m_speed = 50.0f; + Car() + { + m_speed = 50.0f; - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; + b2EdgeShape shape; - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 0.0f; - fd.friction = 0.6f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 0.0f; + fd.friction = 0.6f; - shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); - ground->CreateFixture(&fd); + shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); + ground->CreateFixture(&fd); - float hs[10] = {0.25f, 1.0f, 4.0f, 0.0f, 0.0f, -1.0f, -2.0f, -2.0f, -1.25f, 0.0f}; + float hs[10] = {0.25f, 1.0f, 4.0f, 0.0f, 0.0f, -1.0f, -2.0f, -2.0f, -1.25f, 0.0f}; - float x = 20.0f, y1 = 0.0f, dx = 5.0f; + float x = 20.0f, y1 = 0.0f, dx = 5.0f; - for (int32 i = 0; i < 10; ++i) - { - float y2 = hs[i]; - shape.SetTwoSided(b2Vec2(x, y1), b2Vec2(x + dx, y2)); - ground->CreateFixture(&fd); - y1 = y2; - x += dx; - } + for (int32 i = 0; i < 10; ++i) + { + float y2 = hs[i]; + shape.SetTwoSided(b2Vec2(x, y1), b2Vec2(x + dx, y2)); + ground->CreateFixture(&fd); + y1 = y2; + x += dx; + } - for (int32 i = 0; i < 10; ++i) - { - float y2 = hs[i]; - shape.SetTwoSided(b2Vec2(x, y1), b2Vec2(x + dx, y2)); - ground->CreateFixture(&fd); - y1 = y2; - x += dx; - } + for (int32 i = 0; i < 10; ++i) + { + float y2 = hs[i]; + shape.SetTwoSided(b2Vec2(x, y1), b2Vec2(x + dx, y2)); + ground->CreateFixture(&fd); + y1 = y2; + x += dx; + } - shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); - ground->CreateFixture(&fd); + shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); + ground->CreateFixture(&fd); - x += 80.0f; - shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); - ground->CreateFixture(&fd); + x += 80.0f; + shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); + ground->CreateFixture(&fd); - x += 40.0f; - shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x + 10.0f, 5.0f)); - ground->CreateFixture(&fd); + x += 40.0f; + shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x + 10.0f, 5.0f)); + ground->CreateFixture(&fd); - x += 20.0f; - shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); - ground->CreateFixture(&fd); + x += 20.0f; + shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); + ground->CreateFixture(&fd); - x += 40.0f; - shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x, 20.0f)); - ground->CreateFixture(&fd); - } + x += 40.0f; + shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x, 20.0f)); + ground->CreateFixture(&fd); + } - // Teeter - { - b2BodyDef bd; - bd.position.Set(140.0f, 1.0f); - bd.type = b2_dynamicBody; - b2Body* body = m_world->CreateBody(&bd); + // Teeter + { + b2BodyDef bd; + bd.position.Set(140.0f, 1.0f); + bd.type = b2_dynamicBody; + b2Body* body = m_world->CreateBody(&bd); - b2PolygonShape box; - box.SetAsBox(10.0f, 0.25f); - body->CreateFixture(&box, 1.0f); + b2PolygonShape box; + box.SetAsBox(10.0f, 0.25f); + body->CreateFixture(&box, 1.0f); - b2RevoluteJointDef jd; - jd.Initialize(ground, body, body->GetPosition()); - jd.lowerAngle = -8.0f * b2_pi / 180.0f; - jd.upperAngle = 8.0f * b2_pi / 180.0f; - jd.enableLimit = true; - m_world->CreateJoint(&jd); + b2RevoluteJointDef jd; + jd.Initialize(ground, body, body->GetPosition()); + jd.lowerAngle = -8.0f * b2_pi / 180.0f; + jd.upperAngle = 8.0f * b2_pi / 180.0f; + jd.enableLimit = true; + m_world->CreateJoint(&jd); - body->ApplyAngularImpulse(100.0f, true); - } + body->ApplyAngularImpulse(100.0f, true); + } - // Bridge - { - int32 N = 20; - b2PolygonShape shape; - shape.SetAsBox(1.0f, 0.125f); + // Bridge + { + int32 N = 20; + b2PolygonShape shape; + shape.SetAsBox(1.0f, 0.125f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - fd.friction = 0.6f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + fd.friction = 0.6f; - b2RevoluteJointDef jd; + b2RevoluteJointDef jd; - b2Body* prevBody = ground; - for (int32 i = 0; i < N; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(161.0f + 2.0f * i, -0.125f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); + b2Body* prevBody = ground; + for (int32 i = 0; i < N; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(161.0f + 2.0f * i, -0.125f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); - b2Vec2 anchor(160.0f + 2.0f * i, -0.125f); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); + b2Vec2 anchor(160.0f + 2.0f * i, -0.125f); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); - prevBody = body; - } + prevBody = body; + } - b2Vec2 anchor(160.0f + 2.0f * N, -0.125f); - jd.Initialize(prevBody, ground, anchor); - m_world->CreateJoint(&jd); - } + b2Vec2 anchor(160.0f + 2.0f * N, -0.125f); + jd.Initialize(prevBody, ground, anchor); + m_world->CreateJoint(&jd); + } - // Boxes - { - b2PolygonShape box; - box.SetAsBox(0.5f, 0.5f); + // Boxes + { + b2PolygonShape box; + box.SetAsBox(0.5f, 0.5f); - b2Body* body = NULL; - b2BodyDef bd; - bd.type = b2_dynamicBody; + b2Body* body = NULL; + b2BodyDef bd; + bd.type = b2_dynamicBody; - bd.position.Set(230.0f, 0.5f); - body = m_world->CreateBody(&bd); - body->CreateFixture(&box, 0.5f); + bd.position.Set(230.0f, 0.5f); + body = m_world->CreateBody(&bd); + body->CreateFixture(&box, 0.5f); - bd.position.Set(230.0f, 1.5f); - body = m_world->CreateBody(&bd); - body->CreateFixture(&box, 0.5f); + bd.position.Set(230.0f, 1.5f); + body = m_world->CreateBody(&bd); + body->CreateFixture(&box, 0.5f); - bd.position.Set(230.0f, 2.5f); - body = m_world->CreateBody(&bd); - body->CreateFixture(&box, 0.5f); + bd.position.Set(230.0f, 2.5f); + body = m_world->CreateBody(&bd); + body->CreateFixture(&box, 0.5f); - bd.position.Set(230.0f, 3.5f); - body = m_world->CreateBody(&bd); - body->CreateFixture(&box, 0.5f); + bd.position.Set(230.0f, 3.5f); + body = m_world->CreateBody(&bd); + body->CreateFixture(&box, 0.5f); - bd.position.Set(230.0f, 4.5f); - body = m_world->CreateBody(&bd); - body->CreateFixture(&box, 0.5f); - } + bd.position.Set(230.0f, 4.5f); + body = m_world->CreateBody(&bd); + body->CreateFixture(&box, 0.5f); + } - // Car - { - b2PolygonShape chassis; - b2Vec2 vertices[8]; - vertices[0].Set(-1.5f, -0.5f); - vertices[1].Set(1.5f, -0.5f); - vertices[2].Set(1.5f, 0.0f); - vertices[3].Set(0.0f, 0.9f); - vertices[4].Set(-1.15f, 0.9f); - vertices[5].Set(-1.5f, 0.2f); - chassis.Set(vertices, 6); + // Car + { + b2PolygonShape chassis; + b2Vec2 vertices[8]; + vertices[0].Set(-1.5f, -0.5f); + vertices[1].Set(1.5f, -0.5f); + vertices[2].Set(1.5f, 0.0f); + vertices[3].Set(0.0f, 0.9f); + vertices[4].Set(-1.15f, 0.9f); + vertices[5].Set(-1.5f, 0.2f); + chassis.Set(vertices, 6); - b2CircleShape circle; - circle.m_radius = 0.4f; + b2CircleShape circle; + circle.m_radius = 0.4f; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 1.0f); - m_car = m_world->CreateBody(&bd); - m_car->CreateFixture(&chassis, 1.0f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 1.0f); + m_car = m_world->CreateBody(&bd); + m_car->CreateFixture(&chassis, 1.0f); - b2FixtureDef fd; - fd.shape = &circle; - fd.density = 1.0f; - fd.friction = 0.9f; + b2FixtureDef fd; + fd.shape = &circle; + fd.density = 1.0f; + fd.friction = 0.9f; - bd.position.Set(-1.0f, 0.35f); - m_wheel1 = m_world->CreateBody(&bd); - m_wheel1->CreateFixture(&fd); + bd.position.Set(-1.0f, 0.35f); + m_wheel1 = m_world->CreateBody(&bd); + m_wheel1->CreateFixture(&fd); - bd.position.Set(1.0f, 0.4f); - m_wheel2 = m_world->CreateBody(&bd); - m_wheel2->CreateFixture(&fd); + bd.position.Set(1.0f, 0.4f); + m_wheel2 = m_world->CreateBody(&bd); + m_wheel2->CreateFixture(&fd); - b2WheelJointDef jd; - b2Vec2 axis(0.0f, 1.0f); + b2WheelJointDef jd; + b2Vec2 axis(0.0f, 1.0f); - float mass1 = m_wheel1->GetMass(); - float mass2 = m_wheel2->GetMass(); + float mass1 = m_wheel1->GetMass(); + float mass2 = m_wheel2->GetMass(); - float hertz = 4.0f; - float dampingRatio = 0.7f; - float omega = 2.0f * b2_pi * hertz; + float hertz = 4.0f; + float dampingRatio = 0.7f; + float omega = 2.0f * b2_pi * hertz; - jd.Initialize(m_car, m_wheel1, m_wheel1->GetPosition(), axis); - jd.motorSpeed = 0.0f; - jd.maxMotorTorque = 20.0f; - jd.enableMotor = true; - jd.stiffness = mass1 * omega * omega; - jd.damping = 2.0f * mass1 * dampingRatio * omega; - jd.lowerTranslation = -0.25f; - jd.upperTranslation = 0.25f; - jd.enableLimit = true; - m_spring1 = (b2WheelJoint*)m_world->CreateJoint(&jd); + jd.Initialize(m_car, m_wheel1, m_wheel1->GetPosition(), axis); + jd.motorSpeed = 0.0f; + jd.maxMotorTorque = 20.0f; + jd.enableMotor = true; + jd.stiffness = mass1 * omega * omega; + jd.damping = 2.0f * mass1 * dampingRatio * omega; + jd.lowerTranslation = -0.25f; + jd.upperTranslation = 0.25f; + jd.enableLimit = true; + m_spring1 = (b2WheelJoint*)m_world->CreateJoint(&jd); - jd.Initialize(m_car, m_wheel2, m_wheel2->GetPosition(), axis); - jd.motorSpeed = 0.0f; - jd.maxMotorTorque = 10.0f; - jd.enableMotor = false; - jd.stiffness = mass2 * omega * omega; - jd.damping = 2.0f * mass2 * dampingRatio * omega; - jd.lowerTranslation = -0.25f; - jd.upperTranslation = 0.25f; - jd.enableLimit = true; - m_spring2 = (b2WheelJoint*)m_world->CreateJoint(&jd); - } - } + jd.Initialize(m_car, m_wheel2, m_wheel2->GetPosition(), axis); + jd.motorSpeed = 0.0f; + jd.maxMotorTorque = 10.0f; + jd.enableMotor = false; + jd.stiffness = mass2 * omega * omega; + jd.damping = 2.0f * mass2 * dampingRatio * omega; + jd.lowerTranslation = -0.25f; + jd.upperTranslation = 0.25f; + jd.enableLimit = true; + m_spring2 = (b2WheelJoint*)m_world->CreateJoint(&jd); + } + } - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_A: - m_spring1->SetMotorSpeed(m_speed); - break; + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_A: + m_spring1->SetMotorSpeed(m_speed); + break; - case GLFW_KEY_S: - m_spring1->SetMotorSpeed(0.0f); - break; + case GLFW_KEY_S: + m_spring1->SetMotorSpeed(0.0f); + break; - case GLFW_KEY_D: - m_spring1->SetMotorSpeed(-m_speed); - break; - } - } + case GLFW_KEY_D: + m_spring1->SetMotorSpeed(-m_speed); + break; + } + } - void Step(Settings& settings) override - { - DrawString(5, m_textLine, "Keys: left = a, brake = s, right = d, hz down = q, hz up = e"); + void Step(Settings& settings) override + { + DrawString(5, m_textLine, "Keys: left = a, brake = s, right = d, hz down = q, hz up = e"); + - // g_camera.m_center.x = m_car->GetPosition().x; - g_debugDraw.debugNodeOffset.x += m_car->GetPosition().x; + //g_camera.m_center.x = m_car->GetPosition().x; + g_debugDraw.debugNodeOffset.x += m_car->GetPosition().x; - Test::Step(settings); - } + Test::Step(settings); + } - static Test* Create() { return new Car; } + static Test* Create() + { + return new Car; + } - b2Body* m_car; - b2Body* m_wheel1; - b2Body* m_wheel2; + b2Body* m_car; + b2Body* m_wheel1; + b2Body* m_wheel2; - float m_speed; - b2WheelJoint* m_spring1; - b2WheelJoint* m_spring2; + float m_speed; + b2WheelJoint* m_spring1; + b2WheelJoint* m_spring2; }; static int testIndex = RegisterTest("Examples", "Car", Car::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/chain.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/chain.cpp index 3520b89330..e1580355e3 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/chain.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/chain.cpp @@ -27,63 +27,66 @@ class Chain : public Test { public: - Chain() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + Chain() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2PolygonShape shape; - shape.SetAsBox(0.6f, 0.125f); + { + b2PolygonShape shape; + shape.SetAsBox(0.6f, 0.125f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.friction = 0.2f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.friction = 0.2f; - b2RevoluteJointDef jd; - jd.collideConnected = false; + b2RevoluteJointDef jd; + jd.collideConnected = false; - const float y = 25.0f; - b2Body* prevBody = ground; - for (int32 i = 0; i < 30; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.5f + i, y); - b2Body* body = m_world->CreateBody(&bd); + const float y = 25.0f; + b2Body* prevBody = ground; + for (int32 i = 0; i < 30; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.5f + i, y); + b2Body* body = m_world->CreateBody(&bd); #if TEST_BAD_BODY == 1 - if (i == 10) - { - // Test zero density dynamic body - fd.density = 0.0f; - } - else - { - fd.density = 20.0f; - } + if (i == 10) + { + // Test zero density dynamic body + fd.density = 0.0f; + } + else + { + fd.density = 20.0f; + } #endif - body->CreateFixture(&fd); + body->CreateFixture(&fd); - b2Vec2 anchor(float(i), y); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); + b2Vec2 anchor(float(i), y); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); - prevBody = body; - } - } - } + prevBody = body; + } + } + } - static Test* Create() { return new Chain; } + static Test* Create() + { + return new Chain; + } }; static int testIndex = RegisterTest("Joints", "Chain", Chain::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/chain_problem.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/chain_problem.cpp index a9a48a8730..4b2ab3828d 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/chain_problem.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/chain_problem.cpp @@ -25,16 +25,17 @@ class ChainProblem : public Test { public: + ChainProblem() { { b2Vec2 g(0.0f, -10.0f); m_world->SetGravity(g); - b2Body** bodies = (b2Body**)b2Alloc(2 * sizeof(b2Body*)); + b2Body** bodies = (b2Body**)b2Alloc(2 * sizeof(b2Body*)); b2Joint** joints = (b2Joint**)b2Alloc(0 * sizeof(b2Joint*)); { b2BodyDef bd; - bd.type = b2BodyType(0); + bd.type = b2BodyType(0); bodies[0] = m_world->CreateBody(&bd); { @@ -55,14 +56,14 @@ public: { b2BodyDef bd; bd.type = b2BodyType(2); - // bd.position.Set(6.033980250358582e-01f, 3.028350114822388e+00f); + //bd.position.Set(6.033980250358582e-01f, 3.028350114822388e+00f); bd.position.Set(1.0f, 3.0f); bodies[1] = m_world->CreateBody(&bd); { b2FixtureDef fd; fd.friction = 0.2f; - fd.density = 10.0f; + fd.density = 10.0f; b2PolygonShape shape; b2Vec2 vs[8]; vs[0].Set(0.5f, -3.0f); @@ -83,7 +84,11 @@ public: } } - static Test* Create() { return new ChainProblem; } + static Test* Create() + { + return new ChainProblem; + } + }; static int testIndex = RegisterTest("Bugs", "Chain Problem", ChainProblem::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/character_collision.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/character_collision.cpp index 42f9f81d6f..42af87aec7 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/character_collision.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/character_collision.cpp @@ -28,225 +28,229 @@ class CharacterCollision : public Test { public: - CharacterCollision() - { - // Ground body - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + CharacterCollision() + { + // Ground body + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - // Collinear edges with no adjacency information. - // This shows the problematic case where a box shape can hit - // an internal vertex. - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + // Collinear edges with no adjacency information. + // This shows the problematic case where a box shape can hit + // an internal vertex. + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-8.0f, 1.0f), b2Vec2(-6.0f, 1.0f)); - ground->CreateFixture(&shape, 0.0f); - shape.SetTwoSided(b2Vec2(-6.0f, 1.0f), b2Vec2(-4.0f, 1.0f)); - ground->CreateFixture(&shape, 0.0f); - shape.SetTwoSided(b2Vec2(-4.0f, 1.0f), b2Vec2(-2.0f, 1.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-8.0f, 1.0f), b2Vec2(-6.0f, 1.0f)); + ground->CreateFixture(&shape, 0.0f); + shape.SetTwoSided(b2Vec2(-6.0f, 1.0f), b2Vec2(-4.0f, 1.0f)); + ground->CreateFixture(&shape, 0.0f); + shape.SetTwoSided(b2Vec2(-4.0f, 1.0f), b2Vec2(-2.0f, 1.0f)); + ground->CreateFixture(&shape, 0.0f); + } - // Chain shape - { - b2BodyDef bd; - bd.angle = 0.25f * b2_pi; - b2Body* ground = m_world->CreateBody(&bd); + // Chain shape + { + b2BodyDef bd; + bd.angle = 0.25f * b2_pi; + b2Body* ground = m_world->CreateBody(&bd); - b2Vec2 vs[4]; - vs[0].Set(5.0f, 7.0f); - vs[1].Set(6.0f, 8.0f); - vs[2].Set(7.0f, 8.0f); - vs[3].Set(8.0f, 7.0f); - b2ChainShape shape; - shape.CreateLoop(vs, 4); - ground->CreateFixture(&shape, 0.0f); - } + b2Vec2 vs[4]; + vs[0].Set(5.0f, 7.0f); + vs[1].Set(6.0f, 8.0f); + vs[2].Set(7.0f, 8.0f); + vs[3].Set(8.0f, 7.0f); + b2ChainShape shape; + shape.CreateLoop(vs, 4); + ground->CreateFixture(&shape, 0.0f); + } - // Square tiles. This shows that adjacency shapes may - // have non-smooth collision. There is no solution - // to this problem. - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + // Square tiles. This shows that adjacency shapes may + // have non-smooth collision. There is no solution + // to this problem. + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(1.0f, 1.0f, b2Vec2(4.0f, 3.0f), 0.0f); - ground->CreateFixture(&shape, 0.0f); - shape.SetAsBox(1.0f, 1.0f, b2Vec2(6.0f, 3.0f), 0.0f); - ground->CreateFixture(&shape, 0.0f); - shape.SetAsBox(1.0f, 1.0f, b2Vec2(8.0f, 3.0f), 0.0f); - ground->CreateFixture(&shape, 0.0f); - } + b2PolygonShape shape; + shape.SetAsBox(1.0f, 1.0f, b2Vec2(4.0f, 3.0f), 0.0f); + ground->CreateFixture(&shape, 0.0f); + shape.SetAsBox(1.0f, 1.0f, b2Vec2(6.0f, 3.0f), 0.0f); + ground->CreateFixture(&shape, 0.0f); + shape.SetAsBox(1.0f, 1.0f, b2Vec2(8.0f, 3.0f), 0.0f); + ground->CreateFixture(&shape, 0.0f); + } - // Square made from an edge loop. Collision should be smooth. - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + // Square made from an edge loop. Collision should be smooth. + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2Vec2 vs[4]; - vs[0].Set(-1.0f, 3.0f); - vs[1].Set(1.0f, 3.0f); - vs[2].Set(1.0f, 5.0f); - vs[3].Set(-1.0f, 5.0f); - b2ChainShape shape; - shape.CreateLoop(vs, 4); - ground->CreateFixture(&shape, 0.0f); - } + b2Vec2 vs[4]; + vs[0].Set(-1.0f, 3.0f); + vs[1].Set(1.0f, 3.0f); + vs[2].Set(1.0f, 5.0f); + vs[3].Set(-1.0f, 5.0f); + b2ChainShape shape; + shape.CreateLoop(vs, 4); + ground->CreateFixture(&shape, 0.0f); + } - // Edge loop. Collision should be smooth. - { - b2BodyDef bd; - bd.position.Set(-10.0f, 4.0f); - b2Body* ground = m_world->CreateBody(&bd); + // Edge loop. Collision should be smooth. + { + b2BodyDef bd; + bd.position.Set(-10.0f, 4.0f); + b2Body* ground = m_world->CreateBody(&bd); - b2Vec2 vs[10]; - vs[0].Set(0.0f, 0.0f); - vs[1].Set(6.0f, 0.0f); - vs[2].Set(6.0f, 2.0f); - vs[3].Set(4.0f, 1.0f); - vs[4].Set(2.0f, 2.0f); - vs[5].Set(0.0f, 2.0f); - vs[6].Set(-2.0f, 2.0f); - vs[7].Set(-4.0f, 3.0f); - vs[8].Set(-6.0f, 2.0f); - vs[9].Set(-6.0f, 0.0f); - b2ChainShape shape; - shape.CreateLoop(vs, 10); - ground->CreateFixture(&shape, 0.0f); - } + b2Vec2 vs[10]; + vs[0].Set(0.0f, 0.0f); + vs[1].Set(6.0f, 0.0f); + vs[2].Set(6.0f, 2.0f); + vs[3].Set(4.0f, 1.0f); + vs[4].Set(2.0f, 2.0f); + vs[5].Set(0.0f, 2.0f); + vs[6].Set(-2.0f, 2.0f); + vs[7].Set(-4.0f, 3.0f); + vs[8].Set(-6.0f, 2.0f); + vs[9].Set(-6.0f, 0.0f); + b2ChainShape shape; + shape.CreateLoop(vs, 10); + ground->CreateFixture(&shape, 0.0f); + } - // Square character 1 - { - b2BodyDef bd; - bd.position.Set(-3.0f, 8.0f); - bd.type = b2_dynamicBody; - bd.fixedRotation = true; - bd.allowSleep = false; + // Square character 1 + { + b2BodyDef bd; + bd.position.Set(-3.0f, 8.0f); + bd.type = b2_dynamicBody; + bd.fixedRotation = true; + bd.allowSleep = false; - b2Body* body = m_world->CreateBody(&bd); + b2Body* body = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - body->CreateFixture(&fd); - } + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + body->CreateFixture(&fd); + } - // Square character 2 - { - b2BodyDef bd; - bd.position.Set(-5.0f, 5.0f); - bd.type = b2_dynamicBody; - bd.fixedRotation = true; - bd.allowSleep = false; + // Square character 2 + { + b2BodyDef bd; + bd.position.Set(-5.0f, 5.0f); + bd.type = b2_dynamicBody; + bd.fixedRotation = true; + bd.allowSleep = false; - b2Body* body = m_world->CreateBody(&bd); + b2Body* body = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(0.25f, 0.25f); + b2PolygonShape shape; + shape.SetAsBox(0.25f, 0.25f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - body->CreateFixture(&fd); - } + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + body->CreateFixture(&fd); + } - // Hexagon character - { - b2BodyDef bd; - bd.position.Set(-5.0f, 8.0f); - bd.type = b2_dynamicBody; - bd.fixedRotation = true; - bd.allowSleep = false; + // Hexagon character + { + b2BodyDef bd; + bd.position.Set(-5.0f, 8.0f); + bd.type = b2_dynamicBody; + bd.fixedRotation = true; + bd.allowSleep = false; - b2Body* body = m_world->CreateBody(&bd); + b2Body* body = m_world->CreateBody(&bd); - float angle = 0.0f; - float delta = b2_pi / 3.0f; - b2Vec2 vertices[6]; - for (int32 i = 0; i < 6; ++i) - { - vertices[i].Set(0.5f * cosf(angle), 0.5f * sinf(angle)); - angle += delta; - } + float angle = 0.0f; + float delta = b2_pi / 3.0f; + b2Vec2 vertices[6]; + for (int32 i = 0; i < 6; ++i) + { + vertices[i].Set(0.5f * cosf(angle), 0.5f * sinf(angle)); + angle += delta; + } - b2PolygonShape shape; - shape.Set(vertices, 6); + b2PolygonShape shape; + shape.Set(vertices, 6); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - body->CreateFixture(&fd); - } + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + body->CreateFixture(&fd); + } - // Circle character - { - b2BodyDef bd; - bd.position.Set(3.0f, 5.0f); - bd.type = b2_dynamicBody; - bd.fixedRotation = true; - bd.allowSleep = false; + // Circle character + { + b2BodyDef bd; + bd.position.Set(3.0f, 5.0f); + bd.type = b2_dynamicBody; + bd.fixedRotation = true; + bd.allowSleep = false; - b2Body* body = m_world->CreateBody(&bd); + b2Body* body = m_world->CreateBody(&bd); - b2CircleShape shape; - shape.m_radius = 0.5f; + b2CircleShape shape; + shape.m_radius = 0.5f; - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - body->CreateFixture(&fd); - } + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + body->CreateFixture(&fd); + } - // Circle character - { - b2BodyDef bd; - bd.position.Set(-7.0f, 6.0f); - bd.type = b2_dynamicBody; - bd.allowSleep = false; + // Circle character + { + b2BodyDef bd; + bd.position.Set(-7.0f, 6.0f); + bd.type = b2_dynamicBody; + bd.allowSleep = false; - m_character = m_world->CreateBody(&bd); + m_character = m_world->CreateBody(&bd); - b2CircleShape shape; - shape.m_radius = 0.25f; + b2CircleShape shape; + shape.m_radius = 0.25f; - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.friction = 1.0f; - m_character->CreateFixture(&fd); - } - } + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.friction = 1.0f; + m_character->CreateFixture(&fd); + } + } - void Step(Settings& settings) override - { - b2Vec2 v = m_character->GetLinearVelocity(); - v.x = -5.0f; - m_character->SetLinearVelocity(v); + void Step(Settings& settings) override + { + b2Vec2 v = m_character->GetLinearVelocity(); + v.x = -5.0f; + m_character->SetLinearVelocity(v); - Test::Step(settings); - DrawString(5, m_textLine, "This tests various character collision shapes."); + Test::Step(settings); + DrawString(5, m_textLine, "This tests various character collision shapes."); + + DrawString(5, m_textLine, "Limitation: square and hexagon can snag on aligned boxes."); + + DrawString(5, m_textLine, "Feature: edge chains have smooth collision inside and out."); + + } - DrawString(5, m_textLine, "Limitation: square and hexagon can snag on aligned boxes."); + static Test* Create() + { + return new CharacterCollision; + } - DrawString(5, m_textLine, "Feature: edge chains have smooth collision inside and out."); - } - - static Test* Create() { return new CharacterCollision; } - - b2Body* m_character; + b2Body* m_character; }; static int testIndex = RegisterTest("Examples", "Character Collision", CharacterCollision::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/circle_stack.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/circle_stack.cpp index d642a12d33..62d19ea3fe 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/circle_stack.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/circle_stack.cpp @@ -25,61 +25,65 @@ class CircleStack : public Test { public: - enum - { - e_count = 10 - }; - CircleStack() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + enum + { + e_count = 10 + }; - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + CircleStack() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - { - b2CircleShape shape; - shape.m_radius = 1.0f; + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - for (int32 i = 0; i < e_count; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0, 4.0f + 3.0f * i); + { + b2CircleShape shape; + shape.m_radius = 1.0f; - m_bodies[i] = m_world->CreateBody(&bd); + for (int32 i = 0; i < e_count; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0, 4.0f + 3.0f * i); - m_bodies[i]->CreateFixture(&shape, 1.0f); + m_bodies[i] = m_world->CreateBody(&bd); - m_bodies[i]->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); - } - } - } + m_bodies[i]->CreateFixture(&shape, 1.0f); - void Step(Settings& settings) override - { - Test::Step(settings); + m_bodies[i]->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); + } + } + } - // for (int32 i = 0; i < e_count; ++i) - //{ - // printf("%g ", m_bodies[i]->GetWorldCenter().y); - // } + void Step(Settings& settings) override + { + Test::Step(settings); - // for (int32 i = 0; i < e_count; ++i) - //{ - // printf("%g ", m_bodies[i]->GetLinearVelocity().y); - // } + //for (int32 i = 0; i < e_count; ++i) + //{ + // printf("%g ", m_bodies[i]->GetWorldCenter().y); + //} - // printf("\n"); - } + //for (int32 i = 0; i < e_count; ++i) + //{ + // printf("%g ", m_bodies[i]->GetLinearVelocity().y); + //} - static Test* Create() { return new CircleStack; } + //printf("\n"); + } - b2Body* m_bodies[e_count]; + static Test* Create() + { + return new CircleStack; + } + + b2Body* m_bodies[e_count]; }; static int testIndex = RegisterTest("Stacking", "Circles", CircleStack::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/collision_filtering.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/collision_filtering.cpp index 65acb38668..4903da5f5c 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/collision_filtering.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/collision_filtering.cpp @@ -28,149 +28,152 @@ // The 3 small ones always collide. // The 3 large ones never collide. // The boxes don't collide with triangles (except if both are small). -const int16 k_smallGroup = 1; +const int16 k_smallGroup = 1; const int16 k_largeGroup = -1; const uint16 k_triangleCategory = 0x0002; -const uint16 k_boxCategory = 0x0004; -const uint16 k_circleCategory = 0x0008; +const uint16 k_boxCategory = 0x0004; +const uint16 k_circleCategory = 0x0008; const uint16 k_triangleMask = 0xFFFF; -const uint16 k_boxMask = 0xFFFF ^ k_triangleCategory; -const uint16 k_circleMask = 0xFFFF; +const uint16 k_boxMask = 0xFFFF ^ k_triangleCategory; +const uint16 k_circleMask = 0xFFFF; class CollisionFiltering : public Test { public: - CollisionFiltering() - { - // Ground body - { - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + CollisionFiltering() + { + // Ground body + { + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - b2FixtureDef sd; - sd.shape = &shape; - sd.friction = 0.3f; + b2FixtureDef sd; + sd.shape = &shape; + sd.friction = 0.3f; - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&sd); - } + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&sd); + } - // Small triangle - b2Vec2 vertices[3]; - vertices[0].Set(-1.0f, 0.0f); - vertices[1].Set(1.0f, 0.0f); - vertices[2].Set(0.0f, 2.0f); - b2PolygonShape polygon; - polygon.Set(vertices, 3); + // Small triangle + b2Vec2 vertices[3]; + vertices[0].Set(-1.0f, 0.0f); + vertices[1].Set(1.0f, 0.0f); + vertices[2].Set(0.0f, 2.0f); + b2PolygonShape polygon; + polygon.Set(vertices, 3); - b2FixtureDef triangleShapeDef; - triangleShapeDef.shape = &polygon; - triangleShapeDef.density = 1.0f; + b2FixtureDef triangleShapeDef; + triangleShapeDef.shape = &polygon; + triangleShapeDef.density = 1.0f; - triangleShapeDef.filter.groupIndex = k_smallGroup; - triangleShapeDef.filter.categoryBits = k_triangleCategory; - triangleShapeDef.filter.maskBits = k_triangleMask; + triangleShapeDef.filter.groupIndex = k_smallGroup; + triangleShapeDef.filter.categoryBits = k_triangleCategory; + triangleShapeDef.filter.maskBits = k_triangleMask; - b2BodyDef triangleBodyDef; - triangleBodyDef.type = b2_dynamicBody; - triangleBodyDef.position.Set(-5.0f, 2.0f); + b2BodyDef triangleBodyDef; + triangleBodyDef.type = b2_dynamicBody; + triangleBodyDef.position.Set(-5.0f, 2.0f); - b2Body* body1 = m_world->CreateBody(&triangleBodyDef); - body1->CreateFixture(&triangleShapeDef); + b2Body* body1 = m_world->CreateBody(&triangleBodyDef); + body1->CreateFixture(&triangleShapeDef); - // Large triangle (recycle definitions) - vertices[0] *= 2.0f; - vertices[1] *= 2.0f; - vertices[2] *= 2.0f; - polygon.Set(vertices, 3); - triangleShapeDef.filter.groupIndex = k_largeGroup; - triangleBodyDef.position.Set(-5.0f, 6.0f); - triangleBodyDef.fixedRotation = true; // look at me! + // Large triangle (recycle definitions) + vertices[0] *= 2.0f; + vertices[1] *= 2.0f; + vertices[2] *= 2.0f; + polygon.Set(vertices, 3); + triangleShapeDef.filter.groupIndex = k_largeGroup; + triangleBodyDef.position.Set(-5.0f, 6.0f); + triangleBodyDef.fixedRotation = true; // look at me! - b2Body* body2 = m_world->CreateBody(&triangleBodyDef); - body2->CreateFixture(&triangleShapeDef); + b2Body* body2 = m_world->CreateBody(&triangleBodyDef); + body2->CreateFixture(&triangleShapeDef); - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-5.0f, 10.0f); - b2Body* body = m_world->CreateBody(&bd); + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-5.0f, 10.0f); + b2Body* body = m_world->CreateBody(&bd); - b2PolygonShape p; - p.SetAsBox(0.5f, 1.0f); - body->CreateFixture(&p, 1.0f); + b2PolygonShape p; + p.SetAsBox(0.5f, 1.0f); + body->CreateFixture(&p, 1.0f); - b2PrismaticJointDef jd; - jd.bodyA = body2; - jd.bodyB = body; - jd.enableLimit = true; - jd.localAnchorA.Set(0.0f, 4.0f); - jd.localAnchorB.SetZero(); - jd.localAxisA.Set(0.0f, 1.0f); - jd.lowerTranslation = -1.0f; - jd.upperTranslation = 1.0f; + b2PrismaticJointDef jd; + jd.bodyA = body2; + jd.bodyB = body; + jd.enableLimit = true; + jd.localAnchorA.Set(0.0f, 4.0f); + jd.localAnchorB.SetZero(); + jd.localAxisA.Set(0.0f, 1.0f); + jd.lowerTranslation = -1.0f; + jd.upperTranslation = 1.0f; - m_world->CreateJoint(&jd); - } + m_world->CreateJoint(&jd); + } - // Small box - polygon.SetAsBox(1.0f, 0.5f); - b2FixtureDef boxShapeDef; - boxShapeDef.shape = &polygon; - boxShapeDef.density = 1.0f; - boxShapeDef.restitution = 0.1f; + // Small box + polygon.SetAsBox(1.0f, 0.5f); + b2FixtureDef boxShapeDef; + boxShapeDef.shape = &polygon; + boxShapeDef.density = 1.0f; + boxShapeDef.restitution = 0.1f; - boxShapeDef.filter.groupIndex = k_smallGroup; - boxShapeDef.filter.categoryBits = k_boxCategory; - boxShapeDef.filter.maskBits = k_boxMask; + boxShapeDef.filter.groupIndex = k_smallGroup; + boxShapeDef.filter.categoryBits = k_boxCategory; + boxShapeDef.filter.maskBits = k_boxMask; - b2BodyDef boxBodyDef; - boxBodyDef.type = b2_dynamicBody; - boxBodyDef.position.Set(0.0f, 2.0f); + b2BodyDef boxBodyDef; + boxBodyDef.type = b2_dynamicBody; + boxBodyDef.position.Set(0.0f, 2.0f); - b2Body* body3 = m_world->CreateBody(&boxBodyDef); - body3->CreateFixture(&boxShapeDef); + b2Body* body3 = m_world->CreateBody(&boxBodyDef); + body3->CreateFixture(&boxShapeDef); - // Large box (recycle definitions) - polygon.SetAsBox(2.0f, 1.0f); - boxShapeDef.filter.groupIndex = k_largeGroup; - boxBodyDef.position.Set(0.0f, 6.0f); + // Large box (recycle definitions) + polygon.SetAsBox(2.0f, 1.0f); + boxShapeDef.filter.groupIndex = k_largeGroup; + boxBodyDef.position.Set(0.0f, 6.0f); - b2Body* body4 = m_world->CreateBody(&boxBodyDef); - body4->CreateFixture(&boxShapeDef); + b2Body* body4 = m_world->CreateBody(&boxBodyDef); + body4->CreateFixture(&boxShapeDef); - // Small circle - b2CircleShape circle; - circle.m_radius = 1.0f; + // Small circle + b2CircleShape circle; + circle.m_radius = 1.0f; - b2FixtureDef circleShapeDef; - circleShapeDef.shape = &circle; - circleShapeDef.density = 1.0f; + b2FixtureDef circleShapeDef; + circleShapeDef.shape = &circle; + circleShapeDef.density = 1.0f; - circleShapeDef.filter.groupIndex = k_smallGroup; - circleShapeDef.filter.categoryBits = k_circleCategory; - circleShapeDef.filter.maskBits = k_circleMask; + circleShapeDef.filter.groupIndex = k_smallGroup; + circleShapeDef.filter.categoryBits = k_circleCategory; + circleShapeDef.filter.maskBits = k_circleMask; - b2BodyDef circleBodyDef; - circleBodyDef.type = b2_dynamicBody; - circleBodyDef.position.Set(5.0f, 2.0f); + b2BodyDef circleBodyDef; + circleBodyDef.type = b2_dynamicBody; + circleBodyDef.position.Set(5.0f, 2.0f); + + b2Body* body5 = m_world->CreateBody(&circleBodyDef); + body5->CreateFixture(&circleShapeDef); - b2Body* body5 = m_world->CreateBody(&circleBodyDef); - body5->CreateFixture(&circleShapeDef); + // Large circle + circle.m_radius *= 2.0f; + circleShapeDef.filter.groupIndex = k_largeGroup; + circleBodyDef.position.Set(5.0f, 6.0f); - // Large circle - circle.m_radius *= 2.0f; - circleShapeDef.filter.groupIndex = k_largeGroup; - circleBodyDef.position.Set(5.0f, 6.0f); + b2Body* body6 = m_world->CreateBody(&circleBodyDef); + body6->CreateFixture(&circleShapeDef); + } - b2Body* body6 = m_world->CreateBody(&circleBodyDef); - body6->CreateFixture(&circleShapeDef); - } - - static Test* Create() { return new CollisionFiltering; } + static Test* Create() + { + return new CollisionFiltering; + } }; static int testIndex = RegisterTest("Examples", "Collision Filtering", CollisionFiltering::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/collision_processing.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/collision_processing.cpp index f31db91a3b..1c684bdaec 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/collision_processing.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/collision_processing.cpp @@ -29,161 +29,163 @@ class CollisionProcessing : public Test { public: - CollisionProcessing() - { - // Ground body - { - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-50.0f, 0.0f), b2Vec2(50.0f, 0.0f)); + CollisionProcessing() + { + // Ground body + { + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-50.0f, 0.0f), b2Vec2(50.0f, 0.0f)); - b2FixtureDef sd; - sd.shape = &shape; - ; + b2FixtureDef sd; + sd.shape = &shape;; - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&sd); - } + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&sd); + } - float xLo = -5.0f, xHi = 5.0f; - float yLo = 2.0f, yHi = 35.0f; + float xLo = -5.0f, xHi = 5.0f; + float yLo = 2.0f, yHi = 35.0f; - // Small triangle - b2Vec2 vertices[3]; - vertices[0].Set(-1.0f, 0.0f); - vertices[1].Set(1.0f, 0.0f); - vertices[2].Set(0.0f, 2.0f); + // Small triangle + b2Vec2 vertices[3]; + vertices[0].Set(-1.0f, 0.0f); + vertices[1].Set(1.0f, 0.0f); + vertices[2].Set(0.0f, 2.0f); - b2PolygonShape polygon; - polygon.Set(vertices, 3); + b2PolygonShape polygon; + polygon.Set(vertices, 3); - b2FixtureDef triangleShapeDef; - triangleShapeDef.shape = &polygon; - triangleShapeDef.density = 1.0f; + b2FixtureDef triangleShapeDef; + triangleShapeDef.shape = &polygon; + triangleShapeDef.density = 1.0f; - b2BodyDef triangleBodyDef; - triangleBodyDef.type = b2_dynamicBody; - triangleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + b2BodyDef triangleBodyDef; + triangleBodyDef.type = b2_dynamicBody; + triangleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); - b2Body* body1 = m_world->CreateBody(&triangleBodyDef); - body1->CreateFixture(&triangleShapeDef); + b2Body* body1 = m_world->CreateBody(&triangleBodyDef); + body1->CreateFixture(&triangleShapeDef); - // Large triangle (recycle definitions) - vertices[0] *= 2.0f; - vertices[1] *= 2.0f; - vertices[2] *= 2.0f; - polygon.Set(vertices, 3); + // Large triangle (recycle definitions) + vertices[0] *= 2.0f; + vertices[1] *= 2.0f; + vertices[2] *= 2.0f; + polygon.Set(vertices, 3); - triangleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + triangleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); - b2Body* body2 = m_world->CreateBody(&triangleBodyDef); - body2->CreateFixture(&triangleShapeDef); + b2Body* body2 = m_world->CreateBody(&triangleBodyDef); + body2->CreateFixture(&triangleShapeDef); + + // Small box + polygon.SetAsBox(1.0f, 0.5f); - // Small box - polygon.SetAsBox(1.0f, 0.5f); + b2FixtureDef boxShapeDef; + boxShapeDef.shape = &polygon; + boxShapeDef.density = 1.0f; - b2FixtureDef boxShapeDef; - boxShapeDef.shape = &polygon; - boxShapeDef.density = 1.0f; + b2BodyDef boxBodyDef; + boxBodyDef.type = b2_dynamicBody; + boxBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); - b2BodyDef boxBodyDef; - boxBodyDef.type = b2_dynamicBody; - boxBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + b2Body* body3 = m_world->CreateBody(&boxBodyDef); + body3->CreateFixture(&boxShapeDef); - b2Body* body3 = m_world->CreateBody(&boxBodyDef); - body3->CreateFixture(&boxShapeDef); + // Large box (recycle definitions) + polygon.SetAsBox(2.0f, 1.0f); + boxBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + + b2Body* body4 = m_world->CreateBody(&boxBodyDef); + body4->CreateFixture(&boxShapeDef); - // Large box (recycle definitions) - polygon.SetAsBox(2.0f, 1.0f); - boxBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + // Small circle + b2CircleShape circle; + circle.m_radius = 1.0f; - b2Body* body4 = m_world->CreateBody(&boxBodyDef); - body4->CreateFixture(&boxShapeDef); + b2FixtureDef circleShapeDef; + circleShapeDef.shape = &circle; + circleShapeDef.density = 1.0f; - // Small circle - b2CircleShape circle; - circle.m_radius = 1.0f; + b2BodyDef circleBodyDef; + circleBodyDef.type = b2_dynamicBody; + circleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); - b2FixtureDef circleShapeDef; - circleShapeDef.shape = &circle; - circleShapeDef.density = 1.0f; + b2Body* body5 = m_world->CreateBody(&circleBodyDef); + body5->CreateFixture(&circleShapeDef); - b2BodyDef circleBodyDef; - circleBodyDef.type = b2_dynamicBody; - circleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + // Large circle + circle.m_radius *= 2.0f; + circleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); - b2Body* body5 = m_world->CreateBody(&circleBodyDef); - body5->CreateFixture(&circleShapeDef); + b2Body* body6 = m_world->CreateBody(&circleBodyDef); + body6->CreateFixture(&circleShapeDef); + } - // Large circle - circle.m_radius *= 2.0f; - circleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + void Step(Settings& settings) override + { + Test::Step(settings); - b2Body* body6 = m_world->CreateBody(&circleBodyDef); - body6->CreateFixture(&circleShapeDef); - } + // We are going to destroy some bodies according to contact + // points. We must buffer the bodies that should be destroyed + // because they may belong to multiple contact points. + const int32 k_maxNuke = 6; + b2Body* nuke[k_maxNuke]; + int32 nukeCount = 0; - void Step(Settings& settings) override - { - Test::Step(settings); + // Traverse the contact results. Destroy bodies that + // are touching heavier bodies. + for (int32 i = 0; i < m_pointCount; ++i) + { + ContactPoint* point = m_points + i; - // We are going to destroy some bodies according to contact - // points. We must buffer the bodies that should be destroyed - // because they may belong to multiple contact points. - const int32 k_maxNuke = 6; - b2Body* nuke[k_maxNuke]; - int32 nukeCount = 0; + b2Body* body1 = point->fixtureA->GetBody(); + b2Body* body2 = point->fixtureB->GetBody(); + float mass1 = body1->GetMass(); + float mass2 = body2->GetMass(); - // Traverse the contact results. Destroy bodies that - // are touching heavier bodies. - for (int32 i = 0; i < m_pointCount; ++i) - { - ContactPoint* point = m_points + i; + if (mass1 > 0.0f && mass2 > 0.0f) + { + if (mass2 > mass1) + { + nuke[nukeCount++] = body1; + } + else + { + nuke[nukeCount++] = body2; + } - b2Body* body1 = point->fixtureA->GetBody(); - b2Body* body2 = point->fixtureB->GetBody(); - float mass1 = body1->GetMass(); - float mass2 = body2->GetMass(); + if (nukeCount == k_maxNuke) + { + break; + } + } + } - if (mass1 > 0.0f && mass2 > 0.0f) - { - if (mass2 > mass1) - { - nuke[nukeCount++] = body1; - } - else - { - nuke[nukeCount++] = body2; - } + // Sort the nuke array to group duplicates. + std::sort(nuke, nuke + nukeCount); - if (nukeCount == k_maxNuke) - { - break; - } - } - } + // Destroy the bodies, skipping duplicates. + int32 i = 0; + while (i < nukeCount) + { + b2Body* b = nuke[i++]; + while (i < nukeCount && nuke[i] == b) + { + ++i; + } - // Sort the nuke array to group duplicates. - std::sort(nuke, nuke + nukeCount); + if (b != m_bomb) + { + m_world->DestroyBody(b); + } + } + } - // Destroy the bodies, skipping duplicates. - int32 i = 0; - while (i < nukeCount) - { - b2Body* b = nuke[i++]; - while (i < nukeCount && nuke[i] == b) - { - ++i; - } - - if (b != m_bomb) - { - m_world->DestroyBody(b); - } - } - } - - static Test* Create() { return new CollisionProcessing; } + static Test* Create() + { + return new CollisionProcessing; + } }; static int testIndex = RegisterTest("Examples", "Collision Processing", CollisionProcessing::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/compound_shapes.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/compound_shapes.cpp index 34d2953511..657d8b27b9 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/compound_shapes.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/compound_shapes.cpp @@ -26,199 +26,202 @@ class CompoundShapes : public Test { public: - CompoundShapes() - { - { - b2BodyDef bd; - bd.position.Set(0.0f, 0.0f); - b2Body* body = m_world->CreateBody(&bd); + CompoundShapes() + { + { + b2BodyDef bd; + bd.position.Set(0.0f, 0.0f); + b2Body* body = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(50.0f, 0.0f), b2Vec2(-50.0f, 0.0f)); + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(50.0f, 0.0f), b2Vec2(-50.0f, 0.0f)); - body->CreateFixture(&shape, 0.0f); - } + body->CreateFixture(&shape, 0.0f); + } - // Table 1 - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-15.0f, 1.0f); - m_table1 = m_world->CreateBody(&bd); + // Table 1 + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-15.0f, 1.0f); + m_table1 = m_world->CreateBody(&bd); - b2PolygonShape top; - top.SetAsBox(3.0f, 0.5f, b2Vec2(0.0f, 3.5f), 0.0f); + b2PolygonShape top; + top.SetAsBox(3.0f, 0.5f, b2Vec2(0.0f, 3.5f), 0.0f); - b2PolygonShape leftLeg; - leftLeg.SetAsBox(0.5f, 1.5f, b2Vec2(-2.5f, 1.5f), 0.0f); + b2PolygonShape leftLeg; + leftLeg.SetAsBox(0.5f, 1.5f, b2Vec2(-2.5f, 1.5f), 0.0f); - b2PolygonShape rightLeg; - rightLeg.SetAsBox(0.5f, 1.5f, b2Vec2(2.5f, 1.5f), 0.0f); + b2PolygonShape rightLeg; + rightLeg.SetAsBox(0.5f, 1.5f, b2Vec2(2.5f, 1.5f), 0.0f); - m_table1->CreateFixture(&top, 2.0f); - m_table1->CreateFixture(&leftLeg, 2.0f); - m_table1->CreateFixture(&rightLeg, 2.0f); - } + m_table1->CreateFixture(&top, 2.0f); + m_table1->CreateFixture(&leftLeg, 2.0f); + m_table1->CreateFixture(&rightLeg, 2.0f); + } - // Table 2 - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-5.0f, 1.0f); - m_table2 = m_world->CreateBody(&bd); + // Table 2 + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-5.0f, 1.0f); + m_table2 = m_world->CreateBody(&bd); - b2PolygonShape top; - top.SetAsBox(3.0f, 0.5f, b2Vec2(0.0f, 3.5f), 0.0f); + b2PolygonShape top; + top.SetAsBox(3.0f, 0.5f, b2Vec2(0.0f, 3.5f), 0.0f); - b2PolygonShape leftLeg; - leftLeg.SetAsBox(0.5f, 2.0f, b2Vec2(-2.5f, 2.0f), 0.0f); + b2PolygonShape leftLeg; + leftLeg.SetAsBox(0.5f, 2.0f, b2Vec2(-2.5f, 2.0f), 0.0f); - b2PolygonShape rightLeg; - rightLeg.SetAsBox(0.5f, 2.0f, b2Vec2(2.5f, 2.0f), 0.0f); + b2PolygonShape rightLeg; + rightLeg.SetAsBox(0.5f, 2.0f, b2Vec2(2.5f, 2.0f), 0.0f); - m_table2->CreateFixture(&top, 2.0f); - m_table2->CreateFixture(&leftLeg, 2.0f); - m_table2->CreateFixture(&rightLeg, 2.0f); - } + m_table2->CreateFixture(&top, 2.0f); + m_table2->CreateFixture(&leftLeg, 2.0f); + m_table2->CreateFixture(&rightLeg, 2.0f); + } - // Spaceship 1 - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(5.0f, 1.0f); - m_ship1 = m_world->CreateBody(&bd); + // Spaceship 1 + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(5.0f, 1.0f); + m_ship1 = m_world->CreateBody(&bd); - b2Vec2 vertices[3]; + b2Vec2 vertices[3]; - b2PolygonShape left; - vertices[0].Set(-2.0f, 0.0f); - vertices[1].Set(0.0f, 4.0f / 3.0f); - vertices[2].Set(0.0f, 4.0f); - left.Set(vertices, 3); + b2PolygonShape left; + vertices[0].Set(-2.0f, 0.0f); + vertices[1].Set(0.0f, 4.0f / 3.0f); + vertices[2].Set(0.0f, 4.0f); + left.Set(vertices, 3); - b2PolygonShape right; - vertices[0].Set(2.0f, 0.0f); - vertices[1].Set(0.0f, 4.0f / 3.0f); - vertices[2].Set(0.0f, 4.0f); - right.Set(vertices, 3); + b2PolygonShape right; + vertices[0].Set(2.0f, 0.0f); + vertices[1].Set(0.0f, 4.0f / 3.0f); + vertices[2].Set(0.0f, 4.0f); + right.Set(vertices, 3); - m_ship1->CreateFixture(&left, 2.0f); - m_ship1->CreateFixture(&right, 2.0f); - } + m_ship1->CreateFixture(&left, 2.0f); + m_ship1->CreateFixture(&right, 2.0f); + } - // Spaceship 2 - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(15.0f, 1.0f); - m_ship2 = m_world->CreateBody(&bd); + // Spaceship 2 + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(15.0f, 1.0f); + m_ship2 = m_world->CreateBody(&bd); - b2Vec2 vertices[3]; + b2Vec2 vertices[3]; - b2PolygonShape left; - vertices[0].Set(-2.0f, 0.0f); - vertices[1].Set(1.0f, 2.0f); - vertices[2].Set(0.0f, 4.0f); - left.Set(vertices, 3); + b2PolygonShape left; + vertices[0].Set(-2.0f, 0.0f); + vertices[1].Set(1.0f, 2.0f); + vertices[2].Set(0.0f, 4.0f); + left.Set(vertices, 3); - b2PolygonShape right; - vertices[0].Set(2.0f, 0.0f); - vertices[1].Set(-1.0f, 2.0f); - vertices[2].Set(0.0f, 4.0f); - right.Set(vertices, 3); + b2PolygonShape right; + vertices[0].Set(2.0f, 0.0f); + vertices[1].Set(-1.0f, 2.0f); + vertices[2].Set(0.0f, 4.0f); + right.Set(vertices, 3); - m_ship2->CreateFixture(&left, 2.0f); - m_ship2->CreateFixture(&right, 2.0f); - } - } + m_ship2->CreateFixture(&left, 2.0f); + m_ship2->CreateFixture(&right, 2.0f); + } + } - void Spawn() - { - // Table 1 obstruction - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = m_table1->GetPosition(); - bd.angle = m_table1->GetAngle(); + void Spawn() + { + // Table 1 obstruction + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = m_table1->GetPosition(); + bd.angle = m_table1->GetAngle(); - b2Body* body = m_world->CreateBody(&bd); + b2Body* body = m_world->CreateBody(&bd); - b2PolygonShape box; - box.SetAsBox(4.0f, 0.1f, b2Vec2(0.0f, 3.0f), 0.0f); + b2PolygonShape box; + box.SetAsBox(4.0f, 0.1f, b2Vec2(0.0f, 3.0f), 0.0f); + + body->CreateFixture(&box, 2.0f); + } - body->CreateFixture(&box, 2.0f); - } + // Table 2 obstruction + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = m_table2->GetPosition(); + bd.angle = m_table2->GetAngle(); - // Table 2 obstruction - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = m_table2->GetPosition(); - bd.angle = m_table2->GetAngle(); + b2Body* body = m_world->CreateBody(&bd); - b2Body* body = m_world->CreateBody(&bd); + b2PolygonShape box; + box.SetAsBox(4.0f, 0.1f, b2Vec2(0.0f, 3.0f), 0.0f); + + body->CreateFixture(&box, 2.0f); + } - b2PolygonShape box; - box.SetAsBox(4.0f, 0.1f, b2Vec2(0.0f, 3.0f), 0.0f); + // Ship 1 obstruction + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = m_ship1->GetPosition(); + bd.angle = m_ship1->GetAngle(); + bd.gravityScale = 0.0f; - body->CreateFixture(&box, 2.0f); - } + b2Body* body = m_world->CreateBody(&bd); - // Ship 1 obstruction - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = m_ship1->GetPosition(); - bd.angle = m_ship1->GetAngle(); - bd.gravityScale = 0.0f; + b2CircleShape circle; + circle.m_radius = 0.5f; + circle.m_p.Set(0.0f, 2.0f); - b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&circle, 2.0f); + } - b2CircleShape circle; - circle.m_radius = 0.5f; - circle.m_p.Set(0.0f, 2.0f); + // Ship 2 obstruction + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = m_ship2->GetPosition(); + bd.angle = m_ship2->GetAngle(); + bd.gravityScale = 0.0f; - body->CreateFixture(&circle, 2.0f); - } + b2Body* body = m_world->CreateBody(&bd); - // Ship 2 obstruction - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = m_ship2->GetPosition(); - bd.angle = m_ship2->GetAngle(); - bd.gravityScale = 0.0f; + b2CircleShape circle; + circle.m_radius = 0.5f; + circle.m_p.Set(0.0f, 2.0f); - b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&circle, 2.0f); + } + } - b2CircleShape circle; - circle.m_radius = 0.5f; - circle.m_p.Set(0.0f, 2.0f); + void UpdateUI() override + { + //ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); + ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); + ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_NoResize); - body->CreateFixture(&circle, 2.0f); - } - } + if (ImGui::Button("Spawn")) + { + Spawn(); + } - void UpdateUI() override - { - // ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); - ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); - ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_NoResize); + ImGui::End(); + } - if (ImGui::Button("Spawn")) - { - Spawn(); - } + static Test* Create() + { + return new CompoundShapes; + } - ImGui::End(); - } - - static Test* Create() { return new CompoundShapes; } - - b2Body* m_table1; - b2Body* m_table2; - b2Body* m_ship1; - b2Body* m_ship2; + b2Body* m_table1; + b2Body* m_table2; + b2Body* m_ship1; + b2Body* m_ship2; }; static int testIndex = RegisterTest("Examples", "Compound Shapes", CompoundShapes::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/confined.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/confined.cpp index 44e2f62010..dc0e7cf122 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/confined.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/confined.cpp @@ -25,141 +25,146 @@ class Confined : public Test { public: - enum - { - e_columnCount = 0, - e_rowCount = 0 - }; - Confined() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + enum + { + e_columnCount = 0, + e_rowCount = 0 + }; - b2EdgeShape shape; + Confined() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - // Floor - shape.SetTwoSided(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); + b2EdgeShape shape; - // Left wall - shape.SetTwoSided(b2Vec2(-10.0f, 0.0f), b2Vec2(-10.0f, 20.0f)); - ground->CreateFixture(&shape, 0.0f); + // Floor + shape.SetTwoSided(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); - // Right wall - shape.SetTwoSided(b2Vec2(10.0f, 0.0f), b2Vec2(10.0f, 20.0f)); - ground->CreateFixture(&shape, 0.0f); + // Left wall + shape.SetTwoSided(b2Vec2(-10.0f, 0.0f), b2Vec2(-10.0f, 20.0f)); + ground->CreateFixture(&shape, 0.0f); - // Roof - shape.SetTwoSided(b2Vec2(-10.0f, 20.0f), b2Vec2(10.0f, 20.0f)); - ground->CreateFixture(&shape, 0.0f); - } + // Right wall + shape.SetTwoSided(b2Vec2(10.0f, 0.0f), b2Vec2(10.0f, 20.0f)); + ground->CreateFixture(&shape, 0.0f); - float radius = 0.5f; - b2CircleShape shape; - shape.m_p.SetZero(); - shape.m_radius = radius; + // Roof + shape.SetTwoSided(b2Vec2(-10.0f, 20.0f), b2Vec2(10.0f, 20.0f)); + ground->CreateFixture(&shape, 0.0f); + } - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - fd.friction = 0.1f; + float radius = 0.5f; + b2CircleShape shape; + shape.m_p.SetZero(); + shape.m_radius = radius; - for (int32 j = 0; j < e_columnCount; ++j) - { - for (int i = 0; i < e_rowCount; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-10.0f + (2.1f * j + 1.0f + 0.01f * i) * radius, (2.0f * i + 1.0f) * radius); - b2Body* body = m_world->CreateBody(&bd); + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + fd.friction = 0.1f; - body->CreateFixture(&fd); - } - } + for (int32 j = 0; j < e_columnCount; ++j) + { + for (int i = 0; i < e_rowCount; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-10.0f + (2.1f * j + 1.0f + 0.01f * i) * radius, (2.0f * i + 1.0f) * radius); + b2Body* body = m_world->CreateBody(&bd); - m_world->SetGravity(b2Vec2(0.0f, 0.0f)); - } + body->CreateFixture(&fd); + } + } - void CreateCircle() - { - float radius = 2.0f; - b2CircleShape shape; - shape.m_p.SetZero(); - shape.m_radius = radius; + m_world->SetGravity(b2Vec2(0.0f, 0.0f)); + } - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - fd.friction = 0.0f; + void CreateCircle() + { + float radius = 2.0f; + b2CircleShape shape; + shape.m_p.SetZero(); + shape.m_radius = radius; - b2Vec2 p(RandomFloat(), 3.0f + RandomFloat()); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = p; - // bd.allowSleep = false; - b2Body* body = m_world->CreateBody(&bd); + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + fd.friction = 0.0f; - body->CreateFixture(&fd); - } + b2Vec2 p(RandomFloat(), 3.0f + RandomFloat()); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = p; + //bd.allowSleep = false; + b2Body* body = m_world->CreateBody(&bd); - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_C: - CreateCircle(); - break; - } - } + body->CreateFixture(&fd); + } - void Step(Settings& settings) override - { - bool sleeping = true; - for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext()) - { - if (b->GetType() != b2_dynamicBody) - { - continue; - } + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_C: + CreateCircle(); + break; + } + } - if (b->IsAwake()) - { - sleeping = false; - } - } + void Step(Settings& settings) override + { + bool sleeping = true; + for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext()) + { + if (b->GetType() != b2_dynamicBody) + { + continue; + } - if (m_stepCount == 180) - { - m_stepCount += 0; - } + if (b->IsAwake()) + { + sleeping = false; + } + } - // if (sleeping) - //{ - // CreateCircle(); - // } + if (m_stepCount == 180) + { + m_stepCount += 0; + } - Test::Step(settings); + //if (sleeping) + //{ + // CreateCircle(); + //} - for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext()) - { - if (b->GetType() != b2_dynamicBody) - { - continue; - } + Test::Step(settings); - b2Vec2 p = b->GetPosition(); - if (p.x <= -10.0f || 10.0f <= p.x || p.y <= 0.0f || 20.0f <= p.y) - { - p.x += 0.0f; - } - } + for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext()) + { + if (b->GetType() != b2_dynamicBody) + { + continue; + } - DrawString(5, m_textLine, "Press 'c' to create a circle."); - } + b2Vec2 p = b->GetPosition(); + if (p.x <= -10.0f || 10.0f <= p.x || p.y <= 0.0f || 20.0f <= p.y) + { + p.x += 0.0f; + } + } - static Test* Create() { return new Confined; } + DrawString(5, m_textLine, "Press 'c' to create a circle."); + + } + + static Test* Create() + { + return new Confined; + } }; static int testIndex = RegisterTest("Solver", "Confined", Confined::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/continuous_test.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/continuous_test.cpp index 80187d9daa..d8da4e99c1 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/continuous_test.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/continuous_test.cpp @@ -25,138 +25,136 @@ class ContinuousTest : public Test { public: - ContinuousTest() - { - { - b2BodyDef bd; - bd.position.Set(0.0f, 0.0f); - b2Body* body = m_world->CreateBody(&bd); - b2EdgeShape edge; + ContinuousTest() + { + { + b2BodyDef bd; + bd.position.Set(0.0f, 0.0f); + b2Body* body = m_world->CreateBody(&bd); - edge.SetTwoSided(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); - body->CreateFixture(&edge, 0.0f); + b2EdgeShape edge; - b2PolygonShape shape; - shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f); - body->CreateFixture(&shape, 0.0f); - } + edge.SetTwoSided(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); + body->CreateFixture(&edge, 0.0f); + + b2PolygonShape shape; + shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f); + body->CreateFixture(&shape, 0.0f); + } #if 1 - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 20.0f); - // bd.angle = 0.1f; + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 20.0f); + //bd.angle = 0.1f; - b2PolygonShape shape; - shape.SetAsBox(2.0f, 0.1f); + b2PolygonShape shape; + shape.SetAsBox(2.0f, 0.1f); - m_body = m_world->CreateBody(&bd); - m_body->CreateFixture(&shape, 1.0f); + m_body = m_world->CreateBody(&bd); + m_body->CreateFixture(&shape, 1.0f); - m_angularVelocity = RandomFloat(-50.0f, 50.0f); - // m_angularVelocity = 46.661274f; - m_body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); - m_body->SetAngularVelocity(m_angularVelocity); - } + m_angularVelocity = RandomFloat(-50.0f, 50.0f); + //m_angularVelocity = 46.661274f; + m_body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); + m_body->SetAngularVelocity(m_angularVelocity); + } #else - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 2.0f); - b2Body* body = m_world->CreateBody(&bd); + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 2.0f); + b2Body* body = m_world->CreateBody(&bd); - b2CircleShape shape; - shape.m_p.SetZero(); - shape.m_radius = 0.5f; - body->CreateFixture(&shape, 1.0f); + b2CircleShape shape; + shape.m_p.SetZero(); + shape.m_radius = 0.5f; + body->CreateFixture(&shape, 1.0f); - bd.bullet = true; - bd.position.Set(0.0f, 10.0f); - body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 1.0f); - body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); - } + bd.bullet = true; + bd.position.Set(0.0f, 10.0f); + body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 1.0f); + body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); + } #endif - extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; - extern B2_API int32 b2_toiCalls, b2_toiIters; - extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; - extern B2_API float b2_toiTime, b2_toiMaxTime; + extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; + extern B2_API int32 b2_toiCalls, b2_toiIters; + extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; + extern B2_API float b2_toiTime, b2_toiMaxTime; - b2_gjkCalls = 0; - b2_gjkIters = 0; - b2_gjkMaxIters = 0; - b2_toiCalls = 0; - b2_toiIters = 0; - b2_toiRootIters = 0; - b2_toiMaxRootIters = 0; - b2_toiTime = 0.0f; - b2_toiMaxTime = 0.0f; - } + b2_gjkCalls = 0; b2_gjkIters = 0; b2_gjkMaxIters = 0; + b2_toiCalls = 0; b2_toiIters = 0; + b2_toiRootIters = 0; b2_toiMaxRootIters = 0; + b2_toiTime = 0.0f; b2_toiMaxTime = 0.0f; + } - void Launch() - { - extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; - extern B2_API int32 b2_toiCalls, b2_toiIters; - extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; - extern B2_API float b2_toiTime, b2_toiMaxTime; + void Launch() + { + extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; + extern B2_API int32 b2_toiCalls, b2_toiIters; + extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; + extern B2_API float b2_toiTime, b2_toiMaxTime; - b2_gjkCalls = 0; - b2_gjkIters = 0; - b2_gjkMaxIters = 0; - b2_toiCalls = 0; - b2_toiIters = 0; - b2_toiRootIters = 0; - b2_toiMaxRootIters = 0; - b2_toiTime = 0.0f; - b2_toiMaxTime = 0.0f; + b2_gjkCalls = 0; b2_gjkIters = 0; b2_gjkMaxIters = 0; + b2_toiCalls = 0; b2_toiIters = 0; + b2_toiRootIters = 0; b2_toiMaxRootIters = 0; + b2_toiTime = 0.0f; b2_toiMaxTime = 0.0f; - m_body->SetTransform(b2Vec2(0.0f, 20.0f), 0.0f); - m_angularVelocity = RandomFloat(-50.0f, 50.0f); - m_body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); - m_body->SetAngularVelocity(m_angularVelocity); - } + m_body->SetTransform(b2Vec2(0.0f, 20.0f), 0.0f); + m_angularVelocity = RandomFloat(-50.0f, 50.0f); + m_body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); + m_body->SetAngularVelocity(m_angularVelocity); + } - void Step(Settings& settings) override - { - Test::Step(settings); + void Step(Settings& settings) override + { + Test::Step(settings); - extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; + extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; - if (b2_gjkCalls > 0) - { - DrawString(5, m_textLine, "gjk calls = %d, ave gjk iters = %3.1f, max gjk iters = %d", b2_gjkCalls, - b2_gjkIters / float(b2_gjkCalls), b2_gjkMaxIters); - } + if (b2_gjkCalls > 0) + { + DrawString(5, m_textLine, "gjk calls = %d, ave gjk iters = %3.1f, max gjk iters = %d", + b2_gjkCalls, b2_gjkIters / float(b2_gjkCalls), b2_gjkMaxIters); + + } - extern B2_API int32 b2_toiCalls, b2_toiIters; - extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; - extern B2_API float b2_toiTime, b2_toiMaxTime; + extern B2_API int32 b2_toiCalls, b2_toiIters; + extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; + extern B2_API float b2_toiTime, b2_toiMaxTime; - if (b2_toiCalls > 0) - { - DrawString(5, m_textLine, "toi calls = %d, ave [max] toi iters = %3.1f [%d]", b2_toiCalls, - b2_toiIters / float(b2_toiCalls), b2_toiMaxRootIters); + if (b2_toiCalls > 0) + { + DrawString(5, m_textLine, "toi calls = %d, ave [max] toi iters = %3.1f [%d]", + b2_toiCalls, b2_toiIters / float(b2_toiCalls), b2_toiMaxRootIters); + + + DrawString(5, m_textLine, "ave [max] toi root iters = %3.1f [%d]", + b2_toiRootIters / float(b2_toiCalls), b2_toiMaxRootIters); + - DrawString(5, m_textLine, "ave [max] toi root iters = %3.1f [%d]", b2_toiRootIters / float(b2_toiCalls), - b2_toiMaxRootIters); + DrawString(5, m_textLine, "ave [max] toi time = %.1f [%.1f] (microseconds)", + 1000.0f * b2_toiTime / float(b2_toiCalls), 1000.0f * b2_toiMaxTime); + + } - DrawString(5, m_textLine, "ave [max] toi time = %.1f [%.1f] (microseconds)", - 1000.0f * b2_toiTime / float(b2_toiCalls), 1000.0f * b2_toiMaxTime); - } + if (m_stepCount % 60 == 0) + { + Launch(); + } + } - if (m_stepCount % 60 == 0) - { - Launch(); - } - } + static Test* Create() + { + return new ContinuousTest; + } - static Test* Create() { return new ContinuousTest; } - - b2Body* m_body; - float m_angularVelocity; + b2Body* m_body; + float m_angularVelocity; }; static int testIndex = RegisterTest("Continuous", "Continuous Test", ContinuousTest::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/convex_hull.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/convex_hull.cpp index 44f4da8906..ac047b235e 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/convex_hull.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/convex_hull.cpp @@ -25,84 +25,88 @@ class ConvexHull : public Test { public: - enum - { - e_count = b2_maxPolygonVertices - }; + enum + { + e_count = b2_maxPolygonVertices + }; - ConvexHull() - { - Generate(); - m_auto = false; - } + ConvexHull() + { + Generate(); + m_auto = false; + } - void Generate() - { - b2Vec2 lowerBound(-8.0f, -8.0f); - b2Vec2 upperBound(8.0f, 8.0f); + void Generate() + { + b2Vec2 lowerBound(-8.0f, -8.0f); + b2Vec2 upperBound(8.0f, 8.0f); - for (int32 i = 0; i < e_count; ++i) - { - float x = 10.0f * RandomFloat(); - float y = 10.0f * RandomFloat(); + for (int32 i = 0; i < e_count; ++i) + { + float x = 10.0f * RandomFloat(); + float y = 10.0f * RandomFloat(); - // Clamp onto a square to help create collinearities. - // This will stress the convex hull algorithm. - b2Vec2 v(x, y); - v = b2Clamp(v, lowerBound, upperBound); - m_points[i] = v; - } + // Clamp onto a square to help create collinearities. + // This will stress the convex hull algorithm. + b2Vec2 v(x, y); + v = b2Clamp(v, lowerBound, upperBound); + m_points[i] = v; + } - m_count = e_count; - } + m_count = e_count; + } - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_A: - m_auto = !m_auto; - break; + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_A: + m_auto = !m_auto; + break; - case GLFW_KEY_G: - Generate(); - break; - } - } + case GLFW_KEY_G: + Generate(); + break; + } + } - void Step(Settings& settings) override - { - Test::Step(settings); + void Step(Settings& settings) override + { + Test::Step(settings); - b2PolygonShape shape; - shape.Set(m_points, m_count); + b2PolygonShape shape; + shape.Set(m_points, m_count); - DrawString(5, m_textLine, "Press g to generate a new random convex hull"); + DrawString(5, m_textLine, "Press g to generate a new random convex hull"); + - g_debugDraw.DrawPolygon(shape.m_vertices, shape.m_count, b2Color(0.9f, 0.9f, 0.9f)); + g_debugDraw.DrawPolygon(shape.m_vertices, shape.m_count, b2Color(0.9f, 0.9f, 0.9f)); - for (int32 i = 0; i < m_count; ++i) - { - g_debugDraw.DrawPoint(m_points[i], 3.0f, b2Color(0.3f, 0.9f, 0.3f)); - DrawString(m_points[i] + b2Vec2(0.05f, 0.05f), "%d", i); - } + for (int32 i = 0; i < m_count; ++i) + { + g_debugDraw.DrawPoint(m_points[i], 3.0f, b2Color(0.3f, 0.9f, 0.3f)); + DrawString(m_points[i] + b2Vec2(0.05f, 0.05f), "%d", i); + } - if (shape.Validate() == false) - { - m_textLine += 0; - } + if (shape.Validate() == false) + { + m_textLine += 0; + } - if (m_auto) - { - Generate(); - } - } + if (m_auto) + { + Generate(); + } + } - static Test* Create() { return new ConvexHull; } + static Test* Create() + { + return new ConvexHull; + } - b2Vec2 m_points[b2_maxPolygonVertices]; - int32 m_count; - bool m_auto; + b2Vec2 m_points[b2_maxPolygonVertices]; + int32 m_count; + bool m_auto; }; static int testIndex = RegisterTest("Geometry", "Convex Hull", ConvexHull::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/conveyor_belt.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/conveyor_belt.cpp index 967ff58263..41d4f2c61c 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/conveyor_belt.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/conveyor_belt.cpp @@ -25,70 +25,77 @@ class ConveyorBelt : public Test { public: - ConveyorBelt() - { - // Ground - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + ConveyorBelt() + { + // Ground + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - // Platform - { - b2BodyDef bd; - bd.position.Set(-5.0f, 5.0f); - b2Body* body = m_world->CreateBody(&bd); + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - b2PolygonShape shape; - shape.SetAsBox(10.0f, 0.5f); + // Platform + { + b2BodyDef bd; + bd.position.Set(-5.0f, 5.0f); + b2Body* body = m_world->CreateBody(&bd); - b2FixtureDef fd; - fd.shape = &shape; - fd.friction = 0.8f; - m_platform = body->CreateFixture(&fd); - } + b2PolygonShape shape; + shape.SetAsBox(10.0f, 0.5f); - // Boxes - for (int32 i = 0; i < 5; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-10.0f + 2.0f * i, 7.0f); - b2Body* body = m_world->CreateBody(&bd); + b2FixtureDef fd; + fd.shape = &shape; + fd.friction = 0.8f; + m_platform = body->CreateFixture(&fd); + } - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); - body->CreateFixture(&shape, 20.0f); - } - } + // Boxes + for (int32 i = 0; i < 5; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-10.0f + 2.0f * i, 7.0f); + b2Body* body = m_world->CreateBody(&bd); - void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override - { - Test::PreSolve(contact, oldManifold); + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); + body->CreateFixture(&shape, 20.0f); + } + } - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); + void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override + { + Test::PreSolve(contact, oldManifold); - if (fixtureA == m_platform) - { - contact->SetTangentSpeed(5.0f); - } + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); - if (fixtureB == m_platform) - { - contact->SetTangentSpeed(-5.0f); - } - } + if (fixtureA == m_platform) + { + contact->SetTangentSpeed(5.0f); + } - void Step(Settings& settings) override { Test::Step(settings); } + if (fixtureB == m_platform) + { + contact->SetTangentSpeed(-5.0f); + } + } - static Test* Create() { return new ConveyorBelt; } + void Step(Settings& settings) override + { + Test::Step(settings); + } - b2Fixture* m_platform; + static Test* Create() + { + return new ConveyorBelt; + } + + b2Fixture* m_platform; }; static int testIndex = RegisterTest("Examples", "Conveyor Belt", ConveyorBelt::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/distance_joint.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/distance_joint.cpp index 087b6fcad1..455a600bf2 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/distance_joint.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/distance_joint.cpp @@ -27,94 +27,97 @@ class DistanceJoint : public Test { public: - DistanceJoint() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + DistanceJoint() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.angularDamping = 0.1f; + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.angularDamping = 0.1f; - bd.position.Set(0.0f, 5.0f); - b2Body* body = m_world->CreateBody(&bd); + bd.position.Set(0.0f, 5.0f); + b2Body* body = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); - body->CreateFixture(&shape, 5.0f); + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); + body->CreateFixture(&shape, 5.0f); - m_hertz = 1.0f; - m_dampingRatio = 0.7f; + m_hertz = 1.0f; + m_dampingRatio = 0.7f; - b2DistanceJointDef jd; - jd.Initialize(ground, body, b2Vec2(0.0f, 15.0f), bd.position); - jd.collideConnected = true; - m_length = jd.length; - m_minLength = m_length; - m_maxLength = m_length; - b2LinearStiffness(jd.stiffness, jd.damping, m_hertz, m_dampingRatio, jd.bodyA, jd.bodyB); - m_joint = (b2DistanceJoint*)m_world->CreateJoint(&jd); - } - } + b2DistanceJointDef jd; + jd.Initialize(ground, body, b2Vec2(0.0f, 15.0f), bd.position); + jd.collideConnected = true; + m_length = jd.length; + m_minLength = m_length; + m_maxLength = m_length; + b2LinearStiffness(jd.stiffness, jd.damping, m_hertz, m_dampingRatio, jd.bodyA, jd.bodyB); + m_joint = (b2DistanceJoint*)m_world->CreateJoint(&jd); + } + } - void UpdateUI() override - { - // ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); - ImGui::SetNextWindowSize(ImVec2(260.0f, 150.0f)); - ImGui::Begin("Joint Controls", nullptr, ImGuiWindowFlags_NoResize); + void UpdateUI() override + { + //ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); + ImGui::SetNextWindowSize(ImVec2(260.0f, 150.0f)); + ImGui::Begin("Joint Controls", nullptr, ImGuiWindowFlags_NoResize); - if (ImGui::SliderFloat("Length", &m_length, 0.0f, 20.0f, "%.0f")) - { - m_length = m_joint->SetLength(m_length); - } + if (ImGui::SliderFloat("Length", &m_length, 0.0f, 20.0f, "%.0f")) + { + m_length = m_joint->SetLength(m_length); + } - if (ImGui::SliderFloat("Min Length", &m_minLength, 0.0f, 20.0f, "%.0f")) - { - m_minLength = m_joint->SetMinLength(m_minLength); - } + if (ImGui::SliderFloat("Min Length", &m_minLength, 0.0f, 20.0f, "%.0f")) + { + m_minLength = m_joint->SetMinLength(m_minLength); + } - if (ImGui::SliderFloat("Max Length", &m_maxLength, 0.0f, 20.0f, "%.0f")) - { - m_maxLength = m_joint->SetMaxLength(m_maxLength); - } + if (ImGui::SliderFloat("Max Length", &m_maxLength, 0.0f, 20.0f, "%.0f")) + { + m_maxLength = m_joint->SetMaxLength(m_maxLength); + } - if (ImGui::SliderFloat("Hertz", &m_hertz, 0.0f, 10.0f, "%.1f")) - { - float stiffness; - float damping; - b2LinearStiffness(stiffness, damping, m_hertz, m_dampingRatio, m_joint->GetBodyA(), m_joint->GetBodyB()); - m_joint->SetStiffness(stiffness); - m_joint->SetDamping(damping); - } + if (ImGui::SliderFloat("Hertz", &m_hertz, 0.0f, 10.0f, "%.1f")) + { + float stiffness; + float damping; + b2LinearStiffness(stiffness, damping, m_hertz, m_dampingRatio, m_joint->GetBodyA(), m_joint->GetBodyB()); + m_joint->SetStiffness(stiffness); + m_joint->SetDamping(damping); + } - if (ImGui::SliderFloat("Damping Ratio", &m_dampingRatio, 0.0f, 2.0f, "%.1f")) - { - float stiffness; - float damping; - b2LinearStiffness(stiffness, damping, m_hertz, m_dampingRatio, m_joint->GetBodyA(), m_joint->GetBodyB()); - m_joint->SetStiffness(stiffness); - m_joint->SetDamping(damping); - } + if (ImGui::SliderFloat("Damping Ratio", &m_dampingRatio, 0.0f, 2.0f, "%.1f")) + { + float stiffness; + float damping; + b2LinearStiffness(stiffness, damping, m_hertz, m_dampingRatio, m_joint->GetBodyA(), m_joint->GetBodyB()); + m_joint->SetStiffness(stiffness); + m_joint->SetDamping(damping); + } - ImGui::End(); - } + ImGui::End(); + } - static Test* Create() { return new DistanceJoint; } + static Test* Create() + { + return new DistanceJoint; + } - b2DistanceJoint* m_joint; - float m_length; - float m_minLength; - float m_maxLength; - float m_hertz; - float m_dampingRatio; + b2DistanceJoint* m_joint; + float m_length; + float m_minLength; + float m_maxLength; + float m_hertz; + float m_dampingRatio; }; static int testIndex = RegisterTest("Joints", "Distance Joint", DistanceJoint::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/distance_test.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/distance_test.cpp index 6372330426..0f970de658 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/distance_test.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/distance_test.cpp @@ -26,109 +26,114 @@ class DistanceTest : public Test { public: - DistanceTest() - { - { - m_transformA.SetIdentity(); - m_transformA.p.Set(0.0f, -0.2f); - m_polygonA.SetAsBox(10.0f, 0.2f); - } + DistanceTest() + { + { + m_transformA.SetIdentity(); + m_transformA.p.Set(0.0f, -0.2f); + m_polygonA.SetAsBox(10.0f, 0.2f); + } - { - m_positionB.Set(12.017401f, 0.13678508f); - m_angleB = -0.0109265f; - m_transformB.Set(m_positionB, m_angleB); + { + m_positionB.Set(12.017401f, 0.13678508f); + m_angleB = -0.0109265f; + m_transformB.Set(m_positionB, m_angleB); - m_polygonB.SetAsBox(2.0f, 0.1f); - } - } + m_polygonB.SetAsBox(2.0f, 0.1f); + } + } - static Test* Create() { return new DistanceTest; } + static Test* Create() + { + return new DistanceTest; + } - void Step(Settings& settings) override - { - Test::Step(settings); + void Step(Settings& settings) override + { + Test::Step(settings); - b2DistanceInput input; - input.proxyA.Set(&m_polygonA, 0); - input.proxyB.Set(&m_polygonB, 0); - input.transformA = m_transformA; - input.transformB = m_transformB; - input.useRadii = true; - b2SimplexCache cache; - cache.count = 0; - b2DistanceOutput output; - b2Distance(&output, &cache, &input); + b2DistanceInput input; + input.proxyA.Set(&m_polygonA, 0); + input.proxyB.Set(&m_polygonB, 0); + input.transformA = m_transformA; + input.transformB = m_transformB; + input.useRadii = true; + b2SimplexCache cache; + cache.count = 0; + b2DistanceOutput output; + b2Distance(&output, &cache, &input); - DrawString(5, m_textLine, "distance = %g", output.distance); + DrawString(5, m_textLine, "distance = %g", output.distance); + - DrawString(5, m_textLine, "iterations = %d", output.iterations); + DrawString(5, m_textLine, "iterations = %d", output.iterations); + - { - b2Color color(0.9f, 0.9f, 0.9f); - b2Vec2 v[b2_maxPolygonVertices]; - for (int32 i = 0; i < m_polygonA.m_count; ++i) - { - v[i] = b2Mul(m_transformA, m_polygonA.m_vertices[i]); - } - g_debugDraw.DrawPolygon(v, m_polygonA.m_count, color); + { + b2Color color(0.9f, 0.9f, 0.9f); + b2Vec2 v[b2_maxPolygonVertices]; + for (int32 i = 0; i < m_polygonA.m_count; ++i) + { + v[i] = b2Mul(m_transformA, m_polygonA.m_vertices[i]); + } + g_debugDraw.DrawPolygon(v, m_polygonA.m_count, color); - for (int32 i = 0; i < m_polygonB.m_count; ++i) - { - v[i] = b2Mul(m_transformB, m_polygonB.m_vertices[i]); - } - g_debugDraw.DrawPolygon(v, m_polygonB.m_count, color); - } + for (int32 i = 0; i < m_polygonB.m_count; ++i) + { + v[i] = b2Mul(m_transformB, m_polygonB.m_vertices[i]); + } + g_debugDraw.DrawPolygon(v, m_polygonB.m_count, color); + } - b2Vec2 x1 = output.pointA; - b2Vec2 x2 = output.pointB; + b2Vec2 x1 = output.pointA; + b2Vec2 x2 = output.pointB; - b2Color c1(1.0f, 0.0f, 0.0f); - g_debugDraw.DrawPoint(x1, 4.0f, c1); + b2Color c1(1.0f, 0.0f, 0.0f); + g_debugDraw.DrawPoint(x1, 4.0f, c1); - b2Color c2(1.0f, 1.0f, 0.0f); - g_debugDraw.DrawPoint(x2, 4.0f, c2); - } + b2Color c2(1.0f, 1.0f, 0.0f); + g_debugDraw.DrawPoint(x2, 4.0f, c2); + } - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_A: - m_positionB.x -= 0.1f; - break; + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_A: + m_positionB.x -= 0.1f; + break; - case GLFW_KEY_D: - m_positionB.x += 0.1f; - break; + case GLFW_KEY_D: + m_positionB.x += 0.1f; + break; - case GLFW_KEY_S: - m_positionB.y -= 0.1f; - break; + case GLFW_KEY_S: + m_positionB.y -= 0.1f; + break; - case GLFW_KEY_W: - m_positionB.y += 0.1f; - break; + case GLFW_KEY_W: + m_positionB.y += 0.1f; + break; - case GLFW_KEY_Q: - m_angleB += 0.1f * b2_pi; - break; + case GLFW_KEY_Q: + m_angleB += 0.1f * b2_pi; + break; - case GLFW_KEY_E: - m_angleB -= 0.1f * b2_pi; - break; - } + case GLFW_KEY_E: + m_angleB -= 0.1f * b2_pi; + break; + } - m_transformB.Set(m_positionB, m_angleB); - } + m_transformB.Set(m_positionB, m_angleB); + } - b2Vec2 m_positionB; - float m_angleB; + b2Vec2 m_positionB; + float m_angleB; - b2Transform m_transformA; - b2Transform m_transformB; - b2PolygonShape m_polygonA; - b2PolygonShape m_polygonB; + b2Transform m_transformA; + b2Transform m_transformB; + b2PolygonShape m_polygonA; + b2PolygonShape m_polygonB; }; static int testIndex = RegisterTest("Geometry", "Distance Test", DistanceTest::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/dominos.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/dominos.cpp index f64a141bd4..739876bf55 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/dominos.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/dominos.cpp @@ -25,192 +25,196 @@ class Dominos : public Test { public: - Dominos() - { - b2Body* b1; - { - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - b2BodyDef bd; - b1 = m_world->CreateBody(&bd); - b1->CreateFixture(&shape, 0.0f); - } + Dominos() + { + b2Body* b1; + { + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - { - b2PolygonShape shape; - shape.SetAsBox(6.0f, 0.25f); + b2BodyDef bd; + b1 = m_world->CreateBody(&bd); + b1->CreateFixture(&shape, 0.0f); + } - b2BodyDef bd; - bd.position.Set(-1.5f, 10.0f); - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } + { + b2PolygonShape shape; + shape.SetAsBox(6.0f, 0.25f); - { - b2PolygonShape shape; - shape.SetAsBox(0.1f, 1.0f); + b2BodyDef bd; + bd.position.Set(-1.5f, 10.0f); + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.friction = 0.1f; + { + b2PolygonShape shape; + shape.SetAsBox(0.1f, 1.0f); - for (int i = 0; i < 10; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-6.0f + 1.0f * i, 11.25f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - } - } + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.friction = 0.1f; - { - b2PolygonShape shape; - shape.SetAsBox(7.0f, 0.25f, b2Vec2_zero, 0.3f); + for (int i = 0; i < 10; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-6.0f + 1.0f * i, 11.25f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + } + } - b2BodyDef bd; - bd.position.Set(1.0f, 6.0f); - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } + { + b2PolygonShape shape; + shape.SetAsBox(7.0f, 0.25f, b2Vec2_zero, 0.3f); - b2Body* b2; - { - b2PolygonShape shape; - shape.SetAsBox(0.25f, 1.5f); + b2BodyDef bd; + bd.position.Set(1.0f, 6.0f); + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } - b2BodyDef bd; - bd.position.Set(-7.0f, 4.0f); - b2 = m_world->CreateBody(&bd); - b2->CreateFixture(&shape, 0.0f); - } + b2Body* b2; + { + b2PolygonShape shape; + shape.SetAsBox(0.25f, 1.5f); - b2Body* b3; - { - b2PolygonShape shape; - shape.SetAsBox(6.0f, 0.125f); + b2BodyDef bd; + bd.position.Set(-7.0f, 4.0f); + b2 = m_world->CreateBody(&bd); + b2->CreateFixture(&shape, 0.0f); + } - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-0.9f, 1.0f); - bd.angle = -0.15f; + b2Body* b3; + { + b2PolygonShape shape; + shape.SetAsBox(6.0f, 0.125f); - b3 = m_world->CreateBody(&bd); - b3->CreateFixture(&shape, 10.0f); - } + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-0.9f, 1.0f); + bd.angle = -0.15f; - b2RevoluteJointDef jd; - b2Vec2 anchor; + b3 = m_world->CreateBody(&bd); + b3->CreateFixture(&shape, 10.0f); + } - anchor.Set(-2.0f, 1.0f); - jd.Initialize(b1, b3, anchor); - jd.collideConnected = true; - m_world->CreateJoint(&jd); + b2RevoluteJointDef jd; + b2Vec2 anchor; - b2Body* b4; - { - b2PolygonShape shape; - shape.SetAsBox(0.25f, 0.25f); + anchor.Set(-2.0f, 1.0f); + jd.Initialize(b1, b3, anchor); + jd.collideConnected = true; + m_world->CreateJoint(&jd); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-10.0f, 15.0f); - b4 = m_world->CreateBody(&bd); - b4->CreateFixture(&shape, 10.0f); - } + b2Body* b4; + { + b2PolygonShape shape; + shape.SetAsBox(0.25f, 0.25f); - anchor.Set(-7.0f, 15.0f); - jd.Initialize(b2, b4, anchor); - m_world->CreateJoint(&jd); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-10.0f, 15.0f); + b4 = m_world->CreateBody(&bd); + b4->CreateFixture(&shape, 10.0f); + } - b2Body* b5; - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(6.5f, 3.0f); - b5 = m_world->CreateBody(&bd); + anchor.Set(-7.0f, 15.0f); + jd.Initialize(b2, b4, anchor); + m_world->CreateJoint(&jd); - b2PolygonShape shape; - b2FixtureDef fd; + b2Body* b5; + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(6.5f, 3.0f); + b5 = m_world->CreateBody(&bd); - fd.shape = &shape; - fd.density = 10.0f; - fd.friction = 0.1f; + b2PolygonShape shape; + b2FixtureDef fd; - shape.SetAsBox(1.0f, 0.1f, b2Vec2(0.0f, -0.9f), 0.0f); - b5->CreateFixture(&fd); + fd.shape = &shape; + fd.density = 10.0f; + fd.friction = 0.1f; - shape.SetAsBox(0.1f, 1.0f, b2Vec2(-0.9f, 0.0f), 0.0f); - b5->CreateFixture(&fd); + shape.SetAsBox(1.0f, 0.1f, b2Vec2(0.0f, -0.9f), 0.0f); + b5->CreateFixture(&fd); - shape.SetAsBox(0.1f, 1.0f, b2Vec2(0.9f, 0.0f), 0.0f); - b5->CreateFixture(&fd); - } + shape.SetAsBox(0.1f, 1.0f, b2Vec2(-0.9f, 0.0f), 0.0f); + b5->CreateFixture(&fd); - anchor.Set(6.0f, 2.0f); - jd.Initialize(b1, b5, anchor); - m_world->CreateJoint(&jd); + shape.SetAsBox(0.1f, 1.0f, b2Vec2(0.9f, 0.0f), 0.0f); + b5->CreateFixture(&fd); + } - b2Body* b6; - { - b2PolygonShape shape; - shape.SetAsBox(1.0f, 0.1f); + anchor.Set(6.0f, 2.0f); + jd.Initialize(b1, b5, anchor); + m_world->CreateJoint(&jd); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(6.5f, 4.1f); - b6 = m_world->CreateBody(&bd); - b6->CreateFixture(&shape, 30.0f); - } + b2Body* b6; + { + b2PolygonShape shape; + shape.SetAsBox(1.0f, 0.1f); - anchor.Set(7.5f, 4.0f); - jd.Initialize(b5, b6, anchor); - m_world->CreateJoint(&jd); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(6.5f, 4.1f); + b6 = m_world->CreateBody(&bd); + b6->CreateFixture(&shape, 30.0f); + } - b2Body* b7; - { - b2PolygonShape shape; - shape.SetAsBox(0.1f, 1.0f); + anchor.Set(7.5f, 4.0f); + jd.Initialize(b5, b6, anchor); + m_world->CreateJoint(&jd); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(7.4f, 1.0f); + b2Body* b7; + { + b2PolygonShape shape; + shape.SetAsBox(0.1f, 1.0f); - b7 = m_world->CreateBody(&bd); - b7->CreateFixture(&shape, 10.0f); - } + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(7.4f, 1.0f); - b2DistanceJointDef djd; - djd.bodyA = b3; - djd.bodyB = b7; - djd.localAnchorA.Set(6.0f, 0.0f); - djd.localAnchorB.Set(0.0f, -1.0f); - b2Vec2 d = djd.bodyB->GetWorldPoint(djd.localAnchorB) - djd.bodyA->GetWorldPoint(djd.localAnchorA); - djd.length = d.Length(); + b7 = m_world->CreateBody(&bd); + b7->CreateFixture(&shape, 10.0f); + } - b2LinearStiffness(djd.stiffness, djd.damping, 1.0f, 1.0f, djd.bodyA, djd.bodyB); - m_world->CreateJoint(&djd); + b2DistanceJointDef djd; + djd.bodyA = b3; + djd.bodyB = b7; + djd.localAnchorA.Set(6.0f, 0.0f); + djd.localAnchorB.Set(0.0f, -1.0f); + b2Vec2 d = djd.bodyB->GetWorldPoint(djd.localAnchorB) - djd.bodyA->GetWorldPoint(djd.localAnchorA); + djd.length = d.Length(); - { - float radius = 0.2f; + b2LinearStiffness(djd.stiffness, djd.damping, 1.0f, 1.0f, djd.bodyA, djd.bodyB); + m_world->CreateJoint(&djd); - b2CircleShape shape; - shape.m_radius = radius; + { + float radius = 0.2f; - for (int32 i = 0; i < 4; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(5.9f + 2.0f * radius * i, 2.4f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 10.0f); - } - } - } + b2CircleShape shape; + shape.m_radius = radius; - static Test* Create() { return new Dominos; } + for (int32 i = 0; i < 4; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(5.9f + 2.0f * radius * i, 2.4f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 10.0f); + } + } + } + + static Test* Create() + { + return new Dominos; + } }; static int testIndex = RegisterTest("Examples", "Dominos", Dominos::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/dump_loader.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/dump_loader.cpp index 74e0984b07..3225113b51 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/dump_loader.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/dump_loader.cpp @@ -26,58 +26,63 @@ class DumpLoader : public Test { public: - DumpLoader() - { - b2ChainShape chainShape; - b2Vec2 vertices[] = {b2Vec2(-5, 0), b2Vec2(5, 0), b2Vec2(5, 5), b2Vec2(4, 1), b2Vec2(-4, 1), b2Vec2(-5, 5)}; - chainShape.CreateLoop(vertices, 6); - b2FixtureDef groundFixtureDef; - groundFixtureDef.density = 0; - groundFixtureDef.shape = &chainShape; + DumpLoader() + { + b2ChainShape chainShape; + b2Vec2 vertices[] = {b2Vec2(-5,0), b2Vec2(5,0), b2Vec2(5,5), b2Vec2(4,1), b2Vec2(-4,1), b2Vec2(-5,5)}; + chainShape.CreateLoop(vertices, 6); - b2BodyDef groundBodyDef; - groundBodyDef.type = b2_staticBody; + b2FixtureDef groundFixtureDef; + groundFixtureDef.density = 0; + groundFixtureDef.shape = &chainShape; - b2Body* groundBody = m_world->CreateBody(&groundBodyDef); - b2Fixture* groundBodyFixture = groundBody->CreateFixture(&groundFixtureDef); + b2BodyDef groundBodyDef; + groundBodyDef.type = b2_staticBody; - b2CircleShape ballShape; - ballShape.m_radius = 1; + b2Body *groundBody = m_world->CreateBody(&groundBodyDef); + b2Fixture *groundBodyFixture = groundBody->CreateFixture(&groundFixtureDef); - b2FixtureDef ballFixtureDef; - ballFixtureDef.restitution = 0.75f; - ballFixtureDef.density = 1; - ballFixtureDef.shape = &ballShape; + b2CircleShape ballShape; + ballShape.m_radius = 1; - b2BodyDef ballBodyDef; - ballBodyDef.type = b2BodyType::b2_dynamicBody; - ballBodyDef.position = b2Vec2(0, 10); - // ballBodyDef.angularDamping = 0.2f; + b2FixtureDef ballFixtureDef; + ballFixtureDef.restitution = 0.75f; + ballFixtureDef.density = 1; + ballFixtureDef.shape = &ballShape; - m_ball = m_world->CreateBody(&ballBodyDef); - b2Fixture* ballFixture = m_ball->CreateFixture(&ballFixtureDef); - m_ball->ApplyForceToCenter(b2Vec2(-1000, -400), true); - } + b2BodyDef ballBodyDef; + ballBodyDef.type = b2BodyType::b2_dynamicBody; + ballBodyDef.position = b2Vec2(0, 10); + // ballBodyDef.angularDamping = 0.2f; - void Step(Settings& settings) override - { - b2Vec2 v = m_ball->GetLinearVelocity(); - float omega = m_ball->GetAngularVelocity(); + m_ball = m_world->CreateBody(&ballBodyDef); + b2Fixture *ballFixture = m_ball->CreateFixture(&ballFixtureDef); + m_ball->ApplyForceToCenter(b2Vec2(-1000, -400), true); + } - b2MassData massData; - m_ball->GetMassData(&massData); + void Step(Settings& settings) override + { + b2Vec2 v = m_ball->GetLinearVelocity(); + float omega = m_ball->GetAngularVelocity(); - float ke = 0.5f * massData.mass * b2Dot(v, v) + 0.5f * massData.I * omega * omega; + b2MassData massData; + m_ball->GetMassData(&massData); - DrawString(5, m_textLine, "kinetic energy = %.6f", ke); + float ke = 0.5f * massData.mass * b2Dot(v, v) + 0.5f * massData.I * omega * omega; - Test::Step(settings); - } + DrawString(5, m_textLine, "kinetic energy = %.6f", ke); + - static Test* Create() { return new DumpLoader; } + Test::Step(settings); + } - b2Body* m_ball; + static Test* Create() + { + return new DumpLoader; + } + + b2Body* m_ball; }; static int testIndex = RegisterTest("Bugs", "Dump Loader", DumpLoader::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/dynamic_tree.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/dynamic_tree.cpp index bd2de4d80a..4efcf56903 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/dynamic_tree.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/dynamic_tree.cpp @@ -25,333 +25,336 @@ class DynamicTree : public Test { public: - enum - { - e_actorCount = 128 - }; - DynamicTree() - { - m_worldExtent = 15.0f; - m_proxyExtent = 0.5f; + enum + { + e_actorCount = 128 + }; - srand(888); + DynamicTree() + { + m_worldExtent = 15.0f; + m_proxyExtent = 0.5f; - for (int32 i = 0; i < e_actorCount; ++i) - { - Actor* actor = m_actors + i; - GetRandomAABB(&actor->aabb); - actor->proxyId = m_tree.CreateProxy(actor->aabb, actor); - } + srand(888); - m_stepCount = 0; + for (int32 i = 0; i < e_actorCount; ++i) + { + Actor* actor = m_actors + i; + GetRandomAABB(&actor->aabb); + actor->proxyId = m_tree.CreateProxy(actor->aabb, actor); + } - float h = m_worldExtent; - m_queryAABB.lowerBound.Set(-3.0f, -4.0f + h); - m_queryAABB.upperBound.Set(5.0f, 6.0f + h); + m_stepCount = 0; - m_rayCastInput.p1.Set(-5.0, 5.0f + h); - m_rayCastInput.p2.Set(7.0f, -4.0f + h); - // m_rayCastInput.p1.Set(0.0f, 2.0f + h); - // m_rayCastInput.p2.Set(0.0f, -2.0f + h); - m_rayCastInput.maxFraction = 1.0f; + float h = m_worldExtent; + m_queryAABB.lowerBound.Set(-3.0f, -4.0f + h); + m_queryAABB.upperBound.Set(5.0f, 6.0f + h); - m_automated = false; - } + m_rayCastInput.p1.Set(-5.0, 5.0f + h); + m_rayCastInput.p2.Set(7.0f, -4.0f + h); + //m_rayCastInput.p1.Set(0.0f, 2.0f + h); + //m_rayCastInput.p2.Set(0.0f, -2.0f + h); + m_rayCastInput.maxFraction = 1.0f; - static Test* Create() { return new DynamicTree; } + m_automated = false; + } - void Step(Settings& settings) override - { - B2_NOT_USED(settings); + static Test* Create() + { + return new DynamicTree; + } - m_rayActor = NULL; - for (int32 i = 0; i < e_actorCount; ++i) - { - m_actors[i].fraction = 1.0f; - m_actors[i].overlap = false; - } + void Step(Settings& settings) override + { + B2_NOT_USED(settings); - if (m_automated == true) - { - int32 actionCount = b2Max(1, e_actorCount >> 2); + m_rayActor = NULL; + for (int32 i = 0; i < e_actorCount; ++i) + { + m_actors[i].fraction = 1.0f; + m_actors[i].overlap = false; + } - for (int32 i = 0; i < actionCount; ++i) - { - Action(); - } - } + if (m_automated == true) + { + int32 actionCount = b2Max(1, e_actorCount >> 2); - Query(); - RayCast(); + for (int32 i = 0; i < actionCount; ++i) + { + Action(); + } + } - for (int32 i = 0; i < e_actorCount; ++i) - { - Actor* actor = m_actors + i; - if (actor->proxyId == b2_nullNode) - continue; + Query(); + RayCast(); - b2Color c(0.9f, 0.9f, 0.9f); - if (actor == m_rayActor && actor->overlap) - { - c.Set(0.9f, 0.6f, 0.6f); - } - else if (actor == m_rayActor) - { - c.Set(0.6f, 0.9f, 0.6f); - } - else if (actor->overlap) - { - c.Set(0.6f, 0.6f, 0.9f); - } + for (int32 i = 0; i < e_actorCount; ++i) + { + Actor* actor = m_actors + i; + if (actor->proxyId == b2_nullNode) + continue; - DrawAABB(&actor->aabb, c); - } + b2Color c(0.9f, 0.9f, 0.9f); + if (actor == m_rayActor && actor->overlap) + { + c.Set(0.9f, 0.6f, 0.6f); + } + else if (actor == m_rayActor) + { + c.Set(0.6f, 0.9f, 0.6f); + } + else if (actor->overlap) + { + c.Set(0.6f, 0.6f, 0.9f); + } - b2Color c(0.7f, 0.7f, 0.7f); - DrawAABB(&m_queryAABB, c); + DrawAABB(&actor->aabb, c); + } - g_debugDraw.DrawSegment(m_rayCastInput.p1, m_rayCastInput.p2, c); + b2Color c(0.7f, 0.7f, 0.7f); + DrawAABB(&m_queryAABB, c); - b2Color c1(0.2f, 0.9f, 0.2f); - b2Color c2(0.9f, 0.2f, 0.2f); - g_debugDraw.DrawPoint(m_rayCastInput.p1, 6.0f, c1); - g_debugDraw.DrawPoint(m_rayCastInput.p2, 6.0f, c2); + g_debugDraw.DrawSegment(m_rayCastInput.p1, m_rayCastInput.p2, c); - if (m_rayActor) - { - b2Color cr(0.2f, 0.2f, 0.9f); - b2Vec2 p = m_rayCastInput.p1 + m_rayActor->fraction * (m_rayCastInput.p2 - m_rayCastInput.p1); - g_debugDraw.DrawPoint(p, 6.0f, cr); - } + b2Color c1(0.2f, 0.9f, 0.2f); + b2Color c2(0.9f, 0.2f, 0.2f); + g_debugDraw.DrawPoint(m_rayCastInput.p1, 6.0f, c1); + g_debugDraw.DrawPoint(m_rayCastInput.p2, 6.0f, c2); - { - int32 height = m_tree.GetHeight(); - DrawString(5, m_textLine, "dynamic tree height = %d", height); - } + if (m_rayActor) + { + b2Color cr(0.2f, 0.2f, 0.9f); + b2Vec2 p = m_rayCastInput.p1 + m_rayActor->fraction * (m_rayCastInput.p2 - m_rayCastInput.p1); + g_debugDraw.DrawPoint(p, 6.0f, cr); + } - ++m_stepCount; - } + { + int32 height = m_tree.GetHeight(); + DrawString(5, m_textLine, "dynamic tree height = %d", height); + + } - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_A: - m_automated = !m_automated; - break; + ++m_stepCount; + } - case GLFW_KEY_C: - CreateProxy(); - break; + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_A: + m_automated = !m_automated; + break; - case GLFW_KEY_D: - DestroyProxy(); - break; + case GLFW_KEY_C: + CreateProxy(); + break; - case GLFW_KEY_M: - MoveProxy(); - break; - } - } + case GLFW_KEY_D: + DestroyProxy(); + break; - bool QueryCallback(int32 proxyId) - { - Actor* actor = (Actor*)m_tree.GetUserData(proxyId); - actor->overlap = b2TestOverlap(m_queryAABB, actor->aabb); - return true; - } + case GLFW_KEY_M: + MoveProxy(); + break; + } + } - float RayCastCallback(const b2RayCastInput& input, int32 proxyId) - { - Actor* actor = (Actor*)m_tree.GetUserData(proxyId); + bool QueryCallback(int32 proxyId) + { + Actor* actor = (Actor*)m_tree.GetUserData(proxyId); + actor->overlap = b2TestOverlap(m_queryAABB, actor->aabb); + return true; + } - b2RayCastOutput output; - bool hit = actor->aabb.RayCast(&output, input); + float RayCastCallback(const b2RayCastInput& input, int32 proxyId) + { + Actor* actor = (Actor*)m_tree.GetUserData(proxyId); - if (hit) - { - m_rayCastOutput = output; - m_rayActor = actor; - m_rayActor->fraction = output.fraction; - return output.fraction; - } + b2RayCastOutput output; + bool hit = actor->aabb.RayCast(&output, input); - return input.maxFraction; - } + if (hit) + { + m_rayCastOutput = output; + m_rayActor = actor; + m_rayActor->fraction = output.fraction; + return output.fraction; + } + + return input.maxFraction; + } private: - struct Actor - { - b2AABB aabb; - float fraction; - bool overlap; - int32 proxyId; - }; - void GetRandomAABB(b2AABB* aabb) - { - b2Vec2 w; - w.Set(2.0f * m_proxyExtent, 2.0f * m_proxyExtent); - // aabb->lowerBound.x = -m_proxyExtent; - // aabb->lowerBound.y = -m_proxyExtent + m_worldExtent; - aabb->lowerBound.x = RandomFloat(-m_worldExtent, m_worldExtent); - aabb->lowerBound.y = RandomFloat(0.0f, 2.0f * m_worldExtent); - aabb->upperBound = aabb->lowerBound + w; - } + struct Actor + { + b2AABB aabb; + float fraction; + bool overlap; + int32 proxyId; + }; - void MoveAABB(b2AABB* aabb) - { - b2Vec2 d; - d.x = RandomFloat(-0.5f, 0.5f); - d.y = RandomFloat(-0.5f, 0.5f); - // d.x = 2.0f; - // d.y = 0.0f; - aabb->lowerBound += d; - aabb->upperBound += d; + void GetRandomAABB(b2AABB* aabb) + { + b2Vec2 w; w.Set(2.0f * m_proxyExtent, 2.0f * m_proxyExtent); + //aabb->lowerBound.x = -m_proxyExtent; + //aabb->lowerBound.y = -m_proxyExtent + m_worldExtent; + aabb->lowerBound.x = RandomFloat(-m_worldExtent, m_worldExtent); + aabb->lowerBound.y = RandomFloat(0.0f, 2.0f * m_worldExtent); + aabb->upperBound = aabb->lowerBound + w; + } - b2Vec2 c0 = 0.5f * (aabb->lowerBound + aabb->upperBound); - b2Vec2 min; - min.Set(-m_worldExtent, 0.0f); - b2Vec2 max; - max.Set(m_worldExtent, 2.0f * m_worldExtent); - b2Vec2 c = b2Clamp(c0, min, max); + void MoveAABB(b2AABB* aabb) + { + b2Vec2 d; + d.x = RandomFloat(-0.5f, 0.5f); + d.y = RandomFloat(-0.5f, 0.5f); + //d.x = 2.0f; + //d.y = 0.0f; + aabb->lowerBound += d; + aabb->upperBound += d; - aabb->lowerBound += c - c0; - aabb->upperBound += c - c0; - } + b2Vec2 c0 = 0.5f * (aabb->lowerBound + aabb->upperBound); + b2Vec2 min; min.Set(-m_worldExtent, 0.0f); + b2Vec2 max; max.Set(m_worldExtent, 2.0f * m_worldExtent); + b2Vec2 c = b2Clamp(c0, min, max); - void CreateProxy() - { - for (int32 i = 0; i < e_actorCount; ++i) - { - int32 j = rand() % e_actorCount; - Actor* actor = m_actors + j; - if (actor->proxyId == b2_nullNode) - { - GetRandomAABB(&actor->aabb); - actor->proxyId = m_tree.CreateProxy(actor->aabb, actor); - return; - } - } - } + aabb->lowerBound += c - c0; + aabb->upperBound += c - c0; + } - void DestroyProxy() - { - for (int32 i = 0; i < e_actorCount; ++i) - { - int32 j = rand() % e_actorCount; - Actor* actor = m_actors + j; - if (actor->proxyId != b2_nullNode) - { - m_tree.DestroyProxy(actor->proxyId); - actor->proxyId = b2_nullNode; - return; - } - } - } + void CreateProxy() + { + for (int32 i = 0; i < e_actorCount; ++i) + { + int32 j = rand() % e_actorCount; + Actor* actor = m_actors + j; + if (actor->proxyId == b2_nullNode) + { + GetRandomAABB(&actor->aabb); + actor->proxyId = m_tree.CreateProxy(actor->aabb, actor); + return; + } + } + } - void MoveProxy() - { - for (int32 i = 0; i < e_actorCount; ++i) - { - int32 j = rand() % e_actorCount; - Actor* actor = m_actors + j; - if (actor->proxyId == b2_nullNode) - { - continue; - } + void DestroyProxy() + { + for (int32 i = 0; i < e_actorCount; ++i) + { + int32 j = rand() % e_actorCount; + Actor* actor = m_actors + j; + if (actor->proxyId != b2_nullNode) + { + m_tree.DestroyProxy(actor->proxyId); + actor->proxyId = b2_nullNode; + return; + } + } + } - b2AABB aabb0 = actor->aabb; - MoveAABB(&actor->aabb); - b2Vec2 displacement = actor->aabb.GetCenter() - aabb0.GetCenter(); - m_tree.MoveProxy(actor->proxyId, actor->aabb, displacement); - return; - } - } + void MoveProxy() + { + for (int32 i = 0; i < e_actorCount; ++i) + { + int32 j = rand() % e_actorCount; + Actor* actor = m_actors + j; + if (actor->proxyId == b2_nullNode) + { + continue; + } - void Action() - { - int32 choice = rand() % 20; + b2AABB aabb0 = actor->aabb; + MoveAABB(&actor->aabb); + b2Vec2 displacement = actor->aabb.GetCenter() - aabb0.GetCenter(); + m_tree.MoveProxy(actor->proxyId, actor->aabb, displacement); + return; + } + } - switch (choice) - { - case 0: - CreateProxy(); - break; + void Action() + { + int32 choice = rand() % 20; - case 1: - DestroyProxy(); - break; + switch (choice) + { + case 0: + CreateProxy(); + break; - default: - MoveProxy(); - } - } + case 1: + DestroyProxy(); + break; - void Query() - { - m_tree.Query(this, m_queryAABB); + default: + MoveProxy(); + } + } - for (int32 i = 0; i < e_actorCount; ++i) - { - if (m_actors[i].proxyId == b2_nullNode) - { - continue; - } + void Query() + { + m_tree.Query(this, m_queryAABB); - bool overlap = b2TestOverlap(m_queryAABB, m_actors[i].aabb); - B2_NOT_USED(overlap); - b2Assert(overlap == m_actors[i].overlap); - } - } + for (int32 i = 0; i < e_actorCount; ++i) + { + if (m_actors[i].proxyId == b2_nullNode) + { + continue; + } - void RayCast() - { - m_rayActor = NULL; + bool overlap = b2TestOverlap(m_queryAABB, m_actors[i].aabb); + B2_NOT_USED(overlap); + b2Assert(overlap == m_actors[i].overlap); + } + } - b2RayCastInput input = m_rayCastInput; + void RayCast() + { + m_rayActor = NULL; - // Ray cast against the dynamic tree. - m_tree.RayCast(this, input); + b2RayCastInput input = m_rayCastInput; - // Brute force ray cast. - Actor* bruteActor = NULL; - b2RayCastOutput bruteOutput; - for (int32 i = 0; i < e_actorCount; ++i) - { - if (m_actors[i].proxyId == b2_nullNode) - { - continue; - } + // Ray cast against the dynamic tree. + m_tree.RayCast(this, input); - b2RayCastOutput output; - bool hit = m_actors[i].aabb.RayCast(&output, input); - if (hit) - { - bruteActor = m_actors + i; - bruteOutput = output; - input.maxFraction = output.fraction; - } - } + // Brute force ray cast. + Actor* bruteActor = NULL; + b2RayCastOutput bruteOutput; + for (int32 i = 0; i < e_actorCount; ++i) + { + if (m_actors[i].proxyId == b2_nullNode) + { + continue; + } - if (bruteActor != NULL) - { - b2Assert(bruteOutput.fraction == m_rayCastOutput.fraction); - } - } + b2RayCastOutput output; + bool hit = m_actors[i].aabb.RayCast(&output, input); + if (hit) + { + bruteActor = m_actors + i; + bruteOutput = output; + input.maxFraction = output.fraction; + } + } - float m_worldExtent; - float m_proxyExtent; + if (bruteActor != NULL) + { + b2Assert(bruteOutput.fraction == m_rayCastOutput.fraction); + } + } - b2DynamicTree m_tree; - b2AABB m_queryAABB; - b2RayCastInput m_rayCastInput; - b2RayCastOutput m_rayCastOutput; - Actor* m_rayActor; - Actor m_actors[e_actorCount]; - int32 m_stepCount; - bool m_automated; + float m_worldExtent; + float m_proxyExtent; + + b2DynamicTree m_tree; + b2AABB m_queryAABB; + b2RayCastInput m_rayCastInput; + b2RayCastOutput m_rayCastOutput; + Actor* m_rayActor; + Actor m_actors[e_actorCount]; + int32 m_stepCount; + bool m_automated; }; static int testIndex = RegisterTest("Collision", "Dynamic Tree", DynamicTree::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/edge_shapes.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/edge_shapes.cpp index f7416dc437..3792354969 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/edge_shapes.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/edge_shapes.cpp @@ -26,219 +26,228 @@ class EdgeShapesCallback : public b2RayCastCallback { public: - EdgeShapesCallback() { m_fixture = NULL; } + EdgeShapesCallback() + { + m_fixture = NULL; + } - float ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float fraction) override - { - m_fixture = fixture; - m_point = point; - m_normal = normal; + float ReportFixture(b2Fixture* fixture, const b2Vec2& point, + const b2Vec2& normal, float fraction) override + { + m_fixture = fixture; + m_point = point; + m_normal = normal; - return fraction; - } + return fraction; + } - b2Fixture* m_fixture; - b2Vec2 m_point; - b2Vec2 m_normal; + b2Fixture* m_fixture; + b2Vec2 m_point; + b2Vec2 m_normal; }; class EdgeShapes : public Test { public: - enum - { - e_maxBodies = 256 - }; - EdgeShapes() - { - // Ground body - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + enum + { + e_maxBodies = 256 + }; - float x1 = -20.0f; - float y1 = 2.0f * cosf(x1 / 10.0f * b2_pi); - for (int32 i = 0; i < 80; ++i) - { - float x2 = x1 + 0.5f; - float y2 = 2.0f * cosf(x2 / 10.0f * b2_pi); + EdgeShapes() + { + // Ground body + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(x1, y1), b2Vec2(x2, y2)); - ground->CreateFixture(&shape, 0.0f); + float x1 = -20.0f; + float y1 = 2.0f * cosf(x1 / 10.0f * b2_pi); + for (int32 i = 0; i < 80; ++i) + { + float x2 = x1 + 0.5f; + float y2 = 2.0f * cosf(x2 / 10.0f * b2_pi); - x1 = x2; - y1 = y2; - } - } + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(x1, y1), b2Vec2(x2, y2)); + ground->CreateFixture(&shape, 0.0f); - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.5f, 0.0f); - vertices[1].Set(0.5f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - m_polygons[0].Set(vertices, 3); - } + x1 = x2; + y1 = y2; + } + } - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.1f, 0.0f); - vertices[1].Set(0.1f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - m_polygons[1].Set(vertices, 3); - } + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.5f, 0.0f); + vertices[1].Set(0.5f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + m_polygons[0].Set(vertices, 3); + } - { - float w = 1.0f; - float b = w / (2.0f + b2Sqrt(2.0f)); - float s = b2Sqrt(2.0f) * b; + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.1f, 0.0f); + vertices[1].Set(0.1f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + m_polygons[1].Set(vertices, 3); + } - b2Vec2 vertices[8]; - vertices[0].Set(0.5f * s, 0.0f); - vertices[1].Set(0.5f * w, b); - vertices[2].Set(0.5f * w, b + s); - vertices[3].Set(0.5f * s, w); - vertices[4].Set(-0.5f * s, w); - vertices[5].Set(-0.5f * w, b + s); - vertices[6].Set(-0.5f * w, b); - vertices[7].Set(-0.5f * s, 0.0f); + { + float w = 1.0f; + float b = w / (2.0f + b2Sqrt(2.0f)); + float s = b2Sqrt(2.0f) * b; - m_polygons[2].Set(vertices, 8); - } + b2Vec2 vertices[8]; + vertices[0].Set(0.5f * s, 0.0f); + vertices[1].Set(0.5f * w, b); + vertices[2].Set(0.5f * w, b + s); + vertices[3].Set(0.5f * s, w); + vertices[4].Set(-0.5f * s, w); + vertices[5].Set(-0.5f * w, b + s); + vertices[6].Set(-0.5f * w, b); + vertices[7].Set(-0.5f * s, 0.0f); - { - m_polygons[3].SetAsBox(0.5f, 0.5f); - } + m_polygons[2].Set(vertices, 8); + } - { - m_circle.m_radius = 0.5f; - } + { + m_polygons[3].SetAsBox(0.5f, 0.5f); + } - m_bodyIndex = 0; - memset(m_bodies, 0, sizeof(m_bodies)); + { + m_circle.m_radius = 0.5f; + } - m_angle = 0.0f; - } + m_bodyIndex = 0; + memset(m_bodies, 0, sizeof(m_bodies)); - void Create(int32 index) - { - if (m_bodies[m_bodyIndex] != NULL) - { - m_world->DestroyBody(m_bodies[m_bodyIndex]); - m_bodies[m_bodyIndex] = NULL; - } + m_angle = 0.0f; + } - b2BodyDef bd; + void Create(int32 index) + { + if (m_bodies[m_bodyIndex] != NULL) + { + m_world->DestroyBody(m_bodies[m_bodyIndex]); + m_bodies[m_bodyIndex] = NULL; + } - float x = RandomFloat(-10.0f, 10.0f); - float y = RandomFloat(10.0f, 20.0f); - bd.position.Set(x, y); - bd.angle = RandomFloat(-b2_pi, b2_pi); - bd.type = b2_dynamicBody; + b2BodyDef bd; - if (index == 4) - { - bd.angularDamping = 0.02f; - } + float x = RandomFloat(-10.0f, 10.0f); + float y = RandomFloat(10.0f, 20.0f); + bd.position.Set(x, y); + bd.angle = RandomFloat(-b2_pi, b2_pi); + bd.type = b2_dynamicBody; - m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); + if (index == 4) + { + bd.angularDamping = 0.02f; + } - if (index < 4) - { - b2FixtureDef fd; - fd.shape = m_polygons + index; - fd.friction = 0.3f; - fd.density = 20.0f; - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } - else - { - b2FixtureDef fd; - fd.shape = &m_circle; - fd.friction = 0.3f; - fd.density = 20.0f; - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } + m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); - m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; - } + if (index < 4) + { + b2FixtureDef fd; + fd.shape = m_polygons + index; + fd.friction = 0.3f; + fd.density = 20.0f; + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } + else + { + b2FixtureDef fd; + fd.shape = &m_circle; + fd.friction = 0.3f; + fd.density = 20.0f; + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } - void DestroyBody() - { - for (int32 i = 0; i < e_maxBodies; ++i) - { - if (m_bodies[i] != NULL) - { - m_world->DestroyBody(m_bodies[i]); - m_bodies[i] = NULL; - return; - } - } - } + m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; + } - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_1: - case GLFW_KEY_2: - case GLFW_KEY_3: - case GLFW_KEY_4: - case GLFW_KEY_5: - Create(key - GLFW_KEY_1); - break; + void DestroyBody() + { + for (int32 i = 0; i < e_maxBodies; ++i) + { + if (m_bodies[i] != NULL) + { + m_world->DestroyBody(m_bodies[i]); + m_bodies[i] = NULL; + return; + } + } + } - case GLFW_KEY_D: - DestroyBody(); - break; - } - } + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_1: + case GLFW_KEY_2: + case GLFW_KEY_3: + case GLFW_KEY_4: + case GLFW_KEY_5: + Create(key - GLFW_KEY_1); + break; - void Step(Settings& settings) override - { - bool advanceRay = settings.m_pause == 0 || settings.m_singleStep; + case GLFW_KEY_D: + DestroyBody(); + break; + } + } - Test::Step(settings); - DrawString(5, m_textLine, "Press 1-5 to drop stuff"); + void Step(Settings& settings) override + { + bool advanceRay = settings.m_pause == 0 || settings.m_singleStep; - float L = 25.0f; - b2Vec2 point1(0.0f, 10.0f); - b2Vec2 d(L * cosf(m_angle), -L * b2Abs(sinf(m_angle))); - b2Vec2 point2 = point1 + d; + Test::Step(settings); + DrawString(5, m_textLine, "Press 1-5 to drop stuff"); + - EdgeShapesCallback callback; + float L = 25.0f; + b2Vec2 point1(0.0f, 10.0f); + b2Vec2 d(L * cosf(m_angle), -L * b2Abs(sinf(m_angle))); + b2Vec2 point2 = point1 + d; - m_world->RayCast(&callback, point1, point2); + EdgeShapesCallback callback; - if (callback.m_fixture) - { - g_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); + m_world->RayCast(&callback, point1, point2); - g_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); + if (callback.m_fixture) + { + g_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); - b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; - g_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); - } - else - { - g_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); - } + g_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); - if (advanceRay) - { - m_angle += 0.25f * b2_pi / 180.0f; - } - } + b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; + g_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); + } + else + { + g_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); + } - static Test* Create() { return new EdgeShapes; } + if (advanceRay) + { + m_angle += 0.25f * b2_pi / 180.0f; + } + } - int32 m_bodyIndex; - b2Body* m_bodies[e_maxBodies]; - b2PolygonShape m_polygons[4]; - b2CircleShape m_circle; + static Test* Create() + { + return new EdgeShapes; + } - float m_angle; + int32 m_bodyIndex; + b2Body* m_bodies[e_maxBodies]; + b2PolygonShape m_polygons[4]; + b2CircleShape m_circle; + + float m_angle; }; static int testIndex = RegisterTest("Geometry", "Edge Shapes", EdgeShapes::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/edge_test.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/edge_test.cpp index e9c4bf4dc5..7f53a86f1c 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/edge_test.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/edge_test.cpp @@ -26,242 +26,257 @@ class EdgeTest : public Test { public: - EdgeTest() - { - b2Vec2 vertices[10] = {{10.0f, -4.0f}, {10.0f, 0.0f}, {6.0f, 0.0f}, {4.0f, 2.0f}, {2.0f, 0.0f}, - {-2.0f, 0.0f}, {-6.0f, 0.0f}, {-8.0f, -3.0f}, {-10.0f, 0.0f}, {-10.0f, -4.0f}}; - m_offset1.Set(0.0f, 8.0f); - m_offset2.Set(0.0f, 16.0f); + EdgeTest() + { + b2Vec2 vertices[10] = + { + {10.0f, -4.0f}, + {10.0f, 0.0f}, + {6.0f, 0.0f}, + {4.0f, 2.0f}, + {2.0f, 0.0f}, + {-2.0f, 0.0f}, + {-6.0f, 0.0f}, + {-8.0f, -3.0f}, + {-10.0f, 0.0f}, + {-10.0f, -4.0f} + }; - { - b2Vec2 v1 = vertices[0] + m_offset1; - b2Vec2 v2 = vertices[1] + m_offset1; - b2Vec2 v3 = vertices[2] + m_offset1; - b2Vec2 v4 = vertices[3] + m_offset1; - b2Vec2 v5 = vertices[4] + m_offset1; - b2Vec2 v6 = vertices[5] + m_offset1; - b2Vec2 v7 = vertices[6] + m_offset1; - b2Vec2 v8 = vertices[7] + m_offset1; - b2Vec2 v9 = vertices[8] + m_offset1; - b2Vec2 v10 = vertices[9] + m_offset1; + m_offset1.Set(0.0f, 8.0f); + m_offset2.Set(0.0f, 16.0f); - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + { + b2Vec2 v1 = vertices[0] + m_offset1; + b2Vec2 v2 = vertices[1] + m_offset1; + b2Vec2 v3 = vertices[2] + m_offset1; + b2Vec2 v4 = vertices[3] + m_offset1; + b2Vec2 v5 = vertices[4] + m_offset1; + b2Vec2 v6 = vertices[5] + m_offset1; + b2Vec2 v7 = vertices[6] + m_offset1; + b2Vec2 v8 = vertices[7] + m_offset1; + b2Vec2 v9 = vertices[8] + m_offset1; + b2Vec2 v10 = vertices[9] + m_offset1; - b2EdgeShape shape; + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - shape.SetOneSided(v10, v1, v2, v3); - ground->CreateFixture(&shape, 0.0f); + b2EdgeShape shape; - shape.SetOneSided(v1, v2, v3, v4); - ground->CreateFixture(&shape, 0.0f); + shape.SetOneSided(v10, v1, v2, v3); + ground->CreateFixture(&shape, 0.0f); - shape.SetOneSided(v2, v3, v4, v5); - ground->CreateFixture(&shape, 0.0f); + shape.SetOneSided(v1, v2, v3, v4); + ground->CreateFixture(&shape, 0.0f); - shape.SetOneSided(v3, v4, v5, v6); - ground->CreateFixture(&shape, 0.0f); + shape.SetOneSided(v2, v3, v4, v5); + ground->CreateFixture(&shape, 0.0f); - shape.SetOneSided(v4, v5, v6, v7); - ground->CreateFixture(&shape, 0.0f); + shape.SetOneSided(v3, v4, v5, v6); + ground->CreateFixture(&shape, 0.0f); - shape.SetOneSided(v5, v6, v7, v8); - ground->CreateFixture(&shape, 0.0f); + shape.SetOneSided(v4, v5, v6, v7); + ground->CreateFixture(&shape, 0.0f); - shape.SetOneSided(v6, v7, v8, v9); - ground->CreateFixture(&shape, 0.0f); + shape.SetOneSided(v5, v6, v7, v8); + ground->CreateFixture(&shape, 0.0f); - shape.SetOneSided(v7, v8, v9, v10); - ground->CreateFixture(&shape, 0.0f); + shape.SetOneSided(v6, v7, v8, v9); + ground->CreateFixture(&shape, 0.0f); - shape.SetOneSided(v8, v9, v10, v1); - ground->CreateFixture(&shape, 0.0f); + shape.SetOneSided(v7, v8, v9, v10); + ground->CreateFixture(&shape, 0.0f); - shape.SetOneSided(v9, v10, v1, v2); - ground->CreateFixture(&shape, 0.0f); - } + shape.SetOneSided(v8, v9, v10, v1); + ground->CreateFixture(&shape, 0.0f); - { - b2Vec2 v1 = vertices[0] + m_offset2; - b2Vec2 v2 = vertices[1] + m_offset2; - b2Vec2 v3 = vertices[2] + m_offset2; - b2Vec2 v4 = vertices[3] + m_offset2; - b2Vec2 v5 = vertices[4] + m_offset2; - b2Vec2 v6 = vertices[5] + m_offset2; - b2Vec2 v7 = vertices[6] + m_offset2; - b2Vec2 v8 = vertices[7] + m_offset2; - b2Vec2 v9 = vertices[8] + m_offset2; - b2Vec2 v10 = vertices[9] + m_offset2; + shape.SetOneSided(v9, v10, v1, v2); + ground->CreateFixture(&shape, 0.0f); + } - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + { + b2Vec2 v1 = vertices[0] + m_offset2; + b2Vec2 v2 = vertices[1] + m_offset2; + b2Vec2 v3 = vertices[2] + m_offset2; + b2Vec2 v4 = vertices[3] + m_offset2; + b2Vec2 v5 = vertices[4] + m_offset2; + b2Vec2 v6 = vertices[5] + m_offset2; + b2Vec2 v7 = vertices[6] + m_offset2; + b2Vec2 v8 = vertices[7] + m_offset2; + b2Vec2 v9 = vertices[8] + m_offset2; + b2Vec2 v10 = vertices[9] + m_offset2; - b2EdgeShape shape; + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - shape.SetTwoSided(v1, v2); - ground->CreateFixture(&shape, 0.0f); + b2EdgeShape shape; - shape.SetTwoSided(v2, v3); - ground->CreateFixture(&shape, 0.0f); + shape.SetTwoSided(v1, v2); + ground->CreateFixture(&shape, 0.0f); - shape.SetTwoSided(v3, v4); - ground->CreateFixture(&shape, 0.0f); + shape.SetTwoSided(v2, v3); + ground->CreateFixture(&shape, 0.0f); - shape.SetTwoSided(v4, v5); - ground->CreateFixture(&shape, 0.0f); + shape.SetTwoSided(v3, v4); + ground->CreateFixture(&shape, 0.0f); - shape.SetTwoSided(v5, v6); - ground->CreateFixture(&shape, 0.0f); + shape.SetTwoSided(v4, v5); + ground->CreateFixture(&shape, 0.0f); - shape.SetTwoSided(v6, v7); - ground->CreateFixture(&shape, 0.0f); + shape.SetTwoSided(v5, v6); + ground->CreateFixture(&shape, 0.0f); - shape.SetTwoSided(v7, v8); - ground->CreateFixture(&shape, 0.0f); + shape.SetTwoSided(v6, v7); + ground->CreateFixture(&shape, 0.0f); - shape.SetTwoSided(v8, v9); - ground->CreateFixture(&shape, 0.0f); + shape.SetTwoSided(v7, v8); + ground->CreateFixture(&shape, 0.0f); - shape.SetTwoSided(v9, v10); - ground->CreateFixture(&shape, 0.0f); + shape.SetTwoSided(v8, v9); + ground->CreateFixture(&shape, 0.0f); - shape.SetTwoSided(v10, v1); - ground->CreateFixture(&shape, 0.0f); - } + shape.SetTwoSided(v9, v10); + ground->CreateFixture(&shape, 0.0f); - m_body1 = nullptr; - m_body2 = nullptr; - CreateBoxes(); - m_boxes = true; - } + shape.SetTwoSided(v10, v1); + ground->CreateFixture(&shape, 0.0f); + } - void CreateBoxes() - { - if (m_body1) - { - m_world->DestroyBody(m_body1); - m_body1 = nullptr; - } + m_body1 = nullptr; + m_body2 = nullptr; + CreateBoxes(); + m_boxes = true; + } - if (m_body2) - { - m_world->DestroyBody(m_body2); - m_body2 = nullptr; - } + void CreateBoxes() + { + if (m_body1) + { + m_world->DestroyBody(m_body1); + m_body1 = nullptr; + } - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = b2Vec2(8.0f, 2.6f) + m_offset1; - bd.allowSleep = false; - m_body1 = m_world->CreateBody(&bd); + if (m_body2) + { + m_world->DestroyBody(m_body2); + m_body2 = nullptr; + } - b2PolygonShape shape; - shape.SetAsBox(0.5f, 1.0f); + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = b2Vec2(8.0f, 2.6f) + m_offset1; + bd.allowSleep = false; + m_body1 = m_world->CreateBody(&bd); - m_body1->CreateFixture(&shape, 1.0f); - } + b2PolygonShape shape; + shape.SetAsBox(0.5f, 1.0f); - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = b2Vec2(8.0f, 2.6f) + m_offset2; - bd.allowSleep = false; - m_body2 = m_world->CreateBody(&bd); + m_body1->CreateFixture(&shape, 1.0f); + } - b2PolygonShape shape; - shape.SetAsBox(0.5f, 1.0f); + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = b2Vec2(8.0f, 2.6f) + m_offset2; + bd.allowSleep = false; + m_body2 = m_world->CreateBody(&bd); - m_body2->CreateFixture(&shape, 1.0f); - } - } + b2PolygonShape shape; + shape.SetAsBox(0.5f, 1.0f); - void CreateCircles() - { - if (m_body1) - { - m_world->DestroyBody(m_body1); - m_body1 = nullptr; - } + m_body2->CreateFixture(&shape, 1.0f); + } + } - if (m_body2) - { - m_world->DestroyBody(m_body2); - m_body2 = nullptr; - } + void CreateCircles() + { + if (m_body1) + { + m_world->DestroyBody(m_body1); + m_body1 = nullptr; + } - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = b2Vec2(-0.5f, 0.6f) + m_offset1; - bd.allowSleep = false; - m_body1 = m_world->CreateBody(&bd); + if (m_body2) + { + m_world->DestroyBody(m_body2); + m_body2 = nullptr; + } - b2CircleShape shape; - shape.m_radius = 0.5f; + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = b2Vec2(-0.5f, 0.6f) + m_offset1; + bd.allowSleep = false; + m_body1 = m_world->CreateBody(&bd); - m_body1->CreateFixture(&shape, 1.0f); - } + b2CircleShape shape; + shape.m_radius = 0.5f; - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = b2Vec2(-0.5f, 0.6f) + m_offset2; - bd.allowSleep = false; - m_body2 = m_world->CreateBody(&bd); + m_body1->CreateFixture(&shape, 1.0f); + } - b2CircleShape shape; - shape.m_radius = 0.5f; + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = b2Vec2(-0.5f, 0.6f) + m_offset2; + bd.allowSleep = false; + m_body2 = m_world->CreateBody(&bd); - m_body2->CreateFixture(&shape, 1.0f); - } - } + b2CircleShape shape; + shape.m_radius = 0.5f; - void UpdateUI() override - { - // ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); - ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); - ImGui::Begin("Custom Controls", nullptr, ImGuiWindowFlags_NoResize); + m_body2->CreateFixture(&shape, 1.0f); + } + } - if (ImGui::RadioButton("Boxes", m_boxes == true)) - { - CreateBoxes(); - m_boxes = true; - } + void UpdateUI() override + { + //ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); + ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); + ImGui::Begin("Custom Controls", nullptr, ImGuiWindowFlags_NoResize); - if (ImGui::RadioButton("Circles", m_boxes == false)) - { - CreateCircles(); - m_boxes = false; - } + if (ImGui::RadioButton("Boxes", m_boxes == true)) + { + CreateBoxes(); + m_boxes = true; + } - ImGui::End(); - } + if (ImGui::RadioButton("Circles", m_boxes == false)) + { + CreateCircles(); + m_boxes = false; + } - void Step(Settings& settings) override - { - // if (glfwGetKey(g_mainWindow, GLFW_KEY_A) == GLFW_PRESS) - //{ - // m_body1->ApplyForceToCenter(b2Vec2(-10.0f, 0.0f), true); - // m_body2->ApplyForceToCenter(b2Vec2(-10.0f, 0.0f), true); - // } + ImGui::End(); + } - // if (glfwGetKey(g_mainWindow, GLFW_KEY_D) == GLFW_PRESS) - //{ - // m_body1->ApplyForceToCenter(b2Vec2(10.0f, 0.0f), true); - // m_body2->ApplyForceToCenter(b2Vec2(10.0f, 0.0f), true); - // } + void Step(Settings& settings) override + { + //if (glfwGetKey(g_mainWindow, GLFW_KEY_A) == GLFW_PRESS) + //{ + // m_body1->ApplyForceToCenter(b2Vec2(-10.0f, 0.0f), true); + // m_body2->ApplyForceToCenter(b2Vec2(-10.0f, 0.0f), true); + //} - Test::Step(settings); - } + //if (glfwGetKey(g_mainWindow, GLFW_KEY_D) == GLFW_PRESS) + //{ + // m_body1->ApplyForceToCenter(b2Vec2(10.0f, 0.0f), true); + // m_body2->ApplyForceToCenter(b2Vec2(10.0f, 0.0f), true); + //} - static Test* Create() { return new EdgeTest; } + Test::Step(settings); + } - b2Vec2 m_offset1, m_offset2; - b2Body* m_body1; - b2Body* m_body2; - bool m_boxes; + static Test* Create() + { + return new EdgeTest; + } + + b2Vec2 m_offset1, m_offset2; + b2Body* m_body1; + b2Body* m_body2; + bool m_boxes; }; static int testIndex = RegisterTest("Geometry", "Edge Test", EdgeTest::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/friction.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/friction.cpp index b935e0459c..9f1c06e932 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/friction.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/friction.cpp @@ -25,99 +25,103 @@ class Friction : public Test { public: - Friction() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + Friction() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - { - b2PolygonShape shape; - shape.SetAsBox(13.0f, 0.25f); + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - b2BodyDef bd; - bd.position.Set(-4.0f, 22.0f); - bd.angle = -0.25f; + { + b2PolygonShape shape; + shape.SetAsBox(13.0f, 0.25f); - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } + b2BodyDef bd; + bd.position.Set(-4.0f, 22.0f); + bd.angle = -0.25f; - { - b2PolygonShape shape; - shape.SetAsBox(0.25f, 1.0f); + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } - b2BodyDef bd; - bd.position.Set(10.5f, 19.0f); + { + b2PolygonShape shape; + shape.SetAsBox(0.25f, 1.0f); - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } + b2BodyDef bd; + bd.position.Set(10.5f, 19.0f); - { - b2PolygonShape shape; - shape.SetAsBox(13.0f, 0.25f); + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } - b2BodyDef bd; - bd.position.Set(4.0f, 14.0f); - bd.angle = 0.25f; + { + b2PolygonShape shape; + shape.SetAsBox(13.0f, 0.25f); - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } + b2BodyDef bd; + bd.position.Set(4.0f, 14.0f); + bd.angle = 0.25f; - { - b2PolygonShape shape; - shape.SetAsBox(0.25f, 1.0f); + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } - b2BodyDef bd; - bd.position.Set(-10.5f, 11.0f); + { + b2PolygonShape shape; + shape.SetAsBox(0.25f, 1.0f); - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } + b2BodyDef bd; + bd.position.Set(-10.5f, 11.0f); - { - b2PolygonShape shape; - shape.SetAsBox(13.0f, 0.25f); + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } - b2BodyDef bd; - bd.position.Set(-4.0f, 6.0f); - bd.angle = -0.25f; + { + b2PolygonShape shape; + shape.SetAsBox(13.0f, 0.25f); - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } + b2BodyDef bd; + bd.position.Set(-4.0f, 6.0f); + bd.angle = -0.25f; - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 25.0f; + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); - float friction[5] = {0.75f, 0.5f, 0.35f, 0.1f, 0.0f}; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 25.0f; - for (int i = 0; i < 5; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-15.0f + 4.0f * i, 28.0f); - b2Body* body = m_world->CreateBody(&bd); + float friction[5] = {0.75f, 0.5f, 0.35f, 0.1f, 0.0f}; - fd.friction = friction[i]; - body->CreateFixture(&fd); - } - } - } + for (int i = 0; i < 5; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-15.0f + 4.0f * i, 28.0f); + b2Body* body = m_world->CreateBody(&bd); - static Test* Create() { return new Friction; } + fd.friction = friction[i]; + body->CreateFixture(&fd); + } + } + } + + static Test* Create() + { + return new Friction; + } }; static int testIndex = RegisterTest("Forces", "Friction", Friction::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/gear_joint.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/gear_joint.cpp index d7e1b15771..ddde2cfb8d 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/gear_joint.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/gear_joint.cpp @@ -25,151 +25,156 @@ class GearJoint : public Test { public: - GearJoint() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + GearJoint() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(50.0f, 0.0f), b2Vec2(-50.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(50.0f, 0.0f), b2Vec2(-50.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2CircleShape circle1; - circle1.m_radius = 1.0f; + { + b2CircleShape circle1; + circle1.m_radius = 1.0f; - b2PolygonShape box; - box.SetAsBox(0.5f, 5.0f); + b2PolygonShape box; + box.SetAsBox(0.5f, 5.0f); - b2CircleShape circle2; - circle2.m_radius = 2.0f; + b2CircleShape circle2; + circle2.m_radius = 2.0f; + + b2BodyDef bd1; + bd1.type = b2_staticBody; + bd1.position.Set(10.0f, 9.0f); + b2Body* body1 = m_world->CreateBody(&bd1); + body1->CreateFixture(&circle1, 5.0f); - b2BodyDef bd1; - bd1.type = b2_staticBody; - bd1.position.Set(10.0f, 9.0f); - b2Body* body1 = m_world->CreateBody(&bd1); - body1->CreateFixture(&circle1, 5.0f); + b2BodyDef bd2; + bd2.type = b2_dynamicBody; + bd2.position.Set(10.0f, 8.0f); + b2Body* body2 = m_world->CreateBody(&bd2); + body2->CreateFixture(&box, 5.0f); - b2BodyDef bd2; - bd2.type = b2_dynamicBody; - bd2.position.Set(10.0f, 8.0f); - b2Body* body2 = m_world->CreateBody(&bd2); - body2->CreateFixture(&box, 5.0f); + b2BodyDef bd3; + bd3.type = b2_dynamicBody; + bd3.position.Set(10.0f, 6.0f); + b2Body* body3 = m_world->CreateBody(&bd3); + body3->CreateFixture(&circle2, 5.0f); - b2BodyDef bd3; - bd3.type = b2_dynamicBody; - bd3.position.Set(10.0f, 6.0f); - b2Body* body3 = m_world->CreateBody(&bd3); - body3->CreateFixture(&circle2, 5.0f); + b2RevoluteJointDef jd1; + jd1.Initialize(body1, body2, bd1.position); + b2Joint* joint1 = m_world->CreateJoint(&jd1); - b2RevoluteJointDef jd1; - jd1.Initialize(body1, body2, bd1.position); - b2Joint* joint1 = m_world->CreateJoint(&jd1); + b2RevoluteJointDef jd2; + jd2.Initialize(body2, body3, bd3.position); + b2Joint* joint2 = m_world->CreateJoint(&jd2); - b2RevoluteJointDef jd2; - jd2.Initialize(body2, body3, bd3.position); - b2Joint* joint2 = m_world->CreateJoint(&jd2); + b2GearJointDef jd4; + jd4.bodyA = body1; + jd4.bodyB = body3; + jd4.joint1 = joint1; + jd4.joint2 = joint2; + jd4.ratio = circle2.m_radius / circle1.m_radius; + m_world->CreateJoint(&jd4); + } - b2GearJointDef jd4; - jd4.bodyA = body1; - jd4.bodyB = body3; - jd4.joint1 = joint1; - jd4.joint2 = joint2; - jd4.ratio = circle2.m_radius / circle1.m_radius; - m_world->CreateJoint(&jd4); - } + { + b2CircleShape circle1; + circle1.m_radius = 1.0f; - { - b2CircleShape circle1; - circle1.m_radius = 1.0f; + b2CircleShape circle2; + circle2.m_radius = 2.0f; + + b2PolygonShape box; + box.SetAsBox(0.5f, 5.0f); - b2CircleShape circle2; - circle2.m_radius = 2.0f; + b2BodyDef bd1; + bd1.type = b2_dynamicBody; + bd1.position.Set(-3.0f, 12.0f); + b2Body* body1 = m_world->CreateBody(&bd1); + body1->CreateFixture(&circle1, 5.0f); - b2PolygonShape box; - box.SetAsBox(0.5f, 5.0f); + b2RevoluteJointDef jd1; + jd1.bodyA = ground; + jd1.bodyB = body1; + jd1.localAnchorA = ground->GetLocalPoint(bd1.position); + jd1.localAnchorB = body1->GetLocalPoint(bd1.position); + jd1.referenceAngle = body1->GetAngle() - ground->GetAngle(); + m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&jd1); - b2BodyDef bd1; - bd1.type = b2_dynamicBody; - bd1.position.Set(-3.0f, 12.0f); - b2Body* body1 = m_world->CreateBody(&bd1); - body1->CreateFixture(&circle1, 5.0f); + b2BodyDef bd2; + bd2.type = b2_dynamicBody; + bd2.position.Set(0.0f, 12.0f); + b2Body* body2 = m_world->CreateBody(&bd2); + body2->CreateFixture(&circle2, 5.0f); - b2RevoluteJointDef jd1; - jd1.bodyA = ground; - jd1.bodyB = body1; - jd1.localAnchorA = ground->GetLocalPoint(bd1.position); - jd1.localAnchorB = body1->GetLocalPoint(bd1.position); - jd1.referenceAngle = body1->GetAngle() - ground->GetAngle(); - m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&jd1); + b2RevoluteJointDef jd2; + jd2.Initialize(ground, body2, bd2.position); + m_joint2 = (b2RevoluteJoint*)m_world->CreateJoint(&jd2); - b2BodyDef bd2; - bd2.type = b2_dynamicBody; - bd2.position.Set(0.0f, 12.0f); - b2Body* body2 = m_world->CreateBody(&bd2); - body2->CreateFixture(&circle2, 5.0f); + b2BodyDef bd3; + bd3.type = b2_dynamicBody; + bd3.position.Set(2.5f, 12.0f); + b2Body* body3 = m_world->CreateBody(&bd3); + body3->CreateFixture(&box, 5.0f); - b2RevoluteJointDef jd2; - jd2.Initialize(ground, body2, bd2.position); - m_joint2 = (b2RevoluteJoint*)m_world->CreateJoint(&jd2); + b2PrismaticJointDef jd3; + jd3.Initialize(ground, body3, bd3.position, b2Vec2(0.0f, 1.0f)); + jd3.lowerTranslation = -5.0f; + jd3.upperTranslation = 5.0f; + jd3.enableLimit = true; - b2BodyDef bd3; - bd3.type = b2_dynamicBody; - bd3.position.Set(2.5f, 12.0f); - b2Body* body3 = m_world->CreateBody(&bd3); - body3->CreateFixture(&box, 5.0f); + m_joint3 = (b2PrismaticJoint*)m_world->CreateJoint(&jd3); - b2PrismaticJointDef jd3; - jd3.Initialize(ground, body3, bd3.position, b2Vec2(0.0f, 1.0f)); - jd3.lowerTranslation = -5.0f; - jd3.upperTranslation = 5.0f; - jd3.enableLimit = true; + b2GearJointDef jd4; + jd4.bodyA = body1; + jd4.bodyB = body2; + jd4.joint1 = m_joint1; + jd4.joint2 = m_joint2; + jd4.ratio = circle2.m_radius / circle1.m_radius; + m_joint4 = (b2GearJoint*)m_world->CreateJoint(&jd4); - m_joint3 = (b2PrismaticJoint*)m_world->CreateJoint(&jd3); + b2GearJointDef jd5; + jd5.bodyA = body2; + jd5.bodyB = body3; + jd5.joint1 = m_joint2; + jd5.joint2 = m_joint3; + jd5.ratio = -1.0f / circle2.m_radius; + m_joint5 = (b2GearJoint*)m_world->CreateJoint(&jd5); + } + } - b2GearJointDef jd4; - jd4.bodyA = body1; - jd4.bodyB = body2; - jd4.joint1 = m_joint1; - jd4.joint2 = m_joint2; - jd4.ratio = circle2.m_radius / circle1.m_radius; - m_joint4 = (b2GearJoint*)m_world->CreateJoint(&jd4); + void Step(Settings& settings) override + { + Test::Step(settings); - b2GearJointDef jd5; - jd5.bodyA = body2; - jd5.bodyB = body3; - jd5.joint1 = m_joint2; - jd5.joint2 = m_joint3; - jd5.ratio = -1.0f / circle2.m_radius; - m_joint5 = (b2GearJoint*)m_world->CreateJoint(&jd5); - } - } + float ratio, value; + + ratio = m_joint4->GetRatio(); + value = m_joint1->GetJointAngle() + ratio * m_joint2->GetJointAngle(); + DrawString(5, m_textLine, "theta1 + %4.2f * theta2 = %4.2f", (float) ratio, (float) value); + - void Step(Settings& settings) override - { - Test::Step(settings); + ratio = m_joint5->GetRatio(); + value = m_joint2->GetJointAngle() + ratio * m_joint3->GetJointTranslation(); + DrawString(5, m_textLine, "theta2 + %4.2f * delta = %4.2f", (float) ratio, (float) value); + + } - float ratio, value; + static Test* Create() + { + return new GearJoint; + } - ratio = m_joint4->GetRatio(); - value = m_joint1->GetJointAngle() + ratio * m_joint2->GetJointAngle(); - DrawString(5, m_textLine, "theta1 + %4.2f * theta2 = %4.2f", (float)ratio, (float)value); - - ratio = m_joint5->GetRatio(); - value = m_joint2->GetJointAngle() + ratio * m_joint3->GetJointTranslation(); - DrawString(5, m_textLine, "theta2 + %4.2f * delta = %4.2f", (float)ratio, (float)value); - } - - static Test* Create() { return new GearJoint; } - - b2RevoluteJoint* m_joint1; - b2RevoluteJoint* m_joint2; - b2PrismaticJoint* m_joint3; - b2GearJoint* m_joint4; - b2GearJoint* m_joint5; + b2RevoluteJoint* m_joint1; + b2RevoluteJoint* m_joint2; + b2PrismaticJoint* m_joint3; + b2GearJoint* m_joint4; + b2GearJoint* m_joint5; }; static int testIndex = RegisterTest("Joints", "Gear", GearJoint::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/heavy1.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/heavy1.cpp index 17ba6d183f..d302808aad 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/heavy1.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/heavy1.cpp @@ -25,33 +25,37 @@ class Heavy1 : public Test { public: + Heavy1() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 0.5f); - b2Body* body = m_world->CreateBody(&bd); - - b2CircleShape shape; - shape.m_radius = 0.5f; + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 0.5f); + b2Body* body = m_world->CreateBody(&bd); + + b2CircleShape shape; + shape.m_radius = 0.5f; body->CreateFixture(&shape, 10.0f); - + bd.position.Set(0.0f, 6.0f); - body = m_world->CreateBody(&bd); + body = m_world->CreateBody(&bd); shape.m_radius = 5.0f; body->CreateFixture(&shape, 10.0f); - } - - static Test* Create() { return new Heavy1; } + } + + static Test* Create() + { + return new Heavy1; + } }; static int testIndex = RegisterTest("Solver", "Heavy 1", Heavy1::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/heavy2.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/heavy2.cpp index c34a36995e..271c089b3d 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/heavy2.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/heavy2.cpp @@ -25,33 +25,34 @@ class Heavy2 : public Test { public: + Heavy2() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 2.5f); - b2Body* body = m_world->CreateBody(&bd); - - b2CircleShape shape; - shape.m_radius = 0.5f; + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 2.5f); + b2Body* body = m_world->CreateBody(&bd); + + b2CircleShape shape; + shape.m_radius = 0.5f; body->CreateFixture(&shape, 10.0f); - + bd.position.Set(0.0f, 3.5f); body = m_world->CreateBody(&bd); body->CreateFixture(&shape, 10.0f); - + m_heavy = NULL; - } - + } + void ToggleHeavy() { if (m_heavy) @@ -65,26 +66,29 @@ public: bd.type = b2_dynamicBody; bd.position.Set(0.0f, 9.0f); m_heavy = m_world->CreateBody(&bd); - + b2CircleShape shape; shape.m_radius = 5.0f; m_heavy->CreateFixture(&shape, 10.0f); } } - - void Keyboard(int key) override - { - switch (key) - { + + void Keyboard(int key) override + { + switch (key) + { case GLFW_KEY_H: ToggleHeavy(); break; - } - } - - static Test* Create() { return new Heavy2; } - - b2Body* m_heavy; + } + } + + static Test* Create() + { + return new Heavy2; + } + + b2Body* m_heavy; }; static int testIndex = RegisterTest("Solver", "Heavy 2", Heavy2::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/mobile_balanced.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/mobile_balanced.cpp index 8b68edd0b7..ee5af37831 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/mobile_balanced.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/mobile_balanced.cpp @@ -25,80 +25,84 @@ class MobileBalanced : public Test { public: - enum - { - e_depth = 4 - }; - MobileBalanced() - { - b2Body* ground; + enum + { + e_depth = 4 + }; - // Create ground body. - { - b2BodyDef bodyDef; - bodyDef.position.Set(0.0f, 20.0f); - ground = m_world->CreateBody(&bodyDef); - } + MobileBalanced() + { + b2Body* ground; - float a = 0.5f; - b2Vec2 h(0.0f, a); + // Create ground body. + { + b2BodyDef bodyDef; + bodyDef.position.Set(0.0f, 20.0f); + ground = m_world->CreateBody(&bodyDef); + } - b2Body* root = AddNode(ground, b2Vec2_zero, 0, 3.0f, a); + float a = 0.5f; + b2Vec2 h(0.0f, a); - b2RevoluteJointDef jointDef; - jointDef.bodyA = ground; - jointDef.bodyB = root; - jointDef.localAnchorA.SetZero(); - jointDef.localAnchorB = h; - m_world->CreateJoint(&jointDef); - } + b2Body* root = AddNode(ground, b2Vec2_zero, 0, 3.0f, a); - b2Body* AddNode(b2Body* parent, const b2Vec2& localAnchor, int32 depth, float offset, float a) - { - float density = 20.0f; - b2Vec2 h(0.0f, a); + b2RevoluteJointDef jointDef; + jointDef.bodyA = ground; + jointDef.bodyB = root; + jointDef.localAnchorA.SetZero(); + jointDef.localAnchorB = h; + m_world->CreateJoint(&jointDef); + } - b2Vec2 p = parent->GetPosition() + localAnchor - h; + b2Body* AddNode(b2Body* parent, const b2Vec2& localAnchor, int32 depth, float offset, float a) + { + float density = 20.0f; + b2Vec2 h(0.0f, a); - b2BodyDef bodyDef; - bodyDef.type = b2_dynamicBody; - bodyDef.position = p; - b2Body* body = m_world->CreateBody(&bodyDef); + b2Vec2 p = parent->GetPosition() + localAnchor - h; - b2PolygonShape shape; - shape.SetAsBox(0.25f * a, a); - body->CreateFixture(&shape, density); + b2BodyDef bodyDef; + bodyDef.type = b2_dynamicBody; + bodyDef.position = p; + b2Body* body = m_world->CreateBody(&bodyDef); - if (depth == e_depth) - { - return body; - } + b2PolygonShape shape; + shape.SetAsBox(0.25f * a, a); + body->CreateFixture(&shape, density); - shape.SetAsBox(offset, 0.25f * a, b2Vec2(0, -a), 0.0f); - body->CreateFixture(&shape, density); + if (depth == e_depth) + { + return body; + } - b2Vec2 a1 = b2Vec2(offset, -a); - b2Vec2 a2 = b2Vec2(-offset, -a); - b2Body* body1 = AddNode(body, a1, depth + 1, 0.5f * offset, a); - b2Body* body2 = AddNode(body, a2, depth + 1, 0.5f * offset, a); + shape.SetAsBox(offset, 0.25f * a, b2Vec2(0, -a), 0.0f); + body->CreateFixture(&shape, density); - b2RevoluteJointDef jointDef; - jointDef.bodyA = body; - jointDef.localAnchorB = h; + b2Vec2 a1 = b2Vec2(offset, -a); + b2Vec2 a2 = b2Vec2(-offset, -a); + b2Body* body1 = AddNode(body, a1, depth + 1, 0.5f * offset, a); + b2Body* body2 = AddNode(body, a2, depth + 1, 0.5f * offset, a); - jointDef.localAnchorA = a1; - jointDef.bodyB = body1; - m_world->CreateJoint(&jointDef); + b2RevoluteJointDef jointDef; + jointDef.bodyA = body; + jointDef.localAnchorB = h; - jointDef.localAnchorA = a2; - jointDef.bodyB = body2; - m_world->CreateJoint(&jointDef); + jointDef.localAnchorA = a1; + jointDef.bodyB = body1; + m_world->CreateJoint(&jointDef); - return body; - } + jointDef.localAnchorA = a2; + jointDef.bodyB = body2; + m_world->CreateJoint(&jointDef); - static Test* Create() { return new MobileBalanced; } + return body; + } + + static Test* Create() + { + return new MobileBalanced; + } }; static int testIndex = RegisterTest("Solver", "Mobile Balanced", MobileBalanced::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/mobile_unbalanced.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/mobile_unbalanced.cpp index 6d95738e54..5f62fb6ebf 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/mobile_unbalanced.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/mobile_unbalanced.cpp @@ -25,77 +25,81 @@ class MobileUnbalanced : public Test { public: - enum - { - e_depth = 4 - }; - MobileUnbalanced() - { - b2Body* ground; + enum + { + e_depth = 4 + }; - // Create ground body. - { - b2BodyDef bodyDef; - bodyDef.position.Set(0.0f, 20.0f); - ground = m_world->CreateBody(&bodyDef); - } + MobileUnbalanced() + { + b2Body* ground; - float a = 0.5f; - b2Vec2 h(0.0f, a); + // Create ground body. + { + b2BodyDef bodyDef; + bodyDef.position.Set(0.0f, 20.0f); + ground = m_world->CreateBody(&bodyDef); + } - b2Body* root = AddNode(ground, b2Vec2_zero, 0, 3.0f, a); + float a = 0.5f; + b2Vec2 h(0.0f, a); - b2RevoluteJointDef jointDef; - jointDef.bodyA = ground; - jointDef.bodyB = root; - jointDef.localAnchorA.SetZero(); - jointDef.localAnchorB = h; - m_world->CreateJoint(&jointDef); - } + b2Body* root = AddNode(ground, b2Vec2_zero, 0, 3.0f, a); - b2Body* AddNode(b2Body* parent, const b2Vec2& localAnchor, int32 depth, float offset, float a) - { - float density = 20.0f; - b2Vec2 h(0.0f, a); + b2RevoluteJointDef jointDef; + jointDef.bodyA = ground; + jointDef.bodyB = root; + jointDef.localAnchorA.SetZero(); + jointDef.localAnchorB = h; + m_world->CreateJoint(&jointDef); + } - b2Vec2 p = parent->GetPosition() + localAnchor - h; + b2Body* AddNode(b2Body* parent, const b2Vec2& localAnchor, int32 depth, float offset, float a) + { + float density = 20.0f; + b2Vec2 h(0.0f, a); - b2BodyDef bodyDef; - bodyDef.type = b2_dynamicBody; - bodyDef.position = p; - b2Body* body = m_world->CreateBody(&bodyDef); + b2Vec2 p = parent->GetPosition() + localAnchor - h; - b2PolygonShape shape; - shape.SetAsBox(0.25f * a, a); - body->CreateFixture(&shape, density); + b2BodyDef bodyDef; + bodyDef.type = b2_dynamicBody; + bodyDef.position = p; + b2Body* body = m_world->CreateBody(&bodyDef); - if (depth == e_depth) - { - return body; - } + b2PolygonShape shape; + shape.SetAsBox(0.25f * a, a); + body->CreateFixture(&shape, density); - b2Vec2 a1 = b2Vec2(offset, -a); - b2Vec2 a2 = b2Vec2(-offset, -a); - b2Body* body1 = AddNode(body, a1, depth + 1, 0.5f * offset, a); - b2Body* body2 = AddNode(body, a2, depth + 1, 0.5f * offset, a); + if (depth == e_depth) + { + return body; + } - b2RevoluteJointDef jointDef; - jointDef.bodyA = body; - jointDef.localAnchorB = h; + b2Vec2 a1 = b2Vec2(offset, -a); + b2Vec2 a2 = b2Vec2(-offset, -a); + b2Body* body1 = AddNode(body, a1, depth + 1, 0.5f * offset, a); + b2Body* body2 = AddNode(body, a2, depth + 1, 0.5f * offset, a); - jointDef.localAnchorA = a1; - jointDef.bodyB = body1; - m_world->CreateJoint(&jointDef); + b2RevoluteJointDef jointDef; + jointDef.bodyA = body; + jointDef.localAnchorB = h; - jointDef.localAnchorA = a2; - jointDef.bodyB = body2; - m_world->CreateJoint(&jointDef); + jointDef.localAnchorA = a1; + jointDef.bodyB = body1; + m_world->CreateJoint(&jointDef); - return body; - } + jointDef.localAnchorA = a2; + jointDef.bodyB = body2; + m_world->CreateJoint(&jointDef); - static Test* Create() { return new MobileUnbalanced; } + return body; + } + + static Test* Create() + { + return new MobileUnbalanced; + } }; static int testIndex = RegisterTest("Solver", "Mobile Unbalanced", MobileUnbalanced::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/motor_joint.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/motor_joint.cpp index 1b4873ad0e..a7b0156e9b 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/motor_joint.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/motor_joint.cpp @@ -29,87 +29,90 @@ class MotorJoint : public Test { public: - MotorJoint() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + MotorJoint() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); - b2FixtureDef fd; - fd.shape = &shape; + b2FixtureDef fd; + fd.shape = &shape; - ground->CreateFixture(&fd); - } + ground->CreateFixture(&fd); + } - // Define motorized body - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 8.0f); - b2Body* body = m_world->CreateBody(&bd); + // Define motorized body + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 8.0f); + b2Body* body = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(2.0f, 0.5f); + b2PolygonShape shape; + shape.SetAsBox(2.0f, 0.5f); - b2FixtureDef fd; - fd.shape = &shape; - fd.friction = 0.6f; - fd.density = 2.0f; - body->CreateFixture(&fd); + b2FixtureDef fd; + fd.shape = &shape; + fd.friction = 0.6f; + fd.density = 2.0f; + body->CreateFixture(&fd); - b2MotorJointDef mjd; - mjd.Initialize(ground, body); - mjd.maxForce = 1000.0f; - mjd.maxTorque = 1000.0f; - m_joint = (b2MotorJoint*)m_world->CreateJoint(&mjd); - } + b2MotorJointDef mjd; + mjd.Initialize(ground, body); + mjd.maxForce = 1000.0f; + mjd.maxTorque = 1000.0f; + m_joint = (b2MotorJoint*)m_world->CreateJoint(&mjd); + } - m_go = false; - m_time = 0.0f; - } + m_go = false; + m_time = 0.0f; + } - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_S: - m_go = !m_go; - break; - } - } + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_S: + m_go = !m_go; + break; + } + } - void Step(Settings& settings) override - { - if (m_go && settings.m_hertz > 0.0f) - { - m_time += 1.0f / settings.m_hertz; - } + void Step(Settings& settings) override + { + if (m_go && settings.m_hertz > 0.0f) + { + m_time += 1.0f / settings.m_hertz; + } - b2Vec2 linearOffset; - linearOffset.x = 6.0f * sinf(2.0f * m_time); - linearOffset.y = 8.0f + 4.0f * sinf(1.0f * m_time); + b2Vec2 linearOffset; + linearOffset.x = 6.0f * sinf(2.0f * m_time); + linearOffset.y = 8.0f + 4.0f * sinf(1.0f * m_time); + + float angularOffset = 4.0f * m_time; - float angularOffset = 4.0f * m_time; + m_joint->SetLinearOffset(linearOffset); + m_joint->SetAngularOffset(angularOffset); - m_joint->SetLinearOffset(linearOffset); - m_joint->SetAngularOffset(angularOffset); + g_debugDraw.DrawPoint(linearOffset, 4.0f, b2Color(0.9f, 0.9f, 0.9f)); - g_debugDraw.DrawPoint(linearOffset, 4.0f, b2Color(0.9f, 0.9f, 0.9f)); + Test::Step(settings); + DrawString(5, m_textLine, "Keys: (s) pause"); + m_textLine += 15; + } - Test::Step(settings); - DrawString(5, m_textLine, "Keys: (s) pause"); - m_textLine += 15; - } + static Test* Create() + { + return new MotorJoint; + } - static Test* Create() { return new MotorJoint; } - - b2MotorJoint* m_joint; - float m_time; - bool m_go; + b2MotorJoint* m_joint; + float m_time; + bool m_go; }; static int testIndex = RegisterTest("Joints", "Motor Joint", MotorJoint::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/pinball.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/pinball.cpp index 1c117de53c..c7dca48db4 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/pinball.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/pinball.cpp @@ -27,139 +27,144 @@ class Pinball : public Test { public: - Pinball() - { - // Ground body - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + Pinball() + { + // Ground body + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2Vec2 vs[5]; - vs[0].Set(-8.0f, 6.0f); - vs[1].Set(-8.0f, 20.0f); - vs[2].Set(8.0f, 20.0f); - vs[3].Set(8.0f, 6.0f); - vs[4].Set(0.0f, -2.0f); + b2Vec2 vs[5]; + vs[0].Set(-8.0f, 6.0f); + vs[1].Set(-8.0f, 20.0f); + vs[2].Set(8.0f, 20.0f); + vs[3].Set(8.0f, 6.0f); + vs[4].Set(0.0f, -2.0f); - b2ChainShape loop; - loop.CreateLoop(vs, 5); - b2FixtureDef fd; - fd.shape = &loop; - fd.density = 0.0f; - ground->CreateFixture(&fd); - } + b2ChainShape loop; + loop.CreateLoop(vs, 5); + b2FixtureDef fd; + fd.shape = &loop; + fd.density = 0.0f; + ground->CreateFixture(&fd); + } - // Flippers - { - b2Vec2 p1(-2.0f, 0.0f), p2(2.0f, 0.0f); + // Flippers + { + b2Vec2 p1(-2.0f, 0.0f), p2(2.0f, 0.0f); - b2BodyDef bd; - bd.type = b2_dynamicBody; + b2BodyDef bd; + bd.type = b2_dynamicBody; - bd.position = p1; - b2Body* leftFlipper = m_world->CreateBody(&bd); + bd.position = p1; + b2Body* leftFlipper = m_world->CreateBody(&bd); - bd.position = p2; - b2Body* rightFlipper = m_world->CreateBody(&bd); + bd.position = p2; + b2Body* rightFlipper = m_world->CreateBody(&bd); - b2PolygonShape box; - box.SetAsBox(1.75f, 0.1f); + b2PolygonShape box; + box.SetAsBox(1.75f, 0.1f); - b2FixtureDef fd; - fd.shape = &box; - fd.density = 1.0f; + b2FixtureDef fd; + fd.shape = &box; + fd.density = 1.0f; - leftFlipper->CreateFixture(&fd); - rightFlipper->CreateFixture(&fd); + leftFlipper->CreateFixture(&fd); + rightFlipper->CreateFixture(&fd); - b2RevoluteJointDef jd; - jd.bodyA = ground; - jd.localAnchorB.SetZero(); - jd.enableMotor = true; - jd.maxMotorTorque = 1000.0f; - jd.enableLimit = true; + b2RevoluteJointDef jd; + jd.bodyA = ground; + jd.localAnchorB.SetZero(); + jd.enableMotor = true; + jd.maxMotorTorque = 1000.0f; + jd.enableLimit = true; - jd.motorSpeed = 0.0f; - jd.localAnchorA = p1; - jd.bodyB = leftFlipper; - jd.lowerAngle = -30.0f * b2_pi / 180.0f; - jd.upperAngle = 5.0f * b2_pi / 180.0f; - m_leftJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); + jd.motorSpeed = 0.0f; + jd.localAnchorA = p1; + jd.bodyB = leftFlipper; + jd.lowerAngle = -30.0f * b2_pi / 180.0f; + jd.upperAngle = 5.0f * b2_pi / 180.0f; + m_leftJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); - jd.motorSpeed = 0.0f; - jd.localAnchorA = p2; - jd.bodyB = rightFlipper; - jd.lowerAngle = -5.0f * b2_pi / 180.0f; - jd.upperAngle = 30.0f * b2_pi / 180.0f; - m_rightJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); - } + jd.motorSpeed = 0.0f; + jd.localAnchorA = p2; + jd.bodyB = rightFlipper; + jd.lowerAngle = -5.0f * b2_pi / 180.0f; + jd.upperAngle = 30.0f * b2_pi / 180.0f; + m_rightJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); + } - // Circle character - { - b2BodyDef bd; - bd.position.Set(1.0f, 15.0f); - bd.type = b2_dynamicBody; - bd.bullet = true; + // Circle character + { + b2BodyDef bd; + bd.position.Set(1.0f, 15.0f); + bd.type = b2_dynamicBody; + bd.bullet = true; - m_ball = m_world->CreateBody(&bd); + m_ball = m_world->CreateBody(&bd); - b2CircleShape shape; - shape.m_radius = 0.2f; + b2CircleShape shape; + shape.m_radius = 0.2f; - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - m_ball->CreateFixture(&fd); - } + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + m_ball->CreateFixture(&fd); + } - m_button = false; - } + m_button = false; + } - void Step(Settings& settings) override - { - if (m_button) - { - m_leftJoint->SetMotorSpeed(20.0f); - m_rightJoint->SetMotorSpeed(-20.0f); - } - else - { - m_leftJoint->SetMotorSpeed(-10.0f); - m_rightJoint->SetMotorSpeed(10.0f); - } + void Step(Settings& settings) override + { + if (m_button) + { + m_leftJoint->SetMotorSpeed(20.0f); + m_rightJoint->SetMotorSpeed(-20.0f); + } + else + { + m_leftJoint->SetMotorSpeed(-10.0f); + m_rightJoint->SetMotorSpeed(10.0f); + } - Test::Step(settings); + Test::Step(settings); - DrawString(5, m_textLine, "Press 'a' to control the flippers"); - } + DrawString(5, m_textLine, "Press 'a' to control the flippers"); + - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_A: - m_button = true; - break; - } - } + } - void KeyboardUp(int key) override - { - switch (key) - { - case GLFW_KEY_A: - m_button = false; - break; - } - } + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_A: + m_button = true; + break; + } + } - static Test* Create() { return new Pinball; } + void KeyboardUp(int key) override + { + switch (key) + { + case GLFW_KEY_A: + m_button = false; + break; + } + } - b2RevoluteJoint* m_leftJoint; - b2RevoluteJoint* m_rightJoint; - b2Body* m_ball; - bool m_button; + static Test* Create() + { + return new Pinball; + } + + b2RevoluteJoint* m_leftJoint; + b2RevoluteJoint* m_rightJoint; + b2Body* m_ball; + bool m_button; }; static int testIndex = RegisterTest("Examples", "Pinball", Pinball::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/platformer.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/platformer.cpp index c308f4922b..18b39b8a7e 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/platformer.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/platformer.cpp @@ -25,104 +25,109 @@ class Platformer : public Test { public: - enum State - { - e_unknown, - e_above, - e_below - }; - Platformer() - { - // Ground - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + enum State + { + e_unknown, + e_above, + e_below + }; - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + Platformer() + { + // Ground + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - // Platform - { - b2BodyDef bd; - bd.position.Set(0.0f, 10.0f); - b2Body* body = m_world->CreateBody(&bd); + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - b2PolygonShape shape; - shape.SetAsBox(3.0f, 0.5f); - m_platform = body->CreateFixture(&shape, 0.0f); + // Platform + { + b2BodyDef bd; + bd.position.Set(0.0f, 10.0f); + b2Body* body = m_world->CreateBody(&bd); - m_bottom = 10.0f - 0.5f; - m_top = 10.0f + 0.5f; - } + b2PolygonShape shape; + shape.SetAsBox(3.0f, 0.5f); + m_platform = body->CreateFixture(&shape, 0.0f); - // Actor - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 12.0f); - b2Body* body = m_world->CreateBody(&bd); + m_bottom = 10.0f - 0.5f; + m_top = 10.0f + 0.5f; + } - m_radius = 0.5f; - b2CircleShape shape; - shape.m_radius = m_radius; - m_character = body->CreateFixture(&shape, 20.0f); + // Actor + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 12.0f); + b2Body* body = m_world->CreateBody(&bd); - body->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); + m_radius = 0.5f; + b2CircleShape shape; + shape.m_radius = m_radius; + m_character = body->CreateFixture(&shape, 20.0f); - m_state = e_unknown; - } - } + body->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); - void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override - { - Test::PreSolve(contact, oldManifold); + m_state = e_unknown; + } + } - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); + void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override + { + Test::PreSolve(contact, oldManifold); - if (fixtureA != m_platform && fixtureA != m_character) - { - return; - } + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); - if (fixtureB != m_platform && fixtureB != m_character) - { - return; - } + if (fixtureA != m_platform && fixtureA != m_character) + { + return; + } + + if (fixtureB != m_platform && fixtureB != m_character) + { + return; + } #if 1 - b2Vec2 position = m_character->GetBody()->GetPosition(); + b2Vec2 position = m_character->GetBody()->GetPosition(); - if (position.y < m_top + m_radius - 3.0f * b2_linearSlop) - { - contact->SetEnabled(false); - } + if (position.y < m_top + m_radius - 3.0f * b2_linearSlop) + { + contact->SetEnabled(false); + } #else b2Vec2 v = m_character->GetBody()->GetLinearVelocity(); if (v.y > 0.0f) - { + { contact->SetEnabled(false); } #endif - } + } - void Step(Settings& settings) override - { - Test::Step(settings); + void Step(Settings& settings) override + { + Test::Step(settings); - b2Vec2 v = m_character->GetBody()->GetLinearVelocity(); + b2Vec2 v = m_character->GetBody()->GetLinearVelocity(); DrawString(5, m_textLine, "Character Linear Velocity: %f", v.y); - } + + } - static Test* Create() { return new Platformer; } + static Test* Create() + { + return new Platformer; + } - float m_radius, m_top, m_bottom; - State m_state; - b2Fixture* m_platform; - b2Fixture* m_character; + float m_radius, m_top, m_bottom; + State m_state; + b2Fixture* m_platform; + b2Fixture* m_character; }; static int testIndex = RegisterTest("Examples", "Platformer", Platformer::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/polygon_collision.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/polygon_collision.cpp index dbc924694c..558ad59c27 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/polygon_collision.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/polygon_collision.cpp @@ -25,99 +25,103 @@ class PolygonCollision : public Test { public: - PolygonCollision() - { - { - m_polygonA.SetAsBox(0.2f, 0.4f); - m_transformA.Set(b2Vec2(0.0f, 0.0f), 0.0f); - } + PolygonCollision() + { + { + m_polygonA.SetAsBox(0.2f, 0.4f); + m_transformA.Set(b2Vec2(0.0f, 0.0f), 0.0f); + } - { - m_polygonB.SetAsBox(0.5f, 0.5f); - m_positionB.Set(19.345284f, 1.5632932f); - m_angleB = 1.9160721f; - m_transformB.Set(m_positionB, m_angleB); - } - } + { + m_polygonB.SetAsBox(0.5f, 0.5f); + m_positionB.Set(19.345284f, 1.5632932f); + m_angleB = 1.9160721f; + m_transformB.Set(m_positionB, m_angleB); + } + } - static Test* Create() { return new PolygonCollision; } + static Test* Create() + { + return new PolygonCollision; + } - void Step(Settings& settings) override - { - B2_NOT_USED(settings); + void Step(Settings& settings) override + { + B2_NOT_USED(settings); - b2Manifold manifold; - b2CollidePolygons(&manifold, &m_polygonA, m_transformA, &m_polygonB, m_transformB); + b2Manifold manifold; + b2CollidePolygons(&manifold, &m_polygonA, m_transformA, &m_polygonB, m_transformB); - b2WorldManifold worldManifold; - worldManifold.Initialize(&manifold, m_transformA, m_polygonA.m_radius, m_transformB, m_polygonB.m_radius); + b2WorldManifold worldManifold; + worldManifold.Initialize(&manifold, m_transformA, m_polygonA.m_radius, m_transformB, m_polygonB.m_radius); - DrawString(5, m_textLine, "point count = %d", manifold.pointCount); + DrawString(5, m_textLine, "point count = %d", manifold.pointCount); + - { - b2Color color(0.9f, 0.9f, 0.9f); - b2Vec2 v[b2_maxPolygonVertices]; - for (int32 i = 0; i < m_polygonA.m_count; ++i) - { - v[i] = b2Mul(m_transformA, m_polygonA.m_vertices[i]); - } - g_debugDraw.DrawPolygon(v, m_polygonA.m_count, color); + { + b2Color color(0.9f, 0.9f, 0.9f); + b2Vec2 v[b2_maxPolygonVertices]; + for (int32 i = 0; i < m_polygonA.m_count; ++i) + { + v[i] = b2Mul(m_transformA, m_polygonA.m_vertices[i]); + } + g_debugDraw.DrawPolygon(v, m_polygonA.m_count, color); - for (int32 i = 0; i < m_polygonB.m_count; ++i) - { - v[i] = b2Mul(m_transformB, m_polygonB.m_vertices[i]); - } - g_debugDraw.DrawPolygon(v, m_polygonB.m_count, color); - } + for (int32 i = 0; i < m_polygonB.m_count; ++i) + { + v[i] = b2Mul(m_transformB, m_polygonB.m_vertices[i]); + } + g_debugDraw.DrawPolygon(v, m_polygonB.m_count, color); + } - for (int32 i = 0; i < manifold.pointCount; ++i) - { - g_debugDraw.DrawPoint(worldManifold.points[i], 4.0f, b2Color(0.9f, 0.3f, 0.3f)); - } + for (int32 i = 0; i < manifold.pointCount; ++i) + { + g_debugDraw.DrawPoint(worldManifold.points[i], 4.0f, b2Color(0.9f, 0.3f, 0.3f)); + } - Test::Step(settings); - } + Test::Step(settings); + } - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_A: - m_positionB.x -= 0.1f; - break; + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_A: + m_positionB.x -= 0.1f; + break; - case GLFW_KEY_D: - m_positionB.x += 0.1f; - break; + case GLFW_KEY_D: + m_positionB.x += 0.1f; + break; - case GLFW_KEY_S: - m_positionB.y -= 0.1f; - break; + case GLFW_KEY_S: + m_positionB.y -= 0.1f; + break; - case GLFW_KEY_W: - m_positionB.y += 0.1f; - break; + case GLFW_KEY_W: + m_positionB.y += 0.1f; + break; - case GLFW_KEY_Q: - m_angleB += 0.1f * b2_pi; - break; + case GLFW_KEY_Q: + m_angleB += 0.1f * b2_pi; + break; - case GLFW_KEY_E: - m_angleB -= 0.1f * b2_pi; - break; - } + case GLFW_KEY_E: + m_angleB -= 0.1f * b2_pi; + break; + } - m_transformB.Set(m_positionB, m_angleB); - } + m_transformB.Set(m_positionB, m_angleB); + } - b2PolygonShape m_polygonA; - b2PolygonShape m_polygonB; + b2PolygonShape m_polygonA; + b2PolygonShape m_polygonB; - b2Transform m_transformA; - b2Transform m_transformB; + b2Transform m_transformA; + b2Transform m_transformB; - b2Vec2 m_positionB; - float m_angleB; + b2Vec2 m_positionB; + float m_angleB; }; static int testIndex = RegisterTest("Geometry", "Polygon Collision", PolygonCollision::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/polygon_shapes.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/polygon_shapes.cpp index 369f777ee8..2fa4c1cbc6 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/polygon_shapes.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/polygon_shapes.cpp @@ -31,227 +31,235 @@ class PolygonShapesCallback : public b2QueryCallback { public: - enum - { - e_maxCount = 4 - }; + + enum + { + e_maxCount = 4 + }; - PolygonShapesCallback() { m_count = 0; } + PolygonShapesCallback() + { + m_count = 0; + } - /// Called for each fixture found in the query AABB. - /// @return false to terminate the query. - bool ReportFixture(b2Fixture* fixture) override - { - if (m_count == e_maxCount) - { - return false; - } + /// Called for each fixture found in the query AABB. + /// @return false to terminate the query. + bool ReportFixture(b2Fixture* fixture) override + { + if (m_count == e_maxCount) + { + return false; + } - b2Body* body = fixture->GetBody(); - b2Shape* shape = fixture->GetShape(); + b2Body* body = fixture->GetBody(); + b2Shape* shape = fixture->GetShape(); - bool overlap = b2TestOverlap(shape, 0, &m_circle, 0, body->GetTransform(), m_transform); + bool overlap = b2TestOverlap(shape, 0, &m_circle, 0, body->GetTransform(), m_transform); + + if (overlap) + { + b2Color color(0.95f, 0.95f, 0.6f); + b2Vec2 center = body->GetWorldCenter(); + g_debugDraw->DrawPoint(center, 5.0f, color); + ++m_count; + } - if (overlap) - { - b2Color color(0.95f, 0.95f, 0.6f); - b2Vec2 center = body->GetWorldCenter(); - g_debugDraw->DrawPoint(center, 5.0f, color); - ++m_count; - } + return true; + } - return true; - } - - b2CircleShape m_circle; - b2Transform m_transform; - b2Draw* g_debugDraw; - int32 m_count; + b2CircleShape m_circle; + b2Transform m_transform; + b2Draw* g_debugDraw; + int32 m_count; }; class PolygonShapes : public Test { public: - enum - { - e_maxBodies = 256 - }; - PolygonShapes() - { - // Ground body - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + enum + { + e_maxBodies = 256 + }; - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + PolygonShapes() + { + // Ground body + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.5f, 0.0f); - vertices[1].Set(0.5f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - m_polygons[0].Set(vertices, 3); - } + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.1f, 0.0f); - vertices[1].Set(0.1f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - m_polygons[1].Set(vertices, 3); - } + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.5f, 0.0f); + vertices[1].Set(0.5f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + m_polygons[0].Set(vertices, 3); + } + + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.1f, 0.0f); + vertices[1].Set(0.1f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + m_polygons[1].Set(vertices, 3); + } - { - float w = 1.0f; - float b = w / (2.0f + b2Sqrt(2.0f)); - float s = b2Sqrt(2.0f) * b; + { + float w = 1.0f; + float b = w / (2.0f + b2Sqrt(2.0f)); + float s = b2Sqrt(2.0f) * b; - b2Vec2 vertices[8]; - vertices[0].Set(0.5f * s, 0.0f); - vertices[1].Set(0.5f * w, b); - vertices[2].Set(0.5f * w, b + s); - vertices[3].Set(0.5f * s, w); - vertices[4].Set(-0.5f * s, w); - vertices[5].Set(-0.5f * w, b + s); - vertices[6].Set(-0.5f * w, b); - vertices[7].Set(-0.5f * s, 0.0f); + b2Vec2 vertices[8]; + vertices[0].Set(0.5f * s, 0.0f); + vertices[1].Set(0.5f * w, b); + vertices[2].Set(0.5f * w, b + s); + vertices[3].Set(0.5f * s, w); + vertices[4].Set(-0.5f * s, w); + vertices[5].Set(-0.5f * w, b + s); + vertices[6].Set(-0.5f * w, b); + vertices[7].Set(-0.5f * s, 0.0f); - m_polygons[2].Set(vertices, 8); - } + m_polygons[2].Set(vertices, 8); + } - { - m_polygons[3].SetAsBox(0.5f, 0.5f); - } + { + m_polygons[3].SetAsBox(0.5f, 0.5f); + } - { - m_circle.m_radius = 0.5f; - } + { + m_circle.m_radius = 0.5f; + } - m_bodyIndex = 0; - memset(m_bodies, 0, sizeof(m_bodies)); - } + m_bodyIndex = 0; + memset(m_bodies, 0, sizeof(m_bodies)); + } - void Create(int32 index) - { - if (m_bodies[m_bodyIndex] != NULL) - { - m_world->DestroyBody(m_bodies[m_bodyIndex]); - m_bodies[m_bodyIndex] = NULL; - } + void Create(int32 index) + { + if (m_bodies[m_bodyIndex] != NULL) + { + m_world->DestroyBody(m_bodies[m_bodyIndex]); + m_bodies[m_bodyIndex] = NULL; + } - b2BodyDef bd; - bd.type = b2_dynamicBody; + b2BodyDef bd; + bd.type = b2_dynamicBody; - float x = RandomFloat(-2.0f, 2.0f); - bd.position.Set(x, 10.0f); - bd.angle = RandomFloat(-b2_pi, b2_pi); + float x = RandomFloat(-2.0f, 2.0f); + bd.position.Set(x, 10.0f); + bd.angle = RandomFloat(-b2_pi, b2_pi); - if (index == 4) - { - bd.angularDamping = 0.02f; - } + if (index == 4) + { + bd.angularDamping = 0.02f; + } - m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); + m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); - if (index < 4) - { - b2FixtureDef fd; - fd.shape = m_polygons + index; - fd.density = 1.0f; - fd.friction = 0.3f; - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } - else - { - b2FixtureDef fd; - fd.shape = &m_circle; - fd.density = 1.0f; - fd.friction = 0.3f; + if (index < 4) + { + b2FixtureDef fd; + fd.shape = m_polygons + index; + fd.density = 1.0f; + fd.friction = 0.3f; + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } + else + { + b2FixtureDef fd; + fd.shape = &m_circle; + fd.density = 1.0f; + fd.friction = 0.3f; - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } - m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; - } + m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; + } - void DestroyBody() - { - for (int32 i = 0; i < e_maxBodies; ++i) - { - if (m_bodies[i] != NULL) - { - m_world->DestroyBody(m_bodies[i]); - m_bodies[i] = NULL; - return; - } - } - } + void DestroyBody() + { + for (int32 i = 0; i < e_maxBodies; ++i) + { + if (m_bodies[i] != NULL) + { + m_world->DestroyBody(m_bodies[i]); + m_bodies[i] = NULL; + return; + } + } + } - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_1: - case GLFW_KEY_2: - case GLFW_KEY_3: - case GLFW_KEY_4: - case GLFW_KEY_5: - Create(key - GLFW_KEY_1); - break; + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_1: + case GLFW_KEY_2: + case GLFW_KEY_3: + case GLFW_KEY_4: + case GLFW_KEY_5: + Create(key - GLFW_KEY_1); + break; - case GLFW_KEY_A: - for (int32 i = 0; i < e_maxBodies; i += 2) - { - if (m_bodies[i]) - { - bool enabled = m_bodies[i]->IsEnabled(); - m_bodies[i]->SetEnabled(!enabled); - } - } - break; + case GLFW_KEY_A: + for (int32 i = 0; i < e_maxBodies; i += 2) + { + if (m_bodies[i]) + { + bool enabled = m_bodies[i]->IsEnabled(); + m_bodies[i]->SetEnabled(!enabled); + } + } + break; - case GLFW_KEY_D: - DestroyBody(); - break; - } - } + case GLFW_KEY_D: + DestroyBody(); + break; + } + } - void Step(Settings& settings) override - { - Test::Step(settings); + void Step(Settings& settings) override + { + Test::Step(settings); - PolygonShapesCallback callback; - callback.m_circle.m_radius = 2.0f; - callback.m_circle.m_p.Set(0.0f, 1.1f); - callback.m_transform.SetIdentity(); - callback.g_debugDraw = &g_debugDraw; + PolygonShapesCallback callback; + callback.m_circle.m_radius = 2.0f; + callback.m_circle.m_p.Set(0.0f, 1.1f); + callback.m_transform.SetIdentity(); + callback.g_debugDraw = &g_debugDraw; - b2AABB aabb; - callback.m_circle.ComputeAABB(&aabb, callback.m_transform, 0); + b2AABB aabb; + callback.m_circle.ComputeAABB(&aabb, callback.m_transform, 0); - m_world->QueryAABB(&callback, aabb); + m_world->QueryAABB(&callback, aabb); - b2Color color(0.4f, 0.7f, 0.8f); - g_debugDraw.DrawCircle(callback.m_circle.m_p, callback.m_circle.m_radius, color); + b2Color color(0.4f, 0.7f, 0.8f); + g_debugDraw.DrawCircle(callback.m_circle.m_p, callback.m_circle.m_radius, color); - DrawString(5, m_textLine, "Press 1-5 to drop stuff, maximum of %d overlaps detected", - PolygonShapesCallback::e_maxCount); + DrawString(5, m_textLine, "Press 1-5 to drop stuff, maximum of %d overlaps detected", PolygonShapesCallback::e_maxCount); + + DrawString(5, m_textLine, "Press 'a' to enable/disable some bodies"); + + DrawString(5, m_textLine, "Press 'd' to destroy a body"); + + } - DrawString(5, m_textLine, "Press 'a' to enable/disable some bodies"); + static Test* Create() + { + return new PolygonShapes; + } - DrawString(5, m_textLine, "Press 'd' to destroy a body"); - } - - static Test* Create() { return new PolygonShapes; } - - int32 m_bodyIndex; - b2Body* m_bodies[e_maxBodies]; - b2PolygonShape m_polygons[4]; - b2CircleShape m_circle; + int32 m_bodyIndex; + b2Body* m_bodies[e_maxBodies]; + b2PolygonShape m_polygons[4]; + b2CircleShape m_circle; }; static int testIndex = RegisterTest("Geometry", "Polygon Shapes", PolygonShapes::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/prismatic_joint.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/prismatic_joint.cpp index d078c31b8e..b63d6c5f92 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/prismatic_joint.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/prismatic_joint.cpp @@ -28,87 +28,91 @@ class PrismaticJoint : public Test { public: - PrismaticJoint() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + PrismaticJoint() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - m_enableLimit = true; - m_enableMotor = false; - m_motorSpeed = 10.0f; + m_enableLimit = true; + m_enableMotor = false; + m_motorSpeed = 10.0f; - { - b2PolygonShape shape; - shape.SetAsBox(1.0f, 1.0f); + { + b2PolygonShape shape; + shape.SetAsBox(1.0f, 1.0f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 10.0f); - bd.angle = 0.5f * b2_pi; - bd.allowSleep = false; - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 5.0f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 10.0f); + bd.angle = 0.5f * b2_pi; + bd.allowSleep = false; + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 5.0f); - b2PrismaticJointDef pjd; + b2PrismaticJointDef pjd; - // Horizontal - pjd.Initialize(ground, body, bd.position, b2Vec2(1.0f, 0.0f)); + // Horizontal + pjd.Initialize(ground, body, bd.position, b2Vec2(1.0f, 0.0f)); - pjd.motorSpeed = m_motorSpeed; - pjd.maxMotorForce = 10000.0f; - pjd.enableMotor = m_enableMotor; - pjd.lowerTranslation = -10.0f; - pjd.upperTranslation = 10.0f; - pjd.enableLimit = m_enableLimit; + pjd.motorSpeed = m_motorSpeed; + pjd.maxMotorForce = 10000.0f; + pjd.enableMotor = m_enableMotor; + pjd.lowerTranslation = -10.0f; + pjd.upperTranslation = 10.0f; + pjd.enableLimit = m_enableLimit; - m_joint = (b2PrismaticJoint*)m_world->CreateJoint(&pjd); - } - } + m_joint = (b2PrismaticJoint*)m_world->CreateJoint(&pjd); + } + } - void UpdateUI() override - { - // ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); - ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); - ImGui::Begin("Joint Controls", nullptr, ImGuiWindowFlags_NoResize); + void UpdateUI() override + { + //ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); + ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); + ImGui::Begin("Joint Controls", nullptr, ImGuiWindowFlags_NoResize); - if (ImGui::Checkbox("Limit", &m_enableLimit)) - { - m_joint->EnableLimit(m_enableLimit); - } + if (ImGui::Checkbox("Limit", &m_enableLimit)) + { + m_joint->EnableLimit(m_enableLimit); + } - if (ImGui::Checkbox("Motor", &m_enableMotor)) - { - m_joint->EnableMotor(m_enableMotor); - } + if (ImGui::Checkbox("Motor", &m_enableMotor)) + { + m_joint->EnableMotor(m_enableMotor); + } - if (ImGui::SliderFloat("Speed", &m_motorSpeed, -100.0f, 100.0f, "%.0f")) - { - m_joint->SetMotorSpeed(m_motorSpeed); - } + if (ImGui::SliderFloat("Speed", &m_motorSpeed, -100.0f, 100.0f, "%.0f")) + { + m_joint->SetMotorSpeed(m_motorSpeed); + } - ImGui::End(); - } + ImGui::End(); + } - void Step(Settings& settings) override - { - Test::Step(settings); - float force = m_joint->GetMotorForce(settings.m_hertz); - DrawString(5, m_textLine, "Motor Force = %4.0f", force); - } + void Step(Settings& settings) override + { + Test::Step(settings); + float force = m_joint->GetMotorForce(settings.m_hertz); + DrawString(5, m_textLine, "Motor Force = %4.0f", force); + + } - static Test* Create() { return new PrismaticJoint; } + static Test* Create() + { + return new PrismaticJoint; + } - b2PrismaticJoint* m_joint; - float m_motorSpeed; - bool m_enableMotor; - bool m_enableLimit; + b2PrismaticJoint* m_joint; + float m_motorSpeed; + bool m_enableMotor; + bool m_enableLimit; }; static int testIndex = RegisterTest("Joints", "Prismatic", PrismaticJoint::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/pulley_joint.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/pulley_joint.cpp index b724673d14..83dcd6e283 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/pulley_joint.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/pulley_joint.cpp @@ -25,68 +25,72 @@ class PulleyJoint : public Test { public: - PulleyJoint() - { - float y = 16.0f; - float L = 12.0f; - float a = 1.0f; - float b = 2.0f; + PulleyJoint() + { + float y = 16.0f; + float L = 12.0f; + float a = 1.0f; + float b = 2.0f; - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2CircleShape circle; - circle.m_radius = 2.0f; + b2CircleShape circle; + circle.m_radius = 2.0f; - circle.m_p.Set(-10.0f, y + b + L); - ground->CreateFixture(&circle, 0.0f); + circle.m_p.Set(-10.0f, y + b + L); + ground->CreateFixture(&circle, 0.0f); - circle.m_p.Set(10.0f, y + b + L); - ground->CreateFixture(&circle, 0.0f); - } + circle.m_p.Set(10.0f, y + b + L); + ground->CreateFixture(&circle, 0.0f); + } - { + { - b2PolygonShape shape; - shape.SetAsBox(a, b); + b2PolygonShape shape; + shape.SetAsBox(a, b); - b2BodyDef bd; - bd.type = b2_dynamicBody; + b2BodyDef bd; + bd.type = b2_dynamicBody; - // bd.fixedRotation = true; - bd.position.Set(-10.0f, y); - b2Body* body1 = m_world->CreateBody(&bd); - body1->CreateFixture(&shape, 5.0f); + //bd.fixedRotation = true; + bd.position.Set(-10.0f, y); + b2Body* body1 = m_world->CreateBody(&bd); + body1->CreateFixture(&shape, 5.0f); - bd.position.Set(10.0f, y); - b2Body* body2 = m_world->CreateBody(&bd); - body2->CreateFixture(&shape, 5.0f); + bd.position.Set(10.0f, y); + b2Body* body2 = m_world->CreateBody(&bd); + body2->CreateFixture(&shape, 5.0f); - b2PulleyJointDef pulleyDef; - b2Vec2 anchor1(-10.0f, y + b); - b2Vec2 anchor2(10.0f, y + b); - b2Vec2 groundAnchor1(-10.0f, y + b + L); - b2Vec2 groundAnchor2(10.0f, y + b + L); - pulleyDef.Initialize(body1, body2, groundAnchor1, groundAnchor2, anchor1, anchor2, 1.5f); + b2PulleyJointDef pulleyDef; + b2Vec2 anchor1(-10.0f, y + b); + b2Vec2 anchor2(10.0f, y + b); + b2Vec2 groundAnchor1(-10.0f, y + b + L); + b2Vec2 groundAnchor2(10.0f, y + b + L); + pulleyDef.Initialize(body1, body2, groundAnchor1, groundAnchor2, anchor1, anchor2, 1.5f); - m_joint1 = (b2PulleyJoint*)m_world->CreateJoint(&pulleyDef); - } - } + m_joint1 = (b2PulleyJoint*)m_world->CreateJoint(&pulleyDef); + } + } - void Step(Settings& settings) override - { - Test::Step(settings); + void Step(Settings& settings) override + { + Test::Step(settings); - float ratio = m_joint1->GetRatio(); - float L = m_joint1->GetCurrentLengthA() + ratio * m_joint1->GetCurrentLengthB(); - DrawString(5, m_textLine, "L1 + %4.2f * L2 = %4.2f", (float)ratio, (float)L); - } + float ratio = m_joint1->GetRatio(); + float L = m_joint1->GetCurrentLengthA() + ratio * m_joint1->GetCurrentLengthB(); + DrawString(5, m_textLine, "L1 + %4.2f * L2 = %4.2f", (float) ratio, (float) L); + + } - static Test* Create() { return new PulleyJoint; } + static Test* Create() + { + return new PulleyJoint; + } - b2PulleyJoint* m_joint1; + b2PulleyJoint* m_joint1; }; static int testIndex = RegisterTest("Joints", "Pulley", PulleyJoint::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/pyramid.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/pyramid.cpp index 5f52745160..ee90d5d01b 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/pyramid.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/pyramid.cpp @@ -25,65 +25,68 @@ class Pyramid : public Test { public: - enum - { - e_count = 20 - }; + enum + { + e_count = 20 + }; - Pyramid() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + Pyramid() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - float a = 0.5f; - b2PolygonShape shape; - shape.SetAsBox(a, a); + { + float a = 0.5f; + b2PolygonShape shape; + shape.SetAsBox(a, a); - b2Vec2 x(-7.0f, 0.75f); - b2Vec2 y; - b2Vec2 deltaX(0.5625f, 1.25f); - b2Vec2 deltaY(1.125f, 0.0f); + b2Vec2 x(-7.0f, 0.75f); + b2Vec2 y; + b2Vec2 deltaX(0.5625f, 1.25f); + b2Vec2 deltaY(1.125f, 0.0f); - for (int32 i = 0; i < e_count; ++i) - { - y = x; + for (int32 i = 0; i < e_count; ++i) + { + y = x; - for (int32 j = i; j < e_count; ++j) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = y; - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 5.0f); + for (int32 j = i; j < e_count; ++j) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = y; + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 5.0f); - y += deltaY; - } + y += deltaY; + } - x += deltaX; - } - } - } + x += deltaX; + } + } + } - void Step(Settings& settings) override - { - Test::Step(settings); + void Step(Settings& settings) override + { + Test::Step(settings); - // b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree; + //b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree; - // if (m_stepCount == 400) - //{ - // tree->RebuildBottomUp(); - // } - } + //if (m_stepCount == 400) + //{ + // tree->RebuildBottomUp(); + //} + } - static Test* Create() { return new Pyramid; } + static Test* Create() + { + return new Pyramid; + } }; static int testIndex = RegisterTest("Stacking", "Pyramid", Pyramid::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/ray_cast.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/ray_cast.cpp index 0f31b5d4c9..4dba339838 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/ray_cast.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/ray_cast.cpp @@ -26,7 +26,7 @@ enum { - e_maxBodies = 256 + e_maxBodies = 256 }; // This test demonstrates how to use the world ray-cast feature. @@ -37,62 +37,68 @@ enum class RayCastClosestCallback : public b2RayCastCallback { public: - RayCastClosestCallback() { m_hit = false; } + RayCastClosestCallback() + { + m_hit = false; + } - float ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float fraction) override - { - uintptr_t index = fixture->GetUserData().pointer; - if (index == 1) - { - // By returning -1, we instruct the calling code to ignore this fixture and - // continue the ray-cast to the next fixture. - return -1.0f; - } + float ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float fraction) override + { + uintptr_t index = fixture->GetUserData().pointer; + if (index == 1) + { + // By returning -1, we instruct the calling code to ignore this fixture and + // continue the ray-cast to the next fixture. + return -1.0f; + } - m_hit = true; - m_point = point; - m_normal = normal; + m_hit = true; + m_point = point; + m_normal = normal; - // By returning the current fraction, we instruct the calling code to clip the ray and - // continue the ray-cast to the next fixture. WARNING: do not assume that fixtures - // are reported in order. However, by clipping, we can always get the closest fixture. - return fraction; - } - - bool m_hit; - b2Vec2 m_point; - b2Vec2 m_normal; + // By returning the current fraction, we instruct the calling code to clip the ray and + // continue the ray-cast to the next fixture. WARNING: do not assume that fixtures + // are reported in order. However, by clipping, we can always get the closest fixture. + return fraction; + } + + bool m_hit; + b2Vec2 m_point; + b2Vec2 m_normal; }; // This callback finds any hit. Polygon 0 is filtered. For this type of query we are usually -// just checking for obstruction, so the actual fixture and hit point are irrelevant. +// just checking for obstruction, so the actual fixture and hit point are irrelevant. class RayCastAnyCallback : public b2RayCastCallback { public: - RayCastAnyCallback() { m_hit = false; } + RayCastAnyCallback() + { + m_hit = false; + } - float ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float) override - { - uintptr_t index = fixture->GetUserData().pointer; - if (index == 1) - { - // By returning -1, we instruct the calling code to ignore this fixture and - // continue the ray-cast to the next fixture. - return -1.0f; - } + float ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float) override + { + uintptr_t index = fixture->GetUserData().pointer; + if (index == 1) + { + // By returning -1, we instruct the calling code to ignore this fixture and + // continue the ray-cast to the next fixture. + return -1.0f; + } - m_hit = true; - m_point = point; - m_normal = normal; + m_hit = true; + m_point = point; + m_normal = normal; - // At this point we have a hit, so we know the ray is obstructed. - // By returning 0, we instruct the calling code to terminate the ray-cast. - return 0.0f; - } + // At this point we have a hit, so we know the ray is obstructed. + // By returning 0, we instruct the calling code to terminate the ray-cast. + return 0.0f; + } - bool m_hit; - b2Vec2 m_point; - b2Vec2 m_normal; + bool m_hit; + b2Vec2 m_point; + b2Vec2 m_normal; }; // This ray cast collects multiple hits along the ray. Polygon 0 is filtered. @@ -101,312 +107,319 @@ public: class RayCastMultipleCallback : public b2RayCastCallback { public: - enum - { - e_maxCount = 3 - }; + enum + { + e_maxCount = 3 + }; - RayCastMultipleCallback() { m_count = 0; } + RayCastMultipleCallback() + { + m_count = 0; + } - float ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float) override - { - uintptr_t index = fixture->GetUserData().pointer; - if (index == 1) - { - // By returning -1, we instruct the calling code to ignore this fixture and - // continue the ray-cast to the next fixture. - return -1.0f; - } + float ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float) override + { + uintptr_t index = fixture->GetUserData().pointer; + if (index == 1) + { + // By returning -1, we instruct the calling code to ignore this fixture and + // continue the ray-cast to the next fixture. + return -1.0f; + } - b2Assert(m_count < e_maxCount); + b2Assert(m_count < e_maxCount); - m_points[m_count] = point; - m_normals[m_count] = normal; - ++m_count; + m_points[m_count] = point; + m_normals[m_count] = normal; + ++m_count; - if (m_count == e_maxCount) - { - // At this point the buffer is full. - // By returning 0, we instruct the calling code to terminate the ray-cast. - return 0.0f; - } + if (m_count == e_maxCount) + { + // At this point the buffer is full. + // By returning 0, we instruct the calling code to terminate the ray-cast. + return 0.0f; + } - // By returning 1, we instruct the caller to continue without clipping the ray. - return 1.0f; - } + // By returning 1, we instruct the caller to continue without clipping the ray. + return 1.0f; + } - b2Vec2 m_points[e_maxCount]; - b2Vec2 m_normals[e_maxCount]; - int32 m_count; + b2Vec2 m_points[e_maxCount]; + b2Vec2 m_normals[e_maxCount]; + int32 m_count; }; + class RayCast : public Test { public: - enum Mode - { - e_any = 0, - e_closest = 1, - e_multiple = 2 - }; - RayCast() - { - // Ground body - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + enum Mode + { + e_any = 0, + e_closest = 1, + e_multiple = 2 + }; - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + RayCast() + { + // Ground body + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.5f, 0.0f); - vertices[1].Set(0.5f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - m_polygons[0].Set(vertices, 3); - } + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.1f, 0.0f); - vertices[1].Set(0.1f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - m_polygons[1].Set(vertices, 3); - } + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.5f, 0.0f); + vertices[1].Set(0.5f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + m_polygons[0].Set(vertices, 3); + } - { - float w = 1.0f; - float b = w / (2.0f + b2Sqrt(2.0f)); - float s = b2Sqrt(2.0f) * b; + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.1f, 0.0f); + vertices[1].Set(0.1f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + m_polygons[1].Set(vertices, 3); + } - b2Vec2 vertices[8]; - vertices[0].Set(0.5f * s, 0.0f); - vertices[1].Set(0.5f * w, b); - vertices[2].Set(0.5f * w, b + s); - vertices[3].Set(0.5f * s, w); - vertices[4].Set(-0.5f * s, w); - vertices[5].Set(-0.5f * w, b + s); - vertices[6].Set(-0.5f * w, b); - vertices[7].Set(-0.5f * s, 0.0f); + { + float w = 1.0f; + float b = w / (2.0f + b2Sqrt(2.0f)); + float s = b2Sqrt(2.0f) * b; - m_polygons[2].Set(vertices, 8); - } + b2Vec2 vertices[8]; + vertices[0].Set(0.5f * s, 0.0f); + vertices[1].Set(0.5f * w, b); + vertices[2].Set(0.5f * w, b + s); + vertices[3].Set(0.5f * s, w); + vertices[4].Set(-0.5f * s, w); + vertices[5].Set(-0.5f * w, b + s); + vertices[6].Set(-0.5f * w, b); + vertices[7].Set(-0.5f * s, 0.0f); - { - m_polygons[3].SetAsBox(0.5f, 0.5f); - } + m_polygons[2].Set(vertices, 8); + } - { - m_circle.m_radius = 0.5f; - } + { + m_polygons[3].SetAsBox(0.5f, 0.5f); + } - { - m_edge.SetTwoSided(b2Vec2(-1.0f, 0.0f), b2Vec2(1.0f, 0.0f)); - } + { + m_circle.m_radius = 0.5f; + } - m_bodyIndex = 0; - memset(m_bodies, 0, sizeof(m_bodies)); + { + m_edge.SetTwoSided(b2Vec2(-1.0f, 0.0f), b2Vec2(1.0f, 0.0f)); + } - m_degrees = 0.0f; + m_bodyIndex = 0; + memset(m_bodies, 0, sizeof(m_bodies)); - m_mode = e_closest; - } + m_degrees = 0.0f; - void Create(int32 index) - { - if (m_bodies[m_bodyIndex] != NULL) - { - m_world->DestroyBody(m_bodies[m_bodyIndex]); - m_bodies[m_bodyIndex] = NULL; - } + m_mode = e_closest; + } - b2BodyDef bd; + void Create(int32 index) + { + if (m_bodies[m_bodyIndex] != NULL) + { + m_world->DestroyBody(m_bodies[m_bodyIndex]); + m_bodies[m_bodyIndex] = NULL; + } - float x = RandomFloat(-10.0f, 10.0f); - float y = RandomFloat(0.0f, 20.0f); - bd.position.Set(x, y); - bd.angle = RandomFloat(-b2_pi, b2_pi); + b2BodyDef bd; - if (index == 4) - { - bd.angularDamping = 0.02f; - } + float x = RandomFloat(-10.0f, 10.0f); + float y = RandomFloat(0.0f, 20.0f); + bd.position.Set(x, y); + bd.angle = RandomFloat(-b2_pi, b2_pi); - m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); + if (index == 4) + { + bd.angularDamping = 0.02f; + } - if (index < 4) - { - b2FixtureDef fd; - fd.shape = m_polygons + index; - fd.friction = 0.3f; - fd.userData.pointer = index + 1; - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } - else if (index < 5) - { - b2FixtureDef fd; - fd.shape = &m_circle; - fd.friction = 0.3f; - fd.userData.pointer = index + 1; - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } - else - { - b2FixtureDef fd; - fd.shape = &m_edge; - fd.friction = 0.3f; - fd.userData.pointer = index + 1; + m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } + if (index < 4) + { + b2FixtureDef fd; + fd.shape = m_polygons + index; + fd.friction = 0.3f; + fd.userData.pointer = index + 1; + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } + else if (index < 5) + { + b2FixtureDef fd; + fd.shape = &m_circle; + fd.friction = 0.3f; + fd.userData.pointer = index + 1; + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } + else + { + b2FixtureDef fd; + fd.shape = &m_edge; + fd.friction = 0.3f; + fd.userData.pointer = index + 1; - m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; - } + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } - void DestroyBody() - { - for (int32 i = 0; i < e_maxBodies; ++i) - { - if (m_bodies[i] != NULL) - { - m_world->DestroyBody(m_bodies[i]); - m_bodies[i] = NULL; - return; - } - } - } + m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; + } - void UpdateUI() override - { - // ImGui::SetNextWindowPos(ImVec2(g_debugDrawTestBed.debugNodeOffset.x, g_debugDrawTestBed.debugNodeOffset.y)); - ImGui::SetNextWindowSize(ImVec2(210.0f, 285.0f)); - ImGui::Begin("Ray-cast Controls", nullptr, ImGuiWindowFlags_NoResize); + void DestroyBody() + { + for (int32 i = 0; i < e_maxBodies; ++i) + { + if (m_bodies[i] != NULL) + { + m_world->DestroyBody(m_bodies[i]); + m_bodies[i] = NULL; + return; + } + } + } - if (ImGui::Button("Shape 1")) - { - Create(0); - } + void UpdateUI() override + { + //ImGui::SetNextWindowPos(ImVec2(g_debugDrawTestBed.debugNodeOffset.x, g_debugDrawTestBed.debugNodeOffset.y)); + ImGui::SetNextWindowSize(ImVec2(210.0f, 285.0f)); + ImGui::Begin("Ray-cast Controls", nullptr, ImGuiWindowFlags_NoResize); - if (ImGui::Button("Shape 2")) - { - Create(1); - } + if (ImGui::Button("Shape 1")) + { + Create(0); + } - if (ImGui::Button("Shape 3")) - { - Create(2); - } + if (ImGui::Button("Shape 2")) + { + Create(1); + } - if (ImGui::Button("Shape 4")) - { - Create(3); - } + if (ImGui::Button("Shape 3")) + { + Create(2); + } - if (ImGui::Button("Shape 5")) - { - Create(4); - } + if (ImGui::Button("Shape 4")) + { + Create(3); + } - if (ImGui::Button("Shape 6")) - { - Create(5); - } + if (ImGui::Button("Shape 5")) + { + Create(4); + } - if (ImGui::Button("Destroy Shape")) - { - DestroyBody(); - } + if (ImGui::Button("Shape 6")) + { + Create(5); + } - ImGui::RadioButton("Any", &m_mode, e_any); - ImGui::RadioButton("Closest", &m_mode, e_closest); - ImGui::RadioButton("Multiple", &m_mode, e_multiple); + if (ImGui::Button("Destroy Shape")) + { + DestroyBody(); + } - ImGui::SliderFloat("Angle", &m_degrees, 0.0f, 360.0f, "%.0f"); + ImGui::RadioButton("Any", &m_mode, e_any); + ImGui::RadioButton("Closest", &m_mode, e_closest); + ImGui::RadioButton("Multiple", &m_mode, e_multiple); - ImGui::End(); - } + ImGui::SliderFloat("Angle", &m_degrees, 0.0f, 360.0f, "%.0f"); - void Step(Settings& settings) override - { - Test::Step(settings); + ImGui::End(); + } - DrawString(5, m_textLine, "Shape 1 is intentionally ignored by the ray"); + void Step(Settings& settings) override + { + Test::Step(settings); - switch (m_mode) - { - case e_closest: - DrawString(5, m_textLine, "Ray-cast mode: closest - find closest fixture along the ray"); - break; + DrawString(5, m_textLine, "Shape 1 is intentionally ignored by the ray"); + + switch (m_mode) + { + case e_closest: + DrawString(5, m_textLine, "Ray-cast mode: closest - find closest fixture along the ray"); + break; + + case e_any: + DrawString(5, m_textLine, "Ray-cast mode: any - check for obstruction"); + break; - case e_any: - DrawString(5, m_textLine, "Ray-cast mode: any - check for obstruction"); - break; + case e_multiple: + DrawString(5, m_textLine, "Ray-cast mode: multiple - gather multiple fixtures"); + break; + } - case e_multiple: - DrawString(5, m_textLine, "Ray-cast mode: multiple - gather multiple fixtures"); - break; - } + - float angle = b2_pi * m_degrees / 180.0f; - float L = 11.0f; - b2Vec2 point1(0.0f, 10.0f); - b2Vec2 d(L * cosf(angle), L * sinf(angle)); - b2Vec2 point2 = point1 + d; + float angle = b2_pi * m_degrees / 180.0f; + float L = 11.0f; + b2Vec2 point1(0.0f, 10.0f); + b2Vec2 d(L * cosf(angle), L * sinf(angle)); + b2Vec2 point2 = point1 + d; - if (m_mode == e_closest) - { - RayCastClosestCallback callback; - m_world->RayCast(&callback, point1, point2); + if (m_mode == e_closest) + { + RayCastClosestCallback callback; + m_world->RayCast(&callback, point1, point2); - if (callback.m_hit) - { - g_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); - g_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); - b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; - g_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); - } - else - { - g_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); - } - } - else if (m_mode == e_any) - { - RayCastAnyCallback callback; - m_world->RayCast(&callback, point1, point2); + if (callback.m_hit) + { + g_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); + g_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); + b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; + g_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); + } + else + { + g_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); + } + } + else if (m_mode == e_any) + { + RayCastAnyCallback callback; + m_world->RayCast(&callback, point1, point2); - if (callback.m_hit) - { - g_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); - g_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); - b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; - g_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); - } - else - { - g_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); - } - } - else if (m_mode == e_multiple) - { - RayCastMultipleCallback callback; - m_world->RayCast(&callback, point1, point2); - g_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); + if (callback.m_hit) + { + g_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); + g_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); + b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; + g_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); + } + else + { + g_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); + } + } + else if (m_mode == e_multiple) + { + RayCastMultipleCallback callback; + m_world->RayCast(&callback, point1, point2); + g_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); - for (int32 i = 0; i < callback.m_count; ++i) - { - b2Vec2 p = callback.m_points[i]; - b2Vec2 n = callback.m_normals[i]; - g_debugDraw.DrawPoint(p, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); - g_debugDraw.DrawSegment(point1, p, b2Color(0.8f, 0.8f, 0.8f)); - b2Vec2 head = p + 0.5f * n; - g_debugDraw.DrawSegment(p, head, b2Color(0.9f, 0.9f, 0.4f)); - } - } + for (int32 i = 0; i < callback.m_count; ++i) + { + b2Vec2 p = callback.m_points[i]; + b2Vec2 n = callback.m_normals[i]; + g_debugDraw.DrawPoint(p, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); + g_debugDraw.DrawSegment(point1, p, b2Color(0.8f, 0.8f, 0.8f)); + b2Vec2 head = p + 0.5f * n; + g_debugDraw.DrawSegment(p, head, b2Color(0.9f, 0.9f, 0.4f)); + } + } #if 0 // This case was failing. @@ -447,17 +460,20 @@ public: g_debugDraw.DrawSegment(input.p1, input.p2, color); } #endif - } + } - static Test* Create() { return new RayCast; } + static Test* Create() + { + return new RayCast; + } - int32 m_bodyIndex; - b2Body* m_bodies[e_maxBodies]; - b2PolygonShape m_polygons[4]; - b2CircleShape m_circle; - b2EdgeShape m_edge; - float m_degrees; - int32 m_mode; + int32 m_bodyIndex; + b2Body* m_bodies[e_maxBodies]; + b2PolygonShape m_polygons[4]; + b2CircleShape m_circle; + b2EdgeShape m_edge; + float m_degrees; + int32 m_mode; }; static int testIndex = RegisterTest("Collision", "Ray Cast", RayCast::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/restitution.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/restitution.cpp index 10dd861e57..7772c62363 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/restitution.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/restitution.cpp @@ -27,49 +27,53 @@ class Restitution : public Test { public: - Restitution() - { - const float threshold = 10.0f; - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + Restitution() + { + const float threshold = 10.0f; - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2FixtureDef fd; - fd.shape = &shape; - fd.restitutionThreshold = threshold; - ground->CreateFixture(&fd); - } + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + + b2FixtureDef fd; + fd.shape = &shape; + fd.restitutionThreshold = threshold; + ground->CreateFixture(&fd); + } - { - b2CircleShape shape; - shape.m_radius = 1.0f; + { + b2CircleShape shape; + shape.m_radius = 1.0f; - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; - float restitution[7] = {0.0f, 0.1f, 0.3f, 0.5f, 0.75f, 0.9f, 1.0f}; + float restitution[7] = { 0.0f, 0.1f, 0.3f, 0.5f, 0.75f, 0.9f, 1.0f }; - for (int32 i = 0; i < 7; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-10.0f + 3.0f * i, 20.0f); + for (int32 i = 0; i < 7; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-10.0f + 3.0f * i, 20.0f); - b2Body* body = m_world->CreateBody(&bd); + b2Body* body = m_world->CreateBody(&bd); - fd.restitution = restitution[i]; - fd.restitutionThreshold = threshold; - body->CreateFixture(&fd); - } - } - } + fd.restitution = restitution[i]; + fd.restitutionThreshold = threshold; + body->CreateFixture(&fd); + } + } + } - static Test* Create() { return new Restitution; } + static Test* Create() + { + return new Restitution; + } }; static int testIndex = RegisterTest("Forces", "Restitution", Restitution::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/revolute_joint.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/revolute_joint.cpp index 9422ce3473..e793d86bf2 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/revolute_joint.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/revolute_joint.cpp @@ -27,131 +27,136 @@ class RevoluteJoint : public Test { public: - RevoluteJoint() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + RevoluteJoint() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - b2FixtureDef fd; - fd.shape = &shape; - // fd.filter.categoryBits = 2; + b2FixtureDef fd; + fd.shape = &shape; + //fd.filter.categoryBits = 2; - ground->CreateFixture(&fd); - } + ground->CreateFixture(&fd); + } - m_enableLimit = true; - m_enableMotor = false; - m_motorSpeed = 1.0f; + m_enableLimit = true; + m_enableMotor = false; + m_motorSpeed = 1.0f; - { - b2PolygonShape shape; - shape.SetAsBox(0.25f, 3.0f, b2Vec2(0.0f, 3.0f), 0.0f); + { + b2PolygonShape shape; + shape.SetAsBox(0.25f, 3.0f, b2Vec2(0.0f, 3.0f), 0.0f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-10.0f, 20.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 5.0f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-10.0f, 20.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 5.0f); - b2RevoluteJointDef jd; - jd.Initialize(ground, body, b2Vec2(-10.0f, 20.5f)); - jd.motorSpeed = m_motorSpeed; - jd.maxMotorTorque = 10000.0f; - jd.enableMotor = m_enableMotor; - jd.lowerAngle = -0.25f * b2_pi; - jd.upperAngle = 0.5f * b2_pi; - jd.enableLimit = m_enableLimit; + b2RevoluteJointDef jd; + jd.Initialize(ground, body, b2Vec2(-10.0f, 20.5f)); + jd.motorSpeed = m_motorSpeed; + jd.maxMotorTorque = 10000.0f; + jd.enableMotor = m_enableMotor; + jd.lowerAngle = -0.25f * b2_pi; + jd.upperAngle = 0.5f * b2_pi; + jd.enableLimit = m_enableLimit; - m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&jd); - } + m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&jd); + } - { - b2CircleShape circle_shape; - circle_shape.m_radius = 2.0f; + { + b2CircleShape circle_shape; + circle_shape.m_radius = 2.0f; - b2BodyDef circle_bd; - circle_bd.type = b2_dynamicBody; - circle_bd.position.Set(5.0f, 30.0f); + b2BodyDef circle_bd; + circle_bd.type = b2_dynamicBody; + circle_bd.position.Set(5.0f, 30.0f); - b2FixtureDef fd; - fd.density = 5.0f; - fd.filter.maskBits = 1; - fd.shape = &circle_shape; + b2FixtureDef fd; + fd.density = 5.0f; + fd.filter.maskBits = 1; + fd.shape = &circle_shape; - m_ball = m_world->CreateBody(&circle_bd); - m_ball->CreateFixture(&fd); + m_ball = m_world->CreateBody(&circle_bd); + m_ball->CreateFixture(&fd); - b2PolygonShape polygon_shape; - polygon_shape.SetAsBox(10.0f, 0.5f, b2Vec2(-10.0f, 0.0f), 0.0f); + b2PolygonShape polygon_shape; + polygon_shape.SetAsBox(10.0f, 0.5f, b2Vec2 (-10.0f, 0.0f), 0.0f); - b2BodyDef polygon_bd; - polygon_bd.position.Set(20.0f, 10.0f); - polygon_bd.type = b2_dynamicBody; - polygon_bd.bullet = true; - b2Body* polygon_body = m_world->CreateBody(&polygon_bd); - polygon_body->CreateFixture(&polygon_shape, 2.0f); + b2BodyDef polygon_bd; + polygon_bd.position.Set(20.0f, 10.0f); + polygon_bd.type = b2_dynamicBody; + polygon_bd.bullet = true; + b2Body* polygon_body = m_world->CreateBody(&polygon_bd); + polygon_body->CreateFixture(&polygon_shape, 2.0f); - b2RevoluteJointDef jd; - jd.Initialize(ground, polygon_body, b2Vec2(19.0f, 10.0f)); - jd.lowerAngle = -0.25f * b2_pi; - jd.upperAngle = 0.0f * b2_pi; - jd.enableLimit = true; - jd.enableMotor = true; - jd.motorSpeed = 0.0f; - jd.maxMotorTorque = 10000.0f; + b2RevoluteJointDef jd; + jd.Initialize(ground, polygon_body, b2Vec2(19.0f, 10.0f)); + jd.lowerAngle = -0.25f * b2_pi; + jd.upperAngle = 0.0f * b2_pi; + jd.enableLimit = true; + jd.enableMotor = true; + jd.motorSpeed = 0.0f; + jd.maxMotorTorque = 10000.0f; - m_joint2 = (b2RevoluteJoint*)m_world->CreateJoint(&jd); - } - } + m_joint2 = (b2RevoluteJoint*)m_world->CreateJoint(&jd); + } + } - void UpdateUI() override - { - // ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); - ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); - ImGui::Begin("Joint Controls", nullptr, ImGuiWindowFlags_NoResize); + void UpdateUI() override + { + //ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); + ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); + ImGui::Begin("Joint Controls", nullptr, ImGuiWindowFlags_NoResize); - if (ImGui::Checkbox("Limit", &m_enableLimit)) - { - m_joint1->EnableLimit(m_enableLimit); - } + if (ImGui::Checkbox("Limit", &m_enableLimit)) + { + m_joint1->EnableLimit(m_enableLimit); + } - if (ImGui::Checkbox("Motor", &m_enableMotor)) - { - m_joint1->EnableMotor(m_enableMotor); - } + if (ImGui::Checkbox("Motor", &m_enableMotor)) + { + m_joint1->EnableMotor(m_enableMotor); + } - if (ImGui::SliderFloat("Speed", &m_motorSpeed, -20.0f, 20.0f, "%.0f")) - { - m_joint1->SetMotorSpeed(m_motorSpeed); - } + if (ImGui::SliderFloat("Speed", &m_motorSpeed, -20.0f, 20.0f, "%.0f")) + { + m_joint1->SetMotorSpeed(m_motorSpeed); + } - ImGui::End(); - } + ImGui::End(); + } - void Step(Settings& settings) override - { - Test::Step(settings); + void Step(Settings& settings) override + { + Test::Step(settings); + + float torque1 = m_joint1->GetMotorTorque(settings.m_hertz); + DrawString(5, m_textLine, "Motor Torque 1= %4.0f", torque1); + - float torque1 = m_joint1->GetMotorTorque(settings.m_hertz); - DrawString(5, m_textLine, "Motor Torque 1= %4.0f", torque1); + float torque2 = m_joint2->GetMotorTorque(settings.m_hertz); + DrawString(5, m_textLine, "Motor Torque 2= %4.0f", torque2); + + } - float torque2 = m_joint2->GetMotorTorque(settings.m_hertz); - DrawString(5, m_textLine, "Motor Torque 2= %4.0f", torque2); - } + static Test* Create() + { + return new RevoluteJoint; + } - static Test* Create() { return new RevoluteJoint; } - - b2Body* m_ball; - b2RevoluteJoint* m_joint1; - b2RevoluteJoint* m_joint2; - float m_motorSpeed; - bool m_enableMotor; - bool m_enableLimit; + b2Body* m_ball; + b2RevoluteJoint* m_joint1; + b2RevoluteJoint* m_joint2; + float m_motorSpeed; + bool m_enableMotor; + bool m_enableLimit; }; static int testIndex = RegisterTest("Joints", "Revolute", RevoluteJoint::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/rope.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/rope.cpp index 65b41763f2..846cfaaee6 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/rope.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/rope.cpp @@ -29,254 +29,258 @@ class Rope : public Test { public: - Rope() - { - const int32 N = 20; - const float L = 0.5f; - b2Vec2 vertices[N]; - float masses[N]; + Rope() + { + const int32 N = 20; + const float L = 0.5f; + b2Vec2 vertices[N]; + float masses[N]; - for (int32 i = 0; i < N; ++i) - { - vertices[i].Set(0.0f, L * (N - i)); - masses[i] = 1.0f; - } - masses[0] = 0.0f; - masses[1] = 0.0f; + for (int32 i = 0; i < N; ++i) + { + vertices[i].Set(0.0f, L * (N - i)); + masses[i] = 1.0f; + } + masses[0] = 0.0f; + masses[1] = 0.0f; - m_tuning1.bendHertz = 30.0f; - m_tuning1.bendDamping = 4.0f; - m_tuning1.bendStiffness = 1.0f; - m_tuning1.bendingModel = b2_pbdTriangleBendingModel; - m_tuning1.isometric = true; + m_tuning1.bendHertz = 30.0f; + m_tuning1.bendDamping = 4.0f; + m_tuning1.bendStiffness = 1.0f; + m_tuning1.bendingModel = b2_pbdTriangleBendingModel; + m_tuning1.isometric = true; - m_tuning1.stretchHertz = 30.0f; - m_tuning1.stretchDamping = 4.0f; - m_tuning1.stretchStiffness = 1.0f; - m_tuning1.stretchingModel = b2_pbdStretchingModel; + m_tuning1.stretchHertz = 30.0f; + m_tuning1.stretchDamping = 4.0f; + m_tuning1.stretchStiffness = 1.0f; + m_tuning1.stretchingModel = b2_pbdStretchingModel; - m_tuning2.bendHertz = 30.0f; - m_tuning2.bendDamping = 0.7f; - m_tuning2.bendStiffness = 1.0f; - m_tuning2.bendingModel = b2_pbdHeightBendingModel; - m_tuning2.isometric = true; + m_tuning2.bendHertz = 30.0f; + m_tuning2.bendDamping = 0.7f; + m_tuning2.bendStiffness = 1.0f; + m_tuning2.bendingModel = b2_pbdHeightBendingModel; + m_tuning2.isometric = true; - m_tuning2.stretchHertz = 30.0f; - m_tuning2.stretchDamping = 1.0f; - m_tuning2.stretchStiffness = 1.0f; - m_tuning2.stretchingModel = b2_pbdStretchingModel; + m_tuning2.stretchHertz = 30.0f; + m_tuning2.stretchDamping = 1.0f; + m_tuning2.stretchStiffness = 1.0f; + m_tuning2.stretchingModel = b2_pbdStretchingModel; - m_position1.Set(-5.0f, 15.0f); - m_position2.Set(5.0f, 15.0f); + m_position1.Set(-5.0f, 15.0f); + m_position2.Set(5.0f, 15.0f); - b2RopeDef def; - def.vertices = vertices; - def.count = N; - def.gravity.Set(0.0f, -10.0f); - def.masses = masses; + b2RopeDef def; + def.vertices = vertices; + def.count = N; + def.gravity.Set(0.0f, -10.0f); + def.masses = masses; - def.position = m_position1; - def.tuning = m_tuning1; - m_rope1.Create(def); + def.position = m_position1; + def.tuning = m_tuning1; + m_rope1.Create(def); - def.position = m_position2; - def.tuning = m_tuning2; - m_rope2.Create(def); + def.position = m_position2; + def.tuning = m_tuning2; + m_rope2.Create(def); - m_iterations1 = 8; - m_iterations2 = 8; + m_iterations1 = 8; + m_iterations2 = 8; - m_speed = 10.0f; - } + m_speed = 10.0f; + } - void UpdateUI() override - { - // ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); - ImGui::SetNextWindowSize(ImVec2(200.0f, 700.0f)); - ImGui::Begin("Tuning", nullptr, ImGuiWindowFlags_NoResize); + void UpdateUI() override + { + //ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); + ImGui::SetNextWindowSize(ImVec2(200.0f, 700.0f)); + ImGui::Begin("Tuning", nullptr, ImGuiWindowFlags_NoResize); - ImGui::Separator(); + ImGui::Separator(); ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); + + const ImGuiComboFlags comboFlags = 0; + const char* bendModels[] = { "Spring", "PBD Ang", "XPBD Ang", "PBD Dist", "PBD Height", "PBD Triangle" }; + const char* stretchModels[] = { "PBD", "XPBD" }; - const ImGuiComboFlags comboFlags = 0; - const char* bendModels[] = {"Spring", "PBD Ang", "XPBD Ang", "PBD Dist", "PBD Height", "PBD Triangle"}; - const char* stretchModels[] = {"PBD", "XPBD"}; + ImGui::Text("Rope 1"); + static int bendModel1 = m_tuning1.bendingModel; + if (ImGui::BeginCombo("Bend Model##1", bendModels[bendModel1], comboFlags)) + { + for (int i = 0; i < IM_ARRAYSIZE(bendModels); ++i) + { + bool isSelected = (bendModel1 == i); + if (ImGui::Selectable(bendModels[i], isSelected)) + { + bendModel1 = i; + m_tuning1.bendingModel = b2BendingModel(i); + } - ImGui::Text("Rope 1"); - static int bendModel1 = m_tuning1.bendingModel; - if (ImGui::BeginCombo("Bend Model##1", bendModels[bendModel1], comboFlags)) - { - for (int i = 0; i < IM_ARRAYSIZE(bendModels); ++i) - { - bool isSelected = (bendModel1 == i); - if (ImGui::Selectable(bendModels[i], isSelected)) - { - bendModel1 = i; - m_tuning1.bendingModel = b2BendingModel(i); - } + if (isSelected) + { + ImGui::SetItemDefaultFocus(); + } + } + ImGui::EndCombo(); + } - if (isSelected) - { - ImGui::SetItemDefaultFocus(); - } - } - ImGui::EndCombo(); - } + ImGui::SliderFloat("Damping##B1", &m_tuning1.bendDamping, 0.0f, 4.0f, "%.1f"); + ImGui::SliderFloat("Hertz##B1", &m_tuning1.bendHertz, 0.0f, 60.0f, "%.0f"); + ImGui::SliderFloat("Stiffness##B1", &m_tuning1.bendStiffness, 0.0f, 1.0f, "%.1f"); - ImGui::SliderFloat("Damping##B1", &m_tuning1.bendDamping, 0.0f, 4.0f, "%.1f"); - ImGui::SliderFloat("Hertz##B1", &m_tuning1.bendHertz, 0.0f, 60.0f, "%.0f"); - ImGui::SliderFloat("Stiffness##B1", &m_tuning1.bendStiffness, 0.0f, 1.0f, "%.1f"); + ImGui::Checkbox("Isometric##1", &m_tuning1.isometric); + ImGui::Checkbox("Fixed Mass##1", &m_tuning1.fixedEffectiveMass); + ImGui::Checkbox("Warm Start##1", &m_tuning1.warmStart); - ImGui::Checkbox("Isometric##1", &m_tuning1.isometric); - ImGui::Checkbox("Fixed Mass##1", &m_tuning1.fixedEffectiveMass); - ImGui::Checkbox("Warm Start##1", &m_tuning1.warmStart); + static int stretchModel1 = m_tuning1.stretchingModel; + if (ImGui::BeginCombo("Stretch Model##1", stretchModels[stretchModel1], comboFlags)) + { + for (int i = 0; i < IM_ARRAYSIZE(stretchModels); ++i) + { + bool isSelected = (stretchModel1 == i); + if (ImGui::Selectable(stretchModels[i], isSelected)) + { + stretchModel1 = i; + m_tuning1.stretchingModel = b2StretchingModel(i); + } - static int stretchModel1 = m_tuning1.stretchingModel; - if (ImGui::BeginCombo("Stretch Model##1", stretchModels[stretchModel1], comboFlags)) - { - for (int i = 0; i < IM_ARRAYSIZE(stretchModels); ++i) - { - bool isSelected = (stretchModel1 == i); - if (ImGui::Selectable(stretchModels[i], isSelected)) - { - stretchModel1 = i; - m_tuning1.stretchingModel = b2StretchingModel(i); - } + if (isSelected) + { + ImGui::SetItemDefaultFocus(); + } + } + ImGui::EndCombo(); + } - if (isSelected) - { - ImGui::SetItemDefaultFocus(); - } - } - ImGui::EndCombo(); - } + ImGui::SliderFloat("Damping##S1", &m_tuning1.stretchDamping, 0.0f, 4.0f, "%.1f"); + ImGui::SliderFloat("Hertz##S1", &m_tuning1.stretchHertz, 0.0f, 60.0f, "%.0f"); + ImGui::SliderFloat("Stiffness##S1", &m_tuning1.stretchStiffness, 0.0f, 1.0f, "%.1f"); - ImGui::SliderFloat("Damping##S1", &m_tuning1.stretchDamping, 0.0f, 4.0f, "%.1f"); - ImGui::SliderFloat("Hertz##S1", &m_tuning1.stretchHertz, 0.0f, 60.0f, "%.0f"); - ImGui::SliderFloat("Stiffness##S1", &m_tuning1.stretchStiffness, 0.0f, 1.0f, "%.1f"); + ImGui::SliderInt("Iterations##1", &m_iterations1, 1, 100, "%d"); - ImGui::SliderInt("Iterations##1", &m_iterations1, 1, 100, "%d"); + ImGui::Separator(); - ImGui::Separator(); + ImGui::Text("Rope 2"); + static int bendModel2 = m_tuning2.bendingModel; + if (ImGui::BeginCombo("Bend Model##2", bendModels[bendModel2], comboFlags)) + { + for (int i = 0; i < IM_ARRAYSIZE(bendModels); ++i) + { + bool isSelected = (bendModel2 == i); + if (ImGui::Selectable(bendModels[i], isSelected)) + { + bendModel2 = i; + m_tuning2.bendingModel = b2BendingModel(i); + } - ImGui::Text("Rope 2"); - static int bendModel2 = m_tuning2.bendingModel; - if (ImGui::BeginCombo("Bend Model##2", bendModels[bendModel2], comboFlags)) - { - for (int i = 0; i < IM_ARRAYSIZE(bendModels); ++i) - { - bool isSelected = (bendModel2 == i); - if (ImGui::Selectable(bendModels[i], isSelected)) - { - bendModel2 = i; - m_tuning2.bendingModel = b2BendingModel(i); - } + if (isSelected) + { + ImGui::SetItemDefaultFocus(); + } + } + ImGui::EndCombo(); + } - if (isSelected) - { - ImGui::SetItemDefaultFocus(); - } - } - ImGui::EndCombo(); - } + ImGui::SliderFloat("Damping##B2", &m_tuning2.bendDamping, 0.0f, 4.0f, "%.1f"); + ImGui::SliderFloat("Hertz##B2", &m_tuning2.bendHertz, 0.0f, 60.0f, "%.0f"); + ImGui::SliderFloat("Stiffness##B2", &m_tuning2.bendStiffness, 0.0f, 1.0f, "%.1f"); - ImGui::SliderFloat("Damping##B2", &m_tuning2.bendDamping, 0.0f, 4.0f, "%.1f"); - ImGui::SliderFloat("Hertz##B2", &m_tuning2.bendHertz, 0.0f, 60.0f, "%.0f"); - ImGui::SliderFloat("Stiffness##B2", &m_tuning2.bendStiffness, 0.0f, 1.0f, "%.1f"); + ImGui::Checkbox("Isometric##2", &m_tuning2.isometric); + ImGui::Checkbox("Fixed Mass##2", &m_tuning2.fixedEffectiveMass); + ImGui::Checkbox("Warm Start##2", &m_tuning2.warmStart); - ImGui::Checkbox("Isometric##2", &m_tuning2.isometric); - ImGui::Checkbox("Fixed Mass##2", &m_tuning2.fixedEffectiveMass); - ImGui::Checkbox("Warm Start##2", &m_tuning2.warmStart); + static int stretchModel2 = m_tuning2.stretchingModel; + if (ImGui::BeginCombo("Stretch Model##2", stretchModels[stretchModel2], comboFlags)) + { + for (int i = 0; i < IM_ARRAYSIZE(stretchModels); ++i) + { + bool isSelected = (stretchModel2 == i); + if (ImGui::Selectable(stretchModels[i], isSelected)) + { + stretchModel2 = i; + m_tuning2.stretchingModel = b2StretchingModel(i); + } - static int stretchModel2 = m_tuning2.stretchingModel; - if (ImGui::BeginCombo("Stretch Model##2", stretchModels[stretchModel2], comboFlags)) - { - for (int i = 0; i < IM_ARRAYSIZE(stretchModels); ++i) - { - bool isSelected = (stretchModel2 == i); - if (ImGui::Selectable(stretchModels[i], isSelected)) - { - stretchModel2 = i; - m_tuning2.stretchingModel = b2StretchingModel(i); - } + if (isSelected) + { + ImGui::SetItemDefaultFocus(); + } + } + ImGui::EndCombo(); + } - if (isSelected) - { - ImGui::SetItemDefaultFocus(); - } - } - ImGui::EndCombo(); - } + ImGui::SliderFloat("Damping##S2", &m_tuning2.stretchDamping, 0.0f, 4.0f, "%.1f"); + ImGui::SliderFloat("Hertz##S2", &m_tuning2.stretchHertz, 0.0f, 60.0f, "%.0f"); + ImGui::SliderFloat("Stiffness##S2", &m_tuning2.stretchStiffness, 0.0f, 1.0f, "%.1f"); - ImGui::SliderFloat("Damping##S2", &m_tuning2.stretchDamping, 0.0f, 4.0f, "%.1f"); - ImGui::SliderFloat("Hertz##S2", &m_tuning2.stretchHertz, 0.0f, 60.0f, "%.0f"); - ImGui::SliderFloat("Stiffness##S2", &m_tuning2.stretchStiffness, 0.0f, 1.0f, "%.1f"); + ImGui::SliderInt("Iterations##2", &m_iterations2, 1, 100, "%d"); - ImGui::SliderInt("Iterations##2", &m_iterations2, 1, 100, "%d"); + ImGui::Separator(); - ImGui::Separator(); + ImGui::SliderFloat("Speed", &m_speed, 10.0f, 100.0f, "%.0f"); - ImGui::SliderFloat("Speed", &m_speed, 10.0f, 100.0f, "%.0f"); - - if (ImGui::Button("Reset")) - { - m_position1.Set(-5.0f, 15.0f); - m_position2.Set(5.0f, 15.0f); - m_rope1.Reset(m_position1); - m_rope2.Reset(m_position2); - } + if (ImGui::Button("Reset")) + { + m_position1.Set(-5.0f, 15.0f); + m_position2.Set(5.0f, 15.0f); + m_rope1.Reset(m_position1); + m_rope2.Reset(m_position2); + } ImGui::PopItemWidth(); - ImGui::End(); - } + ImGui::End(); + } - void Step(Settings& settings) override - { - float dt = settings.m_hertz > 0.0f ? 1.0f / settings.m_hertz : 0.0f; + void Step(Settings& settings) override + { + float dt = settings.m_hertz > 0.0f ? 1.0f / settings.m_hertz : 0.0f; - if (settings.m_pause == 1 && settings.m_singleStep == 0) - { - dt = 0.0f; - } + if (settings.m_pause == 1 && settings.m_singleStep == 0) + { + dt = 0.0f; + } - // if (glfwGetKey(g_mainWindow, GLFW_KEY_COMMA) == GLFW_PRESS) - //{ - // m_position1.x -= m_speed * dt; - // m_position2.x -= m_speed * dt; - // } + //if (glfwGetKey(g_mainWindow, GLFW_KEY_COMMA) == GLFW_PRESS) + //{ + // m_position1.x -= m_speed * dt; + // m_position2.x -= m_speed * dt; + //} - // if (glfwGetKey(g_mainWindow, GLFW_KEY_PERIOD) == GLFW_PRESS) - //{ - // m_position1.x += m_speed * dt; - // m_position2.x += m_speed * dt; - // } + //if (glfwGetKey(g_mainWindow, GLFW_KEY_PERIOD) == GLFW_PRESS) + //{ + // m_position1.x += m_speed * dt; + // m_position2.x += m_speed * dt; + //} - m_rope1.SetTuning(m_tuning1); - m_rope2.SetTuning(m_tuning2); - m_rope1.Step(dt, m_iterations1, m_position1); - m_rope2.Step(dt, m_iterations2, m_position2); + m_rope1.SetTuning(m_tuning1); + m_rope2.SetTuning(m_tuning2); + m_rope1.Step(dt, m_iterations1, m_position1); + m_rope2.Step(dt, m_iterations2, m_position2); - Test::Step(settings); + Test::Step(settings); - m_rope1.Draw(&g_debugDraw); - m_rope2.Draw(&g_debugDraw); + m_rope1.Draw(&g_debugDraw); + m_rope2.Draw(&g_debugDraw); - DrawString(5, m_textLine, "Press comma and period to move left and right"); - } + DrawString(5, m_textLine, "Press comma and period to move left and right"); + + } - static Test* Create() { return new Rope; } + static Test* Create() + { + return new Rope; + } - b2Rope m_rope1; - b2Rope m_rope2; - b2RopeTuning m_tuning1; - b2RopeTuning m_tuning2; - int32 m_iterations1; - int32 m_iterations2; - b2Vec2 m_position1; - b2Vec2 m_position2; - float m_speed; + b2Rope m_rope1; + b2Rope m_rope2; + b2RopeTuning m_tuning1; + b2RopeTuning m_tuning2; + int32 m_iterations1; + int32 m_iterations2; + b2Vec2 m_position1; + b2Vec2 m_position2; + float m_speed; }; static int testIndex = RegisterTest("Rope", "Bending", Rope::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/sensor.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/sensor.cpp index b7b4b9bdb0..af9e88c1e1 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/sensor.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/sensor.cpp @@ -27,22 +27,23 @@ class Sensors : public Test { public: - enum - { - e_count = 7 - }; - Sensors() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + enum + { + e_count = 7 + }; - { - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + Sensors() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + { + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } #if 0 { @@ -52,140 +53,143 @@ public: m_sensor = ground->CreateFixture(&sd); } #else - { - b2CircleShape shape; - shape.m_radius = 5.0f; - shape.m_p.Set(0.0f, 10.0f); + { + b2CircleShape shape; + shape.m_radius = 5.0f; + shape.m_p.Set(0.0f, 10.0f); - b2FixtureDef fd; - fd.shape = &shape; - fd.isSensor = true; - m_sensor = ground->CreateFixture(&fd); - } + b2FixtureDef fd; + fd.shape = &shape; + fd.isSensor = true; + m_sensor = ground->CreateFixture(&fd); + } #endif - } + } - { - b2CircleShape shape; - shape.m_radius = 1.0f; + { + b2CircleShape shape; + shape.m_radius = 1.0f; - for (int32 i = 0; i < e_count; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-10.0f + 3.0f * i, 20.0f); - bd.userData.pointer = i; + for (int32 i = 0; i < e_count; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-10.0f + 3.0f * i, 20.0f); + bd.userData.pointer = i; - m_touching[i] = false; - m_bodies[i] = m_world->CreateBody(&bd); + m_touching[i] = false; + m_bodies[i] = m_world->CreateBody(&bd); - m_bodies[i]->CreateFixture(&shape, 1.0f); - } - } + m_bodies[i]->CreateFixture(&shape, 1.0f); + } + } - m_force = 100.0f; - } + m_force = 100.0f; + } - // Implement contact listener. - void BeginContact(b2Contact* contact) override - { - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); + // Implement contact listener. + void BeginContact(b2Contact* contact) override + { + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); - if (fixtureA == m_sensor) - { - uintptr_t index = fixtureB->GetBody()->GetUserData().pointer; - if (index < e_count) - { - m_touching[index] = true; - } - } + if (fixtureA == m_sensor) + { + uintptr_t index = fixtureB->GetBody()->GetUserData().pointer; + if (index < e_count) + { + m_touching[index] = true; + } + } - if (fixtureB == m_sensor) - { - uintptr_t index = fixtureA->GetBody()->GetUserData().pointer; - if (index < e_count) - { - m_touching[index] = true; - } - } - } + if (fixtureB == m_sensor) + { + uintptr_t index = fixtureA->GetBody()->GetUserData().pointer; + if (index < e_count) + { + m_touching[index] = true; + } + } + } - // Implement contact listener. - void EndContact(b2Contact* contact) override - { - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); + // Implement contact listener. + void EndContact(b2Contact* contact) override + { + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); - if (fixtureA == m_sensor) - { - uintptr_t index = fixtureB->GetBody()->GetUserData().pointer; - if (index < e_count) - { - m_touching[index] = false; - } - } + if (fixtureA == m_sensor) + { + uintptr_t index = fixtureB->GetBody()->GetUserData().pointer; + if (index < e_count) + { + m_touching[index] = false; + } + } - if (fixtureB == m_sensor) - { - uintptr_t index = fixtureA->GetBody()->GetUserData().pointer; - if (index < e_count) - { - m_touching[index] = false; - } - } - } + if (fixtureB == m_sensor) + { + uintptr_t index = fixtureA->GetBody()->GetUserData().pointer; + if (index < e_count) + { + m_touching[index] = false; + } + } + } - void UpdateUI() override - { - // ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); - ImGui::SetNextWindowSize(ImVec2(200.0f, 60.0f)); - ImGui::Begin("Sensor Controls", nullptr, ImGuiWindowFlags_NoResize); + void UpdateUI() override + { + //ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); + ImGui::SetNextWindowSize(ImVec2(200.0f, 60.0f)); + ImGui::Begin("Sensor Controls", nullptr, ImGuiWindowFlags_NoResize); - ImGui::SliderFloat("Force", &m_force, 0.0f, 2000.0f, "%.0f"); + ImGui::SliderFloat("Force", &m_force, 0.0f, 2000.0f, "%.0f"); - ImGui::End(); - } + ImGui::End(); + } - void Step(Settings& settings) override - { - Test::Step(settings); + void Step(Settings& settings) override + { + Test::Step(settings); - // Traverse the contact results. Apply a force on shapes - // that overlap the sensor. - for (int32 i = 0; i < e_count; ++i) - { - if (m_touching[i] == false) - { - continue; - } + // Traverse the contact results. Apply a force on shapes + // that overlap the sensor. + for (int32 i = 0; i < e_count; ++i) + { + if (m_touching[i] == false) + { + continue; + } - b2Body* body = m_bodies[i]; - b2Body* ground = m_sensor->GetBody(); + b2Body* body = m_bodies[i]; + b2Body* ground = m_sensor->GetBody(); - b2CircleShape* circle = (b2CircleShape*)m_sensor->GetShape(); - b2Vec2 center = ground->GetWorldPoint(circle->m_p); + b2CircleShape* circle = (b2CircleShape*)m_sensor->GetShape(); + b2Vec2 center = ground->GetWorldPoint(circle->m_p); - b2Vec2 position = body->GetPosition(); + b2Vec2 position = body->GetPosition(); - b2Vec2 d = center - position; - if (d.LengthSquared() < FLT_EPSILON * FLT_EPSILON) - { - continue; - } + b2Vec2 d = center - position; + if (d.LengthSquared() < FLT_EPSILON * FLT_EPSILON) + { + continue; + } - d.Normalize(); - b2Vec2 F = m_force * d; - body->ApplyForce(F, position, false); - } - } + d.Normalize(); + b2Vec2 F = m_force * d; + body->ApplyForce(F, position, false); + } + } - static Test* Create() { return new Sensors; } + static Test* Create() + { + return new Sensors; + } - b2Fixture* m_sensor; - b2Body* m_bodies[e_count]; - float m_force; - bool m_touching[e_count]; + b2Fixture* m_sensor; + b2Body* m_bodies[e_count]; + float m_force; + bool m_touching[e_count]; }; static int testIndex = RegisterTest("Collision", "Sensors", Sensors::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/settings.h b/tests/cpp-tests/Classes/Box2DTestBed/tests/settings.h index 7ba71423e8..a34f6fda0c 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/settings.h +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/settings.h @@ -25,59 +25,62 @@ struct Settings { - Settings() { Reset(); } + Settings() + { + Reset(); + } - void Reset() - { - m_testIndex = 0; - m_windowWidth = 1600; - m_windowHeight = 900; - m_hertz = 60.0f; - m_velocityIterations = 8; - m_positionIterations = 3; - m_drawShapes = true; - m_drawJoints = true; - m_drawAABBs = false; - m_drawContactPoints = false; - m_drawContactNormals = false; - m_drawContactImpulse = false; - m_drawFrictionImpulse = false; - m_drawCOMs = false; - m_drawStats = false; - m_drawProfile = false; - m_enableWarmStarting = true; - m_enableContinuous = true; - m_enableSubStepping = false; - m_enableSleep = true; - m_pause = false; - m_singleStep = false; - } + void Reset() + { + m_testIndex = 0; + m_windowWidth = 1600; + m_windowHeight = 900; + m_hertz = 60.0f; + m_velocityIterations = 8; + m_positionIterations = 3; + m_drawShapes = true; + m_drawJoints = true; + m_drawAABBs = false; + m_drawContactPoints = false; + m_drawContactNormals = false; + m_drawContactImpulse = false; + m_drawFrictionImpulse = false; + m_drawCOMs = false; + m_drawStats = false; + m_drawProfile = false; + m_enableWarmStarting = true; + m_enableContinuous = true; + m_enableSubStepping = false; + m_enableSleep = true; + m_pause = false; + m_singleStep = false; + } - void Save(); - void Load(); + void Save(); + void Load(); - int m_testIndex; - int m_windowWidth; - int m_windowHeight; - float m_hertz; - int m_velocityIterations; - int m_positionIterations; - bool m_drawShapes; - bool m_drawJoints; - bool m_drawAABBs; - bool m_drawContactPoints; - bool m_drawContactNormals; - bool m_drawContactImpulse; - bool m_drawFrictionImpulse; - bool m_drawCOMs; - bool m_drawStats; - bool m_drawProfile; - bool m_enableWarmStarting; - bool m_enableContinuous; - bool m_enableSubStepping; - bool m_enableSleep; - bool m_pause; - bool m_singleStep; + int m_testIndex; + int m_windowWidth; + int m_windowHeight; + float m_hertz; + int m_velocityIterations; + int m_positionIterations; + bool m_drawShapes; + bool m_drawJoints; + bool m_drawAABBs; + bool m_drawContactPoints; + bool m_drawContactNormals; + bool m_drawContactImpulse; + bool m_drawFrictionImpulse; + bool m_drawCOMs; + bool m_drawStats; + bool m_drawProfile; + bool m_enableWarmStarting; + bool m_enableContinuous; + bool m_enableSubStepping; + bool m_enableSleep; + bool m_pause; + bool m_singleStep; }; #endif \ No newline at end of file diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/shape_cast.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/shape_cast.cpp index 60771b5896..2c942add28 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/shape_cast.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/shape_cast.cpp @@ -26,164 +26,168 @@ class ShapeCast : public Test { public: - enum - { - e_vertexCount = 8 - }; + enum + { + e_vertexCount = 8 + }; - ShapeCast() - { + ShapeCast() + { #if 1 - m_vAs[0].Set(-0.5f, 1.0f); - m_vAs[1].Set(0.5f, 1.0f); - m_vAs[2].Set(0.0f, 0.0f); - m_countA = 3; - m_radiusA = b2_polygonRadius; + m_vAs[0].Set(-0.5f, 1.0f); + m_vAs[1].Set(0.5f, 1.0f); + m_vAs[2].Set(0.0f, 0.0f); + m_countA = 3; + m_radiusA = b2_polygonRadius; - m_vBs[0].Set(-0.5f, -0.5f); - m_vBs[1].Set(0.5f, -0.5f); - m_vBs[2].Set(0.5f, 0.5f); - m_vBs[3].Set(-0.5f, 0.5f); - m_countB = 4; - m_radiusB = b2_polygonRadius; + m_vBs[0].Set(-0.5f, -0.5f); + m_vBs[1].Set(0.5f, -0.5f); + m_vBs[2].Set(0.5f, 0.5f); + m_vBs[3].Set(-0.5f, 0.5f); + m_countB = 4; + m_radiusB = b2_polygonRadius; - m_transformA.p.Set(0.0f, 0.25f); - m_transformA.q.SetIdentity(); - m_transformB.p.Set(-4.0f, 0.0f); - m_transformB.q.SetIdentity(); - m_translationB.Set(8.0f, 0.0f); + m_transformA.p.Set(0.0f, 0.25f); + m_transformA.q.SetIdentity(); + m_transformB.p.Set(-4.0f, 0.0f); + m_transformB.q.SetIdentity(); + m_translationB.Set(8.0f, 0.0f); #elif 0 - m_vAs[0].Set(0.0f, 0.0f); - m_countA = 1; - m_radiusA = 0.5f; + m_vAs[0].Set(0.0f, 0.0f); + m_countA = 1; + m_radiusA = 0.5f; - m_vBs[0].Set(0.0f, 0.0f); - m_countB = 1; - m_radiusB = 0.5f; + m_vBs[0].Set(0.0f, 0.0f); + m_countB = 1; + m_radiusB = 0.5f; - m_transformA.p.Set(0.0f, 0.25f); - m_transformA.q.SetIdentity(); - m_transformB.p.Set(-4.0f, 0.0f); - m_transformB.q.SetIdentity(); - m_translationB.Set(8.0f, 0.0f); + m_transformA.p.Set(0.0f, 0.25f); + m_transformA.q.SetIdentity(); + m_transformB.p.Set(-4.0f, 0.0f); + m_transformB.q.SetIdentity(); + m_translationB.Set(8.0f, 0.0f); #else - m_vAs[0].Set(0.0f, 0.0f); - m_vAs[1].Set(2.0f, 0.0f); - m_countA = 2; - m_radiusA = b2_polygonRadius; + m_vAs[0].Set(0.0f, 0.0f); + m_vAs[1].Set(2.0f, 0.0f); + m_countA = 2; + m_radiusA = b2_polygonRadius; - m_vBs[0].Set(0.0f, 0.0f); - m_countB = 1; - m_radiusB = 0.25f; + m_vBs[0].Set(0.0f, 0.0f); + m_countB = 1; + m_radiusB = 0.25f; - // Initial overlap - m_transformA.p.Set(0.0f, 0.0f); - m_transformA.q.SetIdentity(); - m_transformB.p.Set(-0.244360745f, 0.05999358f); - m_transformB.q.SetIdentity(); - m_translationB.Set(0.0f, 0.0399999991f); + // Initial overlap + m_transformA.p.Set(0.0f, 0.0f); + m_transformA.q.SetIdentity(); + m_transformB.p.Set(-0.244360745f, 0.05999358f); + m_transformB.q.SetIdentity(); + m_translationB.Set(0.0f, 0.0399999991f); #endif - } + } - static Test* Create() { return new ShapeCast; } + static Test* Create() + { + return new ShapeCast; + } - void Step(Settings& settings) override - { - Test::Step(settings); + void Step(Settings& settings) override + { + Test::Step(settings); - b2ShapeCastInput input; - input.proxyA.Set(m_vAs, m_countA, m_radiusA); - input.proxyB.Set(m_vBs, m_countB, m_radiusB); - input.transformA = m_transformA; - input.transformB = m_transformB; - input.translationB = m_translationB; + b2ShapeCastInput input; + input.proxyA.Set(m_vAs, m_countA, m_radiusA); + input.proxyB.Set(m_vBs, m_countB, m_radiusB); + input.transformA = m_transformA; + input.transformB = m_transformB; + input.translationB = m_translationB; - b2ShapeCastOutput output; - bool hit = b2ShapeCast(&output, &input); + b2ShapeCastOutput output; + bool hit = b2ShapeCast(&output, &input); - b2Transform transformB2; - transformB2.q = m_transformB.q; - transformB2.p = m_transformB.p + output.lambda * input.translationB; + b2Transform transformB2; + transformB2.q = m_transformB.q; + transformB2.p = m_transformB.p + output.lambda * input.translationB; - b2DistanceInput distanceInput; - distanceInput.proxyA.Set(m_vAs, m_countA, m_radiusA); - distanceInput.proxyB.Set(m_vBs, m_countB, m_radiusB); - distanceInput.transformA = m_transformA; - distanceInput.transformB = transformB2; - distanceInput.useRadii = false; - b2SimplexCache simplexCache; - simplexCache.count = 0; - b2DistanceOutput distanceOutput; + b2DistanceInput distanceInput; + distanceInput.proxyA.Set(m_vAs, m_countA, m_radiusA); + distanceInput.proxyB.Set(m_vBs, m_countB, m_radiusB); + distanceInput.transformA = m_transformA; + distanceInput.transformB = transformB2; + distanceInput.useRadii = false; + b2SimplexCache simplexCache; + simplexCache.count = 0; + b2DistanceOutput distanceOutput; - b2Distance(&distanceOutput, &simplexCache, &distanceInput); + b2Distance(&distanceOutput, &simplexCache, &distanceInput); - DrawString(5, m_textLine, "hit = %s, iters = %d, lambda = %g, distance = %g", hit ? "true" : "false", - output.iterations, output.lambda, distanceOutput.distance); + DrawString(5, m_textLine, "hit = %s, iters = %d, lambda = %g, distance = %g", + hit ? "true" : "false", output.iterations, output.lambda, distanceOutput.distance); + - b2Vec2 vertices[b2_maxPolygonVertices]; + b2Vec2 vertices[b2_maxPolygonVertices]; - for (int32 i = 0; i < m_countA; ++i) - { - vertices[i] = b2Mul(m_transformA, m_vAs[i]); - } + for (int32 i = 0; i < m_countA; ++i) + { + vertices[i] = b2Mul(m_transformA, m_vAs[i]); + } - if (m_countA == 1) - { - g_debugDraw.DrawCircle(vertices[0], m_radiusA, b2Color(0.9f, 0.9f, 0.9f)); - } - else - { - g_debugDraw.DrawPolygon(vertices, m_countA, b2Color(0.9f, 0.9f, 0.9f)); - } + if (m_countA == 1) + { + g_debugDraw.DrawCircle(vertices[0], m_radiusA, b2Color(0.9f, 0.9f, 0.9f)); + } + else + { + g_debugDraw.DrawPolygon(vertices, m_countA, b2Color(0.9f, 0.9f, 0.9f)); + } - for (int32 i = 0; i < m_countB; ++i) - { - vertices[i] = b2Mul(m_transformB, m_vBs[i]); - } + for (int32 i = 0; i < m_countB; ++i) + { + vertices[i] = b2Mul(m_transformB, m_vBs[i]); + } - if (m_countB == 1) - { - g_debugDraw.DrawCircle(vertices[0], m_radiusB, b2Color(0.5f, 0.9f, 0.5f)); - } - else - { - g_debugDraw.DrawPolygon(vertices, m_countB, b2Color(0.5f, 0.9f, 0.5f)); - } + if (m_countB == 1) + { + g_debugDraw.DrawCircle(vertices[0], m_radiusB, b2Color(0.5f, 0.9f, 0.5f)); + } + else + { + g_debugDraw.DrawPolygon(vertices, m_countB, b2Color(0.5f, 0.9f, 0.5f)); + } - for (int32 i = 0; i < m_countB; ++i) - { - vertices[i] = b2Mul(transformB2, m_vBs[i]); - } + for (int32 i = 0; i < m_countB; ++i) + { + vertices[i] = b2Mul(transformB2, m_vBs[i]); + } - if (m_countB == 1) - { - g_debugDraw.DrawCircle(vertices[0], m_radiusB, b2Color(0.5f, 0.7f, 0.9f)); - } - else - { - g_debugDraw.DrawPolygon(vertices, m_countB, b2Color(0.5f, 0.7f, 0.9f)); - } + if (m_countB == 1) + { + g_debugDraw.DrawCircle(vertices[0], m_radiusB, b2Color(0.5f, 0.7f, 0.9f)); + } + else + { + g_debugDraw.DrawPolygon(vertices, m_countB, b2Color(0.5f, 0.7f, 0.9f)); + } - if (hit) - { - b2Vec2 p1 = output.point; - g_debugDraw.DrawPoint(p1, 10.0f, b2Color(0.9f, 0.3f, 0.3f)); - b2Vec2 p2 = p1 + output.normal; - g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.3f, 0.3f)); - } - } + if (hit) + { + b2Vec2 p1 = output.point; + g_debugDraw.DrawPoint(p1, 10.0f, b2Color(0.9f, 0.3f, 0.3f)); + b2Vec2 p2 = p1 + output.normal; + g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.3f, 0.3f)); + } + } - b2Vec2 m_vAs[b2_maxPolygonVertices]; - int32 m_countA; - float m_radiusA; + b2Vec2 m_vAs[b2_maxPolygonVertices]; + int32 m_countA; + float m_radiusA; - b2Vec2 m_vBs[b2_maxPolygonVertices]; - int32 m_countB; - float m_radiusB; + b2Vec2 m_vBs[b2_maxPolygonVertices]; + int32 m_countB; + float m_radiusB; - b2Transform m_transformA; - b2Transform m_transformB; - b2Vec2 m_translationB; + b2Transform m_transformA; + b2Transform m_transformB; + b2Vec2 m_translationB; }; static int testIndex = RegisterTest("Collision", "Shape Cast", ShapeCast::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/shape_editing.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/shape_editing.cpp index c7b753b524..357ed8fa28 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/shape_editing.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/shape_editing.cpp @@ -25,79 +25,84 @@ class ShapeEditing : public Test { public: - ShapeEditing() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + ShapeEditing() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 10.0f); - m_body = m_world->CreateBody(&bd); + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - b2PolygonShape shape; - shape.SetAsBox(4.0f, 4.0f, b2Vec2(0.0f, 0.0f), 0.0f); - m_fixture1 = m_body->CreateFixture(&shape, 10.0f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 10.0f); + m_body = m_world->CreateBody(&bd); - m_fixture2 = NULL; + b2PolygonShape shape; + shape.SetAsBox(4.0f, 4.0f, b2Vec2(0.0f, 0.0f), 0.0f); + m_fixture1 = m_body->CreateFixture(&shape, 10.0f); - m_sensor = false; - } + m_fixture2 = NULL; - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_C: - if (m_fixture2 == NULL) - { - b2CircleShape shape; - shape.m_radius = 3.0f; - shape.m_p.Set(0.5f, -4.0f); - m_fixture2 = m_body->CreateFixture(&shape, 10.0f); - m_body->SetAwake(true); - } - break; + m_sensor = false; + } - case GLFW_KEY_D: - if (m_fixture2 != NULL) - { - m_body->DestroyFixture(m_fixture2); - m_fixture2 = NULL; - m_body->SetAwake(true); - } - break; + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_C: + if (m_fixture2 == NULL) + { + b2CircleShape shape; + shape.m_radius = 3.0f; + shape.m_p.Set(0.5f, -4.0f); + m_fixture2 = m_body->CreateFixture(&shape, 10.0f); + m_body->SetAwake(true); + } + break; - case GLFW_KEY_S: - if (m_fixture2 != NULL) - { - m_sensor = !m_sensor; - m_fixture2->SetSensor(m_sensor); - } - break; - } - } + case GLFW_KEY_D: + if (m_fixture2 != NULL) + { + m_body->DestroyFixture(m_fixture2); + m_fixture2 = NULL; + m_body->SetAwake(true); + } + break; - void Step(Settings& settings) override - { - Test::Step(settings); - DrawString(5, m_textLine, "Press: (c) create a shape, (d) destroy a shape."); + case GLFW_KEY_S: + if (m_fixture2 != NULL) + { + m_sensor = !m_sensor; + m_fixture2->SetSensor(m_sensor); + } + break; + } + } - DrawString(5, m_textLine, "sensor = %d", m_sensor); - } + void Step(Settings& settings) override + { + Test::Step(settings); + DrawString(5, m_textLine, "Press: (c) create a shape, (d) destroy a shape."); + + DrawString(5, m_textLine, "sensor = %d", m_sensor); + + } - static Test* Create() { return new ShapeEditing; } + static Test* Create() + { + return new ShapeEditing; + } - b2Body* m_body; - b2Fixture* m_fixture1; - b2Fixture* m_fixture2; - bool m_sensor; + b2Body* m_body; + b2Fixture* m_fixture1; + b2Fixture* m_fixture2; + bool m_sensor; }; static int testIndex = RegisterTest("Examples", "Shape Editing", ShapeEditing::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/skier.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/skier.cpp index 05529640a2..c5ff525340 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/skier.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/skier.cpp @@ -10,137 +10,141 @@ Test case for collision/jerking issue. class Skier : public Test { public: - Skier() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + Skier() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - float const PlatformWidth = 8.0f; + float const PlatformWidth = 8.0f; - /* - First angle is from the horizontal and should be negative for a downward slope. - Second angle is relative to the preceding slope, and should be positive, creating a kind of - loose 'Z'-shape from the 3 edges. - If A1 = -10, then A2 <= ~1.5 will result in the collision glitch. - If A1 = -30, then A2 <= ~10.0 will result in the glitch. - */ - float const Angle1Degrees = -30.0f; - float const Angle2Degrees = 10.0f; + /* + First angle is from the horizontal and should be negative for a downward slope. + Second angle is relative to the preceding slope, and should be positive, creating a kind of + loose 'Z'-shape from the 3 edges. + If A1 = -10, then A2 <= ~1.5 will result in the collision glitch. + If A1 = -30, then A2 <= ~10.0 will result in the glitch. + */ + float const Angle1Degrees = -30.0f; + float const Angle2Degrees = 10.0f; + + /* + The larger the value of SlopeLength, the less likely the glitch will show up. + */ + float const SlopeLength = 2.0f; - /* - The larger the value of SlopeLength, the less likely the glitch will show up. - */ - float const SlopeLength = 2.0f; + float const SurfaceFriction = 0.2f; - float const SurfaceFriction = 0.2f; + // Convert to radians + float const Slope1Incline = -Angle1Degrees * b2_pi / 180.0f; + float const Slope2Incline = Slope1Incline - Angle2Degrees * b2_pi / 180.0f; + // - // Convert to radians - float const Slope1Incline = -Angle1Degrees * b2_pi / 180.0f; - float const Slope2Incline = Slope1Incline - Angle2Degrees * b2_pi / 180.0f; - // + m_platform_width = PlatformWidth; - m_platform_width = PlatformWidth; + // Horizontal platform + b2Vec2 v1(-PlatformWidth, 0.0f); + b2Vec2 v2(0.0f, 0.0f); + b2Vec2 v3(SlopeLength * cosf(Slope1Incline), -SlopeLength * sinf(Slope1Incline)); + b2Vec2 v4(v3.x + SlopeLength * cosf(Slope2Incline), v3.y - SlopeLength * sinf(Slope2Incline)); + b2Vec2 v5(v4.x, v4.y - 1.0f); - // Horizontal platform - b2Vec2 v1(-PlatformWidth, 0.0f); - b2Vec2 v2(0.0f, 0.0f); - b2Vec2 v3(SlopeLength * cosf(Slope1Incline), -SlopeLength * sinf(Slope1Incline)); - b2Vec2 v4(v3.x + SlopeLength * cosf(Slope2Incline), v3.y - SlopeLength * sinf(Slope2Incline)); - b2Vec2 v5(v4.x, v4.y - 1.0f); + b2Vec2 vertices[5] = { v5, v4, v3, v2, v1 }; - b2Vec2 vertices[5] = {v5, v4, v3, v2, v1}; + b2ChainShape shape; + shape.CreateLoop(vertices, 5); + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 0.0f; + fd.friction = SurfaceFriction; - b2ChainShape shape; - shape.CreateLoop(vertices, 5); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 0.0f; - fd.friction = SurfaceFriction; + ground->CreateFixture(&fd); + } - ground->CreateFixture(&fd); - } + { + float const BodyWidth = 1.0f; + float const BodyHeight = 2.5f; + float const SkiLength = 3.0f; - { - float const BodyWidth = 1.0f; - float const BodyHeight = 2.5f; - float const SkiLength = 3.0f; + /* + Larger values for this seem to alleviate the issue to some extent. + */ + float const SkiThickness = 0.3f; - /* - Larger values for this seem to alleviate the issue to some extent. - */ - float const SkiThickness = 0.3f; + float const SkiFriction = 0.0f; + float const SkiRestitution = 0.15f; - float const SkiFriction = 0.0f; - float const SkiRestitution = 0.15f; + b2BodyDef bd; + bd.type = b2_dynamicBody; - b2BodyDef bd; - bd.type = b2_dynamicBody; + float initial_y = BodyHeight / 2 + SkiThickness; + bd.position.Set(-m_platform_width / 2, initial_y); - float initial_y = BodyHeight / 2 + SkiThickness; - bd.position.Set(-m_platform_width / 2, initial_y); + b2Body* skier = m_world->CreateBody(&bd); - b2Body* skier = m_world->CreateBody(&bd); + b2PolygonShape ski; + b2Vec2 verts[4]; + verts[0].Set(-SkiLength / 2 - SkiThickness, -BodyHeight / 2); + verts[1].Set(-SkiLength / 2, -BodyHeight / 2 - SkiThickness); + verts[2].Set(SkiLength / 2, -BodyHeight / 2 - SkiThickness); + verts[3].Set(SkiLength / 2 + SkiThickness, -BodyHeight / 2); + ski.Set(verts, 4); - b2PolygonShape ski; - b2Vec2 verts[4]; - verts[0].Set(-SkiLength / 2 - SkiThickness, -BodyHeight / 2); - verts[1].Set(-SkiLength / 2, -BodyHeight / 2 - SkiThickness); - verts[2].Set(SkiLength / 2, -BodyHeight / 2 - SkiThickness); - verts[3].Set(SkiLength / 2 + SkiThickness, -BodyHeight / 2); - ski.Set(verts, 4); + b2FixtureDef fd; + fd.density = 1.0f; - b2FixtureDef fd; - fd.density = 1.0f; + fd.friction = SkiFriction; + fd.restitution = SkiRestitution; - fd.friction = SkiFriction; - fd.restitution = SkiRestitution; + fd.shape = &ski; + skier->CreateFixture(&fd); - fd.shape = &ski; - skier->CreateFixture(&fd); + skier->SetLinearVelocity(b2Vec2(0.5f, 0.0f)); - skier->SetLinearVelocity(b2Vec2(0.5f, 0.0f)); + m_skier = skier; + } - m_skier = skier; - } + //g_camera.m_center = b2Vec2(m_platform_width / 2.0f, 0.0f); + //g_camera.m_zoom = 0.4f; + m_fixed_camera = true; + } - // g_camera.m_center = b2Vec2(m_platform_width / 2.0f, 0.0f); - // g_camera.m_zoom = 0.4f; - m_fixed_camera = true; - } + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_C: + m_fixed_camera = !m_fixed_camera; + if(m_fixed_camera) + { + // g_camera.m_center = b2Vec2(m_platform_width / 2.0f, 0.0f); + } + break; + } + } - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_C: - m_fixed_camera = !m_fixed_camera; - if (m_fixed_camera) - { - // g_camera.m_center = b2Vec2(m_platform_width / 2.0f, 0.0f); - } - break; - } - } + void Step(Settings& settings) override + { + DrawString(5, m_textLine, "Keys: c = Camera fixed/tracking"); + - void Step(Settings& settings) override - { - DrawString(5, m_textLine, "Keys: c = Camera fixed/tracking"); + if(!m_fixed_camera) + { + //g_camera.m_center = m_skier->GetPosition(); + } - if (!m_fixed_camera) - { - // g_camera.m_center = m_skier->GetPosition(); - } + Test::Step(settings); + } - Test::Step(settings); - } + static Test* Create() + { + return new Skier; + } - static Test* Create() { return new Skier; } - - b2Body* m_skier; - float m_platform_width; - bool m_fixed_camera; + b2Body* m_skier; + float m_platform_width; + bool m_fixed_camera; }; static int testIndex = RegisterTest("Bugs", "Skier", Skier::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/slider_crank_1.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/slider_crank_1.cpp index e09e8ade19..395b93939e 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/slider_crank_1.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/slider_crank_1.cpp @@ -26,78 +26,81 @@ class SliderCrank1 : public Test { public: - SliderCrank1() - { - b2Body* ground = NULL; - { - b2BodyDef bd; + SliderCrank1() + { + b2Body* ground = NULL; + { + b2BodyDef bd; bd.position.Set(0.0f, 17.0f); - ground = m_world->CreateBody(&bd); - } - - { - b2Body* prevBody = ground; - - // Define crank. - { - b2PolygonShape shape; - shape.SetAsBox(4.0f, 1.0f); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-8.0f, 20.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 2.0f); - - b2RevoluteJointDef rjd; - rjd.Initialize(prevBody, body, b2Vec2(-12.0f, 20.0f)); - m_world->CreateJoint(&rjd); - - prevBody = body; - } - - // Define connecting rod - { - b2PolygonShape shape; - shape.SetAsBox(8.0f, 1.0f); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(4.0f, 20.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 2.0f); - - b2RevoluteJointDef rjd; - rjd.Initialize(prevBody, body, b2Vec2(-4.0f, 20.0f)); - m_world->CreateJoint(&rjd); - - prevBody = body; - } - - // Define piston - { - b2PolygonShape shape; - shape.SetAsBox(3.0f, 3.0f); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.fixedRotation = true; - bd.position.Set(12.0f, 20.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 2.0f); - - b2RevoluteJointDef rjd; - rjd.Initialize(prevBody, body, b2Vec2(12.0f, 20.0f)); - m_world->CreateJoint(&rjd); - - b2PrismaticJointDef pjd; - pjd.Initialize(ground, body, b2Vec2(12.0f, 17.0f), b2Vec2(1.0f, 0.0f)); - m_world->CreateJoint(&pjd); - } - } - } - - static Test* Create() { return new SliderCrank1; } + ground = m_world->CreateBody(&bd); + } + + { + b2Body* prevBody = ground; + + // Define crank. + { + b2PolygonShape shape; + shape.SetAsBox(4.0f, 1.0f); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-8.0f, 20.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 2.0f); + + b2RevoluteJointDef rjd; + rjd.Initialize(prevBody, body, b2Vec2(-12.0f, 20.0f)); + m_world->CreateJoint(&rjd); + + prevBody = body; + } + + // Define connecting rod + { + b2PolygonShape shape; + shape.SetAsBox(8.0f, 1.0f); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(4.0f, 20.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 2.0f); + + b2RevoluteJointDef rjd; + rjd.Initialize(prevBody, body, b2Vec2(-4.0f, 20.0f)); + m_world->CreateJoint(&rjd); + + prevBody = body; + } + + // Define piston + { + b2PolygonShape shape; + shape.SetAsBox(3.0f, 3.0f); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.fixedRotation = true; + bd.position.Set(12.0f, 20.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 2.0f); + + b2RevoluteJointDef rjd; + rjd.Initialize(prevBody, body, b2Vec2(12.0f, 20.0f)); + m_world->CreateJoint(&rjd); + + b2PrismaticJointDef pjd; + pjd.Initialize(ground, body, b2Vec2(12.0f, 17.0f), b2Vec2(1.0f, 0.0f)); + m_world->CreateJoint(&pjd); + } + } + } + + static Test* Create() + { + return new SliderCrank1; + } }; static int testIndex = RegisterTest("Examples", "Slider Crank 1", SliderCrank1::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/slider_crank_2.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/slider_crank_2.cpp index f55a05859c..22119e803a 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/slider_crank_2.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/slider_crank_2.cpp @@ -28,129 +28,133 @@ class SliderCrank2 : public Test { public: - SliderCrank2() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + SliderCrank2() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2Body* prevBody = ground; + { + b2Body* prevBody = ground; - // Define crank. - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 2.0f); + // Define crank. + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 2.0f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 7.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 2.0f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 7.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 2.0f); - b2RevoluteJointDef rjd; - rjd.Initialize(prevBody, body, b2Vec2(0.0f, 5.0f)); - rjd.motorSpeed = 1.0f * b2_pi; - rjd.maxMotorTorque = 10000.0f; - rjd.enableMotor = true; - m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&rjd); + b2RevoluteJointDef rjd; + rjd.Initialize(prevBody, body, b2Vec2(0.0f, 5.0f)); + rjd.motorSpeed = 1.0f * b2_pi; + rjd.maxMotorTorque = 10000.0f; + rjd.enableMotor = true; + m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&rjd); - prevBody = body; - } + prevBody = body; + } - // Define follower. - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 4.0f); + // Define follower. + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 4.0f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 13.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 2.0f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 13.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 2.0f); - b2RevoluteJointDef rjd; - rjd.Initialize(prevBody, body, b2Vec2(0.0f, 9.0f)); - rjd.enableMotor = false; - m_world->CreateJoint(&rjd); + b2RevoluteJointDef rjd; + rjd.Initialize(prevBody, body, b2Vec2(0.0f, 9.0f)); + rjd.enableMotor = false; + m_world->CreateJoint(&rjd); - prevBody = body; - } + prevBody = body; + } - // Define piston - { - b2PolygonShape shape; - shape.SetAsBox(1.5f, 1.5f); + // Define piston + { + b2PolygonShape shape; + shape.SetAsBox(1.5f, 1.5f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.fixedRotation = true; - bd.position.Set(0.0f, 17.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 2.0f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.fixedRotation = true; + bd.position.Set(0.0f, 17.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 2.0f); - b2RevoluteJointDef rjd; - rjd.Initialize(prevBody, body, b2Vec2(0.0f, 17.0f)); - m_world->CreateJoint(&rjd); + b2RevoluteJointDef rjd; + rjd.Initialize(prevBody, body, b2Vec2(0.0f, 17.0f)); + m_world->CreateJoint(&rjd); - b2PrismaticJointDef pjd; - pjd.Initialize(ground, body, b2Vec2(0.0f, 17.0f), b2Vec2(0.0f, 1.0f)); + b2PrismaticJointDef pjd; + pjd.Initialize(ground, body, b2Vec2(0.0f, 17.0f), b2Vec2(0.0f, 1.0f)); - pjd.maxMotorForce = 1000.0f; - pjd.enableMotor = true; + pjd.maxMotorForce = 1000.0f; + pjd.enableMotor = true; - m_joint2 = (b2PrismaticJoint*)m_world->CreateJoint(&pjd); - } + m_joint2 = (b2PrismaticJoint*)m_world->CreateJoint(&pjd); + } - // Create a payload - { - b2PolygonShape shape; - shape.SetAsBox(1.5f, 1.5f); + // Create a payload + { + b2PolygonShape shape; + shape.SetAsBox(1.5f, 1.5f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 23.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 2.0f); - } - } - } + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 23.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 2.0f); + } + } + } - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_F: - m_joint2->EnableMotor(!m_joint2->IsMotorEnabled()); - m_joint2->GetBodyB()->SetAwake(true); - break; + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_F: + m_joint2->EnableMotor(!m_joint2->IsMotorEnabled()); + m_joint2->GetBodyB()->SetAwake(true); + break; - case GLFW_KEY_M: - m_joint1->EnableMotor(!m_joint1->IsMotorEnabled()); - m_joint1->GetBodyB()->SetAwake(true); - break; - } - } + case GLFW_KEY_M: + m_joint1->EnableMotor(!m_joint1->IsMotorEnabled()); + m_joint1->GetBodyB()->SetAwake(true); + break; + } + } - void Step(Settings& settings) override - { - Test::Step(settings); - DrawString(5, m_textLine, "Keys: (f) toggle friction, (m) toggle motor"); + void Step(Settings& settings) override + { + Test::Step(settings); + DrawString(5, m_textLine, "Keys: (f) toggle friction, (m) toggle motor"); + + float torque = m_joint1->GetMotorTorque(settings.m_hertz); + DrawString(5, m_textLine, "Motor Torque = %5.0f", (float) torque); + + } - float torque = m_joint1->GetMotorTorque(settings.m_hertz); - DrawString(5, m_textLine, "Motor Torque = %5.0f", (float)torque); - } + static Test* Create() + { + return new SliderCrank2; + } - static Test* Create() { return new SliderCrank2; } - - b2RevoluteJoint* m_joint1; - b2PrismaticJoint* m_joint2; + b2RevoluteJoint* m_joint1; + b2PrismaticJoint* m_joint2; }; static int testIndex = RegisterTest("Examples", "Slider Crank 2", SliderCrank2::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/test.h b/tests/cpp-tests/Classes/Box2DTestBed/tests/test.h index f2a465e729..0d81acaa72 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/test.h +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/test.h @@ -1,20 +1,20 @@ /* - * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - */ +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ #ifndef TEST_H #define TEST_H @@ -27,121 +27,123 @@ class Test; struct Settings; -#define RAND_LIMIT 32767 +#define RAND_LIMIT 32767 #define DRAW_STRING_NEW_LINE 25 /// Random number in range [-1,1] inline float RandomFloat() { - float r = (float)(std::rand() & (RAND_LIMIT)); - r /= RAND_LIMIT; - r = 2.0f * r - 1.0f; - return r; + float r = (float)(std::rand() & (RAND_LIMIT)); + r /= RAND_LIMIT; + r = 2.0f * r - 1.0f; + return r; } /// Random floating point number in range [lo, hi] inline float RandomFloat(float lo, float hi) { - float r = (float)(std::rand() & (RAND_LIMIT)); - r /= RAND_LIMIT; - r = (hi - lo) * r + lo; - return r; + float r = (float)(std::rand() & (RAND_LIMIT)); + r /= RAND_LIMIT; + r = (hi - lo) * r + lo; + return r; } + // This is called when a joint in the world is implicitly destroyed // because an attached body is destroyed. This gives us a chance to // nullify the mouse joint. class DestructionListener : public b2DestructionListener { public: - void SayGoodbye(b2Fixture* fixture) { B2_NOT_USED(fixture); } - void SayGoodbye(b2Joint* joint); + void SayGoodbye(b2Fixture* fixture) { B2_NOT_USED(fixture); } + void SayGoodbye(b2Joint* joint); - Test* test; + Test* test; }; const int32 k_maxContactPoints = 2048; struct ContactPoint { - b2Fixture* fixtureA; - b2Fixture* fixtureB; - b2Vec2 normal; - b2Vec2 position; - b2PointState state; - float normalImpulse; - float tangentImpulse; - float separation; + b2Fixture* fixtureA; + b2Fixture* fixtureB; + b2Vec2 normal; + b2Vec2 position; + b2PointState state; + float normalImpulse; + float tangentImpulse; + float separation; }; class Test : public b2ContactListener { public: - Test(); - virtual ~Test(); - void DrawTitle(const char* string); - virtual void Step(Settings& settings); - virtual void UpdateUI() {} - virtual void Keyboard(int key) { B2_NOT_USED(key); } - virtual void KeyboardUp(int key) { B2_NOT_USED(key); } - void ShiftMouseDown(const b2Vec2& p); - virtual bool MouseDown(const b2Vec2& p); - virtual void MouseUp(const b2Vec2& p); - virtual void MouseMove(const b2Vec2& p); - void LaunchBomb(); - void LaunchBomb(const b2Vec2& position, const b2Vec2& velocity); + Test(); + virtual ~Test(); - void SpawnBomb(const b2Vec2& worldPt); - void CompleteBombSpawn(const b2Vec2& p); + void DrawTitle(const char* string); + virtual void Step(Settings& settings); + virtual void UpdateUI() {} + virtual void Keyboard(int key) { B2_NOT_USED(key); } + virtual void KeyboardUp(int key) { B2_NOT_USED(key); } + void ShiftMouseDown(const b2Vec2& p); + virtual bool MouseDown(const b2Vec2& p); + virtual void MouseUp(const b2Vec2& p); + virtual void MouseMove(const b2Vec2& p); + void LaunchBomb(); + void LaunchBomb(const b2Vec2& position, const b2Vec2& velocity); - // Let derived tests know that a joint was destroyed. - virtual void JointDestroyed(b2Joint* joint) { B2_NOT_USED(joint); } + void SpawnBomb(const b2Vec2& worldPt); + void CompleteBombSpawn(const b2Vec2& p); - // Callbacks for derived classes. - virtual void BeginContact(b2Contact* contact) override { B2_NOT_USED(contact); } - virtual void EndContact(b2Contact* contact) override { B2_NOT_USED(contact); } - virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override; - virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) override - { - B2_NOT_USED(contact); - B2_NOT_USED(impulse); - } + // Let derived tests know that a joint was destroyed. + virtual void JointDestroyed(b2Joint* joint) { B2_NOT_USED(joint); } - void ShiftOrigin(const b2Vec2& newOrigin); + // Callbacks for derived classes. + virtual void BeginContact(b2Contact* contact) override { B2_NOT_USED(contact); } + virtual void EndContact(b2Contact* contact) override { B2_NOT_USED(contact); } + virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override; + virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) override + { + B2_NOT_USED(contact); + B2_NOT_USED(impulse); + } - void initShader(void); - void DrawString(int x, int y, const char* fmt, ...); - void DrawString(const b2Vec2& p, const char* fmt, ...); - void DrawAABB(b2AABB* aabb, const b2Color& color); - void Flush(); + void ShiftOrigin(const b2Vec2& newOrigin); - cocos2d::extension::PhysicsDebugNodeBox2D g_debugDraw; - cocos2d::DrawNode* debugDrawNode; - std::string debugString = ""; + void initShader(void); + void DrawString(int x, int y, const char* fmt, ...); + void DrawString(const b2Vec2& p, const char* fmt, ...); + void DrawAABB(b2AABB* aabb, const b2Color& color); + void Flush(); - b2World* m_world; + cocos2d::extension::PhysicsDebugNodeBox2D g_debugDraw; + cocos2d::DrawNode* debugDrawNode; + std::string debugString = ""; + + b2World* m_world; protected: - friend class DestructionListener; - friend class BoundaryListener; - friend class ContactListener; + friend class DestructionListener; + friend class BoundaryListener; + friend class ContactListener; - b2Body* m_groundBody; - b2AABB m_worldAABB; - ContactPoint m_points[k_maxContactPoints]; - int32 m_pointCount; - DestructionListener m_destructionListener; - int32 m_textLine; + b2Body* m_groundBody; + b2AABB m_worldAABB; + ContactPoint m_points[k_maxContactPoints]; + int32 m_pointCount; + DestructionListener m_destructionListener; + int32 m_textLine; - b2Body* m_bomb; - b2MouseJoint* m_mouseJoint; - b2Vec2 m_bombSpawnPoint; - bool m_bombSpawning; - b2Vec2 m_mouseWorld; - int32 m_stepCount; - int32 m_textIncrement; - b2Profile m_maxProfile; - b2Profile m_totalProfile; + b2Body* m_bomb; + b2MouseJoint* m_mouseJoint; + b2Vec2 m_bombSpawnPoint; + bool m_bombSpawning; + b2Vec2 m_mouseWorld; + int32 m_stepCount; + int32 m_textIncrement; + b2Profile m_maxProfile; + b2Profile m_totalProfile; }; typedef Test* TestCreateFcn(); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/theo_jansen.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/theo_jansen.cpp index cab814037c..4ff62c7a5d 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/theo_jansen.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/theo_jansen.cpp @@ -28,234 +28,239 @@ class TheoJansen : public Test { public: - void CreateLeg(float s, const b2Vec2& wheelAnchor) - { - b2Vec2 p1(5.4f * s, -6.1f); - b2Vec2 p2(7.2f * s, -1.2f); - b2Vec2 p3(4.3f * s, -1.9f); - b2Vec2 p4(3.1f * s, 0.8f); - b2Vec2 p5(6.0f * s, 1.5f); - b2Vec2 p6(2.5f * s, 3.7f); - b2FixtureDef fd1, fd2; - fd1.filter.groupIndex = -1; - fd2.filter.groupIndex = -1; - fd1.density = 1.0f; - fd2.density = 1.0f; + void CreateLeg(float s, const b2Vec2& wheelAnchor) + { + b2Vec2 p1(5.4f * s, -6.1f); + b2Vec2 p2(7.2f * s, -1.2f); + b2Vec2 p3(4.3f * s, -1.9f); + b2Vec2 p4(3.1f * s, 0.8f); + b2Vec2 p5(6.0f * s, 1.5f); + b2Vec2 p6(2.5f * s, 3.7f); - b2PolygonShape poly1, poly2; + b2FixtureDef fd1, fd2; + fd1.filter.groupIndex = -1; + fd2.filter.groupIndex = -1; + fd1.density = 1.0f; + fd2.density = 1.0f; - if (s > 0.0f) - { - b2Vec2 vertices[3]; + b2PolygonShape poly1, poly2; - vertices[0] = p1; - vertices[1] = p2; - vertices[2] = p3; - poly1.Set(vertices, 3); + if (s > 0.0f) + { + b2Vec2 vertices[3]; - vertices[0] = b2Vec2_zero; - vertices[1] = p5 - p4; - vertices[2] = p6 - p4; - poly2.Set(vertices, 3); - } - else - { - b2Vec2 vertices[3]; + vertices[0] = p1; + vertices[1] = p2; + vertices[2] = p3; + poly1.Set(vertices, 3); - vertices[0] = p1; - vertices[1] = p3; - vertices[2] = p2; - poly1.Set(vertices, 3); + vertices[0] = b2Vec2_zero; + vertices[1] = p5 - p4; + vertices[2] = p6 - p4; + poly2.Set(vertices, 3); + } + else + { + b2Vec2 vertices[3]; - vertices[0] = b2Vec2_zero; - vertices[1] = p6 - p4; - vertices[2] = p5 - p4; - poly2.Set(vertices, 3); - } + vertices[0] = p1; + vertices[1] = p3; + vertices[2] = p2; + poly1.Set(vertices, 3); - fd1.shape = &poly1; - fd2.shape = &poly2; + vertices[0] = b2Vec2_zero; + vertices[1] = p6 - p4; + vertices[2] = p5 - p4; + poly2.Set(vertices, 3); + } - b2BodyDef bd1, bd2; - bd1.type = b2_dynamicBody; - bd2.type = b2_dynamicBody; - bd1.position = m_offset; - bd2.position = p4 + m_offset; + fd1.shape = &poly1; + fd2.shape = &poly2; - bd1.angularDamping = 10.0f; - bd2.angularDamping = 10.0f; + b2BodyDef bd1, bd2; + bd1.type = b2_dynamicBody; + bd2.type = b2_dynamicBody; + bd1.position = m_offset; + bd2.position = p4 + m_offset; - b2Body* body1 = m_world->CreateBody(&bd1); - b2Body* body2 = m_world->CreateBody(&bd2); + bd1.angularDamping = 10.0f; + bd2.angularDamping = 10.0f; - body1->CreateFixture(&fd1); - body2->CreateFixture(&fd2); + b2Body* body1 = m_world->CreateBody(&bd1); + b2Body* body2 = m_world->CreateBody(&bd2); - { - b2DistanceJointDef jd; + body1->CreateFixture(&fd1); + body2->CreateFixture(&fd2); - // Using a soft distance constraint can reduce some jitter. - // It also makes the structure seem a bit more fluid by - // acting like a suspension system. - float dampingRatio = 0.5f; - float frequencyHz = 10.0f; + { + b2DistanceJointDef jd; - jd.Initialize(body1, body2, p2 + m_offset, p5 + m_offset); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_world->CreateJoint(&jd); + // Using a soft distance constraint can reduce some jitter. + // It also makes the structure seem a bit more fluid by + // acting like a suspension system. + float dampingRatio = 0.5f; + float frequencyHz = 10.0f; - jd.Initialize(body1, body2, p3 + m_offset, p4 + m_offset); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_world->CreateJoint(&jd); + jd.Initialize(body1, body2, p2 + m_offset, p5 + m_offset); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_world->CreateJoint(&jd); - jd.Initialize(body1, m_wheel, p3 + m_offset, wheelAnchor + m_offset); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_world->CreateJoint(&jd); + jd.Initialize(body1, body2, p3 + m_offset, p4 + m_offset); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_world->CreateJoint(&jd); - jd.Initialize(body2, m_wheel, p6 + m_offset, wheelAnchor + m_offset); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_world->CreateJoint(&jd); - } + jd.Initialize(body1, m_wheel, p3 + m_offset, wheelAnchor + m_offset); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_world->CreateJoint(&jd); - { - b2RevoluteJointDef jd; - jd.Initialize(body2, m_chassis, p4 + m_offset); - m_world->CreateJoint(&jd); - } - } + jd.Initialize(body2, m_wheel, p6 + m_offset, wheelAnchor + m_offset); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_world->CreateJoint(&jd); + } - TheoJansen() - { - m_offset.Set(0.0f, 8.0f); - m_motorSpeed = 2.0f; - m_motorOn = true; - b2Vec2 pivot(0.0f, 0.8f); + { + b2RevoluteJointDef jd; + jd.Initialize(body2, m_chassis, p4 + m_offset); + m_world->CreateJoint(&jd); + } + } - // Ground - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + TheoJansen() + { + m_offset.Set(0.0f, 8.0f); + m_motorSpeed = 2.0f; + m_motorOn = true; + b2Vec2 pivot(0.0f, 0.8f); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-50.0f, 0.0f), b2Vec2(50.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); + // Ground + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - shape.SetTwoSided(b2Vec2(-50.0f, 0.0f), b2Vec2(-50.0f, 10.0f)); - ground->CreateFixture(&shape, 0.0f); + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-50.0f, 0.0f), b2Vec2(50.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); - shape.SetTwoSided(b2Vec2(50.0f, 0.0f), b2Vec2(50.0f, 10.0f)); - ground->CreateFixture(&shape, 0.0f); - } + shape.SetTwoSided(b2Vec2(-50.0f, 0.0f), b2Vec2(-50.0f, 10.0f)); + ground->CreateFixture(&shape, 0.0f); - // Balls - for (int32 i = 0; i < 40; ++i) - { - b2CircleShape shape; - shape.m_radius = 0.25f; + shape.SetTwoSided(b2Vec2(50.0f, 0.0f), b2Vec2(50.0f, 10.0f)); + ground->CreateFixture(&shape, 0.0f); + } - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-40.0f + 2.0f * i, 0.5f); + // Balls + for (int32 i = 0; i < 40; ++i) + { + b2CircleShape shape; + shape.m_radius = 0.25f; - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 1.0f); - } + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-40.0f + 2.0f * i, 0.5f); - // Chassis - { - b2PolygonShape shape; - shape.SetAsBox(2.5f, 1.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 1.0f); + } - b2FixtureDef sd; - sd.density = 1.0f; - sd.shape = &shape; - sd.filter.groupIndex = -1; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = pivot + m_offset; - m_chassis = m_world->CreateBody(&bd); - m_chassis->CreateFixture(&sd); - } + // Chassis + { + b2PolygonShape shape; + shape.SetAsBox(2.5f, 1.0f); - { - b2CircleShape shape; - shape.m_radius = 1.6f; + b2FixtureDef sd; + sd.density = 1.0f; + sd.shape = &shape; + sd.filter.groupIndex = -1; + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = pivot + m_offset; + m_chassis = m_world->CreateBody(&bd); + m_chassis->CreateFixture(&sd); + } - b2FixtureDef sd; - sd.density = 1.0f; - sd.shape = &shape; - sd.filter.groupIndex = -1; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = pivot + m_offset; - m_wheel = m_world->CreateBody(&bd); - m_wheel->CreateFixture(&sd); - } + { + b2CircleShape shape; + shape.m_radius = 1.6f; - { - b2RevoluteJointDef jd; - jd.Initialize(m_wheel, m_chassis, pivot + m_offset); - jd.collideConnected = false; - jd.motorSpeed = m_motorSpeed; - jd.maxMotorTorque = 400.0f; - jd.enableMotor = m_motorOn; - m_motorJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); - } + b2FixtureDef sd; + sd.density = 1.0f; + sd.shape = &shape; + sd.filter.groupIndex = -1; + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = pivot + m_offset; + m_wheel = m_world->CreateBody(&bd); + m_wheel->CreateFixture(&sd); + } - b2Vec2 wheelAnchor; + { + b2RevoluteJointDef jd; + jd.Initialize(m_wheel, m_chassis, pivot + m_offset); + jd.collideConnected = false; + jd.motorSpeed = m_motorSpeed; + jd.maxMotorTorque = 400.0f; + jd.enableMotor = m_motorOn; + m_motorJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); + } - wheelAnchor = pivot + b2Vec2(0.0f, -0.8f); + b2Vec2 wheelAnchor; + + wheelAnchor = pivot + b2Vec2(0.0f, -0.8f); - CreateLeg(-1.0f, wheelAnchor); - CreateLeg(1.0f, wheelAnchor); + CreateLeg(-1.0f, wheelAnchor); + CreateLeg(1.0f, wheelAnchor); - m_wheel->SetTransform(m_wheel->GetPosition(), 120.0f * b2_pi / 180.0f); - CreateLeg(-1.0f, wheelAnchor); - CreateLeg(1.0f, wheelAnchor); + m_wheel->SetTransform(m_wheel->GetPosition(), 120.0f * b2_pi / 180.0f); + CreateLeg(-1.0f, wheelAnchor); + CreateLeg(1.0f, wheelAnchor); - m_wheel->SetTransform(m_wheel->GetPosition(), -120.0f * b2_pi / 180.0f); - CreateLeg(-1.0f, wheelAnchor); - CreateLeg(1.0f, wheelAnchor); - } + m_wheel->SetTransform(m_wheel->GetPosition(), -120.0f * b2_pi / 180.0f); + CreateLeg(-1.0f, wheelAnchor); + CreateLeg(1.0f, wheelAnchor); + } - void Step(Settings& settings) override - { - DrawString(5, m_textLine, "Keys: left = a, brake = s, right = d, toggle motor = m"); + void Step(Settings& settings) override + { + DrawString(5, m_textLine, "Keys: left = a, brake = s, right = d, toggle motor = m"); + - Test::Step(settings); - } + Test::Step(settings); + } - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_A: - m_motorJoint->SetMotorSpeed(-m_motorSpeed); - break; + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_A: + m_motorJoint->SetMotorSpeed(-m_motorSpeed); + break; - case GLFW_KEY_S: - m_motorJoint->SetMotorSpeed(0.0f); - break; + case GLFW_KEY_S: + m_motorJoint->SetMotorSpeed(0.0f); + break; - case GLFW_KEY_D: - m_motorJoint->SetMotorSpeed(m_motorSpeed); - break; + case GLFW_KEY_D: + m_motorJoint->SetMotorSpeed(m_motorSpeed); + break; - case GLFW_KEY_M: - m_motorJoint->EnableMotor(!m_motorJoint->IsMotorEnabled()); - break; - } - } + case GLFW_KEY_M: + m_motorJoint->EnableMotor(!m_motorJoint->IsMotorEnabled()); + break; + } + } - static Test* Create() { return new TheoJansen; } + static Test* Create() + { + return new TheoJansen; + } - b2Vec2 m_offset; - b2Body* m_chassis; - b2Body* m_wheel; - b2RevoluteJoint* m_motorJoint; - bool m_motorOn; - float m_motorSpeed; + b2Vec2 m_offset; + b2Body* m_chassis; + b2Body* m_wheel; + b2RevoluteJoint* m_motorJoint; + bool m_motorOn; + float m_motorSpeed; }; static int testIndex = RegisterTest("Examples", "Theo Jansen", TheoJansen::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/tiles.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/tiles.cpp index e5b9b5dd5f..9457862196 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/tiles.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/tiles.cpp @@ -27,127 +27,133 @@ class Tiles : public Test { public: - enum - { - e_count = 20 - }; + enum + { + e_count = 20 + }; - Tiles() - { - m_fixtureCount = 0; - b2Timer timer; + Tiles() + { + m_fixtureCount = 0; + b2Timer timer; - { - float a = 0.5f; - b2BodyDef bd; - bd.position.y = -a; - b2Body* ground = m_world->CreateBody(&bd); + { + float a = 0.5f; + b2BodyDef bd; + bd.position.y = -a; + b2Body* ground = m_world->CreateBody(&bd); #if 1 - int32 N = 200; - int32 M = 10; - b2Vec2 position; - position.y = 0.0f; - for (int32 j = 0; j < M; ++j) - { - position.x = -N * a; - for (int32 i = 0; i < N; ++i) - { - b2PolygonShape shape; - shape.SetAsBox(a, a, position, 0.0f); - ground->CreateFixture(&shape, 0.0f); - ++m_fixtureCount; - position.x += 2.0f * a; - } - position.y -= 2.0f * a; - } + int32 N = 200; + int32 M = 10; + b2Vec2 position; + position.y = 0.0f; + for (int32 j = 0; j < M; ++j) + { + position.x = -N * a; + for (int32 i = 0; i < N; ++i) + { + b2PolygonShape shape; + shape.SetAsBox(a, a, position, 0.0f); + ground->CreateFixture(&shape, 0.0f); + ++m_fixtureCount; + position.x += 2.0f * a; + } + position.y -= 2.0f * a; + } #else - int32 N = 200; - int32 M = 10; - b2Vec2 position; - position.x = -N * a; - for (int32 i = 0; i < N; ++i) - { - position.y = 0.0f; - for (int32 j = 0; j < M; ++j) - { - b2PolygonShape shape; - shape.SetAsBox(a, a, position, 0.0f); - ground->CreateFixture(&shape, 0.0f); - position.y -= 2.0f * a; - } - position.x += 2.0f * a; - } + int32 N = 200; + int32 M = 10; + b2Vec2 position; + position.x = -N * a; + for (int32 i = 0; i < N; ++i) + { + position.y = 0.0f; + for (int32 j = 0; j < M; ++j) + { + b2PolygonShape shape; + shape.SetAsBox(a, a, position, 0.0f); + ground->CreateFixture(&shape, 0.0f); + position.y -= 2.0f * a; + } + position.x += 2.0f * a; + } #endif - } + } - { - float a = 0.5f; - b2PolygonShape shape; - shape.SetAsBox(a, a); + { + float a = 0.5f; + b2PolygonShape shape; + shape.SetAsBox(a, a); - b2Vec2 x(-7.0f, 0.75f); - b2Vec2 y; - b2Vec2 deltaX(0.5625f, 1.25f); - b2Vec2 deltaY(1.125f, 0.0f); + b2Vec2 x(-7.0f, 0.75f); + b2Vec2 y; + b2Vec2 deltaX(0.5625f, 1.25f); + b2Vec2 deltaY(1.125f, 0.0f); - for (int32 i = 0; i < e_count; ++i) - { - y = x; + for (int32 i = 0; i < e_count; ++i) + { + y = x; - for (int32 j = i; j < e_count; ++j) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = y; + for (int32 j = i; j < e_count; ++j) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = y; - // if (i == 0 && j == 0) - //{ - // bd.allowSleep = false; - // } - // else - //{ - // bd.allowSleep = true; - // } + //if (i == 0 && j == 0) + //{ + // bd.allowSleep = false; + //} + //else + //{ + // bd.allowSleep = true; + //} - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 5.0f); - ++m_fixtureCount; - y += deltaY; - } + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 5.0f); + ++m_fixtureCount; + y += deltaY; + } - x += deltaX; - } - } + x += deltaX; + } + } - m_createTime = timer.GetMilliseconds(); - } + m_createTime = timer.GetMilliseconds(); + } - void Step(Settings& settings) override - { - const b2ContactManager& cm = m_world->GetContactManager(); - int32 height = cm.m_broadPhase.GetTreeHeight(); - int32 leafCount = cm.m_broadPhase.GetProxyCount(); - int32 minimumNodeCount = 2 * leafCount - 1; - float minimumHeight = ceilf(logf(float(minimumNodeCount)) / logf(2.0f)); - DrawString(5, m_textLine, "dynamic tree height = %d, min = %d", height, int32(minimumHeight)); + void Step(Settings& settings) override + { + const b2ContactManager& cm = m_world->GetContactManager(); + int32 height = cm.m_broadPhase.GetTreeHeight(); + int32 leafCount = cm.m_broadPhase.GetProxyCount(); + int32 minimumNodeCount = 2 * leafCount - 1; + float minimumHeight = ceilf(logf(float(minimumNodeCount)) / logf(2.0f)); + DrawString(5, m_textLine, "dynamic tree height = %d, min = %d", height, int32(minimumHeight)); + - Test::Step(settings); + Test::Step(settings); - DrawString(5, m_textLine, "create time = %6.2f ms, fixture count = %d", m_createTime, m_fixtureCount); + DrawString(5, m_textLine, "create time = %6.2f ms, fixture count = %d", + m_createTime, m_fixtureCount); + - // b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree; + //b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree; - // if (m_stepCount == 400) - //{ - // tree->RebuildBottomUp(); - // } - } + //if (m_stepCount == 400) + //{ + // tree->RebuildBottomUp(); + //} + } - static Test* Create() { return new Tiles; } + static Test* Create() + { + return new Tiles; + } - int32 m_fixtureCount; - float m_createTime; + int32 m_fixtureCount; + float m_createTime; }; static int testIndex = RegisterTest("Benchmark", "Tiles", Tiles::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/time_of_impact.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/time_of_impact.cpp index f33b53476d..3face36e22 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/time_of_impact.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/time_of_impact.cpp @@ -26,85 +26,90 @@ class TimeOfImpact : public Test { public: - TimeOfImpact() - { - m_shapeA.SetAsBox(25.0f, 5.0f); - m_shapeB.SetAsBox(2.5f, 2.5f); - } + TimeOfImpact() + { + m_shapeA.SetAsBox(25.0f, 5.0f); + m_shapeB.SetAsBox(2.5f, 2.5f); + } - static Test* Create() { return new TimeOfImpact; } + static Test* Create() + { + return new TimeOfImpact; + } - void Step(Settings& settings) override - { - Test::Step(settings); + void Step(Settings& settings) override + { + Test::Step(settings); - b2Sweep sweepA; - sweepA.c0.Set(24.0f, -60.0f); - sweepA.a0 = 2.95f; - sweepA.c = sweepA.c0; - sweepA.a = sweepA.a0; - sweepA.localCenter.SetZero(); + b2Sweep sweepA; + sweepA.c0.Set(24.0f, -60.0f); + sweepA.a0 = 2.95f; + sweepA.c = sweepA.c0; + sweepA.a = sweepA.a0; + sweepA.localCenter.SetZero(); - b2Sweep sweepB; - sweepB.c0.Set(53.474274f, -50.252514f); - sweepB.a0 = 513.36676f; // - 162.0f * b2_pi; - sweepB.c.Set(54.595478f, -51.083473f); - sweepB.a = 513.62781f; // - 162.0f * b2_pi; - sweepB.localCenter.SetZero(); + b2Sweep sweepB; + sweepB.c0.Set(53.474274f, -50.252514f); + sweepB.a0 = 513.36676f; // - 162.0f * b2_pi; + sweepB.c.Set(54.595478f, -51.083473f); + sweepB.a = 513.62781f; // - 162.0f * b2_pi; + sweepB.localCenter.SetZero(); - // sweepB.a0 -= 300.0f * b2_pi; - // sweepB.a -= 300.0f * b2_pi; + //sweepB.a0 -= 300.0f * b2_pi; + //sweepB.a -= 300.0f * b2_pi; - b2TOIInput input; - input.proxyA.Set(&m_shapeA, 0); - input.proxyB.Set(&m_shapeB, 0); - input.sweepA = sweepA; - input.sweepB = sweepB; - input.tMax = 1.0f; + b2TOIInput input; + input.proxyA.Set(&m_shapeA, 0); + input.proxyB.Set(&m_shapeB, 0); + input.sweepA = sweepA; + input.sweepB = sweepB; + input.tMax = 1.0f; - b2TOIOutput output; + b2TOIOutput output; - b2TimeOfImpact(&output, &input); + b2TimeOfImpact(&output, &input); - DrawString(5, m_textLine, "toi = %g", output.t); + DrawString(5, m_textLine, "toi = %g", output.t); + - extern B2_API int32 b2_toiMaxIters, b2_toiMaxRootIters; - DrawString(5, m_textLine, "max toi iters = %d, max root iters = %d", b2_toiMaxIters, b2_toiMaxRootIters); + extern B2_API int32 b2_toiMaxIters, b2_toiMaxRootIters; + DrawString(5, m_textLine, "max toi iters = %d, max root iters = %d", b2_toiMaxIters, b2_toiMaxRootIters); + - b2Vec2 vertices[b2_maxPolygonVertices]; + b2Vec2 vertices[b2_maxPolygonVertices]; - b2Transform transformA; - sweepA.GetTransform(&transformA, 0.0f); - for (int32 i = 0; i < m_shapeA.m_count; ++i) - { - vertices[i] = b2Mul(transformA, m_shapeA.m_vertices[i]); - } - g_debugDraw.DrawPolygon(vertices, m_shapeA.m_count, b2Color(0.9f, 0.9f, 0.9f)); + b2Transform transformA; + sweepA.GetTransform(&transformA, 0.0f); + for (int32 i = 0; i < m_shapeA.m_count; ++i) + { + vertices[i] = b2Mul(transformA, m_shapeA.m_vertices[i]); + } + g_debugDraw.DrawPolygon(vertices, m_shapeA.m_count, b2Color(0.9f, 0.9f, 0.9f)); - b2Transform transformB; - sweepB.GetTransform(&transformB, 0.0f); + b2Transform transformB; + sweepB.GetTransform(&transformB, 0.0f); + + //b2Vec2 localPoint(2.0f, -0.1f); - // b2Vec2 localPoint(2.0f, -0.1f); + for (int32 i = 0; i < m_shapeB.m_count; ++i) + { + vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); + } + g_debugDraw.DrawPolygon(vertices, m_shapeB.m_count, b2Color(0.5f, 0.9f, 0.5f)); - for (int32 i = 0; i < m_shapeB.m_count; ++i) - { - vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); - } - g_debugDraw.DrawPolygon(vertices, m_shapeB.m_count, b2Color(0.5f, 0.9f, 0.5f)); + sweepB.GetTransform(&transformB, output.t); + for (int32 i = 0; i < m_shapeB.m_count; ++i) + { + vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); + } + g_debugDraw.DrawPolygon(vertices, m_shapeB.m_count, b2Color(0.5f, 0.7f, 0.9f)); - sweepB.GetTransform(&transformB, output.t); - for (int32 i = 0; i < m_shapeB.m_count; ++i) - { - vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); - } - g_debugDraw.DrawPolygon(vertices, m_shapeB.m_count, b2Color(0.5f, 0.7f, 0.9f)); - - sweepB.GetTransform(&transformB, 1.0f); - for (int32 i = 0; i < m_shapeB.m_count; ++i) - { - vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); - } - g_debugDraw.DrawPolygon(vertices, m_shapeB.m_count, b2Color(0.9f, 0.5f, 0.5f)); + sweepB.GetTransform(&transformB, 1.0f); + for (int32 i = 0; i < m_shapeB.m_count; ++i) + { + vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); + } + g_debugDraw.DrawPolygon(vertices, m_shapeB.m_count, b2Color(0.9f, 0.5f, 0.5f)); #if 0 for (float t = 0.0f; t < 1.0f; t += 0.1f) @@ -117,10 +122,10 @@ public: g_debugDraw.DrawPolygon(vertices, m_shapeB.m_count, b2Color(0.9f, 0.5f, 0.5f)); } #endif - } + } - b2PolygonShape m_shapeA; - b2PolygonShape m_shapeB; + b2PolygonShape m_shapeA; + b2PolygonShape m_shapeB; }; static int testIndex = RegisterTest("Collision", "Time of Impact", TimeOfImpact::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/tumbler.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/tumbler.cpp index e19ffae13f..f7972bc777 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/tumbler.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/tumbler.cpp @@ -25,74 +25,78 @@ class Tumbler : public Test { public: - enum - { - e_count = 800 - }; - Tumbler() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - } + enum + { + e_count = 800 + }; - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.allowSleep = false; - bd.position.Set(0.0f, 10.0f); - b2Body* body = m_world->CreateBody(&bd); + Tumbler() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + } - b2PolygonShape shape; - shape.SetAsBox(0.5f, 10.0f, b2Vec2(10.0f, 0.0f), 0.0); - body->CreateFixture(&shape, 5.0f); - shape.SetAsBox(0.5f, 10.0f, b2Vec2(-10.0f, 0.0f), 0.0); - body->CreateFixture(&shape, 5.0f); - shape.SetAsBox(10.0f, 0.5f, b2Vec2(0.0f, 10.0f), 0.0); - body->CreateFixture(&shape, 5.0f); - shape.SetAsBox(10.0f, 0.5f, b2Vec2(0.0f, -10.0f), 0.0); - body->CreateFixture(&shape, 5.0f); + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.allowSleep = false; + bd.position.Set(0.0f, 10.0f); + b2Body* body = m_world->CreateBody(&bd); - b2RevoluteJointDef jd; - jd.bodyA = ground; - jd.bodyB = body; - jd.localAnchorA.Set(0.0f, 10.0f); - jd.localAnchorB.Set(0.0f, 0.0f); - jd.referenceAngle = 0.0f; - jd.motorSpeed = 0.05f * b2_pi; - jd.maxMotorTorque = 1e8f; - jd.enableMotor = true; - m_joint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); - } + b2PolygonShape shape; + shape.SetAsBox(0.5f, 10.0f, b2Vec2( 10.0f, 0.0f), 0.0); + body->CreateFixture(&shape, 5.0f); + shape.SetAsBox(0.5f, 10.0f, b2Vec2(-10.0f, 0.0f), 0.0); + body->CreateFixture(&shape, 5.0f); + shape.SetAsBox(10.0f, 0.5f, b2Vec2(0.0f, 10.0f), 0.0); + body->CreateFixture(&shape, 5.0f); + shape.SetAsBox(10.0f, 0.5f, b2Vec2(0.0f, -10.0f), 0.0); + body->CreateFixture(&shape, 5.0f); - m_count = 0; - } + b2RevoluteJointDef jd; + jd.bodyA = ground; + jd.bodyB = body; + jd.localAnchorA.Set(0.0f, 10.0f); + jd.localAnchorB.Set(0.0f, 0.0f); + jd.referenceAngle = 0.0f; + jd.motorSpeed = 0.05f * b2_pi; + jd.maxMotorTorque = 1e8f; + jd.enableMotor = true; + m_joint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); + } - void Step(Settings& settings) override - { - Test::Step(settings); + m_count = 0; + } - if (m_count < e_count) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 10.0f); - b2Body* body = m_world->CreateBody(&bd); + void Step(Settings& settings) override + { + Test::Step(settings); - b2PolygonShape shape; - shape.SetAsBox(0.125f, 0.125f); - body->CreateFixture(&shape, 1.0f); + if (m_count < e_count) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 10.0f); + b2Body* body = m_world->CreateBody(&bd); - ++m_count; - } - } + b2PolygonShape shape; + shape.SetAsBox(0.125f, 0.125f); + body->CreateFixture(&shape, 1.0f); - static Test* Create() { return new Tumbler; } + ++m_count; + } + } - b2RevoluteJoint* m_joint; - int32 m_count; + static Test* Create() + { + return new Tumbler; + } + + b2RevoluteJoint* m_joint; + int32 m_count; }; static int testIndex = RegisterTest("Benchmark", "Tumbler", Tumbler::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/web.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/web.cpp index 658bc9f87b..fdacf8aa80 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/web.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/web.cpp @@ -26,190 +26,193 @@ class Web : public Test { public: - Web() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + Web() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); - b2BodyDef bd; - bd.type = b2_dynamicBody; + b2BodyDef bd; + bd.type = b2_dynamicBody; - bd.position.Set(-5.0f, 5.0f); - m_bodies[0] = m_world->CreateBody(&bd); - m_bodies[0]->CreateFixture(&shape, 5.0f); + bd.position.Set(-5.0f, 5.0f); + m_bodies[0] = m_world->CreateBody(&bd); + m_bodies[0]->CreateFixture(&shape, 5.0f); - bd.position.Set(5.0f, 5.0f); - m_bodies[1] = m_world->CreateBody(&bd); - m_bodies[1]->CreateFixture(&shape, 5.0f); + bd.position.Set(5.0f, 5.0f); + m_bodies[1] = m_world->CreateBody(&bd); + m_bodies[1]->CreateFixture(&shape, 5.0f); - bd.position.Set(5.0f, 15.0f); - m_bodies[2] = m_world->CreateBody(&bd); - m_bodies[2]->CreateFixture(&shape, 5.0f); + bd.position.Set(5.0f, 15.0f); + m_bodies[2] = m_world->CreateBody(&bd); + m_bodies[2]->CreateFixture(&shape, 5.0f); - bd.position.Set(-5.0f, 15.0f); - m_bodies[3] = m_world->CreateBody(&bd); - m_bodies[3]->CreateFixture(&shape, 5.0f); + bd.position.Set(-5.0f, 15.0f); + m_bodies[3] = m_world->CreateBody(&bd); + m_bodies[3]->CreateFixture(&shape, 5.0f); - b2DistanceJointDef jd; - b2Vec2 p1, p2, d; + b2DistanceJointDef jd; + b2Vec2 p1, p2, d; - float frequencyHz = 2.0f; - float dampingRatio = 0.0f; + float frequencyHz = 2.0f; + float dampingRatio = 0.0f; - jd.bodyA = ground; - jd.bodyB = m_bodies[0]; - jd.localAnchorA.Set(-10.0f, 0.0f); - jd.localAnchorB.Set(-0.5f, -0.5f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_joints[0] = m_world->CreateJoint(&jd); + jd.bodyA = ground; + jd.bodyB = m_bodies[0]; + jd.localAnchorA.Set(-10.0f, 0.0f); + jd.localAnchorB.Set(-0.5f, -0.5f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_joints[0] = m_world->CreateJoint(&jd); - jd.bodyA = ground; - jd.bodyB = m_bodies[1]; - jd.localAnchorA.Set(10.0f, 0.0f); - jd.localAnchorB.Set(0.5f, -0.5f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_joints[1] = m_world->CreateJoint(&jd); + jd.bodyA = ground; + jd.bodyB = m_bodies[1]; + jd.localAnchorA.Set(10.0f, 0.0f); + jd.localAnchorB.Set(0.5f, -0.5f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_joints[1] = m_world->CreateJoint(&jd); - jd.bodyA = ground; - jd.bodyB = m_bodies[2]; - jd.localAnchorA.Set(10.0f, 20.0f); - jd.localAnchorB.Set(0.5f, 0.5f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_joints[2] = m_world->CreateJoint(&jd); + jd.bodyA = ground; + jd.bodyB = m_bodies[2]; + jd.localAnchorA.Set(10.0f, 20.0f); + jd.localAnchorB.Set(0.5f, 0.5f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_joints[2] = m_world->CreateJoint(&jd); - jd.bodyA = ground; - jd.bodyB = m_bodies[3]; - jd.localAnchorA.Set(-10.0f, 20.0f); - jd.localAnchorB.Set(-0.5f, 0.5f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_joints[3] = m_world->CreateJoint(&jd); + jd.bodyA = ground; + jd.bodyB = m_bodies[3]; + jd.localAnchorA.Set(-10.0f, 20.0f); + jd.localAnchorB.Set(-0.5f, 0.5f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_joints[3] = m_world->CreateJoint(&jd); - jd.bodyA = m_bodies[0]; - jd.bodyB = m_bodies[1]; - jd.localAnchorA.Set(0.5f, 0.0f); - jd.localAnchorB.Set(-0.5f, 0.0f); - ; - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_joints[4] = m_world->CreateJoint(&jd); + jd.bodyA = m_bodies[0]; + jd.bodyB = m_bodies[1]; + jd.localAnchorA.Set(0.5f, 0.0f); + jd.localAnchorB.Set(-0.5f, 0.0f);; + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_joints[4] = m_world->CreateJoint(&jd); - jd.bodyA = m_bodies[1]; - jd.bodyB = m_bodies[2]; - jd.localAnchorA.Set(0.0f, 0.5f); - jd.localAnchorB.Set(0.0f, -0.5f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_joints[5] = m_world->CreateJoint(&jd); + jd.bodyA = m_bodies[1]; + jd.bodyB = m_bodies[2]; + jd.localAnchorA.Set(0.0f, 0.5f); + jd.localAnchorB.Set(0.0f, -0.5f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_joints[5] = m_world->CreateJoint(&jd); - jd.bodyA = m_bodies[2]; - jd.bodyB = m_bodies[3]; - jd.localAnchorA.Set(-0.5f, 0.0f); - jd.localAnchorB.Set(0.5f, 0.0f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_joints[6] = m_world->CreateJoint(&jd); + jd.bodyA = m_bodies[2]; + jd.bodyB = m_bodies[3]; + jd.localAnchorA.Set(-0.5f, 0.0f); + jd.localAnchorB.Set(0.5f, 0.0f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_joints[6] = m_world->CreateJoint(&jd); - jd.bodyA = m_bodies[3]; - jd.bodyB = m_bodies[0]; - jd.localAnchorA.Set(0.0f, -0.5f); - jd.localAnchorB.Set(0.0f, 0.5f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_joints[7] = m_world->CreateJoint(&jd); - } - } + jd.bodyA = m_bodies[3]; + jd.bodyB = m_bodies[0]; + jd.localAnchorA.Set(0.0f, -0.5f); + jd.localAnchorB.Set(0.0f, 0.5f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_joints[7] = m_world->CreateJoint(&jd); + } + } - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_B: - for (int32 i = 0; i < 4; ++i) - { - if (m_bodies[i]) - { - m_world->DestroyBody(m_bodies[i]); - m_bodies[i] = NULL; - break; - } - } - break; + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_B: + for (int32 i = 0; i < 4; ++i) + { + if (m_bodies[i]) + { + m_world->DestroyBody(m_bodies[i]); + m_bodies[i] = NULL; + break; + } + } + break; - case GLFW_KEY_J: - for (int32 i = 0; i < 8; ++i) - { - if (m_joints[i]) - { - m_world->DestroyJoint(m_joints[i]); - m_joints[i] = NULL; - break; - } - } - break; - } - } + case GLFW_KEY_J: + for (int32 i = 0; i < 8; ++i) + { + if (m_joints[i]) + { + m_world->DestroyJoint(m_joints[i]); + m_joints[i] = NULL; + break; + } + } + break; + } + } - void Step(Settings& settings) override - { - Test::Step(settings); - DrawString(5, m_textLine, "Press: (b) to delete a body, (j) to delete a joint"); - } + void Step(Settings& settings) override + { + Test::Step(settings); + DrawString(5, m_textLine, "Press: (b) to delete a body, (j) to delete a joint"); + + } - void JointDestroyed(b2Joint* joint) override - { - for (int32 i = 0; i < 8; ++i) - { - if (m_joints[i] == joint) - { - m_joints[i] = NULL; - break; - } - } - } + void JointDestroyed(b2Joint* joint) override + { + for (int32 i = 0; i < 8; ++i) + { + if (m_joints[i] == joint) + { + m_joints[i] = NULL; + break; + } + } + } - static Test* Create() { return new Web; } + static Test* Create() + { + return new Web; + } - b2Body* m_bodies[4]; - b2Joint* m_joints[8]; + b2Body* m_bodies[4]; + b2Joint* m_joints[8]; }; static int testIndex = RegisterTest("Examples", "Web", Web::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/wheel_joint.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/wheel_joint.cpp index 0388e75708..6be76ff262 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/wheel_joint.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/wheel_joint.cpp @@ -28,94 +28,99 @@ class WheelJoint : public Test { public: - WheelJoint() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + WheelJoint() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - m_enableLimit = true; - m_enableMotor = false; - m_motorSpeed = 10.0f; + m_enableLimit = true; + m_enableMotor = false; + m_motorSpeed = 10.0f; - { - b2CircleShape shape; - shape.m_radius = 2.0f; + { + b2CircleShape shape; + shape.m_radius = 2.0f; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 10.0f); - bd.allowSleep = false; - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 5.0f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 10.0f); + bd.allowSleep = false; + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 5.0f); - b2WheelJointDef jd; + b2WheelJointDef jd; - // Horizontal - jd.Initialize(ground, body, bd.position, b2Vec2(0.0f, 1.0f)); + // Horizontal + jd.Initialize(ground, body, bd.position, b2Vec2(0.0f, 1.0f)); - jd.motorSpeed = m_motorSpeed; - jd.maxMotorTorque = 10000.0f; - jd.enableMotor = m_enableMotor; - jd.lowerTranslation = -3.0f; - jd.upperTranslation = 3.0f; - jd.enableLimit = m_enableLimit; + jd.motorSpeed = m_motorSpeed; + jd.maxMotorTorque = 10000.0f; + jd.enableMotor = m_enableMotor; + jd.lowerTranslation = -3.0f; + jd.upperTranslation = 3.0f; + jd.enableLimit = m_enableLimit; - float hertz = 1.0f; - float dampingRatio = 0.7f; - b2LinearStiffness(jd.stiffness, jd.damping, hertz, dampingRatio, ground, body); + float hertz = 1.0f; + float dampingRatio = 0.7f; + b2LinearStiffness(jd.stiffness, jd.damping, hertz, dampingRatio, ground, body); - m_joint = (b2WheelJoint*)m_world->CreateJoint(&jd); - } - } + m_joint = (b2WheelJoint*)m_world->CreateJoint(&jd); + } + } - void Step(Settings& settings) override - { - Test::Step(settings); + void Step(Settings& settings) override + { + Test::Step(settings); - float torque = m_joint->GetMotorTorque(settings.m_hertz); - DrawString(5, m_textLine, "Motor Torque = %4.0f", torque); + float torque = m_joint->GetMotorTorque(settings.m_hertz); + DrawString(5, m_textLine, "Motor Torque = %4.0f", torque); + - b2Vec2 F = m_joint->GetReactionForce(settings.m_hertz); - DrawString(5, m_textLine, "Reaction Force = (%4.1f, %4.1f)", F.x, F.y); - } + b2Vec2 F = m_joint->GetReactionForce(settings.m_hertz); + DrawString(5, m_textLine, "Reaction Force = (%4.1f, %4.1f)", F.x, F.y); + + } - void UpdateUI() override - { - // ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); - ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); - ImGui::Begin("Joint Controls", nullptr, ImGuiWindowFlags_NoResize); + void UpdateUI() override + { + //ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); + ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); + ImGui::Begin("Joint Controls", nullptr, ImGuiWindowFlags_NoResize); - if (ImGui::Checkbox("Limit", &m_enableLimit)) - { - m_joint->EnableLimit(m_enableLimit); - } + if (ImGui::Checkbox("Limit", &m_enableLimit)) + { + m_joint->EnableLimit(m_enableLimit); + } - if (ImGui::Checkbox("Motor", &m_enableMotor)) - { - m_joint->EnableMotor(m_enableMotor); - } + if (ImGui::Checkbox("Motor", &m_enableMotor)) + { + m_joint->EnableMotor(m_enableMotor); + } - if (ImGui::SliderFloat("Speed", &m_motorSpeed, -100.0f, 100.0f, "%.0f")) - { - m_joint->SetMotorSpeed(m_motorSpeed); - } + if (ImGui::SliderFloat("Speed", &m_motorSpeed, -100.0f, 100.0f, "%.0f")) + { + m_joint->SetMotorSpeed(m_motorSpeed); + } - ImGui::End(); - } + ImGui::End(); + } - static Test* Create() { return new WheelJoint; } + static Test* Create() + { + return new WheelJoint; + } - b2WheelJoint* m_joint; - float m_motorSpeed; - bool m_enableMotor; - bool m_enableLimit; + b2WheelJoint* m_joint; + float m_motorSpeed; + bool m_enableMotor; + bool m_enableLimit; }; static int testIndex = RegisterTest("Joints", "Wheel", WheelJoint::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/wrecking_ball.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/wrecking_ball.cpp index 4ea57671db..c1722a61cb 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/wrecking_ball.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/wrecking_ball.cpp @@ -34,128 +34,132 @@ class WreckingBall : public Test { public: - WreckingBall() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + WreckingBall() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.125f); + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.125f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.friction = 0.2f; - fd.filter.categoryBits = 0x0001; - fd.filter.maskBits = 0xFFFF & ~0x0002; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.friction = 0.2f; + fd.filter.categoryBits = 0x0001; + fd.filter.maskBits = 0xFFFF & ~0x0002; - b2RevoluteJointDef jd; - jd.collideConnected = false; + b2RevoluteJointDef jd; + jd.collideConnected = false; - const int32 N = 10; - const float y = 15.0f; - m_distanceJointDef.localAnchorA.Set(0.0f, y); + const int32 N = 10; + const float y = 15.0f; + m_distanceJointDef.localAnchorA.Set(0.0f, y); - b2Body* prevBody = ground; - for (int32 i = 0; i < N; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.5f + 1.0f * i, y); - if (i == N - 1) - { - bd.position.Set(1.0f * i, y); - bd.angularDamping = 0.4f; - } + b2Body* prevBody = ground; + for (int32 i = 0; i < N; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.5f + 1.0f * i, y); + if (i == N - 1) + { + bd.position.Set(1.0f * i, y); + bd.angularDamping = 0.4f; + } - b2Body* body = m_world->CreateBody(&bd); + b2Body* body = m_world->CreateBody(&bd); - if (i == N - 1) - { - b2CircleShape circleShape; - circleShape.m_radius = 1.5f; - b2FixtureDef sfd; - sfd.shape = &circleShape; - sfd.density = 100.0f; - sfd.filter.categoryBits = 0x0002; - body->CreateFixture(&sfd); - } - else - { - body->CreateFixture(&fd); - } + if (i == N - 1) + { + b2CircleShape circleShape; + circleShape.m_radius = 1.5f; + b2FixtureDef sfd; + sfd.shape = &circleShape; + sfd.density = 100.0f; + sfd.filter.categoryBits = 0x0002; + body->CreateFixture(&sfd); + } + else + { + body->CreateFixture(&fd); + } - b2Vec2 anchor(float(i), y); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); + b2Vec2 anchor(float(i), y); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); - prevBody = body; - } + prevBody = body; + } - m_distanceJointDef.localAnchorB.SetZero(); + m_distanceJointDef.localAnchorB.SetZero(); - float extraLength = 0.01f; - m_distanceJointDef.minLength = 0.0f; - m_distanceJointDef.maxLength = N - 1.0f + extraLength; - m_distanceJointDef.bodyB = prevBody; - } + float extraLength = 0.01f; + m_distanceJointDef.minLength = 0.0f; + m_distanceJointDef.maxLength = N - 1.0f + extraLength; + m_distanceJointDef.bodyB = prevBody; + } - { - m_distanceJointDef.bodyA = ground; - m_distanceJoint = m_world->CreateJoint(&m_distanceJointDef); - m_stabilize = true; - } - } + { + m_distanceJointDef.bodyA = ground; + m_distanceJoint = m_world->CreateJoint(&m_distanceJointDef); + m_stabilize = true; + } + } - void UpdateUI() override - { - // ImGui::SetNextWindowPos(ImVec2(Test::g_debugDraw.debugNodeOffset.x, 100.0f)); - ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); - ImGui::Begin("Wrecking Ball Controls", nullptr, ImGuiWindowFlags_NoResize); + void UpdateUI() override + { +// ImGui::SetNextWindowPos(ImVec2(Test::g_debugDraw.debugNodeOffset.x, 100.0f)); + ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); + ImGui::Begin("Wrecking Ball Controls", nullptr, ImGuiWindowFlags_NoResize); - if (ImGui::Checkbox("Stabilize", &m_stabilize)) - { - if (m_stabilize == true && m_distanceJoint == nullptr) - { - m_distanceJoint = m_world->CreateJoint(&m_distanceJointDef); - } - else if (m_stabilize == false && m_distanceJoint != nullptr) - { - m_world->DestroyJoint(m_distanceJoint); - m_distanceJoint = nullptr; - } - } + if (ImGui::Checkbox("Stabilize", &m_stabilize)) + { + if (m_stabilize == true && m_distanceJoint == nullptr) + { + m_distanceJoint = m_world->CreateJoint(&m_distanceJointDef); + } + else if (m_stabilize == false && m_distanceJoint != nullptr) + { + m_world->DestroyJoint(m_distanceJoint); + m_distanceJoint = nullptr; + } + } - ImGui::End(); - } + ImGui::End(); + } - void Step(Settings& settings) override - { - Test::Step(settings); + void Step(Settings& settings) override + { + Test::Step(settings); - if (m_distanceJoint) - { - DrawString(5, m_textLine, "Distance Joint ON"); - } - else - { - DrawString(5, m_textLine, "Distance Joint OFF"); - } - } + if (m_distanceJoint) + { + DrawString(5, m_textLine, "Distance Joint ON"); + } + else + { + DrawString(5, m_textLine, "Distance Joint OFF"); + } + + } - static Test* Create() { return new WreckingBall; } + static Test* Create() + { + return new WreckingBall; + } - b2DistanceJointDef m_distanceJointDef; - b2Joint* m_distanceJoint; - bool m_stabilize; + b2DistanceJointDef m_distanceJointDef; + b2Joint* m_distanceJoint; + bool m_stabilize; }; static int testIndex = RegisterTest("Examples", "Wrecking Ball", WreckingBall::Create); diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-1159.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-1159.cpp index 34e10a0244..217b173caa 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-1159.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-1159.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -38,21 +38,22 @@ bool Bug1159Layer::init() auto sprite_a = LayerColor::create(Color4B(255, 0, 0, 255), 700, 700); sprite_a->setAnchorPoint(Vec2(0.5f, 0.5f)); sprite_a->setIgnoreAnchorPointForPosition(false); - sprite_a->setPosition(0.0f, s.height / 2); + sprite_a->setPosition(0.0f, s.height/2); addChild(sprite_a); - sprite_a->runAction(RepeatForever::create(Sequence::create(MoveTo::create(1.0f, Vec2(1024.0f, 384.0f)), - MoveTo::create(1.0f, Vec2(0.0f, 384.0f)), nullptr))); + sprite_a->runAction(RepeatForever::create(Sequence::create( + MoveTo::create(1.0f, Vec2(1024.0f, 384.0f)), + MoveTo::create(1.0f, Vec2(0.0f, 384.0f)), + nullptr))); auto sprite_b = LayerColor::create(Color4B(0, 0, 255, 255), 400, 400); sprite_b->setAnchorPoint(Vec2(0.5f, 0.5f)); sprite_b->setIgnoreAnchorPointForPosition(false); - sprite_b->setPosition(s.width / 2, s.height / 2); + sprite_b->setPosition(s.width/2, s.height/2); addChild(sprite_b); - auto label = MenuItemLabel::create(Label::createWithSystemFont("Flip Me", "Helvetica", 24), - CC_CALLBACK_1(Bug1159Layer::callBack, this)); - auto menu = Menu::create(label, nullptr); + auto label = MenuItemLabel::create(Label::createWithSystemFont("Flip Me", "Helvetica", 24), CC_CALLBACK_1(Bug1159Layer::callBack, this) ); + auto menu = Menu::create(label, nullptr); menu->setPosition(s.width - 200.0f, 50.0f); addChild(menu); diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-1159.h b/tests/cpp-tests/Classes/BugsTest/Bug-1159.h index 1db64c6c2d..1a0e5a6a49 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-1159.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-1159.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -32,11 +32,11 @@ class Bug1159Layer : public BugsTestBase public: virtual bool init() override; virtual void onExit() override; - virtual std::string title() const override { return "Bug1159"; } + virtual std::string title() const override { return "Bug1159";} void callBack(cocos2d::Ref* sender); CREATE_FUNC(Bug1159Layer); }; -#endif // __BUG_1159_H__ +#endif // __BUG_1159_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-1174.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-1174.cpp index 7b35bba3ac..0680e587ab 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-1174.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-1174.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -31,23 +31,23 @@ USING_NS_CC; -int check_for_error(Vec2 p1, Vec2 p2, Vec2 p3, Vec2 p4, float s, float t); +int check_for_error( Vec2 p1, Vec2 p2, Vec2 p3, Vec2 p4, float s, float t ); -int check_for_error(Vec2 p1, Vec2 p2, Vec2 p3, Vec2 p4, float s, float t) +int check_for_error( Vec2 p1, Vec2 p2, Vec2 p3, Vec2 p4, float s, float t ) { // the hit point is p3 + t * (p4 - p3); // the hit point also is p1 + s * (p2 - p1); - - auto p4_p3 = p4 - p3; - auto p4_p3_t = p4_p3 * t; + + auto p4_p3 = p4 - p3; + auto p4_p3_t = p4_p3 * t; auto hitPoint1 = p3 + p4_p3_t; - - auto p2_p1 = p2 - p1; - auto p2_p1_s = p2_p1 * s; + + auto p2_p1 = p2 - p1; + auto p2_p1_s = p2_p1 * s; auto hitPoint2 = p1 + p2_p1_s; - + // Since float has rounding errors, only check if diff is < 0.05 - if ((fabs(hitPoint1.x - hitPoint2.x) > 0.1f) || (fabs(hitPoint1.y - hitPoint2.y) > 0.1f)) + if( (fabs( hitPoint1.x - hitPoint2.x) > 0.1f) || ( fabs(hitPoint1.y - hitPoint2.y) > 0.1f) ) { log("ERROR: (%f,%f) != (%f,%f)", hitPoint1.x, hitPoint1.y, hitPoint2.x, hitPoint2.y); return 1; @@ -60,20 +60,20 @@ bool Bug1174Layer::init() { if (BugsTestBase::init()) { - // // seed - // std::srand(0); - - Vec2 A, B, C, D, p1, p2, p3, p4; - float s, t; - - int err = 0; - int ok = 0; +// // seed +// std::srand(0); + Vec2 A,B,C,D,p1,p2,p3,p4; + float s,t; + + int err=0; + int ok=0; + // // Test 1. // log("Test1 - Start"); - for (int i = 0; i < 10000; i++) + for( int i=0; i < 10000; i++) { // A | b // ----- @@ -92,20 +92,19 @@ bool Bug1174Layer::init() // c | d float bx = CCRANDOM_0_1() * 5000; float by = CCRANDOM_0_1() * 5000; - + // a | b // ----- // C | d float cx = CCRANDOM_0_1() * -5000; float cy = CCRANDOM_0_1() * -5000; - - A = Vec2(ax, ay); - B = Vec2(bx, by); - C = Vec2(cx, cy); - D = Vec2(dx, dy); - if (Vec2::isLineIntersect(A, D, B, C, &s, &t)) - { - if (check_for_error(A, D, B, C, s, t)) + + A = Vec2(ax,ay); + B = Vec2(bx,by); + C = Vec2(cx,cy); + D = Vec2(dx,dy); + if( Vec2::isLineIntersect( A, D, B, C, &s, &t) ) { + if( check_for_error(A, D, B, C, s, t) ) err++; else ok++; @@ -117,68 +116,69 @@ bool Bug1174Layer::init() // Test 2. // log("Test2 - Start"); - - p1 = Vec2(220, 480); - p2 = Vec2(304, 325); - p3 = Vec2(264, 416); - p4 = Vec2(186, 416); - s = 0.0f; - t = 0.0f; - if (Vec2::isLineIntersect(p1, p2, p3, p4, &s, &t)) - check_for_error(p1, p2, p3, p4, s, t); + + p1 = Vec2(220,480); + p2 = Vec2(304,325); + p3 = Vec2(264,416); + p4 = Vec2(186,416); + s = 0.0f; + t = 0.0f; + if( Vec2::isLineIntersect(p1, p2, p3, p4, &s, &t) ) + check_for_error(p1, p2, p3, p4, s,t ); log("Test2 - End"); + // // Test 3 // log("Test3 - Start"); - - ok = 0; - err = 0; - for (int i = 0; i < 10000; i++) + + ok=0; + err=0; + for( int i=0;i<10000;i++) { // A | b // ----- // c | d float ax = CCRANDOM_0_1() * -500; float ay = CCRANDOM_0_1() * 500; - p1 = Vec2(ax, ay); - + p1 = Vec2(ax,ay); + // a | b // ----- // c | D float dx = CCRANDOM_0_1() * 500; float dy = CCRANDOM_0_1() * -500; - p2 = Vec2(dx, dy); - + p2 = Vec2(dx,dy); + + ////// - - float y = ay - ((ay - dy) / 2.0f); + + float y = ay - ((ay - dy) /2.0f); // a | b // ----- // C | d float cx = CCRANDOM_0_1() * -500; - p3 = Vec2(cx, y); - + p3 = Vec2(cx,y); + // a | B // ----- // c | d float bx = CCRANDOM_0_1() * 500; - p4 = Vec2(bx, y); + p4 = Vec2(bx,y); s = 0.0f; t = 0.0f; - if (Vec2::isLineIntersect(p1, p2, p3, p4, &s, &t)) - { - if (check_for_error(p1, p2, p3, p4, s, t)) + if( Vec2::isLineIntersect(p1, p2, p3, p4, &s, &t) ) { + if( check_for_error(p1, p2, p3, p4, s,t ) ) err++; else ok++; } } - + log("Test3 - End. OK=%i, err=%i", ok, err); return true; } diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-1174.h b/tests/cpp-tests/Classes/BugsTest/Bug-1174.h index d813835e47..97cdf52919 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-1174.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-1174.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,7 +33,7 @@ public: CREATE_FUNC(Bug1174Layer); virtual bool init() override; - virtual std::string title() const override { return "Bug1174"; } + virtual std::string title() const override { return "Bug1174";} }; -#endif // __BUG_1174_H__ +#endif // __BUG_1174_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-12847.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-12847.cpp index f3cae71e59..0d6ffb0af4 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-12847.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-12847.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -45,44 +45,45 @@ Bug12847Layer::~Bug12847Layer() Director::getInstance()->setProjection(_projection); } + bool Bug12847Layer::init() { if (BugsTestBase::init()) { Director::getInstance()->setProjection(Director::Projection::_2D); auto _visibleSize = Director::getInstance()->getVisibleSize(); - - // Create with Sprite + + //Create with Sprite { sprite1 = Sprite::create("Images/bug12847_sprite.png"); sprite1->getTexture()->setAliasTexParameters(); - sprite1->setPosition(Vec2(_visibleSize.width / 3, 50.0f)); + sprite1->setPosition(Vec2(_visibleSize.width/3, 50.0f)); this->addChild(sprite1, 1); - + sprite2 = Sprite::create("Images/bug12847_sprite.png"); sprite2->getTexture()->setAliasTexParameters(); sprite2->setPosition(sprite1->getPosition() + Vec2(0.0f, sprite1->getContentSize().height)); this->addChild(sprite2, 1); } - // Create with SpriteFrame + //Create with SpriteFrame { SpriteFrameCache::getInstance()->addSpriteFramesWithFile("Images/bug12847_spriteframe.plist"); - + sprite3 = Sprite::createWithSpriteFrameName("bug12847_sprite2.png"); sprite3->getTexture()->setAliasTexParameters(); - sprite3->setPosition(Vec2(_visibleSize.width * 2 / 3, 50.0f)); + sprite3->setPosition(Vec2(_visibleSize.width * 2/3, 50.0f)); this->addChild(sprite3, 1); - + sprite4 = Sprite::createWithSpriteFrameName("bug12847_sprite2.png"); sprite4->getTexture()->setAliasTexParameters(); sprite4->setPosition(sprite3->getPosition() + Vec2(0.0f, sprite3->getContentSize().height)); this->addChild(sprite4, 1); } - + this->scheduleUpdate(); return true; } - + return false; } diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-12847.h b/tests/cpp-tests/Classes/BugsTest/Bug-12847.h index 864b26b339..c34ed2e072 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-12847.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-12847.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -31,19 +31,20 @@ class Bug12847Layer : public BugsTestBase { public: CREATE_FUNC(Bug12847Layer); - + Bug12847Layer(); virtual ~Bug12847Layer(); virtual bool init() override; - virtual std::string title() const override { return "Bug1287"; } - + virtual std::string title() const override { return "Bug1287";} + protected: virtual void update(float dt) override; virtual void onEnter() override; virtual void onExit() override; - + private: + cocos2d::Sprite* sprite1; cocos2d::Sprite* sprite2; cocos2d::Sprite* sprite3; diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-14327.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-14327.cpp index 94723fdf46..a5f56f5751 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-14327.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-14327.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -41,9 +41,9 @@ bool Bug14327Layer::init() { if (BugsTestBase::init()) { - auto glview = Director::getInstance()->getOpenGLView(); + auto glview = Director::getInstance()->getOpenGLView(); auto visibleOrigin = glview->getVisibleOrigin(); - auto visibleSize = glview->getVisibleSize(); + auto visibleSize = glview->getVisibleSize(); auto pBg = Sprite::create("Images/HelloWorld.png"); pBg->setPosition(Vec2(visibleOrigin.x + visibleSize.width / 2, visibleOrigin.y + visibleSize.height / 2)); @@ -52,10 +52,10 @@ bool Bug14327Layer::init() _removeTime = time(nullptr) + 20; _TTFShowTime = Label::createWithSystemFont("Edit control will be removed after 00:20!", "Arial", 20); - _TTFShowTime->setPosition( - Vec2(visibleOrigin.x + visibleSize.width / 2, visibleOrigin.y + visibleSize.height - 60)); + _TTFShowTime->setPosition(Vec2(visibleOrigin.x + visibleSize.width / 2, visibleOrigin.y + visibleSize.height - 60)); this->addChild(_TTFShowTime); + auto editBoxSize = Size(visibleSize.width - 100, visibleSize.height * 0.1); std::string pNormalSprite = "extensions/green_edit.png"; @@ -97,15 +97,14 @@ void Bug14327Layer::editBoxEditingDidBegin(cocos2d::ui::EditBox* editBox) log("editBox %p DidBegin !", editBox); } -void Bug14327Layer::editBoxEditingDidEndWithAction(cocos2d::ui::EditBox* editBox, - cocos2d::ui::EditBoxDelegate::EditBoxEndAction EditBoxEndAction) +void Bug14327Layer::editBoxEditingDidEndWithAction(cocos2d::ui::EditBox* editBox, cocos2d::ui::EditBoxDelegate::EditBoxEndAction EditBoxEndAction) { log("editBox %p DidEnd !", editBox); } -void Bug14327Layer::editBoxTextChanged(cocos2d::ui::EditBox* editBox, std::string_view text) +void Bug14327Layer::editBoxTextChanged(cocos2d::ui::EditBox* editBox, const std::string& text) { - log("editBox %p TextChanged, text: %s ", editBox, text.data()); + log("editBox %p TextChanged, text: %s ", editBox, text.c_str()); } void Bug14327Layer::editBoxReturn(ui::EditBox* editBox) diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-14327.h b/tests/cpp-tests/Classes/BugsTest/Bug-14327.h index 96e1cf157a..db1b6e3bfa 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-14327.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-14327.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,9 +27,10 @@ #include "BugsTest.h" + #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) -# include "ui/UIEditBox/UIEditBox.h" +#include "ui/UIEditBox/UIEditBox.h" class Bug14327Layer : public BugsTestBase, public cocos2d::ui::EditBoxDelegate { @@ -37,13 +38,11 @@ public: CREATE_FUNC(Bug14327Layer); virtual bool init() override; - virtual std::string title() const override { return "Bug14327"; } + virtual std::string title() const override { return "Bug14327";} virtual void editBoxEditingDidBegin(cocos2d::ui::EditBox* editBox) override; - virtual void editBoxEditingDidEndWithAction( - cocos2d::ui::EditBox* editBox, - cocos2d::ui::EditBoxDelegate::EditBoxEndAction EditBoxEndAction) override; - virtual void editBoxTextChanged(cocos2d::ui::EditBox* editBox, std::string_view text) override; + virtual void editBoxEditingDidEndWithAction(cocos2d::ui::EditBox* editBox, cocos2d::ui::EditBoxDelegate::EditBoxEndAction EditBoxEndAction) override; + virtual void editBoxTextChanged(cocos2d::ui::EditBox* editBox, const std::string& text) override; virtual void editBoxReturn(cocos2d::ui::EditBox* editBox) override; protected: @@ -51,7 +50,7 @@ protected: private: time_t _removeTime; - cocos2d::Label* _TTFShowTime; + cocos2d::Label *_TTFShowTime; cocos2d::ui::EditBox* _edit; }; diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-15594.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-15594.cpp index 95c3a4011a..c53821668a 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-15594.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-15594.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,23 +34,24 @@ #include "Bug-15594.h" + USING_NS_CC; bool Bug15594Layer::init() { - if (BugsTestBase::init()) - { + if (BugsTestBase::init()) + { auto sprite3d = Sprite3D::create("Images/bugs/bug15594.c3t", "Images/bugs/bug15594.jpg"); addChild(sprite3d); auto size = Director::getInstance()->getWinSize(); - sprite3d->setPosition(size / 2); + sprite3d->setPosition(size/2); auto animation = Animation3D::create("Images/bugs/bug15594.c3t"); - auto animate = Animate3D::create(animation); - auto repeat = RepeatForever::create(animate); + auto animate = Animate3D::create(animation); + auto repeat = RepeatForever::create(animate); sprite3d->runAction(repeat); - return true; - } + return true; + } return false; } diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-15594.h b/tests/cpp-tests/Classes/BugsTest/Bug-15594.h index d55aa26c55..abd4abde46 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-15594.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-15594.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,7 +34,7 @@ public: CREATE_FUNC(Bug15594Layer); virtual bool init() override; - virtual std::string title() const override { return "Bug15594"; } + virtual std::string title() const override { return "Bug15594";} }; #endif /* defined(__cocos2d_tests__Bug_15594__) */ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-15776.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-15776.cpp index 5a3d08c069..1ea56ddd9e 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-15776.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-15776.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -32,8 +32,10 @@ #include "Bug-15776.h" + USING_NS_CC; + // // IMPORTANT: // THIS TEST WILL CRASH ON TextureCache::addImage() @@ -44,7 +46,7 @@ bool Bug15776Layer::init() { if (BugsTestBase::init()) { - cocos2d::Image* cocos2dxImage = new cocos2d::Image(); + cocos2d::Image *cocos2dxImage = new cocos2d::Image(); cocos2dxImage->initWithImageData(nullptr, 0, false); // should not crash. invalid cocos2dImage auto texture2d = Director::getInstance()->getTextureCache()->addImage(cocos2dxImage, "unused"); diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-15776.h b/tests/cpp-tests/Classes/BugsTest/Bug-15776.h index 3485f8bcf5..97d21f907c 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-15776.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-15776.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -46,4 +46,5 @@ public: virtual std::string subtitle() const override; }; + #endif /* Bug_15776_hpp */ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-350.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-350.cpp index f1e4ac21c2..73e500f958 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-350.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-350.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -23,7 +23,7 @@ ****************************************************************************/ // -// Bug-350 +// Bug-350 // http://code.google.com/p/cocos2d-iphone/issues/detail?id=350 // @@ -35,9 +35,9 @@ bool Bug350Layer::init() { if (BugsTestBase::init()) { - auto size = Director::getInstance()->getWinSize(); + auto size = Director::getInstance()->getWinSize(); auto background = Sprite::create("Hello.png"); - background->setPosition(size.width / 2, size.height / 2); + background->setPosition(size.width/2, size.height/2); addChild(background); return true; } diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-350.h b/tests/cpp-tests/Classes/BugsTest/Bug-350.h index 8f1d5d44a2..4e8982f70e 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-350.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-350.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,7 +33,7 @@ public: CREATE_FUNC(Bug350Layer); virtual bool init() override; - virtual std::string title() const override { return "Bug350"; } + virtual std::string title() const override { return "Bug350";} }; -#endif // __BUG_350_H__ +#endif // __BUG_350_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-422.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-422.cpp index 542ba9a8f4..28b1d56776 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-422.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-422.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -52,21 +52,21 @@ void Bug422Layer::reset() // The menu will be removed, but the instance will be alive // and then a new node will be allocated occupying the memory. // => CRASH BOOM BANG - auto node = getChildByTag(localtag - 1); + auto node = getChildByTag(localtag-1); log("Menu: %p", node); removeChild(node, true); - // [self removeChildByTag:localtag-1 cleanup:NO]; +// [self removeChildByTag:localtag-1 cleanup:NO]; - auto item1 = MenuItemFont::create("One", CC_CALLBACK_1(Bug422Layer::menuCallback, this)); + auto item1 = MenuItemFont::create("One", CC_CALLBACK_1(Bug422Layer::menuCallback, this) ); log("MenuItemFont: %p", item1); - MenuItem* item2 = MenuItemFont::create("Two", CC_CALLBACK_1(Bug422Layer::menuCallback, this)); - auto menu = Menu::create(item1, item2, nullptr); + MenuItem *item2 = MenuItemFont::create("Two", CC_CALLBACK_1(Bug422Layer::menuCallback, this) ); + auto menu = Menu::create(item1, item2, nullptr); menu->alignItemsVertically(); float x = CCRANDOM_0_1() * 50; float y = CCRANDOM_0_1() * 50; - menu->setPosition(menu->getPosition() + Vec2(x, y)); - addChild(menu, 0, localtag); + menu->setPosition(menu->getPosition() + Vec2(x,y)); + addChild(menu, 0, localtag); //[self check:self]; } @@ -74,8 +74,7 @@ void Bug422Layer::reset() void Bug422Layer::check(Node* t) { auto& children = t->getChildren(); - for (const auto& child : children) - { + for(const auto &child : children) { log("%p, rc: %d", child, child->getReferenceCount()); check(child); } diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-422.h b/tests/cpp-tests/Classes/BugsTest/Bug-422.h index dd229fffbf..21c39580ad 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-422.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-422.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,11 +33,11 @@ public: CREATE_FUNC(Bug422Layer); virtual bool init() override; - virtual std::string title() const override { return "Bug422"; } + virtual std::string title() const override { return "Bug422";} void reset(); void check(Node* target); void menuCallback(cocos2d::Ref* sender); }; -#endif // __BUG_422_H__ +#endif // __BUG_422_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-458/Bug-458.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-458/Bug-458.cpp index eae96810a9..4b5db044ae 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-458/Bug-458.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-458/Bug-458.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,27 +34,27 @@ USING_NS_CC; bool Bug458Layer::init() { - if (BugsTestBase::init()) + if(BugsTestBase::init()) { // ask director the the window size auto size = Director::getInstance()->getWinSize(); - auto question = new QuestionContainerSprite(); + auto question = new QuestionContainerSprite(); auto question2 = new QuestionContainerSprite(); question->init(); question2->init(); - // [question setContentSize:CGSizeMake(50,50)]; - // [question2 setContentSize:CGSizeMake(50,50)]; - - auto sprite = MenuItemSprite::create(question2, question, CC_CALLBACK_1(Bug458Layer::selectAnswer, this)); - auto layer = LayerColor::create(Color4B(0, 0, 255, 255), 100, 100); +// [question setContentSize:CGSizeMake(50,50)]; +// [question2 setContentSize:CGSizeMake(50,50)]; + + auto sprite = MenuItemSprite::create(question2, question, CC_CALLBACK_1(Bug458Layer::selectAnswer, this) ); + auto layer = LayerColor::create(Color4B(0,0,255,255), 100, 100); question->release(); question2->release(); - auto layer2 = LayerColor::create(Color4B(255, 0, 0, 255), 100, 100); - auto sprite2 = MenuItemSprite::create(layer, layer2, CC_CALLBACK_1(Bug458Layer::selectAnswer, this)); - auto menu = Menu::create(sprite, sprite2, nullptr); + auto layer2 = LayerColor::create(Color4B(255,0,0,255), 100, 100); + auto sprite2 = MenuItemSprite::create(layer, layer2, CC_CALLBACK_1(Bug458Layer::selectAnswer, this) ); + auto menu = Menu::create(sprite, sprite2, nullptr); menu->alignItemsVerticallyWithPadding(100); menu->setPosition(size.width / 2, size.height / 2); diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-458/Bug-458.h b/tests/cpp-tests/Classes/BugsTest/Bug-458/Bug-458.h index dc033564ec..59a2509840 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-458/Bug-458.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-458/Bug-458.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -36,4 +36,4 @@ public: void selectAnswer(cocos2d::Ref* sender); }; -#endif // __BUG_458_H__ +#endif // __BUG_458_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp index e65c5ee32b..b5f94bea11 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -32,24 +32,24 @@ bool QuestionContainerSprite::init() { if (Sprite::init()) { - // Add label + //Add label auto label = Label::createWithTTF("Answer 1", "fonts/arial.ttf", 12); label->setTag(100); - // Add the background - auto size = Director::getInstance()->getWinSize(); + //Add the background + auto size = Director::getInstance()->getWinSize(); auto corner = Sprite::create("Images/bugs/corner.png"); - int width = size.width * 0.9f - (corner->getContentSize().width * 2); - int height = size.height * 0.15f - (corner->getContentSize().height * 2); + int width = size.width * 0.9f - (corner->getContentSize().width * 2); + int height = size.height * 0.15f - (corner->getContentSize().height * 2); auto layer = LayerColor::create(Color4B(255, 255, 255, 255 * .75), width, height); layer->setPosition(Vec2(-width / 2, -height / 2)); - // First button is blue, - // Second is red - // Used for testing - change later + //First button is blue, + //Second is red + //Used for testing - change later static int a = 0; - + if (a == 0) label->setColor(Color3B::BLUE); else @@ -60,8 +60,7 @@ bool QuestionContainerSprite::init() a++; addChild(layer); - corner->setPosition(Vec2(-(width / 2 + corner->getContentSize().width / 2), - -(height / 2 + corner->getContentSize().height / 2))); + corner->setPosition(Vec2(-(width / 2 + corner->getContentSize().width / 2), -(height / 2 + corner->getContentSize().height / 2))); addChild(corner); auto corner2 = Sprite::create("Images/bugs/corner.png"); @@ -82,29 +81,25 @@ bool QuestionContainerSprite::init() auto edge = Sprite::create("Images/bugs/edge.png"); edge->setScaleX(width); - edge->setPosition(Vec2(corner->getPosition().x + (corner->getContentSize().width / 2) + (width / 2), - corner->getPosition().y)); + edge->setPosition(Vec2(corner->getPosition().x + (corner->getContentSize().width / 2) + (width / 2), corner->getPosition().y)); addChild(edge); - + auto edge2 = Sprite::create("Images/bugs/edge.png"); edge2->setScaleX(width); - edge2->setPosition(Vec2(corner->getPosition().x + (corner->getContentSize().width / 2) + (width / 2), - -corner->getPosition().y)); + edge2->setPosition(Vec2(corner->getPosition().x + (corner->getContentSize().width / 2) + (width / 2), -corner->getPosition().y)); edge2->setFlippedY(true); addChild(edge2); auto edge3 = Sprite::create("Images/bugs/edge.png"); edge3->setRotation(90); edge3->setScaleX(height); - edge3->setPosition(Vec2(corner->getPosition().x, - corner->getPosition().y + (corner->getContentSize().height / 2) + (height / 2))); + edge3->setPosition(Vec2(corner->getPosition().x, corner->getPosition().y + (corner->getContentSize().height / 2) + (height / 2))); addChild(edge3); auto edge4 = Sprite::create("Images/bugs/edge.png"); edge4->setRotation(270); edge4->setScaleX(height); - edge4->setPosition(Vec2(-corner->getPosition().x, - corner->getPosition().y + (corner->getContentSize().height / 2) + (height / 2))); + edge4->setPosition(Vec2(-corner->getPosition().x, corner->getPosition().y + (corner->getContentSize().height / 2) + (height / 2))); addChild(edge4); addChild(label); diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-458/QuestionContainerSprite.h b/tests/cpp-tests/Classes/BugsTest/Bug-458/QuestionContainerSprite.h index efc407f95a..6e31c77448 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-458/QuestionContainerSprite.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-458/QuestionContainerSprite.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,10 +27,10 @@ #include "cocos2d.h" -class QuestionContainerSprite : public cocos2d::Sprite +class QuestionContainerSprite : public cocos2d::Sprite { public: virtual bool init() override; }; -#endif // __QUESTION_CONTAINER_SPRITE_H__ +#endif // __QUESTION_CONTAINER_SPRITE_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-624.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-624.cpp index 62967df872..038423e613 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-624.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-624.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -43,23 +43,23 @@ Bug624Layer::~Bug624Layer() bool Bug624Layer::init() { - if (BugsTestBase::init()) + if(BugsTestBase::init()) { - auto size = Director::getInstance()->getWinSize(); + auto size = Director::getInstance()->getWinSize(); auto label = Label::createWithTTF("Layer1", "fonts/Marker Felt.ttf", 36.0f); - label->setPosition(size.width / 2, size.height / 2); + label->setPosition(size.width/2, size.height/2); addChild(label); - + Device::setAccelerometerEnabled(true); - auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer::onAcceleration, this)); + auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); schedule(CC_SCHEDULE_SELECTOR(Bug624Layer::switchLayer), 5.0f); return true; } - + return false; } @@ -67,13 +67,13 @@ void Bug624Layer::switchLayer(float dt) { unschedule(CC_SCHEDULE_SELECTOR(Bug624Layer::switchLayer)); - auto scene = Scene::create(); + auto scene = Scene::create(); scene->addChild(Bug624Layer2::create(), 0); Director::getInstance()->replaceScene(TransitionFade::create(2.0f, scene, Color3B::WHITE)); } void Bug624Layer::onAcceleration(Acceleration* acc, Event* event) -{ +{ log("Layer1 accel"); } @@ -89,18 +89,19 @@ Bug624Layer2::~Bug624Layer2() bool Bug624Layer2::init() { - if (BugsTestBase::init()) + if(BugsTestBase::init()) { - auto size = Director::getInstance()->getWinSize(); + auto size = Director::getInstance()->getWinSize(); auto label = Label::createWithTTF("Layer2", "fonts/Marker Felt.ttf", 36.0f); - label->setPosition(size.width / 2, size.height / 2); + label->setPosition(size.width/2, size.height/2); addChild(label); - + Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer2::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - + + schedule(CC_SCHEDULE_SELECTOR(Bug624Layer2::switchLayer), 5.0f); return true; @@ -113,12 +114,12 @@ void Bug624Layer2::switchLayer(float dt) { unschedule(CC_SCHEDULE_SELECTOR(Bug624Layer::switchLayer)); - auto scene = Scene::create(); + auto scene = Scene::create(); scene->addChild(Bug624Layer::create(), 0); Director::getInstance()->replaceScene(TransitionFade::create(2.0f, scene, Color3B::RED)); } void Bug624Layer2::onAcceleration(Acceleration* acc, Event* event) -{ +{ log("Layer2 accel"); } diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-624.h b/tests/cpp-tests/Classes/BugsTest/Bug-624.h index f71b73e8a4..37aa5a2b50 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-624.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-624.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,7 +34,7 @@ public: virtual bool init() override; void switchLayer(float dt); virtual void onAcceleration(cocos2d::Acceleration* acc, cocos2d::Event* event); - virtual std::string title() const override { return "Bug624"; } + virtual std::string title() const override { return "Bug624";} CREATE_FUNC(Bug624Layer); }; @@ -46,9 +46,9 @@ public: virtual bool init() override; void switchLayer(float dt); virtual void onAcceleration(cocos2d::Acceleration* acc, cocos2d::Event* event); - virtual std::string title() const override { return "Bug624-2"; } + virtual std::string title() const override { return "Bug624-2";} CREATE_FUNC(Bug624Layer2); }; -#endif // __BUG_624_H__ +#endif // __BUG_624_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-886.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-886.cpp index 9dd133ee0b..c7c1209a87 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-886.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-886.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,11 +33,11 @@ USING_NS_CC; bool Bug886Layer::init() { - if (BugsTestBase::init()) + if(BugsTestBase::init()) { // ask director the the window size // auto size = [[Director sharedDirector] winSize]; - + auto sprite = Sprite::create("Images/bugs/bug886.jpg"); sprite->setAnchorPoint(Vec2::ZERO); sprite->setPosition(Vec2::ZERO); diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-886.h b/tests/cpp-tests/Classes/BugsTest/Bug-886.h index aac1e9850c..a3f1893735 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-886.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-886.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,7 +33,7 @@ public: CREATE_FUNC(Bug886Layer); virtual bool init() override; - virtual std::string title() const override { return "Bug886"; } + virtual std::string title() const override { return "Bug886";} }; -#endif // __BUG_886_H__ +#endif // __BUG_886_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-899.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-899.cpp index f759c40768..cddfdb0b0d 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-899.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-899.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -35,7 +35,7 @@ USING_NS_CC; bool Bug899Layer::init() { - // Director::getInstance()->enableRetinaDisplay(true); +// Director::getInstance()->enableRetinaDisplay(true); if (BugsTestBase::init()) { auto bg = Sprite::create("Images/bugs/RetinaDisplay.jpg"); diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-899.h b/tests/cpp-tests/Classes/BugsTest/Bug-899.h index 37b7bf8d53..e61494ffdb 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-899.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-899.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,7 +33,7 @@ public: CREATE_FUNC(Bug899Layer); virtual bool init() override; - virtual std::string title() const override { return "Bug899"; } + virtual std::string title() const override { return "Bug899";} }; -#endif // __BUG_899_H__ +#endif // __BUG_899_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-914.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-914.cpp index bd1d4b61ed..f80774c7d1 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-914.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-914.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -23,7 +23,7 @@ ****************************************************************************/ // Import the interfaces -#include "Bug-914.h" +#include"Bug-914.h" USING_NS_CC; @@ -34,22 +34,22 @@ bool Bug914Layer::init() // Apple recommends to re-assign "self" with the "super" return value if (BugsTestBase::init()) { - auto listener = EventListenerTouchAllAtOnce::create(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(Bug914Layer::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(Bug914Layer::onTouchesMoved, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - + // ask director the the window size auto size = Director::getInstance()->getWinSize(); - LayerColor* layer; - for (int i = 0; i < 5; i++) + LayerColor *layer; + for( int i=0;i < 5;i++) { - layer = LayerColor::create(Color4B(i * 20, i * 20, i * 20, 255)); - layer->setContentSize(Size(i * 100.0f, i * 100.0f)); - layer->setPosition(size.width / 2, size.height / 2); + layer = LayerColor::create(Color4B(i*20, i*20, i*20,255)); + layer->setContentSize(Size(i*100.0f, i*100.0f)); + layer->setPosition(size.width/2, size.height/2); layer->setAnchorPoint(Vec2(0.5f, 0.5f)); layer->setIgnoreAnchorPointForPosition(false); - addChild(layer, -1 - i); + addChild(layer, -1-i); } // create and initialize a Label @@ -58,11 +58,11 @@ bool Bug914Layer::init() auto menu = Menu::create(item1, nullptr); menu->alignItemsVertically(); - menu->setPosition(size.width / 2, 100); + menu->setPosition(size.width/2, 100); addChild(menu); // position the label on the center of the screen - label->setPosition(size.width / 2, size.height / 2); + label->setPosition(size.width /2 , size.height/2); // add the label as a child to this Layer addChild(label); @@ -71,12 +71,12 @@ bool Bug914Layer::init() return false; } -void Bug914Layer::onTouchesMoved(const std::vector& touches, Event* event) +void Bug914Layer::onTouchesMoved(const std::vector& touches, Event * event) { log("Number of touches: %d", (int)touches.size()); } -void Bug914Layer::onTouchesBegan(const std::vector& touches, Event* event) +void Bug914Layer::onTouchesBegan(const std::vector& touches, Event * event) { onTouchesMoved(touches, event); } diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-914.h b/tests/cpp-tests/Classes/BugsTest/Bug-914.h index cd9d08f5aa..c78952933f 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-914.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-914.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -31,7 +31,7 @@ class Bug914Layer : public BugsTestBase { public: virtual bool init() override; - virtual std::string title() const override { return "Bug914"; } + virtual std::string title() const override { return "Bug914";} void onTouchesMoved(const std::vector& touches, cocos2d::Event* event); void onTouchesBegan(const std::vector& touches, cocos2d::Event* event); @@ -40,4 +40,4 @@ public: CREATE_FUNC(Bug914Layer); }; -#endif // __BUG_914_H__ +#endif // __BUG_914_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.cpp index a1f2b51289..3ed147bb4b 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -38,7 +38,7 @@ bool BugDrawNodeLayer::init() { if (BugsTestBase::init()) { - auto size = Director::getInstance()->getWinSize(); + auto size = Director::getInstance()->getWinSize(); auto testSprite = Sprite::create("Images/close.png"); BlendFunc blend; blend.src = backend::BlendFactor::ZERO; diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.h b/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.h index 47b9472138..e48afef9b7 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,7 +33,7 @@ public: CREATE_FUNC(BugDrawNodeLayer); virtual bool init() override; - virtual std::string title() const override { return "BugDrawNode"; } + virtual std::string title() const override { return "BugDrawNode";} }; #endif \ No newline at end of file diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-Child.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-Child.cpp index b53d10ff94..abab81548f 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-Child.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-Child.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -39,37 +39,37 @@ bool BugChild::init() if (BugsTestBase::init()) { auto size = Director::getInstance()->getWinSize(); - + // create and initialize a Label auto item1 = MenuItemFont::create("Switch Child", CC_CALLBACK_1(BugChild::switchChild, this)); - + menu = Menu::create(item1, nullptr); - + menu->alignItemsVertically(); - menu->setPosition(size.width / 2, 100); + menu->setPosition(size.width/2, 100); addChild(menu); - + parent1 = Sprite::create("Images/grossini.png"); - parent1->setPosition(size.width / 4, size.height / 2); + parent1->setPosition(size.width/4, size.height/2); addChild(parent1); - + parent2 = Sprite::create("Images/grossinis_sister1.png"); - parent2->setPosition(size.width * 3 / 4, size.height / 2); + parent2->setPosition(size.width*3/4, size.height/2); addChild(parent2); - + child = Sprite::create("Images/grossinis_sister2.png"); child->setPosition(20, 20); child->retain(); parent1->addChild(child); return true; } - + return false; } -void BugChild::switchChild(Ref* sender) +void BugChild::switchChild(Ref *sender) { - if (parent1->getChildrenCount() > 0) + if(parent1->getChildrenCount() > 0) { parent1->removeChild(child, false); parent2->addChild(child); @@ -85,49 +85,49 @@ void BugChild::switchChild(Ref* sender) bool BugCameraMask::init() { - if (!BugsTestBase::init()) - return false; - + if (!BugsTestBase::init()) return false; + auto size = Director::getInstance()->getWinSize(); - + auto node = Node::create(); - node->setPosition(size.width / 4, size.height / 3); + node->setPosition(size.width/4, size.height/3); _sprite = Sprite::create("Images/grossini.png"); node->addChild(_sprite); node->setCameraMask((unsigned short)CameraFlag::USER1); - auto move = MoveBy::create(2, Vec2(200, 0)); - + auto move = MoveBy::create(2, Vec2(200,0)); + node->runAction(RepeatForever::create(Sequence::createWithTwoActions(move, move->reverse()))); addChild(node); - + auto camera = Camera::create(); camera->setCameraFlag(CameraFlag::USER1); addChild(camera); - + + auto item1 = MenuItemFont::create("Switch Child", CC_CALLBACK_1(BugCameraMask::switchSpriteFlag, this)); - + auto menu = Menu::create(item1, nullptr); - + menu->alignItemsVertically(); - menu->setPosition(size.width / 2, 100); + menu->setPosition(size.width/2, 100); addChild(menu); - + _spriteMaskLabel = Label::create(); - _spriteMaskLabel->setPosition(size.width / 2, 120); + _spriteMaskLabel->setPosition(size.width/2, 120); addChild(_spriteMaskLabel); updateSpriteMaskLabel(); - + auto label = Label::create(); - label->setPosition(size.width / 2, size.height * 0.9f); + label->setPosition(size.width/2, size.height * 0.9f); label->setString("Sprite should always run action."); addChild(label); - + return true; } -void BugCameraMask::switchSpriteFlag(Ref* sender) +void BugCameraMask::switchSpriteFlag(Ref *sender) { - if ((unsigned short)CameraFlag::USER1 == _sprite->getCameraMask()) + if((unsigned short) CameraFlag::USER1 == _sprite->getCameraMask()) { _sprite->setCameraMask((unsigned short)CameraFlag::DEFAULT); } @@ -135,14 +135,13 @@ void BugCameraMask::switchSpriteFlag(Ref* sender) { _sprite->setCameraMask((unsigned short)CameraFlag::USER1); } - + updateSpriteMaskLabel(); } void BugCameraMask::updateSpriteMaskLabel() { std::stringstream stream; - stream << "The camera Mask is " << (_sprite->getCameraMask() == 1 ? "CameraFlag::Default" : "CameraFlag::User1") - << std::endl; + stream << "The camera Mask is " << (_sprite->getCameraMask() == 1 ? "CameraFlag::Default" : "CameraFlag::User1") << std::endl; _spriteMaskLabel->setString(stream.str()); } diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-Child.h b/tests/cpp-tests/Classes/BugsTest/Bug-Child.h index df83634926..fb603362f6 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-Child.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-Child.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -41,16 +41,17 @@ public: CREATE_FUNC(BugChild); virtual bool init() override; - virtual std::string title() const override { return "BugChild"; } - + virtual std::string title() const override { return "BugChild";} + void switchChild(cocos2d::Ref* sender); - + protected: + cocos2d::Sprite* parent1; cocos2d::Sprite* parent2; - + cocos2d::Sprite* child; - + cocos2d::Menu* menu; }; @@ -58,10 +59,10 @@ class BugCameraMask : public BugsTestBase { public: CREATE_FUNC(BugCameraMask); - + virtual bool init() override; - virtual std::string title() const override { return "BugCameraMask"; } - + virtual std::string title() const override { return "BugCameraMask";} + void switchSpriteFlag(cocos2d::Ref* sender); void updateSpriteMaskLabel(); Node* _sprite; diff --git a/tests/cpp-tests/Classes/BugsTest/BugsTest.cpp b/tests/cpp-tests/Classes/BugsTest/BugsTest.cpp index 074dd6f219..a35705ebae 100644 --- a/tests/cpp-tests/Classes/BugsTest/BugsTest.cpp +++ b/tests/cpp-tests/Classes/BugsTest/BugsTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -39,7 +39,7 @@ #include "Bug-15776.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) -# include "Bug-14327.h" +#include "Bug-14327.h" #endif BugsTests::BugsTests() @@ -58,9 +58,9 @@ BugsTests::BugsTests() ADD_TEST_CASE(BugDrawNodeLayer); ADD_TEST_CASE(Bug12847Layer); ADD_TEST_CASE(Bug15594Layer); - + // NOTE: comment this out because it currently crashes during autotest - // ADD_TEST_CASE(Bug15776Layer); + //ADD_TEST_CASE(Bug15776Layer); #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) ADD_TEST_CASE(Bug14327Layer); diff --git a/tests/cpp-tests/Classes/BugsTest/BugsTest.h b/tests/cpp-tests/Classes/BugsTest/BugsTest.h index dacd08fc05..d06a1cc9c7 100644 --- a/tests/cpp-tests/Classes/BugsTest/BugsTest.h +++ b/tests/cpp-tests/Classes/BugsTest/BugsTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -30,7 +30,7 @@ class BugsTestBase : public TestCase { public: - virtual std::string title() const override { return "No Test Title set"; } + virtual std::string title() const override {return "No Test Title set";} }; DEFINE_TEST_SUITE(BugsTests); diff --git a/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.cpp b/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.cpp index 158543505e..a833ad3fb8 100644 --- a/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.cpp +++ b/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.cpp @@ -27,19 +27,17 @@ THE SOFTWARE. #include "Camera3DTest.h" #include "testResource.h" #include "ui/UISlider.h" -#include "platform/CCFileUtils.h" +#include "platform/CCFileUtils.h" #include "renderer/backend/Device.h" USING_NS_CC; -#define SET_UNIFORM(name, addr, size) \ - do \ - { \ - auto _loc_ = _programState1->getUniformLocation(name); \ - _programState1->setUniform(_loc_, (addr), (size)); \ - _loc_ = _programState2->getUniformLocation(name); \ - _programState2->setUniform(_loc_, (addr), (size)); \ - } while (false) +#define SET_UNIFORM(name, addr, size) do { \ + auto _loc_ = _programState1->getUniformLocation(name); \ + _programState1->setUniform(_loc_, (addr), (size)); \ + _loc_ = _programState2->getUniformLocation(name); \ + _programState2->setUniform(_loc_, (addr), (size)); \ + } while(false) enum { @@ -55,7 +53,7 @@ Camera3DTests::Camera3DTests() ADD_TEST_CASE(CameraCullingDemo); ADD_TEST_CASE(FogTestDemo); ADD_TEST_CASE(CameraArcBallDemo); - // ADD_TEST_CASE(CameraFrameBufferTest); //TODO render target + //ADD_TEST_CASE(CameraFrameBufferTest); //TODO render target ADD_TEST_CASE(BackgroundColorBrushTest); } @@ -68,9 +66,9 @@ CameraRotationTest::CameraRotationTest() { auto s = Director::getInstance()->getWinSize(); - + _camControlNode = Node::create(); - _camControlNode->setPositionNormalized(Vec2(0.5f, 0.5f)); + _camControlNode->setPositionNormalized(Vec2(0.5f,0.5f)); addChild(_camControlNode); _camNode = Node::create(); @@ -78,59 +76,61 @@ CameraRotationTest::CameraRotationTest() _camControlNode->addChild(_camNode); auto sp3d = Sprite3D::create(); - sp3d->setPosition(s.width / 2, s.height / 2); + sp3d->setPosition(s.width/2, s.height/2); addChild(sp3d); - + auto lship = Label::create(); lship->setString("Ship"); lship->setPosition(0, 20); sp3d->addChild(lship); - - // Billboards - // Yellow is at the back + + //Billboards + //Yellow is at the back bill1 = BillBoard::create("Images/Icon.png"); bill1->setPosition3D(Vec3(50.0f, 10.0f, -10.0f)); bill1->setColor(Color3B::YELLOW); bill1->setScale(0.6f); sp3d->addChild(bill1); - + l1 = Label::create(); - l1->setPosition(Vec2(0.0f, -10.0f)); + l1->setPosition(Vec2(0.0f,-10.0f)); l1->setString("Billboard1"); l1->setColor(Color3B::WHITE); l1->setScale(3); bill1->addChild(l1); auto p1 = ParticleSystemQuad::create("Particles/SmallSun.plist"); - p1->setPosition(30.0f, 80.0f); + p1->setPosition(30.0f,80.0f); bill1->addChild(p1); - + bill2 = BillBoard::create("Images/Icon.png"); bill2->setPosition3D(Vec3(-50.0f, -10.0f, 10.0f)); bill2->setScale(0.6f); sp3d->addChild(bill2); - + l2 = Label::create(); l2->setString("Billboard2"); - l2->setPosition(Vec2(0.0f, -10.0f)); + l2->setPosition(Vec2(0.0f,-10.0f)); l2->setColor(Color3B::WHITE); l2->setScale(3); bill2->addChild(l2); - + auto p2 = ParticleSystemQuad::create("Particles/SmallSun.plist"); - p2->setPosition(30, 80); + p2->setPosition(30,80); bill2->addChild(p2); - // 3D models + //3D models auto model = Sprite3D::create("Sprite3DTest/boss1.obj"); model->setScale(4); model->setTexture("Sprite3DTest/boss.png"); - model->setPosition3D(Vec3(s.width / 2, s.height / 2, 0)); + model->setPosition3D(Vec3(s.width/2, s.height/2, 0)); addChild(model); - // Listener - _lis = EventListenerTouchOneByOne::create(); - _lis->onTouchBegan = [](Touch* t, Event* e) { return true; }; + //Listener + _lis = EventListenerTouchOneByOne::create(); + _lis->onTouchBegan = [](Touch* t, Event* e) { + return true; + }; _lis->onTouchMoved = [this](Touch* t, Event* e) { float dx = t->getDelta().x; @@ -146,7 +146,7 @@ CameraRotationTest::CameraRotationTest() }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(_lis, this); - + schedule(CC_SCHEDULE_SELECTOR(CameraRotationTest::update)); } @@ -175,7 +175,9 @@ void CameraRotationTest::onExit() CameraBaseTest::onExit(); } -void CameraRotationTest::update(float dt) {} +void CameraRotationTest::update(float dt) +{ +} //------------------------------------------------------------------ // @@ -183,75 +185,80 @@ void CameraRotationTest::update(float dt) {} // //------------------------------------------------------------------ Camera3DTestDemo::Camera3DTestDemo() - : _cameraType(CameraType::Free) - , _incRot(nullptr) - , _decRot(nullptr) - , _camera(nullptr) - , _bZoomOut(false) - , _bZoomIn(false) - , _bRotateLeft(false) - , _bRotateRight(false) -{} -Camera3DTestDemo::~Camera3DTestDemo() {} -void Camera3DTestDemo::reachEndCallBack() {} +: _cameraType(CameraType::Free) +, _incRot(nullptr) +, _decRot(nullptr) +, _camera(nullptr) +, _bZoomOut(false) +, _bZoomIn(false) +, _bRotateLeft(false) +, _bRotateRight(false) +{ +} +Camera3DTestDemo::~Camera3DTestDemo() +{ +} +void Camera3DTestDemo::reachEndCallBack() +{ +} std::string Camera3DTestDemo::title() const { return "Testing Camera"; } -void Camera3DTestDemo::scaleCameraCallback(Ref* sender, float value) +void Camera3DTestDemo::scaleCameraCallback(Ref* sender,float value) { - if (_camera && _cameraType != CameraType::FirstPerson) + if(_camera&& _cameraType!=CameraType::FirstPerson) { - Vec3 cameraPos = _camera->getPosition3D(); - cameraPos += cameraPos.getNormalized() * value; + Vec3 cameraPos= _camera->getPosition3D(); + cameraPos+= cameraPos.getNormalized()*value; _camera->setPosition3D(cameraPos); } } -void Camera3DTestDemo::rotateCameraCallback(Ref* sender, float value) +void Camera3DTestDemo::rotateCameraCallback(Ref* sender,float value) { - if (_cameraType == CameraType::Free || _cameraType == CameraType::FirstPerson) + if(_cameraType==CameraType::Free || _cameraType==CameraType::FirstPerson) { - Vec3 rotation3D = _camera->getRotation3D(); - rotation3D.y += value; + Vec3 rotation3D= _camera->getRotation3D(); + rotation3D.y+= value; _camera->setRotation3D(rotation3D); } } void Camera3DTestDemo::SwitchViewCallback(Ref* sender, CameraType cameraType) { - if (_cameraType == cameraType) + if(_cameraType==cameraType) { - return; + return ; } _cameraType = cameraType; - if (_cameraType == CameraType::Free) + if(_cameraType==CameraType::Free) { _camera->setPosition3D(Vec3(0, 130, 130) + _sprite3D->getPosition3D()); _camera->lookAt(_sprite3D->getPosition3D()); - + _RotateRightlabel->setColor(Color3B::WHITE); _RotateLeftlabel->setColor(Color3B::WHITE); _ZoomInlabel->setColor(Color3B::WHITE); _ZoomOutlabel->setColor(Color3B::WHITE); } - else if (_cameraType == CameraType::FirstPerson) + else if(_cameraType==CameraType::FirstPerson) { Vec3 newFaceDir; _sprite3D->getWorldToNodeTransform().getForwardVector(&newFaceDir); newFaceDir.normalize(); - _camera->setPosition3D(Vec3(0, 35, 0) + _sprite3D->getPosition3D()); - _camera->lookAt(_sprite3D->getPosition3D() + newFaceDir * 50); - + _camera->setPosition3D(Vec3(0,35,0) + _sprite3D->getPosition3D()); + _camera->lookAt(_sprite3D->getPosition3D() + newFaceDir*50); + _RotateRightlabel->setColor(Color3B::WHITE); _RotateLeftlabel->setColor(Color3B::WHITE); _ZoomInlabel->setColor(Color3B::GRAY); _ZoomOutlabel->setColor(Color3B::GRAY); } - else if (_cameraType == CameraType::ThirdPerson) + else if(_cameraType==CameraType::ThirdPerson) { _camera->setPosition3D(Vec3(0, 130, 130) + _sprite3D->getPosition3D()); _camera->lookAt(_sprite3D->getPosition3D()); - + _RotateRightlabel->setColor(Color3B::GRAY); _RotateLeftlabel->setColor(Color3B::GRAY); _ZoomInlabel->setColor(Color3B::WHITE); @@ -261,115 +268,112 @@ void Camera3DTestDemo::SwitchViewCallback(Ref* sender, CameraType cameraType) void Camera3DTestDemo::onEnter() { CameraBaseTest::onEnter(); - _sprite3D = nullptr; - auto s = Director::getInstance()->getWinSize(); - auto listener = EventListenerTouchAllAtOnce::create(); + _sprite3D=nullptr; + auto s = Director::getInstance()->getWinSize(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(Camera3DTestDemo::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(Camera3DTestDemo::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(Camera3DTestDemo::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - auto layer3D = Layer::create(); - addChild(layer3D, 0); - _layer3D = layer3D; - _curState = State_None; - addNewSpriteWithCoords(Vec3(0, 0, 0), "Sprite3DTest/girl.c3b", true, 0.2f, true); + auto layer3D=Layer::create(); + addChild(layer3D,0); + _layer3D=layer3D; + _curState=State_None; + addNewSpriteWithCoords( Vec3(0,0,0),"Sprite3DTest/girl.c3b",true,0.2f,true); TTFConfig ttfConfig("fonts/arial.ttf", 20); - + auto containerForLabel1 = Node::create(); - _ZoomOutlabel = Label::createWithTTF(ttfConfig, "zoom out"); - _ZoomOutlabel->setPosition(s.width - 50, VisibleRect::top().y - 20); + _ZoomOutlabel = Label::createWithTTF(ttfConfig,"zoom out"); + _ZoomOutlabel->setPosition(s.width-50, VisibleRect::top().y-20); containerForLabel1->addChild(_ZoomOutlabel); addChild(containerForLabel1, 10); - + auto listener1 = EventListenerTouchOneByOne::create(); listener1->setSwallowTouches(true); - + listener1->onTouchBegan = CC_CALLBACK_2(Camera3DTestDemo::onTouchesZoomOut, this); listener1->onTouchEnded = CC_CALLBACK_2(Camera3DTestDemo::onTouchesZoomOutEnd, this); - + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, _ZoomOutlabel); - + auto containerForLabel2 = Node::create(); - _ZoomInlabel = Label::createWithTTF(ttfConfig, "zoom in"); - _ZoomInlabel->setPosition(s.width - 50, VisibleRect::top().y - 70); + _ZoomInlabel = Label::createWithTTF(ttfConfig,"zoom in"); + _ZoomInlabel->setPosition(s.width-50, VisibleRect::top().y-70); containerForLabel2->addChild(_ZoomInlabel); addChild(containerForLabel2, 10); - + auto listener2 = EventListenerTouchOneByOne::create(); listener2->setSwallowTouches(true); - + listener2->onTouchBegan = CC_CALLBACK_2(Camera3DTestDemo::onTouchesZoomIn, this); listener2->onTouchEnded = CC_CALLBACK_2(Camera3DTestDemo::onTouchesZoomInEnd, this); - + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener2, _ZoomInlabel); - + auto containerForLabel3 = Node::create(); - _RotateLeftlabel = Label::createWithTTF(ttfConfig, "rotate left"); - _RotateLeftlabel->setPosition(s.width - 50, VisibleRect::top().y - 120); + _RotateLeftlabel = Label::createWithTTF(ttfConfig,"rotate left"); + _RotateLeftlabel->setPosition(s.width-50, VisibleRect::top().y-120); containerForLabel3->addChild(_RotateLeftlabel); addChild(containerForLabel3, 10); - + auto listener3 = EventListenerTouchOneByOne::create(); listener3->setSwallowTouches(true); - + listener3->onTouchBegan = CC_CALLBACK_2(Camera3DTestDemo::onTouchesRotateLeft, this); listener3->onTouchEnded = CC_CALLBACK_2(Camera3DTestDemo::onTouchesRotateLeftEnd, this); - + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener3, _RotateLeftlabel); - + auto containerForLabel4 = Node::create(); - _RotateRightlabel = Label::createWithTTF(ttfConfig, "rotate right"); - _RotateRightlabel->setPosition(s.width - 50, VisibleRect::top().y - 170); + _RotateRightlabel = Label::createWithTTF(ttfConfig,"rotate right"); + _RotateRightlabel->setPosition(s.width-50, VisibleRect::top().y-170); containerForLabel4->addChild(_RotateRightlabel); addChild(containerForLabel4, 10); - + auto listener4 = EventListenerTouchOneByOne::create(); listener4->setSwallowTouches(true); - + listener4->onTouchBegan = CC_CALLBACK_2(Camera3DTestDemo::onTouchesRotateRight, this); listener4->onTouchEnded = CC_CALLBACK_2(Camera3DTestDemo::onTouchesRotateRightEnd, this); - + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener4, _RotateRightlabel); - - auto label1 = Label::createWithTTF(ttfConfig, "free "); - auto menuItem1 = - MenuItemLabel::create(label1, CC_CALLBACK_1(Camera3DTestDemo::SwitchViewCallback, this, CameraType::Free)); - auto label2 = Label::createWithTTF(ttfConfig, "third person"); - auto menuItem2 = MenuItemLabel::create( - label2, CC_CALLBACK_1(Camera3DTestDemo::SwitchViewCallback, this, CameraType::ThirdPerson)); - auto label3 = Label::createWithTTF(ttfConfig, "first person"); - auto menuItem3 = MenuItemLabel::create( - label3, CC_CALLBACK_1(Camera3DTestDemo::SwitchViewCallback, this, CameraType::FirstPerson)); + + auto label1 = Label::createWithTTF(ttfConfig,"free "); + auto menuItem1 = MenuItemLabel::create(label1, CC_CALLBACK_1(Camera3DTestDemo::SwitchViewCallback,this,CameraType::Free)); + auto label2 = Label::createWithTTF(ttfConfig,"third person"); + auto menuItem2 = MenuItemLabel::create(label2, CC_CALLBACK_1(Camera3DTestDemo::SwitchViewCallback,this,CameraType::ThirdPerson)); + auto label3 = Label::createWithTTF(ttfConfig,"first person"); + auto menuItem3 = MenuItemLabel::create(label3, CC_CALLBACK_1(Camera3DTestDemo::SwitchViewCallback,this,CameraType::FirstPerson)); auto menu = Menu::create(menuItem1, menuItem2, menuItem3, nullptr); - + menu->setPosition(Vec2::ZERO); - - menuItem1->setPosition(VisibleRect::left().x + 100, VisibleRect::top().y - 50); - menuItem2->setPosition(VisibleRect::left().x + 100, VisibleRect::top().y - 100); - menuItem3->setPosition(VisibleRect::left().x + 100, VisibleRect::top().y - 150); + + menuItem1->setPosition(VisibleRect::left().x+100, VisibleRect::top().y-50); + menuItem2->setPosition(VisibleRect::left().x+100, VisibleRect::top().y -100); + menuItem3->setPosition(VisibleRect::left().x+100, VisibleRect::top().y -150); addChild(menu, 0); schedule(CC_SCHEDULE_SELECTOR(Camera3DTestDemo::updateCamera), 0.0f); if (_camera == nullptr) { - _camera = Camera::createPerspective(60, (float)s.width / s.height, 1, 1000); + _camera=Camera::createPerspective(60, (float)s.width/s.height, 1, 1000); _camera->setCameraFlag(CameraFlag::USER1); _layer3D->addChild(_camera); } - SwitchViewCallback(this, CameraType::ThirdPerson); - DrawNode3D* line = DrawNode3D::create(); - // draw x - for (int j = -20; j <= 20; j++) + SwitchViewCallback(this,CameraType::ThirdPerson); + DrawNode3D* line =DrawNode3D::create(); + //draw x + for( int j =-20; j<=20 ;j++) { - line->drawLine(Vec3(-100.0f, 0.0f, 5.0f * j), Vec3(100.0f, 0.0f, 5.0f * j), Color4F(1, 0, 0, 1)); + line->drawLine(Vec3(-100.0f, 0.0f, 5.0f*j),Vec3(100.0f,0.0f,5.0f*j),Color4F(1,0,0,1)); } - // draw z - for (int j = -20; j <= 20; j++) + //draw z + for( int j =-20; j<=20 ;j++) { - line->drawLine(Vec3(5.0f * j, 0.0f, -100.0f), Vec3(5.0f * j, 0.0f, 100.0f), Color4F(0, 0, 1, 1)); + line->drawLine(Vec3(5.0f*j, 0.0f, -100.0f),Vec3(5.0f*j,0.0f,100.0f),Color4F(0,0,1,1)); } - // draw y - line->drawLine(Vec3(0.0f, -50.0f, 0.0f), Vec3(0, 0, 0), Color4F(0, 0.5, 0, 1)); - line->drawLine(Vec3(0, 0, 0), Vec3(0, 50.0f, 0), Color4F(0, 1, 0, 1)); + //draw y + line->drawLine(Vec3(0.0f, -50.0f, 0.0f),Vec3(0,0,0),Color4F(0,0.5,0,1)); + line->drawLine(Vec3(0, 0, 0),Vec3(0,50.0f,0),Color4F(0,1,0,1)); _layer3D->addChild(line); _layer3D->setCameraMask(2); @@ -383,192 +387,191 @@ void Camera3DTestDemo::onExit() } } -void Camera3DTestDemo::addNewSpriteWithCoords(Vec3 p, - std::string fileName, - bool playAnimation, - float scale, - bool bindCamera) +void Camera3DTestDemo::addNewSpriteWithCoords(Vec3 p,std::string fileName,bool playAnimation,float scale,bool bindCamera) { auto sprite = Sprite3D::create(fileName); _layer3D->addChild(sprite); - float globalZOrder = sprite->getGlobalZOrder(); - sprite->setPosition3D(Vec3(p.x, p.y, p.z)); + float globalZOrder=sprite->getGlobalZOrder(); + sprite->setPosition3D( Vec3( p.x, p.y,p.z) ); sprite->setGlobalZOrder(globalZOrder); - if (playAnimation) + if(playAnimation) { - auto animation = Animation3D::create(fileName, "Take 001"); + auto animation = Animation3D::create(fileName,"Take 001"); if (animation) { auto animate = Animate3D::create(animation); sprite->runAction(RepeatForever::create(animate)); } } - if (bindCamera) + if(bindCamera) { - _sprite3D = sprite; + _sprite3D=sprite; } - sprite->setScale(scale); + sprite->setScale(scale); } -void Camera3DTestDemo::onTouchesBegan(const std::vector& touches, cocos2d::Event* event) {} -void Camera3DTestDemo::onTouchesMoved(const std::vector& touches, cocos2d::Event* event) +void Camera3DTestDemo::onTouchesBegan(const std::vector& touches, cocos2d::Event *event) { - if (touches.size() == 1) +} +void Camera3DTestDemo::onTouchesMoved(const std::vector& touches, cocos2d::Event *event) +{ + if(touches.size()==1) { - auto touch = touches[0]; + auto touch = touches[0]; auto location = touch->getLocation(); - Point newPos = touch->getPreviousLocation() - location; - if (_cameraType == CameraType::Free || _cameraType == CameraType::FirstPerson) + Point newPos = touch->getPreviousLocation()-location; + if(_cameraType==CameraType::Free || _cameraType==CameraType::FirstPerson) { Vec3 cameraDir; Vec3 cameraRightDir; _camera->getNodeToWorldTransform().getForwardVector(&cameraDir); cameraDir.normalize(); - cameraDir.y = 0; + cameraDir.y=0; _camera->getNodeToWorldTransform().getRightVector(&cameraRightDir); cameraRightDir.normalize(); - cameraRightDir.y = 0; - Vec3 cameraPos = _camera->getPosition3D(); - cameraPos += cameraDir * newPos.y * 0.1f; - cameraPos += cameraRightDir * newPos.x * 0.1f; + cameraRightDir.y=0; + Vec3 cameraPos= _camera->getPosition3D(); + cameraPos+=cameraDir*newPos.y*0.1f; + cameraPos+=cameraRightDir*newPos.x*0.1f; _camera->setPosition3D(cameraPos); - if (_sprite3D && _cameraType == CameraType::FirstPerson) + if(_sprite3D && _cameraType==CameraType::FirstPerson) { - _sprite3D->setPosition3D(Vec3(_camera->getPositionX(), 0, _camera->getPositionZ())); - _targetPos = _sprite3D->getPosition3D(); + _sprite3D->setPosition3D(Vec3(_camera->getPositionX(),0,_camera->getPositionZ())); + _targetPos=_sprite3D->getPosition3D(); } } } } void Camera3DTestDemo::move3D(float elapsedTime) { - if (_sprite3D) + if(_sprite3D) { - Vec3 curPos = _sprite3D->getPosition3D(); + Vec3 curPos= _sprite3D->getPosition3D(); Vec3 newFaceDir = _targetPos - curPos; - newFaceDir.y = 0.0f; + newFaceDir.y = 0.0f; newFaceDir.normalize(); Vec3 offset = newFaceDir * 25.0f * elapsedTime; - curPos += offset; + curPos+=offset; _sprite3D->setPosition3D(curPos); - if (_cameraType == CameraType::ThirdPerson) + if(_cameraType==CameraType::ThirdPerson) { - Vec3 cameraPos = _camera->getPosition3D(); - cameraPos.x += offset.x; - cameraPos.z += offset.z; + Vec3 cameraPos= _camera->getPosition3D(); + cameraPos.x+=offset.x; + cameraPos.z+=offset.z; _camera->setPosition3D(cameraPos); } } } void Camera3DTestDemo::updateState(float elapsedTime) { - if (_sprite3D) + if(_sprite3D) { - Vec3 curPos = _sprite3D->getPosition3D(); + Vec3 curPos= _sprite3D->getPosition3D(); Vec3 curFaceDir; _sprite3D->getNodeToWorldTransform().getForwardVector(&curFaceDir); - curFaceDir = -curFaceDir; + curFaceDir=-curFaceDir; curFaceDir.normalize(); Vec3 newFaceDir = _targetPos - curPos; - newFaceDir.y = 0.0f; + newFaceDir.y = 0.0f; newFaceDir.normalize(); - float cosAngle = std::fabs(Vec3::dot(curFaceDir, newFaceDir) - 1.0f); - float dist = curPos.distanceSquared(_targetPos); - if (dist <= 4.0f) + float cosAngle = std::fabs(Vec3::dot(curFaceDir,newFaceDir) - 1.0f); + float dist = curPos.distanceSquared(_targetPos); + if(dist<=4.0f) { - if (cosAngle <= 0.01f) + if(cosAngle<=0.01f) _curState = State_Idle; else _curState = State_Rotate; } else { - if (cosAngle > 0.01f) + if(cosAngle>0.01f) _curState = State_Rotate | State_Move; else _curState = State_Move; } } } -void Camera3DTestDemo::onTouchesEnded(const std::vector& touches, cocos2d::Event* event) +void Camera3DTestDemo::onTouchesEnded(const std::vector& touches, cocos2d::Event *event) { - for (auto& item : touches) + for ( auto &item: touches ) { - auto touch = item; + auto touch = item; auto location = touch->getLocationInView(); - if (_camera) + if(_camera) { - if (_sprite3D && _cameraType == CameraType::ThirdPerson && _bZoomOut == false && _bZoomIn == false && - _bRotateLeft == false && _bRotateRight == false) + if(_sprite3D && _cameraType==CameraType::ThirdPerson && _bZoomOut == false && _bZoomIn == false && _bRotateLeft == false && _bRotateRight == false) { Vec3 nearP(location.x, location.y, -1.0f), farP(location.x, location.y, 1.0f); - + auto size = Director::getInstance()->getWinSize(); - nearP = _camera->unproject(nearP); - farP = _camera->unproject(farP); + nearP = _camera->unproject(nearP); + farP = _camera->unproject(farP); Vec3 dir(farP - nearP); - float dist = 0.0f; - float ndd = Vec3::dot(Vec3(0, 1, 0), dir); - if (ndd == 0) - dist = 0.0f; - float ndo = Vec3::dot(Vec3(0, 1, 0), nearP); - dist = (0 - ndo) / ndd; - Vec3 p = nearP + dist * dir; - - if (p.x > 100) + float dist=0.0f; + float ndd = Vec3::dot(Vec3(0,1,0),dir); + if(ndd == 0) + dist=0.0f; + float ndo = Vec3::dot(Vec3(0,1,0),nearP); + dist= (0 - ndo) / ndd; + Vec3 p = nearP + dist * dir; + + if( p.x > 100) p.x = 100; - if (p.x < -100) + if( p.x < -100) p.x = -100; - if (p.z > 100) + if( p.z > 100) p.z = 100; - if (p.z < -100) + if( p.z < -100) p.z = -100; - - _targetPos = p; + + _targetPos=p; } } } } -void onTouchesCancelled(const std::vector& touches, cocos2d::Event* event) {} +void onTouchesCancelled(const std::vector& touches, cocos2d::Event *event) +{ +} void Camera3DTestDemo::updateCamera(float fDelta) { - if (_sprite3D) + if(_sprite3D) { - if (_cameraType == CameraType::ThirdPerson) + if( _cameraType==CameraType::ThirdPerson) { updateState(fDelta); - if (isState(_curState, State_Move)) + if(isState(_curState,State_Move)) { move3D(fDelta); - if (isState(_curState, State_Rotate)) + if(isState(_curState,State_Rotate)) { Vec3 curPos = _sprite3D->getPosition3D(); - + Vec3 newFaceDir = _targetPos - curPos; - newFaceDir.y = 0; + newFaceDir.y = 0; newFaceDir.normalize(); Vec3 up; _sprite3D->getNodeToWorldTransform().getUpVector(&up); up.normalize(); Vec3 right; - Vec3::cross(-newFaceDir, up, &right); + Vec3::cross(-newFaceDir,up,&right); right.normalize(); - Vec3 pos = Vec3(0, 0, 0); + Vec3 pos = Vec3(0,0,0); Mat4 mat; mat.m[0] = right.x; mat.m[1] = right.y; mat.m[2] = right.z; mat.m[3] = 0.0f; - + mat.m[4] = up.x; mat.m[5] = up.y; mat.m[6] = up.z; mat.m[7] = 0.0f; - + mat.m[8] = newFaceDir.x; mat.m[9] = newFaceDir.y; mat.m[10] = newFaceDir.z; mat.m[11] = 0.0f; - + mat.m[12] = pos.x; mat.m[13] = pos.y; mat.m[14] = pos.z; @@ -577,24 +580,24 @@ void Camera3DTestDemo::updateCamera(float fDelta) } } } - if (_bZoomOut == true) + if(_bZoomOut == true) { - if (_camera) + if(_camera) { - if (_cameraType == CameraType::ThirdPerson) + if(_cameraType == CameraType::ThirdPerson) { - Vec3 lookDir = _camera->getPosition3D() - _sprite3D->getPosition3D(); + Vec3 lookDir = _camera->getPosition3D() - _sprite3D->getPosition3D(); Vec3 cameraPos = _camera->getPosition3D(); - if (lookDir.length() <= 300) + if(lookDir.length() <= 300) { cameraPos += lookDir.getNormalized(); _camera->setPosition3D(cameraPos); } } - else if (_cameraType == CameraType::Free) + else if(_cameraType == CameraType::Free) { Vec3 cameraPos = _camera->getPosition3D(); - if (cameraPos.length() <= 300) + if(cameraPos.length() <= 300) { cameraPos += cameraPos.getNormalized(); _camera->setPosition3D(cameraPos); @@ -602,24 +605,24 @@ void Camera3DTestDemo::updateCamera(float fDelta) } } } - if (_bZoomIn == true) + if(_bZoomIn == true) { - if (_camera) + if(_camera) { - if (_cameraType == CameraType::ThirdPerson) + if(_cameraType == CameraType::ThirdPerson) { - Vec3 lookDir = _camera->getPosition3D() - _sprite3D->getPosition3D(); + Vec3 lookDir = _camera->getPosition3D() - _sprite3D->getPosition3D(); Vec3 cameraPos = _camera->getPosition3D(); - if (lookDir.length() >= 50) + if(lookDir.length() >= 50) { cameraPos -= lookDir.getNormalized(); _camera->setPosition3D(cameraPos); } } - else if (_cameraType == CameraType::Free) + else if(_cameraType == CameraType::Free) { Vec3 cameraPos = _camera->getPosition3D(); - if (cameraPos.length() >= 50) + if(cameraPos.length() >= 50) { cameraPos -= cameraPos.getNormalized(); _camera->setPosition3D(cameraPos); @@ -627,21 +630,21 @@ void Camera3DTestDemo::updateCamera(float fDelta) } } } - if (_bRotateLeft == true) + if(_bRotateLeft == true) { - if (_cameraType == CameraType::Free || _cameraType == CameraType::FirstPerson) + if(_cameraType==CameraType::Free || _cameraType==CameraType::FirstPerson) { - Vec3 rotation3D = _camera->getRotation3D(); - rotation3D.y += 1; + Vec3 rotation3D= _camera->getRotation3D(); + rotation3D.y+= 1; _camera->setRotation3D(rotation3D); } } - if (_bRotateRight == true) + if(_bRotateRight == true) { - if (_cameraType == CameraType::Free || _cameraType == CameraType::FirstPerson) + if(_cameraType==CameraType::Free || _cameraType==CameraType::FirstPerson) { - Vec3 rotation3D = _camera->getRotation3D(); - rotation3D.y -= 1; + Vec3 rotation3D= _camera->getRotation3D(); + rotation3D.y-= 1; _camera->setRotation3D(rotation3D); } } @@ -650,11 +653,11 @@ void Camera3DTestDemo::updateCamera(float fDelta) bool Camera3DTestDemo::onTouchesCommon(Touch* touch, Event* event, bool* touchProperty) { auto target = static_cast(event->getCurrentTarget()); - + Vec2 locationInNode = target->convertToNodeSpace(touch->getLocation()); - Size s = target->getContentSize(); - Rect rect = Rect(0, 0, s.width, s.height); - + Size s = target->getContentSize(); + Rect rect = Rect(0, 0, s.width, s.height); + if (rect.containsPoint(locationInNode)) { *touchProperty = true; @@ -662,7 +665,7 @@ bool Camera3DTestDemo::onTouchesCommon(Touch* touch, Event* event, bool* touchPr } return false; } -bool Camera3DTestDemo::isState(unsigned int state, unsigned int bit) const +bool Camera3DTestDemo::isState(unsigned int state,unsigned int bit) const { return (state & bit) == bit; } @@ -702,16 +705,19 @@ void Camera3DTestDemo::onTouchesRotateRightEnd(Touch* touch, Event* event) //////////////////////////////////////////////////////////// // CameraCullingDemo CameraCullingDemo::CameraCullingDemo() - : _layer3D(nullptr) - , _cameraType(CameraType::FirstPerson) - , _cameraFirst(nullptr) - , _cameraThird(nullptr) - , _moveAction(nullptr) - , _drawAABB(nullptr) - , _drawFrustum(nullptr) - , _row(3) -{} -CameraCullingDemo::~CameraCullingDemo() {} +: _layer3D(nullptr) +, _cameraType(CameraType::FirstPerson) +, _cameraFirst(nullptr) +, _cameraThird(nullptr) +, _moveAction(nullptr) +, _drawAABB(nullptr) +, _drawFrustum(nullptr) +, _row(3) +{ +} +CameraCullingDemo::~CameraCullingDemo() +{ +} std::string CameraCullingDemo::title() const { @@ -723,59 +729,59 @@ void CameraCullingDemo::onEnter() CameraBaseTest::onEnter(); schedule(CC_SCHEDULE_SELECTOR(CameraCullingDemo::update), 0.0f); - + auto s = Director::getInstance()->getWinSize(); /*auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(Camera3DTestDemo::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(Camera3DTestDemo::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(Camera3DTestDemo::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);*/ - auto layer3D = Layer::create(); - addChild(layer3D, 0); - _layer3D = layer3D; - + auto layer3D=Layer::create(); + addChild(layer3D,0); + _layer3D=layer3D; + // switch camera MenuItemFont::setFontName("fonts/arial.ttf"); MenuItemFont::setFontSize(20); - - auto menuItem1 = MenuItemFont::create("Switch Camera", CC_CALLBACK_1(CameraCullingDemo::switchViewCallback, this)); - menuItem1->setColor(Color3B(0, 200, 20)); - auto menu = Menu::create(menuItem1, NULL); + + auto menuItem1 = MenuItemFont::create("Switch Camera", CC_CALLBACK_1(CameraCullingDemo::switchViewCallback,this)); + menuItem1->setColor(Color3B(0,200,20)); + auto menu = Menu::create(menuItem1,NULL); menu->setPosition(Vec2::ZERO); - menuItem1->setPosition(VisibleRect::left().x + 80, VisibleRect::top().y - 70); + menuItem1->setPosition(VisibleRect::left().x + 80, VisibleRect::top().y -70); addChild(menu, 1); - + // + - MenuItemFont::setFontSize(40); auto decrease = MenuItemFont::create(" - ", CC_CALLBACK_1(CameraCullingDemo::delSpriteCallback, this)); - decrease->setColor(Color3B(0, 200, 20)); + decrease->setColor(Color3B(0,200,20)); auto increase = MenuItemFont::create(" + ", CC_CALLBACK_1(CameraCullingDemo::addSpriteCallback, this)); - increase->setColor(Color3B(0, 200, 20)); - + increase->setColor(Color3B(0,200,20)); + menu = Menu::create(decrease, increase, nullptr); menu->alignItemsHorizontally(); - menu->setPosition(Vec2(s.width - 60, VisibleRect::top().y - 70)); + menu->setPosition(Vec2(s.width - 60, VisibleRect::top().y -70)); addChild(menu, 1); - + TTFConfig ttfCount("fonts/Marker Felt.ttf", 30); - _labelSprite3DCount = Label::createWithTTF(ttfCount, "0 sprits"); - _labelSprite3DCount->setColor(Color3B(0, 200, 20)); - _labelSprite3DCount->setPosition(Vec2(s.width / 2, VisibleRect::top().y - 70)); + _labelSprite3DCount = Label::createWithTTF(ttfCount,"0 sprits"); + _labelSprite3DCount->setColor(Color3B(0,200,20)); + _labelSprite3DCount->setPosition(Vec2(s.width/2, VisibleRect::top().y -70)); addChild(_labelSprite3DCount); - + // aabb drawNode3D _drawAABB = DrawNode3D::create(); - _drawAABB->setCameraMask((unsigned short)CameraFlag::USER1); + _drawAABB->setCameraMask((unsigned short) CameraFlag::USER1); addChild(_drawAABB); - + // frustum drawNode3D _drawFrustum = DrawNode3D::create(); - _drawFrustum->setCameraMask((unsigned short)CameraFlag::USER1); + _drawFrustum->setCameraMask((unsigned short) CameraFlag::USER1); addChild(_drawFrustum); - + // set camera switchViewCallback(this); - + // add sprite addSpriteCallback(nullptr); } @@ -797,13 +803,13 @@ void CameraCullingDemo::update(float dt) { _drawAABB->clear(); - if (_cameraType == CameraType::ThirdPerson) + if(_cameraType == CameraType::ThirdPerson) drawCameraFrustum(); Vector& children = _layer3D->getChildren(); Vec3 corners[8]; - for (const auto& iter : children) + for (const auto& iter: children) { const AABB& aabb = static_cast(iter)->getAABB(); if (_cameraFirst->isVisibleInFrustum(&aabb)) @@ -819,12 +825,11 @@ void CameraCullingDemo::reachEndCallBack() _cameraFirst->stopActionByTag(100); auto inverse = MoveTo::create(4.f, Vec2(-_cameraFirst->getPositionX(), 0.0f)); inverse->retain(); - + _moveAction->release(); _moveAction = inverse; - auto rot = RotateBy::create(1.f, Vec3(0.f, 180.f, 0.f)); - auto seq = Sequence::create(rot, _moveAction, - CallFunc::create(CC_CALLBACK_0(CameraCullingDemo::reachEndCallBack, this)), nullptr); + auto rot = RotateBy::create(1.f, Vec3(0.f, 180.f, 0.f)); + auto seq = Sequence::create(rot, _moveAction, CallFunc::create(CC_CALLBACK_0(CameraCullingDemo::reachEndCallBack, this)), nullptr); seq->setTag(100); _cameraFirst->runAction(seq); } @@ -832,38 +837,37 @@ void CameraCullingDemo::reachEndCallBack() void CameraCullingDemo::switchViewCallback(Ref* sender) { auto s = Director::getInstance()->getWinSize(); - + if (_cameraFirst == nullptr) { - _cameraFirst = Camera::createPerspective(30.0f, (float)s.width / s.height, 10.0f, 200.0f); + _cameraFirst = Camera::createPerspective(30.0f, (float)s.width/s.height, 10.0f, 200.0f); _cameraFirst->setCameraFlag(CameraFlag::USER8); - _cameraFirst->setPosition3D(Vec3(-100.0f, 0.0f, 0.0f)); - _cameraFirst->lookAt(Vec3(1000.0f, 0.0f, 0.0f)); + _cameraFirst->setPosition3D(Vec3(-100.0f,0.0f,0.0f)); + _cameraFirst->lookAt(Vec3(1000.0f,0.0f,0.0f)); _moveAction = MoveTo::create(4.f, Vec2(-_cameraFirst->getPositionX(), 0.0f)); _moveAction->retain(); - auto seq = Sequence::create( - _moveAction, CallFunc::create(CC_CALLBACK_0(CameraCullingDemo::reachEndCallBack, this)), nullptr); + auto seq = Sequence::create(_moveAction, CallFunc::create(CC_CALLBACK_0(CameraCullingDemo::reachEndCallBack, this)), nullptr); seq->setTag(100); _cameraFirst->runAction(seq); addChild(_cameraFirst); } - + if (_cameraThird == nullptr) { - _cameraThird = Camera::createPerspective(60, (float)s.width / s.height, 1, 1000); + _cameraThird = Camera::createPerspective(60, (float)s.width/s.height, 1, 1000); _cameraThird->setCameraFlag(CameraFlag::USER8); _cameraThird->setPosition3D(Vec3(0.0f, 130.0f, 130.0f)); - _cameraThird->lookAt(Vec3(0, 0, 0)); + _cameraThird->lookAt(Vec3(0,0,0)); addChild(_cameraThird); } - - if (_cameraType == CameraType::FirstPerson) + + if(_cameraType == CameraType::FirstPerson) { _cameraType = CameraType::ThirdPerson; _cameraThird->setCameraFlag(CameraFlag::USER1); _cameraFirst->setCameraFlag(CameraFlag::USER8); } - else if (_cameraType == CameraType::ThirdPerson) + else if(_cameraType == CameraType::ThirdPerson) { _cameraType = CameraType::FirstPerson; _cameraFirst->setCameraFlag(CameraFlag::USER1); @@ -877,7 +881,7 @@ void CameraCullingDemo::addSpriteCallback(Ref* sender) _layer3D->removeAllChildren(); _objects.clear(); _drawAABB->clear(); - + ++_row; for (int x = -_row; x < _row; x++) { @@ -885,29 +889,28 @@ void CameraCullingDemo::addSpriteCallback(Ref* sender) { auto sprite = Sprite3D::create("Sprite3DTest/orc.c3b"); sprite->setPosition3D(Vec3(x * 30.0f, 0.0f, z * 30.0f)); - sprite->setRotation3D(Vec3(0.0f, 180.0f, 0.0f)); + sprite->setRotation3D(Vec3(0.0f,180.0f,0.0f)); _objects.push_back(sprite); _layer3D->addChild(sprite); } } - + // set layer mask. - _layer3D->setCameraMask((unsigned short)CameraFlag::USER1); - + _layer3D->setCameraMask( (unsigned short) CameraFlag::USER1); + // update sprite number char szText[16]; - sprintf(szText, "%d sprits", static_cast(_layer3D->getChildrenCount())); + sprintf(szText,"%d sprits", static_cast(_layer3D->getChildrenCount())); _labelSprite3DCount->setString(szText); } void CameraCullingDemo::delSpriteCallback(Ref* sender) { - if (_row == 0) - return; - + if (_row == 0) return; + _layer3D->removeAllChildren(); _objects.clear(); - + --_row; for (int x = -_row; x < _row; x++) { @@ -919,13 +922,13 @@ void CameraCullingDemo::delSpriteCallback(Ref* sender) _layer3D->addChild(sprite); } } - + // set layer mask. - _layer3D->setCameraMask((unsigned short)CameraFlag::USER1); - + _layer3D->setCameraMask((unsigned short) CameraFlag::USER1); + // update sprite number char szText[16]; - sprintf(szText, "%l sprits", static_cast(_layer3D->getChildrenCount())); + sprintf(szText,"%l sprits", static_cast(_layer3D->getChildrenCount())); _labelSprite3DCount->setString(szText); } @@ -933,47 +936,47 @@ void CameraCullingDemo::drawCameraFrustum() { _drawFrustum->clear(); auto size = Director::getInstance()->getWinSize(); - + Color4F color(1.f, 1.f, 0.f, 1); - + // top-left - Vec3 tl_0, tl_1; - Vec3 src(0, 0, 0); + Vec3 tl_0,tl_1; + Vec3 src(0,0,0); tl_0 = _cameraFirst->unproject(src); - src = Vec3(0, 0, 1); + src = Vec3(0,0,1); tl_1 = _cameraFirst->unproject(src); - + // top-right - Vec3 tr_0, tr_1; - src = Vec3(size.width, 0, 0); + Vec3 tr_0,tr_1; + src = Vec3(size.width,0,0); tr_0 = _cameraFirst->unproject(src); - src = Vec3(size.width, 0, 1); + src = Vec3(size.width,0,1); tr_1 = _cameraFirst->unproject(src); - + // bottom-left - Vec3 bl_0, bl_1; - src = Vec3(0, size.height, 0); + Vec3 bl_0,bl_1; + src = Vec3(0,size.height,0); bl_0 = _cameraFirst->unproject(src); - src = Vec3(0, size.height, 1); + src = Vec3(0,size.height,1); bl_1 = _cameraFirst->unproject(src); - + // bottom-right - Vec3 br_0, br_1; - src = Vec3(size.width, size.height, 0); + Vec3 br_0,br_1; + src = Vec3(size.width,size.height,0); br_0 = _cameraFirst->unproject(src); - src = Vec3(size.width, size.height, 1); + src = Vec3(size.width,size.height,1); br_1 = _cameraFirst->unproject(src); - + _drawFrustum->drawLine(tl_0, tl_1, color); _drawFrustum->drawLine(tr_0, tr_1, color); _drawFrustum->drawLine(bl_0, bl_1, color); _drawFrustum->drawLine(br_0, br_1, color); - + _drawFrustum->drawLine(tl_0, tr_0, color); _drawFrustum->drawLine(tr_0, br_0, color); _drawFrustum->drawLine(br_0, bl_0, color); _drawFrustum->drawLine(bl_0, tl_0, color); - + _drawFrustum->drawLine(tl_1, tr_1, color); _drawFrustum->drawLine(tr_1, br_1, color); _drawFrustum->drawLine(br_1, bl_1, color); @@ -983,20 +986,23 @@ void CameraCullingDemo::drawCameraFrustum() //////////////////////////////////////////////////////////// // CameraArcBallDemo CameraArcBallDemo::CameraArcBallDemo() - : CameraBaseTest() - , _layer3D(nullptr) - , _cameraType(CameraType::Free) - , _camera(nullptr) - , _drawGrid(nullptr) - , _radius(1.0f) - , _distanceZ(50.0f) - , _operate(OperateCamType::RotateCamera) - , _center(Vec3(0, 0, 0)) - , _target(0) - , _sprite3D1(nullptr) - , _sprite3D2(nullptr) -{} -CameraArcBallDemo::~CameraArcBallDemo() {} +: CameraBaseTest() +, _layer3D(nullptr) +, _cameraType(CameraType::Free) +, _camera(nullptr) +, _drawGrid(nullptr) +, _radius(1.0f) +, _distanceZ(50.0f) +, _operate(OperateCamType::RotateCamera) +, _center(Vec3(0,0,0)) +, _target(0) +, _sprite3D1(nullptr) +, _sprite3D2(nullptr) +{ +} +CameraArcBallDemo::~CameraArcBallDemo() +{ +} std::string CameraArcBallDemo::title() const { @@ -1008,34 +1014,32 @@ void CameraArcBallDemo::onEnter() CameraBaseTest::onEnter(); _rotationQuat.set(0.0f, 0.0f, 0.0f, 1.0f); schedule(CC_SCHEDULE_SELECTOR(CameraArcBallDemo::update), 0.0f); - auto s = Director::getInstance()->getWinSize(); - auto listener = EventListenerTouchAllAtOnce::create(); + auto s = Director::getInstance()->getWinSize(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesMoved = CC_CALLBACK_2(CameraArcBallDemo::onTouchsMoved, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // switch camera MenuItemFont::setFontName("fonts/arial.ttf"); MenuItemFont::setFontSize(20); - - auto menuItem1 = - MenuItemFont::create("Switch Operation", CC_CALLBACK_1(CameraArcBallDemo::switchOperateCallback, this)); - menuItem1->setColor(Color3B(0, 200, 20)); - auto menuItem2 = - MenuItemFont::create("Switch Target", CC_CALLBACK_1(CameraArcBallDemo::switchTargetCallback, this)); - menuItem2->setColor(Color3B(0, 200, 20)); - auto menu = Menu::create(menuItem1, menuItem2, NULL); + + auto menuItem1 = MenuItemFont::create("Switch Operation", CC_CALLBACK_1(CameraArcBallDemo::switchOperateCallback,this)); + menuItem1->setColor(Color3B(0,200,20)); + auto menuItem2 = MenuItemFont::create("Switch Target", CC_CALLBACK_1(CameraArcBallDemo::switchTargetCallback,this)); + menuItem2->setColor(Color3B(0,200,20)); + auto menu = Menu::create(menuItem1,menuItem2,NULL); menu->setPosition(Vec2::ZERO); - menuItem1->setPosition(VisibleRect::left().x + 80, VisibleRect::top().y - 70); - menuItem2->setPosition(VisibleRect::left().x + 80, VisibleRect::top().y - 100); + menuItem1->setPosition(VisibleRect::left().x + 80, VisibleRect::top().y -70); + menuItem2->setPosition(VisibleRect::left().x + 80, VisibleRect::top().y -100); addChild(menu, 1); - auto layer3D = Layer::create(); - addChild(layer3D, 0); - _layer3D = layer3D; + auto layer3D=Layer::create(); + addChild(layer3D,0); + _layer3D=layer3D; if (_camera == nullptr) { - _camera = Camera::createPerspective(60, (float)s.width / s.height, 1, 1000); + _camera=Camera::createPerspective(60, (float)s.width/s.height, 1, 1000); _camera->setCameraFlag(CameraFlag::USER1); _camera->setPosition3D(Vec3(0.0f, 10.0f, 50.0f)); _camera->lookAt(Vec3(0, 0, 0), Vec3(0.0f, 1.0f, 0.0f)); @@ -1045,35 +1049,36 @@ void CameraArcBallDemo::onEnter() _sprite3D1 = Sprite3D::create("Sprite3DTest/orc.c3b"); _sprite3D1->setScale(0.5); - _sprite3D1->setRotation3D(Vec3(0.0f, 180.0f, 0.0f)); - _sprite3D1->setPosition3D(Vec3(0, 0, 0)); + _sprite3D1->setRotation3D(Vec3(0.0f,180.0f,0.0f)); + _sprite3D1->setPosition3D(Vec3(0,0,0)); _layer3D->addChild(_sprite3D1); _sprite3D2 = Sprite3D::create("Sprite3DTest/boss.c3b"); _sprite3D2->setScale(0.6f); - _sprite3D2->setRotation3D(Vec3(-90.0f, 0.0f, 0.0f)); - _sprite3D2->setPosition3D(Vec3(20.0f, 0.0f, 0.0f)); + _sprite3D2->setRotation3D(Vec3(-90.0f,0.0f,0.0f)); + _sprite3D2->setPosition3D(Vec3(20.0f,0.0f,0.0f)); _layer3D->addChild(_sprite3D2); - _drawGrid = DrawNode3D::create(); + _drawGrid =DrawNode3D::create(); - // draw x - for (int j = -20; j <= 20; j++) + //draw x + for( int j =-20; j<=20 ;j++) { - _drawGrid->drawLine(Vec3(-100.0f, 0, 5.0f * j), Vec3(100.0f, 0, 5.0f * j), Color4F(1, 0, 0, 1)); + _drawGrid->drawLine(Vec3(-100.0f, 0, 5.0f*j),Vec3(100.0f,0,5.0f*j),Color4F(1,0,0,1)); } - // draw z - for (int j = -20; j <= 20; j++) + //draw z + for( int j =-20; j<=20 ;j++) { - _drawGrid->drawLine(Vec3(5.0f * j, 0, -100.0f), Vec3(5.0f * j, 0, 100.0f), Color4F(0, 0, 1, 1)); + _drawGrid->drawLine(Vec3(5.0f*j, 0, -100.0f),Vec3(5.0f*j,0,100.0f),Color4F(0,0,1,1)); } - // draw y - _drawGrid->drawLine(Vec3(0, 0, 0), Vec3(0, 50.0f, 0), Color4F(0, 1, 0, 1)); + //draw y + _drawGrid->drawLine(Vec3(0, 0, 0),Vec3(0,50.0f,0),Color4F(0,1,0,1)); _layer3D->addChild(_drawGrid); _layer3D->setCameraMask(2); updateCameraTransform(); + } void CameraArcBallDemo::onExit() @@ -1085,77 +1090,74 @@ void CameraArcBallDemo::onExit() } } -void CameraArcBallDemo::onTouchsMoved(const std::vector& touchs, Event* event) +void CameraArcBallDemo::onTouchsMoved( const std::vector &touchs, Event *event ) { if (!touchs.empty()) { - if (_operate == OperateCamType::RotateCamera) // arc ball rotate + if(_operate == OperateCamType::RotateCamera) //arc ball rotate { Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 prelocation = touchs[0]->getPreviousLocationInView(); - Vec2 location = touchs[0]->getLocationInView(); - location.x = 2.0f * (location.x) / (visibleSize.width) - 1.0f; - location.y = 2.0f * (visibleSize.height - location.y) / (visibleSize.height) - 1.0f; - prelocation.x = 2.0f * (prelocation.x) / (visibleSize.width) - 1.0f; - prelocation.y = 2.0f * (visibleSize.height - prelocation.y) / (visibleSize.height) - 1.0f; + Vec2 location = touchs[0]->getLocationInView(); + location.x = 2.0f * (location.x) / (visibleSize.width) - 1.0f; + location.y = 2.0f * (visibleSize.height - location.y) / (visibleSize.height) - 1.0f; + prelocation.x = 2.0f * (prelocation.x) / (visibleSize.width) - 1.0f; + prelocation.y = 2.0f * (visibleSize.height - prelocation.y) / (visibleSize.height) - 1.0f; Vec3 axes; float angle; - calculateArcBall(axes, angle, prelocation.x, prelocation.y, location.x, - location.y); // calculate rotation quaternion parameters - Quaternion quat(axes, angle); // get rotation quaternion + calculateArcBall(axes, angle, prelocation.x, prelocation.y, location.x, location.y); //calculate rotation quaternion parameters + Quaternion quat(axes, angle); //get rotation quaternion _rotationQuat = quat * _rotationQuat; - updateCameraTransform(); // update camera Transform + updateCameraTransform(); //update camera Transform } - else if (_operate == OperateCamType::MoveCamera) // camera zoom + else if(_operate == OperateCamType::MoveCamera) //camera zoom { Point newPos = touchs[0]->getPreviousLocation() - touchs[0]->getLocation(); - _distanceZ -= newPos.y * 0.1f; + _distanceZ -= newPos.y*0.1f; updateCameraTransform(); } } } -void CameraArcBallDemo::calculateArcBall(cocos2d::Vec3& axis, float& angle, float p1x, float p1y, float p2x, float p2y) +void CameraArcBallDemo::calculateArcBall( cocos2d::Vec3 & axis, float & angle, float p1x, float p1y, float p2x, float p2y ) { Mat4 rotation_matrix; Mat4::createRotation(_rotationQuat, &rotation_matrix); - Vec3 uv = rotation_matrix * Vec3(0.0f, 1.0f, 0.0f); // rotation y - Vec3 sv = rotation_matrix * Vec3(1.0f, 0.0f, 0.0f); // rotation x - Vec3 lv = rotation_matrix * Vec3(0.0f, 0.0f, -1.0f); // rotation z + Vec3 uv = rotation_matrix * Vec3(0.0f,1.0f,0.0f); //rotation y + Vec3 sv = rotation_matrix * Vec3(1.0f,0.0f,0.0f); //rotation x + Vec3 lv = rotation_matrix * Vec3(0.0f,0.0f,-1.0f);//rotation z - Vec3 p1 = sv * p1x + uv * p1y - lv * projectToSphere(_radius, p1x, p1y); // start point screen transform to 3d - Vec3 p2 = sv * p2x + uv * p2y - lv * projectToSphere(_radius, p2x, p2y); // end point screen transform to 3d + Vec3 p1 = sv * p1x + uv * p1y - lv * projectToSphere(_radius, p1x, p1y); //start point screen transform to 3d + Vec3 p2 = sv * p2x + uv * p2y - lv * projectToSphere(_radius, p2x, p2y); //end point screen transform to 3d - Vec3::cross(p2, p1, &axis); // calculate rotation axis + Vec3::cross(p2, p1, &axis); //calculate rotation axis axis.normalize(); float t = (p2 - p1).length() / (2.0f * _radius); - // clamp -1 to 1 - if (t > 1.0) - t = 1.0; - if (t < -1.0) - t = -1.0; - angle = asin(t); // rotation angle + //clamp -1 to 1 + if (t > 1.0) t = 1.0; + if (t < -1.0) t = -1.0; + angle = asin(t); //rotation angle } /* project an x,y pair onto a sphere of radius r or a hyperbolic sheet if we are away from the center of the sphere. */ -float CameraArcBallDemo::projectToSphere(float r, float x, float y) +float CameraArcBallDemo::projectToSphere( float r, float x, float y ) { float d, t, z; - d = sqrt(x * x + y * y); - if (d < r * 0.70710678118654752440) // inside sphere + d = sqrt(x*x + y*y); + if (d < r * 0.70710678118654752440)//inside sphere { - z = sqrt(r * r - d * d); - } - else // on hyperbola + z = sqrt(r*r - d*d); + } + else //on hyperbola { t = r / 1.41421356237309504880f; - z = t * t / d; + z = t*t / d; } return z; } @@ -1172,11 +1174,11 @@ void CameraArcBallDemo::updateCameraTransform() void CameraArcBallDemo::switchOperateCallback(Ref* sender) { - if (_operate == OperateCamType::MoveCamera) + if(_operate == OperateCamType::MoveCamera) { _operate = OperateCamType::RotateCamera; } - else if (_operate == OperateCamType::RotateCamera) + else if(_operate == OperateCamType::RotateCamera) { _operate = OperateCamType::MoveCamera; } @@ -1184,13 +1186,13 @@ void CameraArcBallDemo::switchOperateCallback(Ref* sender) void CameraArcBallDemo::switchTargetCallback(Ref* sender) { - if (_target == 0) + if(_target == 0) { _target = 1; _center = _sprite3D2->getPosition3D(); updateCameraTransform(); } - else if (_target == 1) + else if(_target == 1) { _target = 0; _center = _sprite3D1->getPosition3D(); @@ -1200,12 +1202,15 @@ void CameraArcBallDemo::switchTargetCallback(Ref* sender) void CameraArcBallDemo::update(float dt) { - // updateCameraTransform(); + //updateCameraTransform(); } //////////////////////////////////////////////////////////// // FogTestDemo -FogTestDemo::FogTestDemo() : CameraBaseTest() {} +FogTestDemo::FogTestDemo() +: CameraBaseTest() +{ +} FogTestDemo::~FogTestDemo() { CC_SAFE_RELEASE_NULL(_programState1); @@ -1221,152 +1226,159 @@ void FogTestDemo::onEnter() { CameraBaseTest::onEnter(); schedule(CC_SCHEDULE_SELECTOR(FogTestDemo::update), 0.0f); - Director::getInstance()->setClearColor(Color4F(0.5, 0.5, 0.5, 1)); + Director::getInstance()->setClearColor(Color4F(0.5,0.5,0.5,1)); - auto s = Director::getInstance()->getWinSize(); - auto listener = EventListenerTouchAllAtOnce::create(); + auto s = Director::getInstance()->getWinSize(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesMoved = CC_CALLBACK_2(FogTestDemo::onTouchesMoved, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // switch fog type TTFConfig ttfConfig("fonts/arial.ttf", 20); - - auto label1 = Label::createWithTTF(ttfConfig, "Linear "); - auto menuItem1 = MenuItemLabel::create(label1, CC_CALLBACK_1(FogTestDemo::switchTypeCallback, this, 0)); - auto label2 = Label::createWithTTF(ttfConfig, "Exp"); - auto menuItem2 = MenuItemLabel::create(label2, CC_CALLBACK_1(FogTestDemo::switchTypeCallback, this, 1)); - auto label3 = Label::createWithTTF(ttfConfig, "Exp2"); - auto menuItem3 = MenuItemLabel::create(label3, CC_CALLBACK_1(FogTestDemo::switchTypeCallback, this, 2)); - auto menu = Menu::create(menuItem1, menuItem2, menuItem3, nullptr); - + + auto label1 = Label::createWithTTF(ttfConfig,"Linear "); + auto menuItem1 = MenuItemLabel::create(label1, CC_CALLBACK_1(FogTestDemo::switchTypeCallback,this,0)); + auto label2 = Label::createWithTTF(ttfConfig,"Exp"); + auto menuItem2 = MenuItemLabel::create(label2, CC_CALLBACK_1(FogTestDemo::switchTypeCallback,this,1)); + auto label3 = Label::createWithTTF(ttfConfig,"Exp2"); + auto menuItem3 = MenuItemLabel::create(label3, CC_CALLBACK_1(FogTestDemo::switchTypeCallback,this,2)); + auto menu = Menu::create(menuItem1, menuItem2, menuItem3, nullptr); + menu->setPosition(Vec2::ZERO); - - menuItem1->setPosition(VisibleRect::left().x + 60, VisibleRect::top().y - 50); - menuItem2->setPosition(VisibleRect::left().x + 60, VisibleRect::top().y - 100); - menuItem3->setPosition(VisibleRect::left().x + 60, VisibleRect::top().y - 150); + + menuItem1->setPosition(VisibleRect::left().x+60, VisibleRect::top().y-50); + menuItem2->setPosition(VisibleRect::left().x+60, VisibleRect::top().y -100); + menuItem3->setPosition(VisibleRect::left().x+60, VisibleRect::top().y -150); addChild(menu, 0); - auto layer3D = Layer::create(); - addChild(layer3D, 0); - _layer3D = layer3D; + + auto layer3D=Layer::create(); + addChild(layer3D,0); + _layer3D=layer3D; CC_SAFE_RELEASE_NULL(_programState1); CC_SAFE_RELEASE_NULL(_programState2); auto vertexSource = FileUtils::getInstance()->getStringFromFile("Sprite3DTest/fog.vert"); - auto fragSource = FileUtils::getInstance()->getStringFromFile("Sprite3DTest/fog.frag"); - auto program = backend::Device::getInstance()->newProgram(vertexSource, fragSource); - _programState1 = new backend::ProgramState(program); - _programState2 = new backend::ProgramState(program); + auto fragSource = FileUtils::getInstance()->getStringFromFile("Sprite3DTest/fog.frag"); + auto program = backend::Device::getInstance()->newProgram(vertexSource, fragSource); + _programState1 = new backend::ProgramState(program); + _programState2 = new backend::ProgramState(program); CC_SAFE_RELEASE(program); - + _sprite3D1 = Sprite3D::create("Sprite3DTest/teapot.c3b"); _sprite3D2 = Sprite3D::create("Sprite3DTest/teapot.c3b"); _sprite3D1->setProgramState(_programState1); _sprite3D2->setProgramState(_programState2); - auto fogColor = Vec4(0.5, 0.5, 0.5, 1.0); - float fogStart = 10; - float fogEnd = 60; - int fogEquation = 0; + auto fogColor = Vec4(0.5, 0.5, 0.5, 1.0); + float fogStart = 10; + float fogEnd = 60; + int fogEquation = 0; - SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); - SET_UNIFORM("u_fogStart", &fogStart, sizeof(fogStart)); - SET_UNIFORM("u_fogEnd", &fogEnd, sizeof(fogEnd)); - SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); + SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); + SET_UNIFORM("u_fogStart", &fogStart, sizeof(fogStart)); + SET_UNIFORM("u_fogEnd", &fogEnd, sizeof(fogEnd)); + SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); _layer3D->addChild(_sprite3D1); - _sprite3D1->setPosition3D(Vec3(0, 0, 0)); + _sprite3D1->setPosition3D( Vec3( 0, 0,0 ) ); _sprite3D1->setScale(2.0f); - _sprite3D1->setRotation3D(Vec3(-90.0f, 180.0f, 0.0f)); + _sprite3D1->setRotation3D(Vec3(-90.0f,180.0f,0.0f)); _layer3D->addChild(_sprite3D2); - _sprite3D2->setPosition3D(Vec3(0.0f, 0.0f, -20.0f)); + _sprite3D2->setPosition3D( Vec3( 0.0f, 0.0f,-20.0f) ); _sprite3D2->setScale(2.0f); - _sprite3D2->setRotation3D(Vec3(-90.0f, 180.0f, 0.0f)); + _sprite3D2->setRotation3D(Vec3(-90.0f,180.0f,0.0f)); if (_camera == nullptr) { - _camera = Camera::createPerspective(60, (float)s.width / s.height, 1, 1000); + _camera=Camera::createPerspective(60, (float)s.width/s.height, 1, 1000); _camera->setCameraFlag(CameraFlag::USER1); _camera->setPosition3D(Vec3(0.0f, 30.0f, 40.0f)); - _camera->lookAt(Vec3(0, 0, 0), Vec3(0.0f, 1.0f, 0.0f)); + _camera->lookAt(Vec3(0,0,0), Vec3(0.0f, 1.0f, 0.0f)); _layer3D->addChild(_camera); } _layer3D->setCameraMask(2); + #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) - _backToForegroundListener = EventListenerCustom::create(EVENT_RENDERER_RECREATED, [this](EventCustom*) { - Director::getInstance()->setClearColor(Color4F(0.5, 0.5, 0.5, 1)); - CC_SAFE_RELEASE_NULL(_programState1); - CC_SAFE_RELEASE_NULL(_programState2); + _backToForegroundListener = EventListenerCustom::create(EVENT_RENDERER_RECREATED, + [this](EventCustom*) + { + Director::getInstance()->setClearColor(Color4F(0.5,0.5,0.5,1)); + CC_SAFE_RELEASE_NULL(_programState1); + CC_SAFE_RELEASE_NULL(_programState2); - auto vertexSource = FileUtils::getInstance()->getStringFromFile("Sprite3DTest/fog.vert"); - auto fragSource = FileUtils::getInstance()->getStringFromFile("Sprite3DTest/fog.frag"); - auto program = backend::Device::getInstance()->newProgram(vertexSource, fragSource); - _programState1 = new backend::ProgramState(program); - _programState2 = new backend::ProgramState(program); + auto vertexSource = FileUtils::getInstance()->getStringFromFile("Sprite3DTest/fog.vert"); + auto fragSource = FileUtils::getInstance()->getStringFromFile("Sprite3DTest/fog.frag"); + auto program = backend::Device::getInstance()->newProgram(vertexSource, fragSource); + _programState1 = new backend::ProgramState(program); + _programState2 = new backend::ProgramState(program); - _sprite3D1->setProgramState(_programState1); - _sprite3D2->setProgramState(_programState2); - CC_SAFE_RELEASE(program); + _sprite3D1->setProgramState(_programState1); + _sprite3D2->setProgramState(_programState2); + CC_SAFE_RELEASE(program); + + auto fogColor = Vec4(0.5, 0.5, 0.5, 1.0); + float fogStart = 10; + float fogEnd = 60; + int fogEquation = 0; - auto fogColor = Vec4(0.5, 0.5, 0.5, 1.0); - float fogStart = 10; - float fogEnd = 60; - int fogEquation = 0; - - SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); - SET_UNIFORM("u_fogStart", &fogStart, sizeof(fogStart)); - SET_UNIFORM("u_fogEnd", &fogEnd, sizeof(fogEnd)); - SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); - }); + SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); + SET_UNIFORM("u_fogStart", &fogStart, sizeof(fogStart)); + SET_UNIFORM("u_fogEnd", &fogEnd, sizeof(fogEnd)); + SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); + } + ); Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(_backToForegroundListener, -1); #endif + } -void FogTestDemo::switchTypeCallback(Ref* sender, int type) +void FogTestDemo::switchTypeCallback(Ref* sender,int type) { - if (type == 0) + if(type == 0) { auto fogColor = Vec4(0.5, 0.5, 0.5, 1.0); float fogStart = 10; float fogEnd = 60; int fogEquation = 0; - SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); - SET_UNIFORM("u_fogStart", &fogStart, sizeof(fogStart)); - SET_UNIFORM("u_fogEnd", &fogEnd, sizeof(fogEnd)); - SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); - } - else if (type == 1) - { - auto fogColor = Vec4(0.5, 0.5, 0.5, 1.0); - float fogDensity = 0.03f; - int fogEquation = 1; + SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); + SET_UNIFORM("u_fogStart", &fogStart, sizeof(fogStart)); + SET_UNIFORM("u_fogEnd", &fogEnd, sizeof(fogEnd)); + SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); - SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); - SET_UNIFORM("u_fogDensity", &fogDensity, sizeof(fogDensity)); - SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); } - else if (type == 2) + else if(type == 1) { - auto fogColor = Vec4(0.5, 0.5, 0.5, 1.0); - float fogDensity = 0.03f; - int fogEquation = 2; + auto fogColor = Vec4(0.5, 0.5, 0.5, 1.0); + float fogDensity = 0.03f; + int fogEquation = 1; - SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); - SET_UNIFORM("u_fogDensity", &fogDensity, sizeof(fogDensity)); - SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); + SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); + SET_UNIFORM("u_fogDensity", &fogDensity, sizeof(fogDensity)); + SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); + } + else if(type == 2) + { + auto fogColor = Vec4(0.5, 0.5, 0.5, 1.0); + float fogDensity = 0.03f; + int fogEquation = 2; + + SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); + SET_UNIFORM("u_fogDensity", &fogDensity, sizeof(fogDensity)); + SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); } } void FogTestDemo::onExit() { CameraBaseTest::onExit(); - Director::getInstance()->setClearColor(Color4F(0, 0, 0, 1)); + Director::getInstance()->setClearColor(Color4F(0,0,0,1)); if (_camera) { _camera = nullptr; @@ -1377,102 +1389,108 @@ void FogTestDemo::onExit() #endif } -void FogTestDemo::update(float dt) {} - -void FogTestDemo::onTouchesMoved(const std::vector& touches, cocos2d::Event* event) +void FogTestDemo::update(float dt) { - if (touches.size() == 1) +} + +void FogTestDemo::onTouchesMoved(const std::vector& touches, cocos2d::Event *event) +{ + if(touches.size()==1) { Vec2 prelocation = touches[0]->getPreviousLocationInView(); - Vec2 location = touches[0]->getLocationInView(); - Vec2 newPos = prelocation - location; - if (_cameraType == CameraType::Free) + Vec2 location = touches[0]->getLocationInView(); + Vec2 newPos = prelocation - location; + if(_cameraType==CameraType::Free) { Vec3 cameraDir; Vec3 cameraRightDir; _camera->getNodeToWorldTransform().getForwardVector(&cameraDir); cameraDir.normalize(); - cameraDir.y = 0; + cameraDir.y=0; _camera->getNodeToWorldTransform().getRightVector(&cameraRightDir); cameraRightDir.normalize(); - cameraRightDir.y = 0; - Vec3 cameraPos = _camera->getPosition3D(); - cameraPos -= cameraDir * newPos.y * 0.1f; - cameraPos += cameraRightDir * newPos.x * 0.1f; + cameraRightDir.y=0; + Vec3 cameraPos= _camera->getPosition3D(); + cameraPos-=cameraDir*newPos.y*0.1f; + cameraPos+=cameraRightDir*newPos.x*0.1f; _camera->setPosition3D(cameraPos); } } } -// CameraFrameBufferTest::CameraFrameBufferTest() +//CameraFrameBufferTest::CameraFrameBufferTest() //{ +// +//} // -// } -// -// CameraFrameBufferTest::~CameraFrameBufferTest() +//CameraFrameBufferTest::~CameraFrameBufferTest() //{ +// +//} // -// } -// -// std::string CameraFrameBufferTest::title() const +//std::string CameraFrameBufferTest::title() const //{ -// return "Camera FrameBuffer Object Test"; -// } +// return "Camera FrameBuffer Object Test"; +//} // -// void CameraFrameBufferTest::onEnter() +//void CameraFrameBufferTest::onEnter() //{ -// auto sizeInpixels = Director::getInstance()->getWinSizeInPixels(); -// auto size = Director::getInstance()->getWinSize(); -// auto fboSize = Size(sizeInpixels.width * 1, sizeInpixels.height * 1.5); -// auto fbo = experimental::FrameBuffer::create(1, fboSize.width, fboSize.height); -// -// CameraBaseTest::onEnter(); -// //auto sprite = Sprite::createWithTexture(fbo); -// //sprite->setPosition(Vec2(100,100)); -// //std::string filename = "Sprite3DTest/girl.c3b"; -// //auto sprite = Sprite3D::create(filename); -// //sprite->setScale(1.0); -// //auto animation = Animation3D::create(filename); -// //if (animation) -// //{ -// // auto animate = Animate3D::create(animation); -// -// // sprite->runAction(RepeatForever::create(animate)); -// //} -// //sprite->setPosition(Vec2(100,100)); -// auto rt = experimental::RenderTarget::create(fboSize.width, fboSize.height); -// auto rtDS = experimental::RenderTargetDepthStencil::create(fboSize.width, fboSize.height); -// fbo->attachRenderTarget(rt); -// fbo->attachDepthStencilTarget(rtDS); -// auto sprite = Sprite::createWithTexture(fbo->getRenderTarget()->getTexture()); -// sprite->setScale(0.3f); -// sprite->runAction(RepeatForever::create(RotateBy::create(1, 90))); -// sprite->setPosition(size.width/2, size.height/2); -// addChild(sprite); -// -// auto sprite2 = Sprite::create(s_pathGrossini); -// sprite2->setPosition(Vec2(size.width/5,size.height/5)); -// addChild(sprite2); -// sprite2->setCameraMask((unsigned short)CameraFlag::USER1); -// auto move = MoveBy::create(1.0, Vec2(100,100)); -// sprite2->runAction( -// RepeatForever::create( -// Sequence::createWithTwoActions( -// move, move->reverse()) -// ) -// ); -// -// auto camera = Camera::create(); -// camera->setCameraFlag(CameraFlag::USER1); -// camera->setDepth(-1); -// camera->setFrameBufferObject(fbo); -// fbo->setClearColor(Color4F(1,1,1,1)); -// addChild(camera); -// } +// auto sizeInpixels = Director::getInstance()->getWinSizeInPixels(); +// auto size = Director::getInstance()->getWinSize(); +// auto fboSize = Size(sizeInpixels.width * 1, sizeInpixels.height * 1.5); +// auto fbo = experimental::FrameBuffer::create(1, fboSize.width, fboSize.height); +// +// CameraBaseTest::onEnter(); +// //auto sprite = Sprite::createWithTexture(fbo); +// //sprite->setPosition(Vec2(100,100)); +// //std::string filename = "Sprite3DTest/girl.c3b"; +// //auto sprite = Sprite3D::create(filename); +// //sprite->setScale(1.0); +// //auto animation = Animation3D::create(filename); +// //if (animation) +// //{ +// // auto animate = Animate3D::create(animation); +// +// // sprite->runAction(RepeatForever::create(animate)); +// //} +// //sprite->setPosition(Vec2(100,100)); +// auto rt = experimental::RenderTarget::create(fboSize.width, fboSize.height); +// auto rtDS = experimental::RenderTargetDepthStencil::create(fboSize.width, fboSize.height); +// fbo->attachRenderTarget(rt); +// fbo->attachDepthStencilTarget(rtDS); +// auto sprite = Sprite::createWithTexture(fbo->getRenderTarget()->getTexture()); +// sprite->setScale(0.3f); +// sprite->runAction(RepeatForever::create(RotateBy::create(1, 90))); +// sprite->setPosition(size.width/2, size.height/2); +// addChild(sprite); +// +// auto sprite2 = Sprite::create(s_pathGrossini); +// sprite2->setPosition(Vec2(size.width/5,size.height/5)); +// addChild(sprite2); +// sprite2->setCameraMask((unsigned short)CameraFlag::USER1); +// auto move = MoveBy::create(1.0, Vec2(100,100)); +// sprite2->runAction( +// RepeatForever::create( +// Sequence::createWithTwoActions( +// move, move->reverse()) +// ) +// ); +// +// auto camera = Camera::create(); +// camera->setCameraFlag(CameraFlag::USER1); +// camera->setDepth(-1); +// camera->setFrameBufferObject(fbo); +// fbo->setClearColor(Color4F(1,1,1,1)); +// addChild(camera); +//} -BackgroundColorBrushTest::BackgroundColorBrushTest() {} +BackgroundColorBrushTest::BackgroundColorBrushTest() +{ +} -BackgroundColorBrushTest::~BackgroundColorBrushTest() {} +BackgroundColorBrushTest::~BackgroundColorBrushTest() +{ +} std::string BackgroundColorBrushTest::title() const { @@ -1487,18 +1505,18 @@ std::string BackgroundColorBrushTest::subtitle() const void BackgroundColorBrushTest::onEnter() { CameraBaseTest::onEnter(); - + auto s = Director::getInstance()->getWinSize(); - + { // 1st Camera - auto camera = Camera::createPerspective(60.0f, (float)s.width / s.height, 1.0f, 1000.0f); + auto camera = Camera::createPerspective(60.0f, (float)s.width/s.height, 1.0f, 1000.0f); camera->setPosition3D(Vec3(0.0f, 0.0f, 200.0f)); camera->lookAt(Vec3::ZERO); camera->setDepth(-2); camera->setCameraFlag(CameraFlag::USER1); addChild(camera); - + // 3D model auto model = Sprite3D::create("Sprite3DTest/boss1.obj"); model->setScale(4); @@ -1508,15 +1526,15 @@ void BackgroundColorBrushTest::onEnter() addChild(model); model->runAction(RepeatForever::create(RotateBy::create(1.f, Vec3(10.0f, 20.0f, 30.0f)))); } - + { auto base = Node::create(); base->setContentSize(s); base->setCameraMask(static_cast(CameraFlag::USER2)); addChild(base); - + // 2nd Camera - auto camera = Camera::createPerspective(60, (float)s.width / s.height, 1, 1000); + auto camera = Camera::createPerspective(60, (float)s.width/s.height, 1, 1000); auto colorBrush = CameraBackgroundBrush::createColorBrush(Color4F(.1f, .1f, 1.f, .5f), 1.f); camera->setBackgroundBrush(colorBrush); camera->setPosition3D(Vec3(0.0f, 0.0f, 200.0f)); @@ -1524,19 +1542,19 @@ void BackgroundColorBrushTest::onEnter() camera->setDepth(-1); camera->setCameraFlag(CameraFlag::USER2); base->addChild(camera); - + // for alpha setting auto slider = ui::Slider::create(); slider->loadBarTexture("cocosui/sliderTrack.png"); slider->loadSlidBallTextures("cocosui/sliderThumb.png", "cocosui/sliderThumb.png", ""); slider->loadProgressBarTexture("cocosui/sliderProgress.png"); - slider->setPosition(Vec2(s.width / 2, s.height / 4)); + slider->setPosition(Vec2(s.width/2, s.height/4)); slider->setPercent(50); - slider->addEventListener([slider, colorBrush](Ref*, ui::Slider::EventType) { - colorBrush->setColor(Color4F(.1f, .1f, 1.f, (float)slider->getPercent() / 100.f)); + slider->addEventListener([slider, colorBrush](Ref*, ui::Slider::EventType){ + colorBrush->setColor(Color4F(.1f, .1f, 1.f, (float)slider->getPercent()/100.f)); }); addChild(slider); - + // 3D model for 2nd camera auto model = Sprite3D::create("Sprite3DTest/boss1.obj"); model->setScale(4); diff --git a/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.h b/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.h index f15d82be42..75b4e244db 100644 --- a/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.h +++ b/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.h @@ -33,34 +33,33 @@ THE SOFTWARE. #include -namespace cocos2d -{ -class Sprite3D; -class Delay; -} // namespace cocos2d +namespace cocos2d { + class Sprite3D; + class Delay; +} enum State { - State_None = 0, - State_Idle = 0x01, - State_Move = 0x02, - State_Rotate = 0x04, - State_Speak = 0x08, - State_MeleeAttack = 0x10, + State_None = 0, + State_Idle = 0x01, + State_Move = 0x02, + State_Rotate = 0x04, + State_Speak = 0x08, + State_MeleeAttack = 0x10, State_RemoteAttack = 0x20, - State_Attack = 0x40, + State_Attack = 0x40, }; enum class CameraType { - Free = 0, + Free = 0, FirstPerson = 1, ThirdPerson = 2, }; enum class OperateCamType { - MoveCamera = 0, - RotateCamera = 1, + MoveCamera=0, + RotateCamera=1, }; DEFINE_TEST_SUITE(Camera3DTests); @@ -68,6 +67,7 @@ DEFINE_TEST_SUITE(Camera3DTests); class CameraBaseTest : public TestCase { public: + protected: cocos2d::BillBoard* bill1; cocos2d::BillBoard* bill2; @@ -75,8 +75,7 @@ protected: cocos2d::Label* l2; }; -class CameraRotationTest : public CameraBaseTest -{ +class CameraRotationTest : public CameraBaseTest { public: CREATE_FUNC(CameraRotationTest); @@ -93,6 +92,7 @@ public: virtual std::string subtitle() const override; protected: + cocos2d::Node* _camControlNode; cocos2d::Node* _camNode; cocos2d::EventListenerTouchOneByOne* _lis; @@ -109,46 +109,41 @@ public: virtual void onExit() override; // overrides virtual std::string title() const override; - void addNewSpriteWithCoords(cocos2d::Vec3 p, - std::string fileName, - bool playAnimation = false, - float scale = 1.0f, - bool bindCamera = false); + void addNewSpriteWithCoords(cocos2d::Vec3 p,std::string fileName,bool playAnimation=false,float scale=1.0f,bool bindCamera=false); - void onTouchesBegan(const std::vector& touches, cocos2d::Event* event); - void onTouchesMoved(const std::vector& touches, cocos2d::Event* event); - void onTouchesEnded(const std::vector& touches, cocos2d::Event* event); + void onTouchesBegan(const std::vector& touches, cocos2d::Event *event); + void onTouchesMoved(const std::vector& touches, cocos2d::Event *event); + void onTouchesEnded(const std::vector& touches, cocos2d::Event *event); - void scaleCameraCallback(cocos2d::Ref* sender, float value); - void rotateCameraCallback(cocos2d::Ref* sender, float value); - void SwitchViewCallback(cocos2d::Ref* sender, CameraType cameraType); + void scaleCameraCallback(cocos2d::Ref* sender,float value); + void rotateCameraCallback(cocos2d::Ref* sender,float value); + void SwitchViewCallback(cocos2d::Ref* sender,CameraType cameraType); void updateCamera(float fDelta); void move3D(float elapsedTime); void updateState(float elapsedTime); - bool isState(unsigned int state, unsigned int bit) const; + bool isState(unsigned int state,unsigned int bit) const; void reachEndCallBack(); - + bool onTouchesCommon(cocos2d::Touch* touch, cocos2d::Event* event, bool* touchProperty); bool onTouchesZoomOut(cocos2d::Touch* touch, cocos2d::Event* event); void onTouchesZoomOutEnd(cocos2d::Touch* touch, cocos2d::Event* event); bool onTouchesZoomIn(cocos2d::Touch* touch, cocos2d::Event* event); void onTouchesZoomInEnd(cocos2d::Touch* touch, cocos2d::Event* event); - + bool onTouchesRotateLeft(cocos2d::Touch* touch, cocos2d::Event* event); void onTouchesRotateLeftEnd(cocos2d::Touch* touch, cocos2d::Event* event); bool onTouchesRotateRight(cocos2d::Touch* touch, cocos2d::Event* event); void onTouchesRotateRightEnd(cocos2d::Touch* touch, cocos2d::Event* event); - protected: - std::string _title; - cocos2d::Layer* _layer3D; - cocos2d::Sprite3D* _sprite3D; - cocos2d::Vec3 _targetPos; - CameraType _cameraType; - cocos2d::MenuItem* _incRot; - cocos2d::MenuItem* _decRot; - unsigned int _curState; - cocos2d::Camera* _camera; + std::string _title; + cocos2d::Layer* _layer3D; + cocos2d::Sprite3D* _sprite3D; + cocos2d::Vec3 _targetPos; + CameraType _cameraType; + cocos2d::MenuItem* _incRot; + cocos2d::MenuItem* _decRot; + unsigned int _curState; + cocos2d::Camera* _camera; cocos2d::MoveTo* _moveAction; bool _bZoomOut; bool _bZoomIn; @@ -166,12 +161,12 @@ public: CREATE_FUNC(CameraCullingDemo); CameraCullingDemo(); virtual ~CameraCullingDemo(); - + virtual void onEnter() override; virtual void onExit() override; - + virtual void update(float dt) override; - + // overrides virtual std::string title() const override; void reachEndCallBack(); @@ -180,18 +175,18 @@ public: void delSpriteCallback(cocos2d::Ref* sender); void drawCameraFrustum(); - + protected: - cocos2d::Label* _labelSprite3DCount; - cocos2d::Layer* _layer3D; - std::vector _objects; - CameraType _cameraType; - cocos2d::Camera* _cameraFirst; - cocos2d::Camera* _cameraThird; - cocos2d::MoveBy* _moveAction; - cocos2d::DrawNode3D* _drawAABB; - cocos2d::DrawNode3D* _drawFrustum; - int _row; + cocos2d::Label* _labelSprite3DCount; + cocos2d::Layer* _layer3D; + std::vector _objects; + CameraType _cameraType; + cocos2d::Camera* _cameraFirst; + cocos2d::Camera* _cameraThird; + cocos2d::MoveBy* _moveAction; + cocos2d::DrawNode3D* _drawAABB; + cocos2d::DrawNode3D* _drawFrustum; + int _row; }; class CameraArcBallDemo : public CameraBaseTest @@ -200,40 +195,35 @@ public: CREATE_FUNC(CameraArcBallDemo); CameraArcBallDemo(); virtual ~CameraArcBallDemo(); - + virtual void onEnter() override; virtual void onExit() override; - + virtual void update(float dt) override; - + // overrides virtual std::string title() const override; void switchOperateCallback(cocos2d::Ref* sender); void switchTargetCallback(cocos2d::Ref* sender); - void onTouchsMoved(const std::vector& touchs, cocos2d::Event* event); + void onTouchsMoved(const std::vector &touchs, cocos2d::Event *event); void updateCameraTransform(); - void calculateArcBall(cocos2d::Vec3& axis, - float& angle, - float p1x, - float p1y, - float p2x, - float p2y); // calculate rotation quaternion parameters - float projectToSphere(float r, float x, float y); // points on the screen project to arc ball + void calculateArcBall( cocos2d::Vec3 & axis, float & angle, float p1x, float p1y, float p2x, float p2y );//calculate rotation quaternion parameters + float projectToSphere( float r, float x, float y );//points on the screen project to arc ball protected: - cocos2d::Layer* _layer3D; - CameraType _cameraType; - cocos2d::Camera* _camera; - cocos2d::DrawNode3D* _drawGrid; - cocos2d::Quaternion _rotationQuat; // rotation Quaternion - float _radius; // arc ball radius - float _distanceZ; - OperateCamType _operate; // switch rotate or zoom - cocos2d::Vec3 _center; // camera look target - int _target; // switch camera look target - cocos2d::Sprite3D* _sprite3D1; - cocos2d::Sprite3D* _sprite3D2; + cocos2d::Layer* _layer3D; + CameraType _cameraType; + cocos2d::Camera* _camera; + cocos2d::DrawNode3D* _drawGrid; + cocos2d::Quaternion _rotationQuat; //rotation Quaternion + float _radius; //arc ball radius + float _distanceZ; + OperateCamType _operate; //switch rotate or zoom + cocos2d::Vec3 _center; //camera look target + int _target; //switch camera look target + cocos2d::Sprite3D* _sprite3D1; + cocos2d::Sprite3D* _sprite3D2; }; class FogTestDemo : public CameraBaseTest @@ -242,44 +232,44 @@ public: CREATE_FUNC(FogTestDemo); FogTestDemo(); virtual ~FogTestDemo(); - + virtual void onEnter() override; virtual void onExit() override; - + virtual void update(float dt) override; - + // overrides virtual std::string title() const override; - void onTouchesMoved(const std::vector& touches, cocos2d::Event* event); - - void switchTypeCallback(cocos2d::Ref* sender, int type); + void onTouchesMoved(const std::vector& touches, cocos2d::Event *event); + void switchTypeCallback(cocos2d::Ref* sender,int type); + protected: - CameraType _cameraType = CameraType::Free; - cocos2d::Layer* _layer3D = nullptr; - cocos2d::Camera* _camera = nullptr; - cocos2d::Sprite3D* _sprite3D1 = nullptr; - cocos2d::Sprite3D* _sprite3D2 = nullptr; - cocos2d::backend::ProgramState* _programState1 = nullptr; - cocos2d::backend::ProgramState* _programState2 = nullptr; + CameraType _cameraType = CameraType::Free; + cocos2d::Layer* _layer3D = nullptr; + cocos2d::Camera* _camera = nullptr; + cocos2d::Sprite3D* _sprite3D1 = nullptr; + cocos2d::Sprite3D* _sprite3D2 = nullptr; + cocos2d::backend::ProgramState* _programState1 = nullptr; + cocos2d::backend::ProgramState* _programState2 = nullptr; #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) cocos2d::EventListenerCustom* _backToForegroundListener; #endif }; -// class CameraFrameBufferTest : public CameraBaseTest +//class CameraFrameBufferTest : public CameraBaseTest //{ -// public: -// CREATE_FUNC(CameraFrameBufferTest); -// CameraFrameBufferTest(); -// virtual ~CameraFrameBufferTest(); -// // overrides -// virtual std::string title() const override; -// -// virtual void onEnter() override; -// }; +//public: +// CREATE_FUNC(CameraFrameBufferTest); +// CameraFrameBufferTest(); +// virtual ~CameraFrameBufferTest(); +// // overrides +// virtual std::string title() const override; +// +// virtual void onEnter() override; +//}; class BackgroundColorBrushTest : public CameraBaseTest { @@ -287,10 +277,11 @@ public: CREATE_FUNC(BackgroundColorBrushTest); BackgroundColorBrushTest(); virtual ~BackgroundColorBrushTest(); - + // overrides virtual std::string title() const override; virtual std::string subtitle() const override; - + virtual void onEnter() override; }; + diff --git a/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.cpp b/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.cpp index fed2238abd..5e140b8fb8 100644 --- a/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.cpp +++ b/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.cpp @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. Copyright (c) 2021 @aismann; Peter Eismann, Germany; dreifrankensoft - + 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 @@ -33,33 +33,32 @@ #include "ChipmunkTest.h" + USING_NS_CC; USING_NS_CC_EXT; -enum -{ +enum { kTagParentNode = 1, }; -enum -{ +enum { Z_PHYSICS_DEBUG = 100, }; // callback to remove Shapes from the Space ChipmunkTest::ChipmunkTest() -{ +{ // enable events - auto touchListener = EventListenerTouchAllAtOnce::create(); + auto touchListener = EventListenerTouchAllAtOnce::create(); touchListener->onTouchesEnded = CC_CALLBACK_2(ChipmunkTest::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); - + Device::setAccelerometerEnabled(true); auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(ChipmunkTest::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this); - + // title auto label = Label::createWithTTF("Multi touch the screen", "fonts/Marker Felt.ttf", 36.0f); label->setPosition(VisibleRect::center().x, VisibleRect::top().y - 30); @@ -75,16 +74,16 @@ ChipmunkTest::ChipmunkTest() #if 1 // Use batch node. Faster - auto parent = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); + auto parent = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); _spriteTexture = parent->getTexture(); #else // doesn't use batch node. Slower _spriteTexture = Director::getInstance()->getTextureCache()->addImage("Images/grossini_dance_atlas.png"); - auto parent = Node::create(); + auto parent = Node::create(); #endif addChild(parent, 0, kTagParentNode); - addNewSpriteAtPosition(cocos2d::Vec2(200.0f, 200.0f)); + addNewSpriteAtPosition(cocos2d::Vec2(200.0f,200.0f)); // menu for debug layer MenuItemFont::setFontSize(18); @@ -92,28 +91,29 @@ ChipmunkTest::ChipmunkTest() auto menu = Menu::create(item, nullptr); this->addChild(menu); - menu->setPosition(VisibleRect::right().x - 100, VisibleRect::top().y - 60); + menu->setPosition(VisibleRect::right().x-100, VisibleRect::top().y-60); + scheduleUpdate(); + } void ChipmunkTest::toggleDebugCallback(Ref* sender) { - _debugLayer->setVisible(!_debugLayer->isVisible()); + _debugLayer->setVisible(! _debugLayer->isVisible()); } ChipmunkTest::~ChipmunkTest() { // manually Free rogue shapes - for (int i = 0; i < 4; i++) - { - cpShapeFree(_walls[i]); + for( int i=0;i<4;i++) { + cpShapeFree( _walls[i] ); } #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 - cpSpaceFree(_space); + cpSpaceFree(_space); #else - cpHastySpaceFree(_space); + cpHastySpaceFree(_space); #endif Device::setAccelerometerEnabled(false); @@ -123,13 +123,13 @@ void ChipmunkTest::initPhysics() { // init chipmunk - // cpInitChipmunk(); + //cpInitChipmunk(); #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 - _space = cpSpaceNew(); + _space = cpSpaceNew(); #else - _space = cpHastySpaceNew(); - cpHastySpaceSetThreads(_space, 0); + _space = cpHastySpaceNew(); + cpHastySpaceSetThreads(_space, 0); #endif cpSpaceSetGravity(_space, cpv(0.0f, -100.0f)); @@ -139,27 +139,27 @@ void ChipmunkTest::initPhysics() // We have to free them manually // // bottom - _walls[0] = - cpSegmentShapeNew(cpSpaceGetStaticBody(_space), cpv(VisibleRect::leftBottom().x, VisibleRect::leftBottom().y), - cpv(VisibleRect::rightBottom().x, VisibleRect::rightBottom().y), 0.0f); + _walls[0] = cpSegmentShapeNew( cpSpaceGetStaticBody(_space), + cpv(VisibleRect::leftBottom().x,VisibleRect::leftBottom().y), + cpv(VisibleRect::rightBottom().x, VisibleRect::rightBottom().y), 0.0f); // top - _walls[1] = cpSegmentShapeNew(cpSpaceGetStaticBody(_space), cpv(VisibleRect::leftTop().x, VisibleRect::leftTop().y), - cpv(VisibleRect::rightTop().x, VisibleRect::rightTop().y), 0.0f); + _walls[1] = cpSegmentShapeNew( cpSpaceGetStaticBody(_space), + cpv(VisibleRect::leftTop().x, VisibleRect::leftTop().y), + cpv(VisibleRect::rightTop().x, VisibleRect::rightTop().y), 0.0f); // left - _walls[2] = - cpSegmentShapeNew(cpSpaceGetStaticBody(_space), cpv(VisibleRect::leftBottom().x, VisibleRect::leftBottom().y), - cpv(VisibleRect::leftTop().x, VisibleRect::leftTop().y), 0.0f); + _walls[2] = cpSegmentShapeNew( cpSpaceGetStaticBody(_space), + cpv(VisibleRect::leftBottom().x,VisibleRect::leftBottom().y), + cpv(VisibleRect::leftTop().x,VisibleRect::leftTop().y), 0.0f); // right - _walls[3] = - cpSegmentShapeNew(cpSpaceGetStaticBody(_space), cpv(VisibleRect::rightBottom().x, VisibleRect::rightBottom().y), - cpv(VisibleRect::rightTop().x, VisibleRect::rightTop().y), 0.0f); - - for (int i = 0; i < 4; i++) - { + _walls[3] = cpSegmentShapeNew( cpSpaceGetStaticBody(_space), + cpv(VisibleRect::rightBottom().x, VisibleRect::rightBottom().y), + cpv(VisibleRect::rightTop().x, VisibleRect::rightTop().y), 0.0f); + for( int i=0;i<4;i++) { + cpShapeSetElasticity(_walls[i], 1.0f); cpShapeSetFriction(_walls[i], 1.0f); cpSpaceAddShape(_space, _walls[i]); @@ -168,21 +168,21 @@ void ChipmunkTest::initPhysics() // Physics debug layer _debugLayer = PhysicsDebugNodeChipmunk2D::create(_space); this->addChild(_debugLayer, Z_PHYSICS_DEBUG); + } void ChipmunkTest::update(float delta) { // Should use a fixed size step based on the animation interval. int steps = 2; - float dt = Director::getInstance()->getAnimationInterval() / (float)steps; + float dt = Director::getInstance()->getAnimationInterval()/(float)steps; - for (int i = 0; i < steps; i++) - { + for(int i=0; isetCPBody(body); sprite->setPosition(pos); + } void ChipmunkTest::onEnter() @@ -246,30 +248,30 @@ void ChipmunkTest::onEnter() void ChipmunkTest::onTouchesEnded(const std::vector& touches, Event* event) { - // Add a new body/atlas sprite at the touched location + //Add a new body/atlas sprite at the touched location - for (auto& touch : touches) + for( auto &touch: touches) { auto location = touch->getLocation(); - addNewSpriteAtPosition(location); + addNewSpriteAtPosition( location ); } } void ChipmunkTest::onAcceleration(Acceleration* acc, Event* event) { - static float prevX = 0, prevY = 0; + static float prevX=0, prevY=0; #define kFilterFactor 0.05f - float accelX = (float)acc->x * kFilterFactor + (1 - kFilterFactor) * prevX; - float accelY = (float)acc->y * kFilterFactor + (1 - kFilterFactor) * prevY; + float accelX = (float) acc->x * kFilterFactor + (1- kFilterFactor)*prevX; + float accelY = (float) acc->y * kFilterFactor + (1- kFilterFactor)*prevY; prevX = accelX; prevY = accelY; - auto v = cocos2d::Vec2(accelX, accelY); - v = v * 200; + auto v = cocos2d::Vec2( accelX, accelY); + v = v * 200; cpSpaceSetGravity(_space, cpv(v.x, v.y)); } @@ -277,3 +279,4 @@ ChipmunkTests::ChipmunkTests() { ADD_TEST_CASE(ChipmunkTest); } + diff --git a/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.h b/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.h index 9cc7c87ff2..b8d4bdea98 100644 --- a/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.h +++ b/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.h @@ -3,17 +3,17 @@ Copyright (c) 2021 @aismann; Peter Eismann, Germany; dreifrankensoft 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 @@ -53,10 +53,10 @@ public: virtual void onAcceleration(cocos2d::Acceleration* acc, cocos2d::Event* event); private: - cocos2d::Texture2D* _spriteTexture; // weak ref - cocos2d::extension::PhysicsDebugNodeChipmunk2D* _debugLayer; // weak ref + cocos2d::Texture2D* _spriteTexture; // weak ref + cocos2d::extension::PhysicsDebugNodeChipmunk2D* _debugLayer; // weak ref - cpSpace* _space; // strong ref + cpSpace* _space; // strong ref cpShape* _walls[4]; }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/ChipmunkTestBed.cpp b/tests/cpp-tests/Classes/ChipmunkTestBed/ChipmunkTestBed.cpp index f40ab497ca..cbab6df3ee 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/ChipmunkTestBed.cpp +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/ChipmunkTestBed.cpp @@ -20,6 +20,7 @@ THE SOFTWARE. ****************************************************************************/ + #include #include #include @@ -31,20 +32,20 @@ #include "ChipmunkTestBed.h" + USING_NS_CC; USING_NS_CC_EXT; -enum -{ - kTagParentNode = 1, +enum { + kTagParentNode = 1, }; -enum -{ - Z_PHYSICS_DEBUG = 100, +enum { + Z_PHYSICS_DEBUG = 100, }; -extern ChipmunkDemo Example; // Use as template for new Chipmunk2D demos + +extern ChipmunkDemo Example; // Use as template for new Chipmunk2D demos extern ChipmunkDemo LogoSmash; extern ChipmunkDemo PyramidStack; extern ChipmunkDemo Plink; @@ -72,431 +73,391 @@ extern ChipmunkDemo bench_list[]; extern int bench_count; int bench = 16; -static Vec2 cpVert2Point(const cpVect& vert) -{ - return Vec2(vert.x, vert.y) + physicsDebugNodeOffset; + +static Vec2 cpVert2Point(const cpVect& vert) { + return Vec2(vert.x, vert.y) + physicsDebugNodeOffset; } -ChipmunkDemo demos[] = {LogoSmash, PyramidStack, Plink, Tumble, PyramidTopple, Planet, - Springies, Pump, TheoJansen, Query, OneWay, Joints, - Tank, Chains, Crane, ContactGraph, Buoyancy, PlatformerPlayer, - Slice, Convex, Unicycle, Sticky, Shatter}; +ChipmunkDemo demos[] = { LogoSmash, PyramidStack, Plink, Tumble, PyramidTopple, Planet, Springies, Pump, TheoJansen, + Query, OneWay, Joints, Tank, Chains, Crane, ContactGraph, Buoyancy, PlatformerPlayer, Slice, Convex, Unicycle, + Sticky, Shatter }; int demo_count = sizeof(demos); cpVect ChipmunkDemoMouse; cpVect ChipmunkDemoKeyboard; cpBool ChipmunkDemoRightClick = cpFalse; -cpBool ChipmunkDemoRightDown = cpFalse; -cpBool ChipmunkDemoLeftDown = cpFalse; +cpBool ChipmunkDemoRightDown = cpFalse; +cpBool ChipmunkDemoLeftDown = cpFalse; double ChipmunkDemoTime; -cpBody* mouse_body = cpBodyNewKinematic(); +cpBody* mouse_body = cpBodyNewKinematic(); cpConstraint* mouse_joint = NULL; char const* ChipmunkDemoMessageString = NULL; #define GRABBABLE_MASK_BIT (1 << 31) -cpShapeFilter GRAB_FILTER = {CP_NO_GROUP, (unsigned int)GRABBABLE_MASK_BIT, (unsigned int)GRABBABLE_MASK_BIT}; -cpShapeFilter NOT_GRABBABLE_FILTER = {CP_NO_GROUP, ~GRABBABLE_MASK_BIT, ~GRABBABLE_MASK_BIT}; +cpShapeFilter GRAB_FILTER = { CP_NO_GROUP, (unsigned int)GRABBABLE_MASK_BIT, (unsigned int)GRABBABLE_MASK_BIT }; +cpShapeFilter NOT_GRABBABLE_FILTER = { CP_NO_GROUP, ~GRABBABLE_MASK_BIT, ~GRABBABLE_MASK_BIT }; + cocos2d::DrawNode* drawCP = NULL; -void ChipmunkDemoDefaultDrawImpl(cpSpace* space){}; +void ChipmunkDemoDefaultDrawImpl(cpSpace* space) {}; -void ChipmunkDebugDrawDot(cpFloat size, cpVect pos, cpSpaceDebugColor fillColor) -{ +void ChipmunkDebugDrawDot(cpFloat size, cpVect pos, cpSpaceDebugColor fillColor) { - drawCP->drawPoint(Vec2(pos.x, pos.y) + physicsDebugNodeOffset, size, - Color4F(fillColor.r, fillColor.g, fillColor.b, fillColor.a)); +drawCP->drawPoint(Vec2(pos.x, pos.y) + physicsDebugNodeOffset, size, Color4F(fillColor.r, fillColor.g, fillColor.b, fillColor.a)); } -void ChipmunkDebugDrawCircle(cpVect pos, - cpFloat angle, - cpFloat radius, - cpSpaceDebugColor outlineColor, - cpSpaceDebugColor fillColor) -{ +void ChipmunkDebugDrawCircle(cpVect pos, cpFloat angle, cpFloat radius, cpSpaceDebugColor outlineColor, cpSpaceDebugColor fillColor) { - drawCP->drawCircle(Vec2(pos.x, pos.y) + physicsDebugNodeOffset, 100, CC_DEGREES_TO_RADIANS(90), 50, true, 1.0f, - 2.0f, Color4F(fillColor.r, fillColor.g, fillColor.b, fillColor.a)); + drawCP->drawCircle(Vec2(pos.x, pos.y) + physicsDebugNodeOffset, 100, CC_DEGREES_TO_RADIANS(90), 50, true, 1.0f, + 2.0f, Color4F(fillColor.r, fillColor.g, fillColor.b, fillColor.a)); } -void ChipmunkDebugDrawSegment(cpVect a, cpVect b, cpSpaceDebugColor color) -{ - drawCP->drawLine(Vec2(a.x, a.y) + physicsDebugNodeOffset, Vec2(b.x, b.y) + physicsDebugNodeOffset, - Color4F(color.r, color.g, color.b, color.a)); +void ChipmunkDebugDrawSegment(cpVect a, cpVect b, cpSpaceDebugColor color) { + drawCP->drawLine(Vec2(a.x, a.y) + physicsDebugNodeOffset, Vec2(b.x, b.y) + physicsDebugNodeOffset, + Color4F(color.r, color.g, color.b, color.a)); } -void ChipmunkDebugDrawFatSegment(cpVect a, - cpVect b, - cpFloat radius, - cpSpaceDebugColor outlineColor, - cpSpaceDebugColor fillColor) -{ +void ChipmunkDebugDrawFatSegment(cpVect a, cpVect b, cpFloat radius, cpSpaceDebugColor outlineColor, cpSpaceDebugColor fillColor) { - drawCP->drawSegment(Vec2(a.x, a.y) + physicsDebugNodeOffset, Vec2(b.x, b.y) + physicsDebugNodeOffset, radius, - Color4F(outlineColor.r, outlineColor.g, outlineColor.b, outlineColor.a)); + drawCP->drawSegment(Vec2(a.x, a.y) + physicsDebugNodeOffset, Vec2(b.x, b.y) + physicsDebugNodeOffset, radius, + Color4F(outlineColor.r, outlineColor.g, outlineColor.b, outlineColor.a)); } -void ChipmunkDebugDrawPolygon(int count, - const cpVect* verts, - cpFloat radius, - cpSpaceDebugColor outlineColor, - cpSpaceDebugColor fillColor) -{ - Vec2* vec = new Vec2[count]; - for (size_t i = 0; i < count; i++) - { - vec[i] = cpVert2Point(verts[i]); - } - drawCP->drawPolygon(vec, count, Color4F(1.0f, 0.0f, 0.0f, 0.5f), radius, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); +void ChipmunkDebugDrawPolygon(int count, const cpVect* verts, cpFloat radius, cpSpaceDebugColor outlineColor, cpSpaceDebugColor fillColor) { - delete[] vec; + Vec2* vec = new Vec2[count]; + for (size_t i = 0; i < count; i++) { + vec[i] = cpVert2Point(verts[i]); + } + drawCP->drawPolygon(vec, count, Color4F(1.0f, 0.0f, 0.0f, 0.5f), radius, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); + + delete[] vec; } -void ChipmunkDebugDrawBB(cpBB bb, cpSpaceDebugColor color) -{ - Vec2 verts[] = { - Vec2(bb.r, bb.b) + physicsDebugNodeOffset, - Vec2(bb.r, bb.t) + physicsDebugNodeOffset, - Vec2(bb.l, bb.t) + physicsDebugNodeOffset, - Vec2(bb.l, bb.b) + physicsDebugNodeOffset, - }; - drawCP->drawPolygon(verts, sizeof(verts) / sizeof(verts[0]), Color4F(1.0f, 0.0f, 0.0f, 0.0f), 1, - Color4F(0.0f, 0.0f, 1.0f, 1.0f)); +void ChipmunkDebugDrawBB(cpBB bb, cpSpaceDebugColor color) { + Vec2 verts[] = { + Vec2(bb.r, bb.b) + physicsDebugNodeOffset, + Vec2(bb.r, bb.t) + physicsDebugNodeOffset, + Vec2(bb.l, bb.t) + physicsDebugNodeOffset, + Vec2(bb.l, bb.b) + physicsDebugNodeOffset, + }; + drawCP->drawPolygon(verts, sizeof(verts) / sizeof(verts[0]), Color4F(1.0f, 0.0f, 0.0f, 0.0f), 1, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); } + cocos2d::Label* label; -static int max_arbiters = 0; -static int max_points = 0; + +static int max_arbiters = 0; +static int max_points = 0; static int max_constraints = 0; -void ChipmunkTestBed::DrawInfo() -{ - int arbiters = _space->arbiters->num; - int points = 0; +void ChipmunkTestBed::DrawInfo() { + int arbiters = _space->arbiters->num; + int points = 0; - for (int i = 0; i < arbiters; i++) - points += ((cpArbiter*)(_space->arbiters->arr[i]))->count; + for (int i = 0; i < arbiters; i++) + points += ((cpArbiter*)(_space->arbiters->arr[i]))->count; - int constraints = (_space->constraints->num + points) * _space->iterations; + int constraints = (_space->constraints->num + points) * _space->iterations; - max_arbiters = arbiters > max_arbiters ? arbiters : max_arbiters; - max_points = points > max_points ? points : max_points; - max_constraints = constraints > max_constraints ? constraints : max_constraints; + max_arbiters = arbiters > max_arbiters ? arbiters : max_arbiters; + max_points = points > max_points ? points : max_points; + max_constraints = constraints > max_constraints ? constraints : max_constraints; - char buffer[1024]; - const char* format = - "Arbiters: %d (%d) - " - "Contact Points: %d (%d)\n" - "Other Constraints: %d, Iterations: %d\n" - "Constraints x Iterations: %d (%d)\n" - "Time:% 5.2fs, KE:% 5.2e"; + char buffer[1024]; + const char* format = "Arbiters: %d (%d) - " + "Contact Points: %d (%d)\n" + "Other Constraints: %d, Iterations: %d\n" + "Constraints x Iterations: %d (%d)\n" + "Time:% 5.2fs, KE:% 5.2e"; - cpArray* bodies = _space->dynamicBodies; - cpFloat ke = 0.0f; - for (int i = 0; i < bodies->num; i++) - { - cpBody* body = (cpBody*)bodies->arr[i]; - if (body->m == INFINITY || body->i == INFINITY) - continue; + cpArray* bodies = _space->dynamicBodies; + cpFloat ke = 0.0f; + for (int i = 0; i < bodies->num; i++) { + cpBody* body = (cpBody*)bodies->arr[i]; + if (body->m == INFINITY || body->i == INFINITY) + continue; - ke += body->m * cpvdot(body->v, body->v) + body->i * body->w * body->w; - } + ke += body->m * cpvdot(body->v, body->v) + body->i * body->w * body->w; + } - sprintf(buffer, format, arbiters, max_arbiters, points, max_points, _space->constraints->num, _space->iterations, - constraints, max_constraints, ChipmunkDemoTime, (ke < 1e-10f ? 0.0f : ke)); + sprintf(buffer, format, arbiters, max_arbiters, points, max_points, _space->constraints->num, _space->iterations, + constraints, max_constraints, ChipmunkDemoTime, (ke < 1e-10f ? 0.0f : ke)); - drawInfo->setString(buffer); + drawInfo->setString(buffer); } + static char PrintStringBuffer[1024 * 8]; static char* PrintStringCursor; -void ChipmunkDemoPrintString(char const* fmt, ...) -{ - if (PrintStringCursor == NULL) - { - return; - } +void ChipmunkDemoPrintString(char const* fmt, ...) { + if (PrintStringCursor == NULL) { + return; + } - ChipmunkDemoMessageString = PrintStringBuffer; + ChipmunkDemoMessageString = PrintStringBuffer; - va_list args; - va_start(args, fmt); - int remaining = sizeof(PrintStringBuffer) - (PrintStringCursor - PrintStringBuffer); - int would_write = vsnprintf(PrintStringCursor, remaining, fmt, args); - if (would_write > 0 && would_write < remaining) - { - PrintStringCursor += would_write; - } - else - { - // encoding error or overflow, prevent further use until reinitialized - PrintStringCursor = NULL; - } - va_end(args); + va_list args; + va_start(args, fmt); + int remaining = sizeof(PrintStringBuffer) - (PrintStringCursor - PrintStringBuffer); + int would_write = vsnprintf(PrintStringCursor, remaining, fmt, args); + if (would_write > 0 && would_write < remaining) { + PrintStringCursor += would_write; + } + else { + // encoding error or overflow, prevent further use until reinitialized + PrintStringCursor = NULL; + } + va_end(args); - label->setString(ChipmunkDemoMessageString); + label->setString(ChipmunkDemoMessageString); } -cpSpaceDebugColor RGBAColor(float r, float g, float b, float a) -{ - cpSpaceDebugColor color = {r, g, b, a}; - return color; +cpSpaceDebugColor RGBAColor(float r, float g, float b, float a) { + cpSpaceDebugColor color = { r, g, b, a }; + return color; }; -cpSpaceDebugColor LAColor(float l, float a) -{ - cpSpaceDebugColor color = {l, l, l, a}; - return color; +cpSpaceDebugColor LAColor(float l, float a) { + cpSpaceDebugColor color = { l, l, l, a }; + return color; } -static void ShapeFreeWrap(cpSpace* space, cpShape* shape, void* unused) -{ - cpSpaceRemoveShape(space, shape); - cpShapeFree(shape); + +static void ShapeFreeWrap(cpSpace* space, cpShape* shape, void* unused) { + cpSpaceRemoveShape(space, shape); + cpShapeFree(shape); } -static void PostShapeFree(cpShape* shape, cpSpace* space) -{ - cpSpaceAddPostStepCallback(space, (cpPostStepFunc)ShapeFreeWrap, shape, NULL); +static void PostShapeFree(cpShape* shape, cpSpace* space) { + cpSpaceAddPostStepCallback(space, (cpPostStepFunc)ShapeFreeWrap, shape, NULL); } -static void ConstraintFreeWrap(cpSpace* space, cpConstraint* constraint, void* unused) -{ - cpSpaceRemoveConstraint(space, constraint); - cpConstraintFree(constraint); +static void ConstraintFreeWrap(cpSpace* space, cpConstraint* constraint, void* unused) { + cpSpaceRemoveConstraint(space, constraint); + cpConstraintFree(constraint); } -static void PostConstraintFree(cpConstraint* constraint, cpSpace* space) -{ - cpSpaceAddPostStepCallback(space, (cpPostStepFunc)ConstraintFreeWrap, constraint, NULL); +static void PostConstraintFree(cpConstraint* constraint, cpSpace* space) { + cpSpaceAddPostStepCallback(space, (cpPostStepFunc)ConstraintFreeWrap, constraint, NULL); } -static void BodyFreeWrap(cpSpace* space, cpBody* body, void* unused) -{ - cpSpaceRemoveBody(space, body); - cpBodyFree(body); +static void BodyFreeWrap(cpSpace* space, cpBody* body, void* unused) { + cpSpaceRemoveBody(space, body); + cpBodyFree(body); } -static void PostBodyFree(cpBody* body, cpSpace* space) -{ - cpSpaceAddPostStepCallback(space, (cpPostStepFunc)BodyFreeWrap, body, NULL); +static void PostBodyFree(cpBody* body, cpSpace* space) { + cpSpaceAddPostStepCallback(space, (cpPostStepFunc)BodyFreeWrap, body, NULL); } // Safe and future proof way to remove and free all objects that have been added to the space. -void ChipmunkDemoFreeSpaceChildren(cpSpace* space) -{ - // Must remove these BEFORE freeing the body or you will access dangling pointers. - cpSpaceEachShape(space, (cpSpaceShapeIteratorFunc)PostShapeFree, space); - cpSpaceEachConstraint(space, (cpSpaceConstraintIteratorFunc)PostConstraintFree, space); - cpSpaceEachBody(space, (cpSpaceBodyIteratorFunc)PostBodyFree, space); +void ChipmunkDemoFreeSpaceChildren(cpSpace* space) { + // Must remove these BEFORE freeing the body or you will access dangling pointers. + cpSpaceEachShape(space, (cpSpaceShapeIteratorFunc)PostShapeFree, space); + cpSpaceEachConstraint(space, (cpSpaceConstraintIteratorFunc)PostConstraintFree, space); + cpSpaceEachBody(space, (cpSpaceBodyIteratorFunc)PostBodyFree, space); } -void updateMouseBody(void) -{ - cpVect new_point = cpvlerp(mouse_body->p, ChipmunkDemoMouse, 0.25f); - mouse_body->v = cpvmult(cpvsub(new_point, mouse_body->p), 60.0f); - mouse_body->p = new_point; + +void updateMouseBody(void) { + cpVect new_point = cpvlerp(mouse_body->p, ChipmunkDemoMouse, 0.25f); + mouse_body->v = cpvmult(cpvsub(new_point, mouse_body->p), 60.0f); + mouse_body->p = new_point; } -ChipmunkTestBed::ChipmunkTestBed() -{ - // halx99: since adxe init scene default camera at 'initWithXXX' function, only change design size at scene - // construct is ok see also: https://github.com/adxeproject/adxe/commit/581a7921554c09746616759d5a5ca6ce9d3eaa22 - auto director = Director::getInstance(); - auto glview = director->getOpenGLView(); - Size designSize(960 * 0.85, 640 * 0.85); - glview->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::NO_BORDER); +ChipmunkTestBed::ChipmunkTestBed() { + // halx99: since adxe init scene default camera at 'initWithXXX' function, only change design size at scene + // construct is ok see also: https://github.com/adxeproject/adxe/commit/581a7921554c09746616759d5a5ca6ce9d3eaa22 + auto director = Director::getInstance(); + auto glview = director->getOpenGLView(); + Size designSize(960 * 0.85, 640 * 0.85); + glview->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::NO_BORDER); - // creating a keyboard event listener - auto listener = EventListenerKeyboard::create(); - listener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event) { - if ((int)keyCode == 26) // Left - { - ChipmunkDemoKeyboard.x--; - } - if ((int)keyCode == 27) // Right - { - ChipmunkDemoKeyboard.x++; - } - if ((int)keyCode == 28) // Up - { - ChipmunkDemoKeyboard.y++; - } - if ((int)keyCode == 29) // Down - { - ChipmunkDemoKeyboard.y--; - } - }; + // creating a keyboard event listener + auto listener = EventListenerKeyboard::create(); + listener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event) { + if ((int)keyCode == 26) // Left + { + ChipmunkDemoKeyboard.x--; + } + if ((int)keyCode == 27) // Right + { + ChipmunkDemoKeyboard.x++; + } + if ((int)keyCode == 28) // Up + { + ChipmunkDemoKeyboard.y++; + } + if ((int)keyCode == 29) // Down + { + ChipmunkDemoKeyboard.y--; + } + }; - listener->onKeyReleased = [](EventKeyboard::KeyCode keyCode, Event* event) { ChipmunkDemoKeyboard = {0, 0}; }; + listener->onKeyReleased = [](EventKeyboard::KeyCode keyCode, Event* event) + { + ChipmunkDemoKeyboard = { 0, 0 }; + }; - _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - // creating a mouse event listener - _mouseListener = EventListenerMouse::create(); - _mouseListener->onMouseMove = CC_CALLBACK_1(ChipmunkTestBed::onMouseMove, this); - _mouseListener->onMouseUp = CC_CALLBACK_1(ChipmunkTestBed::onMouseUp, this); - _mouseListener->onMouseDown = CC_CALLBACK_1(ChipmunkTestBed::onMouseDown, this); - _eventDispatcher->addEventListenerWithSceneGraphPriority(_mouseListener, this); + // creating a mouse event listener + _mouseListener = EventListenerMouse::create(); + _mouseListener->onMouseMove = CC_CALLBACK_1(ChipmunkTestBed::onMouseMove, this); + _mouseListener->onMouseUp = CC_CALLBACK_1(ChipmunkTestBed::onMouseUp, this); + _mouseListener->onMouseDown = CC_CALLBACK_1(ChipmunkTestBed::onMouseDown, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(_mouseListener, this); - // Some info text - auto label1 = Label::createWithTTF("Use the mouse to grab objects.", "fonts/Marker Felt.ttf", 12.0f); - label1->setPosition(VisibleRect::center().x, VisibleRect::top().y - 100); - label1->setColor(Color3B::WHITE); - this->addChild(label1, 1000); + // Some info text + auto label1 = Label::createWithTTF("Use the mouse to grab objects.", "fonts/Marker Felt.ttf", 12.0f); + label1->setPosition(VisibleRect::center().x, VisibleRect::top().y - 100); + label1->setColor(Color3B::WHITE); + this->addChild(label1, 1000); - // ChipmunkDemoMessageString - label = Label::createWithTTF("", "fonts/Marker Felt.ttf", 12.0f); - label->setPosition(VisibleRect::center().x, VisibleRect::top().y - 130); - label->setColor(Color3B::MAGENTA); - this->addChild(label, 1000); + // ChipmunkDemoMessageString + label = Label::createWithTTF("", "fonts/Marker Felt.ttf", 12.0f); + label->setPosition(VisibleRect::center().x, VisibleRect::top().y - 130); + label->setColor(Color3B::MAGENTA); + this->addChild(label, 1000); - drawInfo = Label::createWithTTF("Use the mouse to grab objects.", "fonts/Marker Felt.ttf", 12.0f); - drawInfo->setAnchorPoint(Vec2(0, 0)); - drawInfo->setPosition(VisibleRect::left().x + 10, VisibleRect::top().y - 60); - drawInfo->setColor(Color3B::WHITE); - this->addChild(drawInfo, 1000); + drawInfo = Label::createWithTTF("Use the mouse to grab objects.", "fonts/Marker Felt.ttf", 12.0f); + drawInfo->setAnchorPoint(Vec2(0, 0)); + drawInfo->setPosition(VisibleRect::left().x + 10, VisibleRect::top().y - 60); + drawInfo->setColor(Color3B::WHITE); + this->addChild(drawInfo, 1000); - draw = DrawNode::create(); - addChild(draw, 100); - drawCP = draw; + draw = DrawNode::create(); + addChild(draw, 100); - scheduleUpdate(); + drawCP = draw; + + scheduleUpdate(); } + ChipmunkTestBed::~ChipmunkTestBed() { - ChipmunkDemoFreeSpaceChildren(_space); - _eventDispatcher->removeEventListener(_mouseListener); + ChipmunkDemoFreeSpaceChildren(_space); + _eventDispatcher->removeEventListener(_mouseListener); } -void ChipmunkTestBed::initPhysics() -{ - if (ChipmunkDemoMessageString) - { - label->setString(ChipmunkDemoMessageString); - } - else - { - label->setString(""); - } - drawCP->clear(); - // Physics debug layer - _debugLayer = PhysicsDebugNodeChipmunk2D::create(_space); - this->addChild(_debugLayer, Z_PHYSICS_DEBUG); + +void ChipmunkTestBed::initPhysics() { + if (ChipmunkDemoMessageString) { + label->setString(ChipmunkDemoMessageString); + } + else { + label->setString(""); + } + drawCP->clear(); + // Physics debug layer + _debugLayer = PhysicsDebugNodeChipmunk2D::create(_space); + this->addChild(_debugLayer, Z_PHYSICS_DEBUG); } -void ChipmunkTestBed::update(float delta) -{ - //#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 - // cpSpaceStep(_space, delta); - //#else - // cpHastySpaceStep(_space, delta); - //#endif +void ChipmunkTestBed::update(float delta) { + //#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + // cpSpaceStep(_space, delta); + //#else + // cpHastySpaceStep(_space, delta); + //#endif } -void ChipmunkTestBed::createResetButton() -{ - auto reset = MenuItemImage::create("Images/r1.png", "Images/r2.png", CC_CALLBACK_1(ChipmunkTestBed::reset, this)); - auto menu = Menu::create(reset, nullptr); - menu->setPosition(VisibleRect::center().x, VisibleRect::bottom().y); - this->addChild(menu, -1); +void ChipmunkTestBed::createResetButton() { + auto reset = MenuItemImage::create("Images/r1.png", "Images/r2.png", CC_CALLBACK_1(ChipmunkTestBed::reset, this)); + auto menu = Menu::create(reset, nullptr); + menu->setPosition(VisibleRect::center().x, VisibleRect::bottom().y); + this->addChild(menu, -1); } -void ChipmunkTestBed::reset(Ref* sender) -{ - ChipmunkDemoFreeSpaceChildren(_space); - getTestSuite()->restartCurrTest(); +void ChipmunkTestBed::reset(Ref* sender) { + ChipmunkDemoFreeSpaceChildren(_space); + getTestSuite()->restartCurrTest(); } -void ChipmunkTestBed::onEnter() -{ - TestCase::onEnter(); - physicsDebugNodeOffset = VisibleRect::center(); - physicsDebugNodeOffset.y += 20; - ChipmunkDemoMessageString = ""; - label->setString(""); +void ChipmunkTestBed::onEnter() { + TestCase::onEnter(); + physicsDebugNodeOffset = VisibleRect::center(); + physicsDebugNodeOffset.y += 20; + ChipmunkDemoMessageString = ""; + label->setString(""); } -void ChipmunkTestBed::onMouseDown(Event* event) -{ - EventMouse* e = (EventMouse*)event; - if ((int)e->getMouseButton() == 0) - { - ChipmunkDemoLeftDown = cpTrue; - // give the mouse click a little radius to make it easier to click small shapes. - cpFloat radius = 5.0; +void ChipmunkTestBed::onMouseDown(Event* event) { + EventMouse* e = (EventMouse*)event; - cpPointQueryInfo info = {0}; - cpShape* shape = cpSpacePointQueryNearest(_space, ChipmunkDemoMouse, radius, GRAB_FILTER, &info); + if ((int)e->getMouseButton() == 0) { + ChipmunkDemoLeftDown = cpTrue; + // give the mouse click a little radius to make it easier to click small shapes. + cpFloat radius = 5.0; - if (shape && cpBodyGetMass(cpShapeGetBody(shape)) < INFINITY) - { - // Use the closest point on the surface if the click is outside of the shape. - cpVect nearest = (info.distance > 0.0f ? info.point : ChipmunkDemoMouse); + cpPointQueryInfo info = { 0 }; + cpShape* shape = cpSpacePointQueryNearest(_space, ChipmunkDemoMouse, radius, GRAB_FILTER, &info); - cpBody* body = cpShapeGetBody(shape); - mouse_joint = cpPivotJointNew2(mouse_body, body, cpvzero, cpBodyWorldToLocal(body, nearest)); - mouse_joint->maxForce = 50000.0f; - mouse_joint->errorBias = cpfpow(1.0f - 0.15f, 60.0f); - cpSpaceAddConstraint(_space, mouse_joint); - } - } - else if ((int)e->getMouseButton() == 1) - { - if (mouse_joint) - { - cpSpaceRemoveConstraint(_space, mouse_joint); - cpConstraintFree(mouse_joint); - mouse_joint = NULL; - } - ChipmunkDemoRightDown = cpTrue; - ChipmunkDemoRightClick = cpTrue; - } + if (shape && cpBodyGetMass(cpShapeGetBody(shape)) < INFINITY) { + // Use the closest point on the surface if the click is outside of the shape. + cpVect nearest = (info.distance > 0.0f ? info.point : ChipmunkDemoMouse); + + cpBody* body = cpShapeGetBody(shape); + mouse_joint = cpPivotJointNew2(mouse_body, body, cpvzero, cpBodyWorldToLocal(body, nearest)); + mouse_joint->maxForce = 50000.0f; + mouse_joint->errorBias = cpfpow(1.0f - 0.15f, 60.0f); + cpSpaceAddConstraint(_space, mouse_joint); + } + } + else if ((int)e->getMouseButton() == 1) { + if (mouse_joint) { + cpSpaceRemoveConstraint(_space, mouse_joint); + cpConstraintFree(mouse_joint); + mouse_joint = NULL; + } + ChipmunkDemoRightDown = cpTrue; + ChipmunkDemoRightClick = cpTrue; + } } -void ChipmunkTestBed::onMouseUp(Event* event) -{ - EventMouse* e = (EventMouse*)event; - mousePresses = false; - if (mouse_joint) - { - cpSpaceRemoveConstraint(_space, mouse_joint); - cpConstraintFree(mouse_joint); - mouse_joint = NULL; - } - ChipmunkDemoLeftDown = cpFalse; - ChipmunkDemoRightDown = cpFalse; - ChipmunkDemoRightClick = cpFalse; +void ChipmunkTestBed::onMouseUp(Event* event) { + EventMouse* e = (EventMouse*)event; + mousePresses = false; + if (mouse_joint) { + cpSpaceRemoveConstraint(_space, mouse_joint); + cpConstraintFree(mouse_joint); + mouse_joint = NULL; + } + ChipmunkDemoLeftDown = cpFalse; + ChipmunkDemoRightDown = cpFalse; + ChipmunkDemoRightClick = cpFalse; } -void ChipmunkTestBed::onMouseMove(Event* event) -{ - EventMouse* e = (EventMouse*)event; +void ChipmunkTestBed::onMouseMove(Event* event) { + EventMouse* e = (EventMouse*)event; - ChipmunkDemoMouse.x = e->getCursorX() - physicsDebugNodeOffset.x; - ChipmunkDemoMouse.y = e->getCursorY() - physicsDebugNodeOffset.y; + ChipmunkDemoMouse.x = e->getCursorX() - physicsDebugNodeOffset.x; + ChipmunkDemoMouse.y = e->getCursorY() - physicsDebugNodeOffset.y; - cpBodySetPosition(mouse_body, ChipmunkDemoMouse); + cpBodySetPosition(mouse_body, ChipmunkDemoMouse); } -void ChipmunkTestBed::updateInit(ChipmunkDemo tt) -{ - PrintStringBuffer[0] = 0; - PrintStringCursor = PrintStringBuffer; - drawCP->clear(); - updateMouseBody(); - ChipmunkDemoTime += tt.timestep; - ChipmunkTestBed::DrawInfo(); - tt.updateFunc(_space, tt.timestep); +void ChipmunkTestBed::updateInit(ChipmunkDemo tt) { + PrintStringBuffer[0] = 0; + PrintStringCursor = PrintStringBuffer; + + + drawCP->clear(); + updateMouseBody(); + ChipmunkDemoTime += tt.timestep; + ChipmunkTestBed::DrawInfo(); + tt.updateFunc(_space, tt.timestep); } //------------------------------------------------------------------ @@ -504,26 +465,22 @@ void ChipmunkTestBed::updateInit(ChipmunkDemo tt) // LogoSmashDemo // //------------------------------------------------------------------ -void LogoSmashDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); - initPhysics(); +void LogoSmashDemo::onEnter() { + ChipmunkTestBed::onEnter(); + initPhysics(); } -std::string LogoSmashDemo::title() const -{ - return LogoSmash.name; +std::string LogoSmashDemo::title() const { + return LogoSmash.name; } -void LogoSmashDemo::initPhysics() -{ - _space = LogoSmash.initFunc(); - ChipmunkTestBed::initPhysics(); +void LogoSmashDemo::initPhysics() { + _space = LogoSmash.initFunc(); + ChipmunkTestBed::initPhysics(); } -void LogoSmashDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(LogoSmash); +void LogoSmashDemo::update(float delta) { + ChipmunkTestBed::updateInit(LogoSmash); } //------------------------------------------------------------------ @@ -531,27 +488,23 @@ void LogoSmashDemo::update(float delta) // PlinkDemo // //------------------------------------------------------------------ -void PlinkDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void PlinkDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string PlinkDemo::title() const -{ - return Plink.name; +std::string PlinkDemo::title() const { + return Plink.name; } -void PlinkDemo::initPhysics() -{ - _space = Plink.initFunc(); - ChipmunkTestBed::initPhysics(); +void PlinkDemo::initPhysics() { + _space = Plink.initFunc(); + ChipmunkTestBed::initPhysics(); } -void PlinkDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(Plink); +void PlinkDemo::update(float delta) { + ChipmunkTestBed::updateInit(Plink); } //------------------------------------------------------------------ @@ -559,26 +512,22 @@ void PlinkDemo::update(float delta) // TumbleDemo // //------------------------------------------------------------------ -void TumbleDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); - initPhysics(); +void TumbleDemo::onEnter() { + ChipmunkTestBed::onEnter(); + initPhysics(); } -std::string TumbleDemo::title() const -{ - return Tumble.name; +std::string TumbleDemo::title() const { + return Tumble.name; } -void TumbleDemo::initPhysics() -{ - _space = Tumble.initFunc(); - ChipmunkTestBed::initPhysics(); +void TumbleDemo::initPhysics() { + _space = Tumble.initFunc(); + ChipmunkTestBed::initPhysics(); } -void TumbleDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(Tumble); +void TumbleDemo::update(float delta) { + ChipmunkTestBed::updateInit(Tumble); } //------------------------------------------------------------------ @@ -586,81 +535,71 @@ void TumbleDemo::update(float delta) // PyramidStackDemo // //------------------------------------------------------------------ -void PyramidStackDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); - initPhysics(); +void PyramidStackDemo::onEnter() { + ChipmunkTestBed::onEnter(); + initPhysics(); } -std::string PyramidStackDemo::title() const -{ - return PyramidStack.name; +std::string PyramidStackDemo::title() const { + return PyramidStack.name; } -void PyramidStackDemo::initPhysics() -{ - _space = PyramidStack.initFunc(); - ChipmunkTestBed::initPhysics(); +void PyramidStackDemo::initPhysics() { + _space = PyramidStack.initFunc(); + ChipmunkTestBed::initPhysics(); } -void PyramidStackDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(PyramidStack); +void PyramidStackDemo::update(float delta) { + ChipmunkTestBed::updateInit(PyramidStack); } + //------------------------------------------------------------------ // // PyramidToppleDemo // //------------------------------------------------------------------ -void PyramidToppleDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); - initPhysics(); +void PyramidToppleDemo::onEnter() { + ChipmunkTestBed::onEnter(); + initPhysics(); } -std::string PyramidToppleDemo::title() const -{ - return PyramidTopple.name; +std::string PyramidToppleDemo::title() const { + return PyramidTopple.name; } -void PyramidToppleDemo::initPhysics() -{ - _space = PyramidTopple.initFunc(); - ChipmunkTestBed::initPhysics(); +void PyramidToppleDemo::initPhysics() { + _space = PyramidTopple.initFunc(); + ChipmunkTestBed::initPhysics(); } -void PyramidToppleDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(PyramidTopple); +void PyramidToppleDemo::update(float delta) { + ChipmunkTestBed::updateInit(PyramidTopple); } + //------------------------------------------------------------------ // // ChainDemo // //------------------------------------------------------------------ -void ChainsDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void ChainsDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string ChainsDemo::title() const -{ - return Chains.name; +std::string ChainsDemo::title() const { + return Chains.name; } -void ChainsDemo::initPhysics() -{ - _space = Chains.initFunc(); - ChipmunkTestBed::initPhysics(); +void ChainsDemo::initPhysics() { + _space = Chains.initFunc(); + ChipmunkTestBed::initPhysics(); } -void ChainsDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(Chains); +void ChainsDemo::update(float delta) { + ChipmunkTestBed::updateInit(Chains); } //------------------------------------------------------------------ @@ -668,27 +607,23 @@ void ChainsDemo::update(float delta) // OneWayDemo // //------------------------------------------------------------------ -void OneWayDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void OneWayDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string OneWayDemo::title() const -{ - return OneWay.name; +std::string OneWayDemo::title() const { + return OneWay.name; } -void OneWayDemo::initPhysics() -{ - _space = OneWay.initFunc(); - ChipmunkTestBed::initPhysics(); +void OneWayDemo::initPhysics() { + _space = OneWay.initFunc(); + ChipmunkTestBed::initPhysics(); } -void OneWayDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(OneWay); +void OneWayDemo::update(float delta) { + ChipmunkTestBed::updateInit(OneWay); } //------------------------------------------------------------------ @@ -696,27 +631,23 @@ void OneWayDemo::update(float delta) // PlanetDemo // //------------------------------------------------------------------ -void PlanetDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void PlanetDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string PlanetDemo::title() const -{ - return Planet.name; +std::string PlanetDemo::title() const { + return Planet.name; } -void PlanetDemo::initPhysics() -{ - _space = Planet.initFunc(); - ChipmunkTestBed::initPhysics(); +void PlanetDemo::initPhysics() { + _space = Planet.initFunc(); + ChipmunkTestBed::initPhysics(); } -void PlanetDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(Planet); +void PlanetDemo::update(float delta) { + ChipmunkTestBed::updateInit(Planet); } //------------------------------------------------------------------ @@ -724,170 +655,153 @@ void PlanetDemo::update(float delta) // TheoJansenDemo // //------------------------------------------------------------------ -void TheoJansenDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void TheoJansenDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string TheoJansenDemo::title() const -{ - return TheoJansen.name; +std::string TheoJansenDemo::title() const { + return TheoJansen.name; } -void TheoJansenDemo::initPhysics() -{ - _space = TheoJansen.initFunc(); - ChipmunkTestBed::initPhysics(); +void TheoJansenDemo::initPhysics() { + _space = TheoJansen.initFunc(); + ChipmunkTestBed::initPhysics(); } -void TheoJansenDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(TheoJansen); +void TheoJansenDemo::update(float delta) { + ChipmunkTestBed::updateInit(TheoJansen); } + //------------------------------------------------------------------ // // TankDemo // //------------------------------------------------------------------ -void TankDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void TankDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string TankDemo::title() const -{ - return Tank.name; +std::string TankDemo::title() const { + return Tank.name; } -void TankDemo::initPhysics() -{ - _space = Tank.initFunc(); - ChipmunkTestBed::initPhysics(); +void TankDemo::initPhysics() { + _space = Tank.initFunc(); + ChipmunkTestBed::initPhysics(); } -void TankDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(Tank); +void TankDemo::update(float delta) { + ChipmunkTestBed::updateInit(Tank); } + //------------------------------------------------------------------ // // BenchDemo // //------------------------------------------------------------------ -void BenchDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void BenchDemo::onEnter() { + ChipmunkTestBed::onEnter(); - auto itemPrev = MenuItemImage::create("Images/b1.png", "Images/b2.png", [&](Ref* sender) { - bench = (bench > 0) ? bench - 1 : (bench_count - 1); - reset(sender); - }); + auto itemPrev = MenuItemImage::create("Images/b1.png", "Images/b2.png", [&](Ref* sender) { + bench = (bench > 0) ? bench - 1 : (bench_count - 1); + reset(sender); + }); - auto itemNext = MenuItemImage::create("Images/f1.png", "Images/f2.png", [&](Ref* sender) { - bench = (bench < (bench_count - 1)) ? bench + 1 : 0; - reset(sender); - }); + auto itemNext = MenuItemImage::create("Images/f1.png", "Images/f2.png", [&](Ref* sender) { + bench = (bench < (bench_count - 1)) ? bench + 1 : 0; + reset(sender); + }); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); - auto menuPrev = Menu::create(itemPrev, nullptr); - menuPrev->alignItemsHorizontally(); - menuPrev->setScale(0.4); - menuPrev->setAnchorPoint(Vec2(0.0f, 0.0f)); - menuPrev->setPosition(Vec2(s.width / 2 - 45, 23.0f)); - addChild(menuPrev); + auto menuPrev = Menu::create(itemPrev, nullptr); + menuPrev->alignItemsHorizontally(); + menuPrev->setScale(0.4); + menuPrev->setAnchorPoint(Vec2(0.0f, 0.0f)); + menuPrev->setPosition(Vec2(s.width / 2 - 45, 23.0f)); + addChild(menuPrev); - auto menuNext = Menu::create(itemNext, nullptr); - menuNext->alignItemsHorizontally(); - menuNext->setScale(0.4); - menuNext->setAnchorPoint(Vec2(0.0f, 0.0f)); - menuNext->setPosition(Vec2(s.width / 2 + 45, 23.0f)); - addChild(menuNext); + auto menuNext = Menu::create(itemNext, nullptr); + menuNext->alignItemsHorizontally(); + menuNext->setScale(0.4); + menuNext->setAnchorPoint(Vec2(0.0f, 0.0f)); + menuNext->setPosition(Vec2(s.width / 2 + 45, 23.0f)); + addChild(menuNext); - initPhysics(); + initPhysics(); } -std::string BenchDemo::title() const -{ - return "Bench"; +std::string BenchDemo::title() const { + return "Bench"; } -std::string BenchDemo::subtitle() const -{ - std::string s = std::to_string(bench + 1) + ". " + bench_list[bench].name; - return s.c_str(); +std::string BenchDemo::subtitle() const { + std::string s = std::to_string(bench+1) + ". " + bench_list[bench].name; + return s.c_str(); } -void BenchDemo::initPhysics() -{ - _space = bench_list[bench].initFunc(); - ChipmunkTestBed::initPhysics(); +void BenchDemo::initPhysics() { + _space = bench_list[bench].initFunc(); + ChipmunkTestBed::initPhysics(); } -void BenchDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(bench_list[bench]); +void BenchDemo::update(float delta) { + ChipmunkTestBed::updateInit(bench_list[bench]); } + //------------------------------------------------------------------ // // SpringiesDemo // //------------------------------------------------------------------ -void SpringiesDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void SpringiesDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string SpringiesDemo::title() const -{ - return Springies.name; +std::string SpringiesDemo::title() const { + return Springies.name; } -void SpringiesDemo::initPhysics() -{ - _space = Springies.initFunc(); - ChipmunkTestBed::initPhysics(); +void SpringiesDemo::initPhysics() { + _space = Springies.initFunc(); + ChipmunkTestBed::initPhysics(); } -void SpringiesDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(Springies); +void SpringiesDemo::update(float delta) { + ChipmunkTestBed::updateInit(Springies); } + //------------------------------------------------------------------ // // ShatterDemo // //------------------------------------------------------------------ -void ShatterDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); - initPhysics(); +void ShatterDemo::onEnter() { + ChipmunkTestBed::onEnter(); + initPhysics(); } -std::string ShatterDemo::title() const -{ - return Shatter.name; +std::string ShatterDemo::title() const { + return Shatter.name; } -void ShatterDemo::initPhysics() -{ - _space = Shatter.initFunc(); - ChipmunkTestBed::initPhysics(); +void ShatterDemo::initPhysics() { + _space = Shatter.initFunc(); + ChipmunkTestBed::initPhysics(); } -void ShatterDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(Shatter); +void ShatterDemo::update(float delta) { + ChipmunkTestBed::updateInit(Shatter); } //------------------------------------------------------------------ @@ -895,27 +809,23 @@ void ShatterDemo::update(float delta) // StickyDemo // //------------------------------------------------------------------ -void StickyDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void StickyDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string StickyDemo::title() const -{ - return Sticky.name; +std::string StickyDemo::title() const { + return Sticky.name; } -void StickyDemo::initPhysics() -{ - _space = Sticky.initFunc(); - ChipmunkTestBed::initPhysics(); +void StickyDemo::initPhysics() { + _space = Sticky.initFunc(); + ChipmunkTestBed::initPhysics(); } -void StickyDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(Sticky); +void StickyDemo::update(float delta) { + ChipmunkTestBed::updateInit(Sticky); } //------------------------------------------------------------------ @@ -923,27 +833,23 @@ void StickyDemo::update(float delta) // CraneDemo // //------------------------------------------------------------------ -void CraneDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void CraneDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string CraneDemo::title() const -{ - return Crane.name; +std::string CraneDemo::title() const { + return Crane.name; } -void CraneDemo::initPhysics() -{ - _space = Crane.initFunc(); - ChipmunkTestBed::initPhysics(); +void CraneDemo::initPhysics() { + _space = Crane.initFunc(); + ChipmunkTestBed::initPhysics(); } -void CraneDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(Crane); +void CraneDemo::update(float delta) { + ChipmunkTestBed::updateInit(Crane); } //------------------------------------------------------------------ @@ -951,27 +857,23 @@ void CraneDemo::update(float delta) // JointsDemo // //------------------------------------------------------------------ -void JointsDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void JointsDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string JointsDemo::title() const -{ - return Joints.name; +std::string JointsDemo::title() const { + return Joints.name; } -void JointsDemo::initPhysics() -{ - _space = Joints.initFunc(); - ChipmunkTestBed::initPhysics(); +void JointsDemo::initPhysics() { + _space = Joints.initFunc(); + ChipmunkTestBed::initPhysics(); } -void JointsDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(Joints); +void JointsDemo::update(float delta) { + ChipmunkTestBed::updateInit(Joints); } //------------------------------------------------------------------ @@ -979,27 +881,23 @@ void JointsDemo::update(float delta) // ConvexDemo // //------------------------------------------------------------------ -void ConvexDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void ConvexDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string ConvexDemo::title() const -{ - return Convex.name; +std::string ConvexDemo::title() const { + return Convex.name; } -void ConvexDemo::initPhysics() -{ - _space = Convex.initFunc(); - ChipmunkTestBed::initPhysics(); +void ConvexDemo::initPhysics() { + _space = Convex.initFunc(); + ChipmunkTestBed::initPhysics(); } -void ConvexDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(Convex); +void ConvexDemo::update(float delta) { + ChipmunkTestBed::updateInit(Convex); } //------------------------------------------------------------------ @@ -1007,27 +905,23 @@ void ConvexDemo::update(float delta) // PumpDemo // //------------------------------------------------------------------ -void PumpDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void PumpDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string PumpDemo::title() const -{ - return Pump.name; +std::string PumpDemo::title() const { + return Pump.name; } -void PumpDemo::initPhysics() -{ - _space = Pump.initFunc(); - ChipmunkTestBed::initPhysics(); +void PumpDemo::initPhysics() { + _space = Pump.initFunc(); + ChipmunkTestBed::initPhysics(); } -void PumpDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(Pump); +void PumpDemo::update(float delta) { + ChipmunkTestBed::updateInit(Pump); } //------------------------------------------------------------------ @@ -1035,27 +929,23 @@ void PumpDemo::update(float delta) // PlatformerPlayerDemo // //------------------------------------------------------------------ -void PlatformerPlayerDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void PlatformerPlayerDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string PlatformerPlayerDemo::title() const -{ - return PlatformerPlayer.name; +std::string PlatformerPlayerDemo::title() const { + return PlatformerPlayer.name; } -void PlatformerPlayerDemo::initPhysics() -{ - _space = PlatformerPlayer.initFunc(); - ChipmunkTestBed::initPhysics(); +void PlatformerPlayerDemo::initPhysics() { + _space = PlatformerPlayer.initFunc(); + ChipmunkTestBed::initPhysics(); } -void PlatformerPlayerDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(PlatformerPlayer); +void PlatformerPlayerDemo::update(float delta) { + ChipmunkTestBed::updateInit(PlatformerPlayer); } //------------------------------------------------------------------ @@ -1063,27 +953,23 @@ void PlatformerPlayerDemo::update(float delta) // QueryDemo // //------------------------------------------------------------------ -void QueryDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void QueryDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string QueryDemo::title() const -{ - return Query.name; +std::string QueryDemo::title() const { + return Query.name; } -void QueryDemo::initPhysics() -{ - _space = Query.initFunc(); - ChipmunkTestBed::initPhysics(); +void QueryDemo::initPhysics() { + _space = Query.initFunc(); + ChipmunkTestBed::initPhysics(); } -void QueryDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(Query); +void QueryDemo::update(float delta) { + ChipmunkTestBed::updateInit(Query); } //------------------------------------------------------------------ @@ -1091,27 +977,23 @@ void QueryDemo::update(float delta) // ContactGraphDemo // //------------------------------------------------------------------ -void ContactGraphDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void ContactGraphDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string ContactGraphDemo::title() const -{ - return ContactGraph.name; +std::string ContactGraphDemo::title() const { + return ContactGraph.name; } -void ContactGraphDemo::initPhysics() -{ - _space = ContactGraph.initFunc(); - ChipmunkTestBed::initPhysics(); +void ContactGraphDemo::initPhysics() { + _space = ContactGraph.initFunc(); + ChipmunkTestBed::initPhysics(); } -void ContactGraphDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(ContactGraph); +void ContactGraphDemo::update(float delta) { + ChipmunkTestBed::updateInit(ContactGraph); } //------------------------------------------------------------------ @@ -1119,27 +1001,23 @@ void ContactGraphDemo::update(float delta) // BuoyancyDemo // //------------------------------------------------------------------ -void BuoyancyDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void BuoyancyDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string BuoyancyDemo::title() const -{ - return Buoyancy.name; +std::string BuoyancyDemo::title() const { + return Buoyancy.name; } -void BuoyancyDemo::initPhysics() -{ - _space = Buoyancy.initFunc(); - ChipmunkTestBed::initPhysics(); +void BuoyancyDemo::initPhysics() { + _space = Buoyancy.initFunc(); + ChipmunkTestBed::initPhysics(); } -void BuoyancyDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(Buoyancy); +void BuoyancyDemo::update(float delta) { + ChipmunkTestBed::updateInit(Buoyancy); } //------------------------------------------------------------------ @@ -1147,27 +1025,23 @@ void BuoyancyDemo::update(float delta) // SliceDemo // //------------------------------------------------------------------ -void SliceDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void SliceDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string SliceDemo::title() const -{ - return Slice.name; +std::string SliceDemo::title() const { + return Slice.name; } -void SliceDemo::initPhysics() -{ - _space = Slice.initFunc(); - ChipmunkTestBed::initPhysics(); +void SliceDemo::initPhysics() { + _space = Slice.initFunc(); + ChipmunkTestBed::initPhysics(); } -void SliceDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(Slice); +void SliceDemo::update(float delta) { + ChipmunkTestBed::updateInit(Slice); } //------------------------------------------------------------------ @@ -1175,88 +1049,82 @@ void SliceDemo::update(float delta) // UnicycleDemo // //------------------------------------------------------------------ -void UnicycleDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void UnicycleDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string UnicycleDemo::title() const -{ - return Unicycle.name; +std::string UnicycleDemo::title() const { + return Unicycle.name; } -void UnicycleDemo::initPhysics() -{ - _space = Unicycle.initFunc(); - ChipmunkTestBed::initPhysics(); +void UnicycleDemo::initPhysics() { + _space = Unicycle.initFunc(); + ChipmunkTestBed::initPhysics(); } -void UnicycleDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(Unicycle); +void UnicycleDemo::update(float delta) { + ChipmunkTestBed::updateInit(Unicycle); } + //------------------------------------------------------------------ // // ExampleDemo // //------------------------------------------------------------------ -void ExampleDemo::onEnter() -{ - ChipmunkTestBed::onEnter(); +void ExampleDemo::onEnter() { + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string ExampleDemo::title() const -{ - return Example.name; +std::string ExampleDemo::title() const { + return Example.name; } -void ExampleDemo::initPhysics() -{ - _space = Example.initFunc(); - ChipmunkTestBed::initPhysics(); +void ExampleDemo::initPhysics() { + _space = Example.initFunc(); + ChipmunkTestBed::initPhysics(); } -void ExampleDemo::update(float delta) -{ - ChipmunkTestBed::updateInit(Example); +void ExampleDemo::update(float delta) { + ChipmunkTestBed::updateInit(Example); } -ChipmunkTestBedTests::ChipmunkTestBedTests() -{ - ADD_TEST_CASE(BenchDemo); - ADD_TEST_CASE(LogoSmashDemo); - ADD_TEST_CASE(PlinkDemo); - ADD_TEST_CASE(TumbleDemo); - ADD_TEST_CASE(PyramidToppleDemo); - ADD_TEST_CASE(PyramidStackDemo); - ADD_TEST_CASE(ChainsDemo); - ADD_TEST_CASE(OneWayDemo); - ADD_TEST_CASE(PlanetDemo); - ADD_TEST_CASE(TheoJansenDemo); - ADD_TEST_CASE(TankDemo); - ADD_TEST_CASE(SpringiesDemo); +ChipmunkTestBedTests::ChipmunkTestBedTests() { + ADD_TEST_CASE(BenchDemo); + ADD_TEST_CASE(LogoSmashDemo); + ADD_TEST_CASE(PlinkDemo); + ADD_TEST_CASE(TumbleDemo); + ADD_TEST_CASE(PyramidToppleDemo); + ADD_TEST_CASE(PyramidStackDemo); + ADD_TEST_CASE(ChainsDemo); + ADD_TEST_CASE(OneWayDemo); + ADD_TEST_CASE(PlanetDemo); + ADD_TEST_CASE(TheoJansenDemo); + ADD_TEST_CASE(TankDemo); - ADD_TEST_CASE(ShatterDemo); - ADD_TEST_CASE(StickyDemo); - ADD_TEST_CASE(CraneDemo); - ADD_TEST_CASE(JointsDemo); + ADD_TEST_CASE(SpringiesDemo); - ADD_TEST_CASE(ConvexDemo); + ADD_TEST_CASE(ShatterDemo); + ADD_TEST_CASE(StickyDemo); + ADD_TEST_CASE(CraneDemo); + ADD_TEST_CASE(JointsDemo); - ADD_TEST_CASE(PumpDemo); - ADD_TEST_CASE(PlatformerPlayerDemo); + ADD_TEST_CASE(ConvexDemo); - ADD_TEST_CASE(QueryDemo); - ADD_TEST_CASE(ContactGraphDemo); - ADD_TEST_CASE(BuoyancyDemo); - ADD_TEST_CASE(SliceDemo); - ADD_TEST_CASE(UnicycleDemo); + ADD_TEST_CASE(PumpDemo); + ADD_TEST_CASE(PlatformerPlayerDemo); - ADD_TEST_CASE(ExampleDemo); // the template for your one examples/Demos + ADD_TEST_CASE(QueryDemo); + ADD_TEST_CASE(ContactGraphDemo); + ADD_TEST_CASE(BuoyancyDemo); + ADD_TEST_CASE(SliceDemo); + ADD_TEST_CASE(UnicycleDemo); + + ADD_TEST_CASE(ExampleDemo); // the template for your one examples/Demos } + diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/ChipmunkTestBed.h b/tests/cpp-tests/Classes/ChipmunkTestBed/ChipmunkTestBed.h index c080f57110..2cce89d31b 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/ChipmunkTestBed.h +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/ChipmunkTestBed.h @@ -20,9 +20,9 @@ THE SOFTWARE. ****************************************************************************/ -// -// cocos2d -// + // + // cocos2d + // #ifndef __CHIPMUNKTESTBED_H__ #define __CHIPMUNKTESTBED_H__ @@ -33,312 +33,290 @@ #include "demo/ChipmunkDemo.h" -class ChipmunkTestBed : public TestCase -{ +class ChipmunkTestBed : public TestCase { public: - CREATE_FUNC(ChipmunkTestBed); + CREATE_FUNC(ChipmunkTestBed); - ChipmunkTestBed(); - ~ChipmunkTestBed(); + ChipmunkTestBed(); + ~ChipmunkTestBed(); - void onEnter() override; - void createResetButton(); - void reset(cocos2d::Ref* sender); + void onEnter() override; + void createResetButton(); + void reset(cocos2d::Ref* sender); - void update(float dt) override; - virtual void initPhysics(); + void update(float dt) override; + virtual void initPhysics(); - void onMouseDown(cocos2d::Event* event); - void onMouseUp(cocos2d::Event* event); - void onMouseMove(cocos2d::Event* event); - void DrawInfo(); - void updateInit(ChipmunkDemo tt); + void onMouseDown(cocos2d::Event* event); + void onMouseUp(cocos2d::Event* event); + void onMouseMove(cocos2d::Event* event); + void DrawInfo(); + void updateInit(ChipmunkDemo tt); - cpSpace* _space; // strong ref - cocos2d::extension::PhysicsDebugNodeChipmunk2D* _debugLayer; // weak ref - int keyPresses; - bool mousePresses = false; + cpSpace* _space; // strong ref + cocos2d::extension::PhysicsDebugNodeChipmunk2D* _debugLayer; // weak ref + int keyPresses; + bool mousePresses = false; private: - cocos2d::EventListenerMouse* _mouseListener; - cocos2d::Node* _trackNode; - cocos2d::DrawNode* draw; - cocos2d::Label* drawInfo; + cocos2d::EventListenerMouse* _mouseListener; + cocos2d::Node* _trackNode; + cocos2d::DrawNode* draw; + cocos2d::Label* drawInfo; + }; -class LogoSmashDemo : public ChipmunkTestBed -{ +class LogoSmashDemo : public ChipmunkTestBed { public: - CREATE_FUNC(LogoSmashDemo); - std::string title() const override; - void onEnter() override; + CREATE_FUNC(LogoSmashDemo); + std::string title() const override; + void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class PlinkDemo : public ChipmunkTestBed -{ +class PlinkDemo : public ChipmunkTestBed { public: - CREATE_FUNC(PlinkDemo); - virtual std::string title() const override; - virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + CREATE_FUNC(PlinkDemo); + virtual std::string title() const override; + virtual void onEnter() override; + void initPhysics() override; + virtual void update(float dt) override; }; -class TumbleDemo : public ChipmunkTestBed -{ -public: - CREATE_FUNC(TumbleDemo); - virtual std::string title() const override; - virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; +class TumbleDemo : public ChipmunkTestBed { +public: + CREATE_FUNC(TumbleDemo); + virtual std::string title() const override; + virtual void onEnter() override; + + void initPhysics() override; + virtual void update(float dt) override; }; -class PyramidStackDemo : public ChipmunkTestBed -{ +class PyramidStackDemo : public ChipmunkTestBed { public: - CREATE_FUNC(PyramidStackDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(PyramidStackDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class PyramidToppleDemo : public ChipmunkTestBed -{ +class PyramidToppleDemo : public ChipmunkTestBed { public: - CREATE_FUNC(PyramidToppleDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(PyramidToppleDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class ChainsDemo : public ChipmunkTestBed -{ +class ChainsDemo : public ChipmunkTestBed { public: - CREATE_FUNC(ChainsDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(ChainsDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class OneWayDemo : public ChipmunkTestBed -{ +class OneWayDemo : public ChipmunkTestBed { public: - CREATE_FUNC(OneWayDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(OneWayDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class PlanetDemo : public ChipmunkTestBed -{ +class PlanetDemo : public ChipmunkTestBed { public: - CREATE_FUNC(PlanetDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(PlanetDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class TheoJansenDemo : public ChipmunkTestBed -{ +class TheoJansenDemo : public ChipmunkTestBed { public: - CREATE_FUNC(TheoJansenDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(TheoJansenDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class TankDemo : public ChipmunkTestBed -{ +class TankDemo : public ChipmunkTestBed { public: - CREATE_FUNC(TankDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(TankDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class BenchDemo : public ChipmunkTestBed -{ +class BenchDemo : public ChipmunkTestBed { public: - CREATE_FUNC(BenchDemo); - virtual std::string title() const override; - virtual std::string subtitle() const override; - virtual void onEnter() override; + CREATE_FUNC(BenchDemo); + virtual std::string title() const override; + virtual std::string subtitle() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + + void initPhysics() override; + virtual void update(float dt) override; }; -class SpringiesDemo : public ChipmunkTestBed -{ +class SpringiesDemo : public ChipmunkTestBed { public: - CREATE_FUNC(SpringiesDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(SpringiesDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class StickyDemo : public ChipmunkTestBed -{ +class StickyDemo : public ChipmunkTestBed { public: - CREATE_FUNC(StickyDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(StickyDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class ShatterDemo : public ChipmunkTestBed -{ +class ShatterDemo : public ChipmunkTestBed { public: - CREATE_FUNC(ShatterDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(ShatterDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class CraneDemo : public ChipmunkTestBed -{ +class CraneDemo : public ChipmunkTestBed { public: - CREATE_FUNC(CraneDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(CraneDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class JointsDemo : public ChipmunkTestBed -{ +class JointsDemo : public ChipmunkTestBed { public: - CREATE_FUNC(JointsDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(JointsDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class ConvexDemo : public ChipmunkTestBed -{ +class ConvexDemo : public ChipmunkTestBed { public: - CREATE_FUNC(ConvexDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(ConvexDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class PumpDemo : public ChipmunkTestBed -{ +class PumpDemo : public ChipmunkTestBed { public: - CREATE_FUNC(PumpDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(PumpDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class PlatformerPlayerDemo : public ChipmunkTestBed -{ +class PlatformerPlayerDemo : public ChipmunkTestBed { public: - CREATE_FUNC(PlatformerPlayerDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(PlatformerPlayerDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class QueryDemo : public ChipmunkTestBed -{ +class QueryDemo : public ChipmunkTestBed { public: - CREATE_FUNC(QueryDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(QueryDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class ContactGraphDemo : public ChipmunkTestBed -{ -public: - CREATE_FUNC(ContactGraphDemo); - virtual std::string title() const override; - virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; +class ContactGraphDemo : public ChipmunkTestBed { +public: + CREATE_FUNC(ContactGraphDemo); + virtual std::string title() const override; + virtual void onEnter() override; + + void initPhysics() override; + virtual void update(float dt) override; }; -class BuoyancyDemo : public ChipmunkTestBed -{ +class BuoyancyDemo : public ChipmunkTestBed { public: - CREATE_FUNC(BuoyancyDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(BuoyancyDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class SliceDemo : public ChipmunkTestBed -{ +class SliceDemo : public ChipmunkTestBed { public: - CREATE_FUNC(SliceDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(SliceDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class UnicycleDemo : public ChipmunkTestBed -{ +class UnicycleDemo : public ChipmunkTestBed { public: - CREATE_FUNC(UnicycleDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(UnicycleDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class ExampleDemo : public ChipmunkTestBed -{ +class ExampleDemo : public ChipmunkTestBed { public: - CREATE_FUNC(ExampleDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(ExampleDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; DEFINE_TEST_SUITE(ChipmunkTestBedTests); diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Bench.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Bench.c index d85a8d6fe1..d99c0216da 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Bench.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Bench.c @@ -4,611 +4,485 @@ #define ENABLE_HASTY 0 #if ENABLE_HASTY -# include "chipmunk/cpHastySpace.h" - -static cpSpace* MakeHastySpace() -{ - cpSpace* space = cpHastySpaceNew(); - cpHastySpaceSetThreads(space, 0); - return space; -} - -# define BENCH_SPACE_NEW MakeHastySpace -# define BENCH_SPACE_FREE cpHastySpaceFree -# define BENCH_SPACE_STEP cpHastySpaceStep + #include "chipmunk/cpHastySpace.h" + + static cpSpace *MakeHastySpace(){ + cpSpace *space = cpHastySpaceNew(); + cpHastySpaceSetThreads(space, 0); + return space; + } + + #define BENCH_SPACE_NEW MakeHastySpace + #define BENCH_SPACE_FREE cpHastySpaceFree + #define BENCH_SPACE_STEP cpHastySpaceStep #else -# define BENCH_SPACE_NEW cpSpaceNew -# define BENCH_SPACE_FREE cpSpaceFree -# define BENCH_SPACE_STEP cpSpaceStep + #define BENCH_SPACE_NEW cpSpaceNew + #define BENCH_SPACE_FREE cpSpaceFree + #define BENCH_SPACE_STEP cpSpaceStep #endif const cpFloat bevel = 1.0; static cpVect simple_terrain_verts[] = { - {350.00, 425.07}, {336.00, 436.55}, {272.00, 435.39}, {258.00, 427.63}, {225.28, 420.00}, {202.82, 396.00}, - {191.81, 388.00}, {189.00, 381.89}, {173.00, 380.39}, {162.59, 368.00}, {150.47, 319.00}, {128.00, 311.55}, - {119.14, 286.00}, {126.84, 263.00}, {120.56, 227.00}, {141.14, 178.00}, {137.52, 162.00}, {146.51, 142.00}, - {156.23, 136.00}, {158.00, 118.27}, {170.00, 100.77}, {208.43, 84.00}, {224.00, 69.65}, {249.30, 68.00}, - {257.00, 54.77}, {363.00, 45.94}, {374.15, 54.00}, {386.00, 69.60}, {413.00, 70.73}, {456.00, 84.89}, - {468.09, 99.00}, {467.09, 123.00}, {464.92, 135.00}, {469.00, 141.03}, {497.00, 148.67}, {513.85, 180.00}, - {509.56, 223.00}, {523.51, 247.00}, {523.00, 277.00}, {497.79, 311.00}, {478.67, 348.00}, {467.90, 360.00}, - {456.76, 382.00}, {432.95, 389.00}, {417.00, 411.32}, {373.00, 433.19}, {361.00, 430.02}, {350.00, 425.07}, + {350.00, 425.07}, {336.00, 436.55}, {272.00, 435.39}, {258.00, 427.63}, {225.28, 420.00}, {202.82, 396.00}, + {191.81, 388.00}, {189.00, 381.89}, {173.00, 380.39}, {162.59, 368.00}, {150.47, 319.00}, {128.00, 311.55}, + {119.14, 286.00}, {126.84, 263.00}, {120.56, 227.00}, {141.14, 178.00}, {137.52, 162.00}, {146.51, 142.00}, + {156.23, 136.00}, {158.00, 118.27}, {170.00, 100.77}, {208.43, 84.00}, {224.00, 69.65}, {249.30, 68.00}, + {257.00, 54.77}, {363.00, 45.94}, {374.15, 54.00}, {386.00, 69.60}, {413.00, 70.73}, {456.00, 84.89}, + {468.09, 99.00}, {467.09, 123.00}, {464.92, 135.00}, {469.00, 141.03}, {497.00, 148.67}, {513.85, 180.00}, + {509.56, 223.00}, {523.51, 247.00}, {523.00, 277.00}, {497.79, 311.00}, {478.67, 348.00}, {467.90, 360.00}, + {456.76, 382.00}, {432.95, 389.00}, {417.00, 411.32}, {373.00, 433.19}, {361.00, 430.02}, {350.00, 425.07}, }; -static int simple_terrain_count = sizeof(simple_terrain_verts) / sizeof(cpVect); +static int simple_terrain_count = sizeof(simple_terrain_verts)/sizeof(cpVect); -// cpBody bodies[1000] = {}; -// cpCircleShape circles[1000] = {}; +//cpBody bodies[1000] = {}; +//cpCircleShape circles[1000] = {}; -static void add_circle(cpSpace* space, int index, cpFloat radius) -{ - cpFloat mass = radius * radius / 25.0f; - cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); - // cpBody *body = cpSpaceAddBody(space, cpBodyInit(&bodies[i], mass, cpMomentForCircle(mass, 0.0f, radius, - // cpvzero))); - cpBodySetPosition(body, cpvmult(frand_unit_circle(), 180.0f)); - - cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); - // cpShape *shape = cpSpaceAddShape(space, cpCircleShapeInit(&circles[i], body, radius, cpvzero)); - cpShapeSetElasticity(shape, 0.0); - cpShapeSetFriction(shape, 0.9); +static void add_circle(cpSpace *space, int index, cpFloat radius){ + cpFloat mass = radius*radius/25.0f; + cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); +// cpBody *body = cpSpaceAddBody(space, cpBodyInit(&bodies[i], mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); + cpBodySetPosition(body, cpvmult(frand_unit_circle(), 180.0f)); + + + cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); +// cpShape *shape = cpSpaceAddShape(space, cpCircleShapeInit(&circles[i], body, radius, cpvzero)); + cpShapeSetElasticity(shape, 0.0); cpShapeSetFriction(shape, 0.9); } -static void add_box(cpSpace* space, int index, cpFloat size) -{ - cpFloat mass = size * size / 100.0f; - cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForBox(mass, size, size))); - // cpBody *body = cpSpaceAddBody(space, cpBodyInit(&bodies[i], mass, cpMomentForBox(mass, size, size))); - cpBodySetPosition(body, cpvmult(frand_unit_circle(), 180.0f)); - - cpShape* shape = cpSpaceAddShape(space, cpBoxShapeNew(body, size - bevel * 2, size - bevel * 2, 0.0)); - cpPolyShapeSetRadius(shape, bevel); - cpShapeSetElasticity(shape, 0.0); - cpShapeSetFriction(shape, 0.9); +static void add_box(cpSpace *space, int index, cpFloat size){ + cpFloat mass = size*size/100.0f; + cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForBox(mass, size, size))); +// cpBody *body = cpSpaceAddBody(space, cpBodyInit(&bodies[i], mass, cpMomentForBox(mass, size, size))); + cpBodySetPosition(body, cpvmult(frand_unit_circle(), 180.0f)); + + + cpShape *shape = cpSpaceAddShape(space, cpBoxShapeNew(body, size - bevel*2, size - bevel*2, 0.0)); + cpPolyShapeSetRadius(shape, bevel); + cpShapeSetElasticity(shape, 0.0); cpShapeSetFriction(shape, 0.9); } -static void add_hexagon(cpSpace* space, int index, cpFloat radius) -{ - cpVect hexagon[6]; - for (int i = 0; i < 6; i++) - { - cpFloat angle = -CP_PI * 2.0f * i / 6.0f; - hexagon[i] = cpvmult(cpv(cos(angle), sin(angle)), radius - bevel); - } - - cpFloat mass = radius * radius; - cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 6, hexagon, cpvzero, 0.0f))); - cpBodySetPosition(body, cpvmult(frand_unit_circle(), 180.0f)); - - cpShape* shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 6, hexagon, cpTransformIdentity, bevel)); - cpShapeSetElasticity(shape, 0.0); - cpShapeSetFriction(shape, 0.9); +static void add_hexagon(cpSpace *space, int index, cpFloat radius){ + cpVect hexagon[6]; + for(int i=0; i<6; i++){ + cpFloat angle = -CP_PI*2.0f*i/6.0f; + hexagon[i] = cpvmult(cpv(cos(angle), sin(angle)), radius - bevel); + } + + cpFloat mass = radius*radius; + cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 6, hexagon, cpvzero, 0.0f))); + cpBodySetPosition(body, cpvmult(frand_unit_circle(), 180.0f)); + + cpShape *shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 6, hexagon, cpTransformIdentity, bevel)); + cpShapeSetElasticity(shape, 0.0); cpShapeSetFriction(shape, 0.9); } -static cpSpace* SetupSpace_simpleTerrain() -{ - cpSpace* space = BENCH_SPACE_NEW(); - cpSpaceSetIterations(space, 10); - cpSpaceSetGravity(space, cpv(0, -100)); - cpSpaceSetCollisionSlop(space, 0.5f); - cpVect offset = cpv(-320, -240); - for (int i = 0; i < (simple_terrain_count - 1); i++) - { - cpVect a = simple_terrain_verts[i], b = simple_terrain_verts[i + 1]; - cpSpaceAddShape(space, - cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); - } - - return space; +static cpSpace * +SetupSpace_simpleTerrain(){ + cpSpace *space = BENCH_SPACE_NEW(); + cpSpaceSetIterations(space, 10); + cpSpaceSetGravity(space, cpv(0, -100)); + cpSpaceSetCollisionSlop(space, 0.5f); + + cpVect offset = cpv(-320, -240); + for(int i=0; i<(simple_terrain_count - 1); i++){ + cpVect a = simple_terrain_verts[i], b = simple_terrain_verts[i+1]; + cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); + } + + return space; } + // SimpleTerrain constant sized objects -static cpSpace* init_SimpleTerrainCircles_1000(void) -{ - cpSpace* space = SetupSpace_simpleTerrain(); - for (int i = 0; i < 1000; i++) - add_circle(space, i, 5.0f); - - return space; +static cpSpace *init_SimpleTerrainCircles_1000(void){ + cpSpace *space = SetupSpace_simpleTerrain(); + for(int i=0; i<1000; i++) add_circle(space, i, 5.0f); + + return space; } -static cpSpace* init_SimpleTerrainCircles_500(void) -{ - cpSpace* space = SetupSpace_simpleTerrain(); - for (int i = 0; i < 500; i++) - add_circle(space, i, 5.0f); - - return space; +static cpSpace *init_SimpleTerrainCircles_500(void){ + cpSpace *space = SetupSpace_simpleTerrain(); + for(int i=0; i<500; i++) add_circle(space, i, 5.0f); + + return space; } -static cpSpace* init_SimpleTerrainCircles_100(void) -{ - cpSpace* space = SetupSpace_simpleTerrain(); - for (int i = 0; i < 100; i++) - add_circle(space, i, 5.0f); - - return space; +static cpSpace *init_SimpleTerrainCircles_100(void){ + cpSpace *space = SetupSpace_simpleTerrain(); + for(int i=0; i<100; i++) add_circle(space, i, 5.0f); + + return space; } -static cpSpace* init_SimpleTerrainBoxes_1000(void) -{ - cpSpace* space = SetupSpace_simpleTerrain(); - for (int i = 0; i < 1000; i++) - add_box(space, i, 10.0f); - - return space; +static cpSpace *init_SimpleTerrainBoxes_1000(void){ + cpSpace *space = SetupSpace_simpleTerrain(); + for(int i=0; i<1000; i++) add_box(space, i, 10.0f); + + return space; } -static cpSpace* init_SimpleTerrainBoxes_500(void) -{ - cpSpace* space = SetupSpace_simpleTerrain(); - for (int i = 0; i < 500; i++) - add_box(space, i, 10.0f); - - return space; +static cpSpace *init_SimpleTerrainBoxes_500(void){ + cpSpace *space = SetupSpace_simpleTerrain(); + for(int i=0; i<500; i++) add_box(space, i, 10.0f); + + return space; } -static cpSpace* init_SimpleTerrainBoxes_100(void) -{ - cpSpace* space = SetupSpace_simpleTerrain(); - for (int i = 0; i < 100; i++) - add_box(space, i, 10.0f); - - return space; +static cpSpace *init_SimpleTerrainBoxes_100(void){ + cpSpace *space = SetupSpace_simpleTerrain(); + for(int i=0; i<100; i++) add_box(space, i, 10.0f); + + return space; } -static cpSpace* init_SimpleTerrainHexagons_1000(void) -{ - cpSpace* space = SetupSpace_simpleTerrain(); - for (int i = 0; i < 1000; i++) - add_hexagon(space, i, 5.0f); - - return space; +static cpSpace *init_SimpleTerrainHexagons_1000(void){ + cpSpace *space = SetupSpace_simpleTerrain(); + for(int i=0; i<1000; i++) add_hexagon(space, i, 5.0f); + + return space; } -static cpSpace* init_SimpleTerrainHexagons_500(void) -{ - cpSpace* space = SetupSpace_simpleTerrain(); - for (int i = 0; i < 500; i++) - add_hexagon(space, i, 5.0f); - - return space; +static cpSpace *init_SimpleTerrainHexagons_500(void){ + cpSpace *space = SetupSpace_simpleTerrain(); + for(int i=0; i<500; i++) add_hexagon(space, i, 5.0f); + + return space; } -static cpSpace* init_SimpleTerrainHexagons_100(void) -{ - cpSpace* space = SetupSpace_simpleTerrain(); - for (int i = 0; i < 100; i++) - add_hexagon(space, i, 5.0f); - - return space; +static cpSpace *init_SimpleTerrainHexagons_100(void){ + cpSpace *space = SetupSpace_simpleTerrain(); + for(int i=0; i<100; i++) add_hexagon(space, i, 5.0f); + + return space; } + // SimpleTerrain variable sized objects -static cpFloat rand_size() -{ - return cpfpow(1.5, cpflerp(-1.5, 3.5, frand())); +static cpFloat rand_size(){ + return cpfpow(1.5, cpflerp(-1.5, 3.5, frand())); } -static cpSpace* init_SimpleTerrainVCircles_200(void) -{ - cpSpace* space = SetupSpace_simpleTerrain(); - for (int i = 0; i < 200; i++) - add_circle(space, i, 5.0f * rand_size()); - - return space; +static cpSpace *init_SimpleTerrainVCircles_200(void){ + cpSpace *space = SetupSpace_simpleTerrain(); + for(int i=0; i<200; i++) add_circle(space, i, 5.0f*rand_size()); + + return space; } -static cpSpace* init_SimpleTerrainVBoxes_200(void) -{ - cpSpace* space = SetupSpace_simpleTerrain(); - for (int i = 0; i < 200; i++) - add_box(space, i, 8.0f * rand_size()); - - return space; +static cpSpace *init_SimpleTerrainVBoxes_200(void){ + cpSpace *space = SetupSpace_simpleTerrain(); + for(int i=0; i<200; i++) add_box(space, i, 8.0f*rand_size()); + + return space; } -static cpSpace* init_SimpleTerrainVHexagons_200(void) -{ - cpSpace* space = SetupSpace_simpleTerrain(); - for (int i = 0; i < 200; i++) - add_hexagon(space, i, 5.0f * rand_size()); - - return space; +static cpSpace *init_SimpleTerrainVHexagons_200(void){ + cpSpace *space = SetupSpace_simpleTerrain(); + for(int i=0; i<200; i++) add_hexagon(space, i, 5.0f*rand_size()); + + return space; } + // ComplexTerrain static cpVect complex_terrain_verts[] = { - {46.78, 479.00}, {35.00, 475.63}, {27.52, 469.00}, {23.52, 455.00}, {23.78, 441.00}, {28.41, 428.00}, - {49.61, 394.00}, {59.00, 381.56}, {80.00, 366.03}, {81.46, 358.00}, {86.31, 350.00}, {77.74, 320.00}, - {70.26, 278.00}, {67.51, 270.00}, {58.86, 260.00}, {57.19, 247.00}, {38.00, 235.60}, {25.76, 221.00}, - {24.58, 209.00}, {27.63, 202.00}, {31.28, 198.00}, {40.00, 193.72}, {48.00, 193.73}, {55.00, 196.70}, - {62.10, 204.00}, {71.00, 209.04}, {79.00, 206.55}, {88.00, 206.81}, {95.88, 211.00}, {103.00, 220.49}, - {131.00, 220.51}, {137.00, 222.66}, {143.08, 228.00}, {146.22, 234.00}, {147.08, 241.00}, {145.45, 248.00}, - {142.31, 253.00}, {132.00, 259.30}, {115.00, 259.70}, {109.28, 270.00}, {112.91, 296.00}, {119.69, 324.00}, - {129.00, 336.26}, {141.00, 337.59}, {153.00, 331.57}, {175.00, 325.74}, {188.00, 325.19}, {235.00, 317.46}, - {250.00, 317.19}, {255.00, 309.12}, {262.62, 302.00}, {262.21, 295.00}, {248.00, 273.59}, {229.00, 257.93}, - {221.00, 255.48}, {215.00, 251.59}, {210.79, 246.00}, {207.47, 234.00}, {203.25, 227.00}, {179.00, 205.90}, - {148.00, 189.54}, {136.00, 181.45}, {120.00, 180.31}, {110.00, 181.65}, {95.00, 179.31}, {63.00, 166.96}, - {50.00, 164.23}, {31.00, 154.49}, {19.76, 145.00}, {15.96, 136.00}, {16.65, 127.00}, {20.57, 120.00}, - {28.00, 114.63}, {40.00, 113.67}, {65.00, 127.22}, {73.00, 128.69}, {81.96, 120.00}, {77.58, 103.00}, - {78.18, 92.00}, {59.11, 77.00}, {52.00, 67.29}, {31.29, 55.00}, {25.67, 47.00}, {24.65, 37.00}, - {27.82, 29.00}, {35.00, 22.55}, {44.00, 20.35}, {49.00, 20.81}, {61.00, 25.69}, {79.00, 37.81}, - {88.00, 49.64}, {97.00, 56.65}, {109.00, 49.61}, {143.00, 38.96}, {197.00, 37.27}, {215.00, 35.30}, - {222.00, 36.65}, {228.42, 41.00}, {233.30, 49.00}, {234.14, 57.00}, {231.00, 65.80}, {224.00, 72.38}, - {218.00, 74.50}, {197.00, 76.62}, {145.00, 78.81}, {123.00, 87.41}, {117.59, 98.00}, {117.79, 104.00}, - {119.00, 106.23}, {138.73, 120.00}, {148.00, 129.50}, {158.50, 149.00}, {203.93, 175.00}, {229.00, 196.60}, - {238.16, 208.00}, {245.20, 221.00}, {275.45, 245.00}, {289.00, 263.24}, {303.60, 287.00}, {312.00, 291.57}, - {339.25, 266.00}, {366.33, 226.00}, {363.43, 216.00}, {364.13, 206.00}, {353.00, 196.72}, {324.00, 181.05}, - {307.00, 169.63}, {274.93, 156.00}, {256.00, 152.48}, {228.00, 145.13}, {221.09, 142.00}, {214.87, 135.00}, - {212.67, 127.00}, {213.81, 119.00}, {219.32, 111.00}, {228.00, 106.52}, {236.00, 106.39}, {290.00, 119.40}, - {299.33, 114.00}, {300.52, 109.00}, {300.30, 53.00}, {301.46, 47.00}, {305.00, 41.12}, {311.00, 36.37}, - {317.00, 34.43}, {325.00, 34.81}, {334.90, 41.00}, {339.45, 50.00}, {339.82, 132.00}, {346.09, 139.00}, - {350.00, 150.26}, {380.00, 167.38}, {393.00, 166.48}, {407.00, 155.54}, {430.00, 147.30}, {437.78, 135.00}, - {433.13, 122.00}, {410.23, 78.00}, {401.59, 69.00}, {393.48, 56.00}, {392.80, 44.00}, {395.50, 38.00}, - {401.00, 32.49}, {409.00, 29.41}, {420.00, 30.84}, {426.92, 36.00}, {432.32, 44.00}, {439.49, 51.00}, - {470.13, 108.00}, {475.71, 124.00}, {483.00, 130.11}, {488.00, 139.43}, {529.00, 139.40}, {536.00, 132.52}, - {543.73, 129.00}, {540.47, 115.00}, {541.11, 100.00}, {552.18, 68.00}, {553.78, 47.00}, {559.00, 39.76}, - {567.00, 35.52}, {577.00, 35.45}, {585.00, 39.58}, {591.38, 50.00}, {591.67, 66.00}, {590.31, 79.00}, - {579.76, 109.00}, {582.25, 119.00}, {583.66, 136.00}, {586.45, 143.00}, {586.44, 151.00}, {580.42, 168.00}, - {577.15, 173.00}, {572.00, 177.13}, {564.00, 179.49}, {478.00, 178.81}, {443.00, 184.76}, {427.10, 190.00}, - {424.00, 192.11}, {415.94, 209.00}, {408.82, 228.00}, {405.82, 241.00}, {411.00, 250.82}, {415.00, 251.50}, - {428.00, 248.89}, {469.00, 246.29}, {505.00, 246.49}, {533.00, 243.60}, {541.87, 248.00}, {547.55, 256.00}, - {548.48, 267.00}, {544.00, 276.00}, {534.00, 282.24}, {513.00, 285.46}, {468.00, 285.76}, {402.00, 291.70}, - {392.00, 290.29}, {377.00, 294.46}, {367.00, 294.43}, {356.44, 304.00}, {354.22, 311.00}, {362.00, 321.36}, - {390.00, 322.44}, {433.00, 330.16}, {467.00, 332.76}, {508.00, 347.64}, {522.00, 357.67}, {528.00, 354.46}, - {536.00, 352.96}, {546.06, 336.00}, {553.47, 306.00}, {564.19, 282.00}, {567.84, 268.00}, {578.72, 246.00}, - {585.00, 240.97}, {592.00, 238.91}, {600.00, 239.72}, {606.00, 242.82}, {612.36, 251.00}, {613.35, 263.00}, - {588.75, 324.00}, {583.25, 350.00}, {572.12, 370.00}, {575.45, 378.00}, {575.20, 388.00}, {589.00, 393.81}, - {599.20, 404.00}, {607.14, 416.00}, {609.96, 430.00}, {615.45, 441.00}, {613.44, 462.00}, {610.48, 469.00}, - {603.00, 475.63}, {590.96, 479.00}, + { 46.78, 479.00}, { 35.00, 475.63}, { 27.52, 469.00}, { 23.52, 455.00}, { 23.78, 441.00}, { 28.41, 428.00}, { 49.61, 394.00}, { 59.00, 381.56}, { 80.00, 366.03}, { 81.46, 358.00}, { 86.31, 350.00}, { 77.74, 320.00}, + { 70.26, 278.00}, { 67.51, 270.00}, { 58.86, 260.00}, { 57.19, 247.00}, { 38.00, 235.60}, { 25.76, 221.00}, { 24.58, 209.00}, { 27.63, 202.00}, { 31.28, 198.00}, { 40.00, 193.72}, { 48.00, 193.73}, { 55.00, 196.70}, + { 62.10, 204.00}, { 71.00, 209.04}, { 79.00, 206.55}, { 88.00, 206.81}, { 95.88, 211.00}, {103.00, 220.49}, {131.00, 220.51}, {137.00, 222.66}, {143.08, 228.00}, {146.22, 234.00}, {147.08, 241.00}, {145.45, 248.00}, + {142.31, 253.00}, {132.00, 259.30}, {115.00, 259.70}, {109.28, 270.00}, {112.91, 296.00}, {119.69, 324.00}, {129.00, 336.26}, {141.00, 337.59}, {153.00, 331.57}, {175.00, 325.74}, {188.00, 325.19}, {235.00, 317.46}, + {250.00, 317.19}, {255.00, 309.12}, {262.62, 302.00}, {262.21, 295.00}, {248.00, 273.59}, {229.00, 257.93}, {221.00, 255.48}, {215.00, 251.59}, {210.79, 246.00}, {207.47, 234.00}, {203.25, 227.00}, {179.00, 205.90}, + {148.00, 189.54}, {136.00, 181.45}, {120.00, 180.31}, {110.00, 181.65}, { 95.00, 179.31}, { 63.00, 166.96}, { 50.00, 164.23}, { 31.00, 154.49}, { 19.76, 145.00}, { 15.96, 136.00}, { 16.65, 127.00}, { 20.57, 120.00}, + { 28.00, 114.63}, { 40.00, 113.67}, { 65.00, 127.22}, { 73.00, 128.69}, { 81.96, 120.00}, { 77.58, 103.00}, { 78.18, 92.00}, { 59.11, 77.00}, { 52.00, 67.29}, { 31.29, 55.00}, { 25.67, 47.00}, { 24.65, 37.00}, + { 27.82, 29.00}, { 35.00, 22.55}, { 44.00, 20.35}, { 49.00, 20.81}, { 61.00, 25.69}, { 79.00, 37.81}, { 88.00, 49.64}, { 97.00, 56.65}, {109.00, 49.61}, {143.00, 38.96}, {197.00, 37.27}, {215.00, 35.30}, + {222.00, 36.65}, {228.42, 41.00}, {233.30, 49.00}, {234.14, 57.00}, {231.00, 65.80}, {224.00, 72.38}, {218.00, 74.50}, {197.00, 76.62}, {145.00, 78.81}, {123.00, 87.41}, {117.59, 98.00}, {117.79, 104.00}, + {119.00, 106.23}, {138.73, 120.00}, {148.00, 129.50}, {158.50, 149.00}, {203.93, 175.00}, {229.00, 196.60}, {238.16, 208.00}, {245.20, 221.00}, {275.45, 245.00}, {289.00, 263.24}, {303.60, 287.00}, {312.00, 291.57}, + {339.25, 266.00}, {366.33, 226.00}, {363.43, 216.00}, {364.13, 206.00}, {353.00, 196.72}, {324.00, 181.05}, {307.00, 169.63}, {274.93, 156.00}, {256.00, 152.48}, {228.00, 145.13}, {221.09, 142.00}, {214.87, 135.00}, + {212.67, 127.00}, {213.81, 119.00}, {219.32, 111.00}, {228.00, 106.52}, {236.00, 106.39}, {290.00, 119.40}, {299.33, 114.00}, {300.52, 109.00}, {300.30, 53.00}, {301.46, 47.00}, {305.00, 41.12}, {311.00, 36.37}, + {317.00, 34.43}, {325.00, 34.81}, {334.90, 41.00}, {339.45, 50.00}, {339.82, 132.00}, {346.09, 139.00}, {350.00, 150.26}, {380.00, 167.38}, {393.00, 166.48}, {407.00, 155.54}, {430.00, 147.30}, {437.78, 135.00}, + {433.13, 122.00}, {410.23, 78.00}, {401.59, 69.00}, {393.48, 56.00}, {392.80, 44.00}, {395.50, 38.00}, {401.00, 32.49}, {409.00, 29.41}, {420.00, 30.84}, {426.92, 36.00}, {432.32, 44.00}, {439.49, 51.00}, + {470.13, 108.00}, {475.71, 124.00}, {483.00, 130.11}, {488.00, 139.43}, {529.00, 139.40}, {536.00, 132.52}, {543.73, 129.00}, {540.47, 115.00}, {541.11, 100.00}, {552.18, 68.00}, {553.78, 47.00}, {559.00, 39.76}, + {567.00, 35.52}, {577.00, 35.45}, {585.00, 39.58}, {591.38, 50.00}, {591.67, 66.00}, {590.31, 79.00}, {579.76, 109.00}, {582.25, 119.00}, {583.66, 136.00}, {586.45, 143.00}, {586.44, 151.00}, {580.42, 168.00}, + {577.15, 173.00}, {572.00, 177.13}, {564.00, 179.49}, {478.00, 178.81}, {443.00, 184.76}, {427.10, 190.00}, {424.00, 192.11}, {415.94, 209.00}, {408.82, 228.00}, {405.82, 241.00}, {411.00, 250.82}, {415.00, 251.50}, + {428.00, 248.89}, {469.00, 246.29}, {505.00, 246.49}, {533.00, 243.60}, {541.87, 248.00}, {547.55, 256.00}, {548.48, 267.00}, {544.00, 276.00}, {534.00, 282.24}, {513.00, 285.46}, {468.00, 285.76}, {402.00, 291.70}, + {392.00, 290.29}, {377.00, 294.46}, {367.00, 294.43}, {356.44, 304.00}, {354.22, 311.00}, {362.00, 321.36}, {390.00, 322.44}, {433.00, 330.16}, {467.00, 332.76}, {508.00, 347.64}, {522.00, 357.67}, {528.00, 354.46}, + {536.00, 352.96}, {546.06, 336.00}, {553.47, 306.00}, {564.19, 282.00}, {567.84, 268.00}, {578.72, 246.00}, {585.00, 240.97}, {592.00, 238.91}, {600.00, 239.72}, {606.00, 242.82}, {612.36, 251.00}, {613.35, 263.00}, + {588.75, 324.00}, {583.25, 350.00}, {572.12, 370.00}, {575.45, 378.00}, {575.20, 388.00}, {589.00, 393.81}, {599.20, 404.00}, {607.14, 416.00}, {609.96, 430.00}, {615.45, 441.00}, {613.44, 462.00}, {610.48, 469.00}, + {603.00, 475.63}, {590.96, 479.00}, }; -static int complex_terrain_count = sizeof(complex_terrain_verts) / sizeof(cpVect); +static int complex_terrain_count = sizeof(complex_terrain_verts)/sizeof(cpVect); -static cpSpace* init_ComplexTerrainCircles_1000(void) -{ - cpSpace* space = BENCH_SPACE_NEW(); - cpSpaceSetIterations(space, 10); - cpSpaceSetGravity(space, cpv(0, -100)); - cpSpaceSetCollisionSlop(space, 0.5f); - - cpVect offset = cpv(-320, -240); - for (int i = 0; i < (complex_terrain_count - 1); i++) - { - cpVect a = complex_terrain_verts[i], b = complex_terrain_verts[i + 1]; - cpSpaceAddShape(space, - cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); - } - - for (int i = 0; i < 1000; i++) - { - cpFloat radius = 5.0f; - cpFloat mass = radius * radius; - cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); - cpBodySetPosition(body, cpvadd(cpvmult(frand_unit_circle(), 180.0f), cpv(0.0f, 300.0f))); - - cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); - cpShapeSetElasticity(shape, 0.0); - cpShapeSetFriction(shape, 0.0); - } - - return space; +static cpSpace *init_ComplexTerrainCircles_1000(void){ + cpSpace *space = BENCH_SPACE_NEW(); + cpSpaceSetIterations(space, 10); + cpSpaceSetGravity(space, cpv(0, -100)); + cpSpaceSetCollisionSlop(space, 0.5f); + + cpVect offset = cpv(-320, -240); + for(int i=0; i<(complex_terrain_count - 1); i++){ + cpVect a = complex_terrain_verts[i], b = complex_terrain_verts[i+1]; + cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); + } + + for(int i=0; i<1000; i++){ + cpFloat radius = 5.0f; + cpFloat mass = radius*radius; + cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); + cpBodySetPosition(body, cpvadd(cpvmult(frand_unit_circle(), 180.0f), cpv(0.0f, 300.0f))); + + cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); + cpShapeSetElasticity(shape, 0.0); cpShapeSetFriction(shape, 0.0); + } + + return space; } -static cpSpace* init_ComplexTerrainHexagons_1000(void) -{ - cpSpace* space = BENCH_SPACE_NEW(); - cpSpaceSetIterations(space, 10); - cpSpaceSetGravity(space, cpv(0, -100)); - cpSpaceSetCollisionSlop(space, 0.5f); - - cpVect offset = cpv(-320, -240); - for (int i = 0; i < (complex_terrain_count - 1); i++) - { - cpVect a = complex_terrain_verts[i], b = complex_terrain_verts[i + 1]; - cpSpaceAddShape(space, - cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); - } - - cpFloat radius = 5.0f; - cpVect hexagon[6]; - for (int i = 0; i < 6; i++) - { - cpFloat angle = -CP_PI * 2.0f * i / 6.0f; - hexagon[i] = cpvmult(cpv(cos(angle), sin(angle)), radius - bevel); - } - - for (int i = 0; i < 1000; i++) - { - cpFloat mass = radius * radius; - cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 6, hexagon, cpvzero, 0.0f))); - cpBodySetPosition(body, cpvadd(cpvmult(frand_unit_circle(), 180.0f), cpv(0.0f, 300.0f))); - - cpShape* shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 6, hexagon, cpTransformIdentity, bevel)); - cpShapeSetElasticity(shape, 0.0); - cpShapeSetFriction(shape, 0.0); - } - - return space; +static cpSpace *init_ComplexTerrainHexagons_1000(void){ + cpSpace *space = BENCH_SPACE_NEW(); + cpSpaceSetIterations(space, 10); + cpSpaceSetGravity(space, cpv(0, -100)); + cpSpaceSetCollisionSlop(space, 0.5f); + + cpVect offset = cpv(-320, -240); + for(int i=0; i<(complex_terrain_count - 1); i++){ + cpVect a = complex_terrain_verts[i], b = complex_terrain_verts[i+1]; + cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); + } + + cpFloat radius = 5.0f; + cpVect hexagon[6]; + for(int i=0; i<6; i++){ + cpFloat angle = -CP_PI*2.0f*i/6.0f; + hexagon[i] = cpvmult(cpv(cos(angle), sin(angle)), radius - bevel); + } + + for(int i=0; i<1000; i++){ + cpFloat mass = radius*radius; + cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 6, hexagon, cpvzero, 0.0f))); + cpBodySetPosition(body, cpvadd(cpvmult(frand_unit_circle(), 180.0f), cpv(0.0f, 300.0f))); + + cpShape *shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 6, hexagon, cpTransformIdentity, bevel)); + cpShapeSetElasticity(shape, 0.0); cpShapeSetFriction(shape, 0.0); + } + + return space; } + // BouncyTerrain static cpVect bouncy_terrain_verts[] = { - {537.18, 23.00}, {520.50, 36.00}, {501.53, 63.00}, {496.14, 76.00}, {498.86, 86.00}, {504.00, 90.51}, - {508.00, 91.36}, {508.77, 84.00}, {513.00, 77.73}, {519.00, 74.48}, {530.00, 74.67}, {545.00, 54.65}, - {554.00, 48.77}, {562.00, 46.39}, {568.00, 45.94}, {568.61, 47.00}, {567.94, 55.00}, {571.27, 64.00}, - {572.92, 80.00}, {572.00, 81.39}, {563.00, 79.93}, {556.00, 82.69}, {551.49, 88.00}, {549.00, 95.76}, - {538.00, 93.40}, {530.00, 102.38}, {523.00, 104.00}, {517.00, 103.02}, {516.22, 109.00}, {518.96, 116.00}, - {526.00, 121.15}, {534.00, 116.48}, {543.00, 116.77}, {549.28, 121.00}, {554.00, 130.17}, {564.00, 125.67}, - {575.60, 129.00}, {573.31, 121.00}, {567.77, 111.00}, {575.00, 106.47}, {578.51, 102.00}, {580.25, 95.00}, - {577.98, 87.00}, {582.00, 85.71}, {597.00, 89.46}, {604.80, 95.00}, {609.28, 104.00}, {610.55, 116.00}, - {609.30, 125.00}, {600.80, 142.00}, {597.31, 155.00}, {584.00, 167.23}, {577.86, 175.00}, {583.52, 184.00}, - {582.64, 195.00}, {591.00, 196.56}, {597.81, 201.00}, {607.45, 219.00}, {607.51, 246.00}, {600.00, 275.46}, - {588.00, 267.81}, {579.00, 264.91}, {557.00, 264.41}, {552.98, 259.00}, {548.00, 246.18}, {558.00, 247.12}, - {565.98, 244.00}, {571.10, 237.00}, {571.61, 229.00}, {568.25, 222.00}, {562.00, 217.67}, {544.00, 213.93}, - {536.73, 214.00}, {535.60, 204.00}, {539.69, 181.00}, {542.84, 171.00}, {550.43, 161.00}, {540.00, 156.27}, - {536.62, 152.00}, {534.70, 146.00}, {527.00, 141.88}, {518.59, 152.00}, {514.51, 160.00}, {510.33, 175.00}, - {519.38, 183.00}, {520.52, 194.00}, {516.00, 201.27}, {505.25, 206.00}, {507.57, 223.00}, {519.90, 260.00}, - {529.00, 260.48}, {534.00, 262.94}, {538.38, 268.00}, {540.00, 275.00}, {537.06, 284.00}, {530.00, 289.23}, - {520.00, 289.23}, {513.00, 284.18}, {509.71, 286.00}, {501.69, 298.00}, {501.56, 305.00}, {504.30, 311.00}, - {512.00, 316.43}, {521.00, 316.42}, {525.67, 314.00}, {535.00, 304.98}, {562.00, 294.80}, {573.00, 294.81}, - {587.52, 304.00}, {600.89, 310.00}, {596.96, 322.00}, {603.28, 327.00}, {606.52, 333.00}, {605.38, 344.00}, - {597.65, 352.00}, {606.36, 375.00}, {607.16, 384.00}, {603.40, 393.00}, {597.00, 398.14}, {577.00, 386.15}, - {564.35, 373.00}, {565.21, 364.00}, {562.81, 350.00}, {553.00, 346.06}, {547.48, 338.00}, {547.48, 330.00}, - {550.00, 323.30}, {544.00, 321.53}, {537.00, 322.70}, {532.00, 326.23}, {528.89, 331.00}, {527.83, 338.00}, - {533.02, 356.00}, {542.00, 360.73}, {546.68, 369.00}, {545.38, 379.00}, {537.58, 386.00}, {537.63, 388.00}, - {555.00, 407.47}, {563.00, 413.52}, {572.57, 418.00}, {582.72, 426.00}, {578.00, 431.12}, {563.21, 440.00}, - {558.00, 449.27}, {549.00, 452.94}, {541.00, 451.38}, {536.73, 448.00}, {533.00, 441.87}, {520.00, 437.96}, - {514.00, 429.69}, {490.00, 415.15}, {472.89, 399.00}, {472.03, 398.00}, {474.00, 396.71}, {486.00, 393.61}, - {492.00, 385.85}, {492.00, 376.15}, {489.04, 371.00}, {485.00, 368.11}, {480.00, 376.27}, {472.00, 379.82}, - {463.00, 378.38}, {455.08, 372.00}, {446.00, 377.69}, {439.00, 385.24}, {436.61, 391.00}, {437.52, 404.00}, - {440.00, 409.53}, {463.53, 433.00}, {473.80, 441.00}, {455.00, 440.30}, {443.00, 436.18}, {436.00, 431.98}, - {412.00, 440.92}, {397.00, 442.46}, {393.59, 431.00}, {393.71, 412.00}, {400.00, 395.10}, {407.32, 387.00}, - {408.54, 380.00}, {407.42, 375.00}, {403.97, 370.00}, {399.00, 366.74}, {393.00, 365.68}, {391.23, 374.00}, - {387.00, 380.27}, {381.00, 383.52}, {371.56, 384.00}, {364.98, 401.00}, {362.96, 412.00}, {363.63, 435.00}, - {345.00, 433.55}, {344.52, 442.00}, {342.06, 447.00}, {337.00, 451.38}, {330.00, 453.00}, {325.00, 452.23}, - {318.00, 448.17}, {298.00, 453.70}, {284.00, 451.49}, {278.62, 449.00}, {291.47, 408.00}, {291.77, 398.00}, - {301.00, 393.83}, {305.00, 393.84}, {305.60, 403.00}, {310.00, 409.47}, {318.00, 413.07}, {325.00, 412.40}, - {332.31, 407.00}, {335.07, 400.00}, {334.40, 393.00}, {329.00, 385.69}, {319.00, 382.79}, {301.00, 389.23}, - {289.00, 389.97}, {265.00, 389.82}, {251.00, 385.85}, {245.00, 389.23}, {239.00, 389.94}, {233.00, 388.38}, - {226.00, 382.04}, {206.00, 374.75}, {206.00, 394.00}, {204.27, 402.00}, {197.00, 401.79}, {191.00, 403.49}, - {186.53, 407.00}, {183.60, 412.00}, {183.60, 422.00}, {189.00, 429.31}, {196.00, 432.07}, {203.00, 431.40}, - {209.47, 427.00}, {213.00, 419.72}, {220.00, 420.21}, {227.00, 418.32}, {242.00, 408.41}, {258.98, 409.00}, - {250.00, 435.43}, {239.00, 438.78}, {223.00, 448.19}, {209.00, 449.70}, {205.28, 456.00}, {199.00, 460.23}, - {190.00, 460.52}, {182.73, 456.00}, {178.00, 446.27}, {160.00, 441.42}, {148.35, 435.00}, {149.79, 418.00}, - {157.72, 401.00}, {161.00, 396.53}, {177.00, 385.00}, {180.14, 380.00}, {181.11, 374.00}, {180.00, 370.52}, - {170.00, 371.68}, {162.72, 368.00}, {158.48, 361.00}, {159.56, 349.00}, {154.00, 342.53}, {146.00, 339.85}, - {136.09, 343.00}, {130.64, 351.00}, {131.74, 362.00}, {140.61, 374.00}, {130.68, 387.00}, {120.75, 409.00}, - {118.09, 421.00}, {117.92, 434.00}, {100.00, 432.40}, {87.00, 427.48}, {81.59, 423.00}, {73.64, 409.00}, - {72.57, 398.00}, {74.62, 386.00}, {78.80, 378.00}, {88.00, 373.43}, {92.49, 367.00}, {93.32, 360.00}, - {91.30, 353.00}, {103.00, 342.67}, {109.00, 343.10}, {116.00, 340.44}, {127.33, 330.00}, {143.00, 327.24}, - {154.30, 322.00}, {145.00, 318.06}, {139.77, 311.00}, {139.48, 302.00}, {144.95, 293.00}, {143.00, 291.56}, - {134.00, 298.21}, {118.00, 300.75}, {109.40, 305.00}, {94.67, 319.00}, {88.00, 318.93}, {81.00, 321.69}, - {67.24, 333.00}, {56.68, 345.00}, {53.00, 351.40}, {47.34, 333.00}, {50.71, 314.00}, {56.57, 302.00}, - {68.00, 287.96}, {91.00, 287.24}, {110.00, 282.36}, {133.80, 271.00}, {147.34, 256.00}, {156.47, 251.00}, - {157.26, 250.00}, {154.18, 242.00}, {154.48, 236.00}, {158.72, 229.00}, {166.71, 224.00}, {170.15, 206.00}, - {170.19, 196.00}, {167.24, 188.00}, {160.00, 182.67}, {150.00, 182.66}, {143.60, 187.00}, {139.96, 195.00}, - {139.50, 207.00}, {136.45, 221.00}, {136.52, 232.00}, {133.28, 238.00}, {129.00, 241.38}, {119.00, 243.07}, - {115.00, 246.55}, {101.00, 253.16}, {86.00, 257.32}, {63.00, 259.24}, {57.00, 257.31}, {50.54, 252.00}, - {47.59, 247.00}, {46.30, 240.00}, {47.58, 226.00}, {50.00, 220.57}, {58.00, 226.41}, {69.00, 229.17}, - {79.00, 229.08}, {94.50, 225.00}, {100.21, 231.00}, {107.00, 233.47}, {107.48, 224.00}, {109.94, 219.00}, - {115.00, 214.62}, {122.57, 212.00}, {116.00, 201.49}, {104.00, 194.57}, {90.00, 194.04}, {79.00, 198.21}, - {73.00, 198.87}, {62.68, 191.00}, {62.58, 184.00}, {64.42, 179.00}, {75.00, 167.70}, {80.39, 157.00}, - {68.79, 140.00}, {61.67, 126.00}, {61.47, 117.00}, {64.43, 109.00}, {63.10, 96.00}, {56.48, 82.00}, - {48.00, 73.88}, {43.81, 66.00}, {43.81, 56.00}, {50.11, 46.00}, {59.00, 41.55}, {71.00, 42.64}, - {78.00, 36.77}, {83.00, 34.75}, {99.00, 34.32}, {117.00, 38.92}, {133.00, 55.15}, {142.00, 50.70}, - {149.74, 51.00}, {143.55, 68.00}, {153.28, 74.00}, {156.23, 79.00}, {157.00, 84.00}, {156.23, 89.00}, - {153.28, 94.00}, {144.58, 99.00}, {151.52, 112.00}, {151.51, 124.00}, {150.00, 126.36}, {133.00, 130.25}, - {126.71, 125.00}, {122.00, 117.25}, {114.00, 116.23}, {107.73, 112.00}, {104.48, 106.00}, {104.32, 99.00}, - {106.94, 93.00}, {111.24, 89.00}, {111.60, 85.00}, {107.24, 73.00}, {102.00, 67.57}, {99.79, 67.00}, - {99.23, 76.00}, {95.00, 82.27}, {89.00, 85.52}, {79.84, 86.00}, {86.73, 114.00}, {98.00, 136.73}, - {99.00, 137.61}, {109.00, 135.06}, {117.00, 137.94}, {122.52, 146.00}, {122.94, 151.00}, {121.00, 158.58}, - {134.00, 160.97}, {153.00, 157.45}, {171.30, 150.00}, {169.06, 142.00}, {169.77, 136.00}, {174.00, 129.73}, - {181.46, 126.00}, {182.22, 120.00}, {182.20, 111.00}, {180.06, 101.00}, {171.28, 85.00}, {171.75, 80.00}, - {182.30, 53.00}, {189.47, 50.00}, {190.62, 38.00}, {194.00, 33.73}, {199.00, 30.77}, {208.00, 30.48}, - {216.00, 34.94}, {224.00, 31.47}, {240.00, 30.37}, {247.00, 32.51}, {249.77, 35.00}, {234.75, 53.00}, - {213.81, 93.00}, {212.08, 99.00}, {213.00, 101.77}, {220.00, 96.77}, {229.00, 96.48}, {236.28, 101.00}, - {240.00, 107.96}, {245.08, 101.00}, {263.00, 65.32}, {277.47, 48.00}, {284.00, 47.03}, {286.94, 41.00}, - {292.00, 36.62}, {298.00, 35.06}, {304.00, 35.77}, {314.00, 43.81}, {342.00, 32.56}, {359.00, 31.32}, - {365.00, 32.57}, {371.00, 36.38}, {379.53, 48.00}, {379.70, 51.00}, {356.00, 52.19}, {347.00, 54.74}, - {344.38, 66.00}, {341.00, 70.27}, {335.00, 73.52}, {324.00, 72.38}, {317.00, 65.75}, {313.00, 67.79}, - {307.57, 76.00}, {315.00, 78.62}, {319.28, 82.00}, {322.23, 87.00}, {323.00, 94.41}, {334.00, 92.49}, - {347.00, 87.47}, {349.62, 80.00}, {353.00, 75.73}, {359.00, 72.48}, {366.00, 72.32}, {372.00, 74.94}, - {377.00, 81.34}, {382.00, 83.41}, {392.00, 83.40}, {399.00, 79.15}, {404.00, 85.74}, {411.00, 85.06}, - {417.00, 86.62}, {423.38, 93.00}, {425.05, 104.00}, {438.00, 110.35}, {450.00, 112.17}, {452.62, 103.00}, - {456.00, 98.73}, {462.00, 95.48}, {472.00, 95.79}, {471.28, 92.00}, {464.00, 84.62}, {445.00, 80.39}, - {436.00, 75.33}, {428.00, 68.46}, {419.00, 68.52}, {413.00, 65.27}, {408.48, 58.00}, {409.87, 46.00}, - {404.42, 39.00}, {408.00, 33.88}, {415.00, 29.31}, {429.00, 26.45}, {455.00, 28.77}, {470.00, 33.81}, - {482.00, 42.16}, {494.00, 46.85}, {499.65, 36.00}, {513.00, 25.95}, {529.00, 22.42}, {537.18, 23.00}, + {537.18, 23.00}, {520.50, 36.00}, {501.53, 63.00}, {496.14, 76.00}, {498.86, 86.00}, {504.00, 90.51}, {508.00, 91.36}, {508.77, 84.00}, {513.00, 77.73}, {519.00, 74.48}, {530.00, 74.67}, {545.00, 54.65}, + {554.00, 48.77}, {562.00, 46.39}, {568.00, 45.94}, {568.61, 47.00}, {567.94, 55.00}, {571.27, 64.00}, {572.92, 80.00}, {572.00, 81.39}, {563.00, 79.93}, {556.00, 82.69}, {551.49, 88.00}, {549.00, 95.76}, + {538.00, 93.40}, {530.00, 102.38}, {523.00, 104.00}, {517.00, 103.02}, {516.22, 109.00}, {518.96, 116.00}, {526.00, 121.15}, {534.00, 116.48}, {543.00, 116.77}, {549.28, 121.00}, {554.00, 130.17}, {564.00, 125.67}, + {575.60, 129.00}, {573.31, 121.00}, {567.77, 111.00}, {575.00, 106.47}, {578.51, 102.00}, {580.25, 95.00}, {577.98, 87.00}, {582.00, 85.71}, {597.00, 89.46}, {604.80, 95.00}, {609.28, 104.00}, {610.55, 116.00}, + {609.30, 125.00}, {600.80, 142.00}, {597.31, 155.00}, {584.00, 167.23}, {577.86, 175.00}, {583.52, 184.00}, {582.64, 195.00}, {591.00, 196.56}, {597.81, 201.00}, {607.45, 219.00}, {607.51, 246.00}, {600.00, 275.46}, + {588.00, 267.81}, {579.00, 264.91}, {557.00, 264.41}, {552.98, 259.00}, {548.00, 246.18}, {558.00, 247.12}, {565.98, 244.00}, {571.10, 237.00}, {571.61, 229.00}, {568.25, 222.00}, {562.00, 217.67}, {544.00, 213.93}, + {536.73, 214.00}, {535.60, 204.00}, {539.69, 181.00}, {542.84, 171.00}, {550.43, 161.00}, {540.00, 156.27}, {536.62, 152.00}, {534.70, 146.00}, {527.00, 141.88}, {518.59, 152.00}, {514.51, 160.00}, {510.33, 175.00}, + {519.38, 183.00}, {520.52, 194.00}, {516.00, 201.27}, {505.25, 206.00}, {507.57, 223.00}, {519.90, 260.00}, {529.00, 260.48}, {534.00, 262.94}, {538.38, 268.00}, {540.00, 275.00}, {537.06, 284.00}, {530.00, 289.23}, + {520.00, 289.23}, {513.00, 284.18}, {509.71, 286.00}, {501.69, 298.00}, {501.56, 305.00}, {504.30, 311.00}, {512.00, 316.43}, {521.00, 316.42}, {525.67, 314.00}, {535.00, 304.98}, {562.00, 294.80}, {573.00, 294.81}, + {587.52, 304.00}, {600.89, 310.00}, {596.96, 322.00}, {603.28, 327.00}, {606.52, 333.00}, {605.38, 344.00}, {597.65, 352.00}, {606.36, 375.00}, {607.16, 384.00}, {603.40, 393.00}, {597.00, 398.14}, {577.00, 386.15}, + {564.35, 373.00}, {565.21, 364.00}, {562.81, 350.00}, {553.00, 346.06}, {547.48, 338.00}, {547.48, 330.00}, {550.00, 323.30}, {544.00, 321.53}, {537.00, 322.70}, {532.00, 326.23}, {528.89, 331.00}, {527.83, 338.00}, + {533.02, 356.00}, {542.00, 360.73}, {546.68, 369.00}, {545.38, 379.00}, {537.58, 386.00}, {537.63, 388.00}, {555.00, 407.47}, {563.00, 413.52}, {572.57, 418.00}, {582.72, 426.00}, {578.00, 431.12}, {563.21, 440.00}, + {558.00, 449.27}, {549.00, 452.94}, {541.00, 451.38}, {536.73, 448.00}, {533.00, 441.87}, {520.00, 437.96}, {514.00, 429.69}, {490.00, 415.15}, {472.89, 399.00}, {472.03, 398.00}, {474.00, 396.71}, {486.00, 393.61}, + {492.00, 385.85}, {492.00, 376.15}, {489.04, 371.00}, {485.00, 368.11}, {480.00, 376.27}, {472.00, 379.82}, {463.00, 378.38}, {455.08, 372.00}, {446.00, 377.69}, {439.00, 385.24}, {436.61, 391.00}, {437.52, 404.00}, + {440.00, 409.53}, {463.53, 433.00}, {473.80, 441.00}, {455.00, 440.30}, {443.00, 436.18}, {436.00, 431.98}, {412.00, 440.92}, {397.00, 442.46}, {393.59, 431.00}, {393.71, 412.00}, {400.00, 395.10}, {407.32, 387.00}, + {408.54, 380.00}, {407.42, 375.00}, {403.97, 370.00}, {399.00, 366.74}, {393.00, 365.68}, {391.23, 374.00}, {387.00, 380.27}, {381.00, 383.52}, {371.56, 384.00}, {364.98, 401.00}, {362.96, 412.00}, {363.63, 435.00}, + {345.00, 433.55}, {344.52, 442.00}, {342.06, 447.00}, {337.00, 451.38}, {330.00, 453.00}, {325.00, 452.23}, {318.00, 448.17}, {298.00, 453.70}, {284.00, 451.49}, {278.62, 449.00}, {291.47, 408.00}, {291.77, 398.00}, + {301.00, 393.83}, {305.00, 393.84}, {305.60, 403.00}, {310.00, 409.47}, {318.00, 413.07}, {325.00, 412.40}, {332.31, 407.00}, {335.07, 400.00}, {334.40, 393.00}, {329.00, 385.69}, {319.00, 382.79}, {301.00, 389.23}, + {289.00, 389.97}, {265.00, 389.82}, {251.00, 385.85}, {245.00, 389.23}, {239.00, 389.94}, {233.00, 388.38}, {226.00, 382.04}, {206.00, 374.75}, {206.00, 394.00}, {204.27, 402.00}, {197.00, 401.79}, {191.00, 403.49}, + {186.53, 407.00}, {183.60, 412.00}, {183.60, 422.00}, {189.00, 429.31}, {196.00, 432.07}, {203.00, 431.40}, {209.47, 427.00}, {213.00, 419.72}, {220.00, 420.21}, {227.00, 418.32}, {242.00, 408.41}, {258.98, 409.00}, + {250.00, 435.43}, {239.00, 438.78}, {223.00, 448.19}, {209.00, 449.70}, {205.28, 456.00}, {199.00, 460.23}, {190.00, 460.52}, {182.73, 456.00}, {178.00, 446.27}, {160.00, 441.42}, {148.35, 435.00}, {149.79, 418.00}, + {157.72, 401.00}, {161.00, 396.53}, {177.00, 385.00}, {180.14, 380.00}, {181.11, 374.00}, {180.00, 370.52}, {170.00, 371.68}, {162.72, 368.00}, {158.48, 361.00}, {159.56, 349.00}, {154.00, 342.53}, {146.00, 339.85}, + {136.09, 343.00}, {130.64, 351.00}, {131.74, 362.00}, {140.61, 374.00}, {130.68, 387.00}, {120.75, 409.00}, {118.09, 421.00}, {117.92, 434.00}, {100.00, 432.40}, { 87.00, 427.48}, { 81.59, 423.00}, { 73.64, 409.00}, + { 72.57, 398.00}, { 74.62, 386.00}, { 78.80, 378.00}, { 88.00, 373.43}, { 92.49, 367.00}, { 93.32, 360.00}, { 91.30, 353.00}, {103.00, 342.67}, {109.00, 343.10}, {116.00, 340.44}, {127.33, 330.00}, {143.00, 327.24}, + {154.30, 322.00}, {145.00, 318.06}, {139.77, 311.00}, {139.48, 302.00}, {144.95, 293.00}, {143.00, 291.56}, {134.00, 298.21}, {118.00, 300.75}, {109.40, 305.00}, { 94.67, 319.00}, { 88.00, 318.93}, { 81.00, 321.69}, + { 67.24, 333.00}, { 56.68, 345.00}, { 53.00, 351.40}, { 47.34, 333.00}, { 50.71, 314.00}, { 56.57, 302.00}, { 68.00, 287.96}, { 91.00, 287.24}, {110.00, 282.36}, {133.80, 271.00}, {147.34, 256.00}, {156.47, 251.00}, + {157.26, 250.00}, {154.18, 242.00}, {154.48, 236.00}, {158.72, 229.00}, {166.71, 224.00}, {170.15, 206.00}, {170.19, 196.00}, {167.24, 188.00}, {160.00, 182.67}, {150.00, 182.66}, {143.60, 187.00}, {139.96, 195.00}, + {139.50, 207.00}, {136.45, 221.00}, {136.52, 232.00}, {133.28, 238.00}, {129.00, 241.38}, {119.00, 243.07}, {115.00, 246.55}, {101.00, 253.16}, { 86.00, 257.32}, { 63.00, 259.24}, { 57.00, 257.31}, { 50.54, 252.00}, + { 47.59, 247.00}, { 46.30, 240.00}, { 47.58, 226.00}, { 50.00, 220.57}, { 58.00, 226.41}, { 69.00, 229.17}, { 79.00, 229.08}, { 94.50, 225.00}, {100.21, 231.00}, {107.00, 233.47}, {107.48, 224.00}, {109.94, 219.00}, + {115.00, 214.62}, {122.57, 212.00}, {116.00, 201.49}, {104.00, 194.57}, { 90.00, 194.04}, { 79.00, 198.21}, { 73.00, 198.87}, { 62.68, 191.00}, { 62.58, 184.00}, { 64.42, 179.00}, { 75.00, 167.70}, { 80.39, 157.00}, + { 68.79, 140.00}, { 61.67, 126.00}, { 61.47, 117.00}, { 64.43, 109.00}, { 63.10, 96.00}, { 56.48, 82.00}, { 48.00, 73.88}, { 43.81, 66.00}, { 43.81, 56.00}, { 50.11, 46.00}, { 59.00, 41.55}, { 71.00, 42.64}, + { 78.00, 36.77}, { 83.00, 34.75}, { 99.00, 34.32}, {117.00, 38.92}, {133.00, 55.15}, {142.00, 50.70}, {149.74, 51.00}, {143.55, 68.00}, {153.28, 74.00}, {156.23, 79.00}, {157.00, 84.00}, {156.23, 89.00}, + {153.28, 94.00}, {144.58, 99.00}, {151.52, 112.00}, {151.51, 124.00}, {150.00, 126.36}, {133.00, 130.25}, {126.71, 125.00}, {122.00, 117.25}, {114.00, 116.23}, {107.73, 112.00}, {104.48, 106.00}, {104.32, 99.00}, + {106.94, 93.00}, {111.24, 89.00}, {111.60, 85.00}, {107.24, 73.00}, {102.00, 67.57}, { 99.79, 67.00}, { 99.23, 76.00}, { 95.00, 82.27}, { 89.00, 85.52}, { 79.84, 86.00}, { 86.73, 114.00}, { 98.00, 136.73}, + { 99.00, 137.61}, {109.00, 135.06}, {117.00, 137.94}, {122.52, 146.00}, {122.94, 151.00}, {121.00, 158.58}, {134.00, 160.97}, {153.00, 157.45}, {171.30, 150.00}, {169.06, 142.00}, {169.77, 136.00}, {174.00, 129.73}, + {181.46, 126.00}, {182.22, 120.00}, {182.20, 111.00}, {180.06, 101.00}, {171.28, 85.00}, {171.75, 80.00}, {182.30, 53.00}, {189.47, 50.00}, {190.62, 38.00}, {194.00, 33.73}, {199.00, 30.77}, {208.00, 30.48}, + {216.00, 34.94}, {224.00, 31.47}, {240.00, 30.37}, {247.00, 32.51}, {249.77, 35.00}, {234.75, 53.00}, {213.81, 93.00}, {212.08, 99.00}, {213.00, 101.77}, {220.00, 96.77}, {229.00, 96.48}, {236.28, 101.00}, + {240.00, 107.96}, {245.08, 101.00}, {263.00, 65.32}, {277.47, 48.00}, {284.00, 47.03}, {286.94, 41.00}, {292.00, 36.62}, {298.00, 35.06}, {304.00, 35.77}, {314.00, 43.81}, {342.00, 32.56}, {359.00, 31.32}, + {365.00, 32.57}, {371.00, 36.38}, {379.53, 48.00}, {379.70, 51.00}, {356.00, 52.19}, {347.00, 54.74}, {344.38, 66.00}, {341.00, 70.27}, {335.00, 73.52}, {324.00, 72.38}, {317.00, 65.75}, {313.00, 67.79}, + {307.57, 76.00}, {315.00, 78.62}, {319.28, 82.00}, {322.23, 87.00}, {323.00, 94.41}, {334.00, 92.49}, {347.00, 87.47}, {349.62, 80.00}, {353.00, 75.73}, {359.00, 72.48}, {366.00, 72.32}, {372.00, 74.94}, + {377.00, 81.34}, {382.00, 83.41}, {392.00, 83.40}, {399.00, 79.15}, {404.00, 85.74}, {411.00, 85.06}, {417.00, 86.62}, {423.38, 93.00}, {425.05, 104.00}, {438.00, 110.35}, {450.00, 112.17}, {452.62, 103.00}, + {456.00, 98.73}, {462.00, 95.48}, {472.00, 95.79}, {471.28, 92.00}, {464.00, 84.62}, {445.00, 80.39}, {436.00, 75.33}, {428.00, 68.46}, {419.00, 68.52}, {413.00, 65.27}, {408.48, 58.00}, {409.87, 46.00}, + {404.42, 39.00}, {408.00, 33.88}, {415.00, 29.31}, {429.00, 26.45}, {455.00, 28.77}, {470.00, 33.81}, {482.00, 42.16}, {494.00, 46.85}, {499.65, 36.00}, {513.00, 25.95}, {529.00, 22.42}, {537.18, 23.00}, }; -static int bouncy_terrain_count = sizeof(bouncy_terrain_verts) / sizeof(cpVect); +static int bouncy_terrain_count = sizeof(bouncy_terrain_verts)/sizeof(cpVect); -static cpSpace* init_BouncyTerrainCircles_500(void) -{ - cpSpace* space = BENCH_SPACE_NEW(); - cpSpaceSetIterations(space, 10); - - cpVect offset = cpv(-320, -240); - for (int i = 0; i < (bouncy_terrain_count - 1); i++) - { - cpVect a = bouncy_terrain_verts[i], b = bouncy_terrain_verts[i + 1]; - cpShape* shape = cpSpaceAddShape( - space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); - cpShapeSetElasticity(shape, 1.0); - } - - for (int i = 0; i < 500; i++) - { - cpFloat radius = 5.0f; - cpFloat mass = radius * radius; - cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); - cpBodySetPosition(body, cpvadd(cpvmult(frand_unit_circle(), 130.0f), cpvzero)); - cpBodySetVelocity(body, cpvmult(frand_unit_circle(), 50.0f)); - - cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); - cpShapeSetElasticity(shape, 1.0); - } - - return space; +static cpSpace *init_BouncyTerrainCircles_500(void){ + cpSpace *space = BENCH_SPACE_NEW(); + cpSpaceSetIterations(space, 10); + + cpVect offset = cpv(-320, -240); + for(int i=0; i<(bouncy_terrain_count - 1); i++){ + cpVect a = bouncy_terrain_verts[i], b = bouncy_terrain_verts[i+1]; + cpShape *shape = cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); + cpShapeSetElasticity(shape, 1.0); + } + + for(int i=0; i<500; i++){ + cpFloat radius = 5.0f; + cpFloat mass = radius*radius; + cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); + cpBodySetPosition(body, cpvadd(cpvmult(frand_unit_circle(), 130.0f), cpvzero)); + cpBodySetVelocity(body, cpvmult(frand_unit_circle(), 50.0f)); + + cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); + cpShapeSetElasticity(shape, 1.0); + } + + return space; } -static cpSpace* init_BouncyTerrainHexagons_500(void) -{ - cpSpace* space = BENCH_SPACE_NEW(); - cpSpaceSetIterations(space, 10); - - cpVect offset = cpv(-320, -240); - for (int i = 0; i < (bouncy_terrain_count - 1); i++) - { - cpVect a = bouncy_terrain_verts[i], b = bouncy_terrain_verts[i + 1]; - cpShape* shape = cpSpaceAddShape( - space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); - cpShapeSetElasticity(shape, 1.0); - } - - cpFloat radius = 5.0f; - cpVect hexagon[6]; - for (int i = 0; i < 6; i++) - { - cpFloat angle = -CP_PI * 2.0f * i / 6.0f; - hexagon[i] = cpvmult(cpv(cos(angle), sin(angle)), radius - bevel); - } - - for (int i = 0; i < 500; i++) - { - cpFloat mass = radius * radius; - cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 6, hexagon, cpvzero, 0.0f))); - cpBodySetPosition(body, cpvadd(cpvmult(frand_unit_circle(), 130.0f), cpvzero)); - cpBodySetVelocity(body, cpvmult(frand_unit_circle(), 50.0f)); - - cpShape* shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 6, hexagon, cpTransformIdentity, bevel)); - cpShapeSetElasticity(shape, 1.0); - } - - return space; +static cpSpace *init_BouncyTerrainHexagons_500(void){ + cpSpace *space = BENCH_SPACE_NEW(); + cpSpaceSetIterations(space, 10); + + cpVect offset = cpv(-320, -240); + for(int i=0; i<(bouncy_terrain_count - 1); i++){ + cpVect a = bouncy_terrain_verts[i], b = bouncy_terrain_verts[i+1]; + cpShape *shape = cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); + cpShapeSetElasticity(shape, 1.0); + } + + cpFloat radius = 5.0f; + cpVect hexagon[6]; + for(int i=0; i<6; i++){ + cpFloat angle = -CP_PI*2.0f*i/6.0f; + hexagon[i] = cpvmult(cpv(cos(angle), sin(angle)), radius - bevel); + } + + for(int i=0; i<500; i++){ + cpFloat mass = radius*radius; + cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 6, hexagon, cpvzero, 0.0f))); + cpBodySetPosition(body, cpvadd(cpvmult(frand_unit_circle(), 130.0f), cpvzero)); + cpBodySetVelocity(body, cpvmult(frand_unit_circle(), 50.0f)); + + cpShape *shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 6, hexagon, cpTransformIdentity, bevel)); + cpShapeSetElasticity(shape, 1.0); + } + + return space; } + // No collisions static cpFloat pentagon_mass = 0.0f; static cpFloat pentagon_moment = 0.0f; -static cpBool NoCollide_begin(cpArbiter* arb, cpSpace* space, void* data) -{ +static cpBool NoCollide_begin(cpArbiter *arb, cpSpace *space, void *data){ + + // CCLOG("NoCollide_begin"); - // CCLOG("NoCollide_begin"); - - return cpTrue; + return cpTrue; } -static cpSpace* init_NoCollide(void) -{ - cpSpace* space = BENCH_SPACE_NEW(); - cpSpaceSetIterations(space, 10); - cpCollisionHandler* handler = cpSpaceAddCollisionHandler(space, 2, 2); - handler->beginFunc = NoCollide_begin; - - float radius = 4.5f; - - cpShapeSetElasticity( - cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpv(-330 - radius, -250 - radius), - cpv(330 + radius, -250 - radius), 0.0f)), - 1.0f); - cpShapeSetElasticity( - cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpv(330 + radius, 250 + radius), - cpv(330 + radius, -250 - radius), 0.0f)), - 1.0f); - cpShapeSetElasticity( - cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpv(330 + radius, 250 + radius), - cpv(-330 - radius, 250 + radius), 0.0f)), - 1.0f); - cpShapeSetElasticity( - cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpv(-330 - radius, -250 - radius), - cpv(-330 - radius, 250 + radius), 0.0f)), - 1.0f); - - for (int x = -320; x <= 320; x += 20) - { - for (int y = -240; y <= 240; y += 20) - { - cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(cpSpaceGetStaticBody(space), radius, cpv(x, y))); - cpShapeSetElasticity(shape, 1.0); - cpShapeSetCollisionType(shape, 2); - } - } - - for (int y = 10 - 240; y <= 240; y += 40) - { - cpFloat mass = 7.0f; - cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); - cpBodySetPosition(body, cpv(-320.0f, y)); - cpBodySetVelocity(body, cpv(100.0f, 0.0f)); - - cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); - cpShapeSetElasticity(shape, 1.0); - cpShapeSetCollisionType(shape, 2); - } - - for (int x = 30 - 320; x <= 320; x += 40) - { - cpFloat mass = 7.0f; - cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); - cpBodySetPosition(body, cpv(x, -240.0f)); - cpBodySetVelocity(body, cpv(0.0f, 100.0f)); - - cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); - cpShapeSetElasticity(shape, 1.0); - cpShapeSetCollisionType(shape, 2); - } - - return space; +static cpSpace *init_NoCollide(void){ + cpSpace *space = BENCH_SPACE_NEW(); + cpSpaceSetIterations(space, 10); + + cpCollisionHandler *handler = cpSpaceAddCollisionHandler(space, 2, 2); + handler->beginFunc = NoCollide_begin; + + + float radius = 4.5f; + + cpShapeSetElasticity(cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpv(-330-radius, -250-radius), cpv( 330+radius, -250-radius), 0.0f)), 1.0f); + cpShapeSetElasticity(cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpv( 330+radius, 250+radius), cpv( 330+radius, -250-radius), 0.0f)), 1.0f); + cpShapeSetElasticity(cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpv( 330+radius, 250+radius), cpv(-330-radius, 250+radius), 0.0f)), 1.0f); + cpShapeSetElasticity(cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpv(-330-radius, -250-radius), cpv(-330-radius, 250+radius), 0.0f)), 1.0f); + + for(int x=-320; x<=320; x+=20){ + for(int y=-240; y<=240; y+=20){ + cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(cpSpaceGetStaticBody(space), radius, cpv(x, y))); + cpShapeSetElasticity(shape, 1.0); + cpShapeSetCollisionType(shape, 2); + } + } + + for(int y=10-240; y<=240; y+=40){ + cpFloat mass = 7.0f; + cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); + cpBodySetPosition(body, cpv(-320.0f, y)); + cpBodySetVelocity(body, cpv(100.0f, 0.0f)); + + cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); + cpShapeSetElasticity(shape, 1.0); + cpShapeSetCollisionType(shape, 2); + } + + for(int x=30-320; x<=320; x+=40){ + cpFloat mass = 7.0f; + cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); + cpBodySetPosition(body, cpv(x, -240.0f)); + cpBodySetVelocity(body, cpv(0.0f, 100.0f)); + + cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); + cpShapeSetElasticity(shape, 1.0); + cpShapeSetCollisionType(shape, 2); + } + + return space; } + // TODO ideas: // addition/removal // Memory usage? (too small to matter?) // http://forums.tigsource.com/index.php?topic=18077.msg518578#msg518578 + // Build benchmark list -static void update(cpSpace* space, double dt) -{ - BENCH_SPACE_STEP(space, dt); +static void update(cpSpace *space, double dt){ + BENCH_SPACE_STEP(space, dt); } -static void destroy(cpSpace* space) -{ - ChipmunkDemoFreeSpaceChildren(space); - BENCH_SPACE_FREE(space); +static void destroy(cpSpace *space){ + ChipmunkDemoFreeSpaceChildren(space); + BENCH_SPACE_FREE(space); } // Make a second demo declaration for this demo to use in the regular demo set. ChipmunkDemo BouncyHexagons = { - "Bouncy Hexagons", 1.0 / 60.0, init_BouncyTerrainHexagons_500, update, ChipmunkDemoDefaultDrawImpl, destroy, + "Bouncy Hexagons", + 1.0/60.0, + init_BouncyTerrainHexagons_500, + update, + ChipmunkDemoDefaultDrawImpl, + destroy, }; -#define BENCH(n) \ - { \ -# n, 1.0 / 60.0, init_##n, update, ChipmunkDemoDefaultDrawImpl, destroy \ - } +#define BENCH(n) {#n, 1.0/60.0, init_##n, update, ChipmunkDemoDefaultDrawImpl, destroy} ChipmunkDemo bench_list[] = { - BENCH(SimpleTerrainCircles_1000), - BENCH(SimpleTerrainCircles_500), - BENCH(SimpleTerrainCircles_100), - BENCH(SimpleTerrainBoxes_1000), - BENCH(SimpleTerrainBoxes_500), - BENCH(SimpleTerrainBoxes_100), - BENCH(SimpleTerrainHexagons_1000), - BENCH(SimpleTerrainHexagons_500), - BENCH(SimpleTerrainHexagons_100), - BENCH(SimpleTerrainVCircles_200), - BENCH(SimpleTerrainVBoxes_200), - BENCH(SimpleTerrainVHexagons_200), - BENCH(ComplexTerrainCircles_1000), - BENCH(ComplexTerrainHexagons_1000), - BENCH(BouncyTerrainCircles_500), - BENCH(BouncyTerrainHexagons_500), - BENCH(NoCollide), + BENCH(SimpleTerrainCircles_1000), + BENCH(SimpleTerrainCircles_500), + BENCH(SimpleTerrainCircles_100), + BENCH(SimpleTerrainBoxes_1000), + BENCH(SimpleTerrainBoxes_500), + BENCH(SimpleTerrainBoxes_100), + BENCH(SimpleTerrainHexagons_1000), + BENCH(SimpleTerrainHexagons_500), + BENCH(SimpleTerrainHexagons_100), + BENCH(SimpleTerrainVCircles_200), + BENCH(SimpleTerrainVBoxes_200), + BENCH(SimpleTerrainVHexagons_200), + BENCH(ComplexTerrainCircles_1000), + BENCH(ComplexTerrainHexagons_1000), + BENCH(BouncyTerrainCircles_500), + BENCH(BouncyTerrainHexagons_500), + BENCH(NoCollide), }; -int bench_count = sizeof(bench_list) / sizeof(ChipmunkDemo); +int bench_count = sizeof(bench_list)/sizeof(ChipmunkDemo); diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Buoyancy.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Buoyancy.c index 05224adbf8..71b607e779 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Buoyancy.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Buoyancy.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -23,9 +23,10 @@ #include "ChipmunkDemo.h" -static void update(cpSpace* space, double dt) +static void +update(cpSpace *space, double dt) { - cpSpaceStep(space, dt); + cpSpaceStep(space, dt); } #define FLUID_DENSITY 0.00014 @@ -34,187 +35,193 @@ static void update(cpSpace* space, double dt) char messageBuffer[1024]; // Modified from chipmunk_private.h -static inline cpFloat k_scalar_body(cpBody* body, cpVect point, cpVect n) +static inline cpFloat +k_scalar_body(cpBody *body, cpVect point, cpVect n) { - cpFloat rcn = cpvcross(cpvsub(point, cpBodyGetPosition(body)), n); - return 1.0f / cpBodyGetMass(body) + rcn * rcn / cpBodyGetMoment(body); + cpFloat rcn = cpvcross(cpvsub(point, cpBodyGetPosition(body)), n); + return 1.0f/cpBodyGetMass(body) + rcn*rcn/cpBodyGetMoment(body); } -static cpBool waterPreSolve(cpArbiter* arb, cpSpace* space, void* ptr) +static cpBool +waterPreSolve(cpArbiter *arb, cpSpace *space, void *ptr) { - CP_ARBITER_GET_SHAPES(arb, water, poly); - cpBody* body = cpShapeGetBody(poly); - - // Get the top of the water sensor bounding box to use as the water level. - cpFloat level = cpShapeGetBB(water).t; - - // Clip the polygon against the water level - int count = cpPolyShapeGetCount(poly); - int clippedCount = 0; + CP_ARBITER_GET_SHAPES(arb, water, poly); + cpBody *body = cpShapeGetBody(poly); + + // Get the top of the water sensor bounding box to use as the water level. + cpFloat level = cpShapeGetBB(water).t; + + // Clip the polygon against the water level + int count = cpPolyShapeGetCount(poly); + int clippedCount = 0; #ifdef _MSC_VER - // MSVC is pretty much the only compiler in existence that doesn't support variable sized arrays. - cpVect clipped[10]; + // MSVC is pretty much the only compiler in existence that doesn't support variable sized arrays. + cpVect clipped[10]; #else - cpVect clipped[count + 1]; + cpVect clipped[count + 1]; #endif - for (int i = 0, j = count - 1; i < count; j = i, i++) - { - cpVect a = cpBodyLocalToWorld(body, cpPolyShapeGetVert(poly, j)); - cpVect b = cpBodyLocalToWorld(body, cpPolyShapeGetVert(poly, i)); - - if (a.y < level) - { - clipped[clippedCount] = a; - clippedCount++; - } - - cpFloat a_level = a.y - level; - cpFloat b_level = b.y - level; - - if (a_level * b_level < 0.0f) - { - cpFloat t = cpfabs(a_level) / (cpfabs(a_level) + cpfabs(b_level)); - - clipped[clippedCount] = cpvlerp(a, b, t); - clippedCount++; - } - } - - // Calculate buoyancy from the clipped polygon area - cpFloat clippedArea = cpAreaForPoly(clippedCount, clipped, 0.0f); - cpFloat displacedMass = clippedArea * FLUID_DENSITY; - cpVect centroid = cpCentroidForPoly(clippedCount, clipped); - - ChipmunkDebugDrawPolygon(clippedCount, clipped, 5.0f, RGBAColor(0, 0, 1, 1), RGBAColor(0, 0, 1, 0.1f)); - ChipmunkDebugDrawDot(5, centroid, RGBAColor(0, 0, 1, 1)); - - cpFloat dt = cpSpaceGetCurrentTimeStep(space); - cpVect g = cpSpaceGetGravity(space); - - // Apply the buoyancy force as an impulse. - cpBodyApplyImpulseAtWorldPoint(body, cpvmult(g, -displacedMass * dt), centroid); - - // Apply linear damping for the fluid drag. - cpVect v_centroid = cpBodyGetVelocityAtWorldPoint(body, centroid); - cpFloat k = k_scalar_body(body, centroid, cpvnormalize(v_centroid)); - cpFloat damping = clippedArea * FLUID_DRAG * FLUID_DENSITY; - cpFloat v_coef = cpfexp(-damping * dt * k); // linear drag - // cpFloat v_coef = 1.0/(1.0 + damping*dt*cpvlength(v_centroid)*k); // quadratic drag - cpBodyApplyImpulseAtWorldPoint(body, cpvmult(cpvsub(cpvmult(v_centroid, v_coef), v_centroid), 1.0 / k), centroid); - - // Apply angular damping for the fluid drag. - cpVect cog = cpBodyLocalToWorld(body, cpBodyGetCenterOfGravity(body)); - cpFloat w_damping = - cpMomentForPoly(FLUID_DRAG * FLUID_DENSITY * clippedArea, clippedCount, clipped, cpvneg(cog), 0.0f); - cpBodySetAngularVelocity(body, cpBodyGetAngularVelocity(body) * cpfexp(-w_damping * dt / cpBodyGetMoment(body))); - - return cpTrue; + for(int i=0, j=count-1; ipreSolveFunc = (cpCollisionPreSolveFunc)waterPreSolve; - - return space; + { + cpFloat width = 200.0f; + cpFloat height = 50.0f; + cpFloat mass = 0.3*FLUID_DENSITY*width*height; + cpFloat moment = cpMomentForBox(mass, width, height); + + body = cpSpaceAddBody(space, cpBodyNew(mass, moment)); + cpBodySetPosition(body, cpv(-50, -100)); + cpBodySetVelocity(body, cpv(0, -100)); + cpBodySetAngularVelocity(body, 1); + + shape = cpSpaceAddShape(space, cpBoxShapeNew(body, width, height, 0.0)); + cpShapeSetFriction(shape, 0.8f); + } + + { + cpFloat width = 40.0f; + cpFloat height = width*2; + cpFloat mass = 0.3*FLUID_DENSITY*width*height; + cpFloat moment = cpMomentForBox(mass, width, height); + + body = cpSpaceAddBody(space, cpBodyNew(mass, moment)); + cpBodySetPosition(body, cpv(-200, -50)); + cpBodySetVelocity(body, cpv(0, -100)); + cpBodySetAngularVelocity(body, 1); + + shape = cpSpaceAddShape(space, cpBoxShapeNew(body, width, height, 0.0)); + cpShapeSetFriction(shape, 0.8f); + } + + cpCollisionHandler *handler = cpSpaceAddCollisionHandler(space, 1, 0); + handler->preSolveFunc = (cpCollisionPreSolveFunc)waterPreSolve; + + return space; } -static void destroy(cpSpace* space) +static void +destroy(cpSpace *space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo Buoyancy = { - "Simple Sensor based fluids.", 1.0 / 180.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, + "Simple Sensor based fluids.", + 1.0/180.0, + init, + update, + ChipmunkDemoDefaultDrawImpl, + destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Chains.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Chains.c index 41cbf8cd2a..e1c727060b 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Chains.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Chains.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,132 +18,133 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" #define CHAIN_COUNT 8 #define LINK_COUNT 10 -static void BreakablejointPostStepRemove(cpSpace* space, cpConstraint* joint, void* unused) +static void +BreakablejointPostStepRemove(cpSpace *space, cpConstraint *joint, void *unused) { - cpSpaceRemoveConstraint(space, joint); - cpConstraintFree(joint); + cpSpaceRemoveConstraint(space, joint); + cpConstraintFree(joint); } -static void BreakableJointPostSolve(cpConstraint* joint, cpSpace* space) +static void +BreakableJointPostSolve(cpConstraint *joint, cpSpace *space) { - cpFloat dt = cpSpaceGetCurrentTimeStep(space); + cpFloat dt = cpSpaceGetCurrentTimeStep(space); + + // Convert the impulse to a force by dividing it by the timestep. + cpFloat force = cpConstraintGetImpulse(joint)/dt; + cpFloat maxForce = cpConstraintGetMaxForce(joint); - // Convert the impulse to a force by dividing it by the timestep. - cpFloat force = cpConstraintGetImpulse(joint) / dt; - cpFloat maxForce = cpConstraintGetMaxForce(joint); - - // If the force is almost as big as the joint's max force, break it. - if (force > 0.9 * maxForce) - { - cpSpaceAddPostStepCallback(space, (cpPostStepFunc)BreakablejointPostStepRemove, joint, NULL); - } + // If the force is almost as big as the joint's max force, break it. + if(force > 0.9*maxForce){ + cpSpaceAddPostStepCallback(space, (cpPostStepFunc)BreakablejointPostStepRemove, joint, NULL); + } } -static void update(cpSpace* space, double dt) +static void +update(cpSpace *space, double dt) { - cpSpaceStep(space, dt); + cpSpaceStep(space, dt); } -static cpSpace* init(void) +static cpSpace * +init(void) { - cpSpace* space = cpSpaceNew(); - cpSpaceSetIterations(space, 30); - cpSpaceSetGravity(space, cpv(0, -100)); - cpSpaceSetSleepTimeThreshold(space, 0.5f); + cpSpace *space = cpSpaceNew(); + cpSpaceSetIterations(space, 30); + cpSpaceSetGravity(space, cpv(0, -100)); + cpSpaceSetSleepTimeThreshold(space, 0.5f); + + cpBody *body, *staticBody = cpSpaceGetStaticBody(space); + cpShape *shape; + + // Create segments around the edge of the screen. + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - cpBody *body, *staticBody = cpSpaceGetStaticBody(space); - cpShape* shape; + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - // Create segments around the edge of the screen. - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(-320, 240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,240), cpv(320,240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + cpFloat mass = 1; + cpFloat width = 20; + cpFloat height = 30; + + cpFloat spacing = width*0.3; + + // Add lots of boxes. + for(int i=0; imagnitudeSum += cpvlength(j); - context->vectorSum = cpvadd(context->vectorSum, j); + cpVect j = cpArbiterTotalImpulse(arb); + context->magnitudeSum += cpvlength(j); + context->vectorSum = cpvadd(context->vectorSum, j); } #endif -static void update(cpSpace* space, double dt) +static void +update(cpSpace *space, double dt) { - cpSpaceStep(space, dt); - - ChipmunkDemoPrintString("Place objects on the scale to weigh them. The ball marks the shapes it's sitting on.\n"); - -// Sum the total impulse applied to the scale from all collision pairs in the contact graph. -// If your compiler supports blocks, your life is a little easier. -// You can use the "Block" versions of the functions without needing the callbacks above. -#if USE_BLOCKS - __block cpVect impulseSum = cpvzero; - cpBodyEachArbiter_b(scaleStaticBody, ^(cpArbiter* arb) { - impulseSum = cpvadd(impulseSum, cpArbiterTotalImpulse(arb)); - }); -#else - cpVect impulseSum = cpvzero; - cpBodyEachArbiter(scaleStaticBody, (cpBodyArbiterIteratorFunc)ScaleIterator, &impulseSum); -#endif - - // Force is the impulse divided by the timestep. - cpFloat force = cpvlength(impulseSum) / dt; - - // Weight can be found similarly from the gravity vector. - cpVect g = cpSpaceGetGravity(space); - cpFloat weight = cpvdot(g, impulseSum) / (cpvlengthsq(g) * dt); - - ChipmunkDemoPrintString("Total force: %5.2f, Total weight: %5.2f. ", force, weight); - -// Highlight and count the number of shapes the ball is touching. -#if USE_BLOCKS - __block int count = 0; - cpBodyEachArbiter_b(ballBody, ^(cpArbiter* arb) { - // body is the body we are iterating the arbiters for. - // CP_ARBITER_GET_*() in an arbiter iterator always returns the body/shape for the iterated body first. - CP_ARBITER_GET_SHAPES(arb, ball, other); - ChipmunkDebugDrawBB(cpShapeGetBB(other), RGBAColor(1, 0, 0, 1)); - - count++; - }); -#else - int count = 0; - cpBodyEachArbiter(ballBody, (cpBodyArbiterIteratorFunc)BallIterator, &count); -#endif - - ChipmunkDemoPrintString("The ball is touching %d shapes.\n", count); - -#if USE_BLOCKS - __block cpFloat magnitudeSum = 0.0f; - __block cpVect vectorSum = cpvzero; - cpBodyEachArbiter_b(ballBody, ^(cpArbiter* arb) { - cpVect j = cpArbiterTotalImpulse(arb); - magnitudeSum += cpvlength(j); - vectorSum = cpvadd(vectorSum, j); - }); - - cpFloat crushForce = (magnitudeSum - cpvlength(vectorSum)) * dt; -#else - struct CrushingContext crush = {0.0f, cpvzero}; - cpBodyEachArbiter(ballBody, (cpBodyArbiterIteratorFunc)EstimateCrushing, &crush); - - cpFloat crushForce = (crush.magnitudeSum - cpvlength(crush.vectorSum)) * dt; -#endif - - if (crushForce > 10.0f) - { - ChipmunkDemoPrintString("The ball is being crushed. (f: %.2f)", crushForce); - } - else - { - ChipmunkDemoPrintString("The ball is not being crushed. (f: %.2f)", crushForce); - } + cpSpaceStep(space, dt); + + ChipmunkDemoPrintString("Place objects on the scale to weigh them. The ball marks the shapes it's sitting on.\n"); + + // Sum the total impulse applied to the scale from all collision pairs in the contact graph. + // If your compiler supports blocks, your life is a little easier. + // You can use the "Block" versions of the functions without needing the callbacks above. + #if USE_BLOCKS + __block cpVect impulseSum = cpvzero; + cpBodyEachArbiter_b(scaleStaticBody, ^(cpArbiter *arb){ + impulseSum = cpvadd(impulseSum, cpArbiterTotalImpulse(arb)); + }); + #else + cpVect impulseSum = cpvzero; + cpBodyEachArbiter(scaleStaticBody, (cpBodyArbiterIteratorFunc)ScaleIterator, &impulseSum); + #endif + + // Force is the impulse divided by the timestep. + cpFloat force = cpvlength(impulseSum)/dt; + + // Weight can be found similarly from the gravity vector. + cpVect g = cpSpaceGetGravity(space); + cpFloat weight = cpvdot(g, impulseSum)/(cpvlengthsq(g)*dt); + + ChipmunkDemoPrintString("Total force: %5.2f, Total weight: %5.2f. ", force, weight); + + + // Highlight and count the number of shapes the ball is touching. + #if USE_BLOCKS + __block int count = 0; + cpBodyEachArbiter_b(ballBody, ^(cpArbiter *arb){ + // body is the body we are iterating the arbiters for. + // CP_ARBITER_GET_*() in an arbiter iterator always returns the body/shape for the iterated body first. + CP_ARBITER_GET_SHAPES(arb, ball, other); + ChipmunkDebugDrawBB(cpShapeGetBB(other), RGBAColor(1, 0, 0, 1)); + + count++; + }); + #else + int count = 0; + cpBodyEachArbiter(ballBody, (cpBodyArbiterIteratorFunc)BallIterator, &count); + #endif + + ChipmunkDemoPrintString("The ball is touching %d shapes.\n", count); + + #if USE_BLOCKS + __block cpFloat magnitudeSum = 0.0f; + __block cpVect vectorSum = cpvzero; + cpBodyEachArbiter_b(ballBody, ^(cpArbiter *arb){ + cpVect j = cpArbiterTotalImpulse(arb); + magnitudeSum += cpvlength(j); + vectorSum = cpvadd(vectorSum, j); + }); + + cpFloat crushForce = (magnitudeSum - cpvlength(vectorSum))*dt; + #else + struct CrushingContext crush = {0.0f, cpvzero}; + cpBodyEachArbiter(ballBody, (cpBodyArbiterIteratorFunc)EstimateCrushing, &crush); + + cpFloat crushForce = (crush.magnitudeSum - cpvlength(crush.vectorSum))*dt; + #endif + + + if(crushForce > 10.0f){ + ChipmunkDemoPrintString("The ball is being crushed. (f: %.2f)", crushForce); + } else { + ChipmunkDemoPrintString("The ball is not being crushed. (f: %.2f)", crushForce); + } } #define WIDTH 4.0f #define HEIGHT 30.0f -static cpSpace* init(void) +static cpSpace * +init(void) { - cpSpace* space = cpSpaceNew(); - cpSpaceSetIterations(space, 30); - cpSpaceSetGravity(space, cpv(0, -300)); - cpSpaceSetCollisionSlop(space, 0.5); - cpSpaceSetSleepTimeThreshold(space, 1.0f); + cpSpace *space = cpSpaceNew(); + cpSpaceSetIterations(space, 30); + cpSpaceSetGravity(space, cpv(0, -300)); + cpSpaceSetCollisionSlop(space, 0.5); + cpSpaceSetSleepTimeThreshold(space, 1.0f); + + cpBody *body, *staticBody = cpSpaceGetStaticBody(space); + cpShape *shape; + + // Create segments around the edge of the screen. + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(-320, 240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - cpBody *body, *staticBody = cpSpaceGetStaticBody(space); - cpShape* shape; + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320, -240), cpv(320, 240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - // Create segments around the edge of the screen. - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(-320, 240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(320, -240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + scaleStaticBody = cpSpaceAddBody(space, cpBodyNewStatic()); + shape = cpSpaceAddShape(space, cpSegmentShapeNew(scaleStaticBody, cpv(-240,-180), cpv(-140,-180), 4.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + // add some boxes to stack on the scale + for(int i=0; i<5; i++){ + body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForBox(1.0f, 30.0f, 30.0f))); + cpBodySetPosition(body, cpv(0, i*32 - 120)); + + shape = cpSpaceAddShape(space, cpBoxShapeNew(body, 30.0f, 30.0f, 0.0)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.8f); + } + + // Add a ball that we'll track which objects are beneath it. + cpFloat radius = 15.0f; + ballBody = cpSpaceAddBody(space, cpBodyNew(10.0f, cpMomentForCircle(10.0f, 0.0f, radius, cpvzero))); + cpBodySetPosition(ballBody, cpv(120, -140 + radius+5)); - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320, -240), cpv(320, 240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(320, -240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - scaleStaticBody = cpSpaceAddBody(space, cpBodyNewStatic()); - shape = cpSpaceAddShape(space, cpSegmentShapeNew(scaleStaticBody, cpv(-240, -180), cpv(-140, -180), 4.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - // add some boxes to stack on the scale - for (int i = 0; i < 5; i++) - { - body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForBox(1.0f, 30.0f, 30.0f))); - cpBodySetPosition(body, cpv(0, i * 32 - 120)); - - shape = cpSpaceAddShape(space, cpBoxShapeNew(body, 30.0f, 30.0f, 0.0)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.8f); - } - - // Add a ball that we'll track which objects are beneath it. - cpFloat radius = 15.0f; - ballBody = cpSpaceAddBody(space, cpBodyNew(10.0f, cpMomentForCircle(10.0f, 0.0f, radius, cpvzero))); - cpBodySetPosition(ballBody, cpv(120, -140 + radius + 5)); - - shape = cpSpaceAddShape(space, cpCircleShapeNew(ballBody, radius, cpvzero)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.9f); - - return space; + shape = cpSpaceAddShape(space, cpCircleShapeNew(ballBody, radius, cpvzero)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.9f); + + return space; } -static void destroy(cpSpace* space) +static void +destroy(cpSpace *space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo ContactGraph = { - "Contact Graph", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, + "Contact Graph", + 1.0/60.0, + init, + update, + ChipmunkDemoDefaultDrawImpl, + destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Convex.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Convex.c index b4e457f26b..72d5506074 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Convex.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Convex.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,93 +18,99 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "chipmunk/chipmunk_unsafe.h" #include "ChipmunkDemo.h" -#define DENSITY (1.0 / 10000.0) +#define DENSITY (1.0/10000.0) -static cpShape* shape; +static cpShape *shape; -static void update(cpSpace* space, double dt) +static void +update(cpSpace *space, double dt) { - cpFloat tolerance = 2.0; - - if (ChipmunkDemoRightClick && cpShapePointQuery(shape, ChipmunkDemoMouse, NULL) > tolerance) - { - cpBody* body = cpShapeGetBody(shape); - int count = cpPolyShapeGetCount(shape); - - // Allocate the space for the new vertexes on the stack. - cpVect* verts = (cpVect*)alloca((count + 1) * sizeof(cpVect)); - - for (int i = 0; i < count; i++) - { - verts[i] = cpPolyShapeGetVert(shape, i); - } - - verts[count] = cpBodyWorldToLocal(body, ChipmunkDemoMouse); - - // This function builds a convex hull for the vertexes. - // Because the result array is the same as verts, it will reduce it in place. - int hullCount = cpConvexHull(count + 1, verts, verts, NULL, tolerance); - - // Figure out how much to shift the body by. - cpVect centroid = cpCentroidForPoly(hullCount, verts); - - // Recalculate the body properties to match the updated shape. - cpFloat mass = cpAreaForPoly(hullCount, verts, 0.0f) * DENSITY; - cpBodySetMass(body, mass); - cpBodySetMoment(body, cpMomentForPoly(mass, hullCount, verts, cpvneg(centroid), 0.0f)); - cpBodySetPosition(body, cpBodyLocalToWorld(body, centroid)); - - // Use the setter function from chipmunk_unsafe.h. - // You could also remove and recreate the shape if you wanted. - cpPolyShapeSetVerts(shape, hullCount, verts, cpTransformTranslate(cpvneg(centroid))); - } - - cpSpaceStep(space, dt); + cpFloat tolerance = 2.0; + + if(ChipmunkDemoRightClick && cpShapePointQuery(shape, ChipmunkDemoMouse, NULL) > tolerance){ + cpBody *body = cpShapeGetBody(shape); + int count = cpPolyShapeGetCount(shape); + + // Allocate the space for the new vertexes on the stack. + cpVect *verts = (cpVect *)alloca((count + 1)*sizeof(cpVect)); + + for(int i=0; ibeginFunc = (cpCollisionBeginFunc)HookCrate; - - return space; + ChipmunkDemoMessageString = "Control the crane by moving the mouse. Right click to release."; + + cpSpace *space = cpSpaceNew(); + cpSpaceSetIterations(space, 30); + cpSpaceSetGravity(space, cpv(0, -100)); + cpSpaceSetDamping(space, 0.8); + + cpBody *staticBody = cpSpaceGetStaticBody(space); + cpShape *shape; + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + // Add a body for the dolly. + dollyBody = cpSpaceAddBody(space, cpBodyNew(10, INFINITY)); + cpBodySetPosition(dollyBody, cpv(0, 100)); + + // Add a block so you can see it. + cpSpaceAddShape(space, cpBoxShapeNew(dollyBody, 30, 30, 0.0)); + + // Add a groove joint for it to move back and forth on. + cpSpaceAddConstraint(space, cpGrooveJointNew(staticBody, dollyBody, cpv(-250, 100), cpv(250, 100), cpvzero)); + + // Add a pivot joint to act as a servo motor controlling it's position + // By updating the anchor points of the pivot joint, you can move the dolly. + dollyServo = cpSpaceAddConstraint(space, cpPivotJointNew(staticBody, dollyBody, cpBodyGetPosition(dollyBody))); + // Max force the dolly servo can generate. + cpConstraintSetMaxForce(dollyServo, 10000); + // Max speed of the dolly servo + cpConstraintSetMaxBias(dollyServo, 100); + // You can also change the error bias to control how it slows down. + //cpConstraintSetErrorBias(dollyServo, 0.2); + + + // Add the crane hook. + cpBody *hookBody = cpSpaceAddBody(space, cpBodyNew(1, INFINITY)); + cpBodySetPosition(hookBody, cpv(0, 50)); + + // Add a sensor shape for it. This will be used to figure out when the hook touches a box. + shape = cpSpaceAddShape(space, cpCircleShapeNew(hookBody, 10, cpvzero)); + cpShapeSetSensor(shape, cpTrue); + cpShapeSetCollisionType(shape, HOOK_SENSOR); + + // Add a slide joint to act as a winch motor + // By updating the max length of the joint you can make it pull up the load. + winchServo = cpSpaceAddConstraint(space, cpSlideJointNew(dollyBody, hookBody, cpvzero, cpvzero, 0, INFINITY)); + // Max force the dolly servo can generate. + cpConstraintSetMaxForce(winchServo, 30000); + // Max speed of the dolly servo + cpConstraintSetMaxBias(winchServo, 60); + + // TODO: cleanup + // Finally a box to play with + cpBody *boxBody = cpSpaceAddBody(space, cpBodyNew(30, cpMomentForBox(30, 50, 50))); + cpBodySetPosition(boxBody, cpv(200, -200)); + + // Add a block so you can see it. + shape = cpSpaceAddShape(space, cpBoxShapeNew(boxBody, 50, 50, 0.0)); + cpShapeSetFriction(shape, 0.7); + cpShapeSetCollisionType(shape, CRATE); + + cpCollisionHandler *handler = cpSpaceAddCollisionHandler(space, HOOK_SENSOR, CRATE); + handler->beginFunc = (cpCollisionBeginFunc)HookCrate; + + + return space; } -static void destroy(cpSpace* space) +static void +destroy(cpSpace *space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo Crane = { - "Crane", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, + "Crane", + 1.0/60.0, + init, + update, + ChipmunkDemoDefaultDrawImpl, + destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Example.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Example.c index d3436dda5a..75279f5779 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Example.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Example.c @@ -29,13 +29,12 @@ #include "chipmunk/chipmunk_unsafe.h" #include "ChipmunkDemo.h" -static void update(cpSpace* space, double dt) -{ +static void update(cpSpace* space, double dt) { cpSpaceStep(space, dt); } -static cpSpace* init(void) -{ + +static cpSpace* init(void) { cpSpace* space = cpSpaceNew(); cpSpaceSetIterations(space, 5); space->damping = 0.1; @@ -44,6 +43,7 @@ static cpSpace* init(void) cpFloat mass = 1.0f; + { cpFloat size = 100.0; @@ -67,9 +67,8 @@ static cpSpace* init(void) const int NUM_VERTS = 5; cpVect verts[NUM_VERTS]; - for (int i = 0; i < NUM_VERTS; i++) - { - cpFloat angle = -2 * M_PI * i / ((cpFloat)NUM_VERTS); + for (int i = 0; i < NUM_VERTS; i++) { + cpFloat angle = -2 * M_PI * i / ((cpFloat) NUM_VERTS); verts[i] = cpv(size / 2.0 * cos(angle), size / 2.0 * sin(angle)); } @@ -83,9 +82,8 @@ static cpSpace* init(void) const int NUM_VERTS = 4; cpVect verts[NUM_VERTS]; - for (int i = 0; i < NUM_VERTS; i++) - { - cpFloat angle = -2 * M_PI * i / ((cpFloat)NUM_VERTS); + for (int i = 0; i < NUM_VERTS; i++) { + cpFloat angle = -2 * M_PI * i / ((cpFloat) NUM_VERTS); verts[i] = cpv(size / 2.0 * cos(angle), size / 2.0 * sin(angle)); } @@ -117,12 +115,16 @@ static cpSpace* init(void) return space; } -static void destroy(cpSpace* space) -{ +static void destroy(cpSpace* space) { ChipmunkDemoFreeSpaceChildren(space); cpSpaceFree(space); } ChipmunkDemo Example = { - "Template to start (GJK)", 1.0f / 60.0f, init, update, ChipmunkDemoDefaultDrawImpl, destroy, + "Template to start (GJK)", + 1.0f / 60.0f, + init, + update, + ChipmunkDemoDefaultDrawImpl, + destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Joints.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Joints.c index db27fe8053..3a7f23a6e1 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Joints.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Joints.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,267 +18,281 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" -static cpBody* addBall(cpSpace* space, cpVect pos, cpVect boxOffset) +static cpBody * +addBall(cpSpace *space, cpVect pos, cpVect boxOffset) { - cpFloat radius = 15.0f; - cpFloat mass = 1.0f; - cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); - cpBodySetPosition(body, cpvadd(pos, boxOffset)); - - cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.7f); - - return body; + cpFloat radius = 15.0f; + cpFloat mass = 1.0f; + cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); + cpBodySetPosition(body, cpvadd(pos, boxOffset)); + + cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.7f); + + return body; } -static cpBody* addLever(cpSpace* space, cpVect pos, cpVect boxOffset) +static cpBody * +addLever(cpSpace *space, cpVect pos, cpVect boxOffset) { - cpFloat mass = 1.0f; - cpVect a = cpv(0, 15); - cpVect b = cpv(0, -15); - - cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForSegment(mass, a, b, 0.0f))); - cpBodySetPosition(body, cpvadd(pos, cpvadd(boxOffset, cpv(0, -15)))); - - cpShape* shape = cpSpaceAddShape(space, cpSegmentShapeNew(body, a, b, 5.0f)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.7f); - - return body; + cpFloat mass = 1.0f; + cpVect a = cpv(0, 15); + cpVect b = cpv(0, -15); + + cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForSegment(mass, a, b, 0.0f))); + cpBodySetPosition(body, cpvadd(pos, cpvadd(boxOffset, cpv(0, -15)))); + + cpShape *shape = cpSpaceAddShape(space, cpSegmentShapeNew(body, a, b, 5.0f)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.7f); + + return body; } -static cpBody* addBar(cpSpace* space, cpVect pos, cpVect boxOffset) +static cpBody * +addBar(cpSpace *space, cpVect pos, cpVect boxOffset) { - cpFloat mass = 2.0f; - cpVect a = cpv(0, 30); - cpVect b = cpv(0, -30); - - cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForSegment(mass, a, b, 0.0f))); - cpBodySetPosition(body, cpvadd(pos, boxOffset)); - - cpShape* shape = cpSpaceAddShape(space, cpSegmentShapeNew(body, a, b, 5.0f)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.7f); - cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); - - return body; + cpFloat mass = 2.0f; + cpVect a = cpv(0, 30); + cpVect b = cpv(0, -30); + + cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForSegment(mass, a, b, 0.0f))); + cpBodySetPosition(body, cpvadd(pos, boxOffset)); + + cpShape *shape = cpSpaceAddShape(space, cpSegmentShapeNew(body, a, b, 5.0f)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.7f); + cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); + + return body; } -static cpBody* addWheel(cpSpace* space, cpVect pos, cpVect boxOffset) +static cpBody * +addWheel(cpSpace *space, cpVect pos, cpVect boxOffset) { - cpFloat radius = 15.0f; - cpFloat mass = 1.0f; - cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); - cpBodySetPosition(body, cpvadd(pos, boxOffset)); - - cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.7f); - cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); - - return body; + cpFloat radius = 15.0f; + cpFloat mass = 1.0f; + cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); + cpBodySetPosition(body, cpvadd(pos, boxOffset)); + + cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.7f); + cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); + + return body; } -static cpBody* addChassis(cpSpace* space, cpVect pos, cpVect boxOffset) +static cpBody * +addChassis(cpSpace *space, cpVect pos, cpVect boxOffset) { - cpFloat mass = 5.0f; - cpFloat width = 80; - cpFloat height = 30; - - cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForBox(mass, width, height))); - cpBodySetPosition(body, cpvadd(pos, boxOffset)); - - cpShape* shape = cpSpaceAddShape(space, cpBoxShapeNew(body, width, height, 0.0)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.7f); - cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); - - return body; + cpFloat mass = 5.0f; + cpFloat width = 80; + cpFloat height = 30; + + cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForBox(mass, width, height))); + cpBodySetPosition(body, cpvadd(pos, boxOffset)); + + cpShape *shape = cpSpaceAddShape(space, cpBoxShapeNew(body, width, height, 0.0)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.7f); + cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); + + return body; } -static cpSpace* init(void) +static cpSpace * +init(void) { - cpSpace* space = cpSpaceNew(); - cpSpaceSetIterations(space, 10); - cpSpaceSetGravity(space, cpv(0, -100)); - cpSpaceSetSleepTimeThreshold(space, 0.5f); - - cpBody* staticBody = cpSpaceGetStaticBody(space); - cpShape* shape; - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, 240), cpv(320, 240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, 120), cpv(320, 120), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, 0), cpv(320, 0), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -120), cpv(320, -120), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(320, -240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(-320, 240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-160, -240), cpv(-160, 240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(0, -240), cpv(0, 240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(160, -240), cpv(160, 240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320, -240), cpv(320, 240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - cpVect boxOffset; - cpBody *body1, *body2; - - cpVect posA = cpv(50, 60); - cpVect posB = cpv(110, 60); - -#define POS_A cpvadd(boxOffset, posA) -#define POS_B cpvadd(boxOffset, posB) - - // Pin Joints - Link shapes with a solid bar or pin. - // Keeps the anchor points the same distance apart from when the joint was created. - boxOffset = cpv(-320, -240); - body1 = addBall(space, posA, boxOffset); - body2 = addBall(space, posB, boxOffset); - cpSpaceAddConstraint(space, cpPinJointNew(body1, body2, cpv(15, 0), cpv(-15, 0))); - - // Slide Joints - Like pin joints but with a min/max distance. - // Can be used for a cheap approximation of a rope. - boxOffset = cpv(-160, -240); - body1 = addBall(space, posA, boxOffset); - body2 = addBall(space, posB, boxOffset); - cpSpaceAddConstraint(space, cpSlideJointNew(body1, body2, cpv(15, 0), cpv(-15, 0), 20.0f, 40.0f)); - - // Pivot Joints - Holds the two anchor points together. Like a swivel. - boxOffset = cpv(0, -240); - body1 = addBall(space, posA, boxOffset); - body2 = addBall(space, posB, boxOffset); - cpSpaceAddConstraint(space, cpPivotJointNew(body1, body2, cpvadd(boxOffset, cpv(80, 60)))); - // cpPivotJointNew() takes it's anchor parameter in world coordinates. The anchors are calculated from that - // cpPivotJointNew2() lets you specify the two anchor points explicitly - - // Groove Joints - Like a pivot joint, but one of the anchors is a line segment that the pivot can slide in - boxOffset = cpv(160, -240); - body1 = addBall(space, posA, boxOffset); - body2 = addBall(space, posB, boxOffset); - cpSpaceAddConstraint(space, cpGrooveJointNew(body1, body2, cpv(30, 30), cpv(30, -30), cpv(-30, 0))); - - // Damped Springs - boxOffset = cpv(-320, -120); - body1 = addBall(space, posA, boxOffset); - body2 = addBall(space, posB, boxOffset); - cpSpaceAddConstraint(space, cpDampedSpringNew(body1, body2, cpv(15, 0), cpv(-15, 0), 20.0f, 5.0f, 0.3f)); - - // Damped Rotary Springs - boxOffset = cpv(-160, -120); - body1 = addBar(space, posA, boxOffset); - body2 = addBar(space, posB, boxOffset); - // Add some pin joints to hold the circles in place. - cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); - cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); - cpSpaceAddConstraint(space, cpDampedRotarySpringNew(body1, body2, 0.0f, 3000.0f, 60.0f)); - - // Rotary Limit Joint - boxOffset = cpv(0, -120); - body1 = addLever(space, posA, boxOffset); - body2 = addLever(space, posB, boxOffset); - // Add some pin joints to hold the circles in place. - cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); - cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); - // Hold their rotation within 90 degrees of each other. - cpSpaceAddConstraint(space, cpRotaryLimitJointNew(body1, body2, -CP_PI / 2.0f, CP_PI / 2.0f)); - - // Ratchet Joint - A rotary ratchet, like a socket wrench - boxOffset = cpv(160, -120); - body1 = addLever(space, posA, boxOffset); - body2 = addLever(space, posB, boxOffset); - // Add some pin joints to hold the circles in place. - cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); - cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); - // Ratchet every 90 degrees - cpSpaceAddConstraint(space, cpRatchetJointNew(body1, body2, 0.0f, CP_PI / 2.0f)); - - // Gear Joint - Maintain a specific angular velocity ratio - boxOffset = cpv(-320, 0); - body1 = addBar(space, posA, boxOffset); - body2 = addBar(space, posB, boxOffset); - // Add some pin joints to hold the circles in place. - cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); - cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); - // Force one to sping 2x as fast as the other - cpSpaceAddConstraint(space, cpGearJointNew(body1, body2, 0.0f, 2.0f)); - - // Simple Motor - Maintain a specific angular relative velocity - boxOffset = cpv(-160, 0); - body1 = addBar(space, posA, boxOffset); - body2 = addBar(space, posB, boxOffset); - // Add some pin joints to hold the circles in place. - cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); - cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); - // Make them spin at 1/2 revolution per second in relation to each other. - cpSpaceAddConstraint(space, cpSimpleMotorNew(body1, body2, CP_PI)); - - // Make a car with some nice soft suspension - boxOffset = cpv(0, 0); - cpBody* wheel1 = addWheel(space, posA, boxOffset); - cpBody* wheel2 = addWheel(space, posB, boxOffset); - cpBody* chassis = addChassis(space, cpv(80, 100), boxOffset); - - cpSpaceAddConstraint(space, cpGrooveJointNew(chassis, wheel1, cpv(-30, -10), cpv(-30, -40), cpvzero)); - cpSpaceAddConstraint(space, cpGrooveJointNew(chassis, wheel2, cpv(30, -10), cpv(30, -40), cpvzero)); - - cpSpaceAddConstraint(space, cpDampedSpringNew(chassis, wheel1, cpv(-30, 0), cpvzero, 50.0f, 20.0f, 10.0f)); - cpSpaceAddConstraint(space, cpDampedSpringNew(chassis, wheel2, cpv(30, 0), cpvzero, 50.0f, 20.0f, 10.0f)); - - return space; + cpSpace *space = cpSpaceNew(); + cpSpaceSetIterations(space, 10); + cpSpaceSetGravity(space, cpv(0, -100)); + cpSpaceSetSleepTimeThreshold(space, 0.5f); + + cpBody *staticBody = cpSpaceGetStaticBody(space); + cpShape *shape; + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,240), cpv(320,240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,120), cpv(320,120), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,0), cpv(320,0), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-120), cpv(320,-120), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-160,-240), cpv(-160,240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(0,-240), cpv(0,240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(160,-240), cpv(160,240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + cpVect boxOffset; + cpBody *body1, *body2; + + cpVect posA = cpv( 50, 60); + cpVect posB = cpv(110, 60); + + #define POS_A cpvadd(boxOffset, posA) + #define POS_B cpvadd(boxOffset, posB) + + // Pin Joints - Link shapes with a solid bar or pin. + // Keeps the anchor points the same distance apart from when the joint was created. + boxOffset = cpv(-320, -240); + body1 = addBall(space, posA, boxOffset); + body2 = addBall(space, posB, boxOffset); + cpSpaceAddConstraint(space, cpPinJointNew(body1, body2, cpv(15,0), cpv(-15,0))); + + // Slide Joints - Like pin joints but with a min/max distance. + // Can be used for a cheap approximation of a rope. + boxOffset = cpv(-160, -240); + body1 = addBall(space, posA, boxOffset); + body2 = addBall(space, posB, boxOffset); + cpSpaceAddConstraint(space, cpSlideJointNew(body1, body2, cpv(15,0), cpv(-15,0), 20.0f, 40.0f)); + + // Pivot Joints - Holds the two anchor points together. Like a swivel. + boxOffset = cpv(0, -240); + body1 = addBall(space, posA, boxOffset); + body2 = addBall(space, posB, boxOffset); + cpSpaceAddConstraint(space, cpPivotJointNew(body1, body2, cpvadd(boxOffset, cpv(80,60)))); + // cpPivotJointNew() takes it's anchor parameter in world coordinates. The anchors are calculated from that + // cpPivotJointNew2() lets you specify the two anchor points explicitly + + // Groove Joints - Like a pivot joint, but one of the anchors is a line segment that the pivot can slide in + boxOffset = cpv(160, -240); + body1 = addBall(space, posA, boxOffset); + body2 = addBall(space, posB, boxOffset); + cpSpaceAddConstraint(space, cpGrooveJointNew(body1, body2, cpv(30,30), cpv(30,-30), cpv(-30,0))); + + // Damped Springs + boxOffset = cpv(-320, -120); + body1 = addBall(space, posA, boxOffset); + body2 = addBall(space, posB, boxOffset); + cpSpaceAddConstraint(space, cpDampedSpringNew(body1, body2, cpv(15,0), cpv(-15,0), 20.0f, 5.0f, 0.3f)); + + // Damped Rotary Springs + boxOffset = cpv(-160, -120); + body1 = addBar(space, posA, boxOffset); + body2 = addBar(space, posB, boxOffset); + // Add some pin joints to hold the circles in place. + cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); + cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); + cpSpaceAddConstraint(space, cpDampedRotarySpringNew(body1, body2, 0.0f, 3000.0f, 60.0f)); + + // Rotary Limit Joint + boxOffset = cpv(0, -120); + body1 = addLever(space, posA, boxOffset); + body2 = addLever(space, posB, boxOffset); + // Add some pin joints to hold the circles in place. + cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); + cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); + // Hold their rotation within 90 degrees of each other. + cpSpaceAddConstraint(space, cpRotaryLimitJointNew(body1, body2, -CP_PI/2.0f, CP_PI/2.0f)); + + // Ratchet Joint - A rotary ratchet, like a socket wrench + boxOffset = cpv(160, -120); + body1 = addLever(space, posA, boxOffset); + body2 = addLever(space, posB, boxOffset); + // Add some pin joints to hold the circles in place. + cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); + cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); + // Ratchet every 90 degrees + cpSpaceAddConstraint(space, cpRatchetJointNew(body1, body2, 0.0f, CP_PI/2.0f)); + + // Gear Joint - Maintain a specific angular velocity ratio + boxOffset = cpv(-320, 0); + body1 = addBar(space, posA, boxOffset); + body2 = addBar(space, posB, boxOffset); + // Add some pin joints to hold the circles in place. + cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); + cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); + // Force one to sping 2x as fast as the other + cpSpaceAddConstraint(space, cpGearJointNew(body1, body2, 0.0f, 2.0f)); + + // Simple Motor - Maintain a specific angular relative velocity + boxOffset = cpv(-160, 0); + body1 = addBar(space, posA, boxOffset); + body2 = addBar(space, posB, boxOffset); + // Add some pin joints to hold the circles in place. + cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); + cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); + // Make them spin at 1/2 revolution per second in relation to each other. + cpSpaceAddConstraint(space, cpSimpleMotorNew(body1, body2, CP_PI)); + + // Make a car with some nice soft suspension + boxOffset = cpv(0, 0); + cpBody *wheel1 = addWheel(space, posA, boxOffset); + cpBody *wheel2 = addWheel(space, posB, boxOffset); + cpBody *chassis = addChassis(space, cpv(80, 100), boxOffset); + + cpSpaceAddConstraint(space, cpGrooveJointNew(chassis, wheel1, cpv(-30, -10), cpv(-30, -40), cpvzero)); + cpSpaceAddConstraint(space, cpGrooveJointNew(chassis, wheel2, cpv( 30, -10), cpv( 30, -40), cpvzero)); + + cpSpaceAddConstraint(space, cpDampedSpringNew(chassis, wheel1, cpv(-30, 0), cpvzero, 50.0f, 20.0f, 10.0f)); + cpSpaceAddConstraint(space, cpDampedSpringNew(chassis, wheel2, cpv( 30, 0), cpvzero, 50.0f, 20.0f, 10.0f)); + + return space; } -static void update(cpSpace* space, double dt) +static void +update(cpSpace *space, double dt) { - cpSpaceStep(space, dt); + cpSpaceStep(space, dt); } -static void destroy(cpSpace* space) +static void +destroy(cpSpace *space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo Joints = { - "Joints and Constraints", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, + "Joints and Constraints", + 1.0/60.0, + init, + update, + ChipmunkDemoDefaultDrawImpl, + destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/LogoSmash.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/LogoSmash.c index 4971f05a5e..3b1fc4bc67 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/LogoSmash.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/LogoSmash.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,147 +18,149 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" -static const int image_width = 188; -static const int image_height = 35; -static const int image_row_length = 24; +static const int image_width = 188; +static const int image_height = 35; +static const int image_row_length = 24; float ChipmunkDebugDrawPointLineScale = 1.0f; static const char image_bitmap[] = { - 15, -16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 7, -64, 15, 63, -32, -2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 31, -64, 15, 127, -125, -1, -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 127, -64, 15, 127, 15, -1, -64, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -64, 15, -2, 31, -1, -64, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -64, 0, -4, 63, -1, -32, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -64, 15, -8, 127, -1, - -32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -64, 0, - -8, -15, -1, -32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -31, - -1, -64, 15, -8, -32, -1, -32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 7, -15, -1, -64, 9, -15, -32, -1, -32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 31, -15, -1, -64, 0, -15, -32, -1, -32, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 63, -7, -1, -64, 9, -29, -32, 127, -61, -16, 63, 15, -61, -1, - -8, 31, -16, 15, -8, 126, 7, -31, -8, 31, -65, -7, -1, -64, 9, -29, -32, 0, 7, -8, 127, - -97, -25, -1, -2, 63, -8, 31, -4, -1, 15, -13, -4, 63, -1, -3, -1, -64, 9, -29, -32, 0, - 7, -8, 127, -97, -25, -1, -2, 63, -8, 31, -4, -1, 15, -13, -2, 63, -1, -3, -1, -64, 9, - -29, -32, 0, 7, -8, 127, -97, -25, -1, -1, 63, -4, 63, -4, -1, 15, -13, -2, 63, -33, -1, - -1, -32, 9, -25, -32, 0, 7, -8, 127, -97, -25, -1, -1, 63, -4, 63, -4, -1, 15, -13, -1, - 63, -33, -1, -1, -16, 9, -25, -32, 0, 7, -8, 127, -97, -25, -1, -1, 63, -4, 63, -4, -1, - 15, -13, -1, 63, -49, -1, -1, -8, 9, -57, -32, 0, 7, -8, 127, -97, -25, -8, -1, 63, -2, - 127, -4, -1, 15, -13, -1, -65, -49, -1, -1, -4, 9, -57, -32, 0, 7, -8, 127, -97, -25, -8, - -1, 63, -2, 127, -4, -1, 15, -13, -1, -65, -57, -1, -1, -2, 9, -57, -32, 0, 7, -8, 127, - -97, -25, -8, -1, 63, -2, 127, -4, -1, 15, -13, -1, -1, -57, -1, -1, -1, 9, -57, -32, 0, - 7, -1, -1, -97, -25, -8, -1, 63, -1, -1, -4, -1, 15, -13, -1, -1, -61, -1, -1, -1, -119, - -57, -32, 0, 7, -1, -1, -97, -25, -8, -1, 63, -1, -1, -4, -1, 15, -13, -1, -1, -61, -1, - -1, -1, -55, -49, -32, 0, 7, -1, -1, -97, -25, -8, -1, 63, -1, -1, -4, -1, 15, -13, -1, - -1, -63, -1, -1, -1, -23, -49, -32, 127, -57, -1, -1, -97, -25, -1, -1, 63, -1, -1, -4, -1, - 15, -13, -1, -1, -63, -1, -1, -1, -16, -49, -32, -1, -25, -1, -1, -97, -25, -1, -1, 63, -33, - -5, -4, -1, 15, -13, -1, -1, -64, -1, -9, -1, -7, -49, -32, -1, -25, -8, 127, -97, -25, -1, - -1, 63, -33, -5, -4, -1, 15, -13, -1, -1, -64, -1, -13, -1, -32, -49, -32, -1, -25, -8, 127, - -97, -25, -1, -2, 63, -49, -13, -4, -1, 15, -13, -1, -1, -64, 127, -7, -1, -119, -17, -15, -1, - -25, -8, 127, -97, -25, -1, -2, 63, -49, -13, -4, -1, 15, -13, -3, -1, -64, 127, -8, -2, 15, - -17, -1, -1, -25, -8, 127, -97, -25, -1, -8, 63, -49, -13, -4, -1, 15, -13, -3, -1, -64, 63, - -4, 120, 0, -17, -1, -1, -25, -8, 127, -97, -25, -8, 0, 63, -57, -29, -4, -1, 15, -13, -4, - -1, -64, 63, -4, 0, 15, -17, -1, -1, -25, -8, 127, -97, -25, -8, 0, 63, -57, -29, -4, -1, - -1, -13, -4, -1, -64, 31, -2, 0, 0, 103, -1, -1, -57, -8, 127, -97, -25, -8, 0, 63, -57, - -29, -4, -1, -1, -13, -4, 127, -64, 31, -2, 0, 15, 103, -1, -1, -57, -8, 127, -97, -25, -8, - 0, 63, -61, -61, -4, 127, -1, -29, -4, 127, -64, 15, -8, 0, 0, 55, -1, -1, -121, -8, 127, - -97, -25, -8, 0, 63, -61, -61, -4, 127, -1, -29, -4, 63, -64, 15, -32, 0, 0, 23, -1, -2, - 3, -16, 63, 15, -61, -16, 0, 31, -127, -127, -8, 31, -1, -127, -8, 31, -128, 7, -128, 0, 0}; + 15,-16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7,-64,15,63,-32,-2,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,31,-64,15,127,-125,-1,-128,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,127,-64,15,127,15,-1,-64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-1,-64,15,-2, + 31,-1,-64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-1,-64,0,-4,63,-1,-32,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,1,-1,-64,15,-8,127,-1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 1,-1,-64,0,-8,-15,-1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-31,-1,-64,15,-8,-32, + -1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7,-15,-1,-64,9,-15,-32,-1,-32,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,31,-15,-1,-64,0,-15,-32,-1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,63,-7,-1,-64,9,-29,-32,127,-61,-16,63,15,-61,-1,-8,31,-16,15,-8,126,7,-31, + -8,31,-65,-7,-1,-64,9,-29,-32,0,7,-8,127,-97,-25,-1,-2,63,-8,31,-4,-1,15,-13, + -4,63,-1,-3,-1,-64,9,-29,-32,0,7,-8,127,-97,-25,-1,-2,63,-8,31,-4,-1,15,-13, + -2,63,-1,-3,-1,-64,9,-29,-32,0,7,-8,127,-97,-25,-1,-1,63,-4,63,-4,-1,15,-13, + -2,63,-33,-1,-1,-32,9,-25,-32,0,7,-8,127,-97,-25,-1,-1,63,-4,63,-4,-1,15,-13, + -1,63,-33,-1,-1,-16,9,-25,-32,0,7,-8,127,-97,-25,-1,-1,63,-4,63,-4,-1,15,-13, + -1,63,-49,-1,-1,-8,9,-57,-32,0,7,-8,127,-97,-25,-8,-1,63,-2,127,-4,-1,15,-13, + -1,-65,-49,-1,-1,-4,9,-57,-32,0,7,-8,127,-97,-25,-8,-1,63,-2,127,-4,-1,15,-13, + -1,-65,-57,-1,-1,-2,9,-57,-32,0,7,-8,127,-97,-25,-8,-1,63,-2,127,-4,-1,15,-13, + -1,-1,-57,-1,-1,-1,9,-57,-32,0,7,-1,-1,-97,-25,-8,-1,63,-1,-1,-4,-1,15,-13,-1, + -1,-61,-1,-1,-1,-119,-57,-32,0,7,-1,-1,-97,-25,-8,-1,63,-1,-1,-4,-1,15,-13,-1, + -1,-61,-1,-1,-1,-55,-49,-32,0,7,-1,-1,-97,-25,-8,-1,63,-1,-1,-4,-1,15,-13,-1, + -1,-63,-1,-1,-1,-23,-49,-32,127,-57,-1,-1,-97,-25,-1,-1,63,-1,-1,-4,-1,15,-13, + -1,-1,-63,-1,-1,-1,-16,-49,-32,-1,-25,-1,-1,-97,-25,-1,-1,63,-33,-5,-4,-1,15, + -13,-1,-1,-64,-1,-9,-1,-7,-49,-32,-1,-25,-8,127,-97,-25,-1,-1,63,-33,-5,-4,-1, + 15,-13,-1,-1,-64,-1,-13,-1,-32,-49,-32,-1,-25,-8,127,-97,-25,-1,-2,63,-49,-13, + -4,-1,15,-13,-1,-1,-64,127,-7,-1,-119,-17,-15,-1,-25,-8,127,-97,-25,-1,-2,63, + -49,-13,-4,-1,15,-13,-3,-1,-64,127,-8,-2,15,-17,-1,-1,-25,-8,127,-97,-25,-1, + -8,63,-49,-13,-4,-1,15,-13,-3,-1,-64,63,-4,120,0,-17,-1,-1,-25,-8,127,-97,-25, + -8,0,63,-57,-29,-4,-1,15,-13,-4,-1,-64,63,-4,0,15,-17,-1,-1,-25,-8,127,-97, + -25,-8,0,63,-57,-29,-4,-1,-1,-13,-4,-1,-64,31,-2,0,0,103,-1,-1,-57,-8,127,-97, + -25,-8,0,63,-57,-29,-4,-1,-1,-13,-4,127,-64,31,-2,0,15,103,-1,-1,-57,-8,127, + -97,-25,-8,0,63,-61,-61,-4,127,-1,-29,-4,127,-64,15,-8,0,0,55,-1,-1,-121,-8, + 127,-97,-25,-8,0,63,-61,-61,-4,127,-1,-29,-4,63,-64,15,-32,0,0,23,-1,-2,3,-16, + 63,15,-61,-16,0,31,-127,-127,-8,31,-1,-127,-8,31,-128,7,-128,0,0 +}; -static inline int get_pixel(int x, int y) +static inline int +get_pixel(int x, int y) { - return (image_bitmap[(x >> 3) + y * image_row_length] >> (~x & 0x7)) & 1; + return (image_bitmap[(x>>3) + y*image_row_length]>>(~x&0x7)) & 1; } static int bodyCount = 0; -static void update(cpSpace* space, double dt) +static void +update(cpSpace *space, double dt) { - cpSpaceStep(space, dt); + cpSpaceStep(space, dt); } -static void DrawDot(cpBody* body, void* unused) +static void +DrawDot(cpBody *body, void *unused) { - ChipmunkDebugDrawDot(3.5 / ChipmunkDebugDrawPointLineScale, cpBodyGetPosition(body), - RGBAColor(0xee / 255.0f, 0xe8 / 255.0f, 0xd5 / 255.0f, 1.0f)); + ChipmunkDebugDrawDot(3.5/ChipmunkDebugDrawPointLineScale, cpBodyGetPosition(body), RGBAColor(0xee/255.0f, 0xe8/255.0f, 0xd5/255.0f, 1.0f)); } -static void draw(cpSpace* space) +static void +draw(cpSpace *space) { - cpSpaceEachBody(space, DrawDot, NULL); - - // ChipmunkDebugDrawCollisionPoints(space); + cpSpaceEachBody(space, DrawDot, NULL); + +// ChipmunkDebugDrawCollisionPoints(space); } -static cpShape* make_ball(cpFloat x, cpFloat y) +static cpShape * +make_ball(cpFloat x, cpFloat y) { - cpBody* body = cpBodyNew(1.0, INFINITY); - cpBodySetPosition(body, cpv(x, y)); + cpBody *body = cpBodyNew(1.0, INFINITY); + cpBodySetPosition(body, cpv(x, y)); - cpShape* shape = cpCircleShapeNew(body, 0.95, cpvzero); - cpShapeSetElasticity(shape, 0.0); - cpShapeSetFriction(shape, 0.0); - - return shape; + cpShape *shape = cpCircleShapeNew(body, 0.95, cpvzero); + cpShapeSetElasticity(shape, 0.0); + cpShapeSetFriction(shape, 0.0); + + return shape; } -static cpSpace* init(void) +static cpSpace * +init(void) { - cpSpace* space = cpSpaceNew(); - cpSpaceSetIterations(space, 1); + cpSpace *space = cpSpaceNew(); + cpSpaceSetIterations(space, 1); + + // The space will contain a very large number of similary sized objects. + // This is the perfect candidate for using the spatial hash. + // Generally you will never need to do this. + cpSpaceUseSpatialHash(space, 2.0, 10000); + + bodyCount = 0; + + cpBody *body; + cpShape *shape; + + for(int y=0; yn) < 0) - { - return cpArbiterIgnore(arb); - } - - return cpTrue; + CP_ARBITER_GET_SHAPES(arb, a, b); + OneWayPlatform *platform = (OneWayPlatform *)cpShapeGetUserData(a); + + if(cpvdot(cpArbiterGetNormal(arb), platform->n) < 0){ + return cpArbiterIgnore(arb); + } + + return cpTrue; } -static void update(cpSpace* space, double dt) +static void +update(cpSpace *space, double dt) { - cpSpaceStep(space, dt); + cpSpaceStep(space, dt); } -static cpSpace* init(void) +static cpSpace * +init(void) { - ChipmunkDemoMessageString = "One way platforms are trivial in Chipmunk using a very simple collision callback."; + ChipmunkDemoMessageString = "One way platforms are trivial in Chipmunk using a very simple collision callback."; + + cpSpace *space = cpSpaceNew(); + cpSpaceSetIterations(space, 10); + cpSpaceSetGravity(space, cpv(0, -100)); - cpSpace* space = cpSpaceNew(); - cpSpaceSetIterations(space, 10); - cpSpaceSetGravity(space, cpv(0, -100)); + cpBody *body, *staticBody = cpSpaceGetStaticBody(space); + cpShape *shape; - cpBody *body, *staticBody = cpSpaceGetStaticBody(space); - cpShape* shape; + // Create segments around the edge of the screen. + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - // Create segments around the edge of the screen. - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(-320, 240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320, -240), cpv(320, 240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + // Add our one way segment + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-160,-100), cpv(160,-100), 10.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetCollisionType(shape, COLLISION_TYPE_ONE_WAY); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + // We'll use the data pointer for the OneWayPlatform struct + platformInstance.n = cpv(0, 1); // let objects pass upwards + cpShapeSetUserData(shape, &platformInstance); + + + // Add a ball to test it out + cpFloat radius = 15.0f; + body = cpSpaceAddBody(space, cpBodyNew(10.0f, cpMomentForCircle(10.0f, 0.0f, radius, cpvzero))); + cpBodySetPosition(body, cpv(0, -200)); + cpBodySetVelocity(body, cpv(0, 170)); - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(320, -240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - // Add our one way segment - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-160, -100), cpv(160, -100), 10.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetCollisionType(shape, COLLISION_TYPE_ONE_WAY); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - // We'll use the data pointer for the OneWayPlatform struct - platformInstance.n = cpv(0, 1); // let objects pass upwards - cpShapeSetUserData(shape, &platformInstance); - - // Add a ball to test it out - cpFloat radius = 15.0f; - body = cpSpaceAddBody(space, cpBodyNew(10.0f, cpMomentForCircle(10.0f, 0.0f, radius, cpvzero))); - cpBodySetPosition(body, cpv(0, -200)); - cpBodySetVelocity(body, cpv(0, 170)); - - shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.9f); - cpShapeSetCollisionType(shape, 2); - - cpCollisionHandler* handler = cpSpaceAddWildcardHandler(space, COLLISION_TYPE_ONE_WAY); - handler->preSolveFunc = PreSolve; - - return space; + shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.9f); + cpShapeSetCollisionType(shape, 2); + + cpCollisionHandler *handler = cpSpaceAddWildcardHandler(space, COLLISION_TYPE_ONE_WAY); + handler->preSolveFunc = PreSolve; + + return space; } -static void destroy(cpSpace* space) +static void +destroy(cpSpace *space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo OneWay = { - "One Way Platforms", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, + "One Way Platforms", + 1.0/60.0, + init, + update, + ChipmunkDemoDefaultDrawImpl, + destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Planet.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Planet.c index cc7d4f8c69..e169e18417 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Planet.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Planet.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,105 +18,114 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" -static cpBody* planetBody; +static cpBody *planetBody; static cpFloat gravityStrength = 5.0e6f; -static void update(cpSpace* space, double dt) +static void +update(cpSpace *space, double dt) { - cpSpaceStep(space, dt); + cpSpaceStep(space, dt); } -static void planetGravityVelocityFunc(cpBody* body, cpVect gravity, cpFloat damping, cpFloat dt) +static void +planetGravityVelocityFunc(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt) { - // Gravitational acceleration is proportional to the inverse square of - // distance, and directed toward the origin. The central planet is assumed - // to be massive enough that it affects the satellites but not vice versa. - cpVect p = cpBodyGetPosition(body); - cpFloat sqdist = cpvlengthsq(p); - cpVect g = cpvmult(p, -gravityStrength / (sqdist * cpfsqrt(sqdist))); - - cpBodyUpdateVelocity(body, g, damping, dt); + // Gravitational acceleration is proportional to the inverse square of + // distance, and directed toward the origin. The central planet is assumed + // to be massive enough that it affects the satellites but not vice versa. + cpVect p = cpBodyGetPosition(body); + cpFloat sqdist = cpvlengthsq(p); + cpVect g = cpvmult(p, -gravityStrength / (sqdist * cpfsqrt(sqdist))); + + cpBodyUpdateVelocity(body, g, damping, dt); } -static cpVect rand_pos(cpFloat radius) +static cpVect +rand_pos(cpFloat radius) { - cpVect v; - do - { - v = cpv(frand() * (640 - 2 * radius) - (320 - radius), frand() * (480 - 2 * radius) - (240 - radius)); - } while (cpvlength(v) < 85.0f); - - return v; + cpVect v; + do { + v = cpv(frand()*(640 - 2*radius) - (320 - radius), frand()*(480 - 2*radius) - (240 - radius)); + } while(cpvlength(v) < 85.0f); + + return v; } -static void add_box(cpSpace* space) +static void +add_box(cpSpace *space) { - const cpFloat size = 10.0f; - const cpFloat mass = 1.0f; + const cpFloat size = 10.0f; + const cpFloat mass = 1.0f; + + cpVect verts[] = { + cpv(-size,-size), + cpv(-size, size), + cpv( size, size), + cpv( size,-size), + }; + + cpFloat radius = cpvlength(cpv(size, size)); + cpVect pos = rand_pos(radius); + + cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 4, verts, cpvzero, 0.0f))); + cpBodySetVelocityUpdateFunc(body, planetGravityVelocityFunc); + cpBodySetPosition(body, pos); - cpVect verts[] = { - cpv(-size, -size), - cpv(-size, size), - cpv(size, size), - cpv(size, -size), - }; + // Set the box's velocity to put it into a circular orbit from its + // starting position. + cpFloat r = cpvlength(pos); + cpFloat v = cpfsqrt(gravityStrength / r) / r; + cpBodySetVelocity(body, cpvmult(cpvperp(pos), v)); - cpFloat radius = cpvlength(cpv(size, size)); - cpVect pos = rand_pos(radius); + // Set the box's angular velocity to match its orbital period and + // align its initial angle with its position. + cpBodySetAngularVelocity(body, v); + cpBodySetAngle(body, cpfatan2(pos.y, pos.x)); - cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 4, verts, cpvzero, 0.0f))); - cpBodySetVelocityUpdateFunc(body, planetGravityVelocityFunc); - cpBodySetPosition(body, pos); - - // Set the box's velocity to put it into a circular orbit from its - // starting position. - cpFloat r = cpvlength(pos); - cpFloat v = cpfsqrt(gravityStrength / r) / r; - cpBodySetVelocity(body, cpvmult(cpvperp(pos), v)); - - // Set the box's angular velocity to match its orbital period and - // align its initial angle with its position. - cpBodySetAngularVelocity(body, v); - cpBodySetAngle(body, cpfatan2(pos.y, pos.x)); - - cpShape* shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 4, verts, cpTransformIdentity, 0.0)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.7f); + cpShape *shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 4, verts, cpTransformIdentity, 0.0)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.7f); } -static cpSpace* init(void) +static cpSpace * +init(void) { - // Create a rouge body to control the planet manually. - cpSpace* space = cpSpaceNew(); - cpSpaceSetIterations(space, 20); - - planetBody = cpSpaceAddBody(space, cpBodyNewKinematic()); - cpBodySetAngularVelocity(planetBody, 0.2f); - - for (int i = 0; i < 30; i++) - { - add_box(space); - } - - cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(planetBody, 70.0f, cpvzero)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - return space; + // Create a rouge body to control the planet manually. + cpSpace *space = cpSpaceNew(); + cpSpaceSetIterations(space, 20); + + planetBody = cpSpaceAddBody(space, cpBodyNewKinematic()); + cpBodySetAngularVelocity(planetBody, 0.2f); + + for(int i=0; i<30; i++){ + add_box(space); + } + + cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(planetBody, 70.0f, cpvzero)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + return space; } -static void destroy(cpSpace* space) +static void +destroy(cpSpace *space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo Planet = { - "Planet", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, + "Planet", + 1.0/60.0, + init, + update, + ChipmunkDemoDefaultDrawImpl, + destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Player.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Player.c index 0ed950dc80..a1d9ddcbb7 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Player.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Player.c @@ -25,156 +25,153 @@ #define PLAYER_VELOCITY 500.0 #define PLAYER_GROUND_ACCEL_TIME 0.1 -#define PLAYER_GROUND_ACCEL (PLAYER_VELOCITY / PLAYER_GROUND_ACCEL_TIME) +#define PLAYER_GROUND_ACCEL (PLAYER_VELOCITY / PLAYER_GROUND_ACCEL_TIME) #define PLAYER_AIR_ACCEL_TIME 0.25 -#define PLAYER_AIR_ACCEL (PLAYER_VELOCITY / PLAYER_AIR_ACCEL_TIME) +#define PLAYER_AIR_ACCEL (PLAYER_VELOCITY / PLAYER_AIR_ACCEL_TIME) -#define JUMP_HEIGHT 50.0 +#define JUMP_HEIGHT 50.0 #define JUMP_BOOST_HEIGHT 55.0 -#define FALL_VELOCITY 900.0 -#define GRAVITY 2000.0 +#define FALL_VELOCITY 900.0 +#define GRAVITY 2000.0 -static cpBody* playerBody = NULL; + +static cpBody* playerBody = NULL; static cpShape* playerShape = NULL; static cpFloat remainingBoost = 0; -static cpBool grounded = cpFalse; -static cpBool lastJumpState = cpFalse; +static cpBool grounded = cpFalse; +static cpBool lastJumpState = cpFalse; -static void SelectPlayerGroundNormal(cpBody* body, cpArbiter* arb, cpVect* groundNormal) -{ - cpVect n = cpvneg(cpArbiterGetNormal(arb)); +static void SelectPlayerGroundNormal(cpBody* body, cpArbiter* arb, cpVect* groundNormal) { + cpVect n = cpvneg(cpArbiterGetNormal(arb)); - if (n.y > groundNormal->y) - { - (*groundNormal) = n; - } + if (n.y > groundNormal->y) { + (*groundNormal) = n; + } } -static void playerUpdateVelocity(cpBody* body, cpVect gravity, cpFloat damping, cpFloat dt) -{ - int jumpState = (ChipmunkDemoKeyboard.y > 0.0f); +static void playerUpdateVelocity(cpBody* body, cpVect gravity, cpFloat damping, cpFloat dt) { + int jumpState = (ChipmunkDemoKeyboard.y > 0.0f); - // Grab the grounding normal from last frame - cpVect groundNormal = cpvzero; - cpBodyEachArbiter(playerBody, (cpBodyArbiterIteratorFunc)SelectPlayerGroundNormal, &groundNormal); + // Grab the grounding normal from last frame + cpVect groundNormal = cpvzero; + cpBodyEachArbiter(playerBody, (cpBodyArbiterIteratorFunc)SelectPlayerGroundNormal, &groundNormal); - grounded = (groundNormal.y > 0.0); - if (groundNormal.y < 0.0f) - remainingBoost = 0.0f; + grounded = (groundNormal.y > 0.0); + if (groundNormal.y < 0.0f) + remainingBoost = 0.0f; - // Do a normal-ish update - cpBool boost = (jumpState && remainingBoost > 0.0f); - cpVect g = (boost ? cpvzero : gravity); - cpBodyUpdateVelocity(body, g, damping, dt); + // Do a normal-ish update + cpBool boost = (jumpState && remainingBoost > 0.0f); + cpVect g = (boost ? cpvzero : gravity); + cpBodyUpdateVelocity(body, g, damping, dt); - // Target horizontal speed for air/ground control - cpFloat target_vx = PLAYER_VELOCITY * ChipmunkDemoKeyboard.x; + // Target horizontal speed for air/ground control + cpFloat target_vx = PLAYER_VELOCITY * ChipmunkDemoKeyboard.x; - // Update the surface velocity and friction - // Note that the "feet" move in the opposite direction of the player. - cpVect surface_v = cpv(-target_vx, 0.0); - playerShape->surfaceV = surface_v; - playerShape->u = (grounded ? PLAYER_GROUND_ACCEL / GRAVITY : 0.0); - // Apply air control if not grounded - if (!grounded) - { - // Smoothly accelerate the velocity - playerBody->v.x = cpflerpconst(playerBody->v.x, target_vx, PLAYER_AIR_ACCEL * dt); - } + // Update the surface velocity and friction + // Note that the "feet" move in the opposite direction of the player. + cpVect surface_v = cpv(-target_vx, 0.0); + playerShape->surfaceV = surface_v; + playerShape->u = (grounded ? PLAYER_GROUND_ACCEL / GRAVITY : 0.0); - body->v.y = cpfclamp(body->v.y, -FALL_VELOCITY, INFINITY); + // Apply air control if not grounded + if (!grounded) { + // Smoothly accelerate the velocity + playerBody->v.x = cpflerpconst(playerBody->v.x, target_vx, PLAYER_AIR_ACCEL * dt); + } + + body->v.y = cpfclamp(body->v.y, -FALL_VELOCITY, INFINITY); } -static void update(cpSpace* space, double dt) -{ - int jumpState = (ChipmunkDemoKeyboard.y > 0.0f); +static void update(cpSpace* space, double dt) { + int jumpState = (ChipmunkDemoKeyboard.y > 0.0f); - // If the jump key was just pressed this frame, jump! - if (jumpState && !lastJumpState && grounded) - { - cpFloat jump_v = cpfsqrt(2.0 * JUMP_HEIGHT * GRAVITY); - playerBody->v = cpvadd(playerBody->v, cpv(0.0, jump_v)); + // If the jump key was just pressed this frame, jump! + if (jumpState && !lastJumpState && grounded) { + cpFloat jump_v = cpfsqrt(2.0 * JUMP_HEIGHT * GRAVITY); + playerBody->v = cpvadd(playerBody->v, cpv(0.0, jump_v)); - remainingBoost = JUMP_BOOST_HEIGHT / jump_v; - } + remainingBoost = JUMP_BOOST_HEIGHT / jump_v; + } - // Step the space - cpSpaceStep(space, dt); + // Step the space + cpSpaceStep(space, dt); - remainingBoost -= dt; - lastJumpState = jumpState; + remainingBoost -= dt; + lastJumpState = jumpState; } -static cpSpace* init(void) -{ - cpSpace* space = cpSpaceNew(); - space->iterations = 10; - space->gravity = cpv(0, -GRAVITY); - // space->sleepTimeThreshold = 1000; +static cpSpace* init(void) { + cpSpace* space = cpSpaceNew(); + space->iterations = 10; + space->gravity = cpv(0, -GRAVITY); + // space->sleepTimeThreshold = 1000; - cpBody *body, *staticBody = cpSpaceGetStaticBody(space); - cpShape* shape; + cpBody* body, * staticBody = cpSpaceGetStaticBody(space); + cpShape* shape; - // Create segments around the edge of the screen. - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(-320, 240), 0.0f)); - shape->e = 1.0f; - shape->u = 1.0f; - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + // Create segments around the edge of the screen. + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(-320, 240), 0.0f)); + shape->e = 1.0f; + shape->u = 1.0f; + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320, -240), cpv(320, 240), 0.0f)); - shape->e = 1.0f; - shape->u = 1.0f; - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320, -240), cpv(320, 240), 0.0f)); + shape->e = 1.0f; + shape->u = 1.0f; + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(320, -240), 0.0f)); - shape->e = 1.0f; - shape->u = 1.0f; - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(320, -240), 0.0f)); + shape->e = 1.0f; + shape->u = 1.0f; + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, 240), cpv(320, 240), 0.0f)); - shape->e = 1.0f; - shape->u = 1.0f; - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, 240), cpv(320, 240), 0.0f)); + shape->e = 1.0f; + shape->u = 1.0f; + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - // Set up the player - body = cpSpaceAddBody(space, cpBodyNew(1.0f, INFINITY)); - body->p = cpv(0, -200); - body->velocity_func = playerUpdateVelocity; - playerBody = body; + // Set up the player + body = cpSpaceAddBody(space, cpBodyNew(1.0f, INFINITY)); + body->p = cpv(0, -200); + body->velocity_func = playerUpdateVelocity; + playerBody = body; - shape = cpSpaceAddShape(space, cpBoxShapeNew2(body, cpBBNew(-15.0, -27.5, 15.0, 27.5), 1.0)); - // shape = cpSpaceAddShape(space, cpSegmentShapeNew(playerBody, cpvzero, cpv(0, radius), radius)); - shape->e = 0.0f; - shape->u = 0.0f; - shape->type = 1; - playerShape = shape; + shape = cpSpaceAddShape(space, cpBoxShapeNew2(body, cpBBNew(-15.0, -27.5, 15.0, 27.5), 1.0)); + // shape = cpSpaceAddShape(space, cpSegmentShapeNew(playerBody, cpvzero, cpv(0, radius), radius)); + shape->e = 0.0f; + shape->u = 0.0f; + shape->type = 1; + playerShape = shape; - // Add some boxes to jump on - for (int i = 0; i < 6; i++) - { - for (int j = 0; j < 3; j++) - { - body = cpSpaceAddBody(space, cpBodyNew(4.0f, INFINITY)); - body->p = cpv(100 + j * 60, -200 + i * 60); + // Add some boxes to jump on + for (int i = 0; i < 6; i++) { + for (int j = 0; j < 3; j++) { + body = cpSpaceAddBody(space, cpBodyNew(4.0f, INFINITY)); + body->p = cpv(100 + j * 60, -200 + i * 60); - shape = cpSpaceAddShape(space, cpBoxShapeNew(body, 50, 50, 0.0)); - shape->e = 0.0f; - shape->u = 0.7f; - } - } + shape = cpSpaceAddShape(space, cpBoxShapeNew(body, 50, 50, 0.0)); + shape->e = 0.0f; + shape->u = 0.7f; + } + } - return space; + return space; } -static void destroy(cpSpace* space) -{ - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); +static void destroy(cpSpace* space) { + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo PlatformerPlayer = { - "Platformer Player Controls", 1.0 / 180.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, + "Platformer Player Controls", + 1.0 / 180.0, + init, + update, + ChipmunkDemoDefaultDrawImpl, + destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Plink.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Plink.c index dec53e8bc4..ecf7ca2129 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Plink.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Plink.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,116 +18,115 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" -static cpFloat pentagon_mass = 0.0f; +static cpFloat pentagon_mass = 0.0f; static cpFloat pentagon_moment = 0.0f; // Iterate over all of the bodies and reset the ones that have fallen offscreen. -static void eachBody(cpBody* body, void* unused) +static void +eachBody(cpBody *body, void *unused) { - cpVect pos = cpBodyGetPosition(body); - if (pos.y < -260) - { - cpFloat x = rand() / (cpFloat)RAND_MAX * 640 - 320; - cpBodySetPosition(body, cpv(x, 260)); - } + cpVect pos = cpBodyGetPosition(body); + if(pos.y < -260){ + cpFloat x = rand()/(cpFloat)RAND_MAX*640 - 320; + cpBodySetPosition(body, cpv(x, 260)); + } } -static void update(cpSpace* space, double dt) +static void +update(cpSpace *space, double dt) { - if (ChipmunkDemoRightDown) - { + if(ChipmunkDemoRightDown){ ChipmunkDemoRightDown = cpFalse; - cpShape* nearest = cpSpacePointQueryNearest(space, ChipmunkDemoMouse, 0.0, GRAB_FILTER, NULL); - if (nearest) - { - cpBody* body = cpShapeGetBody(nearest); - if (cpBodyGetType(body) == CP_BODY_TYPE_STATIC) - { - cpBodySetType(body, CP_BODY_TYPE_DYNAMIC); - cpBodySetMass(body, pentagon_mass); - cpBodySetMoment(body, pentagon_moment); - } - else if (cpBodyGetType(body) == CP_BODY_TYPE_DYNAMIC) - { - cpBodySetType(body, CP_BODY_TYPE_STATIC); - } - } - } - - cpSpaceEachBody(space, &eachBody, NULL); - cpSpaceStep(space, dt); + cpShape *nearest = cpSpacePointQueryNearest(space, ChipmunkDemoMouse, 0.0, GRAB_FILTER, NULL); + if(nearest){ + cpBody *body = cpShapeGetBody(nearest); + if(cpBodyGetType(body) == CP_BODY_TYPE_STATIC){ + cpBodySetType(body, CP_BODY_TYPE_DYNAMIC); + cpBodySetMass(body, pentagon_mass); + cpBodySetMoment(body, pentagon_moment); + } else if(cpBodyGetType(body) == CP_BODY_TYPE_DYNAMIC) { + cpBodySetType(body, CP_BODY_TYPE_STATIC); + } + } + } + + cpSpaceEachBody(space, &eachBody, NULL); + cpSpaceStep(space, dt); } #define NUM_VERTS 5 -static cpSpace* init(void) +static cpSpace * +init(void) { - ChipmunkDemoMessageString = "Right click to make pentagons static/dynamic."; + ChipmunkDemoMessageString = "Right click to make pentagons static/dynamic."; + + cpSpace *space = cpSpaceNew(); + cpSpaceSetIterations(space, 5); + cpSpaceSetGravity(space, cpv(0, -100)); + + cpBody *body, *staticBody = cpSpaceGetStaticBody(space); + cpShape *shape; + + // Vertexes for a triangle shape. + cpVect tris[] = { + cpv(-15,-15), + cpv( 0, 10), + cpv( 15,-15), + }; - cpSpace* space = cpSpaceNew(); - cpSpaceSetIterations(space, 5); - cpSpaceSetGravity(space, cpv(0, -100)); - - cpBody *body, *staticBody = cpSpaceGetStaticBody(space); - cpShape* shape; - - // Vertexes for a triangle shape. - cpVect tris[] = { - cpv(-15, -15), - cpv(0, 10), - cpv(15, -15), - }; - - // Create the static triangles. - for (int i = 0; i < 10; i++) - { - for (int j = 0; j < 6; j++) - { - cpFloat stagger = (j % 2) * 40; - cpVect offset = cpv(i * 80 - 360 + stagger, j * 70 - 200); - shape = cpSpaceAddShape(space, cpPolyShapeNew(staticBody, 3, tris, cpTransformTranslate(offset), 0.0)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - } - } - - // Create vertexes for a pentagon shape. - cpVect verts[NUM_VERTS]; - for (int i = 0; i < NUM_VERTS; i++) - { - cpFloat angle = -2.0f * CP_PI * i / ((cpFloat)NUM_VERTS); - verts[i] = cpv(10 * cos(angle), 10 * sin(angle)); - } - - pentagon_mass = 1.0; - pentagon_moment = cpMomentForPoly(1.0f, NUM_VERTS, verts, cpvzero, 0.0f); - - // Add lots of pentagons. - for (int i = 0; i < 300; i++) - { - body = cpSpaceAddBody(space, cpBodyNew(pentagon_mass, pentagon_moment)); - cpFloat x = rand() / (cpFloat)RAND_MAX * 640 - 320; - cpBodySetPosition(body, cpv(x, 350)); - - shape = cpSpaceAddShape(space, cpPolyShapeNew(body, NUM_VERTS, verts, cpTransformIdentity, 0.0)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.4f); - } - - return space; + // Create the static triangles. + for(int i=0; i<10; i++){ + for(int j=0; j<6; j++){ + cpFloat stagger = (j%2)*40; + cpVect offset = cpv(i*80 - 360 + stagger, j*70 - 200); + shape = cpSpaceAddShape(space, cpPolyShapeNew(staticBody, 3, tris, cpTransformTranslate(offset), 0.0)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + } + } + + // Create vertexes for a pentagon shape. + cpVect verts[NUM_VERTS]; + for(int i=0; i 320.0f) - { - cpBodySetVelocity(ball, cpvzero); - cpBodySetPosition(ball, cpv(-224.0f, 200.0f)); - } - } + cpSpaceStep(space, dt); + + for(int i=0; i 320.0f){ + cpBodySetVelocity(ball, cpvzero); + cpBodySetPosition(ball, cpv(-224.0f, 200.0f)); + } + } } -static cpBody* add_ball(cpSpace* space, cpVect pos) +static cpBody * +add_ball(cpSpace *space, cpVect pos) { - cpBody* body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForCircle(1.0f, 30, 0, cpvzero))); - cpBodySetPosition(body, pos); - - cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(body, 30, cpvzero)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.5f); - - return body; + cpBody *body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForCircle(1.0f, 30, 0, cpvzero))); + cpBodySetPosition(body, pos); + + cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, 30, cpvzero)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.5f); + + return body; } -static cpSpace* init(void) +static cpSpace * +init(void) { - ChipmunkDemoMessageString = "Use the arrow keys to control the machine."; + ChipmunkDemoMessageString = "Use the arrow keys to control the machine."; + + cpSpace *space = cpSpaceNew(); + cpSpaceSetGravity(space, cpv(0, -600)); + + cpBody *staticBody = cpSpaceGetStaticBody(space); + cpShape *shape; + + // beveling all of the line segments slightly helps prevent things from getting stuck on cracks + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-256,16), cpv(-256,300), 2.0f)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.5f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - cpSpace* space = cpSpaceNew(); - cpSpaceSetGravity(space, cpv(0, -600)); + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-256,16), cpv(-192,0), 2.0f)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.5f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - cpBody* staticBody = cpSpaceGetStaticBody(space); - cpShape* shape; + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-192,0), cpv(-192, -64), 2.0f)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.5f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - // beveling all of the line segments slightly helps prevent things from getting stuck on cracks - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-256, 16), cpv(-256, 300), 2.0f)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.5f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-128,-64), cpv(-128,144), 2.0f)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.5f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-256, 16), cpv(-192, 0), 2.0f)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.5f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-192,80), cpv(-192,176), 2.0f)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.5f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-192, 0), cpv(-192, -64), 2.0f)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.5f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-192,176), cpv(-128,240), 2.0f)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.5f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-128, -64), cpv(-128, 144), 2.0f)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.5f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-128,144), cpv(192,64), 2.0f)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.5f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-192, 80), cpv(-192, 176), 2.0f)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.5f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + cpVect verts[] = { + cpv(-30,-80), + cpv(-30, 80), + cpv( 30, 64), + cpv( 30,-80), + }; - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-192, 176), cpv(-128, 240), 2.0f)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.5f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + cpBody *plunger = cpSpaceAddBody(space, cpBodyNew(1.0f, INFINITY)); + cpBodySetPosition(plunger, cpv(-160,-80)); + + shape = cpSpaceAddShape(space, cpPolyShapeNew(plunger, 4, verts, cpTransformIdentity, 0.0)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 0.5f); + cpShapeSetFilter(shape, cpShapeFilterNew(CP_NO_GROUP, 1, 1)); + + // add balls to hopper + for(int i=0; i> 16) & 0xFFFF) / (cpFloat)0xFFFF)); + return cpv(cpflerp(border, 1.0f - border, (cpFloat)(h & 0xFFFF) / (cpFloat) 0xFFFF), + cpflerp(border, 1.0f - border, (cpFloat)((h >> 16) & 0xFFFF) / (cpFloat) 0xFFFF)); } -static cpVect WorleyPoint(int i, int j, struct WorleyContex* context) -{ +static cpVect WorleyPoint(int i, int j, struct WorleyContex* context) { cpFloat size = context->cellSize; int width = context->width; int height = context->height; @@ -59,28 +56,18 @@ static cpVect WorleyPoint(int i, int j, struct WorleyContex* context) cpVect fv = HashVect(i, j, context->seed); return cpv(cpflerp(bb.l, bb.r, 0.5f) + size * (i + fv.x - width * 0.5f), - cpflerp(bb.b, bb.t, 0.5f) + size * (j + fv.y - height * 0.5f)); + cpflerp(bb.b, bb.t, 0.5f) + size * (j + fv.y - height * 0.5f)); } -static int ClipCell(cpShape* shape, - cpVect center, - int i, - int j, - struct WorleyContex* context, - cpVect* verts, - cpVect* clipped, - int count) -{ +static int ClipCell(cpShape* shape, cpVect center, int i, int j, struct WorleyContex* context, cpVect* verts, + cpVect* clipped, int count) { cpVect other = WorleyPoint(i, j, context); // printf(" other %dx%d: (% 5.2f, % 5.2f) ", i, j, other.x, other.y); - if (cpShapePointQuery(shape, other, NULL) > 0.0f) - { + if (cpShapePointQuery(shape, other, NULL) > 0.0f) { // printf("excluded\n"); memcpy(clipped, verts, count * sizeof(cpVect)); return count; - } - else - { + } else { // printf("clipped\n"); } @@ -88,13 +75,11 @@ static int ClipCell(cpShape* shape, cpFloat dist = cpvdot(n, cpvlerp(center, other, 0.5f)); int clipped_count = 0; - for (int j = 0, i = count - 1; j < count; i = j, j++) - { + for (int j = 0, i = count - 1; j < count; i = j, j++) { cpVect a = verts[i]; cpFloat a_dist = cpvdot(a, n) - dist; - if (a_dist <= 0.0) - { + if (a_dist <= 0.0) { clipped[clipped_count] = a; clipped_count++; } @@ -102,8 +87,7 @@ static int ClipCell(cpShape* shape, cpVect b = verts[j]; cpFloat b_dist = cpvdot(b, n) - dist; - if (a_dist * b_dist < 0.0f) - { + if (a_dist * b_dist < 0.0f) { cpFloat t = cpfabs(a_dist) / (cpfabs(a_dist) + cpfabs(b_dist)); clipped[clipped_count] = cpvlerp(a, b, t); @@ -114,34 +98,25 @@ static int ClipCell(cpShape* shape, return clipped_count; } -static void ShatterCell(cpSpace* space, - cpShape* shape, - cpVect cell, - int cell_i, - int cell_j, - struct WorleyContex* context) -{ +static void ShatterCell( + cpSpace* space, cpShape* shape, cpVect cell, int cell_i, int cell_j, struct WorleyContex* context) { // printf("cell %dx%d: (% 5.2f, % 5.2f)\n", cell_i, cell_j, cell.x, cell.y); cpBody* body = cpShapeGetBody(shape); - cpVect* ping = (cpVect*)alloca(MAX_VERTEXES_PER_VORONOI * sizeof(cpVect)); - cpVect* pong = (cpVect*)alloca(MAX_VERTEXES_PER_VORONOI * sizeof(cpVect)); + cpVect* ping = (cpVect*) alloca(MAX_VERTEXES_PER_VORONOI * sizeof(cpVect)); + cpVect* pong = (cpVect*) alloca(MAX_VERTEXES_PER_VORONOI * sizeof(cpVect)); int count = cpPolyShapeGetCount(shape); count = (count > MAX_VERTEXES_PER_VORONOI ? MAX_VERTEXES_PER_VORONOI : count); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { ping[i] = cpBodyLocalToWorld(body, cpPolyShapeGetVert(shape, i)); } - for (int i = 0; i < context->width; i++) - { - for (int j = 0; j < context->height; j++) - { - if (!(i == cell_i && j == cell_j) && cpShapePointQuery(shape, cell, NULL) < 0.0f) - { + for (int i = 0; i < context->width; i++) { + for (int j = 0; j < context->height; j++) { + if (!(i == cell_i && j == cell_j) && cpShapePointQuery(shape, cell, NULL) < 0.0f) { count = ClipCell(shape, cell, i, j, context, ping, pong, count); memcpy(ping, pong, count * sizeof(cpVect)); } @@ -163,24 +138,20 @@ static void ShatterCell(cpSpace* space, cpShapeSetFriction(new_shape, cpShapeGetFriction(shape)); } -static void ShatterShape(cpSpace* space, cpShape* shape, cpFloat cellSize, cpVect focus) -{ +static void ShatterShape(cpSpace* space, cpShape* shape, cpFloat cellSize, cpVect focus) { cpSpaceRemoveShape(space, shape); cpSpaceRemoveBody(space, cpShapeGetBody(shape)); cpBB bb = cpShapeGetBB(shape); - int width = (int)((bb.r - bb.l) / cellSize) + 1; - int height = (int)((bb.t - bb.b) / cellSize) + 1; + int width = (int) ((bb.r - bb.l) / cellSize) + 1; + int height = (int) ((bb.t - bb.b) / cellSize) + 1; // printf("Splitting as %dx%d\n", width, height); struct WorleyContex context = {(uint32_t)rand(), cellSize, width, height, bb, focus}; - for (int i = 0; i < context.width; i++) - { - for (int j = 0; j < context.height; j++) - { + for (int i = 0; i < context.width; i++) { + for (int j = 0; j < context.height; j++) { cpVect cell = WorleyPoint(i, j, &context); - if (cpShapePointQuery(shape, cell, NULL) < 0.0f) - { + if (cpShapePointQuery(shape, cell, NULL) < 0.0f) { ShatterCell(space, shape, cell, i, j, &context); } } @@ -190,23 +161,17 @@ static void ShatterShape(cpSpace* space, cpShape* shape, cpFloat cellSize, cpVec cpShapeFree(shape); } -static void update(cpSpace* space, double dt) -{ +static void update(cpSpace* space, double dt) { cpSpaceStep(space, dt); - if (ChipmunkDemoRightDown) - { + if (ChipmunkDemoRightDown) { cpPointQueryInfo info; - if (cpSpacePointQueryNearest(space, ChipmunkDemoMouse, 0, GRAB_FILTER, &info)) - { + if (cpSpacePointQueryNearest(space, ChipmunkDemoMouse, 0, GRAB_FILTER, &info)) { cpBB bb = cpShapeGetBB(info.shape); cpFloat cell_size = cpfmax(bb.r - bb.l, bb.t - bb.b) / 5.0f; - if (cell_size > 5.0f) - { - ShatterShape(space, (cpShape*)info.shape, cell_size, ChipmunkDemoMouse); - } - else - { + if (cell_size > 5.0f) { + ShatterShape(space, (cpShape*) info.shape, cell_size, ChipmunkDemoMouse); + } else { // printf("Too small to splinter %f\n", cell_size); } } @@ -214,8 +179,7 @@ static void update(cpSpace* space, double dt) } } -static cpSpace* init(void) -{ +static cpSpace* init(void) { ChipmunkDemoMessageString = "Right click something to shatter it."; cpSpace* space = cpSpaceNew(); @@ -246,12 +210,16 @@ static cpSpace* init(void) return space; } -static void destroy(cpSpace* space) -{ +static void destroy(cpSpace* space) { ChipmunkDemoFreeSpaceChildren(space); cpSpaceFree(space); } ChipmunkDemo Shatter = { - "Shatter.", 1.0f / 60.0f, init, update, ChipmunkDemoDefaultDrawImpl, destroy, + "Shatter.", + 1.0f / 60.0f, + init, + update, + ChipmunkDemoDefaultDrawImpl, + destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Slice.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Slice.c index 445452e17a..069de159dc 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Slice.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Slice.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,171 +18,171 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" -#define DENSITY (1.0 / 10000.0) +#define DENSITY (1.0/10000.0) -static void ClipPoly(cpSpace* space, cpShape* shape, cpVect n, cpFloat dist) +static void +ClipPoly(cpSpace *space, cpShape *shape, cpVect n, cpFloat dist) { - cpBody* body = cpShapeGetBody(shape); - - int count = cpPolyShapeGetCount(shape); - int clippedCount = 0; - - cpVect* clipped = (cpVect*)alloca((count + 1) * sizeof(cpVect)); - - for (int i = 0, j = count - 1; i < count; j = i, i++) - { - cpVect a = cpBodyLocalToWorld(body, cpPolyShapeGetVert(shape, j)); - cpFloat a_dist = cpvdot(a, n) - dist; - - if (a_dist < 0.0) - { - clipped[clippedCount] = a; - clippedCount++; - } - - cpVect b = cpBodyLocalToWorld(body, cpPolyShapeGetVert(shape, i)); - cpFloat b_dist = cpvdot(b, n) - dist; - - if (a_dist * b_dist < 0.0f) - { - cpFloat t = cpfabs(a_dist) / (cpfabs(a_dist) + cpfabs(b_dist)); - - clipped[clippedCount] = cpvlerp(a, b, t); - clippedCount++; - } - } - - cpVect centroid = cpCentroidForPoly(clippedCount, clipped); - cpFloat mass = cpAreaForPoly(clippedCount, clipped, 0.0f) * DENSITY; - cpFloat moment = cpMomentForPoly(mass, clippedCount, clipped, cpvneg(centroid), 0.0f); - - cpBody* new_body = cpSpaceAddBody(space, cpBodyNew(mass, moment)); - cpBodySetPosition(new_body, centroid); - cpBodySetVelocity(new_body, cpBodyGetVelocityAtWorldPoint(body, centroid)); - cpBodySetAngularVelocity(new_body, cpBodyGetAngularVelocity(body)); - - cpTransform transform = cpTransformTranslate(cpvneg(centroid)); - cpShape* new_shape = cpSpaceAddShape(space, cpPolyShapeNew(new_body, clippedCount, clipped, transform, 0.0)); - // Copy whatever properties you have set on the original shape that are important - cpShapeSetFriction(new_shape, cpShapeGetFriction(shape)); + cpBody *body = cpShapeGetBody(shape); + + int count = cpPolyShapeGetCount(shape); + int clippedCount = 0; + + cpVect *clipped = (cpVect *)alloca((count + 1)*sizeof(cpVect)); + + for(int i=0, j=count-1; ia; - cpVect b = context->b; - - // Clipping plane normal and distance. - cpVect n = cpvnormalize(cpvperp(cpvsub(b, a))); - cpFloat dist = cpvdot(a, n); - - ClipPoly(space, shape, n, dist); - ClipPoly(space, shape, cpvneg(n), -dist); - - cpBody* body = cpShapeGetBody(shape); - cpSpaceRemoveShape(space, shape); - cpSpaceRemoveBody(space, body); - cpShapeFree(shape); - cpBodyFree(body); + cpVect a = context->a; + cpVect b = context->b; + + // Clipping plane normal and distance. + cpVect n = cpvnormalize(cpvperp(cpvsub(b, a))); + cpFloat dist = cpvdot(a, n); + + ClipPoly(space, shape, n, dist); + ClipPoly(space, shape, cpvneg(n), -dist); + + cpBody *body = cpShapeGetBody(shape); + cpSpaceRemoveShape(space, shape); + cpSpaceRemoveBody(space, body); + cpShapeFree(shape); + cpBodyFree(body); } -static void SliceQuery(cpShape* shape, cpVect point, cpVect normal, cpFloat alpha, struct SliceContext* context) +static void +SliceQuery(cpShape *shape, cpVect point, cpVect normal, cpFloat alpha, struct SliceContext *context) { - cpVect a = context->a; - cpVect b = context->b; - - // Check that the slice was complete by checking that the endpoints aren't in the sliced shape. - if (cpShapePointQuery(shape, a, NULL) > 0.0f && cpShapePointQuery(shape, b, NULL) > 0.0f) - { - // Can't modify the space during a query. - // Must make a post-step callback to do the actual slicing. - cpSpaceAddPostStepCallback(context->space, (cpPostStepFunc)SliceShapePostStep, shape, context); - } + cpVect a = context->a; + cpVect b = context->b; + + // Check that the slice was complete by checking that the endpoints aren't in the sliced shape. + if(cpShapePointQuery(shape, a, NULL) > 0.0f && cpShapePointQuery(shape, b, NULL) > 0.0f){ + // Can't modify the space during a query. + // Must make a post-step callback to do the actual slicing. + cpSpaceAddPostStepCallback(context->space, (cpPostStepFunc)SliceShapePostStep, shape, context); + } } -static void update(cpSpace* space, double dt) +static void +update(cpSpace *space, double dt) { - cpSpaceStep(space, dt); - - static cpBool lastClickState = cpFalse; - static cpVect sliceStart = {0.0, 0.0}; - - // Annoying state tracking code that you wouldn't need - // in a real event driven system. - if (ChipmunkDemoRightClick != lastClickState) - { - if (ChipmunkDemoRightClick) - { - // MouseDown - sliceStart = ChipmunkDemoMouse; - } - else - { - // MouseUp - struct SliceContext context = {sliceStart, ChipmunkDemoMouse, space}; - cpSpaceSegmentQuery(space, sliceStart, ChipmunkDemoMouse, 0.0, GRAB_FILTER, - (cpSpaceSegmentQueryFunc)SliceQuery, &context); - } - - lastClickState = ChipmunkDemoRightClick; - } - - if (ChipmunkDemoRightClick) - { - ChipmunkDebugDrawSegment(sliceStart, ChipmunkDemoMouse, RGBAColor(1, 0, 0, 1)); - } + cpSpaceStep(space, dt); + + static cpBool lastClickState = cpFalse; + static cpVect sliceStart = {0.0, 0.0}; + + // Annoying state tracking code that you wouldn't need + // in a real event driven system. + if(ChipmunkDemoRightClick != lastClickState){ + if(ChipmunkDemoRightClick){ + // MouseDown + sliceStart = ChipmunkDemoMouse; + } else { + // MouseUp + struct SliceContext context = {sliceStart, ChipmunkDemoMouse, space}; + cpSpaceSegmentQuery(space, sliceStart, ChipmunkDemoMouse, 0.0, GRAB_FILTER, (cpSpaceSegmentQueryFunc)SliceQuery, &context); + } + + lastClickState = ChipmunkDemoRightClick; + } + + if(ChipmunkDemoRightClick){ + ChipmunkDebugDrawSegment(sliceStart, ChipmunkDemoMouse, RGBAColor(1, 0, 0, 1)); + } } -static cpSpace* init(void) +static cpSpace * +init(void) { - ChipmunkDemoMessageString = "Right click and drag to slice up the block."; + ChipmunkDemoMessageString = "Right click and drag to slice up the block."; + + cpSpace *space = cpSpaceNew(); + cpSpaceSetIterations(space, 30); + cpSpaceSetGravity(space, cpv(0, -500)); + cpSpaceSetSleepTimeThreshold(space, 0.5f); + cpSpaceSetCollisionSlop(space, 0.5f); + + cpBody *body, *staticBody = cpSpaceGetStaticBody(space); + cpShape *shape; + + // Create segments around the edge of the screen. + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-1000,-240), cpv(1000,-240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - cpSpace* space = cpSpaceNew(); - cpSpaceSetIterations(space, 30); - cpSpaceSetGravity(space, cpv(0, -500)); - cpSpaceSetSleepTimeThreshold(space, 0.5f); - cpSpaceSetCollisionSlop(space, 0.5f); - - cpBody *body, *staticBody = cpSpaceGetStaticBody(space); - cpShape* shape; - - // Create segments around the edge of the screen. - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-1000, -240), cpv(1000, -240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - cpFloat width = 200.0f; - cpFloat height = 300.0f; - cpFloat mass = width * height * DENSITY; - cpFloat moment = cpMomentForBox(mass, width, height); - - body = cpSpaceAddBody(space, cpBodyNew(mass, moment)); - - shape = cpSpaceAddShape(space, cpBoxShapeNew(body, width, height, 0.0)); - cpShapeSetFriction(shape, 0.6f); - - return space; + cpFloat width = 200.0f; + cpFloat height = 300.0f; + cpFloat mass = width*height*DENSITY; + cpFloat moment = cpMomentForBox(mass, width, height); + + body = cpSpaceAddBody(space, cpBodyNew(mass, moment)); + + shape = cpSpaceAddShape(space, cpBoxShapeNew(body, width, height, 0.0)); + cpShapeSetFriction(shape, 0.6f); + + return space; } -static void destroy(cpSpace* space) +static void +destroy(cpSpace *space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo Slice = { - "Slice.", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, + "Slice.", + 1.0/60.0, + init, + update, + ChipmunkDemoDefaultDrawImpl, + destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Springies.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Springies.c index 89fdfab170..8673e08fbe 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Springies.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Springies.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,135 +18,145 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" -static cpFloat springForce(cpConstraint* spring, cpFloat dist) +static cpFloat +springForce(cpConstraint *spring, cpFloat dist) { - cpFloat clamp = 20.0f; - return cpfclamp(cpDampedSpringGetRestLength(spring) - dist, -clamp, clamp) * cpDampedSpringGetStiffness(spring); + cpFloat clamp = 20.0f; + return cpfclamp(cpDampedSpringGetRestLength(spring) - dist, -clamp, clamp)*cpDampedSpringGetStiffness(spring); } -static cpConstraint* -new_spring(cpBody* a, cpBody* b, cpVect anchorA, cpVect anchorB, cpFloat restLength, cpFloat stiff, cpFloat damp) +static cpConstraint * +new_spring(cpBody *a, cpBody *b, cpVect anchorA, cpVect anchorB, cpFloat restLength, cpFloat stiff, cpFloat damp) { - cpConstraint* spring = cpDampedSpringNew(a, b, anchorA, anchorB, restLength, stiff, damp); - cpDampedSpringSetSpringForceFunc(spring, springForce); - - return spring; + cpConstraint *spring = cpDampedSpringNew(a, b, anchorA, anchorB, restLength, stiff, damp); + cpDampedSpringSetSpringForceFunc(spring, springForce); + + return spring; } -static void update(cpSpace* space, double dt) +static void +update(cpSpace *space, double dt) { - cpSpaceStep(space, dt); + cpSpaceStep(space, dt); } -static cpBody* add_bar(cpSpace* space, cpVect a, cpVect b, int group) +static cpBody * +add_bar(cpSpace *space, cpVect a, cpVect b, int group) { - cpVect center = cpvmult(cpvadd(a, b), 1.0f / 2.0f); - cpFloat length = cpvlength(cpvsub(b, a)); - cpFloat mass = length / 160.0f; - - cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, mass * length * length / 12.0f)); - cpBodySetPosition(body, center); - - cpShape* shape = cpSpaceAddShape(space, cpSegmentShapeNew(body, cpvsub(a, center), cpvsub(b, center), 10.0f)); - cpShapeSetFilter(shape, cpShapeFilterNew(group, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); - - return body; + cpVect center = cpvmult(cpvadd(a, b), 1.0f/2.0f); + cpFloat length = cpvlength(cpvsub(b, a)); + cpFloat mass = length/160.0f; + + cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, mass*length*length/12.0f)); + cpBodySetPosition(body, center); + + cpShape *shape = cpSpaceAddShape(space, cpSegmentShapeNew(body, cpvsub(a, center), cpvsub(b, center), 10.0f)); + cpShapeSetFilter(shape, cpShapeFilterNew(group, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); + + return body; } -static cpSpace* init(void) +static cpSpace * +init(void) { - cpSpace* space = cpSpaceNew(); - cpBody* staticBody = cpSpaceGetStaticBody(space); + cpSpace *space = cpSpaceNew(); + cpBody *staticBody = cpSpaceGetStaticBody(space); + + cpBody *body1 = add_bar(space, cpv(-240, 160), cpv(-160, 80), 1); + cpBody *body2 = add_bar(space, cpv(-160, 80), cpv( -80, 160), 1); + cpBody *body3 = add_bar(space, cpv( 0, 160), cpv( 80, 0), 0); + cpBody *body4 = add_bar(space, cpv( 160, 160), cpv( 240, 160), 0); + cpBody *body5 = add_bar(space, cpv(-240, 0), cpv(-160, -80), 2); + cpBody *body6 = add_bar(space, cpv(-160, -80), cpv( -80, 0), 2); + cpBody *body7 = add_bar(space, cpv( -80, 0), cpv( 0, 0), 2); + cpBody *body8 = add_bar(space, cpv( 0, -80), cpv( 80, -80), 0); + cpBody *body9 = add_bar(space, cpv( 240, 80), cpv( 160, 0), 3); + cpBody *body10 = add_bar(space, cpv( 160, 0), cpv( 240, -80), 3); + cpBody *body11 = add_bar(space, cpv(-240, -80), cpv(-160, -160), 4); + cpBody *body12 = add_bar(space, cpv(-160, -160), cpv( -80, -160), 4); + cpBody *body13 = add_bar(space, cpv( 0, -160), cpv( 80, -160), 0); + cpBody *body14 = add_bar(space, cpv( 160, -160), cpv( 240, -160), 0); + + cpSpaceAddConstraint(space, cpPivotJointNew2( body1, body2, cpv( 40,-40), cpv(-40,-40))); + cpSpaceAddConstraint(space, cpPivotJointNew2( body5, body6, cpv( 40,-40), cpv(-40,-40))); + cpSpaceAddConstraint(space, cpPivotJointNew2( body6, body7, cpv( 40, 40), cpv(-40, 0))); + cpSpaceAddConstraint(space, cpPivotJointNew2( body9, body10, cpv(-40,-40), cpv(-40, 40))); + cpSpaceAddConstraint(space, cpPivotJointNew2(body11, body12, cpv( 40,-40), cpv(-40, 0))); + + cpFloat stiff = 100.0f; + cpFloat damp = 0.5f; + cpSpaceAddConstraint(space, new_spring(staticBody, body1, cpv(-320, 240), cpv(-40, 40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body1, cpv(-320, 80), cpv(-40, 40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body1, cpv(-160, 240), cpv(-40, 40), 0.0f, stiff, damp)); - cpBody* body1 = add_bar(space, cpv(-240, 160), cpv(-160, 80), 1); - cpBody* body2 = add_bar(space, cpv(-160, 80), cpv(-80, 160), 1); - cpBody* body3 = add_bar(space, cpv(0, 160), cpv(80, 0), 0); - cpBody* body4 = add_bar(space, cpv(160, 160), cpv(240, 160), 0); - cpBody* body5 = add_bar(space, cpv(-240, 0), cpv(-160, -80), 2); - cpBody* body6 = add_bar(space, cpv(-160, -80), cpv(-80, 0), 2); - cpBody* body7 = add_bar(space, cpv(-80, 0), cpv(0, 0), 2); - cpBody* body8 = add_bar(space, cpv(0, -80), cpv(80, -80), 0); - cpBody* body9 = add_bar(space, cpv(240, 80), cpv(160, 0), 3); - cpBody* body10 = add_bar(space, cpv(160, 0), cpv(240, -80), 3); - cpBody* body11 = add_bar(space, cpv(-240, -80), cpv(-160, -160), 4); - cpBody* body12 = add_bar(space, cpv(-160, -160), cpv(-80, -160), 4); - cpBody* body13 = add_bar(space, cpv(0, -160), cpv(80, -160), 0); - cpBody* body14 = add_bar(space, cpv(160, -160), cpv(240, -160), 0); + cpSpaceAddConstraint(space, new_spring(staticBody, body2, cpv(-160, 240), cpv( 40, 40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body2, cpv( 0, 240), cpv( 40, 40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, cpPivotJointNew2(body1, body2, cpv(40, -40), cpv(-40, -40))); - cpSpaceAddConstraint(space, cpPivotJointNew2(body5, body6, cpv(40, -40), cpv(-40, -40))); - cpSpaceAddConstraint(space, cpPivotJointNew2(body6, body7, cpv(40, 40), cpv(-40, 0))); - cpSpaceAddConstraint(space, cpPivotJointNew2(body9, body10, cpv(-40, -40), cpv(-40, 40))); - cpSpaceAddConstraint(space, cpPivotJointNew2(body11, body12, cpv(40, -40), cpv(-40, 0))); + cpSpaceAddConstraint(space, new_spring(staticBody, body3, cpv( 80, 240), cpv(-40, 80), 0.0f, stiff, damp)); - cpFloat stiff = 100.0f; - cpFloat damp = 0.5f; - cpSpaceAddConstraint(space, new_spring(staticBody, body1, cpv(-320, 240), cpv(-40, 40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body1, cpv(-320, 80), cpv(-40, 40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body1, cpv(-160, 240), cpv(-40, 40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body4, cpv( 80, 240), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body4, cpv( 320, 240), cpv( 40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body2, cpv(-160, 240), cpv(40, 40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body2, cpv(0, 240), cpv(40, 40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body5, cpv(-320, 80), cpv(-40, 40), 0.0f, stiff, damp)); + + cpSpaceAddConstraint(space, new_spring(staticBody, body9, cpv( 320, 80), cpv( 40, 40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body3, cpv(80, 240), cpv(-40, 80), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body10, cpv( 320, 0), cpv( 40,-40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body10, cpv( 320,-160), cpv( 40,-40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body4, cpv(80, 240), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body4, cpv(320, 240), cpv(40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body11, cpv(-320,-160), cpv(-40, 40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body5, cpv(-320, 80), cpv(-40, 40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body12, cpv(-240,-240), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body12, cpv( 0,-240), cpv( 40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body9, cpv(320, 80), cpv(40, 40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body13, cpv( 0,-240), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body13, cpv( 80,-240), cpv( 40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body10, cpv(320, 0), cpv(40, -40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body10, cpv(320, -160), cpv(40, -40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body14, cpv( 80,-240), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body14, cpv( 240,-240), cpv( 40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body14, cpv( 320,-160), cpv( 40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body11, cpv(-320, -160), cpv(-40, 40), 0.0f, stiff, damp)); - - cpSpaceAddConstraint(space, new_spring(staticBody, body12, cpv(-240, -240), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body12, cpv(0, -240), cpv(40, 0), 0.0f, stiff, damp)); - - cpSpaceAddConstraint(space, new_spring(staticBody, body13, cpv(0, -240), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body13, cpv(80, -240), cpv(40, 0), 0.0f, stiff, damp)); - - cpSpaceAddConstraint(space, new_spring(staticBody, body14, cpv(80, -240), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body14, cpv(240, -240), cpv(40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body14, cpv(320, -160), cpv(40, 0), 0.0f, stiff, damp)); - - cpSpaceAddConstraint(space, new_spring(body1, body5, cpv(40, -40), cpv(-40, 40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body1, body6, cpv(40, -40), cpv(40, 40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body2, body3, cpv(40, 40), cpv(-40, 80), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body3, body4, cpv(-40, 80), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body3, body4, cpv(40, -80), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body3, body7, cpv(40, -80), cpv(40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body3, body7, cpv(-40, 80), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body3, body8, cpv(40, -80), cpv(40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body3, body9, cpv(40, -80), cpv(-40, -40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body4, body9, cpv(40, 0), cpv(40, 40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body5, body11, cpv(-40, 40), cpv(-40, 40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body5, body11, cpv(40, -40), cpv(40, -40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body7, body8, cpv(40, 0), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body8, body12, cpv(-40, 0), cpv(40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body8, body13, cpv(-40, 0), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body8, body13, cpv(40, 0), cpv(40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body8, body14, cpv(40, 0), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body10, body14, cpv(40, -40), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body10, body14, cpv(40, -40), cpv(-40, 0), 0.0f, stiff, damp)); - - return space; + cpSpaceAddConstraint(space, new_spring( body1, body5, cpv( 40,-40), cpv(-40, 40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring( body1, body6, cpv( 40,-40), cpv( 40, 40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring( body2, body3, cpv( 40, 40), cpv(-40, 80), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring( body3, body4, cpv(-40, 80), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring( body3, body4, cpv( 40,-80), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring( body3, body7, cpv( 40,-80), cpv( 40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring( body3, body7, cpv(-40, 80), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring( body3, body8, cpv( 40,-80), cpv( 40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring( body3, body9, cpv( 40,-80), cpv(-40,-40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring( body4, body9, cpv( 40, 0), cpv( 40, 40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring( body5, body11, cpv(-40, 40), cpv(-40, 40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring( body5, body11, cpv( 40,-40), cpv( 40,-40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring( body7, body8, cpv( 40, 0), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring( body8, body12, cpv(-40, 0), cpv( 40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring( body8, body13, cpv(-40, 0), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring( body8, body13, cpv( 40, 0), cpv( 40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring( body8, body14, cpv( 40, 0), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body10, body14, cpv( 40,-40), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body10, body14, cpv( 40,-40), cpv(-40, 0), 0.0f, stiff, damp)); + + return space; } -static void destroy(cpSpace* space) +static void +destroy(cpSpace *space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo Springies = { - "Springies", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, + "Springies", + 1.0/60.0, + init, + update, + ChipmunkDemoDefaultDrawImpl, + destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Sticky.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Sticky.c index f7545afdbf..29924d1915 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Sticky.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Sticky.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,173 +18,180 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" -enum -{ - COLLISION_TYPE_STICKY = 1, +enum { + COLLISION_TYPE_STICKY = 1, }; #define STICK_SENSOR_THICKNESS 2.5f -static void PostStepAddJoint(cpSpace* space, void* key, void* data) +static void +PostStepAddJoint(cpSpace *space, void *key, void *data) { - // printf("Adding joint for %p\n", data); - - cpConstraint* joint = (cpConstraint*)key; - cpSpaceAddConstraint(space, joint); +// printf("Adding joint for %p\n", data); + + cpConstraint *joint = (cpConstraint *)key; + cpSpaceAddConstraint(space, joint); } -static cpBool StickyPreSolve(cpArbiter* arb, cpSpace* space, void* data) +static cpBool +StickyPreSolve(cpArbiter *arb, cpSpace *space, void *data) { - // We want to fudge the collisions a bit to allow shapes to overlap more. - // This simulates their squishy sticky surface, and more importantly - // keeps them from separating and destroying the joint. - - // Track the deepest collision point and use that to determine if a rigid collision should occur. - cpFloat deepest = INFINITY; - - // Grab the contact set and iterate over them. - cpContactPointSet contacts = cpArbiterGetContactPointSet(arb); - for (int i = 0; i < contacts.count; i++) - { - // Sink the contact points into the surface of each shape. - contacts.points[i].pointA = cpvsub(contacts.points[i].pointA, cpvmult(contacts.normal, STICK_SENSOR_THICKNESS)); - contacts.points[i].pointB = cpvadd(contacts.points[i].pointB, cpvmult(contacts.normal, STICK_SENSOR_THICKNESS)); - deepest = cpfmin(deepest, contacts.points[i].distance); // + 2.0f*STICK_SENSOR_THICKNESS); - } - - // Set the new contact point data. - cpArbiterSetContactPointSet(arb, &contacts); - - // If the shapes are overlapping enough, then create a - // joint that sticks them together at the first contact point. - if (!cpArbiterGetUserData(arb) && deepest <= 0.0f) - { - CP_ARBITER_GET_BODIES(arb, bodyA, bodyB); - - // Create a joint at the contact point to hold the body in place. - cpVect anchorA = cpBodyWorldToLocal(bodyA, contacts.points[0].pointA); - cpVect anchorB = cpBodyWorldToLocal(bodyB, contacts.points[0].pointB); - cpConstraint* joint = cpPivotJointNew2(bodyA, bodyB, anchorA, anchorB); - - // Give it a finite force for the stickyness. - cpConstraintSetMaxForce(joint, 3e3); - - // Schedule a post-step() callback to add the joint. - cpSpaceAddPostStepCallback(space, PostStepAddJoint, joint, NULL); - - // Store the joint on the arbiter so we can remove it later. - cpArbiterSetUserData(arb, joint); - } - - // Position correction and velocity are handled separately so changing - // the overlap distance alone won't prevent the collision from occuring. - // Explicitly the collision for this frame if the shapes don't overlap using the new distance. - return (deepest <= 0.0f); - - // Lots more that you could improve upon here as well: - // * Modify the joint over time to make it plastic. - // * Modify the joint in the post-step to make it conditionally plastic (like clay). - // * Track a joint for the deepest contact point instead of the first. - // * Track a joint for each contact point. (more complicated since you only get one data pointer). + // We want to fudge the collisions a bit to allow shapes to overlap more. + // This simulates their squishy sticky surface, and more importantly + // keeps them from separating and destroying the joint. + + // Track the deepest collision point and use that to determine if a rigid collision should occur. + cpFloat deepest = INFINITY; + + // Grab the contact set and iterate over them. + cpContactPointSet contacts = cpArbiterGetContactPointSet(arb); + for(int i=0; ipreSolveFunc = StickyPreSolve; - handler->separateFunc = StickySeparate; - - return space; + cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius + STICK_SENSOR_THICKNESS, cpvzero)); + cpShapeSetFriction(shape, 0.9f); + cpShapeSetCollisionType(shape, COLLISION_TYPE_STICKY); + } + + cpCollisionHandler *handler = cpSpaceAddWildcardHandler(space, COLLISION_TYPE_STICKY); + handler->preSolveFunc = StickyPreSolve; + handler->separateFunc = StickySeparate; + + return space; } -static void destroy(cpSpace* space) +static void +destroy(cpSpace *space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo Sticky = { - "Sticky Surfaces", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, + "Sticky Surfaces", + 1.0/60.0, + init, + update, + ChipmunkDemoDefaultDrawImpl, + destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Tank.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Tank.c index 3b5d1d41b4..249828966a 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Tank.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Tank.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,115 +18,119 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" static cpBody *tankBody, *tankControlBody; -static void update(cpSpace* space, double dt) +static void +update(cpSpace *space, double dt) { - // turn the control body based on the angle relative to the actual body - cpVect mouseDelta = cpvsub(ChipmunkDemoMouse, cpBodyGetPosition(tankBody)); - cpFloat turn = cpvtoangle(cpvunrotate(cpBodyGetRotation(tankBody), mouseDelta)); - cpBodySetAngle(tankControlBody, cpBodyGetAngle(tankBody) - turn); - - // drive the tank towards the mouse - if (cpvnear(ChipmunkDemoMouse, cpBodyGetPosition(tankBody), 30.0)) - { - cpBodySetVelocity(tankControlBody, cpvzero); // stop - } - else - { - cpFloat direction = (cpvdot(mouseDelta, cpBodyGetRotation(tankBody)) > 0.0 ? 1.0 : -1.0); - cpBodySetVelocity(tankControlBody, cpvrotate(cpBodyGetRotation(tankBody), cpv(30.0f * direction, 0.0f))); - } - - cpSpaceStep(space, dt); + // turn the control body based on the angle relative to the actual body + cpVect mouseDelta = cpvsub(ChipmunkDemoMouse, cpBodyGetPosition(tankBody)); + cpFloat turn = cpvtoangle(cpvunrotate(cpBodyGetRotation(tankBody), mouseDelta)); + cpBodySetAngle(tankControlBody, cpBodyGetAngle(tankBody) - turn); + + // drive the tank towards the mouse + if(cpvnear(ChipmunkDemoMouse, cpBodyGetPosition(tankBody), 30.0)){ + cpBodySetVelocity(tankControlBody, cpvzero); // stop + } else { + cpFloat direction = (cpvdot(mouseDelta, cpBodyGetRotation(tankBody)) > 0.0 ? 1.0 : -1.0); + cpBodySetVelocity(tankControlBody, cpvrotate(cpBodyGetRotation(tankBody), cpv(30.0f*direction, 0.0f))); + } + + cpSpaceStep(space, dt); } -static cpBody* add_box(cpSpace* space, cpFloat size, cpFloat mass) +static cpBody * +add_box(cpSpace *space, cpFloat size, cpFloat mass) { - cpFloat radius = cpvlength(cpv(size, size)); + cpFloat radius = cpvlength(cpv(size, size)); - cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForBox(mass, size, size))); - cpBodySetPosition( - body, cpv(frand() * (640 - 2 * radius) - (320 - radius), frand() * (480 - 2 * radius) - (240 - radius))); - - cpShape* shape = cpSpaceAddShape(space, cpBoxShapeNew(body, size, size, 0.0)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.7f); - - return body; + cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForBox(mass, size, size))); + cpBodySetPosition(body, cpv(frand()*(640 - 2*radius) - (320 - radius), frand()*(480 - 2*radius) - (240 - radius))); + + cpShape *shape = cpSpaceAddShape(space, cpBoxShapeNew(body, size, size, 0.0)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.7f); + + return body; } -static cpSpace* init(void) +static cpSpace * +init(void) { - ChipmunkDemoMessageString = "Use the mouse to drive the tank, it will follow the cursor."; + ChipmunkDemoMessageString = "Use the mouse to drive the tank, it will follow the cursor."; + + cpSpace *space = cpSpaceNew(); + cpSpaceSetIterations(space, 10); + cpSpaceSetSleepTimeThreshold(space, 0.5f); + + cpBody *staticBody = cpSpaceGetStaticBody(space); + cpShape *shape; + + // Create segments around the edge of the screen. + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - cpSpace* space = cpSpaceNew(); - cpSpaceSetIterations(space, 10); - cpSpaceSetSleepTimeThreshold(space, 0.5f); + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - cpBody* staticBody = cpSpaceGetStaticBody(space); - cpShape* shape; + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - // Create segments around the edge of the screen. - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(-320, 240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320, -240), cpv(320, 240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(320, -240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, 240), cpv(320, 240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - for (int i = 0; i < 50; i++) - { - cpBody* body = add_box(space, 20, 1); - - cpConstraint* pivot = cpSpaceAddConstraint(space, cpPivotJointNew2(staticBody, body, cpvzero, cpvzero)); - cpConstraintSetMaxBias(pivot, 0); // disable joint correction - cpConstraintSetMaxForce(pivot, 1000.0f); // emulate linear friction - - cpConstraint* gear = cpSpaceAddConstraint(space, cpGearJointNew(staticBody, body, 0.0f, 1.0f)); - cpConstraintSetMaxBias(gear, 0); // disable joint correction - cpConstraintSetMaxForce(gear, 5000.0f); // emulate angular friction - } - - // We joint the tank to the control body and control the tank indirectly by modifying the control body. - tankControlBody = cpSpaceAddBody(space, cpBodyNewKinematic()); - tankBody = add_box(space, 30, 10); - - cpConstraint* pivot = cpSpaceAddConstraint(space, cpPivotJointNew2(tankControlBody, tankBody, cpvzero, cpvzero)); - cpConstraintSetMaxBias(pivot, 0); // disable joint correction - cpConstraintSetMaxForce(pivot, 10000.0f); // emulate linear friction - - cpConstraint* gear = cpSpaceAddConstraint(space, cpGearJointNew(tankControlBody, tankBody, 0.0f, 1.0f)); - cpConstraintSetErrorBias(gear, 0); // attempt to fully correct the joint each step - cpConstraintSetMaxBias(gear, 1.2f); // but limit it's angular correction rate - cpConstraintSetMaxForce(gear, 50000.0f); // emulate angular friction - - return space; + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,240), cpv(320,240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + for(int i=0; i<50; i++){ + cpBody *body = add_box(space, 20, 1); + + cpConstraint *pivot = cpSpaceAddConstraint(space, cpPivotJointNew2(staticBody, body, cpvzero, cpvzero)); + cpConstraintSetMaxBias(pivot, 0); // disable joint correction + cpConstraintSetMaxForce(pivot, 1000.0f); // emulate linear friction + + cpConstraint *gear = cpSpaceAddConstraint(space, cpGearJointNew(staticBody, body, 0.0f, 1.0f)); + cpConstraintSetMaxBias(gear, 0); // disable joint correction + cpConstraintSetMaxForce(gear, 5000.0f); // emulate angular friction + } + + // We joint the tank to the control body and control the tank indirectly by modifying the control body. + tankControlBody = cpSpaceAddBody(space, cpBodyNewKinematic()); + tankBody = add_box(space, 30, 10); + + cpConstraint *pivot = cpSpaceAddConstraint(space, cpPivotJointNew2(tankControlBody, tankBody, cpvzero, cpvzero)); + cpConstraintSetMaxBias(pivot, 0); // disable joint correction + cpConstraintSetMaxForce(pivot, 10000.0f); // emulate linear friction + + cpConstraint *gear = cpSpaceAddConstraint(space, cpGearJointNew(tankControlBody, tankBody, 0.0f, 1.0f)); + cpConstraintSetErrorBias(gear, 0); // attempt to fully correct the joint each step + cpConstraintSetMaxBias(gear, 1.2f); // but limit it's angular correction rate + cpConstraintSetMaxForce(gear, 50000.0f); // emulate angular friction + + return space; } -static void destroy(cpSpace* space) +static void +destroy(cpSpace *space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo Tank = { - "Tank", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, + "Tank", + 1.0/60.0, + init, + update, + ChipmunkDemoDefaultDrawImpl, + destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/TheoJansen.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/TheoJansen.c index 7888cf861c..262dedbcd1 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/TheoJansen.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/TheoJansen.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -24,140 +24,145 @@ * the mechanism that Theo Jansen uses in his kinetic sculptures. Brilliant. * Read more here: http://en.wikipedia.org/wiki/Theo_Jansen */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" -static cpConstraint* motor; +static cpConstraint *motor; -static void update(cpSpace* space, double dt) +static void +update(cpSpace *space, double dt) { cpFloat coef = (2.0f + ChipmunkDemoKeyboard.y) / 3.0f; cpFloat rate = ChipmunkDemoKeyboard.x * 10.0f * coef; - cpSimpleMotorSetRate(motor, rate); - cpConstraintSetMaxForce(motor, (rate) ? 100000.0f : 0.0f); - - cpSpaceStep(space, dt); + cpSimpleMotorSetRate(motor, rate); + cpConstraintSetMaxForce(motor, (rate) ? 100000.0f : 0.0f); + + cpSpaceStep(space, dt); } static cpFloat seg_radius = 3.0f; -static void make_leg(cpSpace* space, cpFloat side, cpFloat offset, cpBody* chassis, cpBody* crank, cpVect anchor) +static void +make_leg(cpSpace *space, cpFloat side, cpFloat offset, cpBody *chassis, cpBody *crank, cpVect anchor) { - cpVect a, b; - cpShape* shape; + cpVect a, b; + cpShape *shape; + + cpFloat leg_mass = 1.0f; - cpFloat leg_mass = 1.0f; - - // make leg - a = cpvzero, b = cpv(0.0f, side); - cpBody* upper_leg = cpSpaceAddBody(space, cpBodyNew(leg_mass, cpMomentForSegment(leg_mass, a, b, 0.0f))); - cpBodySetPosition(upper_leg, cpv(offset, 0.0f)); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(upper_leg, a, b, seg_radius)); - cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); - - cpSpaceAddConstraint(space, cpPivotJointNew2(chassis, upper_leg, cpv(offset, 0.0f), cpvzero)); - - // lower leg - a = cpvzero, b = cpv(0.0f, -1.0f * side); - cpBody* lower_leg = cpSpaceAddBody(space, cpBodyNew(leg_mass, cpMomentForSegment(leg_mass, a, b, 0.0f))); - cpBodySetPosition(lower_leg, cpv(offset, -side)); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(lower_leg, a, b, seg_radius)); - cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); - - shape = cpSpaceAddShape(space, cpCircleShapeNew(lower_leg, seg_radius * 2.0f, b)); - cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 1.0f); - - cpSpaceAddConstraint(space, cpPinJointNew(chassis, lower_leg, cpv(offset, 0.0f), cpvzero)); - - cpSpaceAddConstraint(space, cpGearJointNew(upper_leg, lower_leg, 0.0f, 1.0f)); - - cpConstraint* constraint; - cpFloat diag = cpfsqrt(side * side + offset * offset); - - constraint = cpSpaceAddConstraint(space, cpPinJointNew(crank, upper_leg, anchor, cpv(0.0f, side))); - cpPinJointSetDist(constraint, diag); - - constraint = cpSpaceAddConstraint(space, cpPinJointNew(crank, lower_leg, anchor, cpvzero)); - cpPinJointSetDist(constraint, diag); + // make leg + a = cpvzero, b = cpv(0.0f, side); + cpBody *upper_leg = cpSpaceAddBody(space, cpBodyNew(leg_mass, cpMomentForSegment(leg_mass, a, b, 0.0f))); + cpBodySetPosition(upper_leg, cpv(offset, 0.0f)); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(upper_leg, a, b, seg_radius)); + cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); + + cpSpaceAddConstraint(space, cpPivotJointNew2(chassis, upper_leg, cpv(offset, 0.0f), cpvzero)); + + // lower leg + a = cpvzero, b = cpv(0.0f, -1.0f*side); + cpBody *lower_leg = cpSpaceAddBody(space, cpBodyNew(leg_mass, cpMomentForSegment(leg_mass, a, b, 0.0f))); + cpBodySetPosition(lower_leg, cpv(offset, -side)); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(lower_leg, a, b, seg_radius)); + cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); + + shape = cpSpaceAddShape(space, cpCircleShapeNew(lower_leg, seg_radius*2.0f, b)); + cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 1.0f); + + cpSpaceAddConstraint(space, cpPinJointNew(chassis, lower_leg, cpv(offset, 0.0f), cpvzero)); + + cpSpaceAddConstraint(space, cpGearJointNew(upper_leg, lower_leg, 0.0f, 1.0f)); + + cpConstraint *constraint; + cpFloat diag = cpfsqrt(side*side + offset*offset); + + constraint = cpSpaceAddConstraint(space, cpPinJointNew(crank, upper_leg, anchor, cpv(0.0f, side))); + cpPinJointSetDist(constraint, diag); + + constraint = cpSpaceAddConstraint(space, cpPinJointNew(crank, lower_leg, anchor, cpvzero)); + cpPinJointSetDist(constraint, diag); } -static cpSpace* init(void) +static cpSpace * +init(void) { - ChipmunkDemoMessageString = "Use the arrow keys to control the machine."; + ChipmunkDemoMessageString = "Use the arrow keys to control the machine."; + + cpSpace *space = cpSpaceNew(); + cpSpaceSetIterations(space, 20); + cpSpaceSetGravity(space, cpv(0,-500)); + + cpBody *staticBody = cpSpaceGetStaticBody(space); + cpShape *shape; + cpVect a, b; + + // Create segments around the edge of the screen. + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - cpSpace* space = cpSpaceNew(); - cpSpaceSetIterations(space, 20); - cpSpaceSetGravity(space, cpv(0, -500)); + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - cpBody* staticBody = cpSpaceGetStaticBody(space); - cpShape* shape; - cpVect a, b; + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + cpFloat offset = 30.0f; - // Create segments around the edge of the screen. - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(-320, 240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + // make chassis + cpFloat chassis_mass = 2.0f; + a = cpv(-offset, 0.0f), b = cpv(offset, 0.0f); + cpBody *chassis = cpSpaceAddBody(space, cpBodyNew(chassis_mass, cpMomentForSegment(chassis_mass, a, b, 0.0f))); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(chassis, a, b, seg_radius)); + cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); + + // make crank + cpFloat crank_mass = 1.0f; + cpFloat crank_radius = 13.0f; + cpBody *crank = cpSpaceAddBody(space, cpBodyNew(crank_mass, cpMomentForCircle(crank_mass, crank_radius, 0.0f, cpvzero))); + + shape = cpSpaceAddShape(space, cpCircleShapeNew(crank, crank_radius, cpvzero)); + cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); + + cpSpaceAddConstraint(space, cpPivotJointNew2(chassis, crank, cpvzero, cpvzero)); + + cpFloat side = 30.0f; + + int num_legs = 2; + for(int i=0; ionTouchBegan = CC_CALLBACK_2(ClickAndMoveTestCase::onTouchBegan, this); listener->onTouchEnded = CC_CALLBACK_2(ClickAndMoveTestCase::onTouchEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - + auto sprite = Sprite::create(s_pathGrossini); - - auto layer = LayerColor::create(Color4B(255, 255, 0, 255)); + + auto layer = LayerColor::create(Color4B(255,255,0,255)); addChild(layer, -1); - + addChild(sprite, 0, kTagSprite); - sprite->setPosition(20, 150); - - sprite->runAction(JumpTo::create(4, Vec2(300, 48), 100, 4)); - - layer->runAction(RepeatForever::create(Sequence::create(FadeIn::create(1), FadeOut::create(1), nullptr))); + sprite->setPosition(20,150); + + sprite->runAction( JumpTo::create(4, Vec2(300,48), 100, 4) ); + + layer->runAction( RepeatForever::create( + Sequence::create( + FadeIn::create(1), + FadeOut::create(1), + nullptr) + )); } -bool ClickAndMoveTestCase::onTouchBegan(Touch* touch, Event* event) +bool ClickAndMoveTestCase::onTouchBegan(Touch* touch, Event *event) { return true; } -void ClickAndMoveTestCase::onTouchEnded(Touch* touch, Event* event) +void ClickAndMoveTestCase::onTouchEnded(Touch* touch, Event *event) { auto location = touch->getLocation(); auto s = getChildByTag(kTagSprite); s->stopAllActions(); - s->runAction(MoveTo::create(1, Vec2(location.x, location.y))); - float o = location.x - s->getPosition().x; - float a = location.y - s->getPosition().y; - float at = (float)CC_RADIANS_TO_DEGREES(atanf(o / a)); - - if (a < 0) + s->runAction( MoveTo::create(1, Vec2(location.x, location.y) ) ); + float o = location.x - s->getPosition().x; + float a = location.y - s->getPosition().y; + float at = (float) CC_RADIANS_TO_DEGREES( atanf( o/a) ); + + if( a < 0 ) { - if (o < 0) + if( o < 0 ) at = 180 + fabs(at); else - at = 180 - fabs(at); + at = 180 - fabs(at); } - - s->runAction(RotateTo::create(1, at)); + + s->runAction( RotateTo::create(1, at) ); } diff --git a/tests/cpp-tests/Classes/ClickAndMoveTest/ClickAndMoveTest.h b/tests/cpp-tests/Classes/ClickAndMoveTest/ClickAndMoveTest.h index f11276c787..e69bdd723c 100644 --- a/tests/cpp-tests/Classes/ClickAndMoveTest/ClickAndMoveTest.h +++ b/tests/cpp-tests/Classes/ClickAndMoveTest/ClickAndMoveTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 diff --git a/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp b/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp index 3aaa08dae4..1621f3927a 100644 --- a/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp +++ b/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -24,7 +24,7 @@ // // ClippingNodeTest -// +// // // by Pierre-David Bélanger // @@ -37,13 +37,12 @@ USING_NS_CC; -enum -{ - kTagTitleLabel = 1, - kTagSubtitleLabel = 2, - kTagStencilNode = 100, - kTagClipperNode = 101, - kTagContentNode = 102, +enum { + kTagTitleLabel = 1, + kTagSubtitleLabel = 2, + kTagStencilNode = 100, + kTagClipperNode = 101, + kTagContentNode = 102, }; ClippingNodeTests::ClippingNodeTests() @@ -72,59 +71,62 @@ ClippingNodeTests::ClippingNodeTests() bool BaseClippingNodeTest::init() { - if (TestCase::init()) - { - + if (TestCase::init()) { + auto background = Sprite::create(s_back3); - background->setAnchorPoint(Vec2::ZERO); - background->setPosition(Vec2::ZERO); + background->setAnchorPoint( Vec2::ZERO ); + background->setPosition( Vec2::ZERO ); this->addChild(background, -1); this->setup(); return true; - } - return false; + } + return false; } BaseClippingNodeTest::~BaseClippingNodeTest() { - Director::getInstance()->getTextureCache()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); } std::string BaseClippingNodeTest::title() const { - return "Clipping Demo"; + return "Clipping Demo"; +} + +void BaseClippingNodeTest::setup() +{ + } -void BaseClippingNodeTest::setup() {} // BasicTest std::string BasicTest::title() const { - return "Basic Test"; + return "Basic Test"; } std::string BasicTest::subtitle() const { - return ""; + return ""; } void BasicTest::setup() { auto s = Director::getInstance()->getWinSize(); - + auto stencil = this->stencil(); - stencil->setTag(kTagStencilNode); + stencil->setTag( kTagStencilNode ); stencil->setPosition(50, 50); - + auto clipper = this->clipper(); - clipper->setTag(kTagClipperNode); + clipper->setTag( kTagClipperNode ); clipper->setAnchorPoint(Vec2(0.5f, 0.5f)); clipper->setPosition(s.width / 2 - 50, s.height / 2 - 50); clipper->setStencil(stencil); this->addChild(clipper); - + auto content = this->content(); content->setPosition(50, 50); clipper->addChild(content); @@ -157,7 +159,7 @@ DrawNode* BasicTest::shape() Sprite* BasicTest::grossini() { auto grossini = Sprite::create(s_pathGrossini); - grossini->setScale(1.5); + grossini->setScale( 1.5 ); return grossini; } @@ -176,16 +178,17 @@ Node* BasicTest::content() return nullptr; } + // ShapeTest std::string ShapeTest::title() const { - return "Shape Basic Test"; + return "Shape Basic Test"; } std::string ShapeTest::subtitle() const { - return "A DrawNode as stencil and Sprite as content"; + return "A DrawNode as stencil and Sprite as content"; } Node* ShapeTest::stencil() @@ -202,16 +205,17 @@ Node* ShapeTest::content() return node; } + // ShapeInvertedTest std::string ShapeInvertedTest::title() const { - return "Shape Inverted Basic Test"; + return "Shape Inverted Basic Test"; } std::string ShapeInvertedTest::subtitle() const { - return "A DrawNode as stencil and Sprite as content, inverted"; + return "A DrawNode as stencil and Sprite as content, inverted"; } ClippingNode* ShapeInvertedTest::clipper() @@ -225,12 +229,12 @@ ClippingNode* ShapeInvertedTest::clipper() std::string SpriteTest::title() const { - return "Sprite Basic Test"; + return "Sprite Basic Test"; } std::string SpriteTest::subtitle() const { - return "A Sprite as stencil and DrawNode as content"; + return "A Sprite as stencil and DrawNode as content"; } Node* SpriteTest::stencil() @@ -258,12 +262,12 @@ Node* SpriteTest::content() std::string SpriteNoAlphaTest::title() const { - return "Sprite No Alpha Basic Test"; + return "Sprite No Alpha Basic Test"; } std::string SpriteNoAlphaTest::subtitle() const { - return "A Sprite as stencil and DrawNode as content, no alpha"; + return "A Sprite as stencil and DrawNode as content, no alpha"; } ClippingNode* SpriteNoAlphaTest::clipper() @@ -277,12 +281,12 @@ ClippingNode* SpriteNoAlphaTest::clipper() std::string SpriteInvertedTest::title() const { - return "Sprite Inverted Basic Test"; + return "Sprite Inverted Basic Test"; } std::string SpriteInvertedTest::subtitle() const { - return "A Sprite as stencil and DrawNode as content, inverted"; + return "A Sprite as stencil and DrawNode as content, inverted"; } ClippingNode* SpriteInvertedTest::clipper() @@ -297,23 +301,22 @@ ClippingNode* SpriteInvertedTest::clipper() std::string NestedTest::title() const { - return "Nested Test"; + return "Nested Test"; } std::string NestedTest::subtitle() const { - return "Nest 9 Clipping Nodes, max is usually 8"; + return "Nest 9 Clipping Nodes, max is usually 8"; } void NestedTest::setup() { static int depth = 9; - + Node* parent = this; - - for (int i = 0; i < depth; i++) - { - + + for (int i = 0; i < depth; i++) { + int size = 225 - i * (225 / (depth * 2)); auto clipper = ClippingNode::create(); @@ -323,19 +326,20 @@ void NestedTest::setup() clipper->setAlphaThreshold(0.05f); clipper->runAction(RepeatForever::create(RotateBy::create(i % 3 ? 1.33f : 1.66f, i % 2 ? 90.0f : -90.0f))); parent->addChild(clipper); - + auto stencil = Sprite::create(s_pathGrossini); - stencil->setScale(2.5f - (i * (2.5f / depth))); - stencil->setAnchorPoint(Vec2(0.5f, 0.5f)); + stencil->setScale( 2.5f - (i * (2.5f / depth)) ); + stencil->setAnchorPoint( Vec2(0.5f, 0.5f) ); stencil->setPosition(clipper->getContentSize().width / 2, clipper->getContentSize().height / 2); stencil->setVisible(false); stencil->runAction(Sequence::createWithTwoActions(DelayTime::create(i), Show::create())); clipper->setStencil(stencil); clipper->addChild(stencil); - + parent = clipper; } + } // HoleDemo @@ -349,12 +353,12 @@ HoleDemo::~HoleDemo() std::string HoleDemo::title() const { - return "Hole Demo"; + return "Hole Demo"; } std::string HoleDemo::subtitle() const { - return "Touch/click to poke holes"; + return "Touch/click to poke holes"; } void HoleDemo::setup() @@ -362,73 +366,74 @@ void HoleDemo::setup() auto target = Sprite::create(s_pathBlock); target->setAnchorPoint(Vec2::ZERO); target->setScale(3); - + _outerClipper = ClippingNode::create(); _outerClipper->retain(); AffineTransform transform = AffineTransform::IDENTITY; - transform = AffineTransformScale(transform, target->getScale(), target->getScale()); + transform = AffineTransformScale(transform, target->getScale(), target->getScale()); _outerClipper->setContentSize(SizeApplyAffineTransform(target->getContentSize(), transform)); - _outerClipper->setAnchorPoint(Vec2(0.5f, 0.5f)); + _outerClipper->setAnchorPoint( Vec2(0.5f, 0.5f) ); _outerClipper->setPosition(Vec2(this->getContentSize()) * 0.5f); _outerClipper->runAction(RepeatForever::create(RotateBy::create(1, 45))); - - _outerClipper->setStencil(target); - + + _outerClipper->setStencil( target ); + auto holesClipper = ClippingNode::create(); holesClipper->setInverted(true); - holesClipper->setAlphaThreshold(0.05f); - + holesClipper->setAlphaThreshold( 0.05f ); + holesClipper->addChild(target); - + _holes = Node::create(); _holes->retain(); - + holesClipper->addChild(_holes); - + _holesStencil = Node::create(); _holesStencil->retain(); - - holesClipper->setStencil(_holesStencil); - + + holesClipper->setStencil( _holesStencil); + _outerClipper->addChild(holesClipper); this->addChild(_outerClipper); - auto listener = EventListenerTouchAllAtOnce::create(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(HoleDemo::onTouchesBegan, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); } void HoleDemo::pokeHoleAtPoint(Vec2 point) { - float scale = CCRANDOM_0_1() * 0.2 + 0.9; + float scale = CCRANDOM_0_1() * 0.2 + 0.9; float rotation = CCRANDOM_0_1() * 360; - + auto hole = Sprite::create("Images/hole_effect.png"); - hole->setPosition(point); - hole->setRotation(rotation); - hole->setScale(scale); - + hole->setPosition( point ); + hole->setRotation( rotation ); + hole->setScale( scale ); + _holes->addChild(hole); - + auto holeStencil = Sprite::create("Images/hole_stencil.png"); - holeStencil->setPosition(point); - holeStencil->setRotation(rotation); - holeStencil->setScale(scale); - + holeStencil->setPosition( point ); + holeStencil->setRotation( rotation ); + holeStencil->setScale( scale ); + _holesStencil->addChild(holeStencil); - _outerClipper->runAction(Sequence::createWithTwoActions(ScaleBy::create(0.05f, 0.95f), ScaleTo::create(0.125f, 1))); + _outerClipper->runAction(Sequence::createWithTwoActions(ScaleBy::create(0.05f, 0.95f), + ScaleTo::create(0.125f, 1))); } + void HoleDemo::onTouchesBegan(const std::vector& touches, Event* event) { - Touch* touch = (Touch*)touches[0]; - Vec2 point = _outerClipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView())); - auto rect = Rect(0, 0, _outerClipper->getContentSize().width, _outerClipper->getContentSize().height); - if (!rect.containsPoint(point)) - return; + Touch *touch = (Touch *)touches[0]; + Vec2 point = _outerClipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView())); + auto rect = Rect(0, 0, _outerClipper->getContentSize().width, _outerClipper->getContentSize().height); + if (!rect.containsPoint(point)) return; this->pokeHoleAtPoint(point); } @@ -436,20 +441,20 @@ void HoleDemo::onTouchesBegan(const std::vector& touches, Event* event) std::string ScrollViewDemo::title() const { - return "Scroll View Demo"; + return "Scroll View Demo"; } std::string ScrollViewDemo::subtitle() const { - return "Move/drag to scroll the content"; + return "Move/drag to scroll the content"; } void ScrollViewDemo::setup() { auto clipper = ClippingNode::create(); - clipper->setTag(kTagClipperNode); - clipper->setContentSize(Size(200.0f, 200.0f)); - clipper->setAnchorPoint(Vec2(0.5f, 0.5f)); + clipper->setTag( kTagClipperNode ); + clipper->setContentSize( Size(200.0f, 200.0f) ); + clipper->setAnchorPoint( Vec2(0.5f, 0.5f) ); clipper->setPosition(this->getContentSize().width / 2, this->getContentSize().height / 2); clipper->runAction(RepeatForever::create(RotateBy::create(1, 45))); this->addChild(clipper); @@ -460,53 +465,51 @@ void ScrollViewDemo::setup() rectangle[1] = Vec2(clipper->getContentSize().width, 0.0f); rectangle[2] = Vec2(clipper->getContentSize().width, clipper->getContentSize().height); rectangle[3] = Vec2(0.0f, clipper->getContentSize().height); - + Color4F white(1, 1, 1, 1); stencil->drawPolygon(rectangle, 4, white, 1, white); clipper->setStencil(stencil); auto content = Sprite::create(s_back2); - content->setTag(kTagContentNode); - content->setAnchorPoint(Vec2(0.5f, 0.5f)); + content->setTag( kTagContentNode ); + content->setAnchorPoint( Vec2(0.5f, 0.5f) ); content->setPosition(clipper->getContentSize().width / 2, clipper->getContentSize().height / 2); clipper->addChild(content); - + _scrolling = false; - auto listener = EventListenerTouchAllAtOnce::create(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(ScrollViewDemo::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(ScrollViewDemo::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(ScrollViewDemo::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); } -void ScrollViewDemo::onTouchesBegan(const std::vector& touches, Event* event) +void ScrollViewDemo::onTouchesBegan(const std::vector& touches, Event *event) { - Touch* touch = touches[0]; + Touch *touch = touches[0]; auto clipper = this->getChildByTag(kTagClipperNode); - Vec2 point = clipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView())); - auto rect = Rect(0, 0, clipper->getContentSize().width, clipper->getContentSize().height); - _scrolling = rect.containsPoint(point); - _lastPoint = point; + Vec2 point = clipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView())); + auto rect = Rect(0, 0, clipper->getContentSize().width, clipper->getContentSize().height); + _scrolling = rect.containsPoint(point); + _lastPoint = point; } -void ScrollViewDemo::onTouchesMoved(const std::vector& touches, Event* event) +void ScrollViewDemo::onTouchesMoved(const std::vector& touches, Event *event) { - if (!_scrolling) - return; - Touch* touch = touches[0]; + if (!_scrolling) return; + Touch *touch = touches[0]; auto clipper = this->getChildByTag(kTagClipperNode); - auto point = clipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView())); - Vec2 diff = point - _lastPoint; + auto point = clipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView())); + Vec2 diff = point - _lastPoint; auto content = clipper->getChildByTag(kTagContentNode); content->setPosition(content->getPosition() + diff); _lastPoint = point; } -void ScrollViewDemo::onTouchesEnded(const std::vector& touches, Event* event) +void ScrollViewDemo::onTouchesEnded(const std::vector& touches, Event *event) { - if (!_scrolling) - return; + if (!_scrolling) return; _scrolling = false; } @@ -516,36 +519,44 @@ void ScrollViewDemo::onTouchesEnded(const std::vector& touches, Event* e static const float _alphaThreshold = 0.05f; -static const int _planeCount = 8; +static const int _planeCount = 8; static const float _planeColor[][4] = { - {0, 0, 0, 0.65f}, {0.7f, 0, 0, 0.6f}, {0, 0.7f, 0, 0.55f}, {0, 0, 0.7f, 0.5f}, - {0.7f, 0.7f, 0, 0.45f}, {0, 0.7f, 0.7f, 0.4f}, {0.7f, 0, 0.7f, 0.35f}, {0.7f, 0.7f, 0.7f, 0.3f}, + {0, 0, 0, 0.65f}, + {0.7f, 0, 0, 0.6f}, + {0, 0.7f, 0, 0.55f}, + {0, 0, 0.7f, 0.5f}, + {0.7f, 0.7f, 0, 0.45f}, + {0, 0.7f, 0.7f, 0.4f}, + {0.7f, 0, 0.7f, 0.35f}, + {0.7f, 0.7f, 0.7f, 0.3f}, }; -RawStencilBufferTest::~RawStencilBufferTest() {} +RawStencilBufferTest::~RawStencilBufferTest() +{ +} std::string RawStencilBufferTest::title() const { - return "Raw Stencil Tests"; + return "Raw Stencil Tests"; } std::string RawStencilBufferTest::subtitle() const { - return "1:Default"; + return "1:Default"; } void RawStencilBufferTest::setup() { - for (int i = 0; i < _planeCount; ++i) + for(int i = 0; i < _planeCount; ++i) { Sprite* sprite = Sprite::create(s_pathGrossini); - sprite->setAnchorPoint(Vec2(0.5, 0)); - sprite->setScale(2.5f); + sprite->setAnchorPoint( Vec2(0.5, 0) ); + sprite->setScale( 2.5f ); _sprites.pushBack(sprite); Sprite* sprite2 = Sprite::create(s_pathGrossini); - sprite2->setAnchorPoint(Vec2(0.5, 0)); - sprite2->setScale(2.5f); + sprite2->setAnchorPoint( Vec2(0.5, 0) ); + sprite2->setScale( 2.5f ); _spritesStencil.pushBack(sprite2); } @@ -554,23 +565,27 @@ void RawStencilBufferTest::setup() void RawStencilBufferTest::initCommands() { - auto renderer = Director::getInstance()->getRenderer(); - _enableStencilCallback.func = [=]() { renderer->setStencilTest(true); }; + auto renderer = Director::getInstance()->getRenderer(); + _enableStencilCallback.func = [=](){ + renderer->setStencilTest(true); + }; _enableStencilCallback.init(_globalZOrder); - _disableStencilCallback.func = [=]() { renderer->setStencilTest(false); }; + _disableStencilCallback.func = [=](){ + renderer->setStencilTest(false); + }; _disableStencilCallback.init(_globalZOrder); - auto program = backend::Program::getBuiltinProgram(backend::ProgramType::POSITION_UCOLOR); - _programState = new backend::ProgramState(program); - _locColor = _programState->getProgram()->getUniformLocation("u_color"); - _locMVPMatrix = _programState->getProgram()->getUniformLocation("u_MVPMatrix"); + auto program = backend::Program::getBuiltinProgram(backend::ProgramType::POSITION_UCOLOR); + _programState = new backend::ProgramState(program); + _locColor = _programState->getProgram()->getUniformLocation("u_color"); + _locMVPMatrix = _programState->getProgram()->getUniformLocation("u_MVPMatrix"); const auto& projectionMat = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); _programState->setUniform(_locMVPMatrix, projectionMat.m, sizeof(projectionMat.m)); size_t neededCmdSize = _planeCount * 2; _renderCmds.resize(neededCmdSize); - auto winPoint = Vec2(Director::getInstance()->getWinSize()); + auto winPoint = Vec2(Director::getInstance()->getWinSize()); auto planeSize = winPoint * (1.0 / _planeCount); BlendFunc blend; blend.src = backend::BlendFactor::ONE; @@ -578,31 +593,42 @@ void RawStencilBufferTest::initCommands() for (int i = 0, cmdIndex = 0; i < _planeCount; i++) { auto stencilPoint = planeSize * (_planeCount - i); - stencilPoint.x = winPoint.x; + stencilPoint.x = winPoint.x; auto& cmd = _renderCmds[cmdIndex]; cmdIndex++; cmd.init(_globalZOrder, blend); - cmd.setBeforeCallback(CC_CALLBACK_0(RawStencilBufferTest::onBeforeDrawClip, this, i)); - Vec2 vertices[] = {Vec2::ZERO, Vec2(stencilPoint.x, 0.0f), stencilPoint, Vec2(0.0f, stencilPoint.y)}; + cmd.setBeforeCallback( CC_CALLBACK_0(RawStencilBufferTest::onBeforeDrawClip, this, i) ); + Vec2 vertices[] = { + Vec2::ZERO, + Vec2(stencilPoint.x, 0.0f), + stencilPoint, + Vec2(0.0f, stencilPoint.y) + }; unsigned short indices[] = {0, 2, 1, 0, 3, 2}; cmd.createVertexBuffer(sizeof(Vec2), 4, backend::BufferUsage::STATIC); cmd.updateVertexBuffer(vertices, sizeof(vertices)); cmd.createIndexBuffer(backend::IndexFormat::U_SHORT, 6, backend::BufferUsage::STATIC); cmd.updateIndexBuffer(indices, sizeof(indices)); cmd.getPipelineDescriptor().programState = _programState; - auto vertexLayout = _programState->getVertexLayout(); - auto& attributes = _programState->getProgram()->getActiveAttributes(); - auto iter = attributes.find("a_position"); + auto vertexLayout = _programState->getVertexLayout(); + auto& attributes = _programState->getProgram()->getActiveAttributes(); + auto iter = attributes.find("a_position"); if (iter != attributes.end()) vertexLayout->setAttribute("a_position", iter->second.location, backend::VertexFormat::FLOAT2, 0, false); vertexLayout->setLayout(sizeof(Vec2)); + auto& cmd2 = _renderCmds[cmdIndex]; cmdIndex++; cmd2.init(_globalZOrder, blend); cmd2.setBeforeCallback(CC_CALLBACK_0(RawStencilBufferTest::onBeforeDrawSprite, this, i)); - Vec2 vertices2[] = {Vec2::ZERO, Vec2(winPoint.x, 0.0f), winPoint, Vec2(0.0f, winPoint.y)}; + Vec2 vertices2[] = { + Vec2::ZERO, + Vec2(winPoint.x, 0.0f), + winPoint, + Vec2(0.0f, winPoint.y) + }; cmd2.createVertexBuffer(sizeof(Vec2), 4, backend::BufferUsage::STATIC); cmd2.updateVertexBuffer(vertices2, sizeof(vertices2)); cmd2.createIndexBuffer(backend::IndexFormat::U_SHORT, 6, backend::BufferUsage::STATIC); @@ -611,9 +637,9 @@ void RawStencilBufferTest::initCommands() } } -void RawStencilBufferTest::draw(Renderer* renderer, const Mat4& transform, uint32_t flags) -{ - auto winPoint = Vec2(Director::getInstance()->getWinSize()); +void RawStencilBufferTest::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) +{ + auto winPoint = Vec2(Director::getInstance()->getWinSize()); auto planeSize = winPoint * (1.0 / _planeCount); renderer->addCommand(&_enableStencilCallback); @@ -623,25 +649,25 @@ void RawStencilBufferTest::draw(Renderer* renderer, const Mat4& transform, uint3 auto spritePoint = planeSize * i; spritePoint.x += planeSize.x / 2; spritePoint.y = 0; - _sprites.at(i)->setPosition(spritePoint); - _spritesStencil.at(i)->setPosition(spritePoint); + _sprites.at(i)->setPosition( spritePoint ); + _spritesStencil.at(i)->setPosition( spritePoint ); renderer->clear(ClearFlag::STENCIL, Color4F::BLACK, 0.f, 0x0, _globalZOrder); renderer->addCommand(&_renderCmds[cmdIndex]); cmdIndex++; - + Director* director = Director::getInstance(); CCASSERT(nullptr != director, "Director is null when setting matrix stack"); director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); - + _modelViewTransform = this->transform(transform); _spritesStencil.at(i)->visit(renderer, _modelViewTransform, flags); director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); - + renderer->addCommand(&_renderCmds[cmdIndex]); cmdIndex++; - + director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); _modelViewTransform = this->transform(transform); _sprites.at(i)->visit(renderer, _modelViewTransform, flags); @@ -667,28 +693,26 @@ void RawStencilBufferTest::onBeforeDrawSprite(int planeIndex) void RawStencilBufferTest::setupStencilForClippingOnPlane(int plane) { - auto renderer = Director::getInstance()->getRenderer(); + auto renderer = Director::getInstance()->getRenderer(); unsigned int planeMask = 0x1 << plane; renderer->setStencilWriteMask(planeMask); renderer->setStencilCompareFunction(backend::CompareFunction::NEVER, planeMask, planeMask); - renderer->setStencilOperation(backend::StencilOperation::REPLACE, backend::StencilOperation::KEEP, - backend::StencilOperation::KEEP); + renderer->setStencilOperation(backend::StencilOperation::REPLACE, backend::StencilOperation::KEEP, backend::StencilOperation::KEEP); } void RawStencilBufferTest::setupStencilForDrawingOnPlane(int plane) { - auto renderer = Director::getInstance()->getRenderer(); + auto renderer = Director::getInstance()->getRenderer(); unsigned int planeMask = 0x1 << plane; renderer->setStencilCompareFunction(backend::CompareFunction::EQUAL, planeMask, planeMask); - renderer->setStencilOperation(backend::StencilOperation::KEEP, backend::StencilOperation::KEEP, - backend::StencilOperation::KEEP); + renderer->setStencilOperation(backend::StencilOperation::KEEP, backend::StencilOperation::KEEP, backend::StencilOperation::KEEP); } //@implementation RawStencilBufferTest2 std::string RawStencilBufferTest2::subtitle() const { - return "2:DepthMask:FALSE"; + return "2:DepthMask:FALSE"; } void RawStencilBufferTest2::setupStencilForClippingOnPlane(int plane) @@ -707,7 +731,7 @@ void RawStencilBufferTest2::setupStencilForDrawingOnPlane(int plane) std::string RawStencilBufferTest3::subtitle() const { - return "3:DepthTest:DISABLE,DepthMask:FALSE"; + return "3:DepthTest:DISABLE,DepthMask:FALSE"; } void RawStencilBufferTest3::setupStencilForClippingOnPlane(int plane) @@ -727,12 +751,11 @@ void RawStencilBufferTest3::setupStencilForDrawingOnPlane(int plane) void RawStencilBufferTestAlphaTest::setup() { RawStencilBufferTest::setup(); - for (int i = 0; i < _planeCount; ++i) + for(int i = 0; i < _planeCount; ++i) { auto program = backend::Program::getBuiltinProgram(backend::ProgramType::POSITION_TEXTURE_COLOR_ALPHA_TEST); auto programState = new backend::ProgramState(program); - programState->setUniform(programState->getUniformLocation("u_alpha_value"), &_alphaThreshold, - sizeof(_alphaThreshold)); + programState->setUniform(programState->getUniformLocation("u_alpha_value"), &_alphaThreshold, sizeof(_alphaThreshold)); _spritesStencil.at(i)->setProgramState(programState); } } @@ -740,7 +763,7 @@ void RawStencilBufferTestAlphaTest::setup() std::string RawStencilBufferTest4::subtitle() const { - return "4:DepthMask:FALSE,AlphaTest:ENABLE"; + return "4:DepthMask:FALSE,AlphaTest:ENABLE"; } void RawStencilBufferTest4::setupStencilForClippingOnPlane(int plane) @@ -760,7 +783,7 @@ void RawStencilBufferTest4::setupStencilForDrawingOnPlane(int plane) std::string RawStencilBufferTest5::subtitle() const { - return "5:DepthTest:DISABLE,DepthMask:FALSE,AlphaTest:ENABLE"; + return "5:DepthTest:DISABLE,DepthMask:FALSE,AlphaTest:ENABLE"; } void RawStencilBufferTest5::setupStencilForClippingOnPlane(int plane) @@ -782,7 +805,7 @@ void RawStencilBufferTest5::setupStencilForDrawingOnPlane(int plane) std::string RawStencilBufferTest6::subtitle() const { - return "6:ManualClear,AlphaTest:ENABLE"; + return "6:ManualClear,AlphaTest:ENABLE"; } void RawStencilBufferTest6::setup() @@ -796,8 +819,7 @@ void RawStencilBufferTest6::setupStencilForClippingOnPlane(int plane) int planeMask = 0x1 << plane; auto renderer = Director::getInstance()->getRenderer(); renderer->setStencilCompareFunction(backend::CompareFunction::NEVER, planeMask, planeMask); - renderer->setStencilOperation(backend::StencilOperation::REPLACE, backend::StencilOperation::KEEP, - backend::StencilOperation::KEEP); + renderer->setStencilOperation(backend::StencilOperation::REPLACE, backend::StencilOperation::KEEP, backend::StencilOperation::KEEP); renderer->setDepthTest(false); renderer->setDepthWrite(false); } @@ -811,7 +833,7 @@ void RawStencilBufferTest6::setupStencilForDrawingOnPlane(int plane) //#endif // COCOS2D_DEBUG > 1 -// ClippingToRenderTextureTest +//ClippingToRenderTextureTest std::string ClippingToRenderTextureTest::title() const { @@ -825,9 +847,9 @@ std::string ClippingToRenderTextureTest::subtitle() const void ClippingToRenderTextureTest::setup() { - auto button = MenuItemFont::create("Reproduce bug", [&](Ref* sender) { + auto button = MenuItemFont::create("Reproduce bug", [&](Ref *sender) { std::vector nodes; - enumerateChildren("remove me [0-9]", [&](Node* node) { + enumerateChildren("remove me [0-9]", [&](Node *node) { nodes.push_back(node); return false; }); @@ -841,7 +863,7 @@ void ClippingToRenderTextureTest::setup() auto s = Director::getInstance()->getWinSize(); // create menu, it's an autorelease object auto menu = Menu::create(button, nullptr); - menu->setPosition(Point(s.width / 2, s.height / 2)); + menu->setPosition(Point(s.width/2, s.height/2)); this->addChild(menu, 1); expectedBehaviour(); @@ -849,15 +871,16 @@ void ClippingToRenderTextureTest::setup() void ClippingToRenderTextureTest::expectedBehaviour() { - auto director = Director::getInstance(); + auto director = Director::getInstance(); Size visibleSize = director->getVisibleSize(); - Point origin = director->getVisibleOrigin(); + Point origin = director->getVisibleOrigin(); + // add "HelloWorld" splash screen" auto sprite = Sprite::create("Images/grossini.png"); // position the sprite on the center of the screen - sprite->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y)); + sprite->setPosition(Point(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); // add the sprite as a child to this layer this->addChild(sprite, 0); @@ -878,12 +901,13 @@ void ClippingToRenderTextureTest::expectedBehaviour() auto clipper = ClippingNode::create(); clipper->setAnchorPoint(Point(0.5f, 0.5f)); - clipper->setPosition(Point(visibleSize.width / 2, visibleSize.height / 2)); + clipper->setPosition( Point(visibleSize.width/2, visibleSize.height/2) ); clipper->setStencil(stencil); clipper->setInverted(true); container->addChild(clipper, 1); - auto img = DrawNode::create(); + + auto img = DrawNode::create(); triangle[0] = Point(-200, -200); triangle[1] = Point(200, -200); triangle[2] = Point(0, 200); @@ -894,19 +918,21 @@ void ClippingToRenderTextureTest::expectedBehaviour() void ClippingToRenderTextureTest::reproduceBug() { - auto director = Director::getInstance(); + auto director = Director::getInstance(); Size visibleSize = director->getVisibleSize(); - Point origin = director->getVisibleOrigin(); + Point origin = director->getVisibleOrigin(); + // add "HelloWorld" splash screen" auto sprite = Sprite::create("Images/grossini.png"); // position the sprite on the center of the screen - sprite->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y)); + sprite->setPosition(Point(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); // add the sprite as a child to this layer this->addChild(sprite, 0); + // container node that will contain the clippingNode auto container = Node::create(); container->retain(); @@ -921,12 +947,13 @@ void ClippingToRenderTextureTest::reproduceBug() auto clipper = ClippingNode::create(); clipper->setAnchorPoint(Point(0.5f, 0.5f)); - clipper->setPosition(Point(visibleSize.width / 2, visibleSize.height / 2)); + clipper->setPosition( Point(visibleSize.width/2, visibleSize.height/2) ); clipper->setStencil(stencil); clipper->setInverted(true); container->addChild(clipper, 1); - auto img = DrawNode::create(); + + auto img = DrawNode::create(); triangle[0] = Point(-200, -200); triangle[1] = Point(200, -200); triangle[2] = Point(0, 200); @@ -936,9 +963,8 @@ void ClippingToRenderTextureTest::reproduceBug() // container rendered on Texture the size of the screen and because Clipping node use stencil buffer so we need to // create RenderTexture with depthStencil format parameter - RenderTexture* rt = - RenderTexture::create(visibleSize.width, visibleSize.height, backend::PixelFormat::RGBA8, PixelFormat::D24S8); - rt->setPosition(visibleSize.width / 2, visibleSize.height / 2); + RenderTexture* rt = RenderTexture::create(visibleSize.width, visibleSize.height, backend::PixelFormat::RGBA8, PixelFormat::D24S8); + rt->setPosition(visibleSize.width/2, visibleSize.height/2); this->addChild(rt); rt->begin(); @@ -950,25 +976,24 @@ void ClippingToRenderTextureTest::reproduceBug() std::string ClippingRectangleNodeTest::title() const { - return "ClippingRectangleNode Test"; + return "ClippingRectangleNode Test"; } std::string ClippingRectangleNodeTest::subtitle() const { - return "more effectively"; + return "more effectively"; } void ClippingRectangleNodeTest::setup() { auto clipper = ClippingRectangleNode::create(); - clipper->setClippingRegion( - Rect(this->getContentSize().width / 2 - 100, this->getContentSize().height / 2 - 100, 200.0f, 200.0f)); - clipper->setTag(kTagClipperNode); + clipper->setClippingRegion(Rect(this->getContentSize().width / 2 - 100, this->getContentSize().height / 2 - 100, 200.0f, 200.0f)); + clipper->setTag( kTagClipperNode ); this->addChild(clipper); - + auto content = Sprite::create(s_back2); - content->setTag(kTagContentNode); - content->setAnchorPoint(Vec2(0.5f, 0.5f)); + content->setTag( kTagContentNode ); + content->setAnchorPoint( Vec2(0.5f, 0.5f) ); content->setPosition(this->getContentSize().width / 2, this->getContentSize().height / 2); clipper->addChild(content); } diff --git a/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.h b/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.h index a631ad659d..29f89a650c 100644 --- a/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.h +++ b/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,13 +27,9 @@ #include "renderer/CCCustomCommand.h" #include -namespace cocos2d -{ -namespace backend -{ +namespace cocos2d { namespace backend { class ProgramState; -} -} // namespace cocos2d +}} DEFINE_TEST_SUITE(ClippingNodeTests); @@ -45,7 +41,7 @@ public: ~BaseClippingNodeTest(); virtual bool init() override; - virtual std::string title() const override; + virtual std::string title() const override; virtual void setup(); }; @@ -58,15 +54,15 @@ public: virtual std::string subtitle() const override; virtual void setup() override; - virtual cocos2d::Action* actionRotate(); - virtual cocos2d::Action* actionScale(); + virtual cocos2d::Action* actionRotate(); + virtual cocos2d::Action* actionScale(); - virtual cocos2d::DrawNode* shape(); - virtual cocos2d::Sprite* grossini(); + virtual cocos2d::DrawNode* shape(); + virtual cocos2d::Sprite* grossini(); - virtual cocos2d::Node* stencil(); - virtual cocos2d::ClippingNode* clipper(); - virtual cocos2d::Node* content(); + virtual cocos2d::Node* stencil(); + virtual cocos2d::ClippingNode* clipper(); + virtual cocos2d::Node* content(); }; class ShapeTest : public BasicTest @@ -144,10 +140,9 @@ public: virtual std::string title() const override; virtual std::string subtitle() const override; void pokeHoleAtPoint(cocos2d::Vec2 point); - void onTouchesBegan(const std::vector& touches, cocos2d::Event* event); - + void onTouchesBegan(const std::vector& touches, cocos2d::Event *event); private: - cocos2d::ClippingNode* _outerClipper; + cocos2d::ClippingNode* _outerClipper; cocos2d::Node* _holes; cocos2d::Node* _holesStencil; }; @@ -160,12 +155,11 @@ public: virtual std::string title() const override; virtual std::string subtitle() const override; virtual void setup() override; - void onTouchesBegan(const std::vector& touches, cocos2d::Event* event); - void onTouchesMoved(const std::vector& touches, cocos2d::Event* event); - void onTouchesEnded(const std::vector& touches, cocos2d::Event* event); - + void onTouchesBegan(const std::vector& touches, cocos2d::Event *event); + void onTouchesMoved(const std::vector& touches, cocos2d::Event *event); + void onTouchesEnded(const std::vector& touches, cocos2d::Event *event); private: - bool _scrolling; + bool _scrolling; cocos2d::Vec2 _lastPoint; }; @@ -181,10 +175,10 @@ public: virtual std::string title() const override; virtual std::string subtitle() const override; virtual void setup() override; - virtual void draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, uint32_t flags) override; + virtual void draw(cocos2d::Renderer *renderer, const cocos2d::Mat4 &transform, uint32_t flags) override; - virtual void setupStencilForClippingOnPlane(int plane); - virtual void setupStencilForDrawingOnPlane(int plane); + virtual void setupStencilForClippingOnPlane(int plane); + virtual void setupStencilForDrawingOnPlane(int plane); protected: void onBeforeDrawClip(int planeIndex); @@ -282,7 +276,7 @@ class ClippingRectangleNodeTest : public BaseClippingNodeTest { public: CREATE_FUNC(ClippingRectangleNodeTest); - + virtual std::string title() const override; virtual std::string subtitle() const override; virtual void setup() override; diff --git a/tests/cpp-tests/Classes/ConfigurationTest/ConfigurationTest.cpp b/tests/cpp-tests/Classes/ConfigurationTest/ConfigurationTest.cpp index d947af8263..5381f8772a 100644 --- a/tests/cpp-tests/Classes/ConfigurationTest/ConfigurationTest.cpp +++ b/tests/cpp-tests/Classes/ConfigurationTest/ConfigurationTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -22,6 +22,7 @@ THE SOFTWARE. ****************************************************************************/ + #include "ConfigurationTest.h" #include "../testResource.h" #include "cocos2d.h" @@ -51,7 +52,7 @@ void ConfigurationLoadConfig::onEnter() { ConfigurationBase::onEnter(); - Configuration::getInstance()->loadConfigFile("configs/config-test-ok.plist"); + Configuration::getInstance()->loadConfigFile("configs/config-test-ok.plist"); std::string config = Configuration::getInstance()->getInfo(); log("%s\n", config.c_str()); } @@ -70,8 +71,8 @@ void ConfigurationQuery::onEnter() { ConfigurationBase::onEnter(); - log("cocos2d version: %s", Configuration::getInstance()->getValue("adxe.version").asString().c_str()); - log("OpenGL version: %s", Configuration::getInstance()->getValue("gl.version").asString().c_str()); + log("cocos2d version: %s", Configuration::getInstance()->getValue("adxe.version").asString().c_str() ); + log("OpenGL version: %s", Configuration::getInstance()->getValue("gl.version").asString().c_str() ); } std::string ConfigurationQuery::subtitle() const @@ -88,7 +89,7 @@ void ConfigurationInvalid::onEnter() { ConfigurationBase::onEnter(); - Configuration::getInstance()->loadConfigFile("configs/config-test-invalid.plist"); + Configuration::getInstance()->loadConfigFile("configs/config-test-invalid.plist"); } std::string ConfigurationInvalid::subtitle() const @@ -106,22 +107,23 @@ void ConfigurationDefault::onEnter() ConfigurationBase::onEnter(); std::string c_value = Configuration::getInstance()->getValue("invalid.key", Value("no key")).asString(); - if (c_value != "no key") - log("1. Test failed!"); - else - log("1. Test OK!"); + if( c_value != "no key" ) + log("1. Test failed!"); + else + log("1. Test OK!"); - bool b_value = Configuration::getInstance()->getValue("invalid.key", Value(true)).asBool(); - if (!b_value) - log("2. Test failed!"); - else - log("2. Test OK!"); + bool b_value = Configuration::getInstance()->getValue("invalid.key", Value(true)).asBool(); + if( ! b_value ) + log("2. Test failed!"); + else + log("2. Test OK!"); + + double d_value = Configuration::getInstance()->getValue("invalid.key", Value(42.42)).asDouble(); + if( d_value != 42.42 ) + log("3. Test failed!"); + else + log("3. Test OK!"); - double d_value = Configuration::getInstance()->getValue("invalid.key", Value(42.42)).asDouble(); - if (d_value != 42.42) - log("3. Test failed!"); - else - log("3. Test OK!"); } std::string ConfigurationDefault::subtitle() const @@ -138,13 +140,13 @@ void ConfigurationSet::onEnter() { ConfigurationBase::onEnter(); - Configuration* conf = Configuration::getInstance(); + Configuration *conf = Configuration::getInstance(); - conf->setValue("this.is.an.int.value", Value(10)); - conf->setValue("this.is.a.bool.value", Value(true)); - conf->setValue("this.is.a.string.value", Value("hello world")); + conf->setValue("this.is.an.int.value", Value(10) ); + conf->setValue("this.is.a.bool.value", Value(true) ); + conf->setValue("this.is.a.string.value", Value("hello world") ); - auto str = conf->getInfo(); + auto str = conf->getInfo(); log("%s\n", str.c_str()); } @@ -152,3 +154,4 @@ std::string ConfigurationSet::subtitle() const { return "Tests setting values manually"; } + diff --git a/tests/cpp-tests/Classes/ConfigurationTest/ConfigurationTest.h b/tests/cpp-tests/Classes/ConfigurationTest/ConfigurationTest.h index 04f97b5598..802c151264 100644 --- a/tests/cpp-tests/Classes/ConfigurationTest/ConfigurationTest.h +++ b/tests/cpp-tests/Classes/ConfigurationTest/ConfigurationTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -32,6 +32,7 @@ DEFINE_TEST_SUITE(ConfigurationTests); class ConfigurationBase : public TestCase { protected: + public: virtual std::string title() const override; }; @@ -81,4 +82,5 @@ public: virtual std::string subtitle() const override; }; -#endif // __CONFIGURATIONTEST_H__ + +#endif // __CONFIGURATIONTEST_H__ diff --git a/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.cpp b/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.cpp index ae09e42ee1..d7a40b21fc 100644 --- a/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.cpp +++ b/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.cpp @@ -28,13 +28,13 @@ #include #include #if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) -# include -# include -# include -# include +#include +#include +#include +#include #else -# include -# include +#include +#include #endif USING_NS_CC; @@ -51,9 +51,13 @@ ConsoleTests::ConsoleTests() ADD_TEST_CASE(ConsoleUploadFile); } -BaseTestConsole::BaseTestConsole() {} +BaseTestConsole::BaseTestConsole() +{ +} -BaseTestConsole::~BaseTestConsole() {} +BaseTestConsole::~BaseTestConsole() +{ +} std::string BaseTestConsole::title() const { @@ -68,20 +72,21 @@ std::string BaseTestConsole::title() const ConsoleCustomCommand::ConsoleCustomCommand() { - _console = Director::getInstance()->getConsole(); + _console = Director::getInstance()->getConsole(); static Console::Command commands[] = { - {"hello", "This is just a user generated command", - [](int fd, std::string_view args) { - const char msg[] = "how are you?\nArguments passed: "; - send(fd, msg, sizeof(msg), 0); - send(fd, args.data(), args.length(), 0); - send(fd, "\n", 1, 0); - }}, + {"hello", "This is just a user generated command", [](int fd, const std::string& args) { + const char msg[] = "how are you?\nArguments passed: "; + send(fd, msg, sizeof(msg),0); + send(fd, args.c_str(), args.length(),0); + send(fd, "\n",1,0); + }}, }; _console->addCommand(commands[0]); } -ConsoleCustomCommand::~ConsoleCustomCommand() {} +ConsoleCustomCommand::~ConsoleCustomCommand() +{ +} void ConsoleCustomCommand::onEnter() { @@ -98,6 +103,7 @@ std::string ConsoleCustomCommand::subtitle() const return "telnet localhost 5678"; } + //------------------------------------------------------------------ // // ConsoleUploadFile @@ -106,22 +112,26 @@ std::string ConsoleCustomCommand::subtitle() const ConsoleUploadFile::ConsoleUploadFile() { - std::srand((unsigned)time(nullptr)); - int id = rand() % 100000; + std::srand ((unsigned)time(nullptr)); + int id = rand()%100000; char buf[32]; sprintf(buf, "%d", id); _targetFileName = std::string("grossini") + buf + ".png"; - std::thread t = std::thread(&ConsoleUploadFile::uploadFile, this); + std::thread t = std::thread( &ConsoleUploadFile::uploadFile, this); t.detach(); } void ConsoleUploadFile::onEnter() { BaseTestConsole::onEnter(); + } -ConsoleUploadFile::~ConsoleUploadFile() {} +ConsoleUploadFile::~ConsoleUploadFile() +{ + +} void ConsoleUploadFile::uploadFile() { @@ -140,14 +150,14 @@ void ConsoleUploadFile::uploadFile() /* Obtain address(es) matching host/port */ memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ + hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ hints.ai_socktype = SOCK_STREAM; /* stream socket */ - hints.ai_flags = 0; - hints.ai_protocol = 0; /* Any protocol */ + hints.ai_flags = 0; + hints.ai_protocol = 0; /* Any protocol */ #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) WSADATA wsaData; - WSAStartup(MAKEWORD(2, 2), &wsaData); + WSAStartup(MAKEWORD(2, 2),&wsaData); #endif std::string nodeName; @@ -157,7 +167,7 @@ void ConsoleUploadFile::uploadFile() nodeName = "localhost"; s = getaddrinfo(nodeName.c_str(), "5678", &hints, &result); - if (s != 0) + if (s != 0) { CCLOG("ConsoleUploadFile: getaddrinfo error"); return; @@ -168,14 +178,14 @@ void ConsoleUploadFile::uploadFile() If socket(2) (or connect(2)) fails, we (close the socket and) try the next address. */ - for (rp = result; rp != nullptr; rp = rp->ai_next) - { - sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); + for (rp = result; rp != nullptr; rp = rp->ai_next) { + sfd = socket(rp->ai_family, rp->ai_socktype, + rp->ai_protocol); if (sfd == -1) continue; if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1) - break; /* Success */ + break; /* Success */ #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) closesocket(sfd); @@ -184,13 +194,12 @@ void ConsoleUploadFile::uploadFile() #endif } - if (rp == nullptr) - { /* No address succeeded */ + if (rp == nullptr) { /* No address succeeded */ CCLOG("ConsoleUploadFile: could not connect!"); return; } - freeaddrinfo(result); /* No longer needed */ + freeaddrinfo(result); /* No longer needed */ std::string tmp = "upload"; @@ -200,9 +209,9 @@ void ConsoleUploadFile::uploadFile() char cmd[512] = {0}; strcpy(cmd, tmp.c_str()); - send(sfd, cmd, strlen(cmd), 0); + send(sfd,cmd,strlen(cmd),0); - size_t offset = 0; + size_t offset = 0; auto readBuffer = [&offset](char* buf, size_t bytes, const Data& data) -> ssize_t { if (offset >= data.getSize()) return 0; @@ -215,11 +224,11 @@ void ConsoleUploadFile::uploadFile() return actualReadBytes; }; - while (true) + while(true) { char buffer[3], *out; - unsigned char* in; - in = (unsigned char*)buffer; + unsigned char *in; + in = (unsigned char *)buffer; // copy the file into the buffer: ssize_t ret = readBuffer(buffer, 3, srcFileData); if (ret > 0) @@ -227,16 +236,16 @@ void ConsoleUploadFile::uploadFile() int len = base64Encode(in, (unsigned int)ret, &out); send(sfd, out, len, 0); free(out); - if (ret < 3) + if(ret < 3) { - // eof + //eof log("Reach the end, total send: %d bytes", (int)offset); break; } } else { - // read error + //read error break; } } @@ -262,8 +271,9 @@ std::string ConsoleUploadFile::title() const std::string ConsoleUploadFile::subtitle() const { auto sharedFileUtils = FileUtils::getInstance(); - + std::string writablePath = sharedFileUtils->getWritablePath(); return "file uploaded to:" + writablePath + _targetFileName; } + diff --git a/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.h b/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.h index d8ee9ae90b..4f06e3618e 100644 --- a/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.h +++ b/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.h @@ -39,6 +39,7 @@ public: virtual std::string title() const override; }; + class ConsoleCustomCommand : public BaseTestConsole { public: @@ -52,7 +53,7 @@ protected: ConsoleCustomCommand(); virtual ~ConsoleCustomCommand(); - cocos2d::Console* _console; + cocos2d::Console *_console; private: CC_DISALLOW_COPY_AND_ASSIGN(ConsoleCustomCommand); @@ -72,11 +73,10 @@ protected: virtual ~ConsoleUploadFile(); void uploadFile(); - private: CC_DISALLOW_COPY_AND_ASSIGN(ConsoleUploadFile); std::string _targetFileName; }; -#endif // _CONSOLE_TEST_H_ +#endif // _CONSOLE_TEST_H_ diff --git a/tests/cpp-tests/Classes/CurlTest/CurlTest.cpp b/tests/cpp-tests/Classes/CurlTest/CurlTest.cpp index 1f7a170047..595383452f 100644 --- a/tests/cpp-tests/Classes/CurlTest/CurlTest.cpp +++ b/tests/cpp-tests/Classes/CurlTest/CurlTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -39,9 +39,9 @@ CurlTest::CurlTest() { auto label = Label::createWithTTF("Curl Test", "fonts/arial.ttf", 28); addChild(label, 0); - label->setPosition(VisibleRect::center().x, VisibleRect::top().y - 50); + label->setPosition(VisibleRect::center().x, VisibleRect::top().y-50); - auto listener = EventListenerTouchAllAtOnce::create(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesEnded = CC_CALLBACK_2(CurlTest::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); @@ -49,57 +49,57 @@ CurlTest::CurlTest() _label = Label::createWithTTF("Touch the screen to connect", "fonts/arial.ttf", 22); _label->setPosition(VisibleRect::center()); addChild(_label, 0); - + _label->retain(); } -struct MemoryStruct -{ - char* memory; - size_t size; +struct MemoryStruct { + char *memory; + size_t size; }; -static size_t WriteMemoryCallback(void* contents, size_t size, size_t nmemb, void* userp) +static size_t +WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { - size_t realsize = size * nmemb; - struct MemoryStruct* mem = (struct MemoryStruct*)userp; - - mem->memory = (char*)realloc(mem->memory, mem->size + realsize + 1); - if (mem->memory == NULL) - { - /* out of memory! */ - printf("not enough memory (realloc returned NULL)\n"); - return 0; - } - - memcpy(&(mem->memory[mem->size]), contents, realsize); - mem->size += realsize; - mem->memory[mem->size] = 0; - - return realsize; + size_t realsize = size * nmemb; + struct MemoryStruct *mem = (struct MemoryStruct *)userp; + + mem->memory = (char*)realloc(mem->memory, mem->size + realsize + 1); + if(mem->memory == NULL) { + /* out of memory! */ + printf("not enough memory (realloc returned NULL)\n"); + return 0; + } + + memcpy(&(mem->memory[mem->size]), contents, realsize); + mem->size += realsize; + mem->memory[mem->size] = 0; + + return realsize; } + // the test code is // http://curl.haxx.se/mail/lib-2009-12/0071.html -void CurlTest::onTouchesEnded(const std::vector& touches, Event* event) +void CurlTest::onTouchesEnded(const std::vector& touches, Event *event) { - CURL* curl; + CURL *curl; CURLcode res; char buffer[10]; struct MemoryStruct chunk; - - chunk.memory = (char*)malloc(1); /* will be grown as needed by the realloc above */ - chunk.size = 0; /* no data at this point */ + + chunk.memory = (char*)malloc(1); /* will be grown as needed by the realloc above */ + chunk.size = 0; /* no data at this point */ curl = curl_easy_init(); - if (curl) + if (curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://webtest.cocos2d-x.org/curltest"); - // code from http://curl.haxx.se/libcurl/c/getinmemory.html + //code from http://curl.haxx.se/libcurl/c/getinmemory.html /* we pass our 'chunk' struct to the callback function */ - curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&chunk); - // If we don't provide a write function for curl, it will receive error code 23 on windows. + curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk); + //If we don't provide a write function for curl, it will receive error code 23 on windows. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); res = curl_easy_perform(curl); @@ -111,14 +111,14 @@ void CurlTest::onTouchesEnded(const std::vector& touches, Event* event) } else { - sprintf(buffer, "code: %i", res); + sprintf(buffer,"code: %i",res); _label->setString(buffer); } - } - else + } + else { _label->setString("no curl"); - } + } } CurlTest::~CurlTest() diff --git a/tests/cpp-tests/Classes/CurlTest/CurlTest.h b/tests/cpp-tests/Classes/CurlTest/CurlTest.h index 15e23a9ffa..e36ba2f7a4 100644 --- a/tests/cpp-tests/Classes/CurlTest/CurlTest.h +++ b/tests/cpp-tests/Classes/CurlTest/CurlTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -38,10 +38,10 @@ public: CurlTest(); ~CurlTest(); - void onTouchesEnded(const std::vector& touches, cocos2d::Event* event); + void onTouchesEnded(const std::vector& touches, cocos2d::Event *event); private: cocos2d::Label* _label; }; -#endif // _CURL_TEST_H_ +#endif // _CURL_TEST_H_ diff --git a/tests/cpp-tests/Classes/CurrentLanguageTest/CurrentLanguageTest.cpp b/tests/cpp-tests/Classes/CurrentLanguageTest/CurrentLanguageTest.cpp index 33230b0570..b2b58c8e2f 100644 --- a/tests/cpp-tests/Classes/CurrentLanguageTest/CurrentLanguageTest.cpp +++ b/tests/cpp-tests/Classes/CurrentLanguageTest/CurrentLanguageTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -35,16 +35,16 @@ CurrentLanguageTest::CurrentLanguageTest() { auto label = Label::createWithTTF("Current language Test", "fonts/arial.ttf", 28); addChild(label, 0); - label->setPosition(VisibleRect::center().x, VisibleRect::top().y - 50); + label->setPosition(VisibleRect::center().x, VisibleRect::top().y-50); auto labelLanguage = Label::createWithTTF("", "fonts/arial.ttf", 20); labelLanguage->setPosition(VisibleRect::center()); - + auto labelLanguageCode = Label::createWithTTF("", "fonts/arial.ttf", 20); - labelLanguageCode->setPosition(VisibleRect::center().x, VisibleRect::center().y - 50); - + labelLanguageCode->setPosition(VisibleRect::center().x, VisibleRect::center().y-50); + const char* currentLanguageCode = Application::getInstance()->getCurrentLanguageCode(); - + labelLanguageCode->setString(currentLanguageCode); LanguageType currentLanguageType = Application::getInstance()->getCurrentLanguage(); @@ -103,3 +103,4 @@ CurrentLanguageTest::CurrentLanguageTest() addChild(labelLanguage); addChild(labelLanguageCode); } + diff --git a/tests/cpp-tests/Classes/CurrentLanguageTest/CurrentLanguageTest.h b/tests/cpp-tests/Classes/CurrentLanguageTest/CurrentLanguageTest.h index 19fb749372..6c5bfb83af 100644 --- a/tests/cpp-tests/Classes/CurrentLanguageTest/CurrentLanguageTest.h +++ b/tests/cpp-tests/Classes/CurrentLanguageTest/CurrentLanguageTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -38,4 +38,4 @@ public: CurrentLanguageTest(); }; -#endif // _CURRENT_LANGUAGE_TEST_H_ +#endif // _CURRENT_LANGUAGE_TEST_H_ diff --git a/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.cpp b/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.cpp index 2e1dbf6c6c..58b09ff4f3 100644 --- a/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.cpp +++ b/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -44,19 +44,19 @@ std::string PrettyPrinterDemo::subtitle() const void PrettyPrinterDemo::addSprite() { // create sprites - + auto s1 = Sprite::create("Images/grossini.png"); auto s2 = Sprite::create("Images/grossini_dance_01.png"); auto s3 = Sprite::create("Images/grossini_dance_02.png"); auto s4 = Sprite::create("Images/grossini_dance_03.png"); auto s5 = Sprite::create("Images/grossini_dance_04.png"); - + s1->setPosition(50, 50); s2->setPosition(60, 50); s3->setPosition(70, 50); s4->setPosition(80, 50); s5->setPosition(90, 50); - + this->addChild(s1); this->addChild(s2); this->addChild(s3); @@ -68,41 +68,41 @@ void PrettyPrinterDemo::onEnter() { TestCase::onEnter(); auto s = Director::getInstance()->getWinSize(); - + auto label = Label::createWithTTF(title().c_str(), "fonts/arial.ttf", 28); - label->setPosition(s.width / 2, s.height * 4 / 5); + label->setPosition(s.width/2, s.height * 4/5); this->addChild(label, 1); - + std::string strSubtitle = subtitle(); - if (strSubtitle.empty() == false) + if(strSubtitle.empty() == false) { auto subLabel = Label::createWithTTF(strSubtitle.c_str(), "fonts/Thonburi.ttf", 16); - subLabel->setPosition(s.width / 2, s.height * 3 / 5); + subLabel->setPosition(s.width/2, s.height * 3/5); this->addChild(subLabel, 1); } - + // Test code - // TODO: minggo - // PrettyPrinter visitor; - // - // // print dictionary - // auto dict = __Dictionary::createWithContentsOfFile("animations/animations.plist"); - // dict->acceptVisitor(visitor); - // log("%s", visitor.getResult().c_str()); - // log("-------------------------------"); - // - // __Set myset; - // for (int i = 0; i < 30; ++i) { - // myset.addObject(__String::createWithFormat("str: %d", i)); - // } - // visitor.clear(); - // myset.acceptVisitor(visitor); - // log("%s", visitor.getResult().c_str()); - // log("-------------------------------"); - // - // visitor.clear(); + //TODO: minggo +// PrettyPrinter visitor; +// +// // print dictionary +// auto dict = __Dictionary::createWithContentsOfFile("animations/animations.plist"); +// dict->acceptVisitor(visitor); +// log("%s", visitor.getResult().c_str()); +// log("-------------------------------"); +// +// __Set myset; +// for (int i = 0; i < 30; ++i) { +// myset.addObject(__String::createWithFormat("str: %d", i)); +// } +// visitor.clear(); +// myset.acceptVisitor(visitor); +// log("%s", visitor.getResult().c_str()); +// log("-------------------------------"); +// +// visitor.clear(); addSprite(); - // dict = Director::getInstance()->getTextureCache()->snapshotTextures(); - // dict->acceptVisitor(visitor); - // log("%s", visitor.getResult().c_str()); +// dict = Director::getInstance()->getTextureCache()->snapshotTextures(); +// dict->acceptVisitor(visitor); +// log("%s", visitor.getResult().c_str()); } diff --git a/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.h b/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.h index d576ea3ecc..6742f6c162 100644 --- a/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.h +++ b/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -39,9 +39,9 @@ public: virtual std::string subtitle() const override; virtual void onEnter() override; void addSprite(); - protected: - std::string _title; + std::string _title; }; -#endif // __DATAVISITOR_TEST_H__ + +#endif // __DATAVISITOR_TEST_H__ diff --git a/tests/cpp-tests/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp b/tests/cpp-tests/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp index 3efcd947ea..1c94ff53ab 100644 --- a/tests/cpp-tests/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp +++ b/tests/cpp-tests/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -45,151 +45,126 @@ string DrawPrimitivesBaseTest::title() const DrawNodeTest::DrawNodeTest() { auto s = Director::getInstance()->getWinSize(); - + auto draw = DrawNode::create(); addChild(draw, 10); - - draw->drawPoint(Vec2(s.width / 2 - 120, s.height / 2 - 120), 10, - Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); - - draw->drawPoint(Vec2(s.width / 2 + 120, s.height / 2 + 120), 10, - Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); - + + draw->drawPoint(Vec2(s.width/2-120, s.height/2-120), 10, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); + + draw->drawPoint(Vec2(s.width/2+120, s.height/2+120), 10, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); + // draw 4 small points - Vec2 position[] = {Vec2(60, 60), Vec2(70, 70), Vec2(60, 70), Vec2(70, 60)}; - draw->drawPoints(position, 4, 5, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); - + Vec2 position[] = { Vec2(60,60), Vec2(70,70), Vec2(60,70), Vec2(70,60) }; + draw->drawPoints( position, 4, 5, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); + // draw a line - draw->drawLine(Vec2(0, 0), Vec2(s.width, s.height), Color4F(1.0, 0.0, 0.0, 0.5)); - + draw->drawLine(Vec2(0,0), Vec2(s.width, s.height), Color4F(1.0, 0.0, 0.0, 0.5)); + // draw a rectangle - draw->drawRect(Vec2(23, 23), Vec2(7, 7), Color4F(1, 1, 0, 1)); - - draw->drawRect(Vec2(15, 30), Vec2(30, 15), Vec2(15, 0), Vec2(0, 15), - Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); - + draw->drawRect(Vec2(23,23), Vec2(7,7), Color4F(1,1,0,1)); + + draw->drawRect(Vec2(15,30), Vec2(30,15), Vec2(15,0), Vec2(0,15), Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); + // draw a circle - draw->drawCircle(VisibleRect::center() + Vec2(140, 0), 100, CC_DEGREES_TO_RADIANS(90), 50, true, 1.0f, 2.0f, - Color4F(1.0f, 0.0f, 0.0f, 0.5f)); - - draw->drawCircle(VisibleRect::center() - Vec2(140, 0), 50, CC_DEGREES_TO_RADIANS(90), 30, false, - Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); + draw->drawCircle(VisibleRect::center() + Vec2(140,0), 100, CC_DEGREES_TO_RADIANS(90), 50, true, 1.0f, 2.0f, Color4F(1.0f, 0.0f, 0.0f, 0.5f)); + + draw->drawCircle(VisibleRect::center() - Vec2(140,0), 50, CC_DEGREES_TO_RADIANS(90), 30, false, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); // Draw some beziers - draw->drawQuadBezier(Vec2(s.width - 150, s.height - 150), Vec2(s.width - 70, s.height - 10), - Vec2(s.width - 10, s.height - 10), 10, - Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); - - draw->drawQuadBezier(Vec2(0.0f, s.height), Vec2(s.width / 2, s.height / 2), Vec2(s.width, s.height), 50, - Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); - - draw->drawCubicBezier(VisibleRect::center(), Vec2(VisibleRect::center().x + 30, VisibleRect::center().y + 50), - Vec2(VisibleRect::center().x + 60, VisibleRect::center().y - 50), VisibleRect::right(), 100, - Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); - - draw->drawCubicBezier(Vec2(s.width - 250, 40.0f), Vec2(s.width - 70, 100.0f), Vec2(s.width - 30, 250.0f), - Vec2(s.width - 10, s.height - 50), 10, - Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); - + draw->drawQuadBezier(Vec2(s.width - 150, s.height - 150), Vec2(s.width - 70, s.height - 10), Vec2(s.width - 10, s.height - 10), 10, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); + + draw->drawQuadBezier(Vec2(0.0f, s.height), Vec2(s.width/2, s.height/2), Vec2(s.width, s.height), 50, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); + + draw->drawCubicBezier(VisibleRect::center(), Vec2(VisibleRect::center().x+30,VisibleRect::center().y+50), Vec2(VisibleRect::center().x+60,VisibleRect::center().y-50),VisibleRect::right(),100, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); + + draw->drawCubicBezier(Vec2(s.width - 250, 40.0f), Vec2(s.width - 70, 100.0f), Vec2(s.width - 30, 250.0f), Vec2(s.width - 10, s.height - 50), 10, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); + auto array = PointArray::create(20); - array->addControlPoint(Vec2(0.0f, 0.0f)); - array->addControlPoint(Vec2(80.0f, 80.0f)); - array->addControlPoint(Vec2(s.width - 80, 80.0f)); - array->addControlPoint(Vec2(s.width - 80, s.height - 80)); - array->addControlPoint(Vec2(80.0f, s.height - 80)); - array->addControlPoint(Vec2(80.0f, 80.0f)); - array->addControlPoint(Vec2(s.width / 2, s.height / 2)); + array->addControlPoint(Vec2(0.0f,0.0f)); + array->addControlPoint(Vec2(80.0f,80.0f)); + array->addControlPoint(Vec2(s.width-80,80.0f)); + array->addControlPoint(Vec2(s.width-80,s.height-80)); + array->addControlPoint(Vec2(80.0f,s.height-80)); + array->addControlPoint(Vec2(80.0f,80.0f)); + array->addControlPoint(Vec2(s.width/2, s.height/2)); draw->drawCardinalSpline(array, 0.5f, 50, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); - + auto array2 = PointArray::create(20); array2->addControlPoint(Vec2(s.width / 2, 30.0f)); - array2->addControlPoint(Vec2(s.width - 80, 30.0f)); + array2->addControlPoint(Vec2(s.width -80, 30.0f)); array2->addControlPoint(Vec2(s.width - 80, s.height - 80)); array2->addControlPoint(Vec2(s.width / 2, s.height - 80)); array2->addControlPoint(Vec2(s.width / 2, 30.0f)); draw->drawCatmullRom(array2, 50, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); - + // open random color poly - Vec2 vertices[] = {Vec2(0.0f, 0.0f), Vec2(50.0f, 50.0f), Vec2(100.0f, 50.0f), Vec2(100.0f, 100.0f), - Vec2(50.0f, 100.0f)}; - draw->drawPoly(vertices, 5, false, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); - + Vec2 vertices[] = { Vec2(0.0f,0.0f), Vec2(50.0f,50.0f), Vec2(100.0f,50.0f), Vec2(100.0f,100.0f), Vec2(50.0f,100.0f) }; + draw->drawPoly( vertices, 5, false, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); + // closed random color poly - Vec2 vertices2[] = {Vec2(30.0f, 130.0f), Vec2(30.0f, 230.0f), Vec2(50.0f, 200.0f)}; - draw->drawPoly(vertices2, 3, true, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); - + Vec2 vertices2[] = { Vec2(30.0f,130.0f), Vec2(30.0f,230.0f), Vec2(50.0f,200.0f) }; + draw->drawPoly( vertices2, 3, true, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); + // Draw 10 circles - for (int i = 0; i < 10; i++) + for( int i=0; i < 10; i++) { - draw->drawDot(Vec2(s.width / 2, s.height / 2), 10 * (10 - i), - Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); + draw->drawDot(Vec2(s.width/2, s.height/2), 10*(10-i), Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); } - + // Draw polygons - Vec2 points[] = {Vec2(s.height / 4, 0.0f), Vec2(s.width, s.height / 5), Vec2(s.width / 3 * 2, s.height)}; - draw->drawPolygon(points, sizeof(points) / sizeof(points[0]), Color4F(1.0f, 0.0f, 0.0f, 0.5f), 4, - Color4F(0.0f, 0.0f, 1.0f, 0.5f)); - + Vec2 points[] = { Vec2(s.height/4,0.0f), Vec2(s.width,s.height/5), Vec2(s.width/3*2,s.height) }; + draw->drawPolygon(points, sizeof(points)/sizeof(points[0]), Color4F(1.0f,0.0f,0.0f,0.5f), 4, Color4F(0.0f,0.0f,1.0f,0.5f)); + // star poly (triggers buggs) { - const float o = 80; - const float w = 20; - const float h = 50; - Vec2 star[] = { - Vec2(o + w, o - h), Vec2(o + w * 2, o), // lower spike - Vec2(o + w * 2 + h, o + w), Vec2(o + w * 2, o + w * 2), // right spike + const float o=80; + const float w=20; + const float h=50; + Vec2 star[] = { + Vec2(o+w,o-h), Vec2(o+w*2, o), // lower spike + Vec2(o + w*2 + h, o+w ), Vec2(o + w*2, o+w*2), // right spike // {o +w, o+w*2+h}, {o,o+w*2}, // top spike // {o -h, o+w}, {o,o}, // left spike }; - - draw->drawPolygon(star, sizeof(star) / sizeof(star[0]), Color4F(1.0f, 0.0f, 0.0f, 0.5f), 1, - Color4F(0.0f, 0.0f, 1.0f, 1.0f)); + + draw->drawPolygon(star, sizeof(star)/sizeof(star[0]), Color4F(1.0f,0.0f,0.0f,0.5f), 1, Color4F(0.0f,0.0f,1.0f,1.0f)); } - + // star poly (doesn't trigger bug... order is important un tesselation is supported. { - const float o = 180; - const float w = 20; - const float h = 50; - Vec2 star[] = { - Vec2(o, o), - Vec2(o + w, o - h), - Vec2(o + w * 2, o), // lower spike - Vec2(o + w * 2 + h, o + w), - Vec2(o + w * 2, o + w * 2), // right spike - Vec2(o + w, o + w * 2 + h), - Vec2(o, o + w * 2), // top spike - Vec2(o - h, o + w), // left spike + const float o=180; + const float w=20; + const float h=50; + Vec2 star[] = { + Vec2(o,o), Vec2(o+w,o-h), Vec2(o+w*2, o), // lower spike + Vec2(o + w*2 + h, o+w ), Vec2(o + w*2, o+w*2), // right spike + Vec2(o +w, o+w*2+h), Vec2(o,o+w*2), // top spike + Vec2(o -h, o+w), // left spike }; - - draw->drawPolygon(star, sizeof(star) / sizeof(star[0]), Color4F(1.0f, 0.0f, 0.0f, 0.5f), 1, - Color4F(0.0f, 0.0f, 1.0f, 1.0f)); + + draw->drawPolygon(star, sizeof(star)/sizeof(star[0]), Color4F(1.0f,0.0f,0.0f,0.5f), 1, Color4F(0.0f,0.0f,1.0f,1.0f)); } - - // draw a solid polygon - Vec2 vertices3[] = {Vec2(60.0f, 160.0f), Vec2(70.0f, 190.0f), Vec2(100.0f, 190.0f), Vec2(90.0f, 160.0f)}; - draw->drawSolidPoly(vertices3, 4, Color4F(1.0f, 1.0f, 0.0f, 1.0f)); - - // draw a solid rectangle - draw->drawSolidRect(Vec2(10.0f, 10.0f), Vec2(20.0f, 20.0f), Color4F(1.0f, 1.0f, 0.0f, 1.0f)); - - // draw a solid circle - draw->drawSolidCircle(VisibleRect::center() + Vec2(140.0f, 0.0f), 40, CC_DEGREES_TO_RADIANS(90), 50, 2.0f, 2.0f, - Color4F(0.0f, 1.0f, 0.0f, 1.0f)); - + + //draw a solid polygon + Vec2 vertices3[] = {Vec2(60.0f,160.0f), Vec2(70.0f,190.0f), Vec2(100.0f,190.0f), Vec2(90.0f,160.0f)}; + draw->drawSolidPoly( vertices3, 4, Color4F(1.0f,1.0f,0.0f,1.0f) ); + + //draw a solid rectangle + draw->drawSolidRect(Vec2(10.0f,10.0f), Vec2(20.0f,20.0f), Color4F(1.0f,1.0f,0.0f,1.0f)); + + //draw a solid circle + draw->drawSolidCircle( VisibleRect::center() + Vec2(140.0f,0.0f), 40, CC_DEGREES_TO_RADIANS(90), 50, 2.0f, 2.0f, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + // Draw segment - draw->drawSegment(Vec2(20.0f, s.height), Vec2(20.0f, s.height / 2), 10, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); - - draw->drawSegment(Vec2(10.0f, s.height / 2), Vec2(s.width / 2, s.height / 2), 40, Color4F(1.0f, 0.0f, 1.0f, 0.5f)); + draw->drawSegment(Vec2(20.0f,s.height), Vec2(20.0f,s.height/2), 10, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + + draw->drawSegment(Vec2(10.0f,s.height/2), Vec2(s.width/2, s.height/2), 40, Color4F(1.0f, 0.0f, 1.0f, 0.5f)); // Draw triangle - draw->drawTriangle(Vec2(10.0f, 10.0f), Vec2(70.0f, 30.0f), Vec2(100.0f, 140.0f), - Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); - - for (int i = 0; i < 100; i++) - { - draw->drawPoint(Vec2(i * 7.0f, 5.0f), (float)i / 5 + 1, - Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); + draw->drawTriangle(Vec2(10.0f, 10.0f), Vec2(70.0f, 30.0f), Vec2(100.0f, 140.0f), Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); + + for (int i = 0; i < 100; i++) { + draw->drawPoint(Vec2(i*7.0f, 5.0f), (float)i/5+1, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); } auto draw1 = DrawNode::create(); @@ -198,8 +173,8 @@ DrawNodeTest::DrawNodeTest() draw1->drawLine(Vec2(0.0f, s.height), Vec2(s.width, s.height - 20), Color4F::YELLOW); draw1->drawLine(Vec2(0.0f, 0.0f), Vec2(s.width, s.height - 20), Color4F::YELLOW); - draw->runAction(RepeatForever::create(Sequence::create(FadeIn::create(1.2), FadeOut::create(1.2), NULL))); - draw1->runAction(RepeatForever::create(Sequence::create(FadeIn::create(1.2), FadeOut::create(1.2), NULL))); + draw->runAction(RepeatForever::create(Sequence::create(FadeIn::create(1.2),FadeOut::create(1.2), NULL))); + draw1->runAction(RepeatForever::create(Sequence::create(FadeIn::create(1.2),FadeOut::create(1.2), NULL))); } string DrawNodeTest::title() const @@ -222,11 +197,9 @@ Issue11942Test::Issue11942Test() // draw a circle draw->setLineWidth(1); - draw->drawCircle(VisibleRect::center() - Vec2(140.0f, 0.0f), 50, CC_DEGREES_TO_RADIANS(90), 30, false, - Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); + draw->drawCircle(VisibleRect::center() - Vec2(140.0f,0.0f), 50, CC_DEGREES_TO_RADIANS(90), 30, false, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); draw->setLineWidth(10); - draw->drawCircle(VisibleRect::center() + Vec2(140.0f, 0.0f), 50, CC_DEGREES_TO_RADIANS(90), 30, false, - Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); + draw->drawCircle(VisibleRect::center() + Vec2(140.0f,0.0f), 50, CC_DEGREES_TO_RADIANS(90), 30, false, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); } string Issue11942Test::title() const diff --git a/tests/cpp-tests/Classes/DrawPrimitivesTest/DrawPrimitivesTest.h b/tests/cpp-tests/Classes/DrawPrimitivesTest/DrawPrimitivesTest.h index 37c10faf46..e5aae33dcb 100644 --- a/tests/cpp-tests/Classes/DrawPrimitivesTest/DrawPrimitivesTest.h +++ b/tests/cpp-tests/Classes/DrawPrimitivesTest/DrawPrimitivesTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -42,7 +42,7 @@ public: CREATE_FUNC(DrawNodeTest); DrawNodeTest(); - + virtual std::string title() const override; virtual std::string subtitle() const override; }; @@ -56,4 +56,5 @@ public: virtual std::string title() const override; virtual std::string subtitle() const override; + }; diff --git a/tests/cpp-tests/Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp b/tests/cpp-tests/Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp index ed7b707522..1ccd5aadba 100644 --- a/tests/cpp-tests/Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp +++ b/tests/cpp-tests/Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -26,7 +26,7 @@ USING_NS_CC; -enum +enum { kTagTextLayer = 1, @@ -34,7 +34,7 @@ enum kTagSprite2 = 2, kTagBackground = 1, - kTagLabel = 2, + kTagLabel = 2, }; EffectAdvanceTests::EffectAdvanceTests() @@ -56,25 +56,25 @@ void Effect1::onEnter() { EffectAdvanceBaseTest::onEnter(); - // auto target = getChildByTag(kTagBackground); - + //auto target = getChildByTag(kTagBackground); + // To reuse a grid the grid size and the grid type must be the same. // in this case: // Lens3D is Grid3D and it's size is (15,10) // Waves3D is Grid3D and it's size is (15,10) - - auto size = Director::getInstance()->getWinSize(); - auto lens = Lens3D::create(0.0f, Size(15, 10), Vec2(size.width / 2, size.height / 2), 240); - auto waves = Waves3D::create(10, Size(15, 10), 18, 15); + + auto size = Director::getInstance()->getWinSize(); + auto lens = Lens3D::create(0.0f, Size(15,10), Vec2(size.width/2,size.height/2), 240); + auto waves = Waves3D::create(10, Size(15,10), 18, 15); auto reuse = ReuseGrid::create(1); auto delay = DelayTime::create(8); - // auto orbit = OrbitCamera::create(5, 1, 2, 0, 180, 0, -90); - // auto orbit_back = orbit->reverse(); +// auto orbit = OrbitCamera::create(5, 1, 2, 0, 180, 0, -90); +// auto orbit_back = orbit->reverse(); //_bgNode->runAction( RepeatForever::create( Sequence::create( orbit, orbit_back, nullptr) ) ); - _bgNode->runAction(Sequence::create(lens, delay, reuse, waves, nullptr)); + _bgNode->runAction( Sequence::create(lens, delay, reuse, waves, nullptr) ); } std::string Effect1::title() const @@ -91,18 +91,18 @@ void Effect2::onEnter() { EffectAdvanceBaseTest::onEnter(); - // auto target = getChildByTag(kTagBackground); - + //auto target = getChildByTag(kTagBackground); + // To reuse a grid the grid size and the grid type must be the same. // in this case: // ShakyTiles is TiledGrid3D and it's size is (15,10) // Shuffletiles is TiledGrid3D and it's size is (15,10) // TurnOfftiles is TiledGrid3D and it's size is (15,10) - auto shaky = ShakyTiles3D::create(5, Size(15, 10), 4, false); - auto shuffle = ShuffleTiles::create(0, Size(15, 10), 3); - auto turnoff = TurnOffTiles::create(0, Size(15, 10), 3); - auto turnon = turnoff->reverse(); - + auto shaky = ShakyTiles3D::create(5, Size(15,10), 4, false); + auto shuffle = ShuffleTiles::create(0, Size(15,10), 3); + auto turnoff = TurnOffTiles::create(0, Size(15,10), 3); + auto turnon = turnoff->reverse(); + // reuse 2 times: // 1 for shuffle // 2 for turn off @@ -110,12 +110,12 @@ void Effect2::onEnter() auto reuse = ReuseGrid::create(2); auto delay = DelayTime::create(1); - - // id orbit = [OrbitCamera::create:5 radius:1 deltaRadius:2 angleZ:0 deltaAngleZ:180 angleX:0 deltaAngleX:-90]; - // id orbit_back = [orbit reverse]; - // - // [target runAction: [RepeatForever::create: [Sequence actions: orbit, orbit_back, nil]]]; - _bgNode->runAction(Sequence::create(shaky, delay, reuse, shuffle, delay->clone(), turnoff, turnon, nullptr)); + +// id orbit = [OrbitCamera::create:5 radius:1 deltaRadius:2 angleZ:0 deltaAngleZ:180 angleX:0 deltaAngleX:-90]; +// id orbit_back = [orbit reverse]; +// +// [target runAction: [RepeatForever::create: [Sequence actions: orbit, orbit_back, nil]]]; + _bgNode->runAction(Sequence::create( shaky, delay, reuse, shuffle, delay->clone(), turnoff, turnon, nullptr) ); } std::string Effect2::title() const @@ -123,6 +123,7 @@ std::string Effect2::title() const return "ShakyTiles + ShuffleTiles + TurnOffTiles"; } + //------------------------------------------------------------------ // // Effect3 @@ -131,18 +132,18 @@ std::string Effect2::title() const void Effect3::onEnter() { EffectAdvanceBaseTest::onEnter(); - // auto bg = getChildByTag(kTagBackground); - // auto target1 = bg->getChildByTag(kTagSprite1); - // auto target2 = bg->getChildByTag(kTagSprite2); - auto waves = Waves::create(5, Size(15, 10), 5, 20, true, false); - auto shaky = Shaky3D::create(5, Size(15, 10), 4, false); - - _target1->runAction(RepeatForever::create(waves)); - _target2->runAction(RepeatForever::create(shaky)); - + //auto bg = getChildByTag(kTagBackground); + //auto target1 = bg->getChildByTag(kTagSprite1); + //auto target2 = bg->getChildByTag(kTagSprite2); + auto waves = Waves::create(5, Size(15,10), 5, 20, true, false); + auto shaky = Shaky3D::create(5, Size(15,10), 4, false); + + _target1->runAction( RepeatForever::create( waves ) ); + _target2->runAction( RepeatForever::create( shaky ) ); + // moving background. Testing issue #244 - auto move = MoveBy::create(3, Vec2(200, 0)); - _bgNode->runAction(RepeatForever::create(Sequence::create(move, move->reverse(), nullptr))); + auto move = MoveBy::create(3, Vec2(200,0) ); + _bgNode->runAction(RepeatForever::create( Sequence::create(move, move->reverse(), nullptr) )); } std::string Effect3::title() const @@ -150,6 +151,7 @@ std::string Effect3::title() const return "Effects on 2 sprites"; } + //------------------------------------------------------------------ // // Effect4 @@ -159,20 +161,28 @@ std::string Effect3::title() const class Lens3DTarget : public Node { public: - virtual void setPosition(const Vec2& var) { _lens3D->setPosition(var); } - - virtual const Vec2& getPosition() const { return _lens3D->getPosition(); } - + virtual void setPosition(const Vec2& var) + { + _lens3D->setPosition(var); + } + + virtual const Vec2& getPosition() const + { + return _lens3D->getPosition(); + } + static Lens3DTarget* create(Lens3D* pAction) { Lens3DTarget* pRet = new Lens3DTarget(); - pRet->_lens3D = pAction; + pRet->_lens3D = pAction; pRet->autorelease(); return pRet; } - private: - Lens3DTarget() : _lens3D(nullptr) {} + + Lens3DTarget() + : _lens3D(nullptr) + {} Lens3D* _lens3D; }; @@ -180,27 +190,27 @@ private: void Effect4::onEnter() { EffectAdvanceBaseTest::onEnter(); - // Node* gridNode = NodeGrid::create(); - - auto lens = Lens3D::create(10, Size(32, 24), Vec2(100, 180), 150); - auto move = JumpBy::create(5, Vec2(380, 0), 100, 4); + //Node* gridNode = NodeGrid::create(); + + auto lens = Lens3D::create(10, Size(32,24), Vec2(100,180), 150); + auto move = JumpBy::create(5, Vec2(380,0), 100, 4); auto move_back = move->reverse(); - auto seq = Sequence::create(move, move_back, nullptr); + auto seq = Sequence::create( move, move_back, nullptr); - /* In cocos2d-iphone, the type of action's target is 'id', so it supports using the instance of 'Lens3D' as its - target. While in cocos2d-x, the target of action only supports Node or its subclass, so we make an encapsulation - for Lens3D to achieve that. + /* In cocos2d-iphone, the type of action's target is 'id', so it supports using the instance of 'Lens3D' as its target. + While in cocos2d-x, the target of action only supports Node or its subclass, + so we make an encapsulation for Lens3D to achieve that. */ auto director = Director::getInstance(); - auto pTarget = Lens3DTarget::create(lens); + auto pTarget = Lens3DTarget::create(lens); // Please make sure the target been added to its parent. this->addChild(pTarget); - // gridNode->addChild(pTarget); + //gridNode->addChild(pTarget); director->getActionManager()->addAction(seq, pTarget, false); - - _bgNode->runAction(lens); + + _bgNode->runAction( lens ); } std::string Effect4::title() const @@ -217,16 +227,19 @@ void Effect5::onEnter() { EffectAdvanceBaseTest::onEnter(); - // CCDirector::getInstance()->setProjection(DirectorProjection2D); + //CCDirector::getInstance()->setProjection(DirectorProjection2D); + + auto effect = Liquid::create(2, Size(32,24), 1, 20); - auto effect = Liquid::create(2, Size(32, 24), 1, 20); - - auto stopEffect = Sequence::create(effect, DelayTime::create(2), StopGrid::create(), - // [DelayTime::create:2], - // [[effect copy] autorelease], - nullptr); - - // auto bg = getChildByTag(kTagBackground); + auto stopEffect = Sequence::create( + effect, + DelayTime::create(2), + StopGrid::create(), + // [DelayTime::create:2], + // [[effect copy] autorelease], + nullptr); + + //auto bg = getChildByTag(kTagBackground); _bgNode->runAction(stopEffect); } @@ -250,32 +263,32 @@ void Effect5::onExit() void Issue631::onEnter() { EffectAdvanceBaseTest::onEnter(); - - auto effect = Sequence::create(DelayTime::create(2.0f), Shaky3D::create(5.0f, Size(5, 5), 16, false), nullptr); + + auto effect = Sequence::create( DelayTime::create(2.0f), Shaky3D::create(5.0f, Size(5, 5), 16, false), nullptr); // cleanup - // auto bg = getChildByTag(kTagBackground); + //auto bg = getChildByTag(kTagBackground); removeChild(_bgNode, true); // background - auto layer = LayerColor::create(Color4B(255, 0, 0, 255)); + auto layer = LayerColor::create( Color4B(255,0,0,255) ); addChild(layer, -10); auto sprite = Sprite::create("Images/grossini.png"); - sprite->setPosition(50, 80); + sprite->setPosition(50,80); layer->addChild(sprite, 10); - + // foreground auto layer2BaseGrid = NodeGrid::create(); - auto layer2 = LayerColor::create(Color4B(0, 255, 0, 255)); - auto fog = Sprite::create("Images/Fog.png"); + auto layer2 = LayerColor::create(Color4B( 0, 255,0,255 ) ); + auto fog = Sprite::create("Images/Fog.png"); BlendFunc bf = {backend::BlendFactor::SRC_ALPHA, backend::BlendFactor::ONE_MINUS_SRC_ALPHA}; fog->setBlendFunc(bf); layer2->addChild(fog, 1); addChild(layer2BaseGrid, 1); layer2BaseGrid->addChild(layer2); - - layer2BaseGrid->runAction(RepeatForever::create(effect)); + + layer2BaseGrid->runAction( RepeatForever::create(effect) ); } std::string Issue631::title() const @@ -297,41 +310,43 @@ std::string Issue631::subtitle() const void EffectAdvanceBaseTest::onEnter() { TestCase::onEnter(); - + _bgNode = NodeGrid::create(); - _bgNode->setAnchorPoint(Vec2(0.5f, 0.5f)); + _bgNode->setAnchorPoint(Vec2(0.5f,0.5f)); addChild(_bgNode); //_bgNode->setPosition( VisibleRect::center() ); auto bg = Sprite::create("Images/background3.png"); - bg->setPosition(VisibleRect::center()); - // addChild(bg, 0, kTagBackground); - // bg->setPosition( VisibleRect::center() ); + bg->setPosition( VisibleRect::center() ); + //addChild(bg, 0, kTagBackground); + //bg->setPosition( VisibleRect::center() ); _bgNode->addChild(bg); _target1 = NodeGrid::create(); - _target1->setAnchorPoint(Vec2(0.5f, 0.5f)); + _target1->setAnchorPoint(Vec2(0.5f,0.5f)); auto grossini = Sprite::create("Images/grossinis_sister2.png"); _target1->addChild(grossini); _bgNode->addChild(_target1); - _target1->setPosition(VisibleRect::left().x + VisibleRect::getVisibleRect().size.width / 3.0f, - VisibleRect::bottom().y + 200); - auto sc = ScaleBy::create(2, 5); + _target1->setPosition(VisibleRect::left().x+VisibleRect::getVisibleRect().size.width/3.0f, VisibleRect::bottom().y+ 200); + auto sc = ScaleBy::create(2, 5); auto sc_back = sc->reverse(); - _target1->runAction(RepeatForever::create(Sequence::create(sc, sc_back, nullptr))); + _target1->runAction( RepeatForever::create(Sequence::create(sc, sc_back, nullptr) ) ); + _target2 = NodeGrid::create(); - _target2->setAnchorPoint(Vec2(0.5f, 0.5f)); + _target2->setAnchorPoint(Vec2(0.5f,0.5f)); auto tamara = Sprite::create("Images/grossinis_sister1.png"); _target2->addChild(tamara); _bgNode->addChild(_target2); - _target2->setPosition(VisibleRect::left().x + 2 * VisibleRect::getVisibleRect().size.width / 3.0f, - VisibleRect::bottom().y + 200); - auto sc2 = ScaleBy::create(2, 5); + _target2->setPosition(VisibleRect::left().x+2*VisibleRect::getVisibleRect().size.width/3.0f,VisibleRect::bottom().y+200); + auto sc2 = ScaleBy::create(2, 5); auto sc2_back = sc2->reverse(); - _target2->runAction(RepeatForever::create(Sequence::create(sc2, sc2_back, nullptr))); + _target2->runAction( RepeatForever::create(Sequence::create(sc2, sc2_back, nullptr) ) ); + } -EffectAdvanceBaseTest::~EffectAdvanceBaseTest() {} +EffectAdvanceBaseTest::~EffectAdvanceBaseTest() +{ +} std::string EffectAdvanceBaseTest::title() const { diff --git a/tests/cpp-tests/Classes/EffectsAdvancedTest/EffectsAdvancedTest.h b/tests/cpp-tests/Classes/EffectsAdvancedTest/EffectsAdvancedTest.h index 3613e22478..da9bcee865 100644 --- a/tests/cpp-tests/Classes/EffectsAdvancedTest/EffectsAdvancedTest.h +++ b/tests/cpp-tests/Classes/EffectsAdvancedTest/EffectsAdvancedTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -30,12 +30,12 @@ DEFINE_TEST_SUITE(EffectAdvanceTests); -class EffectAdvanceBaseTest : public TestCase +class EffectAdvanceBaseTest: public TestCase { protected: cocos2d::TextureAtlas* _atlas; - std::string _title; + std::string _title; cocos2d::Node* _bgNode; cocos2d::Node* _target1; diff --git a/tests/cpp-tests/Classes/EffectsTest/EffectsTest.cpp b/tests/cpp-tests/Classes/EffectsTest/EffectsTest.cpp index de2b32641c..6963dde531 100644 --- a/tests/cpp-tests/Classes/EffectsTest/EffectsTest.cpp +++ b/tests/cpp-tests/Classes/EffectsTest/EffectsTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -50,250 +50,250 @@ EffectTests::EffectTests() ADD_TEST_CASE(JumpTiles3DDemo); ADD_TEST_CASE(SplitRowsDemo); ADD_TEST_CASE(SplitColsDemo); - // ADD_TEST_CASE(PageTurn3DDemo); // TODO crash on iPhone X - // ADD_TEST_CASE(PageTurn3DRectDemo); +// ADD_TEST_CASE(PageTurn3DDemo); // TODO crash on iPhone X +// ADD_TEST_CASE(PageTurn3DRectDemo); } Shaky3DDemo::Shaky3DDemo() { - _title = "Shaky3D"; + _title = "Shaky3D"; _subtitle = ""; } cocos2d::ActionInterval* Shaky3DDemo::createEffect(float t) { - return Shaky3D::create(t, Size(15, 10), 5, false); + return Shaky3D::create(t, Size(15,10), 5, false); } Waves3DDemo::Waves3DDemo() { - _title = "Waves3D"; + _title = "Waves3D"; _subtitle = ""; } cocos2d::ActionInterval* Waves3DDemo::createEffect(float t) { - return Waves3D::create(t, Size(15, 10), 5, 40); + return Waves3D::create(t, Size(15,10), 5, 40); } cocos2d::ActionInterval* FlipX3DDemo::createEffect(float t) { - auto flipx = FlipX3D::create(t); + auto flipx = FlipX3D::create(t); auto flipx_back = flipx->reverse(); - auto delay = DelayTime::create(2); + auto delay = DelayTime::create(2); return Sequence::create(flipx, delay, flipx_back, nullptr); } FlipX3DDemo::FlipX3DDemo() { - _title = "FlipX3D"; + _title = "FlipX3D"; _subtitle = ""; } cocos2d::ActionInterval* FlipY3DDemo::createEffect(float t) { - auto flipy = FlipY3D::create(t); + auto flipy = FlipY3D::create(t); auto flipy_back = flipy->reverse(); - auto delay = DelayTime::create(2); - + auto delay = DelayTime::create(2); + return Sequence::create(flipy, delay, flipy_back, nullptr); } FlipY3DDemo::FlipY3DDemo() { - _title = "FlipY3D"; + _title = "FlipY3D"; _subtitle = ""; } cocos2d::ActionInterval* Lens3DDemo::createEffect(float t) { auto size = Director::getInstance()->getWinSize(); - return Lens3D::create(t, Size(15, 10), Vec2(size.width / 2, size.height / 2), 240); + return Lens3D::create(t, Size(15,10), Vec2(size.width/2,size.height/2), 240); } Lens3DDemo::Lens3DDemo() { - _title = "Lens3D"; + _title = "Lens3D"; _subtitle = ""; } cocos2d::ActionInterval* Ripple3DDemo::createEffect(float t) { auto size = Director::getInstance()->getWinSize(); - return Ripple3D::create(t, Size(32, 24), Vec2(size.width / 2, size.height / 2), 240, 4, 160); + return Ripple3D::create(t, Size(32,24), Vec2(size.width/2,size.height/2), 240, 4, 160); } Ripple3DDemo::Ripple3DDemo() { - _title = "Ripple3D"; + _title = "Ripple3D"; _subtitle = ""; } cocos2d::ActionInterval* LiquidDemo::createEffect(float t) { - return Liquid::create(t, Size(16, 12), 4, 20); + return Liquid::create(t, Size(16,12), 4, 20); } LiquidDemo::LiquidDemo() { - _title = "Liquid"; + _title = "Liquid"; _subtitle = ""; } cocos2d::ActionInterval* WavesDemo::createEffect(float t) { - return Waves::create(t, Size(16, 12), 4, 20, true, true); + return Waves::create(t, Size(16,12), 4, 20, true, true); } WavesDemo::WavesDemo() { - _title = "Waves"; + _title = "Waves"; _subtitle = ""; } cocos2d::ActionInterval* TwirlDemo::createEffect(float t) { auto size = Director::getInstance()->getWinSize(); - return Twirl::create(t, Size(12, 8), Vec2(size.width / 2, size.height / 2), 1, 2.5f); + return Twirl::create(t, Size(12,8), Vec2(size.width/2, size.height/2), 1, 2.5f); } TwirlDemo::TwirlDemo() { - _title = "Twirl"; + _title = "Twirl"; _subtitle = ""; } cocos2d::ActionInterval* ShakyTiles3DDemo::createEffect(float t) { - return ShakyTiles3D::create(t, Size(16, 12), 5, false); + return ShakyTiles3D::create(t, Size(16,12), 5, false) ; } ShakyTiles3DDemo::ShakyTiles3DDemo() { - _title = "ShakyTiles3D"; + _title = "ShakyTiles3D"; _subtitle = ""; } cocos2d::ActionInterval* ShatteredTiles3DDemo::createEffect(float t) { - return ShatteredTiles3D::create(t, Size(16, 12), 5, false); + return ShatteredTiles3D::create(t, Size(16,12), 5, false); } ShatteredTiles3DDemo::ShatteredTiles3DDemo() { - _title = "ShatteredTiles3D"; + _title = "ShatteredTiles3D"; _subtitle = ""; } cocos2d::ActionInterval* ShuffleTilesDemo::createEffect(float t) { - auto shuffle = ShuffleTiles::create(t, Size(16, 12), 25); + auto shuffle = ShuffleTiles::create(t, Size(16,12), 25); auto shuffle_back = shuffle->reverse(); - auto delay = DelayTime::create(2); - + auto delay = DelayTime::create(2); + return Sequence::create(shuffle, delay, shuffle_back, nullptr); } ShuffleTilesDemo::ShuffleTilesDemo() { - _title = "ShuffleTiles"; + _title = "ShuffleTiles"; _subtitle = ""; } cocos2d::ActionInterval* FadeOutTRTilesDemo::createEffect(float t) { - auto fadeout = FadeOutTRTiles::create(t, Size(16, 12)); - auto back = fadeout->reverse(); - auto delay = DelayTime::create(0.5f); - + auto fadeout = FadeOutTRTiles::create(t, Size(16,12)); + auto back = fadeout->reverse(); + auto delay = DelayTime::create(0.5f); + return Sequence::create(fadeout, delay, back, nullptr); } FadeOutTRTilesDemo::FadeOutTRTilesDemo() { - _title = "FadeOutTRTiles"; + _title = "FadeOutTRTiles"; _subtitle = ""; } cocos2d::ActionInterval* FadeOutBLTilesDemo::createEffect(float t) { - auto fadeout = FadeOutBLTiles::create(t, Size(16, 12)); - auto back = fadeout->reverse(); - auto delay = DelayTime::create(0.5f); - + auto fadeout = FadeOutBLTiles::create(t, Size(16,12)); + auto back = fadeout->reverse(); + auto delay = DelayTime::create(0.5f); + return Sequence::create(fadeout, delay, back, nullptr); } FadeOutBLTilesDemo::FadeOutBLTilesDemo() { - _title = "FadeOutBLTiles"; + _title = "FadeOutBLTiles"; _subtitle = ""; } cocos2d::ActionInterval* FadeOutUpTilesDemo::createEffect(float t) { - auto fadeout = FadeOutUpTiles::create(t, Size(16, 12)); - auto back = fadeout->reverse(); - auto delay = DelayTime::create(0.5f); - + auto fadeout = FadeOutUpTiles::create(t, Size(16,12)); + auto back = fadeout->reverse(); + auto delay = DelayTime::create(0.5f); + return Sequence::create(fadeout, delay, back, nullptr); } FadeOutUpTilesDemo::FadeOutUpTilesDemo() { - _title = "FadeOutUpTiles"; + _title = "FadeOutUpTiles"; _subtitle = ""; } cocos2d::ActionInterval* FadeOutDownTilesDemo::createEffect(float t) { - auto fadeout = FadeOutDownTiles::create(t, Size(16, 12)); - auto back = fadeout->reverse(); - auto delay = DelayTime::create(0.5f); - + auto fadeout = FadeOutDownTiles::create(t, Size(16,12)); + auto back = fadeout->reverse(); + auto delay = DelayTime::create(0.5f); + return Sequence::create(fadeout, delay, back, nullptr); } FadeOutDownTilesDemo::FadeOutDownTilesDemo() { - _title = "FadeOutDownTiles"; + _title = "FadeOutDownTiles"; _subtitle = ""; } cocos2d::ActionInterval* TurnOffTilesDemo::createEffect(float t) { - auto fadeout = TurnOffTiles::create(t, Size(48, 32), 25); - auto back = fadeout->reverse(); - auto delay = DelayTime::create(0.5f); - + auto fadeout = TurnOffTiles::create(t, Size(48,32), 25); + auto back = fadeout->reverse(); + auto delay = DelayTime::create(0.5f); + return Sequence::create(fadeout, delay, back, nullptr); } TurnOffTilesDemo::TurnOffTilesDemo() { - _title = "TurnOffTiles"; + _title = "TurnOffTiles"; _subtitle = ""; } cocos2d::ActionInterval* WavesTiles3DDemo::createEffect(float t) { - return WavesTiles3D::create(t, Size(15, 10), 4, 120); + return WavesTiles3D::create(t, Size(15,10), 4, 120); } WavesTiles3DDemo::WavesTiles3DDemo() { - _title = "WavesTiles3D"; + _title = "WavesTiles3D"; _subtitle = ""; } cocos2d::ActionInterval* JumpTiles3DDemo::createEffect(float t) { - return JumpTiles3D::create(t, Size(15, 10), 2, 30); + return JumpTiles3D::create(t, Size(15,10), 2, 30); } JumpTiles3DDemo::JumpTiles3DDemo() { - _title = "JumpTiles3D"; + _title = "JumpTiles3D"; _subtitle = ""; } @@ -304,7 +304,7 @@ cocos2d::ActionInterval* SplitRowsDemo::createEffect(float t) SplitRowsDemo::SplitRowsDemo() { - _title = "SplitRows"; + _title = "SplitRows"; _subtitle = ""; } @@ -315,48 +315,54 @@ cocos2d::ActionInterval* SplitColsDemo::createEffect(float t) SplitColsDemo::SplitColsDemo() { - _title = "SplitCols"; + _title = "SplitCols"; _subtitle = ""; } cocos2d::ActionInterval* PageTurn3DDemo::createEffect(float t) { - return PageTurn3D::create(t, Size(15, 10)); + return PageTurn3D::create(t, Size(15,10)); } PageTurn3DDemo::PageTurn3DDemo() { - _title = "PageTurn3D"; + _title = "PageTurn3D"; _subtitle = ""; } cocos2d::ActionInterval* PageTurn3DRectDemo::createEffect(float t) { - return PageTurn3D::create(t, Size(15, 10)); + return PageTurn3D::create(t, Size(15,10)); } PageTurn3DRectDemo::PageTurn3DRectDemo() { - _title = "PageTurn3D-Rect"; + _title = "PageTurn3D-Rect"; _subtitle = ""; } -#define SID_RESTART 1 +#define SID_RESTART 1 -EffectBaseTest::EffectBaseTest() : _gridNodeTarget(nullptr) {} +EffectBaseTest::EffectBaseTest() +: _gridNodeTarget(nullptr) +{ + +} bool EffectBaseTest::init() { - if (TestCase::init()) + if(TestCase::init()) { - LayerColor* background = LayerColor::create(Color4B(32, 128, 32, 255)); - this->addChild(background, -20); - if (isRectEffect()) + LayerColor *background = LayerColor::create( Color4B(32,128,32,255) ); + this->addChild(background,-20); + if(isRectEffect()) { Size visibleSize = Director::getInstance()->getVisibleSize(); - Rect gridRect = Rect(visibleSize.width * 0.2, visibleSize.height * 0.2, visibleSize.width * 0.6, - visibleSize.height * 0.6); - _gridNodeTarget = NodeGrid::create(gridRect); + Rect gridRect = Rect(visibleSize.width * 0.2, + visibleSize.height * 0.2, + visibleSize.width * 0.6, + visibleSize.height * 0.6); + _gridNodeTarget = NodeGrid::create(gridRect); } else { @@ -364,29 +370,27 @@ bool EffectBaseTest::init() } addChild(_gridNodeTarget, 0); _gridNodeTarget->runAction(createEffect(3)); - + auto bg = Sprite::create(s_back3); _gridNodeTarget->addChild(bg, 0); bg->setPosition(VisibleRect::center()); - + auto grossini = Sprite::create(s_pathSister2); _gridNodeTarget->addChild(grossini, 1); - grossini->setPosition(VisibleRect::left().x + VisibleRect::getVisibleRect().size.width / 3, - VisibleRect::center().y); - auto sc = ScaleBy::create(2, 5); + grossini->setPosition(VisibleRect::left().x+VisibleRect::getVisibleRect().size.width/3,VisibleRect::center().y); + auto sc = ScaleBy::create(2, 5); auto sc_back = sc->reverse(); - grossini->runAction(RepeatForever::create(Sequence::create(sc, sc_back, nullptr))); - + grossini->runAction( RepeatForever::create(Sequence::create(sc, sc_back, nullptr) ) ); + auto tamara = Sprite::create(s_pathSister1); _gridNodeTarget->addChild(tamara, 1); - tamara->setPosition(VisibleRect::left().x + 2 * VisibleRect::getVisibleRect().size.width / 3, - VisibleRect::center().y); - auto sc2 = ScaleBy::create(2, 5); + tamara->setPosition(VisibleRect::left().x+2*VisibleRect::getVisibleRect().size.width/3,VisibleRect::center().y); + auto sc2 = ScaleBy::create(2, 5); auto sc2_back = sc2->reverse(); - tamara->runAction(RepeatForever::create(Sequence::create(sc2, sc2_back, nullptr))); - - schedule(CC_SCHEDULE_SELECTOR(EffectBaseTest::checkAnim)); - + tamara->runAction( RepeatForever::create(Sequence::create(sc2, sc2_back, nullptr)) ); + + schedule( CC_SCHEDULE_SELECTOR(EffectBaseTest::checkAnim) ); + return true; } return false; @@ -394,8 +398,10 @@ bool EffectBaseTest::init() void EffectBaseTest::checkAnim(float dt) { - if (_gridNodeTarget->getNumberOfRunningActions() == 0 && _gridNodeTarget->getGrid() != nullptr) + if ( _gridNodeTarget->getNumberOfRunningActions() == 0 && _gridNodeTarget->getGrid() != nullptr) _gridNodeTarget->setGrid(nullptr); } -EffectBaseTest::~EffectBaseTest() {} +EffectBaseTest::~EffectBaseTest() +{ +} diff --git a/tests/cpp-tests/Classes/EffectsTest/EffectsTest.h b/tests/cpp-tests/Classes/EffectsTest/EffectsTest.h index 7a6bf22a68..3d9e767064 100644 --- a/tests/cpp-tests/Classes/EffectsTest/EffectsTest.h +++ b/tests/cpp-tests/Classes/EffectsTest/EffectsTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,14 +34,13 @@ class EffectBaseTest : public TestCase public: EffectBaseTest(); virtual ~EffectBaseTest(); - protected: virtual bool init() override; - virtual cocos2d::ActionInterval* createEffect(float t) { return nullptr; } + virtual cocos2d::ActionInterval* createEffect(float t) {return nullptr;} void checkAnim(float dt); - virtual bool isRectEffect() { return false; } - virtual std::string title() const override { return _title; }; - virtual std::string subtitle() const override { return _subtitle; }; + virtual bool isRectEffect(){return false;} + virtual std::string title() const override {return _title;}; + virtual std::string subtitle() const override {return _subtitle;}; std::string _title; std::string _subtitle; cocos2d::NodeGrid* _gridNodeTarget; @@ -52,7 +51,6 @@ class Shaky3DDemo : public EffectBaseTest public: CREATE_FUNC(Shaky3DDemo); Shaky3DDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -62,7 +60,6 @@ class Waves3DDemo : public EffectBaseTest public: CREATE_FUNC(Waves3DDemo); Waves3DDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -72,7 +69,6 @@ class FlipX3DDemo : public EffectBaseTest public: CREATE_FUNC(FlipX3DDemo); FlipX3DDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -82,7 +78,6 @@ class FlipY3DDemo : public EffectBaseTest public: CREATE_FUNC(FlipY3DDemo); FlipY3DDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -92,7 +87,6 @@ class Lens3DDemo : public EffectBaseTest public: CREATE_FUNC(Lens3DDemo); Lens3DDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -102,7 +96,6 @@ class Ripple3DDemo : public EffectBaseTest public: CREATE_FUNC(Ripple3DDemo); Ripple3DDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -112,7 +105,6 @@ class LiquidDemo : public EffectBaseTest public: CREATE_FUNC(LiquidDemo); LiquidDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -122,7 +114,6 @@ class WavesDemo : public EffectBaseTest public: CREATE_FUNC(WavesDemo); WavesDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -132,7 +123,6 @@ class TwirlDemo : public EffectBaseTest public: CREATE_FUNC(TwirlDemo); TwirlDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -142,7 +132,6 @@ class ShakyTiles3DDemo : public EffectBaseTest public: CREATE_FUNC(ShakyTiles3DDemo); ShakyTiles3DDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -152,7 +141,6 @@ class ShatteredTiles3DDemo : public EffectBaseTest public: CREATE_FUNC(ShatteredTiles3DDemo); ShatteredTiles3DDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -162,7 +150,6 @@ class ShuffleTilesDemo : public EffectBaseTest public: CREATE_FUNC(ShuffleTilesDemo); ShuffleTilesDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -172,7 +159,6 @@ class FadeOutTRTilesDemo : public EffectBaseTest public: CREATE_FUNC(FadeOutTRTilesDemo); FadeOutTRTilesDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -182,7 +168,6 @@ class FadeOutBLTilesDemo : public EffectBaseTest public: CREATE_FUNC(FadeOutBLTilesDemo); FadeOutBLTilesDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -192,7 +177,6 @@ class FadeOutUpTilesDemo : public EffectBaseTest public: CREATE_FUNC(FadeOutUpTilesDemo); FadeOutUpTilesDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -202,7 +186,6 @@ class FadeOutDownTilesDemo : public EffectBaseTest public: CREATE_FUNC(FadeOutDownTilesDemo); FadeOutDownTilesDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -212,7 +195,6 @@ class TurnOffTilesDemo : public EffectBaseTest public: CREATE_FUNC(TurnOffTilesDemo); TurnOffTilesDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -222,7 +204,6 @@ class WavesTiles3DDemo : public EffectBaseTest public: CREATE_FUNC(WavesTiles3DDemo); WavesTiles3DDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -232,7 +213,6 @@ class JumpTiles3DDemo : public EffectBaseTest public: CREATE_FUNC(JumpTiles3DDemo); JumpTiles3DDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -242,7 +222,6 @@ class SplitRowsDemo : public EffectBaseTest public: CREATE_FUNC(SplitRowsDemo); SplitRowsDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -252,7 +231,6 @@ class SplitColsDemo : public EffectBaseTest public: CREATE_FUNC(SplitColsDemo); SplitColsDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -262,7 +240,6 @@ class PageTurn3DDemo : public EffectBaseTest public: CREATE_FUNC(PageTurn3DDemo); PageTurn3DDemo(); - protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -272,9 +249,8 @@ class PageTurn3DRectDemo : public EffectBaseTest public: CREATE_FUNC(PageTurn3DRectDemo); PageTurn3DRectDemo(); - protected: - virtual bool isRectEffect() override { return true; } + virtual bool isRectEffect() override {return true;} virtual cocos2d::ActionInterval* createEffect(float t) override; }; diff --git a/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.cpp index fd9115ce5e..dc0ddcf967 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -29,18 +29,15 @@ USING_NS_CC; USING_NS_CC_EXT; -const char* sceneManifests[] = {"Manifests/AMTestScene1/project.manifest", "Manifests/AMTestScene2/project.manifest", - "Manifests/AMTestScene3/project.manifest"}; -const char* storagePaths[] = {"CppTests/AssetsManagerExTest/scene1/", "CppTests/AssetsManagerExTest/scene2/", - "CppTests/AssetsManagerExTest/scene3"}; -const char* backgroundPaths[] = {"Images/assetMgrBackground1.jpg", "Images/assetMgrBackground2.png", - "Images/assetMgrBackground3.png"}; +const char* sceneManifests[] = {"Manifests/AMTestScene1/project.manifest", "Manifests/AMTestScene2/project.manifest", "Manifests/AMTestScene3/project.manifest"}; +const char* storagePaths[] = {"CppTests/AssetsManagerExTest/scene1/", "CppTests/AssetsManagerExTest/scene2/", "CppTests/AssetsManagerExTest/scene3"}; +const char* backgroundPaths[] = {"Images/assetMgrBackground1.jpg", "Images/assetMgrBackground2.png", "Images/assetMgrBackground3.png"}; AssetsManagerExTests::AssetsManagerExTests() { - addTestCase("AssetsManager Test1", []() { return AssetsManagerExLoaderScene::create(0); }); - addTestCase("AssetsManager Test2", []() { return AssetsManagerExLoaderScene::create(1); }); - addTestCase("AssetsManager Test3", []() { return AssetsManagerExLoaderScene::create(2); }); + addTestCase("AssetsManager Test1", [](){ return AssetsManagerExLoaderScene::create(0); }); + addTestCase("AssetsManager Test2", [](){ return AssetsManagerExLoaderScene::create(1); }); + addTestCase("AssetsManager Test3", [](){ return AssetsManagerExLoaderScene::create(2); }); } AssetsManagerExLoaderScene* AssetsManagerExLoaderScene::create(int testIndex) @@ -60,13 +57,15 @@ AssetsManagerExLoaderScene* AssetsManagerExLoaderScene::create(int testIndex) } AssetsManagerExLoaderScene::AssetsManagerExLoaderScene(int testIndex) - : _testIndex(testIndex) - , _loadLayer(nullptr) - , _downloadMenu(nullptr) - , _am(nullptr) - , _progress(nullptr) - , _amListener(nullptr) -{} +: _testIndex(testIndex) +, _loadLayer(nullptr) +, _downloadMenu(nullptr) +, _am(nullptr) +, _progress(nullptr) +, _amListener(nullptr) +{ + +} bool AssetsManagerExLoaderScene::init() { @@ -76,8 +75,7 @@ bool AssetsManagerExLoaderScene::init() } auto downloadLabel = Label::createWithTTF("Start Download", "fonts/arial.ttf", 16); - auto downloadItem = - MenuItemLabel::create(downloadLabel, CC_CALLBACK_1(AssetsManagerExLoaderScene::startDownloadCallback, this)); + auto downloadItem = MenuItemLabel::create(downloadLabel, CC_CALLBACK_1(AssetsManagerExLoaderScene::startDownloadCallback, this)); downloadItem->setPosition(Vec2(VisibleRect::center().x, VisibleRect::bottom().y + 100)); _downloadMenu = Menu::create(downloadItem, nullptr); _downloadMenu->setPosition(Vec2::ZERO); @@ -88,15 +86,14 @@ bool AssetsManagerExLoaderScene::init() auto sprite = Sprite::create("Images/Icon.png"); _loadLayer->addChild(sprite); - sprite->setPosition(VisibleRect::center()); - + sprite->setPosition( VisibleRect::center() ); + TTFConfig config("fonts/tahoma.ttf", 30); _progress = Label::createWithTTF(config, "0%", TextHAlignment::CENTER); - _progress->setPosition(Vec2(VisibleRect::center().x, VisibleRect::center().y + 50)); + _progress->setPosition( Vec2(VisibleRect::center().x, VisibleRect::center().y + 50) ); _loadLayer->addChild(_progress); - - std::string manifestPath = sceneManifests[_testIndex], - storagePath = FileUtils::getInstance()->getWritablePath() + storagePaths[_testIndex]; + + std::string manifestPath = sceneManifests[_testIndex], storagePath = FileUtils::getInstance()->getWritablePath() + storagePaths[_testIndex]; CCLOG("Storage path for this test : %s", storagePath.c_str()); _am = AssetsManagerEx::create(manifestPath, storagePath); _am->retain(); @@ -126,84 +123,83 @@ void AssetsManagerExLoaderScene::startDownloadCallback(Ref* sender) } else { - _amListener = - cocos2d::extension::EventListenerAssetsManagerEx::create(_am, [this](EventAssetsManagerEx* event) { - static int failCount = 0; - switch (event->getEventCode()) + _amListener = cocos2d::extension::EventListenerAssetsManagerEx::create(_am, [this](EventAssetsManagerEx* event){ + static int failCount = 0; + switch (event->getEventCode()) + { + case EventAssetsManagerEx::EventCode::ERROR_NO_LOCAL_MANIFEST: + { + CCLOG("No local manifest file found, skip assets update."); + this->onLoadEnd(); + } + break; + case EventAssetsManagerEx::EventCode::UPDATE_PROGRESSION: + { + std::string assetId = event->getAssetId(); + float percent = event->getPercent(); + std::string str; + if (assetId == AssetsManagerEx::VERSION_ID) { - case EventAssetsManagerEx::EventCode::ERROR_NO_LOCAL_MANIFEST: - { - CCLOG("No local manifest file found, skip assets update."); - this->onLoadEnd(); + str = StringUtils::format("Version file: %.2f", percent) + "%"; } - break; - case EventAssetsManagerEx::EventCode::UPDATE_PROGRESSION: + else if (assetId == AssetsManagerEx::MANIFEST_ID) { - std::string assetId = event->getAssetId(); - float percent = event->getPercent(); - std::string str; - if (assetId == AssetsManagerEx::VERSION_ID) - { - str = StringUtils::format("Version file: %.2f", percent) + "%"; - } - else if (assetId == AssetsManagerEx::MANIFEST_ID) - { - str = StringUtils::format("Manifest file: %.2f", percent) + "%"; - } - else - { - str = StringUtils::format("%.2f", percent) + "%"; - CCLOG("%.2f Percent", percent); - } - if (this->_progress != nullptr) - this->_progress->setString(str); + str = StringUtils::format("Manifest file: %.2f", percent) + "%"; } - break; - case EventAssetsManagerEx::EventCode::ERROR_DOWNLOAD_MANIFEST: - case EventAssetsManagerEx::EventCode::ERROR_PARSE_MANIFEST: + else { - CCLOG("Fail to download manifest file, update skipped."); - this->onLoadEnd(); + str = StringUtils::format("%.2f", percent) + "%"; + CCLOG("%.2f Percent", percent); } - break; - case EventAssetsManagerEx::EventCode::ALREADY_UP_TO_DATE: - case EventAssetsManagerEx::EventCode::UPDATE_FINISHED: - { - CCLOG("Update finished. %s", event->getMessage().c_str()); - this->onLoadEnd(); - } - break; - case EventAssetsManagerEx::EventCode::UPDATE_FAILED: - { - CCLOG("Update failed. %s", event->getMessage().c_str()); + if (this->_progress != nullptr) + this->_progress->setString(str); + } + break; + case EventAssetsManagerEx::EventCode::ERROR_DOWNLOAD_MANIFEST: + case EventAssetsManagerEx::EventCode::ERROR_PARSE_MANIFEST: + { + CCLOG("Fail to download manifest file, update skipped."); + this->onLoadEnd(); + } + break; + case EventAssetsManagerEx::EventCode::ALREADY_UP_TO_DATE: + case EventAssetsManagerEx::EventCode::UPDATE_FINISHED: + { + CCLOG("Update finished. %s", event->getMessage().c_str()); + this->onLoadEnd(); + } + break; + case EventAssetsManagerEx::EventCode::UPDATE_FAILED: + { + CCLOG("Update failed. %s", event->getMessage().c_str()); - failCount++; - if (failCount < 5) - { - _am->downloadFailedAssets(); - } - else - { - CCLOG("Reach maximum fail count, exit update process"); - failCount = 0; - this->onLoadEnd(); - } - } - break; - case EventAssetsManagerEx::EventCode::ERROR_UPDATING: + failCount++; + if (failCount < 5) { - CCLOG("Asset %s : %s", event->getAssetId().c_str(), event->getMessage().c_str()); + _am->downloadFailedAssets(); } - break; - case EventAssetsManagerEx::EventCode::ERROR_DECOMPRESS: + else { - CCLOG("%s", event->getMessage().c_str()); + CCLOG("Reach maximum fail count, exit update process"); + failCount = 0; + this->onLoadEnd(); } + } + break; + case EventAssetsManagerEx::EventCode::ERROR_UPDATING: + { + CCLOG("Asset %s : %s", event->getAssetId().c_str(), event->getMessage().c_str()); + } + break; + case EventAssetsManagerEx::EventCode::ERROR_DECOMPRESS: + { + CCLOG("%s", event->getMessage().c_str()); + } + break; + default: break; - default: - break; - } - }); + } + }); Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(_amListener, 1); _am->update(); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.h b/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.h index a3ba81dc89..b817ff9bf8 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -36,14 +36,14 @@ public: static AssetsManagerExLoaderScene* create(int testIndex); AssetsManagerExLoaderScene(int testIndex); - + void startDownloadCallback(cocos2d::Ref* sender); virtual std::string title() const override; virtual bool init() override; virtual void onExit() override; - + private: int _testIndex; cocos2d::Layer* _loadLayer; diff --git a/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.cpp index d30100ae5f..4e8460233b 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -29,6 +29,6 @@ ExtensionsTests::ExtensionsTests() { - addTest("AssetsManagerExTest", []() { return new AssetsManagerExTests; }); - addTest("TableViewTest", []() { return new TableViewTests; }); + addTest("AssetsManagerExTest", [](){ return new AssetsManagerExTests; }); + addTest("TableViewTest", [](){ return new TableViewTests; }); } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.h b/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.h index 665686ae90..2a02f0627f 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 diff --git a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp index 2cdde3fb23..badafef57f 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -26,18 +26,18 @@ USING_NS_CC; -void CustomTableViewCell::draw(Renderer* renderer, const Mat4& transform, uint32_t flags) +void CustomTableViewCell::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) { - TableViewCell::draw(renderer, transform, flags); - // draw bounding box - // auto pos = getPosition(); - // auto size = Size(178, 200); - // Vec2 vertices[4]={ - // Vec2(pos.x+1, pos.y+1), - // Vec2(pos.x+size.width-1, pos.y+1), - // Vec2(pos.x+size.width-1, pos.y+size.height-1), - // Vec2(pos.x+1, pos.y+size.height-1), - // }; - // DrawPrimitives::drawColor4B(0, 0, 255, 255); - // DrawPrimitives::drawPoly(vertices, 4, true); + TableViewCell::draw(renderer, transform, flags); + // draw bounding box +// auto pos = getPosition(); +// auto size = Size(178, 200); +// Vec2 vertices[4]={ +// Vec2(pos.x+1, pos.y+1), +// Vec2(pos.x+size.width-1, pos.y+1), +// Vec2(pos.x+size.width-1, pos.y+size.height-1), +// Vec2(pos.x+1, pos.y+size.height-1), +// }; +// DrawPrimitives::drawColor4B(0, 0, 255, 255); +// DrawPrimitives::drawPoly(vertices, 4, true); } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.h b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.h index 60ab09bad9..4fd2f0fe41 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,7 +34,8 @@ class CustomTableViewCell : public cocos2d::extension::TableViewCell { public: - virtual void draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, uint32_t flags) override; + virtual void draw(cocos2d::Renderer *renderer, const cocos2d::Mat4 &transform, uint32_t flags) override; }; #endif /* __CUSTOMTABELVIEWCELL_H__ */ + diff --git a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp index 249c4fa07f..e496b77359 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -37,16 +37,16 @@ TableViewTests::TableViewTests() // on "init" you need to initialize your instance bool TableViewTest::init() { - if (!TestCase::init()) + if ( !TestCase::init() ) { return false; } - Size winSize = Director::getInstance()->getWinSize(); + Size winSize = Director::getInstance()->getWinSize(); TableView* tableView = TableView::create(this, Size(250.0f, 60.0f)); tableView->setDirection(ScrollView::Direction::HORIZONTAL); - tableView->setPosition(Vec2(20.0f, winSize.height / 2 - 30)); + tableView->setPosition(Vec2(20.0f,winSize.height/2-30)); tableView->setDelegate(this); this->addChild(tableView); tableView->reloadData(); @@ -57,13 +57,14 @@ bool TableViewTest::init() tableView->removeChild(testNode, true); CCAssert(nullptr == tableView->getChildByName("testNode"), "The added child has been removed!"); - tableView = TableView::create(this, Size(60.0f, 250.0f)); - tableView->setDirection(ScrollView::Direction::VERTICAL); - tableView->setPosition(Vec2(winSize.width - 150, winSize.height / 2 - 120)); - tableView->setDelegate(this); - tableView->setVerticalFillOrder(TableView::VerticalFillOrder::TOP_DOWN); - this->addChild(tableView); - tableView->reloadData(); + + tableView = TableView::create(this, Size(60.0f, 250.0f)); + tableView->setDirection(ScrollView::Direction::VERTICAL); + tableView->setPosition(Vec2(winSize.width-150,winSize.height/2-120)); + tableView->setDelegate(this); + tableView->setVerticalFillOrder(TableView::VerticalFillOrder::TOP_DOWN); + this->addChild(tableView); + tableView->reloadData(); return true; } @@ -73,21 +74,19 @@ void TableViewTest::tableCellTouched(TableView* table, TableViewCell* cell) CCLOG("cell touched at index: %d", static_cast(cell->getIdx())); } -Size TableViewTest::tableCellSizeForIndex(TableView* table, ssize_t idx) +Size TableViewTest::tableCellSizeForIndex(TableView *table, ssize_t idx) { - if (idx == 2) - { + if (idx == 2) { return Size(100, 100); } return Size(60, 60); } -TableViewCell* TableViewTest::tableCellAtIndex(TableView* table, ssize_t idx) +TableViewCell* TableViewTest::tableCellAtIndex(TableView *table, ssize_t idx) { - auto string = StringUtils::format("%d", static_cast(idx)); - TableViewCell* cell = table->dequeueCell(); - if (!cell) - { + auto string = StringUtils::format("%d", static_cast(idx)); + TableViewCell *cell = table->dequeueCell(); + if (!cell) { cell = new CustomTableViewCell(); cell->autorelease(); auto sprite = Sprite::create("Images/Icon.png"); @@ -97,7 +96,7 @@ TableViewCell* TableViewTest::tableCellAtIndex(TableView* table, ssize_t idx) auto label = Label::createWithSystemFont(string, "Helvetica", 20.0); label->setPosition(Vec2::ZERO); - label->setAnchorPoint(Vec2::ZERO); + label->setAnchorPoint(Vec2::ZERO); label->setTag(123); cell->addChild(label); } @@ -107,10 +106,11 @@ TableViewCell* TableViewTest::tableCellAtIndex(TableView* table, ssize_t idx) label->setString(string); } + return cell; } -ssize_t TableViewTest::numberOfCellsInTableView(TableView* table) +ssize_t TableViewTest::numberOfCellsInTableView(TableView *table) { return 20; } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h index a439f924db..f01df050cc 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -31,23 +31,19 @@ DEFINE_TEST_SUITE(TableViewTests); -class TableViewTest : public TestCase, - public cocos2d::extension::TableViewDataSource, - public cocos2d::extension::TableViewDelegate +class TableViewTest : public TestCase, public cocos2d::extension::TableViewDataSource, public cocos2d::extension::TableViewDelegate { public: CREATE_FUNC(TableViewTest); - virtual bool init() override; - - virtual void scrollViewDidScroll(cocos2d::extension::ScrollView* view) override{}; - virtual void scrollViewDidZoom(cocos2d::extension::ScrollView* view) override {} - virtual void tableCellTouched(cocos2d::extension::TableView* table, - cocos2d::extension::TableViewCell* cell) override; - virtual cocos2d::Size tableCellSizeForIndex(cocos2d::extension::TableView* table, ssize_t idx) override; - virtual cocos2d::extension::TableViewCell* tableCellAtIndex(cocos2d::extension::TableView* table, - ssize_t idx) override; - virtual ssize_t numberOfCellsInTableView(cocos2d::extension::TableView* table) override; + virtual bool init() override; + + virtual void scrollViewDidScroll(cocos2d::extension::ScrollView* view)override {}; + virtual void scrollViewDidZoom(cocos2d::extension::ScrollView* view)override {} + virtual void tableCellTouched(cocos2d::extension::TableView* table, cocos2d::extension::TableViewCell* cell)override; + virtual cocos2d::Size tableCellSizeForIndex(cocos2d::extension::TableView *table, ssize_t idx)override; + virtual cocos2d::extension::TableViewCell* tableCellAtIndex(cocos2d::extension::TableView *table, ssize_t idx)override; + virtual ssize_t numberOfCellsInTableView(cocos2d::extension::TableView *table)override; }; -#endif // __TABLEVIEWTESTSCENE_H__ +#endif // __TABLEVIEWTESTSCENE_H__ diff --git a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp index 4a8d50b819..831a1e2cdc 100644 --- a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp +++ b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -60,27 +60,26 @@ void TestResolutionDirectories::onEnter() std::string ret; sharedFileUtils->purgeCachedEntries(); - _defaultSearchPathArray = sharedFileUtils->getOriginalSearchPaths(); + _defaultSearchPathArray = sharedFileUtils->getOriginalSearchPaths(); std::vector searchPaths = _defaultSearchPathArray; - searchPaths.insert(searchPaths.begin(), "Misc"); + searchPaths.insert(searchPaths.begin(), "Misc"); sharedFileUtils->setSearchPaths(searchPaths); - _defaultResolutionsOrderArray = sharedFileUtils->getSearchResolutionsOrder(); + _defaultResolutionsOrderArray = sharedFileUtils->getSearchResolutionsOrder(); std::vector resolutionsOrder = _defaultResolutionsOrderArray; resolutionsOrder.insert(resolutionsOrder.begin(), "resources-ipadhd"); - resolutionsOrder.insert(resolutionsOrder.begin() + 1, "resources-ipad"); - resolutionsOrder.insert(resolutionsOrder.begin() + 2, "resources-widehd"); - resolutionsOrder.insert(resolutionsOrder.begin() + 3, "resources-wide"); - resolutionsOrder.insert(resolutionsOrder.begin() + 4, "resources-hd"); - resolutionsOrder.insert(resolutionsOrder.begin() + 5, "resources-iphone"); + resolutionsOrder.insert(resolutionsOrder.begin()+1, "resources-ipad"); + resolutionsOrder.insert(resolutionsOrder.begin()+2, "resources-widehd"); + resolutionsOrder.insert(resolutionsOrder.begin()+3, "resources-wide"); + resolutionsOrder.insert(resolutionsOrder.begin()+4, "resources-hd"); + resolutionsOrder.insert(resolutionsOrder.begin()+5, "resources-iphone"); sharedFileUtils->setSearchResolutionsOrder(resolutionsOrder); - for (int i = 1; i < 7; i++) - { + for( int i=1; i<7; i++) { auto filename = StringUtils::format("test%d.txt", i); - ret = sharedFileUtils->fullPathForFilename(filename); + ret = sharedFileUtils->fullPathForFilename(filename); log("%s -> %s", filename.c_str(), ret.c_str()); } } @@ -115,12 +114,12 @@ void TestSearchPath::onEnter() std::string ret; sharedFileUtils->purgeCachedEntries(); - _defaultSearchPathArray = sharedFileUtils->getOriginalSearchPaths(); + _defaultSearchPathArray = sharedFileUtils->getOriginalSearchPaths(); std::vector searchPaths = _defaultSearchPathArray; - std::string writablePath = sharedFileUtils->getWritablePath(); - std::string fileName = writablePath + "external.txt"; - char szBuf[100] = "Hello Cocos2d-x!"; - FILE* fp = fopen(fileName.c_str(), "wb"); + std::string writablePath = sharedFileUtils->getWritablePath(); + std::string fileName = writablePath+"external.txt"; + char szBuf[100] = "Hello Cocos2d-x!"; + FILE* fp = fopen(fileName.c_str(), "wb"); if (fp) { size_t ret = fwrite(szBuf, 1, strlen(szBuf), fp); @@ -131,20 +130,19 @@ void TestSearchPath::onEnter() } searchPaths.insert(searchPaths.begin(), writablePath); - searchPaths.insert(searchPaths.begin() + 1, "Misc/searchpath1"); - searchPaths.insert(searchPaths.begin() + 2, "Misc/searchpath2"); + searchPaths.insert(searchPaths.begin()+1, "Misc/searchpath1"); + searchPaths.insert(searchPaths.begin()+2, "Misc/searchpath2"); sharedFileUtils->setSearchPaths(searchPaths); - _defaultResolutionsOrderArray = sharedFileUtils->getSearchResolutionsOrder(); + _defaultResolutionsOrderArray = sharedFileUtils->getSearchResolutionsOrder(); std::vector resolutionsOrder = _defaultResolutionsOrderArray; resolutionsOrder.insert(resolutionsOrder.begin(), "resources-ipad"); sharedFileUtils->setSearchResolutionsOrder(resolutionsOrder); - for (int i = 1; i < 3; i++) - { + for( int i=1; i<3; i++) { auto filename = StringUtils::format("file%d.txt", i); - ret = sharedFileUtils->fullPathForFilename(filename); + ret = sharedFileUtils->fullPathForFilename(filename); log("%s -> %s", filename.c_str(), ret.c_str()); } @@ -157,7 +155,7 @@ void TestSearchPath::onEnter() if (fp) { char szReadBuf[100] = {0}; - size_t read = fread(szReadBuf, 1, strlen(szReadBuf), fp); + size_t read = fread(szReadBuf, 1, strlen(szReadBuf), fp); if (read > 0) log("The content of file from writable path: %s", szReadBuf); fclose(fp); @@ -190,7 +188,7 @@ void TestSearchPath::onEnter() void TestSearchPath::onExit() { - FileUtils* sharedFileUtils = FileUtils::getInstance(); + FileUtils *sharedFileUtils = FileUtils::getInstance(); // reset search path sharedFileUtils->setSearchPaths(_defaultSearchPathArray); @@ -227,13 +225,13 @@ void TestFilenameLookup::onEnter() this->addChild(sprite); auto s = Director::getInstance()->getWinSize(); - sprite->setPosition(s.width / 2, s.height / 2); + sprite->setPosition(s.width/2, s.height/2); } void TestFilenameLookup::onExit() { - FileUtils* sharedFileUtils = FileUtils::getInstance(); + FileUtils *sharedFileUtils = FileUtils::getInstance(); // reset filename lookup sharedFileUtils->setFilenameLookupDictionary(ValueMap()); @@ -251,7 +249,7 @@ std::string TestFilenameLookup::title() const void TestIsFileExist::onEnter() { FileUtilsDemo::onEnter(); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto sharedFileUtils = FileUtils::getInstance(); Label* label = nullptr; @@ -259,22 +257,20 @@ void TestIsFileExist::onEnter() isExist = sharedFileUtils->isFileExist("Images/grossini.png"); - label = Label::createWithSystemFont(isExist ? "Images/grossini.png exists" : "Images/grossini.png doesn't exist", - "", 20); - label->setPosition(s.width / 2, s.height / 3); + label = Label::createWithSystemFont(isExist ? "Images/grossini.png exists" : "Images/grossini.png doesn't exist", "", 20); + label->setPosition(s.width/2, s.height/3); this->addChild(label); isExist = sharedFileUtils->isFileExist("Images/grossini.xcf"); - label = Label::createWithSystemFont(isExist ? "Images/grossini.xcf exists" : "Images/grossini.xcf doesn't exist", - "", 20); - label->setPosition(s.width / 2, s.height / 3 * 2); + label = Label::createWithSystemFont(isExist ? "Images/grossini.xcf exists" : "Images/grossini.xcf doesn't exist", "", 20); + label->setPosition(s.width/2, s.height/3*2); this->addChild(label); } void TestIsFileExist::onExit() { - FileUtils* sharedFileUtils = FileUtils::getInstance(); + FileUtils *sharedFileUtils = FileUtils::getInstance(); // reset filename lookup sharedFileUtils->setFilenameLookupDictionary(ValueMap()); @@ -297,29 +293,30 @@ std::string TestIsFileExist::subtitle() const void TestIsDirectoryExist::onEnter() { FileUtilsDemo::onEnter(); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto util = FileUtils::getInstance(); - int x = s.width / 2, y = s.height / 3; + int x = s.width/2, y = s.height/3; Label* label = nullptr; std::string dir; - auto getMsg = [&dir](bool b) -> std::string { + auto getMsg = [&dir](bool b)-> std::string + { char msg[512]; - snprintf((char*)msg, 512, "%s for dir: \"%s\"", b ? "success" : "failed", dir.c_str()); + snprintf((char *)msg, 512, "%s for dir: \"%s\"", b ? "success" : "failed", dir.c_str()); return std::string(msg); }; - dir = "Images"; + dir = "Images"; label = Label::createWithSystemFont(getMsg(util->isDirectoryExist(dir)), "", 20); label->setPosition(x, y * 2); this->addChild(label); - dir = util->getWritablePath(); + dir = util->getWritablePath(); label = Label::createWithSystemFont(getMsg(util->isDirectoryExist(dir)), "", 20); label->setPosition(x, y * 1); this->addChild(label); - dir = util->getWritablePath(); + dir = util->getWritablePath(); label = Label::createWithSystemFont(getMsg(util->isDirectoryExist(dir)), "", 20); label->setPosition(x, y * 1); this->addChild(label); @@ -328,7 +325,7 @@ void TestIsDirectoryExist::onEnter() void TestIsDirectoryExist::onExit() { - FileUtils* sharedFileUtils = FileUtils::getInstance(); + FileUtils *sharedFileUtils = FileUtils::getInstance(); // reset filename lookup sharedFileUtils->purgeCachedEntries(); @@ -351,19 +348,20 @@ std::string TestIsDirectoryExist::subtitle() const void TestFileFuncs::onEnter() { FileUtilsDemo::onEnter(); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto sharedFileUtils = FileUtils::getInstance(); - int x = s.width / 2, y = s.height / 5; + int x = s.width/2, + y = s.height/5; Label* label = nullptr; - std::string filename = "__test.test"; + std::string filename = "__test.test"; std::string filename2 = "__newtest.test"; - std::string filepath = sharedFileUtils->getWritablePath() + filename; - std::string content = "Test string content to put into created file"; + std::string filepath = sharedFileUtils->getWritablePath() + filename; + std::string content = "Test string content to put into created file"; std::string msg; - FILE* out = fopen(filepath.c_str(), "w"); + FILE *out = fopen(filepath.c_str(), "w"); fputs(content.c_str(), out); fclose(out); @@ -376,8 +374,8 @@ void TestFileFuncs::onEnter() // getFileSize Test int32_t size = sharedFileUtils->getFileSize(filepath); - msg = StringUtils::format("getFileSize: Test file size equals %d", size); - label = Label::createWithSystemFont(msg, "", 20); + msg = StringUtils::format("getFileSize: Test file size equals %d", size); + label = Label::createWithSystemFont(msg, "", 20); label->setPosition(x, y * 3); this->addChild(label); @@ -405,8 +403,7 @@ void TestFileFuncs::onEnter() } else { - label = Label::createWithSystemFont( - "renameFile: Failed to rename test file to '__newtest.test', further test skipped", "", 20); + label = Label::createWithSystemFont("renameFile: Failed to rename test file to '__newtest.test', further test skipped", "", 20); label->setPosition(x, y * 2); this->addChild(label); } @@ -434,14 +431,15 @@ std::string TestFileFuncs::subtitle() const void TestDirectoryFuncs::onEnter() { FileUtilsDemo::onEnter(); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto sharedFileUtils = FileUtils::getInstance(); - int x = s.width / 2, y = s.height / 4; + int x = s.width/2, + y = s.height/4; Label* label = nullptr; - std::string dir = sharedFileUtils->getWritablePath() + "__test"; - std::string subDir = "dir1/dir2"; + std::string dir = sharedFileUtils->getWritablePath() + "__test"; + std::string subDir = "dir1/dir2"; std::string fullSubDir = dir + "/" + subDir; std::string msg; bool ok; @@ -450,7 +448,7 @@ void TestDirectoryFuncs::onEnter() ok = sharedFileUtils->createDirectory(dir); if (ok && sharedFileUtils->isDirectoryExist(dir)) { - msg = StringUtils::format("createDirectory: Directory '__test' created"); + msg = StringUtils::format("createDirectory: Directory '__test' created"); label = Label::createWithSystemFont(msg, "", 20); label->setPosition(x, y * 3); this->addChild(label); @@ -459,14 +457,14 @@ void TestDirectoryFuncs::onEnter() ok = sharedFileUtils->createDirectory(fullSubDir); if (ok && sharedFileUtils->isDirectoryExist(fullSubDir)) { - msg = StringUtils::format("createDirectory: Sub directories '%s' created", subDir.c_str()); + msg = StringUtils::format("createDirectory: Sub directories '%s' created", subDir.c_str()); label = Label::createWithSystemFont(msg, "", 20); label->setPosition(x, y * 2); this->addChild(label); } else { - msg = StringUtils::format("createDirectory: Failed to create sub directories '%s'", subDir.c_str()); + msg = StringUtils::format("createDirectory: Failed to create sub directories '%s'", subDir.c_str()); label = Label::createWithSystemFont(msg, "", 20); label->setPosition(x, y * 2); this->addChild(label); @@ -476,14 +474,14 @@ void TestDirectoryFuncs::onEnter() ok = sharedFileUtils->removeDirectory(dir); if (ok && !sharedFileUtils->isDirectoryExist(dir)) { - msg = StringUtils::format("removeDirectory: Directory '__test' removed"); + msg = StringUtils::format("removeDirectory: Directory '__test' removed"); label = Label::createWithSystemFont(msg, "", 20); label->setPosition(x, y); this->addChild(label); } else { - msg = StringUtils::format("removeDirectory: Failed to remove directory '__test'"); + msg = StringUtils::format("removeDirectory: Failed to remove directory '__test'"); label = Label::createWithSystemFont(msg, "", 20); label->setPosition(x, y); this->addChild(label); @@ -491,7 +489,7 @@ void TestDirectoryFuncs::onEnter() } else { - msg = StringUtils::format("createDirectory: Directory '__test' can not be created"); + msg = StringUtils::format("createDirectory: Directory '__test' can not be created"); label = Label::createWithSystemFont(msg, "", 20); label->setPosition(x, y * 2); this->addChild(label); @@ -523,11 +521,11 @@ void TestWriteString::onEnter() readResult->setPosition(winSize.width / 2, winSize.height / 3); std::string writablePath = FileUtils::getInstance()->getWritablePath(); - std::string fileName = "writeStringTest.txt"; + std::string fileName = "writeStringTest.txt"; // writeTest std::string writeDataStr = "the string data will be write into a file"; - std::string fullPath = writablePath + fileName; + std::string fullPath = writablePath + fileName; if (FileUtils::getInstance()->writeStringToFile(writeDataStr, fullPath.c_str())) { log("see the plist file at %s", fullPath.c_str()); @@ -559,34 +557,42 @@ std::string TestWriteString::subtitle() const return ""; } -class CustomBuffer : public ResizableBuffer -{}; +class CustomBuffer : public ResizableBuffer {}; -struct AlreadyExistsBuffer -{}; +struct AlreadyExistsBuffer {}; NS_CC_BEGIN -template <> -class ResizableBufferAdapter : public ResizableBuffer -{ +template<> +class ResizableBufferAdapter : public ResizableBuffer { public: - explicit ResizableBufferAdapter(AlreadyExistsBuffer* buffer) {} - virtual void resize(size_t size) override {} - virtual void* buffer() const override { return nullptr; } + explicit ResizableBufferAdapter(AlreadyExistsBuffer* buffer) { + } + virtual void resize(size_t size) override { + + } + virtual void* buffer() const override { + return nullptr; + } }; NS_CC_END -static void saveAsBinaryText(std::string_view filename, const std::vector& binary) -{ +static void saveAsBinaryText(const std::string& filename, const std::vector& binary){ auto fs = FileUtils::getInstance(); std::string text(binary.begin(), binary.end()); fs->writeStringToFile(text, filename); } static const std::string FileErrors[] = { - "OK", "NotExists", "OpenFailed", "ReadFailed", "NotInitialized", "TooLarge", "ObtainSizeFailed", + "OK", + "NotExists", + "OpenFailed", + "ReadFailed", + "NotInitialized", + "TooLarge", + "ObtainSizeFailed", }; + void TestGetContents::onEnter() { FileUtilsDemo::onEnter(); @@ -606,25 +612,26 @@ void TestGetContents::onEnter() this->addChild(readResult); readResult->setPosition(winSize.width / 2, winSize.height / 2); - std::vector binary = {'\r', '\n', '\r', '\n', '\0', '\0', '\r', '\n'}; - _generatedFile = fs->getWritablePath() + "file-with-zeros-and-crlf"; + std::vector binary = {'\r','\n','\r','\n','\0','\0','\r','\n'}; + _generatedFile = fs->getWritablePath() + "file-with-zeros-and-crlf"; saveAsBinaryText(_generatedFile, binary); + auto runTests = [&]() { // Test read string in binary mode std::string bs; fs->getContents(_generatedFile, &bs); - if (bs.size() != binary.size() || !std::equal(bs.begin(), bs.end(), binary.begin())) + if ( bs.size() != binary.size() || !std::equal( bs.begin(), bs.end(), binary.begin() ) ) return std::string("failed: read as binary string"); // Text read string in text mode std::string ts = fs->getStringFromFile(_generatedFile); - if (strcmp(ts.c_str(), "\r\n\r\n") != 0) + if (strcmp(ts.c_str(), "\r\n\r\n")!=0) return std::string("failed: read as zero terminated string"); + std::string files[] = {_generatedFile, "background.wav", "fileLookup.plist"}; - for (auto& file : files) - { + for (auto& file : files) { std::string sbuf; auto serr = fs->getContents(file, &sbuf); @@ -688,12 +695,12 @@ void TestWriteData::onEnter() readResult->setPosition(winSize.width / 2, winSize.height / 3); std::string writablePath = FileUtils::getInstance()->getWritablePath(); - std::string fileName = "writeDataTest.txt"; + std::string fileName = "writeDataTest.txt"; // writeTest std::string writeDataStr = "the binary data will be write into a file"; Data writeData; - writeData.copy((unsigned char*)writeDataStr.c_str(), writeDataStr.size()); + writeData.copy((unsigned char *)writeDataStr.c_str(), writeDataStr.size()); std::string fullPath = writablePath + fileName; if (FileUtils::getInstance()->writeDataToFile(writeData, fullPath.c_str())) { @@ -708,8 +715,8 @@ void TestWriteData::onEnter() // readTest unsigned char* buffer = nullptr; - Data readData = FileUtils::getInstance()->getDataFromFile(fullPath); - buffer = (unsigned char*)malloc(sizeof(unsigned char) * (readData.getSize() + 1)); + Data readData = FileUtils::getInstance()->getDataFromFile(fullPath); + buffer = (unsigned char*)malloc(sizeof(unsigned char) * (readData.getSize() + 1)); memcpy(buffer, readData.getBytes(), readData.getSize()); buffer[readData.getSize()] = '\0'; std::string readDataStr((const char*)buffer); @@ -753,7 +760,7 @@ void TestWriteValueMap::onEnter() mapInValueMap["string1"] = "string in dictInMap key 0"; mapInValueMap["string2"] = "string in dictInMap key 1"; mapInValueMap["none"].getType(); - + valueMap["data0"] = Value(mapInValueMap); valueMap["data1"] = Value("string in array"); @@ -763,25 +770,26 @@ void TestWriteValueMap::onEnter() arrayInMap.push_back(Value("string 1 in arrayInMap")); valueMap["data2"] = arrayInMap; - // add boolean to the plist + //add boolean to the plist auto booleanObject = Value(true); - valueMap["data3"] = booleanObject; + valueMap["data3"] = booleanObject; - // add integer to the plist - auto intObject = Value(1024); + //add integer to the plist + auto intObject = Value(1024); valueMap["data4"] = intObject; - // add float to the plist - auto floatObject = Value(1024.1024f); + //add float to the plist + auto floatObject = Value(1024.1024f); valueMap["data5"] = floatObject; - // add double to the plist + //add double to the plist auto doubleObject = Value(1024.123); valueMap["data6"] = doubleObject; + // end with / std::string writablePath = FileUtils::getInstance()->getWritablePath(); - std::string fullPath = writablePath + "testWriteValueMap.plist"; + std::string fullPath = writablePath + "testWriteValueMap.plist"; if (FileUtils::getInstance()->writeValueMapToFile(valueMap, fullPath.c_str())) { log("see the plist file at %s", fullPath.c_str()); @@ -793,7 +801,7 @@ void TestWriteValueMap::onEnter() writeResult->setString("write failed"); } - ValueMap readValueMap = FileUtils::getInstance()->getValueMapFromFile(fullPath.c_str()); + ValueMap readValueMap = FileUtils::getInstance()->getValueMapFromFile(fullPath.c_str()); std::string readDataStr = "read data:\n"; // read value map data ValueMap readMapInMap = readValueMap["data0"].asValueMap(); @@ -865,25 +873,26 @@ void TestWriteValueVector::onEnter() arrayInArray.push_back(Value("string 1 in arrayInArray")); array.push_back(Value(arrayInArray)); - // add boolean to the plist + //add boolean to the plist auto booleanObject = Value(true); array.push_back(booleanObject); - // add integer to the plist + //add integer to the plist auto intObject = Value(1024); array.push_back(intObject); - // add float to the plist + //add float to the plist auto floatObject = Value(1024.1024f); array.push_back(floatObject); - // add double to the plist + //add double to the plist auto doubleObject = Value(1024.123); array.push_back(doubleObject); + // end with / std::string writablePath = FileUtils::getInstance()->getWritablePath(); - std::string fullPath = writablePath + "testWriteValueVector.plist"; + std::string fullPath = writablePath + "testWriteValueVector.plist"; if (FileUtils::getInstance()->writeValueVectorToFile(array, fullPath.c_str())) { log("see the plist file at %s", fullPath.c_str()); @@ -895,7 +904,7 @@ void TestWriteValueVector::onEnter() writeResult->setString("write failed"); } - ValueVector readArray = FileUtils::getInstance()->getValueVectorFromFile(fullPath.c_str()); + ValueVector readArray = FileUtils::getInstance()->getValueVectorFromFile(fullPath.c_str()); std::string readDataStr = "read data:\n"; // read value map data ValueMap readMapInArray = readArray.at(0).asValueMap(); @@ -945,19 +954,21 @@ std::string TestWriteValueVector::subtitle() const void TestUnicodePath::onEnter() { FileUtilsDemo::onEnter(); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto util = FileUtils::getInstance(); - int x = s.width / 2, y = s.height / 5; + int x = s.width/2, + y = s.height/5; Label* label = nullptr; - std::string dir = "中文路径/"; + std::string dir = "中文路径/"; std::string filename = "测试文件.test"; std::string act; - auto getMsg = [&act](bool b, std::string_view path) -> std::string { + auto getMsg = [&act](bool b, const std::string& path)-> std::string + { char msg[512]; - snprintf((char*)msg, 512, "%s for %s path: \"%s\"", b ? "success" : "failed", act.c_str(), path.data()); + snprintf((char *)msg, 512, "%s for %s path: \"%s\"", b ? "success" : "failed", act.c_str(), path.c_str()); return std::string(msg); }; @@ -968,9 +979,9 @@ void TestUnicodePath::onEnter() util->createDirectory(dirPath); } - act = "create"; + act = "create"; bool isExist = util->isDirectoryExist(dirPath); - label = Label::createWithSystemFont(getMsg(isExist, dirPath), "", 12, Size(s.width, 0)); + label = Label::createWithSystemFont(getMsg(isExist, dirPath), "", 12, Size(s.width, 0)); label->setPosition(x, y * 4); this->addChild(label); @@ -978,16 +989,16 @@ void TestUnicodePath::onEnter() { // Check whether unicode file should be create or not std::string filePath = dirPath + filename; - if (!util->isFileExist(filePath)) + if (! util->isFileExist(filePath)) { std::string writeDataStr = " 测试字符串."; Data writeData; - writeData.copy((unsigned char*)writeDataStr.c_str(), writeDataStr.size()); + writeData.copy((unsigned char *)writeDataStr.c_str(), writeDataStr.size()); util->writeDataToFile(writeData, filePath); } isExist = util->isFileExist(filePath); - label = Label::createWithSystemFont(getMsg(isExist, filePath), "", 12, Size(s.width, 0)); + label = Label::createWithSystemFont(getMsg(isExist, filePath), "", 12, Size(s.width, 0)); label->setPosition(x, y * 3); this->addChild(label); @@ -996,8 +1007,8 @@ void TestUnicodePath::onEnter() { // read file content and log it unsigned char* buffer = nullptr; - Data readData = util->getDataFromFile(filePath); - buffer = (unsigned char*)malloc(sizeof(unsigned char) * (readData.getSize() + 1)); + Data readData = util->getDataFromFile(filePath); + buffer = (unsigned char*)malloc(sizeof(unsigned char) * (readData.getSize() + 1)); memcpy(buffer, readData.getBytes(), readData.getSize()); buffer[readData.getSize()] = '\0'; // vc can't treat unicode string correctly, don't use unicode string in code @@ -1020,7 +1031,7 @@ void TestUnicodePath::onEnter() void TestUnicodePath::onExit() { - FileUtils* sharedFileUtils = FileUtils::getInstance(); + FileUtils *sharedFileUtils = FileUtils::getInstance(); sharedFileUtils->purgeCachedEntries(); sharedFileUtils->setFilenameLookupDictionary(ValueMap()); FileUtilsDemo::onExit(); @@ -1041,33 +1052,30 @@ std::string TestUnicodePath::subtitle() const void TestIsFileExistAsync::onEnter() { FileUtilsDemo::onEnter(); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto sharedFileUtils = FileUtils::getInstance(); - + sharedFileUtils->isFileExist("Images/grossini.png", [=](bool isExist) { - CCASSERT(std::this_thread::get_id() == Director::getInstance()->getCocos2dThreadId(), - "Callback should be on cocos thread"); - auto label = Label::createWithSystemFont( - isExist ? "Images/grossini.png exists" : "Images/grossini.png doesn't exist", "", 20); - label->setPosition(s.width / 2, s.height / 3); + CCASSERT(std::this_thread::get_id() == Director::getInstance()->getCocos2dThreadId(), "Callback should be on cocos thread"); + auto label = Label::createWithSystemFont(isExist ? "Images/grossini.png exists" : "Images/grossini.png doesn't exist", "", 20); + label->setPosition(s.width/2, s.height/3); this->addChild(label); - + isExist = sharedFileUtils->isFileExist("Images/grossini.xcf"); - label = Label::createWithSystemFont( - isExist ? "Images/grossini.xcf exists" : "Images/grossini.xcf doesn't exist", "", 20); - label->setPosition(s.width / 2, s.height / 3 * 2); + label = Label::createWithSystemFont(isExist ? "Images/grossini.xcf exists" : "Images/grossini.xcf doesn't exist", "", 20); + label->setPosition(s.width/2, s.height/3*2); this->addChild(label); }); } void TestIsFileExistAsync::onExit() { - - FileUtils* sharedFileUtils = FileUtils::getInstance(); - + + FileUtils *sharedFileUtils = FileUtils::getInstance(); + // reset filename lookup sharedFileUtils->setFilenameLookupDictionary(ValueMap()); - + FileUtilsDemo::onExit(); } @@ -1084,17 +1092,18 @@ std::string TestIsFileExistAsync::subtitle() const void TestIsDirectoryExistAsync::onEnter() { FileUtilsDemo::onEnter(); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto util = FileUtils::getInstance(); - int x = s.width / 2, y = s.height / 3; - + int x = s.width/2, y = s.height/3; + std::string dir; - auto getMsg = [](bool b, std::string_view dir) -> std::string { + auto getMsg = [](bool b, const std::string& dir)-> std::string + { char msg[512]; - snprintf((char*)msg, 512, "%s for dir: \"%s\"", b ? "success" : "failed", dir.data()); + snprintf((char *)msg, 512, "%s for dir: \"%s\"", b ? "success" : "failed", dir.c_str()); return std::string(msg); }; - + dir = util->getWritablePath(); util->isDirectoryExist(dir, [=](bool exists) { CCAssert(exists, "Writable path should exist"); @@ -1106,12 +1115,12 @@ void TestIsDirectoryExistAsync::onEnter() void TestIsDirectoryExistAsync::onExit() { - - FileUtils* sharedFileUtils = FileUtils::getInstance(); - + + FileUtils *sharedFileUtils = FileUtils::getInstance(); + // reset filename lookup sharedFileUtils->purgeCachedEntries(); - + FileUtilsDemo::onExit(); } @@ -1128,39 +1137,41 @@ std::string TestIsDirectoryExistAsync::subtitle() const void TestFileFuncsAsync::onEnter() { FileUtilsDemo::onEnter(); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto sharedFileUtils = FileUtils::getInstance(); - - int x = s.width / 2, y = s.height / 5; - - std::string filename = "__test.test"; + + int x = s.width/2, + y = s.height/5; + + std::string filename = "__test.test"; std::string filename2 = "__newtest.test"; - std::string filepath = sharedFileUtils->getWritablePath() + filename; - std::string content = "Test string content to put into created file"; + std::string filepath = sharedFileUtils->getWritablePath() + filename; + std::string content = "Test string content to put into created file"; std::string msg; - - FILE* out = fopen(filepath.c_str(), "w"); + + FILE *out = fopen(filepath.c_str(), "w"); fputs(content.c_str(), out); fclose(out); - + + sharedFileUtils->isFileExist(filepath, [=](bool exists) { CCASSERT(exists, "File could not be found"); auto label = Label::createWithSystemFont("Test file '__test.test' created", "", 20); label->setPosition(x, y * 4); this->addChild(label); - + sharedFileUtils->getFileSize(filepath, [=](int32_t size) { - auto msg = StringUtils::format("getFileSize: Test file size equals %d", size); + auto msg = StringUtils::format("getFileSize: Test file size equals %d", size); auto label = Label::createWithSystemFont(msg, "", 20); label->setPosition(x, y * 3); this->addChild(label); - - sharedFileUtils->renameFile(sharedFileUtils->getWritablePath(), filename, filename2, [=](bool success) { + + sharedFileUtils->renameFile(sharedFileUtils->getWritablePath(), filename, filename2, [=] (bool success) { CCASSERT(success, "Was not able to properly rename file"); auto label = Label::createWithSystemFont("renameFile: Test file renamed to '__newtest.test'", "", 20); label->setPosition(x, y * 2); this->addChild(label); - + sharedFileUtils->removeFile(sharedFileUtils->getWritablePath() + filename2, [=](bool success) { CCASSERT(success, "Was not able to remove file"); auto label = Label::createWithSystemFont("removeFile: Test file removed", "", 20); @@ -1169,6 +1180,7 @@ void TestFileFuncsAsync::onEnter() }); }); }); + }); } @@ -1185,33 +1197,32 @@ std::string TestFileFuncsAsync::subtitle() const void TestWriteStringAsync::onEnter() { FileUtilsDemo::onEnter(); - + auto winSize = Director::getInstance()->getWinSize(); - + auto writeResult = Label::createWithTTF("show writeResult", "fonts/Thonburi.ttf", 18); this->addChild(writeResult); writeResult->setPosition(winSize.width / 2, winSize.height * 3 / 4); - + auto readResult = Label::createWithTTF("show readResult", "fonts/Thonburi.ttf", 18); this->addChild(readResult); readResult->setPosition(winSize.width / 2, winSize.height / 3); - + std::string writablePath = FileUtils::getInstance()->getWritablePath(); - std::string fileName = "writeStringTest.txt"; - + std::string fileName = "writeStringTest.txt"; + // writeTest std::string writeDataStr = "the string data will be write into a file"; - std::string fullPath = writablePath + fileName; - - FileUtils::getInstance()->writeStringToFile(writeDataStr, fullPath, [=](bool success) { + std::string fullPath = writablePath + fileName; + + FileUtils::getInstance()->writeStringToFile(writeDataStr, fullPath, [=](bool success) + { CCASSERT(success, "Write String to data failed"); writeResult->setString("write success:" + writeDataStr); - FileUtils::getInstance()->getStringFromFile(fullPath, [=](std::string_view value) { + FileUtils::getInstance()->getStringFromFile(fullPath, [=](const std::string& value) { CCASSERT(!value.empty(), "String should be readable"); - - std::string strVal = "read success: "; - readResult->setString(strVal.append(value)); + readResult->setString("read success: " + value); }); }); } @@ -1246,24 +1257,25 @@ void TestWriteDataAsync::onEnter() readResult->setPosition(winSize.width / 2, winSize.height / 3); std::string writablePath = FileUtils::getInstance()->getWritablePath(); - std::string fileName = "writeDataTest.txt"; + std::string fileName = "writeDataTest.txt"; // writeTest std::string writeDataStr = "the binary data will be write into a file"; Data writeData; - writeData.copy((unsigned char*)writeDataStr.c_str(), writeDataStr.size()); + writeData.copy((unsigned char *)writeDataStr.c_str(), writeDataStr.size()); std::string fullPath = writablePath + fileName; + FileUtils::getInstance()->writeDataToFile(writeData, fullPath, [=](bool success) { if (success) { writeResult->setString("Write result success"); - } + } else { writeResult->setString("Write result failure"); } - + FileUtils::getInstance()->getDataFromFile(fullPath, [=](const Data& readData) { auto buffer = (unsigned char*)malloc(sizeof(unsigned char) * (readData.getSize() + 1)); memcpy(buffer, readData.getBytes(), readData.getSize()); @@ -1306,23 +1318,24 @@ void TestListFiles::onEnter() cntLabel->setPosition(winSize.width / 2, winSize.height / 3); // writeTest std::vector listFonts = FileUtils::getInstance()->listFiles("fonts"); - auto defaultPath = FileUtils::getInstance()->getDefaultResourceRootPath(); - std::vector list = FileUtils::getInstance()->listFiles(defaultPath); + auto defaultPath = FileUtils::getInstance()->getDefaultResourceRootPath(); + std::vector list = FileUtils::getInstance()->listFiles (defaultPath); - char cntBuffer[200] = {0}; - snprintf(cntBuffer, 200, "'fonts/' %zu, $defaultResourceRootPath %zu", listFonts.size(), list.size()); + char cntBuffer[200] = { 0 }; + snprintf(cntBuffer, 200, "'fonts/' %zu, $defaultResourceRootPath %zu",listFonts.size(), list.size()); - for (int i = 0; i < listFonts.size(); i++) + for(int i=0;isetString(cntBuffer); + } void TestListFiles::onExit() @@ -1340,6 +1353,8 @@ std::string TestListFiles::subtitle() const return ""; } + + void TestIsFileExistRejectFolder::onEnter() { FileUtilsDemo::onEnter(); @@ -1353,13 +1368,14 @@ void TestIsFileExistRejectFolder::onEnter() auto cntLabel = Label::createWithTTF("waiting...", "fonts/Thonburi.ttf", 18); this->addChild(cntLabel); cntLabel->setPosition(winSize.width / 2, winSize.height / 3); - - auto exists = FileUtils::getInstance()->isFileExist("NavMesh/maps"); + + auto exists = FileUtils::getInstance()->isFileExist("NavMesh/maps"); auto isDirectory = FileUtils::getInstance()->isDirectoryExist("NavMesh/maps"); - char cntBuffer[200] = {0}; - snprintf(cntBuffer, 200, "isDir: %s, isFile: %s", isDirectory ? "true" : "false", exists ? "true" : "false"); + char cntBuffer[200] = { 0 }; + snprintf(cntBuffer, 200, "isDir: %s, isFile: %s", isDirectory ? "true": "false" , exists ? "true" : "false"); cntLabel->setString(cntBuffer); + } void TestIsFileExistRejectFolder::onExit() diff --git a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.h b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.h index 4187f38aed..ead129feac 100644 --- a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.h +++ b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,6 +27,7 @@ #include "../BaseTest.h" + DEFINE_TEST_SUITE(FileUtilsTests); class FileUtilsDemo : public TestCase @@ -43,7 +44,6 @@ public: virtual void onExit() override; virtual std::string title() const override; virtual std::string subtitle() const override; - private: std::vector _defaultSearchPathArray; std::vector _defaultResolutionsOrderArray; @@ -58,7 +58,6 @@ public: virtual void onExit() override; virtual std::string title() const override; virtual std::string subtitle() const override; - private: std::vector _defaultSearchPathArray; std::vector _defaultResolutionsOrderArray; @@ -136,7 +135,6 @@ public: virtual void onExit() override; virtual std::string title() const override; virtual std::string subtitle() const override; - private: std::string _generatedFile; }; @@ -189,7 +187,7 @@ class TestIsFileExistAsync : public FileUtilsDemo { public: CREATE_FUNC(TestIsFileExistAsync); - + virtual void onEnter() override; virtual void onExit() override; virtual std::string title() const override; @@ -200,7 +198,7 @@ class TestIsDirectoryExistAsync : public FileUtilsDemo { public: CREATE_FUNC(TestIsDirectoryExistAsync); - + virtual void onEnter() override; virtual void onExit() override; virtual std::string title() const override; @@ -211,7 +209,7 @@ class TestFileFuncsAsync : public FileUtilsDemo { public: CREATE_FUNC(TestFileFuncsAsync); - + virtual void onEnter() override; virtual std::string title() const override; virtual std::string subtitle() const override; @@ -221,7 +219,7 @@ class TestDirectoryFuncsAsync : public FileUtilsDemo { public: CREATE_FUNC(TestDirectoryFuncsAsync); - + virtual void onEnter() override; virtual std::string title() const override; virtual std::string subtitle() const override; @@ -231,7 +229,7 @@ class TestWriteStringAsync : public FileUtilsDemo { public: CREATE_FUNC(TestWriteStringAsync); - + virtual void onEnter() override; virtual void onExit() override; virtual std::string title() const override; @@ -242,7 +240,7 @@ class TestWriteDataAsync : public FileUtilsDemo { public: CREATE_FUNC(TestWriteDataAsync); - + virtual void onEnter() override; virtual void onExit() override; virtual std::string title() const override; diff --git a/tests/cpp-tests/Classes/FontTest/FontTest.cpp b/tests/cpp-tests/Classes/FontTest/FontTest.cpp index f47dd7a775..6e131ce06f 100644 --- a/tests/cpp-tests/Classes/FontTest/FontTest.cpp +++ b/tests/cpp-tests/Classes/FontTest/FontTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -29,65 +29,62 @@ USING_NS_CC; -enum -{ +enum { kTagLabel1, kTagLabel2, kTagLabel3, kTagLabel4, - + kTagColor1, kTagColor2, kTagColor3, }; -// you don't need any ifdef anymore -static std::string fontList[] = { - "fonts/A Damn Mess.ttf", "fonts/Abberancy.ttf", "fonts/Abduction.ttf", - "fonts/Paint Boy.ttf", "fonts/Schwarzwald.ttf", "fonts/Scissor Cuts.ttf", +//you don't need any ifdef anymore +static std::string fontList[] = +{ + "fonts/A Damn Mess.ttf", + "fonts/Abberancy.ttf", + "fonts/Abduction.ttf", + "fonts/Paint Boy.ttf", + "fonts/Schwarzwald.ttf", + "fonts/Scissor Cuts.ttf", }; -static int vAlignIdx = 0; -static TextVAlignment verticalAlignment[] = { +static int vAlignIdx = 0; +static TextVAlignment verticalAlignment[] = +{ TextVAlignment::TOP, TextVAlignment::CENTER, TextVAlignment::BOTTOM, }; + FontTests::FontTests() { for (auto& fontFile : fontList) { - addTestCase("FontTests", [&]() { - vAlignIdx = 0; - return FontTest::create(fontFile); - }); + addTestCase("FontTests", [&](){vAlignIdx = 0; return FontTest::create(fontFile); }); } - + for (auto& fontFile : fontList) { - addTestCase("FontTests", [&]() { - vAlignIdx = 1; - return FontTest::create(fontFile); - }); + addTestCase("FontTests", [&](){ vAlignIdx = 1; return FontTest::create(fontFile); }); } - + for (auto& fontFile : fontList) { - addTestCase("FontTests", [&]() { - vAlignIdx = 2; - return FontTest::create(fontFile); - }); + addTestCase("FontTests", [&](){vAlignIdx = 2; return FontTest::create(fontFile); }); } - ADD_TEST_CASE(FontNoReplacementTest); - ADD_TEST_CASE(FontReplacementTest); + ADD_TEST_CASE(FontNoReplacementTest); + ADD_TEST_CASE(FontReplacementTest); } -void FontTest::showFont(std::string_view fontFile) +void FontTest::showFont(const std::string& fontFile) { auto s = Director::getInstance()->getWinSize(); - auto blockSize = Size(s.width / 3, 200); + auto blockSize = Size(s.width/3, 200); float fontSize = 26; removeChildByTag(kTagLabel1, true); @@ -98,36 +95,37 @@ void FontTest::showFont(std::string_view fontFile) removeChildByTag(kTagColor2, true); removeChildByTag(kTagColor3, true); - auto top = Label::createWithSystemFont(fontFile, fontFile, 24); - auto left = Label::createWithSystemFont("alignment left", fontFile, fontSize, blockSize, TextHAlignment::LEFT, - verticalAlignment[vAlignIdx]); - auto center = Label::createWithSystemFont("alignment center", fontFile, fontSize, blockSize, TextHAlignment::CENTER, - verticalAlignment[vAlignIdx]); - auto right = Label::createWithSystemFont("alignment right", fontFile, fontSize, blockSize, TextHAlignment::RIGHT, - verticalAlignment[vAlignIdx]); + auto top = Label::createWithSystemFont(fontFile, fontFile, 24); + auto left = Label::createWithSystemFont("alignment left", fontFile, fontSize, + blockSize, TextHAlignment::LEFT, verticalAlignment[vAlignIdx]); + auto center = Label::createWithSystemFont("alignment center", fontFile, fontSize, + blockSize, TextHAlignment::CENTER, verticalAlignment[vAlignIdx]); + auto right = Label::createWithSystemFont("alignment right", fontFile, fontSize, + blockSize, TextHAlignment::RIGHT, verticalAlignment[vAlignIdx]); - auto leftColor = LayerColor::create(Color4B(100, 100, 100, 255), blockSize.width, blockSize.height); + auto leftColor = LayerColor::create(Color4B(100, 100, 100, 255), blockSize.width, blockSize.height); auto centerColor = LayerColor::create(Color4B(200, 100, 100, 255), blockSize.width, blockSize.height); - auto rightColor = LayerColor::create(Color4B(100, 100, 200, 255), blockSize.width, blockSize.height); + auto rightColor = LayerColor::create(Color4B(100, 100, 200, 255), blockSize.width, blockSize.height); leftColor->setIgnoreAnchorPointForPosition(false); centerColor->setIgnoreAnchorPointForPosition(false); rightColor->setIgnoreAnchorPointForPosition(false); - top->setAnchorPoint(Vec2(0.5, 1)); - left->setAnchorPoint(Vec2(0, 0.5)); - leftColor->setAnchorPoint(Vec2(0, 0.5)); - center->setAnchorPoint(Vec2(0, 0.5)); - centerColor->setAnchorPoint(Vec2(0, 0.5)); - right->setAnchorPoint(Vec2(0, 0.5)); - rightColor->setAnchorPoint(Vec2(0, 0.5)); - top->setPosition(s.width / 2, s.height - 20); - left->setPosition(0, s.height / 2); + top->setAnchorPoint(Vec2(0.5, 1)); + left->setAnchorPoint(Vec2(0,0.5)); + leftColor->setAnchorPoint(Vec2(0,0.5)); + center->setAnchorPoint(Vec2(0,0.5)); + centerColor->setAnchorPoint(Vec2(0,0.5)); + right->setAnchorPoint(Vec2(0,0.5)); + rightColor->setAnchorPoint(Vec2(0,0.5)); + + top->setPosition(s.width/2,s.height-20); + left->setPosition(0,s.height/2); leftColor->setPosition(left->getPosition()); - center->setPosition(blockSize.width, s.height / 2); + center->setPosition(blockSize.width, s.height/2); centerColor->setPosition(center->getPosition()); - right->setPosition(blockSize.width * 2, s.height / 2); + right->setPosition(blockSize.width*2, s.height/2); rightColor->setPosition(right->getPosition()); this->addChild(leftColor, -1, kTagColor1); @@ -146,136 +144,138 @@ std::string FontTest::title() const FontNoReplacementTest* FontNoReplacementTest::create() { - auto ret = new FontNoReplacementTest; - if (ret->init()) - { - ret->autorelease(); - } - else - { - delete ret; - ret = nullptr; - } + auto ret = new FontNoReplacementTest; + if (ret->init()) + { + ret->autorelease(); + } + else + { + delete ret; + ret = nullptr; + } - return ret; + return ret; } FontNoReplacementTest::FontNoReplacementTest() { - _replace = false; + _replace = false; } FontNoReplacementTest::~FontNoReplacementTest() { - // need to clear the caches since we change the lookup dictionary after the application init. - FontAtlasCache::unloadFontAtlasTTF("fonts/A Damn Mess.ttf"); - FontFreeType::releaseFont("fonts/A Damn Mess.ttf"); - FontAtlasCache::unloadFontAtlasTTF("fonts/Abberancy.ttf"); - FontFreeType::releaseFont("fonts/Abberancy.ttf"); - FontAtlasCache::unloadFontAtlasTTF("fonts/Abduction.ttf"); - FontFreeType::releaseFont("fonts/Abduction.ttf"); - FontAtlasCache::unloadFontAtlasTTF("fonts/Schwarzwald.ttf"); - FontFreeType::releaseFont("fonts/Schwarzwald.ttf"); - FileUtils::getInstance()->setFilenameLookupDictionary(ValueMap()); + // need to clear the caches since we change the lookup dictionary after the application init. + FontAtlasCache::unloadFontAtlasTTF("fonts/A Damn Mess.ttf"); + FontFreeType::releaseFont("fonts/A Damn Mess.ttf"); + FontAtlasCache::unloadFontAtlasTTF("fonts/Abberancy.ttf"); + FontFreeType::releaseFont("fonts/Abberancy.ttf"); + FontAtlasCache::unloadFontAtlasTTF("fonts/Abduction.ttf"); + FontFreeType::releaseFont("fonts/Abduction.ttf"); + FontAtlasCache::unloadFontAtlasTTF("fonts/Schwarzwald.ttf"); + FontFreeType::releaseFont("fonts/Schwarzwald.ttf"); + FileUtils::getInstance()->setFilenameLookupDictionary(ValueMap()); } void FontNoReplacementTest::onEnter() { - TestCase::onEnter(); + TestCase::onEnter(); - std::string suffix; - if (_replace) - { - ValueMap dict{{"fonts/A Damn Mess.ttf", Value("fonts/arial.ttf")}, - {"fonts/Abberancy.ttf", Value("fonts/arial.ttf")}, - {"fonts/Abduction.ttf", Value("fonts/arial.ttf")}, - {"fonts/Schwarzwald.ttf", Value("fonts/arial.ttf")}}; + std::string suffix; + if (_replace) + { + ValueMap dict{ + { "fonts/A Damn Mess.ttf", Value("fonts/arial.ttf") }, + { "fonts/Abberancy.ttf", Value("fonts/arial.ttf") }, + { "fonts/Abduction.ttf", Value("fonts/arial.ttf") }, + { "fonts/Schwarzwald.ttf", Value("fonts/arial.ttf") } + }; - FileUtils::getInstance()->setFilenameLookupDictionary(dict); - suffix = " replaced by arial.ttf"; - } + FileUtils::getInstance()->setFilenameLookupDictionary(dict); + suffix = " replaced by arial.ttf"; + } - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); - auto blockSize = Size(s.width / 3, 200); - float fontSize = 26; + auto blockSize = Size(s.width / 3, 200); + float fontSize = 26; - removeChildByTag(kTagLabel1, true); - removeChildByTag(kTagLabel2, true); - removeChildByTag(kTagLabel3, true); - removeChildByTag(kTagLabel4, true); - removeChildByTag(kTagColor1, true); - removeChildByTag(kTagColor2, true); - removeChildByTag(kTagColor3, true); + removeChildByTag(kTagLabel1, true); + removeChildByTag(kTagLabel2, true); + removeChildByTag(kTagLabel3, true); + removeChildByTag(kTagLabel4, true); + removeChildByTag(kTagColor1, true); + removeChildByTag(kTagColor2, true); + removeChildByTag(kTagColor3, true); - auto top = Label::createWithTTF("fonts/A Damn Mess.ttf" + suffix, "fonts/A Damn Mess.ttf", 24); - auto left = Label::createWithTTF("fonts/Abberancy.ttf" + suffix, "fonts/Abberancy.ttf", fontSize, blockSize, - TextHAlignment::LEFT, verticalAlignment[0]); - auto center = Label::createWithTTF("fonts/Abduction.ttf" + suffix, "fonts/Abduction.ttf", fontSize, blockSize, - TextHAlignment::CENTER, verticalAlignment[0]); - auto right = Label::createWithTTF("fonts/Schwarzwald.ttf" + suffix, "fonts/Schwarzwald.ttf", fontSize, blockSize, - TextHAlignment::RIGHT, verticalAlignment[0]); + auto top = Label::createWithTTF("fonts/A Damn Mess.ttf" + suffix, "fonts/A Damn Mess.ttf", 24); + auto left = Label::createWithTTF("fonts/Abberancy.ttf" + suffix, "fonts/Abberancy.ttf", fontSize, + blockSize, TextHAlignment::LEFT, verticalAlignment[0]); + auto center = Label::createWithTTF("fonts/Abduction.ttf" + suffix, "fonts/Abduction.ttf", fontSize, + blockSize, TextHAlignment::CENTER, verticalAlignment[0]); + auto right = Label::createWithTTF("fonts/Schwarzwald.ttf" + suffix, "fonts/Schwarzwald.ttf", fontSize, + blockSize, TextHAlignment::RIGHT, verticalAlignment[0]); - auto leftColor = LayerColor::create(Color4B(100, 100, 100, 255), blockSize.width, blockSize.height); - auto centerColor = LayerColor::create(Color4B(200, 100, 100, 255), blockSize.width, blockSize.height); - auto rightColor = LayerColor::create(Color4B(100, 100, 200, 255), blockSize.width, blockSize.height); + auto leftColor = LayerColor::create(Color4B(100, 100, 100, 255), blockSize.width, blockSize.height); + auto centerColor = LayerColor::create(Color4B(200, 100, 100, 255), blockSize.width, blockSize.height); + auto rightColor = LayerColor::create(Color4B(100, 100, 200, 255), blockSize.width, blockSize.height); - leftColor->setIgnoreAnchorPointForPosition(false); - centerColor->setIgnoreAnchorPointForPosition(false); - rightColor->setIgnoreAnchorPointForPosition(false); + leftColor->setIgnoreAnchorPointForPosition(false); + centerColor->setIgnoreAnchorPointForPosition(false); + rightColor->setIgnoreAnchorPointForPosition(false); - top->setAnchorPoint(Vec2(0.5, 1)); - left->setAnchorPoint(Vec2(0, 0.5)); - leftColor->setAnchorPoint(Vec2(0, 0.5)); - center->setAnchorPoint(Vec2(0, 0.5)); - centerColor->setAnchorPoint(Vec2(0, 0.5)); - right->setAnchorPoint(Vec2(0, 0.5)); - rightColor->setAnchorPoint(Vec2(0, 0.5)); + top->setAnchorPoint(Vec2(0.5, 1)); + left->setAnchorPoint(Vec2(0, 0.5)); + leftColor->setAnchorPoint(Vec2(0, 0.5)); + center->setAnchorPoint(Vec2(0, 0.5)); + centerColor->setAnchorPoint(Vec2(0, 0.5)); + right->setAnchorPoint(Vec2(0, 0.5)); + rightColor->setAnchorPoint(Vec2(0, 0.5)); - top->setPosition(s.width / 2, s.height - 20); - left->setPosition(0, s.height / 2); - leftColor->setPosition(left->getPosition()); - center->setPosition(blockSize.width, s.height / 2); - centerColor->setPosition(center->getPosition()); - right->setPosition(blockSize.width * 2, s.height / 2); - rightColor->setPosition(right->getPosition()); + top->setPosition(s.width / 2, s.height - 20); + left->setPosition(0, s.height / 2); + leftColor->setPosition(left->getPosition()); + center->setPosition(blockSize.width, s.height / 2); + centerColor->setPosition(center->getPosition()); + right->setPosition(blockSize.width * 2, s.height / 2); + rightColor->setPosition(right->getPosition()); - this->addChild(leftColor, -1, kTagColor1); - this->addChild(left, 0, kTagLabel1); - this->addChild(rightColor, -1, kTagColor2); - this->addChild(right, 0, kTagLabel2); - this->addChild(centerColor, -1, kTagColor3); - this->addChild(center, 0, kTagLabel3); - this->addChild(top, 0, kTagLabel4); + this->addChild(leftColor, -1, kTagColor1); + this->addChild(left, 0, kTagLabel1); + this->addChild(rightColor, -1, kTagColor2); + this->addChild(right, 0, kTagLabel2); + this->addChild(centerColor, -1, kTagColor3); + this->addChild(center, 0, kTagLabel3); + this->addChild(top, 0, kTagLabel4); } std::string FontNoReplacementTest::title() const { - return "Font no replacement test"; + return "Font no replacement test"; } FontReplacementTest* FontReplacementTest::create() { - auto ret = new FontReplacementTest; - if (ret->init()) - { - ret->autorelease(); - } - else - { - delete ret; - ret = nullptr; - } + auto ret = new FontReplacementTest; + if (ret->init()) + { + ret->autorelease(); + } + else + { + delete ret; + ret = nullptr; + } - return ret; + return ret; } FontReplacementTest::FontReplacementTest() { - _replace = true; + _replace = true; } std::string FontReplacementTest::title() const { - return "Font replacement test"; + return "Font replacement test"; } diff --git a/tests/cpp-tests/Classes/FontTest/FontTest.h b/tests/cpp-tests/Classes/FontTest/FontTest.h index d7dc5a5b33..2659dd5a15 100644 --- a/tests/cpp-tests/Classes/FontTest/FontTest.h +++ b/tests/cpp-tests/Classes/FontTest/FontTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,7 +33,7 @@ DEFINE_TEST_SUITE(FontTests); class FontTest : public TestCase { public: - static FontTest* create(std::string_view fontFile) + static FontTest* create(const std::string& fontFile) { auto ret = new FontTest; if (ret->init()) @@ -50,7 +50,7 @@ public: return ret; } - void showFont(std::string_view fontFile); + void showFont(const std::string& fontFile); virtual std::string title() const override; }; @@ -58,25 +58,23 @@ public: class FontNoReplacementTest : public TestCase { public: - static FontNoReplacementTest* create(); - ~FontNoReplacementTest(); - virtual void onEnter() override; - virtual std::string title() const override; - + static FontNoReplacementTest* create(); + ~FontNoReplacementTest(); + virtual void onEnter() override; + virtual std::string title() const override; protected: - FontNoReplacementTest(); + FontNoReplacementTest(); - bool _replace; + bool _replace; }; class FontReplacementTest : public FontNoReplacementTest { public: - static FontReplacementTest* create(); - virtual std::string title() const override; - + static FontReplacementTest* create(); + virtual std::string title() const override; protected: - FontReplacementTest(); + FontReplacementTest(); }; -#endif // _FONT_TEST_H_ +#endif // _FONT_TEST_H_ diff --git a/tests/cpp-tests/Classes/ImGuiEXTTest/ImGuiEXTTest.cpp b/tests/cpp-tests/Classes/ImGuiEXTTest/ImGuiEXTTest.cpp index 575a3d3552..cbf141f585 100644 --- a/tests/cpp-tests/Classes/ImGuiEXTTest/ImGuiEXTTest.cpp +++ b/tests/cpp-tests/Classes/ImGuiEXTTest/ImGuiEXTTest.cpp @@ -8,15 +8,15 @@ USING_NS_CC_EXT; #if defined(CC_PLATFORM_PC) -static bool show_test_window = true; +static bool show_test_window = true; static bool show_another_window = true; -static ImVec4 clear_color = ImColor(114, 144, 154); +static ImVec4 clear_color = ImColor(114, 144, 154); ImGuiEXTTests::ImGuiEXTTests() { - // Resize (expand) window + // Resize (expand) window static Size resourceSize(1280, 720); - auto director = Director::getInstance(); + auto director = Director::getInstance(); GLViewImpl* view = (GLViewImpl*)Director::getInstance()->getOpenGLView(); view->setWindowed(resourceSize.width, resourceSize.height); @@ -50,12 +50,9 @@ void ImGuiEXTTest::onDrawImGui() ImGui::Text("Hello, world!"); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ImGui::ColorEdit3("clear color", (float*)&clear_color); - if (ImGui::Button("Test Window")) - show_test_window ^= 1; - if (ImGui::Button("Another Window")) - show_another_window ^= 1; - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, - ImGui::GetIO().Framerate); + if (ImGui::Button("Test Window")) show_test_window ^= 1; + if (ImGui::Button("Another Window")) show_another_window ^= 1; + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); } // 2. Show another simple window, this time using an explicit Begin/End pair diff --git a/tests/cpp-tests/Classes/ImGuiEXTTest/ImGuiEXTTest.h b/tests/cpp-tests/Classes/ImGuiEXTTest/ImGuiEXTTest.h index e55ff3821b..c3c60ca57f 100644 --- a/tests/cpp-tests/Classes/ImGuiEXTTest/ImGuiEXTTest.h +++ b/tests/cpp-tests/Classes/ImGuiEXTTest/ImGuiEXTTest.h @@ -47,4 +47,4 @@ public: #endif -#endif // _CURL_TEST_H_ +#endif // _CURL_TEST_H_ diff --git a/tests/cpp-tests/Classes/InputTest/MouseTest.cpp b/tests/cpp-tests/Classes/InputTest/MouseTest.cpp index c39e1da6fd..c810030515 100644 --- a/tests/cpp-tests/Classes/InputTest/MouseTest.cpp +++ b/tests/cpp-tests/Classes/InputTest/MouseTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -26,13 +26,7 @@ USING_NS_CC; -template -std::string tostr(const T& t) -{ - std::ostringstream os; - os << t; - return os.str(); -} +template std::string tostr(const T& t) { std::ostringstream os; os<getWinSize(); - // Create a label to display the mouse action + //Create a label to display the mouse action _labelAction = Label::createWithTTF("Click mouse button and see this change", "fonts/arial.ttf", 22); - _labelAction->setPosition(Vec2(s.width / 2, s.height * 2 / 3)); + _labelAction->setPosition(Vec2(s.width/2, s.height*2/3)); addChild(_labelAction, 0); - // Create a label to display the mouse position + //Create a label to display the mouse position _labelPosition = Label::createWithTTF("Mouse not supported on this device", "fonts/arial.ttf", 22); - _labelPosition->setPosition(Vec2(s.width / 2, s.height / 3)); + _labelPosition->setPosition(Vec2(s.width/2, s.height/3)); addChild(_labelPosition); - _mouseListener = EventListenerMouse::create(); - _mouseListener->onMouseMove = CC_CALLBACK_1(MouseEventTest::onMouseMove, this); - _mouseListener->onMouseUp = CC_CALLBACK_1(MouseEventTest::onMouseUp, this); - _mouseListener->onMouseDown = CC_CALLBACK_1(MouseEventTest::onMouseDown, this); + + _mouseListener = EventListenerMouse::create(); + _mouseListener->onMouseMove = CC_CALLBACK_1(MouseEventTest::onMouseMove, this); + _mouseListener->onMouseUp = CC_CALLBACK_1(MouseEventTest::onMouseUp, this); + _mouseListener->onMouseDown = CC_CALLBACK_1(MouseEventTest::onMouseDown, this); _mouseListener->onMouseScroll = CC_CALLBACK_1(MouseEventTest::onMouseScroll, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(_mouseListener, this); @@ -73,35 +68,35 @@ MouseEventTest::~MouseEventTest() _eventDispatcher->removeEventListener(_mouseListener); } -void MouseEventTest::onMouseDown(Event* event) +void MouseEventTest::onMouseDown(Event *event) { - EventMouse* e = (EventMouse*)event; + EventMouse* e = (EventMouse*)event; std::string str = "Mouse Down detected, Key: "; str += tostr(static_cast(e->getMouseButton())); _labelAction->setString(str.c_str()); } -void MouseEventTest::onMouseUp(Event* event) +void MouseEventTest::onMouseUp(Event *event) { - EventMouse* e = (EventMouse*)event; + EventMouse* e = (EventMouse*)event; std::string str = "Mouse Up detected, Key: "; str += tostr(static_cast(e->getMouseButton())); _labelAction->setString(str.c_str()); } -void MouseEventTest::onMouseMove(Event* event) +void MouseEventTest::onMouseMove(Event *event) { - EventMouse* e = (EventMouse*)event; + EventMouse* e = (EventMouse*)event; std::string str = "MousePosition X:"; - str = str + tostr(e->getCursorX()) + " Y:" + tostr(e->getCursorY()); + str = str + tostr(e->getCursorX()) + " Y:" + tostr(e->getCursorY()); _labelPosition->setString(str.c_str()); } -void MouseEventTest::onMouseScroll(Event* event) +void MouseEventTest::onMouseScroll(Event *event) { - EventMouse* e = (EventMouse*)event; + EventMouse* e = (EventMouse*)event; std::string str = "Mouse Scroll detected, X: "; - str = str + tostr(e->getScrollX()) + " Y: " + tostr(e->getScrollY()); + str = str + tostr(e->getScrollX()) + " Y: " + tostr(e->getScrollY()); _labelAction->setString(str.c_str()); } @@ -123,12 +118,16 @@ std::string MouseEventTest::subtitle() const HideMouseTest::HideMouseTest() { - - _lis = EventListenerMouse::create(); - _lis->onMouseDown = [](Event* e) { Director::getInstance()->getOpenGLView()->setCursorVisible(false); }; - - _lis->onMouseUp = [](Event* e) { Director::getInstance()->getOpenGLView()->setCursorVisible(true); }; - + + _lis = EventListenerMouse::create(); + _lis->onMouseDown = [](Event* e){ + Director::getInstance()->getOpenGLView()->setCursorVisible(false); + }; + + _lis->onMouseUp = [](Event* e){ + Director::getInstance()->getOpenGLView()->setCursorVisible(true); + }; + _eventDispatcher->addEventListenerWithSceneGraphPriority(_lis, this); } @@ -146,3 +145,4 @@ std::string HideMouseTest::subtitle() const { return "Click to hide mouse"; } + diff --git a/tests/cpp-tests/Classes/InputTest/MouseTest.h b/tests/cpp-tests/Classes/InputTest/MouseTest.h index dd8be001f8..cc2162dad8 100644 --- a/tests/cpp-tests/Classes/InputTest/MouseTest.h +++ b/tests/cpp-tests/Classes/InputTest/MouseTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,6 +33,7 @@ DEFINE_TEST_SUITE(MouseTests); class BaseMouseTest : public TestCase { public: + }; class MouseEventTest : public BaseMouseTest @@ -46,13 +47,13 @@ public: void onMouseUp(cocos2d::Event* event); void onMouseMove(cocos2d::Event* event); void onMouseScroll(cocos2d::Event* event); - + virtual std::string title() const override; virtual std::string subtitle() const override; private: - cocos2d::Label* _labelAction; - cocos2d::Label* _labelPosition; + cocos2d::Label* _labelAction; + cocos2d::Label* _labelPosition; cocos2d::EventListenerMouse* _mouseListener; }; @@ -62,10 +63,10 @@ public: CREATE_FUNC(HideMouseTest); HideMouseTest(); ~HideMouseTest(); - + virtual std::string title() const override; virtual std::string subtitle() const override; - + private: cocos2d::EventListenerMouse* _lis; }; diff --git a/tests/cpp-tests/Classes/IntervalTest/IntervalTest.cpp b/tests/cpp-tests/Classes/IntervalTest/IntervalTest.cpp index 16398102fe..a998e7edeb 100644 --- a/tests/cpp-tests/Classes/IntervalTest/IntervalTest.cpp +++ b/tests/cpp-tests/Classes/IntervalTest/IntervalTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,11 +27,11 @@ USING_NS_CC; -#define SID_STEP1 100 -#define SID_STEP2 101 -#define SID_STEP3 102 +#define SID_STEP1 100 +#define SID_STEP2 101 +#define SID_STEP3 102 -#define IDC_PAUSE 200 +#define IDC_PAUSE 200 IntervalTests::IntervalTests() { @@ -46,7 +46,7 @@ IntervalTest::IntervalTest() // sun auto sun = ParticleSun::create(); sun->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); - sun->setPosition(VisibleRect::rightTop().x - 32, VisibleRect::rightTop().y - 32); + sun->setPosition(VisibleRect::rightTop().x-32,VisibleRect::rightTop().y-32); sun->setTotalParticles(130); sun->setLife(0.6f); @@ -60,51 +60,43 @@ IntervalTest::IntervalTest() _label4 = Label::createWithBMFont("fonts/bitmapFontTest4.fnt", "0"); scheduleUpdate(); - schedule( - [&](float dt) { - _time1 += dt; + schedule([&](float dt){ + _time1 +=dt; - char str[10] = {0}; - sprintf(str, "%2.1f", _time1); - _label1->setString(str); - }, - "step_1"); + char str[10] = {0}; + sprintf(str, "%2.1f", _time1); + _label1->setString( str ); + }, "step_1"); - schedule( - [&](float dt) { - _time2 += dt; + schedule([&](float dt){ + _time2 +=dt; - char str[10] = {0}; - sprintf(str, "%2.1f", _time2); - _label2->setString(str); - }, - 0.5, "step_2"); + char str[10] = {0}; + sprintf(str, "%2.1f", _time2); + _label2->setString( str ); + }, 0.5, "step_2"); - schedule( - [&](float dt) { - _time3 += dt; + schedule([&](float dt){ + _time3 +=dt; - char str[10] = {0}; - sprintf(str, "%2.1f", _time3); - _label3->setString(str); - }, - 1, "step_3"); + char str[10] = {0}; + sprintf(str, "%2.1f", _time3); + _label3->setString( str ); + }, 1, "step_3"); - schedule( - [&](float dt) { - _time4 += dt; + schedule([&](float dt){ + _time4 +=dt; - char str[10] = {0}; - sprintf(str, "%2.1f", _time4); - _label4->setString(str); - }, - 2, "step_4"); + char str[10] = {0}; + sprintf(str, "%2.1f", _time4); + _label4->setString( str ); + }, 2, "step_4"); - _label0->setPosition(s.width * 1 / 6, s.height / 2); - _label1->setPosition(s.width * 2 / 6, s.height / 2); - _label2->setPosition(s.width * 3 / 6, s.height / 2); - _label3->setPosition(s.width * 4 / 6, s.height / 2); - _label4->setPosition(s.width * 5 / 6, s.height / 2); + _label0->setPosition(s.width*1/6, s.height/2); + _label1->setPosition(s.width*2/6, s.height/2); + _label2->setPosition(s.width*3/6, s.height/2); + _label3->setPosition(s.width*4/6, s.height/2); + _label4->setPosition(s.width*5/6, s.height/2); addChild(_label0); addChild(_label1); @@ -115,27 +107,27 @@ IntervalTest::IntervalTest() // Sprite auto sprite = Sprite::create(s_pathGrossini); sprite->setPosition(VisibleRect::left().x + 40, VisibleRect::bottom().y + 50); - - auto jump = JumpBy::create(3, Vec2(s.width - 80, 0.0f), 50, 4); - + + auto jump = JumpBy::create(3, Vec2(s.width-80,0.0f), 50, 4); + addChild(sprite); - sprite->runAction(RepeatForever::create(Sequence::create(jump, jump->reverse(), nullptr))); + sprite->runAction( RepeatForever::create(Sequence::create(jump, jump->reverse(), nullptr) )); // pause button auto item1 = MenuItemFont::create("Pause", [&](Ref* sender) { - if (Director::getInstance()->isPaused()) - Director::getInstance()->resume(); - else - Director::getInstance()->pause(); - }); - auto menu = Menu::create(item1, nullptr); - menu->setPosition(s.width / 2, s.height - 50); + if(Director::getInstance()->isPaused()) + Director::getInstance()->resume(); + else + Director::getInstance()->pause(); + }); + auto menu = Menu::create(item1, nullptr); + menu->setPosition(s.width/2, s.height-50); - addChild(menu); + addChild( menu ); } IntervalTest::~IntervalTest() { - if (Director::getInstance()->isPaused()) + if(Director::getInstance()->isPaused()) { Director::getInstance()->resume(); } @@ -143,7 +135,7 @@ IntervalTest::~IntervalTest() void IntervalTest::update(float dt) { - _time0 += dt; + _time0 +=dt; char time[10] = {0}; sprintf(time, "%2.1f", _time0); _label0->setString(time); diff --git a/tests/cpp-tests/Classes/IntervalTest/IntervalTest.h b/tests/cpp-tests/Classes/IntervalTest/IntervalTest.h index f885358abc..68bd6ca6ae 100644 --- a/tests/cpp-tests/Classes/IntervalTest/IntervalTest.h +++ b/tests/cpp-tests/Classes/IntervalTest/IntervalTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -38,16 +38,16 @@ public: virtual void update(float dt) override; - // CREATE_NODE(IntervalLayer); + //CREATE_NODE(IntervalLayer); protected: - cocos2d::Label* _label0; - cocos2d::Label* _label1; - cocos2d::Label* _label2; - cocos2d::Label* _label3; - cocos2d::Label* _label4; + cocos2d::Label* _label0; + cocos2d::Label* _label1; + cocos2d::Label* _label2; + cocos2d::Label* _label3; + cocos2d::Label* _label4; - float _time0, _time1, _time2, _time3, _time4; + float _time0, _time1, _time2, _time3, _time4; }; #endif diff --git a/tests/cpp-tests/Classes/JNITest/JNITest.cpp b/tests/cpp-tests/Classes/JNITest/JNITest.cpp index feba30d292..d873f93cee 100644 --- a/tests/cpp-tests/Classes/JNITest/JNITest.cpp +++ b/tests/cpp-tests/Classes/JNITest/JNITest.cpp @@ -1,19 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - Copyright (c) 2021 Bytedance inc. - - https://adxeproject.github.io/ - + + 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 @@ -25,11 +24,12 @@ #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) -# include "JNITest.h" +#include "JNITest.h" -# include "platform/android/jni/JniHelper.h" -# include +#include "platform/android/jni/JniHelper.h" + +#include USING_NS_CC; @@ -48,7 +48,7 @@ JNITest::JNITest() checkLabel->setPosition(VisibleRect::center()); addChild(checkLabel); - const char* classPath = "org.cocos2dx.cpp_tests.JNITest"; + const std::string classPath = "org.cocos2dx.cpp_tests.JNITest"; JniHelper::callStaticVoidMethod(classPath, "voidMethod1"); @@ -65,24 +65,23 @@ JNITest::JNITest() CC_ASSERT(i == 20); float f = JniHelper::callStaticFloatMethod(classPath, "floatMethod", float(2.35), float(7.65)); - CC_ASSERT(f == 10.0); - + CC_ASSERT(f == 10.0); + double d = JniHelper::callStaticDoubleMethod(classPath, "doubleMethod", double(2.5), int(4)); - CC_ASSERT(d == 10.0); + CC_ASSERT(d == 10.0); std::string str = "ABCDEF"; - std::string s1 = JniHelper::callStaticStringMethod(classPath, "stringMethod", str, true); + std::string s1 = JniHelper::callStaticStringMethod(classPath, "stringMethod", str, true); CC_ASSERT(s1 == "FEDCBA"); std::string s2 = JniHelper::callStaticStringMethod(classPath, "stringMethod", str, false); CC_ASSERT(s2 == "ABCDEF"); const char* cstr = "XYZ"; - std::string s3 = JniHelper::callStaticStringMethod(classPath, "stringMethod", cstr, true); + std::string s3 = JniHelper::callStaticStringMethod(classPath, "stringMethod", cstr, true); CC_ASSERT(s3 == "ZYX"); // should not crash - for (int i = 0; i < 10000; i++) - { + for (int i = 0; i < 10000; i++) { JniHelper::callStaticVoidMethod(classPath, "voidMethod4", "ABCDEF"); } diff --git a/tests/cpp-tests/Classes/JNITest/JNITest.h b/tests/cpp-tests/Classes/JNITest/JNITest.h index 2d00e22937..1cc3a59ddf 100644 --- a/tests/cpp-tests/Classes/JNITest/JNITest.h +++ b/tests/cpp-tests/Classes/JNITest/JNITest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,8 +27,8 @@ #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) -# include "cocos2d.h" -# include "../BaseTest.h" +#include "cocos2d.h" +#include "../BaseTest.h" DEFINE_TEST_SUITE(JNITests); @@ -40,4 +40,4 @@ public: JNITest(); }; #endif -#endif // _JNI_TEST_H_ +#endif // _JNI_TEST_H_ diff --git a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp index b490f025c7..0918b0f48a 100644 --- a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp +++ b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -31,18 +31,16 @@ USING_NS_CC; using namespace ui; using namespace extension; -enum -{ - kTagTileMap = 1, +enum { + kTagTileMap = 1, kTagSpriteManager = 1, - kTagAnimation1 = 1, - kTagBitmapAtlas1 = 1, - kTagBitmapAtlas2 = 2, - kTagBitmapAtlas3 = 3, + kTagAnimation1 = 1, + kTagBitmapAtlas1 = 1, + kTagBitmapAtlas2 = 2, + kTagBitmapAtlas3 = 3, }; -enum -{ +enum { kTagSprite1, kTagSprite2, kTagSprite3, @@ -152,34 +150,36 @@ LabelFNTColorAndOpacity::LabelFNTColorAndOpacity() { _time = 0; - auto col = LayerColor::create(Color4B(128, 128, 128, 255)); + auto col = LayerColor::create( Color4B(128,128,128,255) ); addChild(col, -10); - + auto label1 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "Test"); - - label1->setAnchorPoint(Vec2(0, 0)); + + label1->setAnchorPoint( Vec2(0,0) ); addChild(label1, 0, kTagBitmapAtlas1); - auto fade = FadeOut::create(1.0f); + auto fade = FadeOut::create(1.0f); auto fade_in = fade->reverse(); - auto seq = Sequence::create(fade, fade_in, nullptr); - auto repeat = RepeatForever::create(seq); + auto seq = Sequence::create(fade, fade_in, nullptr); + auto repeat = RepeatForever::create(seq); label1->runAction(repeat); - + auto label2 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "Test"); - label2->setColor(Color3B::RED); + label2->setColor( Color3B::RED ); addChild(label2, 0, kTagBitmapAtlas2); - auto tint = Sequence::create(TintTo::create(1, 255, 0, 0), TintTo::create(1, 0, 255, 0), - TintTo::create(1, 0, 0, 255), nullptr); - label2->runAction(RepeatForever::create(tint)); - + auto tint = Sequence::create(TintTo::create(1, 255, 0, 0), + TintTo::create(1, 0, 255, 0), + TintTo::create(1, 0, 0, 255), + nullptr); + label2->runAction( RepeatForever::create(tint) ); + auto label3 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "Test"); - label3->setAnchorPoint(Vec2(1, 1)); + label3->setAnchorPoint( Vec2(1,1) ); addChild(label3, 0, kTagBitmapAtlas3); - - label1->setPosition(VisibleRect::leftBottom()); - label2->setPosition(VisibleRect::center()); - label3->setPosition(VisibleRect::rightTop()); - + + label1->setPosition( VisibleRect::leftBottom() ); + label2->setPosition( VisibleRect::center() ); + label3->setPosition( VisibleRect::rightTop() ); + schedule(CC_CALLBACK_1(LabelFNTColorAndOpacity::step, this), "step_key"); } @@ -188,14 +188,14 @@ void LabelFNTColorAndOpacity::step(float dt) _time += dt; char string[15] = {0}; sprintf(string, "%2.2f Test j", _time); - - auto label1 = (Label*)getChildByTag(kTagBitmapAtlas1); + + auto label1 = (Label*) getChildByTag(kTagBitmapAtlas1); label1->setString(string); - - auto label2 = (Label*)getChildByTag(kTagBitmapAtlas2); + + auto label2 = (Label*) getChildByTag(kTagBitmapAtlas2); label2->setString(string); - - auto label3 = (Label*)getChildByTag(kTagBitmapAtlas3); + + auto label3 = (Label*) getChildByTag(kTagBitmapAtlas3); label3->setString(string); } @@ -212,53 +212,56 @@ std::string LabelFNTColorAndOpacity::subtitle() const LabelFNTSpriteActions::LabelFNTSpriteActions() { _time = 0; - + auto s = Director::getInstance()->getWinSize(); - + auto drawNode = DrawNode::create(); - drawNode->drawLine(Vec2(0.0f, s.height / 2), Vec2(s.width, s.height / 2), Color4F(1.0f, 1.0f, 1.0f, 1.0f)); - drawNode->drawLine(Vec2(s.width / 2, 0.0f), Vec2(s.width / 2, s.height), Color4F(1.0f, 1.0f, 1.0f, 1.0f)); + drawNode->drawLine( Vec2(0.0f, s.height/2), Vec2(s.width, s.height/2), Color4F(1.0f, 1.0f, 1.0f, 1.0f) ); + drawNode->drawLine( Vec2(s.width/2, 0.0f), Vec2(s.width/2, s.height), Color4F(1.0f, 1.0f, 1.0f, 1.0f) ); addChild(drawNode, -1); // Upper Label auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Bitmap Font Atlas"); addChild(label); - - label->setPosition(Vec2(s.width / 2, s.height / 2)); - - auto BChar = (Sprite*)label->getLetter(0); - auto FChar = (Sprite*)label->getLetter(7); - auto AChar = (Sprite*)label->getLetter(12); - - auto rotate = RotateBy::create(2, 360); + + + label->setPosition( Vec2(s.width/2, s.height/2) ); + + auto BChar = (Sprite*) label->getLetter(0); + auto FChar = (Sprite*) label->getLetter(7); + auto AChar = (Sprite*) label->getLetter(12); + + + auto rotate = RotateBy::create(2, 360); auto rot_4ever = RepeatForever::create(rotate); - - auto scale = ScaleBy::create(2, 1.5f); - auto scale_back = scale->reverse(); - auto scale_seq = Sequence::create(scale, scale_back, nullptr); + + auto scale = ScaleBy::create(2, 1.5f); + auto scale_back = scale->reverse(); + auto scale_seq = Sequence::create(scale, scale_back,nullptr); auto scale_4ever = RepeatForever::create(scale_seq); - - auto jump = JumpBy::create(0.5f, Vec2::ZERO, 60, 1); + + auto jump = JumpBy::create(0.5f, Vec2::ZERO, 60, 1); auto jump_4ever = RepeatForever::create(jump); - - auto fade_out = FadeOut::create(1); - auto fade_in = FadeIn::create(1); - auto seq = Sequence::create(fade_out, fade_in, nullptr); + + auto fade_out = FadeOut::create(1); + auto fade_in = FadeIn::create(1); + auto seq = Sequence::create(fade_out, fade_in, nullptr); auto fade_4ever = RepeatForever::create(seq); - + BChar->runAction(rot_4ever); BChar->runAction(scale_4ever); FChar->runAction(jump_4ever); AChar->runAction(fade_4ever); - + + // Bottom Label auto label2 = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "00.0"); addChild(label2, 0, kTagBitmapAtlas2); - label2->setPosition(Vec2(s.width / 2.0f, 80.0f)); - - auto lastChar = (Sprite*)label2->getLetter(3); - lastChar->runAction(rot_4ever->clone()); - + label2->setPosition( Vec2(s.width/2.0f, 80.0f) ); + + auto lastChar = (Sprite*) label2->getLetter(3); + lastChar->runAction( rot_4ever->clone() ); + schedule(CC_CALLBACK_1(LabelFNTSpriteActions::step, this), 0.1f, "step_key"); } @@ -267,7 +270,7 @@ void LabelFNTSpriteActions::step(float dt) _time += dt; char string[10] = {0}; sprintf(string, "%04.1f", _time); - auto label1 = (Label*)getChildByTag(kTagBitmapAtlas2); + auto label1 = (Label*) getChildByTag(kTagBitmapAtlas2); label1->setString(string); } @@ -285,10 +288,10 @@ LabelFNTPadding::LabelFNTPadding() { auto label = Label::createWithBMFont("fonts/bitmapFontTest4.fnt", "abcdefg"); addChild(label); - + auto s = Director::getInstance()->getWinSize(); - - label->setPosition(Vec2(s.width / 2, s.height / 2)); + + label->setPosition( Vec2(s.width/2, s.height/2) ); } std::string LabelFNTPadding::title() const @@ -306,17 +309,17 @@ LabelFNTOffset::LabelFNTOffset() auto s = Director::getInstance()->getWinSize(); Label* label = nullptr; - label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "FaFeFiFoFu"); + label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "FaFeFiFoFu"); addChild(label); - label->setPosition(Vec2(s.width / 2, s.height / 2 + 50)); - + label->setPosition( Vec2(s.width/2, s.height/2+50) ); + label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "fafefifofu"); addChild(label); - label->setPosition(Vec2(s.width / 2, s.height / 2)); + label->setPosition( Vec2(s.width/2, s.height/2) ); label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "aeiou"); addChild(label); - label->setPosition(Vec2(s.width / 2, s.height / 2 - 50)); + label->setPosition( Vec2(s.width/2, s.height/2-50) ); } std::string LabelFNTOffset::title() const @@ -332,21 +335,21 @@ std::string LabelFNTOffset::subtitle() const LabelFNTColor::LabelFNTColor() { auto winSize = Director::getInstance()->getWinSize(); - + auto label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "Blue"); - label->setColor(Color3B::BLUE); + label->setColor( Color3B::BLUE ); addChild(label); label->setPosition(winSize.width / 2, winSize.height * 0.7f); label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "Red"); addChild(label); label->setPosition(winSize.width / 2, winSize.height * 0.5f); - label->setColor(Color3B::RED); + label->setColor( Color3B::RED ); label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "Green"); addChild(label); - label->setPosition(winSize.width / 2, winSize.height * 0.3f); - label->setColor(Color3B::GREEN); + label->setPosition(winSize.width / 2, winSize.height * 0.3f); + label->setColor( Color3B::GREEN ); label->setString("Green"); } @@ -388,17 +391,17 @@ std::string LabelFNTOpacity::subtitle() const LabelFNTHundredLabels::LabelFNTHundredLabels() { // Upper Label - for (int i = 0; i < 100; i++) + for ( int i=0 ; i < 100;i ++ ) { char str[6] = {0}; sprintf(str, "-%d-", i); auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", str); addChild(label); - + auto s = Director::getInstance()->getWinSize(); - auto p = Vec2(CCRANDOM_0_1() * s.width, CCRANDOM_0_1() * s.height); - label->setPosition(p); + auto p = Vec2( CCRANDOM_0_1() * s.width, CCRANDOM_0_1() * s.height); + label->setPosition( p ); } } @@ -418,17 +421,18 @@ LabelFNTMultiLine::LabelFNTMultiLine() // Left auto label1 = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", " Multi line\nLeft"); - label1->setAnchorPoint(Vec2(0, 0)); + label1->setAnchorPoint(Vec2(0,0)); addChild(label1, 0, kTagBitmapAtlas1); s = label1->getContentSize(); CCLOG("content size: %.2fx%.2f", s.width, s.height); + // Center - auto label2 = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "Multi line\nCenter"); + auto label2 = Label::createWithBMFont( "fonts/bitmapFontTest3.fnt", "Multi line\nCenter"); addChild(label2, 0, kTagBitmapAtlas2); - s = label2->getContentSize(); + s= label2->getContentSize(); CCLOG("content size: %.2fx%.2f", s.width, s.height); // right @@ -461,17 +465,17 @@ LabelFNTandTTFEmpty::LabelFNTandTTFEmpty() // LabelBMFont auto label1 = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "", TextHAlignment::CENTER, s.width); addChild(label1, 0, kTagBitmapAtlas1); - label1->setPosition(Vec2(s.width / 2, s.height - 100)); + label1->setPosition(Vec2(s.width/2, s.height - 100)); // LabelTTF - TTFConfig ttfConfig("fonts/arial.ttf", 24); - auto label2 = Label::createWithTTF(ttfConfig, "", TextHAlignment::CENTER, s.width); + TTFConfig ttfConfig("fonts/arial.ttf",24); + auto label2 = Label::createWithTTF(ttfConfig,"", TextHAlignment::CENTER,s.width); addChild(label2, 0, kTagBitmapAtlas2); - label2->setPosition(Vec2(s.width / 2, s.height / 2)); - + label2->setPosition(Vec2(s.width/2, s.height / 2)); + auto label3 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.plist"); addChild(label3, 0, kTagBitmapAtlas3); - label3->setPosition(Vec2(s.width / 2, 100.0f)); + label3->setPosition(Vec2(s.width/2, 100.0f)); schedule(CC_CALLBACK_1(LabelFNTandTTFEmpty::updateStrings, this), 1.0f, "update_strings_key"); @@ -480,16 +484,16 @@ LabelFNTandTTFEmpty::LabelFNTandTTFEmpty() void LabelFNTandTTFEmpty::updateStrings(float dt) { - auto label1 = static_cast(getChildByTag(kTagBitmapAtlas1)); - auto label2 = static_cast(getChildByTag(kTagBitmapAtlas2)); - auto label3 = static_cast(getChildByTag(kTagBitmapAtlas3)); + auto label1 = static_cast( getChildByTag(kTagBitmapAtlas1) ); + auto label2 = static_cast( getChildByTag(kTagBitmapAtlas2) ); + auto label3 = static_cast( getChildByTag(kTagBitmapAtlas3) ); - if (!setEmpty) + if( ! setEmpty ) { label1->setString("not empty"); label2->setString("not empty"); label3->setString("hi"); - + setEmpty = true; } else @@ -497,7 +501,7 @@ void LabelFNTandTTFEmpty::updateStrings(float dt) label1->setString(""); label2->setString(""); label3->setString(""); - + setEmpty = false; } } @@ -519,7 +523,7 @@ LabelFNTRetina::LabelFNTRetina() // LabelBMFont auto label1 = Label::createWithBMFont("fonts/konqa32.fnt", "TESTING RETINA DISPLAY"); addChild(label1); - label1->setPosition(Vec2(s.width / 2, s.height / 2)); + label1->setPosition(Vec2(s.width/2, s.height/2)); } std::string LabelFNTRetina::title() const @@ -536,7 +540,7 @@ LabelFNTGlyphDesigner::LabelFNTGlyphDesigner() { auto winSize = Director::getInstance()->getWinSize(); - auto layer = LayerColor::create(Color4B(128, 128, 128, 255)); + auto layer = LayerColor::create(Color4B(128,128,128,255)); addChild(layer, -10); auto label1 = Label::createWithBMFont("fonts/futura-48.fnt", "Testing Glyph Designer"); @@ -564,12 +568,9 @@ std::string LabelFNTGlyphDesigner::subtitle() const /// BitmapFontMultiLineAlignmentNew -#define LongSentencesExample \ - "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore " \ - "magna aliqua." -#define LineBreaksExample "Lorem ipsum dolor\nsit amet\nconsectetur adipisicing elit\nblah\nblah" -#define MixedExample \ - "ABC\nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt\nDEF" +#define LongSentencesExample "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." +#define LineBreaksExample "Lorem ipsum dolor\nsit amet\nconsectetur adipisicing elit\nblah\nblah" +#define MixedExample "ABC\nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt\nDEF" #define ArrowsMax 0.95 #define ArrowsMin 0.7 @@ -592,29 +593,26 @@ bool LabelFNTMultiLineAlignment::init() return false; } - auto listener = EventListenerTouchAllAtOnce::create(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(LabelFNTMultiLineAlignment::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(LabelFNTMultiLineAlignment::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(LabelFNTMultiLineAlignment::onTouchesEnded, this); - + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // ask director the the window size auto size = Director::getInstance()->getWinSize(); // create and initialize a Label - this->_label = Label::createWithBMFont("fonts/markerFelt.fnt", "", TextHAlignment::CENTER, size.width / 1.5); + this->_label = Label::createWithBMFont("fonts/markerFelt.fnt", "", TextHAlignment::CENTER, size.width/1.5); this->_arrowsBar = Sprite::create("Images/arrowsBar.png"); - this->_arrows = Sprite::create("Images/arrows.png"); + this->_arrows = Sprite::create("Images/arrows.png"); MenuItemFont::setFontSize(20); - auto longSentences = - MenuItemFont::create("Long Flowing Sentences", CC_CALLBACK_1(LabelFNTMultiLineAlignment::stringChanged, this)); - auto lineBreaks = MenuItemFont::create("Short Sentences With Intentional Line Breaks", - CC_CALLBACK_1(LabelFNTMultiLineAlignment::stringChanged, this)); - auto mixed = MenuItemFont::create("Long Sentences Mixed With Intentional Line Breaks", - CC_CALLBACK_1(LabelFNTMultiLineAlignment::stringChanged, this)); - auto stringMenu = Menu::create(longSentences, lineBreaks, mixed, nullptr); + auto longSentences = MenuItemFont::create("Long Flowing Sentences", CC_CALLBACK_1(LabelFNTMultiLineAlignment::stringChanged, this)); + auto lineBreaks = MenuItemFont::create("Short Sentences With Intentional Line Breaks", CC_CALLBACK_1(LabelFNTMultiLineAlignment::stringChanged, this)); + auto mixed = MenuItemFont::create("Long Sentences Mixed With Intentional Line Breaks", CC_CALLBACK_1(LabelFNTMultiLineAlignment::stringChanged, this)); + auto stringMenu = Menu::create(longSentences, lineBreaks, mixed, nullptr); stringMenu->alignItemsVertically(); longSentences->setTag(LongSentences); @@ -627,9 +625,9 @@ bool LabelFNTMultiLineAlignment::init() MenuItemFont::setFontSize(30); - auto left = MenuItemFont::create("Left", CC_CALLBACK_1(LabelFNTMultiLineAlignment::alignmentChanged, this)); + auto left = MenuItemFont::create("Left", CC_CALLBACK_1(LabelFNTMultiLineAlignment::alignmentChanged, this)); auto center = MenuItemFont::create("Center", CC_CALLBACK_1(LabelFNTMultiLineAlignment::alignmentChanged, this)); - auto right = MenuItemFont::create("Right", CC_CALLBACK_1(LabelFNTMultiLineAlignment::alignmentChanged, this)); + auto right = MenuItemFont::create("Right", CC_CALLBACK_1(LabelFNTMultiLineAlignment::alignmentChanged, this)); auto alignmentMenu = Menu::create(left, center, right, nullptr); alignmentMenu->alignItemsHorizontallyWithPadding(alignmentItemPadding); @@ -639,7 +637,7 @@ bool LabelFNTMultiLineAlignment::init() right->setTag(RightAlign); // position the label on the center of the screen - this->_label->setPosition(Vec2(size.width / 2, size.height / 2)); + this->_label->setPosition(Vec2(size.width/2, size.height/2)); this->_arrowsBar->setVisible(false); @@ -647,8 +645,8 @@ bool LabelFNTMultiLineAlignment::init() this->_arrowsBar->setScaleX(arrowsWidth / this->_arrowsBar->getContentSize().width); this->_arrowsBar->setPosition(Vec2(((ArrowsMax + ArrowsMin) / 2) * size.width, this->_label->getPosition().y)); - stringMenu->setPosition(Vec2(size.width / 2, size.height - menuItemPaddingCenter)); - alignmentMenu->setPosition(Vec2(size.width / 2, menuItemPaddingCenter + 15)); + stringMenu->setPosition(Vec2(size.width/2, size.height - menuItemPaddingCenter)); + alignmentMenu->setPosition(Vec2(size.width/2, menuItemPaddingCenter+15)); this->selectSentenceItem(longSentences); this->selectAlignmentItem(center); @@ -673,7 +671,7 @@ std::string LabelFNTMultiLineAlignment::subtitle() const return ""; } -void LabelFNTMultiLineAlignment::selectAlignmentItem(cocos2d::MenuItemFont* item) +void LabelFNTMultiLineAlignment::selectAlignmentItem(cocos2d::MenuItemFont * item) { if (this->_lastAlignmentItem && this->_lastAlignmentItem != item) { @@ -737,7 +735,7 @@ std::string LabelFNTMultiLineAlignment::getItemString(cocos2d::MenuItemFont* ite return str; } -void LabelFNTMultiLineAlignment::stringChanged(cocos2d::Ref* sender) +void LabelFNTMultiLineAlignment::stringChanged(cocos2d::Ref *sender) { auto item = (MenuItemFont*)sender; @@ -746,7 +744,7 @@ void LabelFNTMultiLineAlignment::stringChanged(cocos2d::Ref* sender) this->snapArrowsToEdge(); } -void LabelFNTMultiLineAlignment::alignmentChanged(cocos2d::Ref* sender) +void LabelFNTMultiLineAlignment::alignmentChanged(cocos2d::Ref *sender) { auto item = static_cast(sender); @@ -755,9 +753,9 @@ void LabelFNTMultiLineAlignment::alignmentChanged(cocos2d::Ref* sender) this->snapArrowsToEdge(); } -void LabelFNTMultiLineAlignment::onTouchesBegan(const std::vector& touches, cocos2d::Event* event) +void LabelFNTMultiLineAlignment::onTouchesBegan(const std::vector& touches, cocos2d::Event *event) { - auto touch = touches[0]; + auto touch = touches[0]; auto location = touch->getLocationInView(); if (this->_arrows->getBoundingBox().containsPoint(location)) @@ -767,7 +765,7 @@ void LabelFNTMultiLineAlignment::onTouchesBegan(const std::vector& touch } } -void LabelFNTMultiLineAlignment::onTouchesEnded(const std::vector& touches, cocos2d::Event* event) +void LabelFNTMultiLineAlignment::onTouchesEnded(const std::vector& touches, cocos2d::Event *event) { _drag = false; this->snapArrowsToEdge(); @@ -775,20 +773,20 @@ void LabelFNTMultiLineAlignment::onTouchesEnded(const std::vector& touch this->_arrowsBar->setVisible(false); } -void LabelFNTMultiLineAlignment::onTouchesMoved(const std::vector& touches, cocos2d::Event* event) +void LabelFNTMultiLineAlignment::onTouchesMoved(const std::vector& touches, cocos2d::Event *event) { - if (!_drag) + if (! _drag) { return; } - auto touch = touches[0]; + auto touch = touches[0]; auto location = touch->getLocationInView(); auto winSize = Director::getInstance()->getWinSize(); - this->_arrows->setPosition(Vec2(MAX(MIN(location.x, ArrowsMax * winSize.width), ArrowsMin * winSize.width), - this->_arrows->getPosition().y)); + this->_arrows->setPosition(Vec2(MAX(MIN(location.x, ArrowsMax*winSize.width), ArrowsMin*winSize.width), + this->_arrows->getPosition().y)); float labelWidth = fabs(this->_arrows->getPosition().x - this->_label->getPosition().x) * 2; @@ -797,8 +795,8 @@ void LabelFNTMultiLineAlignment::onTouchesMoved(const std::vector& touch void LabelFNTMultiLineAlignment::snapArrowsToEdge() { - this->_arrows->setPosition( - Vec2(this->_label->getPosition().x + this->_label->getContentSize().width / 2, this->_label->getPosition().y)); + this->_arrows->setPosition(Vec2(this->_label->getPosition().x + this->_label->getContentSize().width/2, + this->_label->getPosition().y)); } /// LabelFNTMultiLineAlignmentUNICODE @@ -814,8 +812,8 @@ bool LabelFNTMultiLineAlignmentUNICODE::init() this->_menuItems[1]->setString("Spanish"); this->_menuItems[2]->setString("Ukrainian"); - auto ttfConfig = this->_label->getTTFConfig(); - ttfConfig.fontSize = 20; + auto ttfConfig = this->_label->getTTFConfig(); + ttfConfig.fontSize = 20; ttfConfig.fontFilePath = "fonts/tahoma.ttf"; this->_label->setTTFConfig(ttfConfig); @@ -863,7 +861,7 @@ std::string LabelFNTMultiLineAlignmentUNICODE::getItemString(cocos2d::MenuItemFo /// BMFontUnicodeNew LabelFNTUNICODELanguages::LabelFNTUNICODELanguages() { - auto strings = FileUtils::getInstance()->getValueMapFromFile("strings/LabelFNTUNICODELanguages.xml"); + auto strings = FileUtils::getInstance()->getValueMapFromFile("strings/LabelFNTUNICODELanguages.xml"); std::string chinese = strings["chinese1"].asString(); std::string russian = strings["russian"].asString(); std::string spanish = strings["spanish"].asString(); @@ -873,19 +871,19 @@ LabelFNTUNICODELanguages::LabelFNTUNICODELanguages() auto label1 = Label::createWithBMFont("fonts/arial-unicode-26.fnt", spanish, TextHAlignment::CENTER, 200); addChild(label1); - label1->setPosition(Vec2(s.width / 2, s.height / 5 * 3)); - + label1->setPosition(Vec2(s.width/2, s.height/5*3)); + auto label2 = Label::createWithBMFont("fonts/arial-unicode-26.fnt", chinese); addChild(label2); - label2->setPosition(Vec2(s.width / 2, s.height / 5 * 2.5)); + label2->setPosition(Vec2(s.width/2, s.height/5*2.5)); auto label3 = Label::createWithBMFont("fonts/arial-26-en-ru.fnt", russian); addChild(label3); - label3->setPosition(Vec2(s.width / 2, s.height / 5 * 2)); + label3->setPosition(Vec2(s.width/2, s.height/5*2)); auto label4 = Label::createWithBMFont("fonts/arial-unicode-26.fnt", japanese); addChild(label4); - label4->setPosition(Vec2(s.width / 2, s.height / 5 * 1.5)); + label4->setPosition(Vec2(s.width/2, s.height/5*1.5)); } std::string LabelFNTUNICODELanguages::title() const @@ -901,26 +899,29 @@ std::string LabelFNTUNICODELanguages::subtitle() const LabelFNTBounds::LabelFNTBounds() { auto s = Director::getInstance()->getWinSize(); - - auto layer = LayerColor::create(Color4B(128, 128, 128, 255)); + + auto layer = LayerColor::create(Color4B(128,128,128,255)); addChild(layer, -10); - + // LabelBMFont - auto label1 = - Label::createWithBMFont("fonts/boundsTestFont.fnt", "Testing Glyph Designer", TextHAlignment::CENTER, s.width); + auto label1 = Label::createWithBMFont("fonts/boundsTestFont.fnt", "Testing Glyph Designer", TextHAlignment::CENTER,s.width); addChild(label1); - label1->setPosition(Vec2(s.width / 2, s.height / 2)); + label1->setPosition(Vec2(s.width/2, s.height/2)); - auto drawNode = DrawNode::create(); + auto drawNode = DrawNode::create(); auto labelSize = label1->getContentSize(); auto origin = Director::getInstance()->getWinSize(); - - origin.width = origin.width / 2 - (labelSize.width / 2); + + origin.width = origin.width / 2 - (labelSize.width / 2); origin.height = origin.height / 2 - (labelSize.height / 2); - - Vec2 vertices[4] = {Vec2(origin.width, origin.height), Vec2(labelSize.width + origin.width, origin.height), - Vec2(labelSize.width + origin.width, labelSize.height + origin.height), - Vec2(origin.width, labelSize.height + origin.height)}; + + Vec2 vertices[4]= + { + Vec2(origin.width, origin.height), + Vec2(labelSize.width + origin.width, origin.height), + Vec2(labelSize.width + origin.width, labelSize.height + origin.height), + Vec2(origin.width, labelSize.height + origin.height) + }; drawNode->drawPoly(vertices, 4, true, Color4F(1.0f, 1.0f, 1.0f, 1.0f)); addChild(drawNode); } @@ -943,8 +944,7 @@ LabelFNTMultiFontAtlasNoRotation::LabelFNTMultiFontAtlasNoRotation() addChild(label1); label1->setPosition(Vec2(s.width / 2, s.height / 3 * 2)); - auto label2 = Label::createWithBMFont("fonts/geneva-32.fnt", "And this is Geneva", TextHAlignment::LEFT, 0, - Rect(0, 128, 0, 0), false); + auto label2 = Label::createWithBMFont("fonts/geneva-32.fnt", "And this is Geneva", TextHAlignment::LEFT, 0, Rect(0, 128, 0, 0), false); addChild(label2); label2->setPosition(Vec2(s.width / 2, s.height / 3 * 1)); } @@ -967,14 +967,12 @@ LabelFNTMultiFontAtlasWithRotation::LabelFNTMultiFontAtlasWithRotation() spriteCache->addSpriteFramesWithFile("fonts/bmfont-rotated-test.plist"); // Label BMFont - auto label1 = Label::createWithBMFont("fonts/helvetica-regular-32.fnt", "Helvetica with SubTextureKey", - TextHAlignment::CENTER, 0, "helvetica-regular-32.png"); + auto label1 = Label::createWithBMFont("fonts/helvetica-regular-32.fnt", "Helvetica with SubTextureKey", TextHAlignment::CENTER, 0, "helvetica-regular-32.png"); label1->setPosition(Vec2(s.width / 2, s.height / 3 * 2)); this->addChild(label1); const auto frame = spriteCache->getSpriteFrameByName("geneva-regular-32.png"); - auto label2 = Label::createWithBMFont("fonts/geneva-regular-32.fnt", "Geneva with Rect and Rotated", - TextHAlignment::CENTER, 0, frame->getRectInPixels(), frame->isRotated()); + auto label2 = Label::createWithBMFont("fonts/geneva-regular-32.fnt", "Geneva with Rect and Rotated", TextHAlignment::CENTER, 0, frame->getRectInPixels(), frame->isRotated()); label2->setPosition(Vec2(s.width / 2, s.height / 3 * 1)); this->addChild(label2); } @@ -995,8 +993,8 @@ LabelTTFLongLineWrapping::LabelTTFLongLineWrapping() // Long sentence TTFConfig ttfConfig("fonts/arial.ttf", 14); - auto label1 = Label::createWithTTF(ttfConfig, LongSentencesExample, TextHAlignment::CENTER, size.width); - label1->setPosition(Vec2(size.width / 2, size.height / 2)); + auto label1 = Label::createWithTTF(ttfConfig, LongSentencesExample, TextHAlignment::CENTER,size.width); + label1->setPosition( Vec2(size.width/2, size.height/2) ); label1->setAnchorPoint(Vec2(0.5f, 1.0f)); addChild(label1); } @@ -1017,21 +1015,21 @@ LabelTTFColor::LabelTTFColor() TTFConfig ttfConfig("fonts/arial.ttf", 18); // Green - auto label1 = Label::createWithTTF(ttfConfig, "Green", TextHAlignment::CENTER, size.width); - label1->setPosition(size.width / 2, size.height * 0.5f); - label1->setTextColor(Color4B::GREEN); + auto label1 = Label::createWithTTF(ttfConfig,"Green", TextHAlignment::CENTER, size.width); + label1->setPosition(size.width/2, size.height * 0.5f); + label1->setTextColor( Color4B::GREEN ); addChild(label1); // Red - auto label2 = Label::createWithTTF(ttfConfig, "Red", TextHAlignment::CENTER, size.width); - label2->setPosition(size.width / 2, size.height * 0.65f); - label2->setTextColor(Color4B::RED); + auto label2 = Label::createWithTTF(ttfConfig,"Red", TextHAlignment::CENTER, size.width); + label2->setPosition(size.width/2, size.height * 0.65f); + label2->setTextColor( Color4B::RED ); addChild(label2); // Blue - auto label3 = Label::createWithTTF(ttfConfig, "Blue", TextHAlignment::CENTER, size.width); - label3->setPosition(size.width / 2, size.height * 0.35f); - label3->setTextColor(Color4B::BLUE); + auto label3 = Label::createWithTTF(ttfConfig,"Blue", TextHAlignment::CENTER, size.width); + label3->setPosition(size.width/2, size.height * 0.35f); + label3->setTextColor( Color4B::BLUE ); addChild(label3); } @@ -1055,16 +1053,17 @@ LabelTTFDynamicAlignment::LabelTTFDynamicAlignment() addChild(_label); auto menu = Menu::create( - MenuItemFont::create("Left", CC_CALLBACK_1(LabelTTFDynamicAlignment::setAlignmentLeft, this)), - MenuItemFont::create("Center", CC_CALLBACK_1(LabelTTFDynamicAlignment::setAlignmentCenter, this)), - MenuItemFont::create("Right", CC_CALLBACK_1(LabelTTFDynamicAlignment::setAlignmentRight, this)), nullptr); - + MenuItemFont::create("Left", CC_CALLBACK_1(LabelTTFDynamicAlignment::setAlignmentLeft, this)), + MenuItemFont::create("Center", CC_CALLBACK_1(LabelTTFDynamicAlignment::setAlignmentCenter, this)), + MenuItemFont::create("Right", CC_CALLBACK_1(LabelTTFDynamicAlignment::setAlignmentRight, this)), + nullptr); + menu->alignItemsHorizontallyWithPadding(20); menu->setPosition(winSize.width / 2, winSize.height * 0.25f); addChild(menu); } -void LabelTTFDynamicAlignment::updateAlignment() +void LabelTTFDynamicAlignment::updateAlignment() { if (_label) { @@ -1106,20 +1105,21 @@ std::string LabelTTFDynamicAlignment::subtitle() const LabelTTFCJKWrappingTest::LabelTTFCJKWrappingTest() { auto size = Director::getInstance()->getWinSize(); - + auto drawNode = DrawNode::create(); drawNode->setAnchorPoint(Vec2(0, 0)); this->addChild(drawNode); - drawNode->drawSegment(Vec2(size.width * 0.1f, size.height * 0.8f), Vec2(size.width * 0.1, 0.0f), 1, - Color4F(1.0f, 0.0f, 0.0f, 1.0f)); - drawNode->drawSegment(Vec2(size.width * 0.85f, size.height * 0.8f), Vec2(size.width * 0.85f, 0.0f), 1, - Color4F(1.0f, 0.0f, 0.0f, 1.0f)); - + drawNode->drawSegment( + Vec2(size.width * 0.1f, size.height * 0.8f), + Vec2(size.width * 0.1, 0.0f), 1, Color4F(1.0f, 0.0f, 0.0f, 1.0f)); + drawNode->drawSegment( + Vec2(size.width * 0.85f, size.height * 0.8f), + Vec2(size.width * 0.85f, 0.0f), 1, Color4F(1.0f, 0.0f, 0.0f, 1.0f)); + TTFConfig ttfConfig("fonts/HKYuanMini.ttf", 25, GlyphCollection::DYNAMIC); - auto label1 = - Label::createWithTTF(ttfConfig, "你好,Cocos2d-x v3的New Label.", TextHAlignment::LEFT, size.width * 0.75f); - if (label1) - { + auto label1 = Label::createWithTTF(ttfConfig, + "你好,Cocos2d-x v3的New Label.", TextHAlignment::LEFT, size.width * 0.75f); + if(label1) { label1->setTextColor(Color4B(128, 255, 255, 255)); label1->setPosition(Vec2(size.width * 0.1f, size.height * 0.6f)); label1->setAnchorPoint(Vec2(0.0f, 0.5f)); @@ -1130,20 +1130,18 @@ LabelTTFCJKWrappingTest::LabelTTFCJKWrappingTest() label1->setTTFConfig(ttfConfig); } - auto label2 = - Label::createWithTTF(ttfConfig, "早上好,Cocos2d-x v3的New Label.", TextHAlignment::LEFT, size.width * 0.75f); - if (label2) - { + auto label2 = Label::createWithTTF(ttfConfig, + "早上好,Cocos2d-x v3的New Label.", TextHAlignment::LEFT, size.width * 0.75f); + if(label2) { label2->setTextColor(Color4B(255, 128, 255, 255)); label2->setPosition(Vec2(size.width * 0.1f, size.height * 0.4f)); label2->setAnchorPoint(Vec2(0.0f, 0.5f)); this->addChild(label2); } - auto label3 = Label::createWithTTF(ttfConfig, "美好的一天啊美好的一天啊美好的一天啊", TextHAlignment::LEFT, - size.width * 0.75f); - if (label3) - { + auto label3 = Label::createWithTTF(ttfConfig, + "美好的一天啊美好的一天啊美好的一天啊", TextHAlignment::LEFT, size.width * 0.75f); + if(label3) { label3->setTextColor(Color4B(255, 255, 128, 255)); label3->setPosition(Vec2(size.width * 0.1f, size.height * 0.2f)); label3->setAnchorPoint(Vec2(0.0f, 0.5f)); @@ -1159,7 +1157,7 @@ std::string LabelTTFCJKWrappingTest::title() const std::string LabelTTFCJKWrappingTest::subtitle() const { return "New Label with CJK + ASCII characters\n" - "Characters should stay in the correct position"; + "Characters should stay in the correct position"; } // @@ -1167,20 +1165,20 @@ std::string LabelTTFCJKWrappingTest::subtitle() const // LabelTTFUnicodeNew::LabelTTFUnicodeNew() { - auto strings = FileUtils::getInstance()->getValueMapFromFile("strings/LabelFNTUNICODELanguages.xml"); - std::string chinese = strings["chinese1"].asString(); - auto winSize = Director::getInstance()->getWinSize(); + auto strings = FileUtils::getInstance()->getValueMapFromFile("strings/LabelFNTUNICODELanguages.xml"); + std::string chinese = strings["chinese1"].asString(); + auto winSize = Director::getInstance()->getWinSize(); // Spanish auto label1 = Label::createWithTTF("Buen día, ¿cómo te llamas?", "fonts/arial.ttf", 23); label1->setPosition(winSize.width / 2, winSize.height * 0.65f); addChild(label1); - + // German auto label2 = Label::createWithTTF("In welcher Straße haben Sie gelebt?", "fonts/arial.ttf", 23); label2->setPosition(winSize.width / 2, winSize.height * 0.5f); addChild(label2); - + // Chinese auto label3 = Label::createWithTTF(chinese, "fonts/HKYuanMini.ttf", 24); label3->setPosition(winSize.width / 2, winSize.height * 0.35f); @@ -1203,8 +1201,8 @@ std::string LabelTTFUnicodeNew::subtitle() const LabelTTFEmoji::LabelTTFEmoji() { std::string emojiString = FileUtils::getInstance()->getStringFromFile("fonts/emoji.txt"); - auto winSize = Director::getInstance()->getWinSize(); - + auto winSize = Director::getInstance()->getWinSize(); + auto label = Label::createWithTTF(emojiString, "fonts/NotoEmoji-Regular.ttf", 23); label->setPosition(winSize.width / 2, winSize.height / 2); label->setDimensions(winSize.width, winSize.height); @@ -1223,28 +1221,30 @@ std::string LabelTTFEmoji::subtitle() const return "Uses the new Label with TTF. Testing Emoji"; } + LabelTTFFontsTestNew::LabelTTFFontsTestNew() { - const char* ttfpaths[] = { - "fonts/A Damn Mess.ttf", "fonts/Abberancy.ttf", "fonts/Abduction.ttf", "fonts/American Typewriter.ttf", - "fonts/Paint Boy.ttf", "fonts/Schwarzwald.ttf", "fonts/Scissor Cuts.ttf", + const char *ttfpaths[] = { + "fonts/A Damn Mess.ttf", + "fonts/Abberancy.ttf", + "fonts/Abduction.ttf", + "fonts/American Typewriter.ttf", + "fonts/Paint Boy.ttf", + "fonts/Schwarzwald.ttf", + "fonts/Scissor Cuts.ttf", }; int fontCount = sizeof(ttfpaths) / sizeof(ttfpaths[0]); - auto size = Director::getInstance()->getWinSize(); - TTFConfig ttfConfig(ttfpaths[0], 20, GlyphCollection::NEHE); + auto size = Director::getInstance()->getWinSize(); + TTFConfig ttfConfig(ttfpaths[0],20, GlyphCollection::NEHE); - for (int i = 0; i < fontCount; ++i) - { + for (int i = 0; i < fontCount; ++i) { ttfConfig.fontFilePath = ttfpaths[i]; - auto label = Label::createWithTTF(ttfConfig, ttfpaths[i], TextHAlignment::CENTER, 0); - if (label) - { + auto label = Label::createWithTTF(ttfConfig, ttfpaths[i], TextHAlignment::CENTER,0); + if( label ) { label->setPosition(size.width / 2, ((size.height * 0.6) / fontCount * i) + (size.height / 4)); addChild(label); - } - else - { + } else { log("ERROR: Cannot load: %s", ttfpaths[i]); } } @@ -1263,40 +1263,53 @@ std::string LabelTTFFontsTestNew::subtitle() const LabelTTFDistanceField::LabelTTFDistanceField() { auto size = Director::getInstance()->getWinSize(); - TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC, nullptr, true); + TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC,nullptr,true); - auto label1 = Label::createWithTTF(ttfConfig, "Distance Field", TextHAlignment::CENTER, size.width); - label1->setPosition(Vec2(size.width / 2, size.height * 0.6f)); - label1->setTextColor(Color4B::GREEN); + auto label1 = Label::createWithTTF(ttfConfig,"Distance Field",TextHAlignment::CENTER,size.width); + label1->setPosition( Vec2(size.width/2, size.height * 0.6f) ); + label1->setTextColor( Color4B::GREEN ); addChild(label1); - auto action = Sequence::create(DelayTime::create(1.0f), ScaleTo::create(6.0f, 5.0f, 5.0f), - ScaleTo::create(6.0f, 1.0f, 1.0f), nullptr); + auto action = Sequence::create( + DelayTime::create(1.0f), + ScaleTo::create(6.0f,5.0f,5.0f), + ScaleTo::create(6.0f,1.0f,1.0f), + nullptr); label1->runAction(RepeatForever::create(action)); // Draw the label border auto& labelContentSize = label1->getContentSize(); - auto borderDraw = DrawNode::create(); + auto borderDraw = DrawNode::create(); label1->addChild(borderDraw); borderDraw->clear(); borderDraw->setLineWidth(1); - Vec2 vertices[4] = {Vec2::ZERO, Vec2(labelContentSize.width, 0.0f), - Vec2(labelContentSize.width, labelContentSize.height), Vec2(0.0f, labelContentSize.height)}; + Vec2 vertices[4] = + { + Vec2::ZERO, + Vec2(labelContentSize.width, 0.0f), + Vec2(labelContentSize.width, labelContentSize.height), + Vec2(0.0f, labelContentSize.height) + }; borderDraw->drawPoly(vertices, 4, true, Color4F::RED); - auto label2 = Label::createWithTTF(ttfConfig, "Distance Field", TextHAlignment::CENTER, size.width); - label2->setPosition(Vec2(size.width / 2, size.height * 0.3f)); - label2->setTextColor(Color4B::RED); + auto label2 = Label::createWithTTF(ttfConfig,"Distance Field",TextHAlignment::CENTER,size.width); + label2->setPosition( Vec2(size.width/2, size.height * 0.3f) ); + label2->setTextColor( Color4B::RED ); addChild(label2); - + // Draw the label border auto& labelContentSize2 = label2->getContentSize(); - auto borderDraw2 = DrawNode::create(); + auto borderDraw2 = DrawNode::create(); label2->addChild(borderDraw2); borderDraw2->clear(); borderDraw2->setLineWidth(1); - Vec2 vertices2[4] = {Vec2::ZERO, Vec2(labelContentSize2.width, 0.0f), - Vec2(labelContentSize2.width, labelContentSize2.height), Vec2(0.0f, labelContentSize2.height)}; + Vec2 vertices2[4] = + { + Vec2::ZERO, + Vec2(labelContentSize2.width, 0.0f), + Vec2(labelContentSize2.width, labelContentSize2.height), + Vec2(0.0f, labelContentSize2.height) + }; borderDraw2->drawPoly(vertices2, 4, true, Color4F::GREEN); } @@ -1314,35 +1327,35 @@ LabelOutlineAndGlowTest::LabelOutlineAndGlowTest() { auto size = Director::getInstance()->getWinSize(); - auto bg = LayerColor::create(Color4B(200, 191, 231, 255)); + auto bg = LayerColor::create(Color4B(200,191,231,255)); this->addChild(bg); - TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC, nullptr, true); + TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC,nullptr,true); - auto label1 = Label::createWithTTF(ttfConfig, "Glow", TextHAlignment::CENTER, size.width); - label1->setPosition(Vec2(size.width / 2, size.height * 0.7)); - label1->setTextColor(Color4B::GREEN); + auto label1 = Label::createWithTTF(ttfConfig,"Glow", TextHAlignment::CENTER, size.width); + label1->setPosition( Vec2(size.width/2, size.height*0.7) ); + label1->setTextColor( Color4B::GREEN ); label1->enableGlow(Color4B::YELLOW); addChild(label1); ttfConfig.outlineSize = 1; - auto label2 = Label::createWithTTF(ttfConfig, "Outline", TextHAlignment::CENTER, size.width); - label2->setPosition(Vec2(size.width / 2, size.height * 0.6)); - label2->setTextColor(Color4B::RED); + auto label2 = Label::createWithTTF(ttfConfig,"Outline", TextHAlignment::CENTER, size.width); + label2->setPosition( Vec2(size.width/2, size.height*0.6) ); + label2->setTextColor( Color4B::RED ); label2->enableOutline(Color4B::BLUE); addChild(label2); ttfConfig.outlineSize = 2; - auto label3 = Label::createWithTTF(ttfConfig, "Outline", TextHAlignment::CENTER, size.width); - label3->setPosition(Vec2(size.width / 2, size.height * 0.48)); - label3->setTextColor(Color4B::RED); + auto label3 = Label::createWithTTF(ttfConfig,"Outline", TextHAlignment::CENTER, size.width); + label3->setPosition( Vec2(size.width/2, size.height*0.48) ); + label3->setTextColor( Color4B::RED ); label3->enableOutline(Color4B::BLUE); addChild(label3); ttfConfig.outlineSize = 3; - auto label4 = Label::createWithTTF(ttfConfig, "Outline", TextHAlignment::CENTER, size.width); - label4->setPosition(Vec2(size.width / 2, size.height * 0.36)); - label4->setTextColor(Color4B::RED); + auto label4 = Label::createWithTTF(ttfConfig,"Outline", TextHAlignment::CENTER, size.width); + label4->setPosition( Vec2(size.width/2, size.height*0.36) ); + label4->setTextColor( Color4B::RED ); label4->enableOutline(Color4B::BLUE); addChild(label4); } @@ -1357,7 +1370,10 @@ std::string LabelOutlineAndGlowTest::subtitle() const return "Testing outline and glow of label"; } -LabelShadowTest::LabelShadowTest() {} +LabelShadowTest::LabelShadowTest() +{ + +} void LabelShadowTest::onEnter() { @@ -1365,7 +1381,7 @@ void LabelShadowTest::onEnter() auto size = Director::getInstance()->getWinSize(); - auto bg = LayerColor::create(Color4B(200, 191, 231, 255)); + auto bg = LayerColor::create(Color4B(200,191,231,255)); this->addChild(bg); auto slider = ui::Slider::create(); @@ -1391,51 +1407,51 @@ void LabelShadowTest::onEnter() slider2->addEventListener(CC_CALLBACK_2(LabelShadowTest::sliderEvent, this)); addChild(slider2, 999); - float subtitleY = _subtitleLabel->getPosition().y; + float subtitleY = _subtitleLabel->getPosition().y; float horizontalSliderY = slider->getPosition().y; - float step = (subtitleY - horizontalSliderY) / 4; + float step = (subtitleY - horizontalSliderY) / 4; - TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC, nullptr, true); + TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC,nullptr,true); - shadowLabelTTF = Label::createWithTTF(ttfConfig, "TTF:Shadow"); - shadowLabelTTF->setPosition(Vec2(size.width / 2, horizontalSliderY + step * (0.5f + 3))); - shadowLabelTTF->setTextColor(Color4B::RED); + shadowLabelTTF = Label::createWithTTF(ttfConfig,"TTF:Shadow"); + shadowLabelTTF->setPosition( Vec2(size.width/2, horizontalSliderY + step * (0.5f + 3)) ); + shadowLabelTTF->setTextColor( Color4B::RED ); shadowLabelTTF->enableShadow(Color4B::BLACK); addChild(shadowLabelTTF); - shadowLabelOutline = Label::createWithTTF(ttfConfig, "TTF:Shadow"); - shadowLabelOutline->setPosition(Vec2(size.width / 2, horizontalSliderY + step * (0.5f + 2))); - shadowLabelOutline->setTextColor(Color4B::RED); - shadowLabelOutline->enableOutline(Color4B::YELLOW, 1); + shadowLabelOutline = Label::createWithTTF(ttfConfig,"TTF:Shadow"); + shadowLabelOutline->setPosition( Vec2(size.width/2, horizontalSliderY + step * (0.5f + 2)) ); + shadowLabelOutline->setTextColor( Color4B::RED ); + shadowLabelOutline->enableOutline(Color4B::YELLOW,1); shadowLabelOutline->enableShadow(Color4B::GREEN); addChild(shadowLabelOutline); - shadowLabelGrow = Label::createWithTTF(ttfConfig, "TTF:Shadow"); - shadowLabelGrow->setPosition(Vec2(size.width / 2, horizontalSliderY + step * (0.5f + 1))); - shadowLabelGrow->setTextColor(Color4B::RED); + shadowLabelGrow = Label::createWithTTF(ttfConfig,"TTF:Shadow"); + shadowLabelGrow->setPosition( Vec2(size.width/2, horizontalSliderY + step * (0.5f + 1)) ); + shadowLabelGrow->setTextColor( Color4B::RED ); shadowLabelGrow->enableGlow(Color4B::YELLOW); shadowLabelGrow->enableShadow(Color4B::BLUE); addChild(shadowLabelGrow); shadowLabelBMFont = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "BMFont:Shadow"); - shadowLabelBMFont->setPosition(Vec2(size.width / 2, horizontalSliderY + step * 0.5f)); - shadowLabelBMFont->setColor(Color3B::RED); + shadowLabelBMFont->setPosition( Vec2(size.width/2, horizontalSliderY + step * 0.5f)); + shadowLabelBMFont->setColor( Color3B::RED ); shadowLabelBMFont->enableShadow(Color4B::GREEN); addChild(shadowLabelBMFont); } -void LabelShadowTest::sliderEvent(Ref* pSender, ui::Slider::EventType type) +void LabelShadowTest::sliderEvent(Ref *pSender, ui::Slider::EventType type) { if (type == Slider::EventType::ON_PERCENTAGE_CHANGED) { - Slider* slider = (Slider*)this->getChildByTag(1); - Slider* slider2 = (Slider*)this->getChildByTag(2); + Slider* slider = (Slider*)this->getChildByTag(1); + Slider* slider2 = (Slider*)this->getChildByTag(2); - auto offset = Size(slider->getPercent() - 50, 50 - slider2->getPercent()); - shadowLabelTTF->enableShadow(Color4B::BLACK, offset); - shadowLabelBMFont->enableShadow(Color4B::GREEN, offset); - shadowLabelOutline->enableShadow(Color4B::GREEN, offset); - shadowLabelGrow->enableShadow(Color4B::BLUE, offset); + auto offset = Size(slider->getPercent()-50,50 - slider2->getPercent()); + shadowLabelTTF->enableShadow(Color4B::BLACK,offset); + shadowLabelBMFont->enableShadow(Color4B::GREEN,offset); + shadowLabelOutline->enableShadow(Color4B::GREEN,offset); + shadowLabelGrow->enableShadow(Color4B::BLUE,offset); } } @@ -1456,14 +1472,14 @@ LabelCharMapTest::LabelCharMapTest() auto label1 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.plist"); addChild(label1, 0, kTagSprite1); label1->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT); - label1->setPosition(Vec2(10, 100)); - label1->setOpacity(200); + label1->setPosition( Vec2(10,100) ); + label1->setOpacity( 200 ); auto label2 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.plist"); addChild(label2, 0, kTagSprite2); label2->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT); - label2->setPosition(Vec2(10, 200)); - label2->setOpacity(32); + label2->setPosition( Vec2(10,200) ); + label2->setOpacity( 32 ); schedule(CC_CALLBACK_1(LabelCharMapTest::step, this), "step_key"); } @@ -1499,24 +1515,24 @@ std::string LabelCharMapTest::subtitle() const //------------------------------------------------------------------ LabelCharMapColorTest::LabelCharMapColorTest() { - auto label1 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.plist"); + auto label1 = Label::createWithCharMap( "fonts/tuffy_bold_italic-charmap.plist"); addChild(label1, 0, kTagSprite1); label1->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT); - label1->setPosition(Vec2(10, 100)); - label1->setOpacity(200); + label1->setPosition( Vec2(10,100) ); + label1->setOpacity( 200 ); auto label2 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.plist"); addChild(label2, 0, kTagSprite2); label2->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT); - label2->setPosition(Vec2(10, 200)); - label2->setColor(Color3B::RED); + label2->setPosition( Vec2(10,200) ); + label2->setColor( Color3B::RED ); - auto fade = FadeOut::create(1.0f); + auto fade = FadeOut::create(1.0f); auto fade_in = fade->reverse(); - auto cb = CallFunc::create(CC_CALLBACK_0(LabelCharMapColorTest::actionFinishCallback, this)); - auto seq = Sequence::create(fade, fade_in, cb, nullptr); - auto repeat = RepeatForever::create(seq); - label2->runAction(repeat); + auto cb = CallFunc::create(CC_CALLBACK_0(LabelCharMapColorTest::actionFinishCallback, this)); + auto seq = Sequence::create(fade, fade_in, cb, nullptr); + auto repeat = RepeatForever::create( seq ); + label2->runAction( repeat ); _time = 0; @@ -1538,7 +1554,7 @@ void LabelCharMapColorTest::step(float dt) auto label2 = (Label*)getChildByTag(kTagSprite2); sprintf(string, "%d", (int)_time); - label2->setString(string); + label2->setString( string ); } std::string LabelCharMapColorTest::title() const @@ -1555,10 +1571,10 @@ LabelCrashTest::LabelCrashTest() { auto size = Director::getInstance()->getWinSize(); - TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC, nullptr, true); + TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC,nullptr,true); - auto label1 = Label::createWithTTF(ttfConfig, "Test崩溃123", TextHAlignment::CENTER, size.width); - label1->setPosition(Vec2(size.width / 2, size.height / 2)); + auto label1 = Label::createWithTTF(ttfConfig,"Test崩溃123", TextHAlignment::CENTER, size.width); + label1->setPosition( Vec2(size.width/2, size.height/2) ); addChild(label1); } @@ -1574,42 +1590,50 @@ std::string LabelCrashTest::subtitle() const LabelTTFOldNew::LabelTTFOldNew() { - auto s = Director::getInstance()->getWinSize(); - float delta = s.height / 4; + auto s = Director::getInstance()->getWinSize(); + float delta = s.height/4; auto label1 = Label::createWithSystemFont("Cocos2d-x Label Test", "arial", 24); addChild(label1, 0, kTagBitmapAtlas1); - label1->setPosition(Vec2(s.width / 2, delta * 2)); + label1->setPosition(Vec2(s.width/2, delta * 2)); label1->setColor(Color3B::RED); TTFConfig ttfConfig("fonts/arial.ttf", 24); auto label2 = Label::createWithTTF(ttfConfig, "Cocos2d-x Label Test"); addChild(label2, 0, kTagBitmapAtlas2); - label2->setPosition(Vec2(s.width / 2, delta * 2)); + label2->setPosition(Vec2(s.width/2, delta * 2)); - auto drawNode = DrawNode::create(); + auto drawNode = DrawNode::create(); auto labelSize = label1->getContentSize(); auto origin = Director::getInstance()->getWinSize(); - - origin.width = origin.width / 2 - (labelSize.width / 2); + + origin.width = origin.width / 2 - (labelSize.width / 2); origin.height = origin.height / 2 - (labelSize.height / 2); - - Vec2 vertices[4] = {Vec2(origin.width, origin.height), Vec2(labelSize.width + origin.width, origin.height), - Vec2(labelSize.width + origin.width, labelSize.height + origin.height), - Vec2(origin.width, labelSize.height + origin.height)}; + + Vec2 vertices[4]= + { + Vec2(origin.width, origin.height), + Vec2(labelSize.width + origin.width, origin.height), + Vec2(labelSize.width + origin.width, labelSize.height + origin.height), + Vec2(origin.width, labelSize.height + origin.height) + }; drawNode->drawPoly(vertices, 4, true, Color4F(1.0f, 0.0f, 0.0f, 1.0f)); - + labelSize = label2->getContentSize(); origin = Director::getInstance()->getWinSize(); - - origin.width = origin.width / 2 - (labelSize.width / 2); + + origin.width = origin.width / 2 - (labelSize.width / 2); origin.height = origin.height / 2 - (labelSize.height / 2); - - Vec2 vertices2[4] = {Vec2(origin.width, origin.height), Vec2(labelSize.width + origin.width, origin.height), - Vec2(labelSize.width + origin.width, labelSize.height + origin.height), - Vec2(origin.width, labelSize.height + origin.height)}; + + Vec2 vertices2[4]= + { + Vec2(origin.width, origin.height), + Vec2(labelSize.width + origin.width, origin.height), + Vec2(labelSize.width + origin.width, labelSize.height + origin.height), + Vec2(origin.width, labelSize.height + origin.height) + }; drawNode->drawPoly(vertices2, 4, true, Color4F(1.0f, 1.0f, 1.0f, 1.0f)); - + addChild(drawNode); } @@ -1629,11 +1653,11 @@ LabelFontNameTest::LabelFontNameTest() auto label1 = Label::create(); label1->setString("Default Font"); - label1->setPosition(Vec2(size.width / 2, size.height * 0.7)); + label1->setPosition( Vec2(size.width/2, size.height * 0.7) ); addChild(label1); - auto label3 = Label::createWithSystemFont("Marker Felt", "Marker Felt", 32); - label3->setPosition(Vec2(size.width / 2, size.height * 0.5)); + auto label3 = Label::createWithSystemFont("Marker Felt","Marker Felt",32); + label3->setPosition( Vec2(size.width/2, size.height * 0.5) ); addChild(label3); } @@ -1650,9 +1674,9 @@ std::string LabelFontNameTest::subtitle() const LabelAlignmentTest::LabelAlignmentTest() { auto blockSize = Size(200, 160); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); - auto pos = Vec2((s.width - blockSize.width) / 2, (s.height - blockSize.height) / 2); + auto pos = Vec2((s.width - blockSize.width) / 2, (s.height - blockSize.height) / 2); auto colorLayer = LayerColor::create(Color4B(100, 100, 100, 255), blockSize.width, blockSize.height); colorLayer->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT); colorLayer->setPosition(pos); @@ -1663,15 +1687,17 @@ LabelAlignmentTest::LabelAlignmentTest() auto menu = Menu::create( MenuItemFont::create("Left", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentLeft, this)), MenuItemFont::create("Center", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentCenter, this)), - MenuItemFont::create("Right", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentRight, this)), nullptr); + MenuItemFont::create("Right", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentRight, this)), + nullptr); menu->alignItemsVerticallyWithPadding(4); menu->setPosition(Vec2(50.0f, s.height / 2 - 20)); this->addChild(menu); - menu = Menu::create(MenuItemFont::create("Top", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentTop, this)), - MenuItemFont::create("Middle", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentMiddle, this)), - MenuItemFont::create("Bottom", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentBottom, this)), - nullptr); + menu = Menu::create( + MenuItemFont::create("Top", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentTop, this)), + MenuItemFont::create("Middle", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentMiddle, this)), + MenuItemFont::create("Bottom", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentBottom, this)), + nullptr); menu->alignItemsVerticallyWithPadding(4); menu->setPosition(Vec2(s.width - 50, s.height / 2 - 20)); this->addChild(menu); @@ -1728,8 +1754,8 @@ LabelIssue4428Test::LabelIssue4428Test() { auto size = Director::getInstance()->getWinSize(); - auto label = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "123\n456"); - label->setPosition(Vec2(size.width / 2.0f, size.height / 2.0f)); + auto label = Label::createWithBMFont( "fonts/bitmapFontTest3.fnt", "123\n456"); + label->setPosition(Vec2(size.width /2.0f, size.height / 2.0f)); label->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT); addChild(label); @@ -1756,7 +1782,7 @@ std::string LabelIssue4428Test::subtitle() const LabelIssue4999Test::LabelIssue4999Test() { - auto label = Label::createWithTTF("Smaller font test", "fonts/arial.ttf", 5); + auto label = Label::createWithTTF("Smaller font test", "fonts/arial.ttf",5); label->setPosition(VisibleRect::center()); label->setAnchorPoint(Vec2::ANCHOR_MIDDLE); addChild(label); @@ -1776,14 +1802,14 @@ LabelLineHeightTest::LabelLineHeightTest() { auto size = Director::getInstance()->getWinSize(); - auto bg = LayerColor::create(Color4B(200, 191, 231, 255)); + auto bg = LayerColor::create(Color4B(200,191,231,255)); this->addChild(bg); - TTFConfig ttfConfig("fonts/arial.ttf", 25, GlyphCollection::DYNAMIC, nullptr, false); + TTFConfig ttfConfig("fonts/arial.ttf", 25, GlyphCollection::DYNAMIC,nullptr,false); - label = Label::createWithTTF(ttfConfig, "Test\nLine\nHeight"); - label->setPosition(Vec2(size.width / 2, size.height * 0.5f)); - label->setTextColor(Color4B::RED); + label = Label::createWithTTF(ttfConfig,"Test\nLine\nHeight"); + label->setPosition( Vec2(size.width/2, size.height*0.5f) ); + label->setTextColor( Color4B::RED ); addChild(label); auto slider = ui::Slider::create(); @@ -1797,11 +1823,11 @@ LabelLineHeightTest::LabelLineHeightTest() addChild(slider); } -void LabelLineHeightTest::sliderEvent(Ref* sender, ui::Slider::EventType type) +void LabelLineHeightTest::sliderEvent(Ref *sender, ui::Slider::EventType type) { if (type == Slider::EventType::ON_PERCENTAGE_CHANGED) { - Slider* slider = (Slider*)sender; + Slider* slider = (Slider*)sender; label->setLineHeight(slider->getPercent()); } } @@ -1820,14 +1846,14 @@ LabelAdditionalKerningTest::LabelAdditionalKerningTest() { auto size = Director::getInstance()->getWinSize(); - auto bg = LayerColor::create(Color4B(200, 191, 231, 255)); + auto bg = LayerColor::create(Color4B(200,191,231,255)); this->addChild(bg); - TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC, nullptr, false); + TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC,nullptr,false); - label = Label::createWithTTF(ttfConfig, "Test additional kerning"); - label->setPosition(size.width / 2, size.height * 0.5f); - label->setTextColor(Color4B::RED); + label = Label::createWithTTF(ttfConfig,"Test additional kerning"); + label->setPosition(size.width/2, size.height * 0.5f); + label->setTextColor( Color4B::RED ); addChild(label); auto slider = ui::Slider::create(); @@ -1841,11 +1867,11 @@ LabelAdditionalKerningTest::LabelAdditionalKerningTest() addChild(slider); } -void LabelAdditionalKerningTest::sliderEvent(Ref* sender, ui::Slider::EventType type) +void LabelAdditionalKerningTest::sliderEvent(Ref *sender, ui::Slider::EventType type) { if (type == Slider::EventType::ON_PERCENTAGE_CHANGED) { - Slider* slider = (Slider*)sender; + Slider* slider = (Slider*)sender; label->setAdditionalKerning(slider->getPercent()); } } @@ -1863,7 +1889,7 @@ std::string LabelAdditionalKerningTest::subtitle() const LabelIssue8492Test::LabelIssue8492Test() { auto label = Label::createWithBMFont("fonts/bitmapFontChinese.fnt", "中国中国中国中国中国"); - label->setDimensions(5, 100); + label->setDimensions(5,100); label->setPosition(VisibleRect::center()); addChild(label); } @@ -1880,8 +1906,8 @@ std::string LabelIssue8492Test::subtitle() const LabelMultilineWithOutline::LabelMultilineWithOutline() { - auto label = Label::createWithTTF("Multi-line text\nwith\noutline feature", "fonts/arial.ttf", 24); - label->enableOutline(Color4B::ORANGE, 1); + auto label = Label::createWithTTF("Multi-line text\nwith\noutline feature", "fonts/arial.ttf", 24); + label->enableOutline(Color4B::ORANGE,1); label->setPosition(VisibleRect::center()); addChild(label); } @@ -1896,15 +1922,16 @@ std::string LabelMultilineWithOutline::subtitle() const return "end in string 'outline feature'"; } + LabelIssue9255Test::LabelIssue9255Test() { - Size s = Director::getInstance()->getWinSize(); + Size s = Director::getInstance()->getWinSize(); auto parent = Node::create(); - parent->setPosition(s.width / 2, s.height / 2); + parent->setPosition(s.width/2, s.height/2); parent->setVisible(false); this->addChild(parent); - auto label = Label::createWithTTF("Crashed!!!", "fonts/HKYuanMini.ttf", 24); + auto label = Label::createWithTTF("Crashed!!!", "fonts/HKYuanMini.ttf", 24); label->setPosition(VisibleRect::center()); parent->addChild(label); } @@ -1921,7 +1948,7 @@ std::string LabelIssue9255Test::subtitle() const LabelSmallDimensionsTest::LabelSmallDimensionsTest() { - auto label = Label::createWithSystemFont("Hello World!", "fonts/arial.ttf", 24, Size(30.0f, 100.0f)); + auto label = Label::createWithSystemFont("Hello World!", "fonts/arial.ttf", 24, Size(30.0f,100.0f)); label->setPosition(VisibleRect::center()); addChild(label); } @@ -1941,13 +1968,13 @@ LabelIssue10089Test::LabelIssue10089Test() auto center = VisibleRect::center(); auto labelA = Label::createWithSystemFont("create label with system font", "fonts/arial.ttf", 24); - auto size = labelA->getContentSize(); + auto size = labelA->getContentSize(); labelA->setDimensions(size.width, size.height); labelA->setPosition(center.x, center.y + 50); addChild(labelA); auto labelB = Label::createWithTTF("create label with TTF", "fonts/arial.ttf", 24); - size = labelB->getContentSize(); + size = labelB->getContentSize(); labelB->setDimensions(size.width, size.height); labelB->setPosition(center.x, center.y - 50); addChild(labelB); @@ -2029,8 +2056,9 @@ LabelIssue11576Test::LabelIssue11576Test() label->getLetter(index); } - this->runAction(Sequence::create(DelayTime::create(2.0f), - CallFunc::create([label]() { label->setString("Hello World!"); }), nullptr)); + this->runAction(Sequence::create(DelayTime::create(2.0f), CallFunc::create([label](){ + label->setString("Hello World!"); + }), nullptr)); label->setPosition(center.x, center.y); addChild(label); @@ -2077,13 +2105,17 @@ LabelIssue12409Test::LabelIssue12409Test() addChild(label); auto labelSize = label->getContentSize(); - auto winSize = Director::getInstance()->getWinSize(); + auto winSize = Director::getInstance()->getWinSize(); Vec2 labelOrigin; - labelOrigin.x = winSize.width / 2 - (labelSize.width / 2); - labelOrigin.y = winSize.height / 2 - (labelSize.height / 2); - Vec2 vertices[4] = {Vec2(labelOrigin.x, labelOrigin.y), Vec2(labelOrigin.x + labelSize.width, labelOrigin.y), - Vec2(labelOrigin.x + labelSize.width, labelOrigin.y + labelSize.height), - Vec2(labelOrigin.x, labelOrigin.y + labelSize.height)}; + labelOrigin.x = winSize.width / 2 - (labelSize.width / 2); + labelOrigin.y = winSize.height / 2 - (labelSize.height / 2); + Vec2 vertices[4] = + { + Vec2(labelOrigin.x, labelOrigin.y), + Vec2(labelOrigin.x + labelSize.width, labelOrigin.y), + Vec2(labelOrigin.x + labelSize.width, labelOrigin.y + labelSize.height), + Vec2(labelOrigin.x, labelOrigin.y + labelSize.height) + }; auto drawNode = DrawNode::create(); drawNode->drawPoly(vertices, 4, true, Color4F::WHITE); @@ -2108,13 +2140,13 @@ LabelAddChildTest::LabelAddChildTest() label->setPosition(center.x, center.y); addChild(label); - auto jump = JumpBy::create(1.0f, Vec2::ZERO, 60, 1); + auto jump = JumpBy::create(1.0f, Vec2::ZERO, 60, 1); auto jump_4ever = RepeatForever::create(jump); label->runAction(jump_4ever); auto spite = Sprite::create("Images/SpookyPeas.png"); spite->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT); - spite->setPosition(label->getContentSize().width, label->getContentSize().height / 2); + spite->setPosition(label->getContentSize().width, label->getContentSize().height/2); label->addChild(spite); } @@ -2153,7 +2185,8 @@ LabelIssue11585Test::LabelIssue11585Test() label->getLetter(0)->setColor(Color3B::RED); label->getLetter(1)->setColor(Color3B::GREEN); label->getLetter(2)->setColor(Color3B::BLUE); - auto action = RepeatForever::create(Sequence::create(FadeOut::create(2), FadeIn::create(2), nullptr)); + auto action = RepeatForever::create(Sequence::create( + FadeOut::create(2), FadeIn::create(2),nullptr)); label->runAction(action); } @@ -2174,9 +2207,9 @@ LabelIssue10688Test::LabelIssue10688Test() auto label = Label::createWithTTF("Glow MenuItemLabel", "fonts/arial.ttf", 30); label->setTextColor(Color4B::RED); label->enableGlow(Color4B::YELLOW); - auto menuItem1 = MenuItemLabel::create(label, [](Ref*) {}); + auto menuItem1 = MenuItemLabel::create(label, [](Ref*){}); menuItem1->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT); - menuItem1->setPosition(center.x - label->getContentSize().width / 2, center.y); + menuItem1->setPosition(center.x - label->getContentSize().width/2, center.y); auto menu = Menu::create(menuItem1, NULL); menu->setPosition(Vec2::ZERO); @@ -2203,7 +2236,9 @@ LabelIssue13202Test::LabelIssue13202Test() label->getContentSize(); label->setString("A"); - this->scheduleOnce([](float dt) { FontAtlasCache::purgeCachedData(); }, 0.15f, "FontAtlasCache::purgeCachedData"); + this->scheduleOnce([](float dt){ + FontAtlasCache::purgeCachedData(); + }, 0.15f, "FontAtlasCache::purgeCachedData"); } std::string LabelIssue13202Test::title() const @@ -2235,18 +2270,18 @@ std::string LabelIssue9500Test::subtitle() const return "Spaces should not be lost if label created with Fingerpop.ttf"; } -ControlStepper* LabelLayoutBaseTest::makeControlStepper() +ControlStepper *LabelLayoutBaseTest::makeControlStepper() { - auto minusSprite = Sprite::create("extensions/stepper-minus.png"); - auto plusSprite = Sprite::create("extensions/stepper-plus.png"); - + auto minusSprite = Sprite::create("extensions/stepper-minus.png"); + auto plusSprite = Sprite::create("extensions/stepper-plus.png"); + return ControlStepper::create(minusSprite, plusSprite); } LabelLayoutBaseTest::LabelLayoutBaseTest() { auto size = Director::getInstance()->getVisibleSize(); - + this->initTestLabel(size); this->initFontSizeChange(size); @@ -2266,18 +2301,19 @@ void LabelLayoutBaseTest::initFontSizeChange(const cocos2d::Size& size) auto fontSizeLabel = Label::createWithSystemFont("font size:20", "Arial", 10); fontSizeLabel->setName("fontSize"); - ControlStepper* stepper = this->makeControlStepper(); - stepper->setPosition(size.width * 0.5 - stepper->getContentSize().width / 2, size.height * 0.8); + ControlStepper *stepper = this->makeControlStepper(); + stepper->setPosition(size.width * 0.5 - stepper->getContentSize().width / 2, + size.height * 0.8); stepper->setValue(20); - stepper->addTargetWithActionForControlEvents(this, cccontrol_selector(LabelLayoutBaseTest::valueChanged), + stepper->addTargetWithActionForControlEvents(this, + cccontrol_selector(LabelLayoutBaseTest::valueChanged), Control::EventType::VALUE_CHANGED); this->addChild(stepper); stepper->setName("stepper"); stepper->setScale(0.5); - fontSizeLabel->setPosition( - stepper->getPosition() - - Vec2(stepper->getContentSize().width / 2 + fontSizeLabel->getContentSize().width / 2, 0.0f)); + fontSizeLabel->setPosition(stepper->getPosition() - + Vec2(stepper->getContentSize().width/2 + fontSizeLabel->getContentSize().width/2,0.0f)); this->addChild(fontSizeLabel); } @@ -2288,21 +2324,20 @@ void LabelLayoutBaseTest::initWrapOption(const cocos2d::Size& size) label->setPosition(Vec2(size.width * 0.8f - 100, size.height * 0.8f)); this->addChild(label); - CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", "cocosui/check_box_normal_press.png", - "cocosui/check_box_active.png", "cocosui/check_box_normal_disable.png", + CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", + "cocosui/check_box_normal_press.png", + "cocosui/check_box_active.png", + "cocosui/check_box_normal_disable.png", "cocosui/check_box_active_disable.png"); checkBox->setPosition(Vec2(size.width * 0.8f - 55, size.height * 0.8f)); checkBox->setScale(0.5); checkBox->setSelected(true); checkBox->setName("toggleWrap"); - checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event) { - if (event == CheckBox::EventType::SELECTED) - { + checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event){ + if (event == CheckBox::EventType::SELECTED) { _label->enableWrap(true); - } - else - { + }else{ _label->enableWrap(false); } this->updateDrawNodeSize(_label->getContentSize()); @@ -2316,53 +2351,55 @@ void LabelLayoutBaseTest::initToggleLabelTypeOption(const cocos2d::Size& size) label->setColor(Color3B::WHITE); label->setPosition(Vec2(size.width * 0.8f + 15, size.height * 0.8f)); this->addChild(label); - - CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", "cocosui/check_box_normal_press.png", - "cocosui/check_box_active.png", "cocosui/check_box_normal_disable.png", + + CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", + "cocosui/check_box_normal_press.png", + "cocosui/check_box_active.png", + "cocosui/check_box_normal_disable.png", "cocosui/check_box_active_disable.png"); checkBox->setPosition(Vec2(size.width * 0.8f + 70, size.height * 0.8f)); checkBox->setScale(0.5); checkBox->setName("toggleType"); checkBox->setSelected(true); - auto stepper = (ControlStepper*)this->getChildByName("stepper"); + auto stepper = (ControlStepper*)this->getChildByName("stepper"); - checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event) { - float fontSize = stepper->getValue(); + checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event){ + float fontSize = stepper->getValue(); - if (event == CheckBox::EventType::SELECTED) - { - _labelType = 0; - auto ttfConfig = _label->getTTFConfig(); + if (event == CheckBox::EventType::SELECTED) { + _labelType = 0; + auto ttfConfig = _label->getTTFConfig(); ttfConfig.fontSize = fontSize; _label->setTTFConfig(ttfConfig); - } - else - { + }else{ _labelType = 1; _label->setBMFontFilePath("fonts/enligsh-chinese.fnt"); _label->setBMFontSize(fontSize); } }); this->addChild(checkBox); + } void LabelLayoutBaseTest::initAlignmentOption(const cocos2d::Size& size) { - // add text alignment settings + //add text alignment settings MenuItemFont::setFontSize(30); auto menu = Menu::create( MenuItemFont::create("Left", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentLeft, this)), MenuItemFont::create("Center", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentCenter, this)), - MenuItemFont::create("Right", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentRight, this)), nullptr); + MenuItemFont::create("Right", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentRight, this)), + nullptr); menu->alignItemsVerticallyWithPadding(4); menu->setPosition(Vec2(50.0f, size.height / 2 - 20)); this->addChild(menu); - menu = Menu::create(MenuItemFont::create("Top", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentTop, this)), - MenuItemFont::create("Middle", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentMiddle, this)), - MenuItemFont::create("Bottom", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentBottom, this)), - nullptr); + menu = Menu::create( + MenuItemFont::create("Top", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentTop, this)), + MenuItemFont::create("Middle", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentMiddle, this)), + MenuItemFont::create("Bottom", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentBottom, this)), + nullptr); menu->alignItemsVerticallyWithPadding(4); menu->setPosition(Vec2(size.width - 50, size.height / 2 - 20)); this->addChild(menu); @@ -2392,24 +2429,22 @@ void LabelLayoutBaseTest::initSliders(const cocos2d::Size& size) addChild(slider2); auto winSize = Director::getInstance()->getVisibleSize(); - slider->addEventListener([=](Ref* ref, Slider::EventType event) { - float percent = slider->getPercent(); - auto labelSize = _label->getContentSize(); + slider->addEventListener([=](Ref* ref, Slider::EventType event){ + float percent = slider->getPercent(); + auto labelSize = _label->getContentSize(); auto drawNodeSize = Size(percent / 100.0 * winSize.width, labelSize.height); - if (drawNodeSize.width <= 0) - { + if(drawNodeSize.width <=0){ drawNodeSize.width = 0.1f; } _label->setDimensions(drawNodeSize.width, drawNodeSize.height); this->updateDrawNodeSize(drawNodeSize); }); - slider2->addEventListener([=](Ref* ref, Slider::EventType event) { - float percent = slider2->getPercent(); - auto labelSize = _label->getContentSize(); - auto drawNodeSize = Size(labelSize.width, percent / 100.0 * winSize.height); - if (drawNodeSize.height <= 0) - { + slider2->addEventListener([=](Ref* ref, Slider::EventType event){ + float percent = slider2->getPercent(); + auto labelSize = _label->getContentSize(); + auto drawNodeSize = Size( labelSize.width, percent / 100.0 * winSize.height); + if(drawNodeSize.height <= 0){ drawNodeSize.height = 0.1f; } _label->setDimensions(drawNodeSize.width, drawNodeSize.height); @@ -2421,7 +2456,7 @@ void LabelLayoutBaseTest::initTestLabel(const cocos2d::Size& size) { auto center = VisibleRect::center(); _label = Label::createWithTTF("五六七八This is a very long sentence一二三四.", "fonts/HKYuanMini.ttf", 20); - _label->setDimensions(size.width / 2, size.height / 2); + _label->setDimensions(size.width/2, size.height/2); _label->setPosition(center); _label->setName("Label"); _label->setString("五六七八This is a very long sentence一二三."); @@ -2438,6 +2473,7 @@ void LabelLayoutBaseTest::initDrawNode(const cocos2d::Size& size) this->updateDrawNodeSize(_label->getContentSize()); } + void LabelLayoutBaseTest::setAlignmentLeft(Ref* sender) { _label->setHorizontalAlignment(TextHAlignment::LEFT); @@ -2468,55 +2504,56 @@ void LabelLayoutBaseTest::setAlignmentBottom(Ref* sender) _label->setVerticalAlignment(TextVAlignment::BOTTOM); } -void LabelLayoutBaseTest::valueChanged(cocos2d::Ref* sender, cocos2d::extension::Control::EventType controlEvent) + +void LabelLayoutBaseTest::valueChanged(cocos2d::Ref *sender, cocos2d::extension::Control::EventType controlEvent) { ControlStepper* pControl = (ControlStepper*)sender; // Change value of label. auto fontSizeLabel = (Label*)this->getChildByName("fontSize"); - float fontSize = (float)pControl->getValue(); + float fontSize = (float)pControl->getValue(); fontSizeLabel->setString(StringUtils::format("font size:%d", (int)fontSize)); - - if (_labelType == 0) - { - auto ttfConfig = _label->getTTFConfig(); + + if (_labelType == 0) { + auto ttfConfig = _label->getTTFConfig(); ttfConfig.fontSize = fontSize; _label->setTTFConfig(ttfConfig); - } - else if (_labelType == 1) - { + }else if(_labelType == 1){ _label->setBMFontSize(fontSize); - } - else if (_labelType == 2) - { + }else if (_labelType == 2) { _label->setSystemFontSize(fontSize); } this->updateDrawNodeSize(_label->getContentSize()); - - // FIXME::When calling getLetter, the label Overflow feature will be invalid. - // auto letterSprite = _label->getLetter(1); - // auto moveBy = ScaleBy::create(1.0,2.0); - // letterSprite->stopAllActions(); - // letterSprite->runAction(Sequence::create(moveBy, moveBy->clone()->reverse(), nullptr )); - // - // CCLOG("label line height = %f", _label->getLineHeight()); + + //FIXME::When calling getLetter, the label Overflow feature will be invalid. +// auto letterSprite = _label->getLetter(1); +// auto moveBy = ScaleBy::create(1.0,2.0); +// letterSprite->stopAllActions(); +// letterSprite->runAction(Sequence::create(moveBy, moveBy->clone()->reverse(), nullptr )); +// +// CCLOG("label line height = %f", _label->getLineHeight()); } -void LabelLayoutBaseTest::updateDrawNodeSize(const cocos2d::Size& drawNodeSize) +void LabelLayoutBaseTest::updateDrawNodeSize(const cocos2d::Size &drawNodeSize) { auto origin = Director::getInstance()->getWinSize(); auto labelSize = _label->getContentSize(); - origin.width = origin.width / 2 - (labelSize.width / 2); + origin.width = origin.width / 2 - (labelSize.width / 2); origin.height = origin.height / 2 - (labelSize.height / 2); - Vec2 vertices[4] = {Vec2(origin.width, origin.height), Vec2(drawNodeSize.width + origin.width, origin.height), - Vec2(drawNodeSize.width + origin.width, drawNodeSize.height + origin.height), - Vec2(origin.width, drawNodeSize.height + origin.height)}; + Vec2 vertices[4]= + { + Vec2(origin.width, origin.height), + Vec2(drawNodeSize.width + origin.width, origin.height), + Vec2(drawNodeSize.width + origin.width, drawNodeSize.height + origin.height), + Vec2(origin.width, drawNodeSize.height + origin.height) + }; _drawNode->clear(); _drawNode->drawLine(vertices[0], vertices[1], Color4F(1.0f, 1.0f, 1.0f, 1.0f)); _drawNode->drawLine(vertices[0], vertices[3], Color4F(1.0f, 1.0f, 1.0f, 1.0f)); _drawNode->drawLine(vertices[2], vertices[3], Color4F(1.0f, 1.0f, 1.0f, 1.0f)); _drawNode->drawLine(vertices[1], vertices[2], Color4F(1.0f, 1.0f, 1.0f, 1.0f)); + } LabelWrapByWordTest::LabelWrapByWordTest() @@ -2525,6 +2562,7 @@ LabelWrapByWordTest::LabelWrapByWordTest() _label->setAdditionalKerning(2); _label->setVerticalAlignment(TextVAlignment::CENTER); _label->setOverflow(Label::Overflow::CLAMP); + } std::string LabelWrapByWordTest::title() const @@ -2539,12 +2577,13 @@ std::string LabelWrapByWordTest::subtitle() const LabelWrapByCharTest::LabelWrapByCharTest() { - _label->setLineBreakWithoutSpace(true); + _label->setLineBreakWithoutSpace(true); _label->setString("五六七八This \nis a very long sentence一二三四."); _label->setLineSpacing(5); _label->setAdditionalKerning(2); _label->setVerticalAlignment(TextVAlignment::TOP); _label->setOverflow(Label::Overflow::CLAMP); + } std::string LabelWrapByCharTest::title() const @@ -2562,9 +2601,8 @@ std::string LabelWrapByCharTest::subtitle() const LabelWrapNoBreakSpaceTest::LabelWrapNoBreakSpaceTest() { _label->setLineBreakWithoutSpace(false); - const char* no_break_space_utf8 = "\xC2\xA0"; // 0xA0 - no-break space - auto str = StringUtils::format( - "The price is $%s1.25. \n\nthe space between \"$\" and \"1.25\" is a no break space.", no_break_space_utf8); + const char* no_break_space_utf8 = "\xC2\xA0"; // 0xA0 - no-break space + auto str = StringUtils::format("The price is $%s1.25. \n\nthe space between \"$\" and \"1.25\" is a no break space.", no_break_space_utf8); _label->setString(str); _label->setVerticalAlignment(TextVAlignment::TOP); _label->setOverflow(Label::Overflow::CLAMP); @@ -2628,19 +2666,19 @@ LabelResizeTest::LabelResizeTest() _label->setVerticalAlignment(TextVAlignment::TOP); _label->setOverflow(Label::Overflow::RESIZE_HEIGHT); + this->updateDrawNodeSize(_label->getContentSize()); auto slider1 = (ui::Slider*)this->getChildByTag(1); - auto slider2 = (ui::Slider*)this->getChildByTag(2); - slider2->setVisible(false); - + auto slider2 = (ui::Slider*)this->getChildByTag(2); + slider2->setVisible(false); + auto winSize = Director::getInstance()->getVisibleSize(); - slider1->addEventListener([=](Ref* ref, Slider::EventType event) { - float percent = slider1->getPercent(); - auto drawNodeSize = Size(percent / 100.0 * winSize.width, _label->getContentSize().height); - if (drawNodeSize.height <= 0) - { + slider1->addEventListener([=](Ref* ref, Slider::EventType event){ + float percent = slider1->getPercent(); + auto drawNodeSize = Size(percent / 100.0 * winSize.width,_label->getContentSize().height); + if(drawNodeSize.height <= 0){ drawNodeSize.height = 0.1f; } _label->setDimensions(drawNodeSize.width, drawNodeSize.height); @@ -2649,32 +2687,32 @@ LabelResizeTest::LabelResizeTest() auto stepper = (ControlStepper*)this->getChildByName("stepper"); stepper->setValue(12); - + auto label = Label::createWithSystemFont("Char Line break:", "Arial", 10); label->setColor(Color3B::WHITE); label->setPosition(Vec2(winSize.width * 0.1f, winSize.height * 0.8f)); this->addChild(label); - - CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", "cocosui/check_box_normal_press.png", - "cocosui/check_box_active.png", "cocosui/check_box_normal_disable.png", + + CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", + "cocosui/check_box_normal_press.png", + "cocosui/check_box_active.png", + "cocosui/check_box_normal_disable.png", "cocosui/check_box_active_disable.png"); - checkBox->setPosition(Vec2(winSize.width * 0.2f, winSize.height * 0.8f)); + checkBox->setPosition(Vec2(winSize.width * 0.2f , winSize.height * 0.8f)); checkBox->setScale(0.5); checkBox->setSelected(false); checkBox->setName("LineBreak"); - - checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event) { - if (event == CheckBox::EventType::SELECTED) - { + + checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event){ + if (event == CheckBox::EventType::SELECTED) { _label->setLineBreakWithoutSpace(true); - } - else - { + }else{ _label->setLineBreakWithoutSpace(false); } this->updateDrawNodeSize(_label->getContentSize()); }); this->addChild(checkBox); + } std::string LabelResizeTest::title() const @@ -2694,19 +2732,19 @@ LabelToggleTypeTest::LabelToggleTypeTest() _label->setVerticalAlignment(TextVAlignment::CENTER); _label->setOverflow(Label::Overflow::NONE); + this->updateDrawNodeSize(_label->getContentSize()); auto slider1 = (ui::Slider*)this->getChildByTag(1); - auto slider2 = (ui::Slider*)this->getChildByTag(2); - slider2->setVisible(false); + auto slider2 = (ui::Slider*)this->getChildByTag(2); + slider2->setVisible(false); auto winSize = Director::getInstance()->getVisibleSize(); - slider1->addEventListener([=](Ref* ref, Slider::EventType event) { - float percent = slider1->getPercent(); - auto drawNodeSize = Size(percent / 100.0 * winSize.width, _label->getContentSize().height); - if (drawNodeSize.height <= 0) - { + slider1->addEventListener([=](Ref* ref, Slider::EventType event){ + float percent = slider1->getPercent(); + auto drawNodeSize = Size(percent / 100.0 * winSize.width,_label->getContentSize().height); + if(drawNodeSize.height <= 0){ drawNodeSize.height = 0.1f; } _label->setDimensions(drawNodeSize.width, drawNodeSize.height); @@ -2721,21 +2759,20 @@ LabelToggleTypeTest::LabelToggleTypeTest() label->setPosition(Vec2(winSize.width * 0.1f, winSize.height * 0.8f)); this->addChild(label); - CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", "cocosui/check_box_normal_press.png", - "cocosui/check_box_active.png", "cocosui/check_box_normal_disable.png", + CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", + "cocosui/check_box_normal_press.png", + "cocosui/check_box_active.png", + "cocosui/check_box_normal_disable.png", "cocosui/check_box_active_disable.png"); - checkBox->setPosition(Vec2(winSize.width * 0.2f, winSize.height * 0.8f)); + checkBox->setPosition(Vec2(winSize.width * 0.2f , winSize.height * 0.8f)); checkBox->setScale(0.5); checkBox->setSelected(false); checkBox->setName("LineBreak"); - checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event) { - if (event == CheckBox::EventType::SELECTED) - { + checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event){ + if (event == CheckBox::EventType::SELECTED) { _label->setLineBreakWithoutSpace(true); - } - else - { + }else{ _label->setLineBreakWithoutSpace(false); } this->updateDrawNodeSize(_label->getContentSize()); @@ -2748,32 +2785,32 @@ LabelToggleTypeTest::LabelToggleTypeTest() void LabelToggleTypeTest::initToggleCheckboxes() { const float BUTTON_WIDTH = 100; - float startPosX = 0; - Size winSize = Director::getInstance()->getVisibleSize(); + float startPosX = 0; + Size winSize = Director::getInstance()->getVisibleSize(); // Create a radio button group auto radioButtonGroup = RadioButtonGroup::create(); this->addChild(radioButtonGroup); // Create the radio buttons - static const int NUMBER_OF_BUTTONS = 4; - startPosX = winSize.width / 2.0f - (NUMBER_OF_BUTTONS - 1) * 0.5 * BUTTON_WIDTH - 30; + static const int NUMBER_OF_BUTTONS = 4; + startPosX = winSize.width / 2.0f - (NUMBER_OF_BUTTONS - 1 ) * 0.5 * BUTTON_WIDTH - 30; std::vector labelTypes = {"Normal", "Clamp", "Shrink", "RESIZE"}; - - for (int i = 0; i < NUMBER_OF_BUTTONS; ++i) + + for(int i = 0; i < NUMBER_OF_BUTTONS; ++i) { RadioButton* radioButton = RadioButton::create("cocosui/radio_button_off.png", "cocosui/radio_button_on.png"); - float posX = startPosX + BUTTON_WIDTH * i; + float posX = startPosX + BUTTON_WIDTH * i; radioButton->setPosition(Vec2(posX, winSize.height / 2.0f + 70)); radioButton->setScale(1.2f); radioButton->addEventListener(CC_CALLBACK_2(LabelToggleTypeTest::onChangedRadioButtonSelect, this)); radioButton->setTag(i); radioButtonGroup->addRadioButton(radioButton); this->addChild(radioButton); - + auto label = Label::createWithSystemFont(labelTypes.at(i), "Arial", 20); - label->setPosition(radioButton->getPosition() + Vec2(50.0f, 0.0f)); + label->setPosition(radioButton->getPosition() + Vec2(50.0f,0.0f)); this->addChild(label); } } @@ -2788,33 +2825,33 @@ std::string LabelToggleTypeTest::subtitle() const return ""; } + void LabelToggleTypeTest::onChangedRadioButtonSelect(RadioButton* radioButton, RadioButton::EventType type) { - if (radioButton == nullptr) + if(radioButton == nullptr) { return; } - + switch (type) { case RadioButton::EventType::SELECTED: { - switch (radioButton->getTag()) - { - case 0: - _label->setOverflow(Label::Overflow::NONE); - break; - case 1: - _label->setOverflow(Label::Overflow::CLAMP); - break; - case 2: - _label->setOverflow(Label::Overflow::SHRINK); - break; - case 3: - _label->setOverflow(Label::Overflow::RESIZE_HEIGHT); - break; - default: - break; + switch (radioButton->getTag()) { + case 0: + _label->setOverflow(Label::Overflow::NONE); + break; + case 1: + _label->setOverflow(Label::Overflow::CLAMP); + break; + case 2: + _label->setOverflow(Label::Overflow::SHRINK); + break; + case 3: + _label->setOverflow(Label::Overflow::RESIZE_HEIGHT); + break; + default: + break; } break; } @@ -2836,10 +2873,10 @@ LabelSystemFontTest::LabelSystemFontTest() _label->enableOutline(Color4B::RED, 1.0); _label->setString("This is a very\n 我爱你中国\n long sentence"); _labelType = 2; - + auto stepper = (ControlStepper*)this->getChildByName("stepper"); stepper->setEnabled(true); - + auto checkbox = (CheckBox*)(this->getChildByName("toggleType")); checkbox->setEnabled(false); @@ -2848,37 +2885,36 @@ LabelSystemFontTest::LabelSystemFontTest() auto slider1 = (ui::Slider*)this->getChildByTag(1); auto winSize = Director::getInstance()->getVisibleSize(); - slider1->addEventListener([=](Ref* ref, Slider::EventType event) { - float percent = slider1->getPercent(); - auto drawNodeSize = Size(percent / 100.0 * winSize.width, _label->getContentSize().height); - if (drawNodeSize.height <= 0) - { + slider1->addEventListener([=](Ref* ref, Slider::EventType event){ + float percent = slider1->getPercent(); + auto drawNodeSize = Size(percent / 100.0 * winSize.width,_label->getContentSize().height); + if(drawNodeSize.height <= 0){ drawNodeSize.height = 0.1f; } _label->setDimensions(drawNodeSize.width, drawNodeSize.height); this->updateDrawNodeSize(drawNodeSize); }); + auto label = Label::createWithSystemFont("char Line break:", "Arial", 10); label->setColor(Color3B::WHITE); label->setPosition(Vec2(winSize.width * 0.1f, winSize.height * 0.8f)); this->addChild(label); - CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", "cocosui/check_box_normal_press.png", - "cocosui/check_box_active.png", "cocosui/check_box_normal_disable.png", + CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", + "cocosui/check_box_normal_press.png", + "cocosui/check_box_active.png", + "cocosui/check_box_normal_disable.png", "cocosui/check_box_active_disable.png"); - checkBox->setPosition(Vec2(winSize.width * 0.2f, winSize.height * 0.8f)); + checkBox->setPosition(Vec2(winSize.width * 0.2f , winSize.height * 0.8f)); checkBox->setScale(0.5); checkBox->setSelected(false); checkBox->setName("LineBreak"); - checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event) { - if (event == CheckBox::EventType::SELECTED) - { + checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event){ + if (event == CheckBox::EventType::SELECTED) { _label->setLineBreakWithoutSpace(true); - } - else - { + }else{ _label->setLineBreakWithoutSpace(false); } this->updateDrawNodeSize(_label->getContentSize()); @@ -2894,23 +2930,23 @@ LabelSystemFontTest::LabelSystemFontTest() void LabelSystemFontTest::initToggleCheckboxes() { const float BUTTON_WIDTH = 100; - float startPosX = 0; - Size winSize = Director::getInstance()->getVisibleSize(); + float startPosX = 0; + Size winSize = Director::getInstance()->getVisibleSize(); // Create a radio button group auto radioButtonGroup = RadioButtonGroup::create(); this->addChild(radioButtonGroup); // Create the radio buttons - static const int NUMBER_OF_BUTTONS = 4; - startPosX = winSize.width / 2.0f - (NUMBER_OF_BUTTONS - 1) * 0.5 * BUTTON_WIDTH - 30; + static const int NUMBER_OF_BUTTONS = 4; + startPosX = winSize.width / 2.0f - (NUMBER_OF_BUTTONS - 1 ) * 0.5 * BUTTON_WIDTH - 30; std::vector labelTypes = {"Normal", "Clamp", "Shrink", "RESIZE"}; - for (int i = 0; i < NUMBER_OF_BUTTONS; ++i) + for(int i = 0; i < NUMBER_OF_BUTTONS; ++i) { RadioButton* radioButton = RadioButton::create("cocosui/radio_button_off.png", "cocosui/radio_button_on.png"); - float posX = startPosX + BUTTON_WIDTH * i; + float posX = startPosX + BUTTON_WIDTH * i; radioButton->setPosition(Vec2(posX, winSize.height / 2.0f + 70)); radioButton->setScale(1.2f); radioButton->addEventListener(CC_CALLBACK_2(LabelSystemFontTest::onChangedRadioButtonSelect, this)); @@ -2919,7 +2955,7 @@ void LabelSystemFontTest::initToggleCheckboxes() this->addChild(radioButton); auto label = Label::createWithSystemFont(labelTypes.at(i), "Arial", 20); - label->setPosition(radioButton->getPosition() + Vec2(50.0f, 0.0f)); + label->setPosition(radioButton->getPosition() + Vec2(50.0f,0.0f)); this->addChild(label); } } @@ -2934,9 +2970,10 @@ std::string LabelSystemFontTest::subtitle() const return ""; } + void LabelSystemFontTest::onChangedRadioButtonSelect(RadioButton* radioButton, RadioButton::EventType type) { - if (radioButton == nullptr) + if(radioButton == nullptr) { return; } @@ -2945,22 +2982,21 @@ void LabelSystemFontTest::onChangedRadioButtonSelect(RadioButton* radioButton, R { case RadioButton::EventType::SELECTED: { - switch (radioButton->getTag()) - { - case 0: - _label->setOverflow(Label::Overflow::NONE); - break; - case 1: - _label->setOverflow(Label::Overflow::CLAMP); - break; - case 2: - _label->setOverflow(Label::Overflow::SHRINK); - break; - case 3: - _label->setOverflow(Label::Overflow::RESIZE_HEIGHT); - break; - default: - break; + switch (radioButton->getTag()) { + case 0: + _label->setOverflow(Label::Overflow::NONE); + break; + case 1: + _label->setOverflow(Label::Overflow::CLAMP); + break; + case 2: + _label->setOverflow(Label::Overflow::SHRINK); + break; + case 3: + _label->setOverflow(Label::Overflow::RESIZE_HEIGHT); + break; + default: + break; } break; } @@ -2986,8 +3022,10 @@ LabelCharMapFontTest::LabelCharMapFontTest() checkbox->setEnabled(false); this->updateDrawNodeSize(_label->getContentSize()); + } + std::string LabelCharMapFontTest::title() const { return "CharMap Font Test"; @@ -3001,11 +3039,11 @@ std::string LabelCharMapFontTest::subtitle() const LabelIssue13846Test::LabelIssue13846Test() { auto center = VisibleRect::center(); - + auto label = Label::createWithTTF("12345", "fonts/arial.ttf", 26); label->setPosition(center); addChild(label); - + label->getLetter(2)->setVisible(false); } @@ -3026,8 +3064,7 @@ LabelRichText::LabelRichText() { auto center = VisibleRect::center(); - auto richText2 = RichText::createWithXML( - "Mixing UIRichText with non UIWidget code. For more samples, see the UIRichTextTest.cpp file"); + auto richText2 = RichText::createWithXML("Mixing UIRichText with non UIWidget code. For more samples, see the UIRichTextTest.cpp file"); if (richText2) { richText2->ignoreContentAdaptWithSize(false); @@ -3053,29 +3090,29 @@ LabelItalics::LabelItalics() auto s = Director::getInstance()->getWinSize(); // LabelBMFont - auto label1 = - Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "hello non-italics", TextHAlignment::CENTER, s.width); + auto label1 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "hello non-italics", TextHAlignment::CENTER, s.width); addChild(label1, 0, kTagBitmapAtlas1); - label1->setPosition(Vec2(s.width / 2, s.height * 4 / 6)); + label1->setPosition(Vec2(s.width/2, s.height*4/6)); // you can enable italics by calling this method _label1a = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "hello italics", TextHAlignment::CENTER, s.width); addChild(_label1a, 0, kTagBitmapAtlas1); - _label1a->setPosition(Vec2(s.width / 2, s.height * 3 / 6)); + _label1a->setPosition(Vec2(s.width/2, s.height*3/6)); // you can enable italics by calling this method _label1a->enableItalics(); + // LabelTTF - TTFConfig ttfConfig("fonts/arial.ttf", 24); - auto label2 = Label::createWithTTF(ttfConfig, "hello non-italics", TextHAlignment::CENTER, s.width); + TTFConfig ttfConfig("fonts/arial.ttf",24); + auto label2 = Label::createWithTTF(ttfConfig, "hello non-italics", TextHAlignment::CENTER,s.width); addChild(label2, 0, kTagBitmapAtlas2); - label2->setPosition(Vec2(s.width / 2, s.height * 2 / 6)); + label2->setPosition(Vec2(s.width/2, s.height*2/6)); // or by setting the italics parameter on TTFConfig ttfConfig.italics = true; - _label2a = Label::createWithTTF(ttfConfig, "hello italics", TextHAlignment::CENTER, s.width); + _label2a = Label::createWithTTF(ttfConfig, "hello italics", TextHAlignment::CENTER,s.width); addChild(_label2a, 0, kTagBitmapAtlas2); - _label2a->setPosition(Vec2(s.width / 2, s.height * 1 / 6)); + _label2a->setPosition(Vec2(s.width/2, s.height*1/6)); auto menuItem = MenuItemFont::create("disable italics", [&](cocos2d::Ref* sender) { _label2a->disableEffect(LabelEffect::ITALICS); @@ -3105,29 +3142,29 @@ LabelBold::LabelBold() auto s = Director::getInstance()->getWinSize(); // LabelBMFont - auto label1 = - Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "hello non-bold", TextHAlignment::CENTER, s.width); + auto label1 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "hello non-bold", TextHAlignment::CENTER, s.width); addChild(label1, 0, kTagBitmapAtlas1); - label1->setPosition(Vec2(s.width / 2, s.height * 4 / 6)); + label1->setPosition(Vec2(s.width/2, s.height*4/6)); // you can enable italics by calling this method _label1a = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "hello bold", TextHAlignment::CENTER, s.width); addChild(_label1a, 0, kTagBitmapAtlas1); - _label1a->setPosition(Vec2(s.width / 2, s.height * 3 / 6)); + _label1a->setPosition(Vec2(s.width/2, s.height*3/6)); // you can enable italics by calling this method _label1a->enableBold(); + // LabelTTF - TTFConfig ttfConfig("fonts/arial.ttf", 24); - auto label2 = Label::createWithTTF(ttfConfig, "hello non-bold", TextHAlignment::CENTER, s.width); + TTFConfig ttfConfig("fonts/arial.ttf",24); + auto label2 = Label::createWithTTF(ttfConfig, "hello non-bold", TextHAlignment::CENTER,s.width); addChild(label2, 0, kTagBitmapAtlas2); - label2->setPosition(Vec2(s.width / 2, s.height * 2 / 6)); + label2->setPosition(Vec2(s.width/2, s.height*2/6)); // or by setting the italics parameter on TTFConfig ttfConfig.bold = true; - _label2a = Label::createWithTTF(ttfConfig, "hello bold", TextHAlignment::CENTER, s.width); + _label2a = Label::createWithTTF(ttfConfig, "hello bold", TextHAlignment::CENTER,s.width); addChild(_label2a, 0, kTagBitmapAtlas2); - _label2a->setPosition(Vec2(s.width / 2, s.height * 1 / 6)); + _label2a->setPosition(Vec2(s.width/2, s.height*1/6)); auto menuItem = MenuItemFont::create("disable bold", [&](cocos2d::Ref* sender) { _label2a->disableEffect(LabelEffect::BOLD); @@ -3157,29 +3194,29 @@ LabelUnderline::LabelUnderline() auto s = Director::getInstance()->getWinSize(); // LabelBMFont - auto label1 = - Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "hello non-underline", TextHAlignment::CENTER, s.width); + auto label1 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "hello non-underline", TextHAlignment::CENTER, s.width); addChild(label1, 0, kTagBitmapAtlas1); - label1->setPosition(Vec2(s.width / 2, s.height * 4 / 6)); + label1->setPosition(Vec2(s.width/2, s.height*4/6)); // you can enable italics by calling this method _label1a = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "hello underline", TextHAlignment::CENTER, s.width); addChild(_label1a, 0, kTagBitmapAtlas1); - _label1a->setPosition(Vec2(s.width / 2, s.height * 3 / 6)); + _label1a->setPosition(Vec2(s.width/2, s.height*3/6)); // you can enable underline by calling this method _label1a->enableUnderline(); + // LabelTTF - TTFConfig ttfConfig("fonts/arial.ttf", 24); - auto label2 = Label::createWithTTF(ttfConfig, "hello non-underline", TextHAlignment::CENTER, s.width); + TTFConfig ttfConfig("fonts/arial.ttf",24); + auto label2 = Label::createWithTTF(ttfConfig, "hello non-underline", TextHAlignment::CENTER,s.width); addChild(label2, 0, kTagBitmapAtlas2); - label2->setPosition(Vec2(s.width / 2, s.height * 2 / 6)); + label2->setPosition(Vec2(s.width/2, s.height*2/6)); // or by setting the italics parameter on TTFConfig ttfConfig.underline = true; - _label2a = Label::createWithTTF(ttfConfig, "hello underline", TextHAlignment::CENTER, s.width); + _label2a = Label::createWithTTF(ttfConfig, "hello underline", TextHAlignment::CENTER,s.width); addChild(_label2a, 0, kTagBitmapAtlas2); - _label2a->setPosition(Vec2(s.width / 2, s.height * 1 / 6)); + _label2a->setPosition(Vec2(s.width/2, s.height*1/6)); auto menuItem = MenuItemFont::create("disable underline", [&](cocos2d::Ref* sender) { _label2a->disableEffect(LabelEffect::UNDERLINE); @@ -3209,19 +3246,18 @@ LabelUnderlineMultiline::LabelUnderlineMultiline() auto s = Director::getInstance()->getWinSize(); // bmfont - _label1a = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "hello underline\nand multiline", - TextHAlignment::CENTER, s.width); + _label1a = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "hello underline\nand multiline", TextHAlignment::CENTER, s.width); addChild(_label1a, 0, kTagBitmapAtlas1); - _label1a->setPosition(Vec2(s.width / 2, s.height * 2 / 3)); + _label1a->setPosition(Vec2(s.width/2, s.height*2/3)); // you can enable underline by calling this method _label1a->enableUnderline(); // ttf - TTFConfig ttfConfig("fonts/arial.ttf", 24); + TTFConfig ttfConfig("fonts/arial.ttf",24); ttfConfig.underline = true; _label2a = Label::createWithTTF(ttfConfig, "hello\nunderline\nwith multiline", TextHAlignment::LEFT, s.width); addChild(_label2a, 0, kTagBitmapAtlas2); - _label2a->setPosition(Vec2(s.width / 2, s.height * 1 / 3)); + _label2a->setPosition(Vec2(s.width/2, s.height*1/3)); auto menuItem = MenuItemFont::create("disable underline", [&](cocos2d::Ref* sender) { _label2a->disableEffect(LabelEffect::UNDERLINE); @@ -3251,19 +3287,18 @@ LabelStrikethrough::LabelStrikethrough() auto s = Director::getInstance()->getWinSize(); // bmfont - _label1a = Label::createWithBMFont("fonts/bitmapFontTest4.fnt", "hello strikethrough\nand multiline", - TextHAlignment::LEFT, s.width); + _label1a = Label::createWithBMFont("fonts/bitmapFontTest4.fnt", "hello strikethrough\nand multiline", TextHAlignment::LEFT, s.width); addChild(_label1a, 0, kTagBitmapAtlas1); - _label1a->setPosition(Vec2(s.width / 2, s.height * 2 / 3)); + _label1a->setPosition(Vec2(s.width/2, s.height*2/3)); // you can enable underline by calling this method _label1a->enableStrikethrough(); // ttf - TTFConfig ttfConfig("fonts/arial.ttf", 24); + TTFConfig ttfConfig("fonts/arial.ttf",24); ttfConfig.strikethrough = true; _label2a = Label::createWithTTF(ttfConfig, "hello\nstrikethrough\nwith multiline", TextHAlignment::RIGHT, s.width); addChild(_label2a, 0, kTagBitmapAtlas2); - _label2a->setPosition(Vec2(s.width / 2, s.height * 1 / 3)); + _label2a->setPosition(Vec2(s.width/2, s.height*1/3)); auto menuItem = MenuItemFont::create("disable underline", [&](cocos2d::Ref* sender) { _label2a->disableEffect(LabelEffect::STRIKETHROUGH); @@ -3295,22 +3330,22 @@ LabelLocalizationTest::LabelLocalizationTest() _localizationBin->initLanguageData("configs/ENGLISH.lang.csb"); const float BUTTON_WIDTH = 100; - float startPosX = 0; - Size winSize = Director::getInstance()->getVisibleSize(); + float startPosX = 0; + Size winSize = Director::getInstance()->getVisibleSize(); // Create a radio button group auto radioButtonGroup = RadioButtonGroup::create(); this->addChild(radioButtonGroup); // Create the radio buttons - const int NUMBER_OF_BUTTONS = 3; - startPosX = winSize.width / 2.0f - (NUMBER_OF_BUTTONS - 1) * 0.5 * BUTTON_WIDTH - 30; - std::vector labelTypes = {"English", "Chinese", "Japanese"}; + const int NUMBER_OF_BUTTONS = 3; + startPosX = winSize.width / 2.0f - (NUMBER_OF_BUTTONS - 1) * 0.5 * BUTTON_WIDTH - 30; + std::vector labelTypes = { "English", "Chinese", "Japanese" }; for (int i = 0; i < NUMBER_OF_BUTTONS; ++i) { RadioButton* radioButton = RadioButton::create("cocosui/radio_button_off.png", "cocosui/radio_button_on.png"); - float posX = startPosX + BUTTON_WIDTH * i; + float posX = startPosX + BUTTON_WIDTH * i; radioButton->setPosition(Vec2(posX, winSize.height / 2.0f + 70)); radioButton->setScale(1.2f); radioButton->addEventListener(CC_CALLBACK_2(LabelLocalizationTest::onChangedRadioButtonSelect, this)); @@ -3327,7 +3362,7 @@ LabelLocalizationTest::LabelLocalizationTest() addChild(_label1, 0); _label1->setPosition(Vec2(winSize.width / 2, winSize.height * 1 / 3)); - Label* label = Label::createWithSystemFont("From json data :", "Arial", 24); + Label * label = Label::createWithSystemFont("From json data :", "Arial", 24); label->setAnchorPoint(Vec2(0.0f, 0.5f)); addChild(label, 0); label->setPosition(Vec2(20.0f, winSize.height * 1 / 3 + 24)); @@ -3352,6 +3387,7 @@ std::string LabelLocalizationTest::subtitle() const return "Change language selected and see label change"; } + void LabelLocalizationTest::onChangedRadioButtonSelect(RadioButton* radioButton, RadioButton::EventType type) { if (radioButton == nullptr) @@ -3363,8 +3399,7 @@ void LabelLocalizationTest::onChangedRadioButtonSelect(RadioButton* radioButton, { case RadioButton::EventType::SELECTED: { - switch (radioButton->getTag()) - { + switch (radioButton->getTag()) { case 0: _localizationJson->initLanguageData("configs/en-US.lang.json"); _label1->setString(_localizationJson->getLocalizationString("Text Label")); @@ -3404,28 +3439,28 @@ LabelIssue15214::LabelIssue15214() Label* label = Label::createWithTTF("TTF with setColor()", "fonts/arial.ttf", 24.0f); label->enableUnderline(); label->setColor(cocos2d::Color3B::BLUE); - label->setPosition(size.width / 2, size.height / 5 * 4); + label->setPosition(size.width/2, size.height/5*4); this->addChild(label); // 2 Label* label2 = Label::createWithSystemFont("System with setColor()", "Verdana", 24.0f); label2->enableUnderline(); label2->setColor(cocos2d::Color3B::BLUE); - label2->setPosition(size.width / 2, size.height / 5 * 3); + label2->setPosition(size.width/2, size.height/5*3); this->addChild(label2); // 3 Label* label3 = Label::createWithTTF("TTF with setTextColor()", "fonts/arial.ttf", 24.0f); label3->enableUnderline(); label3->setTextColor(Color4B::BLUE); - label3->setPosition(size.width / 2, size.height / 5 * 2); + label3->setPosition(size.width/2, size.height/5*2); this->addChild(label3); // 4 Label* label4 = Label::createWithSystemFont("System with setTextColor()", "Verdana", 24.0f); label4->enableUnderline(); label4->setTextColor(Color4B::BLUE); - label4->setPosition(size.width / 2, size.height / 5 * 1); + label4->setPosition(size.width/2, size.height/5*1); this->addChild(label4); } @@ -3444,11 +3479,9 @@ std::string LabelIssue15214::subtitle() const // LabelIssue16293::LabelIssue16293() { - auto size = Director::getInstance()->getVisibleSize(); - Label* label = Label::createWithTTF( - "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789", "fonts/arial.ttf", - 12); - label->setPosition(size.width / 2, size.height / 2); + auto size = Director::getInstance()->getVisibleSize(); + Label* label = Label::createWithTTF("012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789", "fonts/arial.ttf", 12); + label->setPosition(size.width/2, size.height/2); this->addChild(label); } @@ -3471,7 +3504,7 @@ LabelIssue16471::LabelIssue16471() auto node = Node::create(); addChild(node, 100); - node->setPosition(size.width / 2, size.height / 2); + node->setPosition(size.width/2, size.height/2); // Used Google Translate to translate from Chinese: // Here is set to false then textLabel: TextColor valid @@ -3508,16 +3541,16 @@ LabelIssue16717::LabelIssue16717() { auto label = Label::createWithTTF("Hello World", "fonts/arial.ttf", 70); label->setPosition(VisibleRect::center() + Vec2(0.0f, 40.0f)); - label->enableOutline(Color4B(0, 255, 0, 100), 10); // Set 100 alpha for outline - label->setTextColor(Color4B(0, 0, 255, 100)); // Also set 100 alpha for text + label->enableOutline(Color4B(0, 255, 0, 100), 10); // Set 100 alpha for outline + label->setTextColor(Color4B(0, 0, 255, 100)); // Also set 100 alpha for text addChild(label); } { auto label = Label::createWithTTF("Hello World", "fonts/arial.ttf", 70); label->setPosition(VisibleRect::center() + Vec2(0.0f, -40.0f)); - label->enableOutline(Color4B(0, 255, 0, 100), 10); // Set 100 alpha for outline - label->setTextColor(Color4B(0, 255, 0, 100)); // Also set 100 alpha for text + label->enableOutline(Color4B(0, 255, 0, 100), 10); // Set 100 alpha for outline + label->setTextColor(Color4B(0, 255, 0, 100)); // Also set 100 alpha for text addChild(label); } } @@ -3537,15 +3570,15 @@ std::string LabelIssue16717::subtitle() const // LabelIssueLineGap::LabelIssueLineGap() { - + auto size = Director::getInstance()->getWinSize(); - + auto label1 = Label::createWithTTF("test \ntest", "fonts/FingerpopGap.ttf", 30); label1->setPosition(Vec2(size.width / 3, size.height / 2)); addChild(label1); - + auto label2 = Label::createWithSystemFont("test \ntest", "fonts/FingerpopGap.ttf", 30); - label2->setPosition(Vec2(size.width / 3 * 1.8, size.height / 2)); + label2->setPosition(Vec2(size.width / 3 * 1.8 , size.height / 2)); addChild(label2); } @@ -3565,13 +3598,13 @@ std::string LabelIssueLineGap::subtitle() const LabelIssue17902::LabelIssue17902() { auto center = VisibleRect::center(); - + auto label = Label::createWithTTF("abcdefg\nhijklmn", "fonts/arial.ttf", 26); label->setLineHeight(40); label->setPosition(center); addChild(label); - scheduleOnce(CC_CALLBACK_0(LabelIssue17902::purgeCachedData, this), 1.0f, "purge_cached_data"); + scheduleOnce(CC_CALLBACK_0(LabelIssue17902::purgeCachedData, this), 1.0f, "purge_cached_data"); } void LabelIssue17902::purgeCachedData() @@ -3594,19 +3627,19 @@ std::string LabelIssue17902::subtitle() const // LabelIssue20523::LabelIssue20523() { - auto size = Director::getInstance()->getWinSize(); + auto size = Director::getInstance()->getWinSize(); auto _crashingLabel = Label::createWithTTF("0", "fonts/Marker Felt.ttf", 120); _crashingLabel->setPosition(Vec2(size.width / 2, size.height / 2)); _crashingLabel->setColor(cocos2d::Color3B(200, 200, 200)); addChild(_crashingLabel, 1); //_crashingLabel->setWidth(size.width); - this->schedule( - [this, _crashingLabel](float) { + this->schedule([this, _crashingLabel](float) + { ++_i; _crashingLabel->setString(std::to_string(_i)); - }, - 1, CC_REPEAT_FOREVER, 0, "repeat"); + }, 1, CC_REPEAT_FOREVER, 0, "repeat"); + } std::string LabelIssue20523::title() const @@ -3622,8 +3655,7 @@ std::string LabelIssue20523::subtitle() const // // LabelLetterColorsTest // -LabelLetterColorsTest::LabelLetterColorsTest() -{ +LabelLetterColorsTest::LabelLetterColorsTest() { auto center = VisibleRect::center(); auto label = Label::createWithTTF("", "fonts/arial.ttf", 24); @@ -3636,21 +3668,17 @@ LabelLetterColorsTest::LabelLetterColorsTest() label->setString("abcd\ne"); // Must not crash at here. } -std::string LabelLetterColorsTest::title() const -{ +std::string LabelLetterColorsTest::title() const { return "Test for letter colors"; } -std::string LabelLetterColorsTest::subtitle() const -{ +std::string LabelLetterColorsTest::subtitle() const { return "Should not crash!"; } -void LabelLetterColorsTest::setLetterColors(cocos2d::Label* label, const cocos2d::Color3B& color) -{ +void LabelLetterColorsTest::setLetterColors(cocos2d::Label* label, const cocos2d::Color3B& color) { int n = label->getStringLength(); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { Sprite* letter = label->getLetter(i); if (letter != nullptr) letter->setColor(color); diff --git a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.h b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.h index 3e38903f78..8405563441 100644 --- a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.h +++ b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,12 +34,12 @@ DEFINE_TEST_SUITE(NewLabelTests); class AtlasDemoNew : public TestCase -{}; +{ +}; class LabelFNTColorAndOpacity : public AtlasDemoNew { - float _time; - + float _time; public: CREATE_FUNC(LabelFNTColorAndOpacity); @@ -53,8 +53,7 @@ public: class LabelFNTSpriteActions : public AtlasDemoNew { - float _time; - + float _time; public: CREATE_FUNC(LabelFNTSpriteActions); @@ -75,6 +74,7 @@ public: virtual std::string subtitle() const override; }; + class LabelFNTOffset : public AtlasDemoNew { public: @@ -180,13 +180,13 @@ public: virtual std::string getItemString(cocos2d::MenuItemFont* item); protected: - cocos2d::Label* _label = nullptr; + cocos2d::Label* _label = nullptr; cocos2d::Sprite* _arrowsBar = nullptr; - cocos2d::Sprite* _arrows = nullptr; + cocos2d::Sprite* _arrows = nullptr; std::vector _menuItems; - cocos2d::MenuItemFont* _lastSentenceItem = nullptr; - cocos2d::MenuItemFont* _lastAlignmentItem = nullptr; - bool _drag = false; + cocos2d::MenuItemFont *_lastSentenceItem = nullptr; + cocos2d::MenuItemFont *_lastAlignmentItem = nullptr; + bool _drag = false; }; class LabelFNTMultiLineAlignmentUNICODE : public LabelFNTMultiLineAlignment @@ -218,7 +218,7 @@ public: CREATE_FUNC(LabelFNTBounds); LabelFNTBounds(); - + virtual std::string title() const override; virtual std::string subtitle() const override; }; @@ -233,6 +233,7 @@ public: virtual std::string subtitle() const override; }; + class LabelFNTMultiFontAtlasWithRotation : public AtlasDemoNew { public: @@ -271,7 +272,7 @@ public: CREATE_FUNC(LabelTTFUnicodeNew); LabelTTFUnicodeNew(); - + virtual std::string title() const override; virtual std::string subtitle() const override; }; @@ -284,22 +285,24 @@ public: LabelTTFDynamicAlignment(); virtual std::string title() const override; virtual std::string subtitle() const override; - + private: + void setAlignmentLeft(cocos2d::Ref* sender); void setAlignmentCenter(cocos2d::Ref* sender); void setAlignmentRight(cocos2d::Ref* sender); void updateAlignment(); - + cocos2d::Label* _label; - cocos2d::TextHAlignment _horizAlign; + cocos2d::TextHAlignment _horizAlign; + }; class LabelTTFEmoji : public AtlasDemoNew { public: CREATE_FUNC(LabelTTFEmoji); - + LabelTTFEmoji(); virtual std::string title() const override; virtual std::string subtitle() const override; @@ -375,7 +378,6 @@ public: virtual std::string subtitle() const override; void sliderEvent(cocos2d::Ref* sender, cocos2d::ui::Slider::EventType type); - private: cocos2d::Label* shadowLabelOutline; cocos2d::Label* shadowLabelTTF; @@ -396,7 +398,7 @@ public: void step(float dt); private: - float _time; + float _time; }; class LabelCharMapColorTest : public AtlasDemoNew @@ -413,7 +415,7 @@ public: void actionFinishCallback(); private: - float _time; + float _time; }; class LabelCrashTest : public AtlasDemoNew @@ -457,14 +459,13 @@ public: LabelAlignmentTest(); virtual std::string title() const override; virtual std::string subtitle() const override; - private: - void setAlignmentLeft(cocos2d::Ref* sender); - void setAlignmentCenter(cocos2d::Ref* sender); - void setAlignmentRight(cocos2d::Ref* sender); - void setAlignmentTop(cocos2d::Ref* sender); - void setAlignmentMiddle(cocos2d::Ref* sender); - void setAlignmentBottom(cocos2d::Ref* sender); + void setAlignmentLeft(cocos2d::Ref* sender); + void setAlignmentCenter(cocos2d::Ref* sender); + void setAlignmentRight(cocos2d::Ref* sender); + void setAlignmentTop(cocos2d::Ref* sender); + void setAlignmentMiddle(cocos2d::Ref* sender); + void setAlignmentBottom(cocos2d::Ref* sender); cocos2d::Label* _label; }; @@ -502,7 +503,6 @@ public: virtual std::string subtitle() const override; void sliderEvent(cocos2d::Ref* sender, cocos2d::ui::Slider::EventType type); - private: cocos2d::Label* label; }; @@ -518,7 +518,6 @@ public: virtual std::string subtitle() const override; void sliderEvent(cocos2d::Ref* sender, cocos2d::ui::Slider::EventType type); - private: cocos2d::Label* label; }; @@ -704,18 +703,18 @@ class LabelLayoutBaseTest : public AtlasDemoNew { public: LabelLayoutBaseTest(); - void updateDrawNodeSize(const cocos2d::Size& drawNodeSize); + void updateDrawNodeSize(const cocos2d::Size &drawNodeSize); cocos2d::extension::ControlStepper* makeControlStepper(); void valueChanged(cocos2d::Ref* sender, cocos2d::extension::Control::EventType controlEvent); protected: - void setAlignmentLeft(cocos2d::Ref* sender); - void setAlignmentCenter(cocos2d::Ref* sender); - void setAlignmentRight(cocos2d::Ref* sender); - void setAlignmentTop(cocos2d::Ref* sender); - void setAlignmentMiddle(cocos2d::Ref* sender); - void setAlignmentBottom(cocos2d::Ref* sender); - + void setAlignmentLeft(cocos2d::Ref* sender); + void setAlignmentCenter(cocos2d::Ref* sender); + void setAlignmentRight(cocos2d::Ref* sender); + void setAlignmentTop(cocos2d::Ref* sender); + void setAlignmentMiddle(cocos2d::Ref* sender); + void setAlignmentBottom(cocos2d::Ref* sender); + void initWrapOption(const cocos2d::Size& size); void initToggleLabelTypeOption(const cocos2d::Size& size); void initAlignmentOption(const cocos2d::Size& size); @@ -801,7 +800,7 @@ public: LabelToggleTypeTest(); void initToggleCheckboxes(); - void onChangedRadioButtonSelect(cocos2d::ui::RadioButton* radioButton, cocos2d::ui::RadioButton::EventType type); + void onChangedRadioButtonSelect(cocos2d::ui::RadioButton* radioButton,cocos2d::ui::RadioButton::EventType type); virtual std::string title() const override; virtual std::string subtitle() const override; @@ -814,7 +813,7 @@ public: LabelSystemFontTest(); void initToggleCheckboxes(); - void onChangedRadioButtonSelect(cocos2d::ui::RadioButton* radioButton, cocos2d::ui::RadioButton::EventType type); + void onChangedRadioButtonSelect(cocos2d::ui::RadioButton* radioButton,cocos2d::ui::RadioButton::EventType type); virtual std::string title() const override; virtual std::string subtitle() const override; @@ -835,9 +834,9 @@ class LabelIssue13846Test : public AtlasDemoNew { public: CREATE_FUNC(LabelIssue13846Test); - + LabelIssue13846Test(); - + virtual std::string title() const override; virtual std::string subtitle() const override; }; @@ -982,9 +981,9 @@ class LabelIssueLineGap : public AtlasDemoNew { public: CREATE_FUNC(LabelIssueLineGap); - + LabelIssueLineGap(); - + virtual std::string title() const override; virtual std::string subtitle() const override; }; @@ -993,11 +992,11 @@ class LabelIssue17902 : public AtlasDemoNew { public: CREATE_FUNC(LabelIssue17902); - + LabelIssue17902(); virtual void purgeCachedData(); - + virtual std::string title() const override; virtual std::string subtitle() const override; }; @@ -1016,8 +1015,7 @@ protected: int _i = 0; }; -class LabelLetterColorsTest : public AtlasDemoNew -{ +class LabelLetterColorsTest : public AtlasDemoNew { public: CREATE_FUNC(LabelLetterColorsTest); diff --git a/tests/cpp-tests/Classes/LayerTest/LayerTest.cpp b/tests/cpp-tests/Classes/LayerTest/LayerTest.cpp index 26d26a6e4c..1bc88b56b6 100644 --- a/tests/cpp-tests/Classes/LayerTest/LayerTest.cpp +++ b/tests/cpp-tests/Classes/LayerTest/LayerTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -28,7 +28,7 @@ USING_NS_CC; -enum +enum { kTagLayer = 1, }; @@ -62,10 +62,9 @@ static void setEnableRecursiveCascading(Node* node, bool enable) { node->setCascadeColorEnabled(enable); node->setCascadeOpacityEnabled(enable); - + auto& children = node->getChildren(); - for (const auto& child : children) - { + for(const auto &child : children) { setEnableRecursiveCascading(child, enable); } } @@ -79,30 +78,41 @@ std::string LayerTest::title() const void LayerTestCascadingOpacityA::onEnter() { LayerTest::onEnter(); - - auto s = Director::getInstance()->getWinSize(); + + auto s = Director::getInstance()->getWinSize(); auto layer1 = Layer::create(); - + auto sister1 = Sprite::create("Images/grossinis_sister1.png"); auto sister2 = Sprite::create("Images/grossinis_sister2.png"); - auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); - + auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); + layer1->addChild(sister1); layer1->addChild(sister2); layer1->addChild(label); - this->addChild(layer1, 0, kTagLayer); - - sister1->setPosition(Vec2(s.width * 1 / 3, s.height / 2)); - sister2->setPosition(Vec2(s.width * 2 / 3, s.height / 2)); - label->setPosition(Vec2(s.width / 2, s.height / 2)); - - layer1->runAction(RepeatForever::create( - Sequence::create(FadeTo::create(4, 0), FadeTo::create(4, 255), DelayTime::create(1), nullptr))); + this->addChild( layer1, 0, kTagLayer); + + sister1->setPosition( Vec2( s.width*1/3, s.height/2)); + sister2->setPosition( Vec2( s.width*2/3, s.height/2)); + label->setPosition( Vec2( s.width/2, s.height/2)); + + layer1->runAction( + RepeatForever::create( + Sequence::create( + FadeTo::create(4, 0), + FadeTo::create(4, 255), + DelayTime::create(1), + nullptr))); sister1->runAction( - RepeatForever::create(Sequence::create(FadeTo::create(2, 0), FadeTo::create(2, 255), FadeTo::create(2, 0), - FadeTo::create(2, 255), DelayTime::create(1), nullptr))); - + RepeatForever::create( + Sequence::create( + FadeTo::create(2, 0), + FadeTo::create(2, 255), + FadeTo::create(2, 0), + FadeTo::create(2, 255), + DelayTime::create(1), + nullptr))); + // Enable cascading in scene setEnableRecursiveCascading(this, true); } @@ -112,37 +122,49 @@ std::string LayerTestCascadingOpacityA::subtitle() const return "Layer: cascading opacity"; } + // LayerTestCascadingOpacityB void LayerTestCascadingOpacityB::onEnter() { LayerTest::onEnter(); - - auto s = Director::getInstance()->getWinSize(); - auto layer1 = LayerColor::create(Color4B(192, 0, 0, 255), s.width, s.height / 2); + + auto s = Director::getInstance()->getWinSize(); + auto layer1 = LayerColor::create(Color4B(192, 0, 0, 255), s.width, s.height/2); layer1->setCascadeColorEnabled(false); - - layer1->setPosition(Vec2(0.0f, s.height / 2)); - + + layer1->setPosition( Vec2(0.0f, s.height/2)); + auto sister1 = Sprite::create("Images/grossinis_sister1.png"); auto sister2 = Sprite::create("Images/grossinis_sister2.png"); - auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); - + auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); + layer1->addChild(sister1); layer1->addChild(sister2); layer1->addChild(label); - this->addChild(layer1, 0, kTagLayer); - - sister1->setPosition(Vec2(s.width * 1 / 3, 0.0f)); - sister2->setPosition(Vec2(s.width * 2 / 3, 0.0f)); - label->setPosition(Vec2(s.width / 2, 0.0f)); - - layer1->runAction(RepeatForever::create( - Sequence::create(FadeTo::create(4, 0), FadeTo::create(4, 255), DelayTime::create(1), nullptr))); - + this->addChild( layer1, 0, kTagLayer); + + sister1->setPosition( Vec2( s.width*1/3, 0.0f)); + sister2->setPosition( Vec2( s.width*2/3, 0.0f)); + label->setPosition( Vec2( s.width/2, 0.0f)); + + layer1->runAction( + RepeatForever::create( + Sequence::create( + FadeTo::create(4, 0), + FadeTo::create(4, 255), + DelayTime::create(1), + nullptr))); + sister1->runAction( - RepeatForever::create(Sequence::create(FadeTo::create(2, 0), FadeTo::create(2, 255), FadeTo::create(2, 0), - FadeTo::create(2, 255), DelayTime::create(1), nullptr))); - + RepeatForever::create( + Sequence::create( + FadeTo::create(2, 0), + FadeTo::create(2, 255), + FadeTo::create(2, 0), + FadeTo::create(2, 255), + DelayTime::create(1), + nullptr))); + // Enable cascading in scene setEnableRecursiveCascading(this, true); } @@ -152,37 +174,49 @@ std::string LayerTestCascadingOpacityB::subtitle() const return "CCLayerColor: cascading opacity"; } + // LayerTestCascadingOpacityC void LayerTestCascadingOpacityC::onEnter() { LayerTest::onEnter(); - - auto s = Director::getInstance()->getWinSize(); - auto layer1 = LayerColor::create(Color4B(192, 0, 0, 255), s.width, s.height / 2); + + auto s = Director::getInstance()->getWinSize(); + auto layer1 = LayerColor::create(Color4B(192, 0, 0, 255), s.width, s.height/2); layer1->setCascadeColorEnabled(false); layer1->setCascadeOpacityEnabled(false); - - layer1->setPosition(Vec2(0.0f, s.height / 2)); - + + layer1->setPosition( Vec2(0.0f, s.height/2)); + auto sister1 = Sprite::create("Images/grossinis_sister1.png"); auto sister2 = Sprite::create("Images/grossinis_sister2.png"); - auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); - + auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); + layer1->addChild(sister1); layer1->addChild(sister2); layer1->addChild(label); - this->addChild(layer1, 0, kTagLayer); - - sister1->setPosition(Vec2(s.width * 1 / 3, 0.0f)); - sister2->setPosition(Vec2(s.width * 2 / 3, 0.0f)); - label->setPosition(Vec2(s.width / 2, 0.0f)); - - layer1->runAction(RepeatForever::create( - Sequence::create(FadeTo::create(4, 0), FadeTo::create(4, 255), DelayTime::create(1), nullptr))); - + this->addChild( layer1, 0, kTagLayer); + + sister1->setPosition( Vec2( s.width*1/3, 0.0f)); + sister2->setPosition( Vec2( s.width*2/3, 0.0f)); + label->setPosition( Vec2( s.width/2, 0.0f)); + + layer1->runAction( + RepeatForever::create( + Sequence::create( + FadeTo::create(4, 0), + FadeTo::create(4, 255), + DelayTime::create(1), + nullptr))); + sister1->runAction( - RepeatForever::create(Sequence::create(FadeTo::create(2, 0), FadeTo::create(2, 255), FadeTo::create(2, 0), - FadeTo::create(2, 255), DelayTime::create(1), nullptr))); + RepeatForever::create( + Sequence::create( + FadeTo::create(2, 0), + FadeTo::create(2, 255), + FadeTo::create(2, 0), + FadeTo::create(2, 255), + DelayTime::create(1), + nullptr))); } std::string LayerTestCascadingOpacityC::subtitle() const @@ -190,39 +224,53 @@ std::string LayerTestCascadingOpacityC::subtitle() const return "CCLayerColor: non-cascading opacity"; } + //// Example LayerTestCascadingColor // LayerTestCascadingColorA void LayerTestCascadingColorA::onEnter() { LayerTest::onEnter(); - - auto s = Director::getInstance()->getWinSize(); + + auto s = Director::getInstance()->getWinSize(); auto layer1 = Layer::create(); - + auto sister1 = Sprite::create("Images/grossinis_sister1.png"); auto sister2 = Sprite::create("Images/grossinis_sister2.png"); - auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); - + auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); + layer1->addChild(sister1); layer1->addChild(sister2); layer1->addChild(label); - this->addChild(layer1, 0, kTagLayer); - - sister1->setPosition(Vec2(s.width * 1 / 3, s.height / 2)); - sister2->setPosition(Vec2(s.width * 2 / 3, s.height / 2)); - label->setPosition(Vec2(s.width / 2, s.height / 2)); - - layer1->runAction(RepeatForever::create(Sequence::create( - TintTo::create(6, 255, 0, 255), TintTo::create(6, 255, 255, 255), DelayTime::create(1), nullptr))); - - sister1->runAction(RepeatForever::create(Sequence::create( - TintTo::create(2, 255, 255, 0), TintTo::create(2, 255, 255, 255), TintTo::create(2, 0, 255, 255), - TintTo::create(2, 255, 255, 255), TintTo::create(2, 255, 0, 255), TintTo::create(2, 255, 255, 255), - DelayTime::create(1), nullptr))); - + this->addChild( layer1, 0, kTagLayer); + + sister1->setPosition( Vec2( s.width*1/3, s.height/2)); + sister2->setPosition( Vec2( s.width*2/3, s.height/2)); + label->setPosition( Vec2( s.width/2, s.height/2)); + + layer1->runAction( + RepeatForever::create( + Sequence::create( + TintTo::create(6, 255, 0, 255), + TintTo::create(6, 255, 255, 255), + DelayTime::create(1), + nullptr))); + + sister1->runAction( + RepeatForever::create( + Sequence::create( + TintTo::create(2, 255, 255, 0), + TintTo::create(2, 255, 255, 255), + TintTo::create(2, 0, 255, 255), + TintTo::create(2, 255, 255, 255), + TintTo::create(2, 255, 0, 255), + TintTo::create(2, 255, 255, 255), + DelayTime::create(1), + nullptr))); + // Enable cascading in scene setEnableRecursiveCascading(this, true); + } std::string LayerTestCascadingColorA::subtitle() const @@ -230,36 +278,49 @@ std::string LayerTestCascadingColorA::subtitle() const return "Layer: cascading color"; } + // LayerTestCascadingColorB void LayerTestCascadingColorB::onEnter() { LayerTest::onEnter(); - auto s = Director::getInstance()->getWinSize(); - auto layer1 = LayerColor::create(Color4B(255, 255, 255, 255), s.width, s.height / 2); - - layer1->setPosition(Vec2(0.0f, s.height / 2)); - + auto s = Director::getInstance()->getWinSize(); + auto layer1 = LayerColor::create(Color4B(255, 255, 255, 255), s.width, s.height/2); + + layer1->setPosition( Vec2(0.0f, s.height/2)); + auto sister1 = Sprite::create("Images/grossinis_sister1.png"); auto sister2 = Sprite::create("Images/grossinis_sister2.png"); - auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); - + auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); + layer1->addChild(sister1); layer1->addChild(sister2); layer1->addChild(label); - this->addChild(layer1, 0, kTagLayer); - - sister1->setPosition(Vec2(s.width * 1 / 3, 0.0f)); - sister2->setPosition(Vec2(s.width * 2 / 3, 0.0f)); - label->setPosition(Vec2(s.width / 2, 0.0f)); - - layer1->runAction(RepeatForever::create(Sequence::create( - TintTo::create(6, 255, 0, 255), TintTo::create(6, 255, 255, 255), DelayTime::create(1), nullptr))); - - sister1->runAction(RepeatForever::create(Sequence::create( - TintTo::create(2, 255, 255, 0), TintTo::create(2, 255, 255, 255), TintTo::create(2, 0, 255, 255), - TintTo::create(2, 255, 255, 255), TintTo::create(2, 255, 0, 255), TintTo::create(2, 255, 255, 255), - DelayTime::create(1), nullptr))); - + this->addChild( layer1, 0, kTagLayer); + + sister1->setPosition( Vec2( s.width*1/3, 0.0f)); + sister2->setPosition( Vec2( s.width*2/3, 0.0f)); + label->setPosition( Vec2( s.width/2, 0.0f)); + + layer1->runAction( + RepeatForever::create( + Sequence::create( + TintTo::create(6, 255, 0, 255), + TintTo::create(6, 255, 255, 255), + DelayTime::create(1), + nullptr))); + + sister1->runAction( + RepeatForever::create( + Sequence::create( + TintTo::create(2, 255, 255, 0), + TintTo::create(2, 255, 255, 255), + TintTo::create(2, 0, 255, 255), + TintTo::create(2, 255, 255, 255), + TintTo::create(2, 255, 0, 255), + TintTo::create(2, 255, 255, 255), + DelayTime::create(1), + nullptr))); + // Enable cascading in scene setEnableRecursiveCascading(this, true); } @@ -269,35 +330,48 @@ std::string LayerTestCascadingColorB::subtitle() const return "CCLayerColor: cascading color"; } + // LayerTestCascadingColorC void LayerTestCascadingColorC::onEnter() { LayerTest::onEnter(); - auto s = Director::getInstance()->getWinSize(); - auto layer1 = LayerColor::create(Color4B(255, 255, 255, 255), s.width, s.height / 2); + auto s = Director::getInstance()->getWinSize(); + auto layer1 = LayerColor::create(Color4B(255, 255, 255, 255), s.width, s.height/2); layer1->setCascadeColorEnabled(false); - layer1->setPosition(Vec2(0.0f, s.height / 2)); - + layer1->setPosition( Vec2(0.0f, s.height/2)); + auto sister1 = Sprite::create("Images/grossinis_sister1.png"); auto sister2 = Sprite::create("Images/grossinis_sister2.png"); - auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); - + auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); + layer1->addChild(sister1); layer1->addChild(sister2); layer1->addChild(label); - this->addChild(layer1, 0, kTagLayer); - - sister1->setPosition(Vec2(s.width * 1 / 3, 0.0f)); - sister2->setPosition(Vec2(s.width * 2 / 3, 0.0f)); - label->setPosition(Vec2(s.width / 2, 0.0f)); - - layer1->runAction(RepeatForever::create(Sequence::create( - TintTo::create(6, 255, 0, 255), TintTo::create(6, 255, 255, 255), DelayTime::create(1), nullptr))); - - sister1->runAction(RepeatForever::create(Sequence::create( - TintTo::create(2, 255, 255, 0), TintTo::create(2, 255, 255, 255), TintTo::create(2, 0, 255, 255), - TintTo::create(2, 255, 255, 255), TintTo::create(2, 255, 0, 255), TintTo::create(2, 255, 255, 255), - DelayTime::create(1), nullptr))); + this->addChild( layer1, 0, kTagLayer); + + sister1->setPosition( Vec2( s.width*1/3, 0.0f)); + sister2->setPosition( Vec2( s.width*2/3, 0.0f)); + label->setPosition( Vec2( s.width/2, 0.0f)); + + layer1->runAction( + RepeatForever::create( + Sequence::create( + TintTo::create(6, 255, 0, 255), + TintTo::create(6, 255, 255, 255), + DelayTime::create(1), + nullptr))); + + sister1->runAction( + RepeatForever::create( + Sequence::create( + TintTo::create(2, 255, 255, 0), + TintTo::create(2, 255, 255, 255), + TintTo::create(2, 0, 255, 255), + TintTo::create(2, 255, 255, 255), + TintTo::create(2, 255, 0, 255), + TintTo::create(2, 255, 255, 255), + DelayTime::create(1), + nullptr))); } std::string LayerTestCascadingColorC::subtitle() const @@ -314,45 +388,45 @@ void LayerTest1::onEnter() { LayerTest::onEnter(); - auto listener = EventListenerTouchAllAtOnce::create(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(LayerTest1::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(LayerTest1::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(LayerTest1::onTouchesEnded, this); - + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - - auto s = Director::getInstance()->getWinSize(); - auto layer = LayerColor::create(Color4B(0xFF, 0x00, 0x00, 0x80), 200, 200); - + + auto s = Director::getInstance()->getWinSize(); + auto layer = LayerColor::create( Color4B(0xFF, 0x00, 0x00, 0x80), 200, 200); + layer->setIgnoreAnchorPointForPosition(false); - layer->setPosition(Vec2(s.width / 2, s.height / 2)); + layer->setPosition( Vec2(s.width/2, s.height/2) ); addChild(layer, 1, kTagLayer); } -void LayerTest1::updateSize(Vec2& touchLocation) -{ +void LayerTest1::updateSize(Vec2 &touchLocation) +{ auto s = Director::getInstance()->getWinSize(); + + auto newSize = Size( fabs(touchLocation.x - s.width/2)*2, fabs(touchLocation.y - s.height/2)*2); + + auto l = (LayerColor*) getChildByTag(kTagLayer); - auto newSize = Size(fabs(touchLocation.x - s.width / 2) * 2, fabs(touchLocation.y - s.height / 2) * 2); - - auto l = (LayerColor*)getChildByTag(kTagLayer); - - l->setContentSize(newSize); + l->setContentSize( newSize ); } -void LayerTest1::onTouchesBegan(const std::vector& touches, Event* event) +void LayerTest1::onTouchesBegan(const std::vector& touches, Event *event) { onTouchesMoved(touches, event); } -void LayerTest1::onTouchesMoved(const std::vector& touches, Event* event) +void LayerTest1::onTouchesMoved(const std::vector& touches, Event *event) { auto touchLocation = touches[0]->getLocation(); updateSize(touchLocation); } -void LayerTest1::onTouchesEnded(const std::vector& touches, Event* event) +void LayerTest1::onTouchesEnded(const std::vector& touches, Event *event) { onTouchesMoved(touches, event); } @@ -371,25 +445,25 @@ void LayerTest2::onEnter() { LayerTest::onEnter(); - auto s = Director::getInstance()->getWinSize(); - auto layer1 = LayerColor::create(Color4B(255, 255, 0, 80), 100, 300); - layer1->setPosition(Vec2(s.width / 3, s.height / 2)); + auto s = Director::getInstance()->getWinSize(); + auto layer1 = LayerColor::create( Color4B(255, 255, 0, 80), 100, 300); + layer1->setPosition(Vec2(s.width/3, s.height/2)); layer1->setIgnoreAnchorPointForPosition(false); addChild(layer1, 1); - - auto layer2 = LayerColor::create(Color4B(0, 0, 255, 255), 100, 300); - layer2->setPosition(Vec2((s.width / 3) * 2, s.height / 2)); + + auto layer2 = LayerColor::create( Color4B(0, 0, 255, 255), 100, 300); + layer2->setPosition(Vec2((s.width/3)*2, s.height/2)); layer2->setIgnoreAnchorPointForPosition(false); addChild(layer2, 1); - - auto actionTint = TintBy::create(2, -255, -127, 0); + + auto actionTint = TintBy::create(2, -255, -127, 0); auto actionTintBack = actionTint->reverse(); - auto seq1 = Sequence::create(actionTint, actionTintBack, nullptr); + auto seq1 = Sequence::create( actionTint, actionTintBack, nullptr); layer1->runAction(seq1); - auto actionFade = FadeOut::create(2.0f); + auto actionFade = FadeOut::create(2.0f); auto actionFadeBack = actionFade->reverse(); - auto seq2 = Sequence::create(actionFade, actionFadeBack, nullptr); + auto seq2 = Sequence::create(actionFade, actionFadeBack, nullptr); layer2->runAction(seq2); } @@ -406,30 +480,30 @@ std::string LayerTest2::subtitle() const LayerTestBlend::LayerTestBlend() { - auto s = Director::getInstance()->getWinSize(); - auto layer1 = LayerColor::create(Color4B(255, 255, 255, 80)); - + auto s = Director::getInstance()->getWinSize(); + auto layer1 = LayerColor::create( Color4B(255, 255, 255, 80) ); + auto sister1 = Sprite::create(s_pathSister1); auto sister2 = Sprite::create(s_pathSister2); - + addChild(sister1); addChild(sister2); addChild(layer1, 100, kTagLayer); + + sister1->setPosition( Vec2( s.width*1/3, s.height/2) ); + sister2->setPosition( Vec2( s.width*2/3, s.height/2) ); - sister1->setPosition(Vec2(s.width * 1 / 3, s.height / 2)); - sister2->setPosition(Vec2(s.width * 2 / 3, s.height / 2)); - - schedule(CC_SCHEDULE_SELECTOR(LayerTestBlend::newBlend), 1.0f); + schedule( CC_SCHEDULE_SELECTOR(LayerTestBlend::newBlend), 1.0f); } void LayerTestBlend::newBlend(float dt) { - auto layer = (LayerColor*)getChildByTag(kTagLayer); + auto layer = (LayerColor*)getChildByTag(kTagLayer); - backend::BlendFactor src; - backend::BlendFactor dst; + backend::BlendFactor src; + backend::BlendFactor dst; - if (layer->getBlendFunc().dst == backend::BlendFactor::ZERO) + if( layer->getBlendFunc().dst == backend::BlendFactor::ZERO ) { src = backend::BlendFactor::SRC_ALPHA; dst = backend::BlendFactor::ONE_MINUS_SRC_ALPHA; @@ -441,9 +515,10 @@ void LayerTestBlend::newBlend(float dt) } BlendFunc bf = {src, dst}; - layer->setBlendFunc(bf); + layer->setBlendFunc( bf ); } + std::string LayerTestBlend::subtitle() const { return "ColorLayer: blend"; @@ -456,19 +531,18 @@ std::string LayerTestBlend::subtitle() const //------------------------------------------------------------------ LayerGradientTest::LayerGradientTest() { - auto layer1 = LayerGradient::create(Color4B(255, 0, 0, 255), Color4B(0, 255, 0, 255), Vec2(0.9f, 0.9f)); + auto layer1 = LayerGradient::create(Color4B(255,0,0,255), Color4B(0,255,0,255), Vec2(0.9f, 0.9f)); addChild(layer1, 0, kTagLayer); - auto listener = EventListenerTouchAllAtOnce::create(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesMoved = CC_CALLBACK_2(LayerGradientTest::onTouchesMoved, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); auto label1 = Label::createWithTTF("Compressed Interpolation: Enabled", "fonts/Marker Felt.ttf", 26); auto label2 = Label::createWithTTF("Compressed Interpolation: Disabled", "fonts/Marker Felt.ttf", 26); - auto item1 = MenuItemLabel::create(label1); - auto item2 = MenuItemLabel::create(label2); - auto item = - MenuItemToggle::createWithCallback(CC_CALLBACK_1(LayerGradientTest::toggleItem, this), item1, item2, nullptr); + auto item1 = MenuItemLabel::create(label1); + auto item2 = MenuItemLabel::create(label2); + auto item = MenuItemToggle::createWithCallback( CC_CALLBACK_1(LayerGradientTest::toggleItem, this), item1, item2, nullptr); auto menu = Menu::create(item, nullptr); addChild(menu); @@ -476,23 +550,23 @@ LayerGradientTest::LayerGradientTest() menu->setPosition(Vec2(s.width / 2, 100.0f)); } -void LayerGradientTest::toggleItem(Ref* sender) +void LayerGradientTest::toggleItem(Ref *sender) { - auto gradient = static_cast(getChildByTag(kTagLayer)); - gradient->setCompressedInterpolation(!gradient->isCompressedInterpolation()); + auto gradient = static_cast( getChildByTag(kTagLayer) ); + gradient->setCompressedInterpolation(! gradient->isCompressedInterpolation()); } -void LayerGradientTest::onTouchesMoved(const std::vector& touches, Event* event) +void LayerGradientTest::onTouchesMoved(const std::vector& touches, Event *event) { auto s = Director::getInstance()->getWinSize(); auto touch = touches[0]; - auto start = touch->getLocation(); + auto start = touch->getLocation(); - auto diff = Vec2(s.width / 2, s.height / 2) - start; - diff = diff.getNormalized(); + auto diff = Vec2(s.width/2,s.height/2) - start; + diff = diff.getNormalized(); - auto gradient = static_cast(getChildByTag(1)); + auto gradient = static_cast( getChildByTag(1) ); gradient->setVector(diff); } @@ -513,7 +587,7 @@ std::string LayerGradientTest::subtitle() const //------------------------------------------------------------------ LayerGradientTest2::LayerGradientTest2() { - auto layer = LayerGradient::create(Color4B(255, 0, 0, 255), Color4B(255, 255, 0, 255)); + auto layer = LayerGradient::create(Color4B(255,0,0,255), Color4B(255,255,0,255)); addChild(layer); } @@ -529,7 +603,7 @@ std::string LayerGradientTest2::subtitle() const // LayerIgnoreAnchorPointPos -#define kLayerIgnoreAnchorPoint 1000 +#define kLayerIgnoreAnchorPoint 1000 void LayerIgnoreAnchorPointPos::onEnter() { @@ -540,33 +614,32 @@ void LayerIgnoreAnchorPointPos::onEnter() auto l = LayerColor::create(Color4B(255, 0, 0, 255), 150, 150); l->setAnchorPoint(Vec2(0.5f, 0.5f)); - l->setPosition(Vec2(s.width / 2, s.height / 2)); + l->setPosition(Vec2( s.width/2, s.height/2)); - auto move = MoveBy::create(2, Vec2(100, 2)); - auto back = (MoveBy*)move->reverse(); - auto seq = Sequence::create(move, back, nullptr); + auto move = MoveBy::create(2, Vec2(100,2)); + auto back = (MoveBy *)move->reverse(); + auto seq = Sequence::create(move, back, nullptr); l->runAction(RepeatForever::create(seq)); this->addChild(l, 0, kLayerIgnoreAnchorPoint); auto child = Sprite::create("Images/grossini.png"); l->addChild(child); auto lsize = l->getContentSize(); - child->setPosition(Vec2(lsize.width / 2, lsize.height / 2)); + child->setPosition(Vec2(lsize.width/2, lsize.height/2)); - auto item = - MenuItemFont::create("Toggle ignore anchor point", CC_CALLBACK_1(LayerIgnoreAnchorPointPos::onToggle, this)); + auto item = MenuItemFont::create("Toggle ignore anchor point", CC_CALLBACK_1(LayerIgnoreAnchorPointPos::onToggle, this)); auto menu = Menu::create(item, nullptr); this->addChild(menu); - menu->setPosition(Vec2(s.width / 2, s.height / 2)); + menu->setPosition(Vec2(s.width/2, s.height/2)); } void LayerIgnoreAnchorPointPos::onToggle(Ref* pObject) { - auto layer = this->getChildByTag(kLayerIgnoreAnchorPoint); + auto layer = this->getChildByTag(kLayerIgnoreAnchorPoint); bool ignore = layer->isIgnoreAnchorPointForPosition(); - layer->setIgnoreAnchorPointForPosition(!ignore); + layer->setIgnoreAnchorPointForPosition(! ignore); } std::string LayerIgnoreAnchorPointPos::title() const @@ -589,32 +662,32 @@ void LayerIgnoreAnchorPointRot::onEnter() auto l = LayerColor::create(Color4B(255, 0, 0, 255), 200, 200); l->setAnchorPoint(Vec2(0.5f, 0.5f)); - l->setPosition(Vec2(s.width / 2, s.height / 2)); + l->setPosition(Vec2( s.width/2, s.height/2)); this->addChild(l, 0, kLayerIgnoreAnchorPoint); auto rot = RotateBy::create(2, 360); l->runAction(RepeatForever::create(rot)); + auto child = Sprite::create("Images/grossini.png"); l->addChild(child); auto lsize = l->getContentSize(); - child->setPosition(Vec2(lsize.width / 2, lsize.height / 2)); + child->setPosition(Vec2(lsize.width/2, lsize.height/2)); - auto item = - MenuItemFont::create("Toggle ignore anchor point", CC_CALLBACK_1(LayerIgnoreAnchorPointRot::onToggle, this)); + auto item = MenuItemFont::create("Toggle ignore anchor point", CC_CALLBACK_1(LayerIgnoreAnchorPointRot::onToggle, this)); auto menu = Menu::create(item, nullptr); this->addChild(menu); - menu->setPosition(Vec2(s.width / 2, s.height / 2)); + menu->setPosition(Vec2(s.width/2, s.height/2)); } void LayerIgnoreAnchorPointRot::onToggle(Ref* pObject) { - auto layer = this->getChildByTag(kLayerIgnoreAnchorPoint); + auto layer = this->getChildByTag(kLayerIgnoreAnchorPoint); bool ignore = layer->isIgnoreAnchorPointForPosition(); - layer->setIgnoreAnchorPointForPosition(!ignore); + layer->setIgnoreAnchorPointForPosition(! ignore); } std::string LayerIgnoreAnchorPointRot::title() const @@ -631,17 +704,18 @@ std::string LayerIgnoreAnchorPointRot::subtitle() const void LayerIgnoreAnchorPointScale::onEnter() { LayerTest::onEnter(); - + auto s = Director::getInstance()->getWinSize(); auto l = LayerColor::create(Color4B(255, 0, 0, 255), 200, 200); l->setAnchorPoint(Vec2(0.5f, 1.0f)); - l->setPosition(Vec2(s.width / 2, s.height / 2)); + l->setPosition(Vec2( s.width/2, s.height/2)); + auto scale = ScaleBy::create(2, 2); - auto back = (ScaleBy*)scale->reverse(); - auto seq = Sequence::create(scale, back, nullptr); + auto back = (ScaleBy*)scale->reverse(); + auto seq = Sequence::create(scale, back, nullptr); l->runAction(RepeatForever::create(seq)); @@ -650,22 +724,21 @@ void LayerIgnoreAnchorPointScale::onEnter() auto child = Sprite::create("Images/grossini.png"); l->addChild(child); auto lsize = l->getContentSize(); - child->setPosition(Vec2(lsize.width / 2, lsize.height / 2)); + child->setPosition(Vec2(lsize.width/2, lsize.height/2)); - auto item = - MenuItemFont::create("Toggle ignore anchor point", CC_CALLBACK_1(LayerIgnoreAnchorPointScale::onToggle, this)); + auto item = MenuItemFont::create("Toggle ignore anchor point", CC_CALLBACK_1(LayerIgnoreAnchorPointScale::onToggle, this)); auto menu = Menu::create(item, nullptr); this->addChild(menu); - menu->setPosition(Vec2(s.width / 2, s.height / 2)); + menu->setPosition(Vec2(s.width/2, s.height/2)); } void LayerIgnoreAnchorPointScale::onToggle(Ref* pObject) { - auto layer = this->getChildByTag(kLayerIgnoreAnchorPoint); + auto layer = this->getChildByTag(kLayerIgnoreAnchorPoint); bool ignore = layer->isIgnoreAnchorPointForPosition(); - layer->setIgnoreAnchorPointForPosition(!ignore); + layer->setIgnoreAnchorPointForPosition(! ignore); } std::string LayerIgnoreAnchorPointScale::title() const @@ -682,22 +755,22 @@ LayerExtendedBlendOpacityTest::LayerExtendedBlendOpacityTest() { auto layer1 = LayerGradient::create(Color4B(255, 0, 0, 255), Color4B(255, 0, 255, 255)); layer1->setContentSize(Size(80.0f, 80.0f)); - layer1->setPosition(Vec2(50.0f, 50.0f)); + layer1->setPosition(Vec2(50.0f,50.0f)); addChild(layer1); - + auto layer2 = LayerGradient::create(Color4B(0, 0, 0, 127), Color4B(255, 255, 255, 127)); layer2->setContentSize(Size(80.0f, 80.0f)); - layer2->setPosition(Vec2(100.0f, 90.0f)); + layer2->setPosition(Vec2(100.0f,90.0f)); addChild(layer2); - + auto layer3 = LayerGradient::create(); layer3->setContentSize(Size(80.0f, 80.0f)); - layer3->setPosition(Vec2(150.0f, 140.0f)); + layer3->setPosition(Vec2(150.0f,140.0f)); layer3->setStartColor(Color3B(255, 0, 0)); layer3->setEndColor(Color3B(255, 0, 255)); layer3->setStartOpacity(255); layer3->setEndOpacity(255); - layer3->setBlendFunc(BlendFunc::ALPHA_NON_PREMULTIPLIED); + layer3->setBlendFunc( BlendFunc::ALPHA_NON_PREMULTIPLIED ); addChild(layer3); } @@ -715,27 +788,27 @@ std::string LayerExtendedBlendOpacityTest::subtitle() const void LayerBug3162A::onEnter() { LayerTest::onEnter(); - - Size size = VisibleRect::getVisibleRect().size; - size.width = size.width / 2; - size.height = size.height / 3; + + Size size = VisibleRect::getVisibleRect().size; + size.width = size.width / 2; + size.height = size.height / 3; Color4B color[3] = {Color4B(255, 0, 0, 255), Color4B(0, 255, 0, 255), Color4B(0, 0, 255, 255)}; - + for (int i = 0; i < 3; ++i) { _layer[i] = LayerColor::create(color[i]); _layer[i]->setContentSize(size); - _layer[i]->setPosition(Vec2(size.width / 2, size.height / 2) - Vec2(20.0f, 20.0f)); + _layer[i]->setPosition(Vec2(size.width/2, size.height/2) - Vec2(20.0f, 20.0f)); _layer[i]->setOpacity(150); _layer[i]->setCascadeOpacityEnabled(true); if (i > 0) { - _layer[i - 1]->addChild(_layer[i]); + _layer[i-1]->addChild(_layer[i]); } } - + this->addChild(_layer[0]); - + schedule(CC_SCHEDULE_SELECTOR(LayerBug3162A::step), 0.5, CC_REPEAT_FOREVER, 0); } @@ -758,30 +831,30 @@ std::string LayerBug3162A::subtitle() const void LayerBug3162B::onEnter() { LayerTest::onEnter(); - - Size size = VisibleRect::getVisibleRect().size; - size.width = size.width / 2; - size.height = size.height / 3; + + Size size = VisibleRect::getVisibleRect().size; + size.width = size.width / 2; + size.height = size.height / 3; Color4B color[3] = {Color4B(200, 0, 0, 255), Color4B(150, 0, 0, 255), Color4B(100, 0, 0, 255)}; - + for (int i = 0; i < 3; ++i) { _layer[i] = LayerColor::create(color[i]); _layer[i]->setContentSize(size); - _layer[i]->setPosition(Vec2(size.width / 2, size.height / 2) - Vec2(20.0f, 20.0f)); + _layer[i]->setPosition(Vec2(size.width/2, size.height/2) - Vec2(20.0f, 20.0f)); //_layer[i]->setOpacity(150); if (i > 0) { - _layer[i - 1]->addChild(_layer[i]); + _layer[i-1]->addChild(_layer[i]); } } - + this->addChild(_layer[0]); - + _layer[0]->setCascadeColorEnabled(true); _layer[1]->setCascadeColorEnabled(true); _layer[2]->setCascadeColorEnabled(true); - + schedule(CC_SCHEDULE_SELECTOR(LayerBug3162B::step), 0.5, CC_REPEAT_FOREVER, 0); } @@ -807,7 +880,7 @@ std::string LayerColorOccludeBug::title() const std::string LayerColorOccludeBug::subtitle() const { - return "Layer Color Should not occlude titles and any sprites"; + return "Layer Color Should not occlude titles and any sprites"; } void LayerColorOccludeBug::onEnter() @@ -834,22 +907,22 @@ std::string LayerRadialGradientTest::title() const void LayerRadialGradientTest::onEnter() { LayerTest::onEnter(); - + _currentSeletedItemIndex = 0; - + auto director = Director::getInstance(); director->setClearColor(Color4F(0, 0, 0, 0)); auto origin = director->getVisibleOrigin(); - auto size = director->getVisibleSize(); - Vec2 center(origin.x + size.width / 2 + 50, origin.y + size.height / 2); + auto size = director->getVisibleSize(); + Vec2 center(origin.x + size.width/2 + 50, origin.y + size.height/2); float radius = (size.height - 50) / 2; - _layer = LayerRadialGradient::create(Color4B(145, 106, 209, 140), Color4B(0, 0, 0, 0), radius, center, 1.0f); + _layer = LayerRadialGradient::create(Color4B(145, 106, 209, 140), Color4B(0, 0, 0, 0), radius, center, 1.0f); addChild(_layer); - + auto scaleSlider = LayerRadialGradientTest::createSlider(); scaleSlider->setPosition(Vec2(50.0f, 130.0f)); addChild(scaleSlider); - + auto listview = createListView(); listview->setPosition(Vec2(100.0f, 150.0f)); addChild(listview); @@ -866,7 +939,7 @@ cocos2d::ui::Slider* LayerRadialGradientTest::createSlider() slider->setRotation(90); slider->setTag(101); slider->setPercent(50); - + return slider; } @@ -874,114 +947,113 @@ void LayerRadialGradientTest::listviewCallback(cocos2d::Ref* sender, cocos2d::ui { // clear all text to white auto listview = static_cast(sender); - for (auto& item : listview->getItems()) + for (auto &item : listview->getItems()) static_cast(item)->setColor(cocos2d::Color3B::WHITE); - + _currentSeletedItemIndex = (int)listview->getCurSelectedIndex(); listview->getItem(_currentSeletedItemIndex)->setColor(cocos2d::Color3B::RED); - + int percent = 100; auto slider = static_cast(getChildByTag(101)); switch (_currentSeletedItemIndex) { - case 0: - // scale - slider->setPercent(_layer->getScaleX() / 2 * percent); - break; - case 1: - // skewx - slider->setPercent(_layer->getSkewX() / 90 * percent); - break; - case 2: - // skewy - slider->setPercent(_layer->getSkewY() / 90 * percent); - break; - case 3: - // expand - slider->setPercent(_layer->getExpand() * percent); - break; - case 4: - // radius - slider->setPercent(_layer->getRadius() / 300 * percent); - break; - - default: - break; + case 0: + // scale + slider->setPercent(_layer->getScaleX() / 2 * percent); + break; + case 1: + // skewx + slider->setPercent(_layer->getSkewX() / 90 * percent); + break; + case 2: + // skewy + slider->setPercent(_layer->getSkewY() / 90 * percent); + break; + case 3: + // expand + slider->setPercent(_layer->getExpand() * percent); + break; + case 4: + // radius + slider->setPercent(_layer->getRadius() / 300 * percent); + break; + + default: + break; } } void LayerRadialGradientTest::sliderCallback(cocos2d::Ref* sender, cocos2d::ui::Slider::EventType type) { - auto slider = static_cast(sender); + auto slider = static_cast(sender); float percent = slider->getPercent() / 100.f; switch (_currentSeletedItemIndex) { - case 0: - // scale - _layer->setScale(percent * 2); - CCLOG("scale is %f", percent * 2); - break; - case 1: - // skewx - _layer->setSkewX(90 * percent); - CCLOG("SkewX is %f", 90 * percent); - break; - case 2: - // skewy - _layer->setSkewY(90 * percent); - CCLOG("SkewY is %f", 90 * percent); - break; - case 3: - // expand - _layer->setExpand(percent); - CCLOG("expand is %f", percent); - break; - case 4: - // radius - _layer->setRadius(300 * percent); - CCLOG("radius is %f", 300 * percent); - break; - default: - break; + case 0: + // scale + _layer->setScale(percent * 2); + CCLOG("scale is %f", percent * 2); + break; + case 1: + // skewx + _layer->setSkewX(90 * percent); + CCLOG("SkewX is %f", 90 * percent); + break; + case 2: + // skewy + _layer->setSkewY(90 * percent); + CCLOG("SkewY is %f", 90 * percent); + break; + case 3: + // expand + _layer->setExpand(percent); + CCLOG("expand is %f", percent); + break; + case 4: + // radius + _layer->setRadius(300 * percent); + CCLOG("radius is %f", 300 * percent); + break; + default: + break; } } cocos2d::ui::ListView* LayerRadialGradientTest::createListView() { auto listview = cocos2d::ui::ListView::create(); - + auto scale = cocos2d::ui::Text::create(); scale->setString("scale[0-2]"); - scale->setColor(cocos2d::Color3B::RED); // default seleted item + scale->setColor(cocos2d::Color3B::RED); // default seleted item scale->setTouchEnabled(true); listview->pushBackCustomItem(scale); - + auto skewx = cocos2d::ui::Text::create(); skewx->setString("skewx[0-90]"); skewx->setTouchEnabled(true); listview->pushBackCustomItem(skewx); - + auto skewy = cocos2d::ui::Text::create(); skewy->setString("skewy[0-90]"); skewy->setTouchEnabled(true); listview->pushBackCustomItem(skewy); - + auto expand = cocos2d::ui::Text::create(); expand->setString("expand[0-1]"); expand->setTouchEnabled(true); listview->pushBackCustomItem(expand); - + auto radius = cocos2d::ui::Text::create(); radius->setString("radius[0-300]"); radius->setTouchEnabled(true); listview->pushBackCustomItem(radius); - + listview->setContentSize(scale->getContentSize() * 5); listview->setCurSelectedIndex(0); listview->setTouchEnabled(true); - listview->addEventListener( - (ui::ListView::ccListViewCallback)CC_CALLBACK_2(LayerRadialGradientTest::listviewCallback, this)); + listview->addEventListener((ui::ListView::ccListViewCallback)CC_CALLBACK_2(LayerRadialGradientTest::listviewCallback, this)); listview->setTag(100); - + return listview; } diff --git a/tests/cpp-tests/Classes/LayerTest/LayerTest.h b/tests/cpp-tests/Classes/LayerTest/LayerTest.h index 96817d751b..9ef5155f09 100644 --- a/tests/cpp-tests/Classes/LayerTest/LayerTest.h +++ b/tests/cpp-tests/Classes/LayerTest/LayerTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -35,9 +35,8 @@ class LayerTest : public TestCase { public: virtual std::string title() const override; - protected: - std::string _title; + std::string _title; }; class LayerTestCascadingOpacityA : public LayerTest @@ -88,6 +87,7 @@ public: virtual std::string subtitle() const override; }; + class LayerTest1 : public LayerTest { public: @@ -96,7 +96,7 @@ public: virtual void onEnter() override; virtual std::string subtitle() const override; - void updateSize(cocos2d::Vec2& touchLocation); + void updateSize(cocos2d::Vec2 &touchLocation); void onTouchesBegan(const std::vector& touches, cocos2d::Event* event); void onTouchesMoved(const std::vector& touches, cocos2d::Event* event); @@ -111,6 +111,7 @@ public: virtual std::string subtitle() const override; }; + class LayerTestBlend : public LayerTest { public: @@ -129,7 +130,7 @@ public: void onTouchesMoved(const std::vector& touches, cocos2d::Event* event); virtual std::string title() const override; virtual std::string subtitle() const override; - void toggleItem(cocos2d::Ref* sender); + void toggleItem(cocos2d::Ref *sender); }; class LayerGradientTest2 : public LayerTest @@ -187,9 +188,9 @@ public: virtual void onEnter() override; virtual std::string title() const override; virtual std::string subtitle() const override; - + void step(float dt); - + private: cocos2d::LayerColor* _layer[3]; }; @@ -201,9 +202,9 @@ public: virtual void onEnter() override; virtual std::string title() const override; virtual std::string subtitle() const override; - + void step(float dt); - + private: cocos2d::LayerColor* _layer[3]; }; @@ -216,7 +217,7 @@ public: virtual void onExit() override; virtual std::string title() const override; virtual std::string subtitle() const override; - + private: cocos2d::LayerColor* _layer; }; @@ -227,16 +228,16 @@ public: CREATE_FUNC(LayerRadialGradientTest); virtual void onEnter() override; virtual std::string title() const override; - + void sliderCallback(cocos2d::Ref* sender, cocos2d::ui::Slider::EventType type); void listviewCallback(cocos2d::Ref* sender, cocos2d::ui::ListView::EventType type); - private: cocos2d::ui::Slider* createSlider(); cocos2d::ui::ListView* createListView(); - + cocos2d::LayerRadialGradient* _layer; int _currentSeletedItemIndex; }; + #endif diff --git a/tests/cpp-tests/Classes/LightTest/LightTest.cpp b/tests/cpp-tests/Classes/LightTest/LightTest.cpp index 77d67012ea..26c449459d 100644 --- a/tests/cpp-tests/Classes/LightTest/LightTest.cpp +++ b/tests/cpp-tests/Classes/LightTest/LightTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -31,49 +31,49 @@ LightTests::LightTests() ADD_TEST_CASE(LightTest); } -LightTest::LightTest() : _directionalLight(nullptr), _pointLight(nullptr), _spotLight(nullptr) +LightTest::LightTest() + : _directionalLight(nullptr) + , _pointLight(nullptr) + , _spotLight(nullptr) { addSprite(); addLights(); scheduleUpdate(); - auto s = Director::getInstance()->getWinSize(); - auto camera = Camera::createPerspective(60, (float)s.width / s.height, 1.0f, 1000.0f); + auto s = Director::getInstance()->getWinSize(); + auto camera = Camera::createPerspective(60, (float)s.width/s.height, 1.0f, 1000.0f); camera->setCameraFlag(CameraFlag::USER1); camera->setPosition3D(Vec3(0.0f, 100.0f, 100.0f)); camera->lookAt(Vec3(0.0f, 0.0f, 0.0f), Vec3(0.0f, 1.0f, 0.0f)); addChild(camera); TTFConfig ttfConfig("fonts/arial.ttf", 15); - _ambientLightLabel = Label::createWithTTF(ttfConfig, "Ambient Light ON"); + _ambientLightLabel = Label::createWithTTF(ttfConfig,"Ambient Light ON"); _ambientLightLabel->retain(); - auto menuItem0 = - MenuItemLabel::create(_ambientLightLabel, CC_CALLBACK_1(LightTest::SwitchLight, this, LightType::AMBIENT)); - _directionalLightLabel = Label::createWithTTF(ttfConfig, "Directional Light OFF"); + auto menuItem0 = MenuItemLabel::create(_ambientLightLabel, CC_CALLBACK_1(LightTest::SwitchLight,this,LightType::AMBIENT)); + _directionalLightLabel = Label::createWithTTF(ttfConfig,"Directional Light OFF"); _directionalLightLabel->retain(); - auto menuItem1 = MenuItemLabel::create(_directionalLightLabel, - CC_CALLBACK_1(LightTest::SwitchLight, this, LightType::DIRECTIONAL)); - _pointLightLabel = Label::createWithTTF(ttfConfig, "Point Light OFF"); + auto menuItem1 = MenuItemLabel::create(_directionalLightLabel, CC_CALLBACK_1(LightTest::SwitchLight,this,LightType::DIRECTIONAL)); + _pointLightLabel = Label::createWithTTF(ttfConfig,"Point Light OFF"); _pointLightLabel->retain(); - auto menuItem2 = - MenuItemLabel::create(_pointLightLabel, CC_CALLBACK_1(LightTest::SwitchLight, this, LightType::POINT)); - _spotLightLabel = Label::createWithTTF(ttfConfig, "Spot Light OFF"); + auto menuItem2 = MenuItemLabel::create(_pointLightLabel, CC_CALLBACK_1(LightTest::SwitchLight,this,LightType::POINT)); + _spotLightLabel = Label::createWithTTF(ttfConfig,"Spot Light OFF"); _spotLightLabel->retain(); - auto menuItem3 = - MenuItemLabel::create(_spotLightLabel, CC_CALLBACK_1(LightTest::SwitchLight, this, LightType::SPOT)); + auto menuItem3 = MenuItemLabel::create(_spotLightLabel, CC_CALLBACK_1(LightTest::SwitchLight,this,LightType::SPOT)); auto menu = Menu::create(menuItem0, menuItem1, menuItem2, menuItem3, nullptr); menu->setPosition(Vec2::ZERO); menuItem0->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); - menuItem0->setPosition(Vec2(VisibleRect::left().x, VisibleRect::top().y - 50)); + menuItem0->setPosition( Vec2(VisibleRect::left().x, VisibleRect::top().y-50) ); menuItem1->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); - menuItem1->setPosition(Vec2(VisibleRect::left().x, VisibleRect::top().y - 100)); + menuItem1->setPosition( Vec2(VisibleRect::left().x, VisibleRect::top().y-100) ); menuItem2->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); - menuItem2->setPosition(Vec2(VisibleRect::left().x, VisibleRect::top().y - 150)); + menuItem2->setPosition( Vec2(VisibleRect::left().x, VisibleRect::top().y -150)); menuItem3->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); - menuItem3->setPosition(Vec2(VisibleRect::left().x, VisibleRect::top().y - 200)); + menuItem3->setPosition( Vec2(VisibleRect::left().x, VisibleRect::top().y -200)); addChild(menu); } + LightTest::~LightTest() { if (_spotLightLabel) @@ -119,7 +119,7 @@ void LightTest::addSprite() { std::string fileName = "Sprite3DTest/orc.c3b"; - auto sprite = Sprite3D::create(fileName); + auto sprite = Sprite3D::create(fileName); sprite->setRotation3D(Vec3(0.0f, 180.0f, 0.0f)); sprite->setPosition(Vec2(0.0f, 0.0f)); sprite->setScale(2.0); @@ -138,7 +138,7 @@ void LightTest::addSprite() { std::string fileName = "Sprite3DTest/sphere.c3b"; - auto sprite = Sprite3D::create(fileName); + auto sprite = Sprite3D::create(fileName); sprite->setPosition(Vec2(30.0f, 0.0f)); addChild(sprite); sprite->setCameraMask(2); @@ -146,7 +146,7 @@ void LightTest::addSprite() { std::string fileName = "Sprite3DTest/sphere.c3b"; - auto sprite = Sprite3D::create(fileName); + auto sprite = Sprite3D::create(fileName); sprite->setScale(0.5f); sprite->setPosition(Vec2(-50.0f, 0.0f)); addChild(sprite); @@ -155,7 +155,7 @@ void LightTest::addSprite() { std::string fileName = "Sprite3DTest/sphere.c3b"; - auto sprite = Sprite3D::create(fileName); + auto sprite = Sprite3D::create(fileName); sprite->setScale(0.5f); sprite->setPosition(Vec2(-30.0f, 10.0f)); addChild(sprite); @@ -165,7 +165,7 @@ void LightTest::addSprite() void LightTest::addLights() { - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); _ambientLight = AmbientLight::create(Color3B(200, 200, 200)); _ambientLight->retain(); _ambientLight->setEnabled(true); @@ -184,8 +184,7 @@ void LightTest::addLights() addChild(_pointLight); _pointLight->setCameraMask(2); - _spotLight = - SpotLight::create(Vec3(-1.0f, -1.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f), Color3B(200, 200, 200), 0.0, 0.5, 10000.0f); + _spotLight = SpotLight::create(Vec3(-1.0f, -1.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f), Color3B(200, 200, 200), 0.0, 0.5, 10000.0f); _spotLight->retain(); _spotLight->setEnabled(false); addChild(_spotLight); @@ -196,7 +195,7 @@ void LightTest::addLights() auto tintto2 = TintTo::create(4, 0, 255, 0); auto tintto3 = TintTo::create(4, 255, 0, 0); auto tintto4 = TintTo::create(4, 255, 255, 255); - auto seq = Sequence::create(tintto1, tintto2, tintto3, tintto4, nullptr); + auto seq = Sequence::create(tintto1,tintto2, tintto3, tintto4, nullptr); _ambientLight->runAction(RepeatForever::create(seq)); } @@ -205,7 +204,7 @@ void LightTest::addLights() auto tintto2 = TintTo::create(4, 0, 255, 0); auto tintto3 = TintTo::create(4, 0, 0, 255); auto tintto4 = TintTo::create(4, 255, 255, 255); - auto seq = Sequence::create(tintto1, tintto2, tintto3, tintto4, nullptr); + auto seq = Sequence::create(tintto1,tintto2, tintto3, tintto4, nullptr); _directionalLight->runAction(RepeatForever::create(seq)); } @@ -214,7 +213,7 @@ void LightTest::addLights() auto tintto2 = TintTo::create(4, 0, 255, 0); auto tintto3 = TintTo::create(4, 0, 0, 255); auto tintto4 = TintTo::create(4, 255, 255, 255); - auto seq = Sequence::create(tintto2, tintto1, tintto3, tintto4, nullptr); + auto seq = Sequence::create(tintto2, tintto1, tintto3, tintto4, nullptr); _pointLight->runAction(RepeatForever::create(seq)); } @@ -223,12 +222,12 @@ void LightTest::addLights() auto tintto2 = TintTo::create(4, 0, 255, 0); auto tintto3 = TintTo::create(4, 0, 0, 255); auto tintto4 = TintTo::create(4, 255, 255, 255); - auto seq = Sequence::create(tintto3, tintto2, tintto1, tintto4, nullptr); + auto seq = Sequence::create(tintto3, tintto2, tintto1, tintto4, nullptr); _spotLight->runAction(RepeatForever::create(seq)); } } -void LightTest::update(float delta) +void LightTest::update( float delta ) { static float angleDelta = 0.0; @@ -257,49 +256,49 @@ void LightTest::update(float delta) TestCase::update(delta); } -void LightTest::SwitchLight(Ref* sender, LightType lightType) +void LightTest::SwitchLight( Ref* sender, LightType lightType ) { switch (lightType) { case LightType::AMBIENT: - { - char str[32]; - bool isON = !_ambientLight->isEnabled(); - sprintf(str, "Ambient Light %s", isON == true ? "ON" : "OFF"); - _ambientLight->setEnabled(isON); - _ambientLightLabel->setString(str); - } - break; + { + char str[32]; + bool isON = !_ambientLight->isEnabled(); + sprintf(str, "Ambient Light %s", isON == true? "ON":"OFF"); + _ambientLight->setEnabled(isON); + _ambientLightLabel->setString(str); + } + break; case LightType::DIRECTIONAL: - { - char str[32]; - bool isON = !_directionalLight->isEnabled(); - sprintf(str, "Directional Light %s", isON == true ? "ON" : "OFF"); - _directionalLight->setEnabled(isON); - _directionalLightLabel->setString(str); - } - break; + { + char str[32]; + bool isON = !_directionalLight->isEnabled(); + sprintf(str, "Directional Light %s", isON == true? "ON":"OFF"); + _directionalLight->setEnabled(isON); + _directionalLightLabel->setString(str); + } + break; case LightType::POINT: - { - char str[32]; - bool isON = !_pointLight->isEnabled(); - sprintf(str, "Point Light %s", isON == true ? "ON" : "OFF"); - _pointLight->setEnabled(isON); - _pointLightLabel->setString(str); - } - break; + { + char str[32]; + bool isON = !_pointLight->isEnabled(); + sprintf(str, "Point Light %s", isON == true? "ON":"OFF"); + _pointLight->setEnabled(isON); + _pointLightLabel->setString(str); + } + break; case LightType::SPOT: - { - char str[32]; - bool isON = !_spotLight->isEnabled(); - sprintf(str, "Spot Light %s", isON == true ? "ON" : "OFF"); - _spotLight->setEnabled(isON); - _spotLightLabel->setString(str); - } - break; + { + char str[32]; + bool isON = !_spotLight->isEnabled(); + sprintf(str, "Spot Light %s", isON == true? "ON":"OFF"); + _spotLight->setEnabled(isON); + _spotLightLabel->setString(str); + } + break; default: break; diff --git a/tests/cpp-tests/Classes/LightTest/LightTest.h b/tests/cpp-tests/Classes/LightTest/LightTest.h index e7b32fb9a7..2112f1ce20 100644 --- a/tests/cpp-tests/Classes/LightTest/LightTest.h +++ b/tests/cpp-tests/Classes/LightTest/LightTest.h @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2013 cocos2d-x.org Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -44,10 +44,12 @@ public: void SwitchLight(cocos2d::Ref* sender, cocos2d::LightType lightType); private: + void addSprite(); void addLights(); private: + cocos2d::AmbientLight* _ambientLight; cocos2d::DirectionLight* _directionalLight; cocos2d::PointLight* _pointLight; @@ -60,3 +62,4 @@ private: }; #endif + diff --git a/tests/cpp-tests/Classes/MaterialSystemTest/MaterialSystemTest.cpp b/tests/cpp-tests/Classes/MaterialSystemTest/MaterialSystemTest.cpp index 54ecfbb029..de0539305e 100644 --- a/tests/cpp-tests/Classes/MaterialSystemTest/MaterialSystemTest.cpp +++ b/tests/cpp-tests/Classes/MaterialSystemTest/MaterialSystemTest.cpp @@ -37,6 +37,7 @@ USING_NS_CC; static void printProperties(Properties* properties, int indent); + // MARK: Tests MaterialSystemTest::MaterialSystemTest() @@ -65,7 +66,7 @@ void Material_Sprite3DTest::onEnter() sprite->setScale(8.f); sprite->setTexture("Sprite3DTest/boss.png"); this->addChild(sprite); - sprite->setPositionNormalized(Vec2(0.5f, 0.5f)); + sprite->setPositionNormalized(Vec2(0.5f,0.5f)); } std::string Material_Sprite3DTest::subtitle() const @@ -78,20 +79,25 @@ void Material_MultipleSprite3D::onEnter() MaterialSystemBaseTest::onEnter(); const char* names[] = { - "Sprite3DTest/ReskinGirl.c3b", "Sprite3DTest/ReskinGirl.c3b", "Sprite3DTest/ReskinGirl.c3b", - "Sprite3DTest/ReskinGirl.c3b", "Sprite3DTest/ReskinGirl.c3b", "Sprite3DTest/ReskinGirl.c3b", - "Sprite3DTest/ReskinGirl.c3b", "Sprite3DTest/ReskinGirl.c3b", + "Sprite3DTest/ReskinGirl.c3b", + "Sprite3DTest/ReskinGirl.c3b", + "Sprite3DTest/ReskinGirl.c3b", + "Sprite3DTest/ReskinGirl.c3b", + "Sprite3DTest/ReskinGirl.c3b", + "Sprite3DTest/ReskinGirl.c3b", + "Sprite3DTest/ReskinGirl.c3b", + "Sprite3DTest/ReskinGirl.c3b", }; const int totalNames = sizeof(names) / sizeof(names[0]); auto size = Director::getInstance()->getWinSize(); - for (int i = 0; i < totalNames; i++) + for(int i=0;iaddChild(sprite); - sprite->setPosition(Vec2((size.width / (totalNames + 1)) * (i + 1), size.height / 4)); + sprite->setPosition(Vec2((size.width/(totalNames+1))*(i+1), size.height/4)); sprite->setScale(3); } } @@ -113,7 +119,7 @@ void Material_2DEffects::onEnter() // Print the properties of every namespace within this one. printProperties(properties, 0); - Material* mat1 = Material::createWithProperties(properties); + Material *mat1 = Material::createWithProperties(properties); auto spriteBlur = Sprite::create("Images/grossini.png"); spriteBlur->setPositionNormalized(Vec2(0.2f, 0.5f)); @@ -137,13 +143,11 @@ void Material_2DEffects::onEnter() timeUniforms.clear(); -#define FETCH_CCTIME_LOCATION(sprite) \ - do \ - { \ - auto programState = sprite->getProgramState(); \ - auto location = programState->getUniformLocation("u_Time"); \ - timeUniforms.emplace_back(programState, location); \ - } while (0) +#define FETCH_CCTIME_LOCATION(sprite) do { \ + auto programState = sprite->getProgramState(); \ + auto location = programState->getUniformLocation("u_Time"); \ + timeUniforms.emplace_back(programState, location); \ + }while(0) FETCH_CCTIME_LOCATION(spriteBlur); FETCH_CCTIME_LOCATION(spriteOutline); @@ -165,7 +169,7 @@ void Material_2DEffects::updateCCTimeUniforms(float) { float time = Director::getInstance()->getTotalFrames() * Director::getInstance()->getAnimationInterval(); Vec4 random(time / 10.0f, time, time * 2.0f, time * 4.0f); - for (auto& loc : timeUniforms) + for (auto &loc : timeUniforms) { loc.programState->setUniform(loc.location, &random, sizeof(random)); } @@ -180,25 +184,21 @@ void Material_2DEffects::updateCCTimeUniforms(float) */ class EffectAutoBindingResolver : public backend::ProgramState::AutoBindingResolver { - virtual bool resolveAutoBinding(backend::ProgramState* programState, - /* Node* node,*/ std::string_view uniform, - std::string_view autoBinding) override; + virtual bool resolveAutoBinding(backend::ProgramState* programState,/* Node* node,*/ const std::string& uniform, const std::string& autoBinding) override; void callbackRadius(backend::ProgramState* programState, backend::UniformLocation uniform); void callbackColor(backend::ProgramState* programState, backend::UniformLocation uniform); }; -bool EffectAutoBindingResolver::resolveAutoBinding(backend::ProgramState* programState, - /*Node* node,*/ std::string_view uniform, - std::string_view autoBinding) +bool EffectAutoBindingResolver::resolveAutoBinding(backend::ProgramState* programState, /*Node* node,*/ const std::string& uniform, const std::string& autoBinding) { - if (autoBinding.compare("DYNAMIC_RADIUS") == 0) + if (autoBinding.compare("DYNAMIC_RADIUS")==0) { auto loc = programState->getUniformLocation(uniform); programState->setCallbackUniform(loc, CC_CALLBACK_2(EffectAutoBindingResolver::callbackRadius, this)); return true; } - else if (autoBinding.compare("OUTLINE_COLOR") == 0) + else if (autoBinding.compare("OUTLINE_COLOR")==0) { auto loc = programState->getUniformLocation(uniform); programState->setCallbackUniform(loc, CC_CALLBACK_2(EffectAutoBindingResolver::callbackColor, this)); @@ -207,13 +207,13 @@ bool EffectAutoBindingResolver::resolveAutoBinding(backend::ProgramState* progra return false; } -void EffectAutoBindingResolver::callbackRadius(backend::ProgramState* programState, backend::UniformLocation uniform) +void EffectAutoBindingResolver::callbackRadius(backend::ProgramState *programState, backend::UniformLocation uniform) { float f = CCRANDOM_0_1() * 10; programState->setUniform(uniform, &f, sizeof(f)); } -void EffectAutoBindingResolver::callbackColor(backend::ProgramState* programState, backend::UniformLocation uniform) +void EffectAutoBindingResolver::callbackColor(backend::ProgramState *programState, backend::UniformLocation uniform) { float r = CCRANDOM_0_1(); float g = CCRANDOM_0_1(); @@ -233,17 +233,18 @@ Material_AutoBindings::~Material_AutoBindings() delete _resolver; } + void Material_AutoBindings::onEnter() { MaterialSystemBaseTest::onEnter(); - // auto properties = Properties::createNonRefCounted("Materials/2d_effects.material#sample"); +// auto properties = Properties::createNonRefCounted("Materials/2d_effects.material#sample"); auto properties = Properties::createNonRefCounted("Materials/auto_binding_test.material#sample"); // Print the properties of every namespace within this one. printProperties(properties, 0); - Material* mat1 = Material::createWithProperties(properties); + Material *mat1 = Material::createWithProperties(properties); auto spriteBlur = Sprite::create("Images/grossini.png"); spriteBlur->setPositionNormalized(Vec2(0.2f, 0.5f)); @@ -266,8 +267,8 @@ void Material_AutoBindings::onEnter() spriteEdgeDetect->setProgramState(mat1->getTechniqueByName("edge_detect")->getPassByIndex(0)->getProgramState()); _noiseProgramState = spriteNoise->getProgramState(); - _locationTime = _noiseProgramState->getUniformLocation("u_Time"); - + _locationTime = _noiseProgramState->getUniformLocation("u_Time"); + schedule(CC_SCHEDULE_SELECTOR(Material_AutoBindings::updateUniformTime)); // properties is not a "Ref" object CC_SAFE_DELETE(properties); @@ -295,23 +296,24 @@ void Material_setTechnique::onEnter() auto sprite = Sprite3D::create("Sprite3DTest/boss1.obj"); sprite->setScale(6); this->addChild(sprite); - sprite->setPositionNormalized(Vec2(0.5f, 0.5f)); + sprite->setPositionNormalized(Vec2(0.5f,0.5f)); _sprite = sprite; - Material* mat = Material::createWithFilename("Materials/3d_effects.material"); + + Material *mat = Material::createWithFilename("Materials/3d_effects.material"); sprite->setMaterial(mat); // lights auto light1 = AmbientLight::create(Color3B::RED); addChild(light1); - auto light2 = DirectionLight::create(Vec3(-1, 1, 0), Color3B::GREEN); + auto light2 = DirectionLight::create(Vec3(-1,1,0), Color3B::GREEN); addChild(light2); - this->schedule(CC_CALLBACK_1(Material_setTechnique::changeMaterial, this), 1, "cookie"); + this->schedule(CC_CALLBACK_1(Material_setTechnique::changeMaterial, this), 1, "cookie"); _techniqueState = 0; - auto rot = RotateBy::create(5, Vec3(30.0f, 60.0f, 270.0f)); + auto rot = RotateBy::create(5, Vec3(30.0f,60.0f,270.0f)); auto repeat = RepeatForever::create(rot); sprite->runAction(repeat); } @@ -326,17 +328,17 @@ void Material_setTechnique::changeMaterial(float dt) // get it from Mesh 0 switch (_techniqueState) { - case 0: - _sprite->getMaterial(0)->setTechnique("lit"); - break; - case 1: - _sprite->getMaterial(0)->setTechnique("normal"); - break; - case 2: - _sprite->getMaterial(0)->setTechnique("outline"); - break; - default: - break; + case 0: + _sprite->getMaterial(0)->setTechnique("lit"); + break; + case 1: + _sprite->getMaterial(0)->setTechnique("normal"); + break; + case 2: + _sprite->getMaterial(0)->setTechnique("outline"); + break; + default: + break; } _techniqueState = (_techniqueState + 1) % 3; @@ -354,10 +356,10 @@ void Material_clone::onEnter() this->addChild(sprite); sprite->setPositionNormalized(Vec2(0.25f, 0.5f)); - Material* mat = Material::createWithFilename("Materials/3d_effects.material"); + Material *mat = Material::createWithFilename("Materials/3d_effects.material"); sprite->setMaterial(mat); - auto rot = RotateBy::create(5, Vec3(360.0f, 240.0f, 120.0f)); + auto rot = RotateBy::create(5, Vec3(360.0f,240.0f,120.0f)); auto repeat = RepeatForever::create(rot); sprite->runAction(repeat); @@ -383,7 +385,8 @@ void Material_clone::onEnter() mat->setTechnique("outline"); // should affect only sprite 3 - // mat2->setTechnique("normal"); +// mat2->setTechnique("normal"); + } std::string Material_clone::subtitle() const @@ -399,74 +402,76 @@ const int SHOW_LEBAL_TAG = 114; void Material_parsePerformance::onEnter() { MaterialSystemBaseTest::onEnter(); - + _maxParsingCoumt = 5e3; - + auto screenSize = Director::getInstance()->getWinSize(); - + ui::Slider* slider = ui::Slider::create(); slider->loadBarTexture("cocosui/sliderTrack.png"); slider->loadSlidBallTextures("cocosui/sliderThumb.png", "cocosui/sliderThumb.png", ""); slider->loadProgressBarTexture("cocosui/sliderProgress.png"); slider->setPercent(50); - + slider->setPosition(Vec2(screenSize.width / 2.0f, screenSize.height / 3.0f)); slider->addEventListener([&](Ref* sender, ui::Slider::EventType type) { + if (type == ui::Slider::EventType::ON_SLIDEBALL_UP) { ui::Slider* slider = dynamic_cast(sender); - float p = slider->getPercent() / 100.0f; + float p = slider->getPercent() / 100.0f; slider->setTouchEnabled(false); CCLOG("Will parsing material %d times", (int)(p * _maxParsingCoumt)); Label* label = dynamic_cast(this->getChildByTag(SHOW_LEBAL_TAG)); - if (label) + if(label) { label->setString("Testing start!"); } this->scheduleOnce( - [this, p, slider](float) { - this->parsingTesting(p * _maxParsingCoumt); - slider->setTouchEnabled(true); - }, - 1.0, "schedule test parsing"); + [this, p, slider](float) + { + this->parsingTesting(p * _maxParsingCoumt); + slider->setTouchEnabled(true); + }, + 1.0, "schedule test parsing"); + } }); - + addChild(slider); - - auto label = Label::createWithSystemFont( - "Max parsing count is 10000, which may crash because of high memory consumption.", "Helvetica", 10); + + auto label = Label::createWithSystemFont("Max parsing count is 10000, which may crash because of high memory consumption.", "Helvetica", 10); label->setPosition(Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f - 20)); addChild(label); label = Label::createWithSystemFont("Slide to test parsing performance", "Helvetica", 10); label->setPosition(Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f)); addChild(label); - + label = Label::createWithSystemFont("", "Helvetica", 10); label->setPosition(Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f + 20)); label->setTag(SHOW_LEBAL_TAG); addChild(label); + } void Material_parsePerformance::parsingTesting(unsigned int count) { std::clock_t begin = std::clock(); - + for (unsigned int i = 0; i < count; i++) { Material::createWithFilename("Materials/2d_effects.material"); Material::createWithFilename("Materials/3d_effects.material"); } - - std::clock_t end = std::clock(); + + std::clock_t end = std::clock(); double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; - Label* label = dynamic_cast(this->getChildByTag(SHOW_LEBAL_TAG)); - if (label) + Label* label = dynamic_cast(this->getChildByTag(SHOW_LEBAL_TAG)); + if(label) { - std::string str = StringUtils::format("Testing completed! Took: %.3f seconds for parsing material %d times.", - elapsed_secs, count); + std::string str = StringUtils::format("Testing completed! Took: %.3f seconds for parsing material %d times.", elapsed_secs, count); label->setString(str); - + CCLOG("Took: %.3f seconds for parsing material %d times.", elapsed_secs, count); } } @@ -482,17 +487,17 @@ static void printProperties(Properties* properties, int indent) { // Print the name and ID of the current namespace. const char* spacename = properties->getNamespace(); - const char* id = properties->getId(); + const char* id = properties->getId(); char chindent[64]; - int i = 0; - for (i = 0; i < indent * 2; i++) + int i=0; + for(i=0; igetNextProperty(); + const char* name = properties->getNextProperty(); const char* value = NULL; while (name != NULL) { @@ -504,9 +509,9 @@ static void printProperties(Properties* properties, int indent) Properties* space = properties->getNextNamespace(); while (space != NULL) { - printProperties(space, indent + 1); + printProperties(space, indent+1); space = properties->getNextNamespace(); } - log("%s}\n", chindent); + log("%s}\n",chindent); } diff --git a/tests/cpp-tests/Classes/MaterialSystemTest/MaterialSystemTest.h b/tests/cpp-tests/Classes/MaterialSystemTest/MaterialSystemTest.h index 518cfef708..5262858f9e 100644 --- a/tests/cpp-tests/Classes/MaterialSystemTest/MaterialSystemTest.h +++ b/tests/cpp-tests/Classes/MaterialSystemTest/MaterialSystemTest.h @@ -46,6 +46,7 @@ public: virtual void onEnter() override; virtual std::string subtitle() const override; + }; class Material_MultipleSprite3D : public MaterialSystemBaseTest @@ -65,15 +66,13 @@ public: virtual void onEnter() override; virtual std::string subtitle() const override; void updateCCTimeUniforms(float); - + private: - struct Locations - { - Locations(cocos2d::backend::ProgramState* ps, cocos2d::backend::UniformLocation loc) - : programState(ps), location(loc) - {} - - cocos2d::backend::ProgramState* programState = nullptr; + struct Locations { + Locations(cocos2d::backend::ProgramState *ps, cocos2d::backend::UniformLocation loc) + : programState(ps), location(loc) {} + + cocos2d::backend::ProgramState *programState = nullptr; cocos2d::backend::UniformLocation location; }; std::vector timeUniforms; @@ -95,8 +94,8 @@ public: private: cocos2d::backend::UniformLocation _locationTime; - EffectAutoBindingResolver* _resolver = nullptr; - cocos2d::backend::ProgramState* _noiseProgramState = nullptr; + EffectAutoBindingResolver *_resolver = nullptr; + cocos2d::backend::ProgramState *_noiseProgramState = nullptr; }; class Material_setTechnique : public MaterialSystemBaseTest @@ -131,7 +130,9 @@ public: virtual void onEnter() override; virtual std::string subtitle() const override; void parsingTesting(unsigned int count); - protected: unsigned int _maxParsingCoumt; }; + + + diff --git a/tests/cpp-tests/Classes/MenuTest/MenuTest.cpp b/tests/cpp-tests/Classes/MenuTest/MenuTest.cpp index 9a71dc99bc..9c2e36b0ba 100644 --- a/tests/cpp-tests/Classes/MenuTest/MenuTest.cpp +++ b/tests/cpp-tests/Classes/MenuTest/MenuTest.cpp @@ -29,22 +29,21 @@ USING_NS_CC; -enum -{ - kTagMenu = 1, - kTagMenu0 = 0, +enum { + kTagMenu = 1, + kTagMenu0 = 0, kTagMenu1 = 1, }; -#define MID_CALLBACK 1000 -#define MID_CALLBACK2 1001 -#define MID_DISABLED 1002 -#define MID_ENABLE 1003 -#define MID_CONFIG 1004 -#define MID_QUIT 1005 -#define MID_OPACITY 1006 -#define MID_ALIGN 1007 -#define MID_CALLBACK3 1008 +#define MID_CALLBACK 1000 +#define MID_CALLBACK2 1001 +#define MID_DISABLED 1002 +#define MID_ENABLE 1003 +#define MID_CONFIG 1004 +#define MID_QUIT 1005 +#define MID_OPACITY 1006 +#define MID_ALIGN 1007 +#define MID_CALLBACK3 1008 #define MID_BACKCALLBACK 1009 MenuTests::MenuTests() @@ -60,43 +59,42 @@ MenuLayerMainMenu::MenuLayerMainMenu() { _touchListener = EventListenerTouchOneByOne::create(); _touchListener->setSwallowTouches(true); - _touchListener->onTouchBegan = CC_CALLBACK_2(MenuLayerMainMenu::touchBegan, this); - _touchListener->onTouchMoved = CC_CALLBACK_2(MenuLayerMainMenu::touchMoved, this); - _touchListener->onTouchEnded = CC_CALLBACK_2(MenuLayerMainMenu::touchEnded, this); + _touchListener->onTouchBegan = CC_CALLBACK_2(MenuLayerMainMenu::touchBegan, this); + _touchListener->onTouchMoved = CC_CALLBACK_2(MenuLayerMainMenu::touchMoved, this); + _touchListener->onTouchEnded = CC_CALLBACK_2(MenuLayerMainMenu::touchEnded, this); _touchListener->onTouchCancelled = CC_CALLBACK_2(MenuLayerMainMenu::touchCancelled, this); _eventDispatcher->addEventListenerWithFixedPriority(_touchListener, 1); + + // Font Item + auto spriteNormal = Sprite::create(s_MenuItem, Rect(0,23*2,115,23)); + auto spriteSelected = Sprite::create(s_MenuItem, Rect(0,23*1,115,23)); + auto spriteDisabled = Sprite::create(s_MenuItem, Rect(0,23*0,115,23)); - // Font Item - auto spriteNormal = Sprite::create(s_MenuItem, Rect(0, 23 * 2, 115, 23)); - auto spriteSelected = Sprite::create(s_MenuItem, Rect(0, 23 * 1, 115, 23)); - auto spriteDisabled = Sprite::create(s_MenuItem, Rect(0, 23 * 0, 115, 23)); - - auto item1 = MenuItemSprite::create(spriteNormal, spriteSelected, spriteDisabled, - CC_CALLBACK_1(MenuLayerMainMenu::menuCallback, this)); - + auto item1 = MenuItemSprite::create(spriteNormal, spriteSelected, spriteDisabled, CC_CALLBACK_1(MenuLayerMainMenu::menuCallback, this) ); + // Image Item - auto item2 = - MenuItemImage::create(s_SendScore, s_PressSendScore, CC_CALLBACK_1(MenuLayerMainMenu::menuCallback2, this)); + auto item2 = MenuItemImage::create(s_SendScore, s_PressSendScore, CC_CALLBACK_1(MenuLayerMainMenu::menuCallback2, this) ); // Label Item (LabelAtlas) auto labelAtlas = LabelAtlas::create("0123456789", "fonts/labelatlas.png", 16, 24, '.'); - auto item3 = MenuItemLabel::create(labelAtlas, CC_CALLBACK_1(MenuLayerMainMenu::menuCallbackDisabled, this)); - item3->setDisabledColor(Color3B(32, 32, 64)); - item3->setColor(Color3B(200, 200, 255)); - CCLOG("test MenuItem Label getString: %s", item3->getString().data()); + auto item3 = MenuItemLabel::create(labelAtlas, CC_CALLBACK_1(MenuLayerMainMenu::menuCallbackDisabled, this) ); + item3->setDisabledColor( Color3B(32,32,64) ); + item3->setColor( Color3B(200,200,255) ); + CCLOG("test MenuItem Label getString: %s", item3->getString().c_str()); // Font Item - auto item4 = MenuItemFont::create("I toggle enable items", - [&](Ref* sender) { _disabledItem->setEnabled(!_disabledItem->isEnabled()); }); + auto item4 = MenuItemFont::create("I toggle enable items", [&](Ref *sender) { + _disabledItem->setEnabled(! _disabledItem->isEnabled() ); + }); item4->setFontSizeObj(20); item4->setFontName("fonts/Marker Felt.ttf"); - + // Label Item (LabelBMFont) auto label = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "configuration"); auto item5 = MenuItemLabel::create(label, CC_CALLBACK_1(MenuLayerMainMenu::menuCallbackConfig, this)); // Testing issue #500 - item5->setScale(0.8f); + item5->setScale( 0.8f ); // Events MenuItemFont::setFontName("fonts/Marker Felt.ttf"); @@ -104,56 +102,62 @@ MenuLayerMainMenu::MenuLayerMainMenu() auto item6 = MenuItemFont::create("Bugs", CC_CALLBACK_1(MenuLayerMainMenu::menuCallbackBugsTest, this)); // Font Item - auto item7 = MenuItemFont::create("Quit", CC_CALLBACK_1(MenuLayerMainMenu::onQuit, this)); - - auto item8 = MenuItemFont::create("Remove menu item when moving", - CC_CALLBACK_1(MenuLayerMainMenu::menuMovingCallback, this)); - + auto item7= MenuItemFont::create("Quit", CC_CALLBACK_1(MenuLayerMainMenu::onQuit, this)); + + auto item8 = MenuItemFont::create("Remove menu item when moving", CC_CALLBACK_1(MenuLayerMainMenu::menuMovingCallback, this)); + auto color_action = TintBy::create(0.5f, 0, -255, -255); - auto color_back = color_action->reverse(); - auto seq = Sequence::create(color_action, color_back, nullptr); + auto color_back = color_action->reverse(); + auto seq = Sequence::create(color_action, color_back, nullptr); item7->runAction(RepeatForever::create(seq)); - auto menu = Menu::create(item1, item2, item3, item4, item5, item6, item7, item8, nullptr); + auto menu = Menu::create( item1, item2, item3, item4, item5, item6, item7, item8, nullptr); menu->alignItemsVertically(); - + + // elastic effect auto s = Director::getInstance()->getWinSize(); - - int i = 0; - for (const auto& child : menu->getChildren()) - { + + int i=0; + for(const auto &child : menu->getChildren()) { auto dstPoint = child->getPosition(); - int offset = (int)(s.width / 2 + 50); - if (i % 2 == 0) + int offset = (int) (s.width/2 + 50); + if( i % 2 == 0) offset = -offset; - - child->setPosition(Vec2(dstPoint.x + offset, dstPoint.y)); - child->runAction(EaseElasticOut::create(MoveBy::create(2, Vec2(dstPoint.x - offset, 0.0f)), 0.35f)); + + child->setPosition( Vec2( dstPoint.x + offset, dstPoint.y) ); + child->runAction( + EaseElasticOut::create(MoveBy::create(2, Vec2(dstPoint.x - offset,0.0f)), 0.35f) + ); i++; } - _disabledItem = item3; - item3->retain(); - _disabledItem->setEnabled(false); + _disabledItem = item3; item3->retain(); + _disabledItem->setEnabled( false ); addChild(menu); menu->setTag(100); - menu->setPosition(Vec2(s.width / 2, s.height / 2)); + menu->setPosition(Vec2(s.width/2, s.height/2)); menu->setScale(0); - menu->runAction(ScaleTo::create(1, 1)); + menu->runAction(ScaleTo::create(1,1)); } -bool MenuLayerMainMenu::touchBegan(Touch* touch, Event* event) +bool MenuLayerMainMenu::touchBegan(Touch *touch, Event * event) { return true; } -void MenuLayerMainMenu::touchEnded(Touch* touch, Event* event) {} +void MenuLayerMainMenu::touchEnded(Touch *touch, Event * event) +{ +} -void MenuLayerMainMenu::touchCancelled(Touch* touch, Event* event) {} +void MenuLayerMainMenu::touchCancelled(Touch *touch, Event * event) +{ +} -void MenuLayerMainMenu::touchMoved(Touch* touch, Event* event) {} +void MenuLayerMainMenu::touchMoved(Touch *touch, Event * event) +{ +} MenuLayerMainMenu::~MenuLayerMainMenu() { @@ -178,7 +182,7 @@ void MenuLayerMainMenu::allowTouches(float dt) log("TOUCHES ALLOWED AGAIN"); } -void MenuLayerMainMenu::menuCallbackDisabled(Ref* sender) +void MenuLayerMainMenu::menuCallbackDisabled(Ref* sender) { // hijack all touch events for 5 seconds _eventDispatcher->setPriority(_touchListener, -1); @@ -191,7 +195,7 @@ void MenuLayerMainMenu::menuCallback2(Ref* sender) static_cast(_parent)->switchTo(2, false); } -void MenuLayerMainMenu::menuCallbackBugsTest(Ref* pSender) +void MenuLayerMainMenu::menuCallbackBugsTest(Ref *pSender) { static_cast(_parent)->switchTo(4, false); } @@ -199,10 +203,10 @@ void MenuLayerMainMenu::menuCallbackBugsTest(Ref* pSender) void MenuLayerMainMenu::onQuit(Ref* sender) { //[[Director sharedDirector] end]; - // getCocosApp()->exit(); + //getCocosApp()->exit(); } -void MenuLayerMainMenu::menuMovingCallback(Ref* pSender) +void MenuLayerMainMenu::menuMovingCallback(Ref *pSender) { static_cast(_parent)->switchTo(5, false); } @@ -214,26 +218,24 @@ void MenuLayerMainMenu::menuMovingCallback(Ref* pSender) //------------------------------------------------------------------ MenuLayer2::MenuLayer2() { - for (int i = 0; i < 2; i++) + for( int i=0;i < 2;i++ ) { auto item1 = MenuItemImage::create(s_PlayNormal, s_PlaySelect, CC_CALLBACK_1(MenuLayer2::menuCallback, this)); - auto item2 = - MenuItemImage::create(s_HighNormal, s_HighSelect, CC_CALLBACK_1(MenuLayer2::menuCallbackOpacity, this)); - auto item3 = - MenuItemImage::create(s_AboutNormal, s_AboutSelect, CC_CALLBACK_1(MenuLayer2::menuCallbackAlign, this)); - - item1->setScaleX(1.5f); - item2->setScaleX(0.5f); - item3->setScaleX(0.5f); - + auto item2 = MenuItemImage::create(s_HighNormal, s_HighSelect, CC_CALLBACK_1(MenuLayer2::menuCallbackOpacity, this)); + auto item3 = MenuItemImage::create(s_AboutNormal, s_AboutSelect, CC_CALLBACK_1(MenuLayer2::menuCallbackAlign, this)); + + item1->setScaleX( 1.5f ); + item2->setScaleX( 0.5f ); + item3->setScaleX( 0.5f ); + auto menu = Menu::create(item1, item2, item3, nullptr); - + auto s = Director::getInstance()->getWinSize(); - menu->setPosition(Vec2(s.width / 2, s.height / 2)); + menu->setPosition(Vec2(s.width/2, s.height/2)); - menu->setTag(kTagMenu); - - addChild(menu, 0, 100 + i); + menu->setTag( kTagMenu ); + + addChild(menu, 0, 100+i); _centeredMenu = menu->getPosition(); } @@ -242,51 +244,54 @@ MenuLayer2::MenuLayer2() alignMenusH(); } -MenuLayer2::~MenuLayer2() {} +MenuLayer2::~MenuLayer2() +{ +} void MenuLayer2::alignMenusH() { - for (int i = 0; i < 2; i++) + for(int i=0;i<2;i++) { - auto menu = static_cast(getChildByTag(100 + i)); - menu->setPosition(_centeredMenu); - if (i == 0) + auto menu = static_cast( getChildByTag(100+i) ); + menu->setPosition( _centeredMenu ); + if(i==0) { // TIP: if no padding, padding = 5 - menu->alignItemsHorizontally(); + menu->alignItemsHorizontally(); auto p = menu->getPosition(); - menu->setPosition(p + Vec2(0.0f, 30.0f)); - } - else + menu->setPosition(p + Vec2(0.0f,30.0f)); + + } + else { // TIP: but padding is configurable menu->alignItemsHorizontallyWithPadding(40); auto p = menu->getPosition(); - menu->setPosition(p - Vec2(0.0f, 30.0f)); - } + menu->setPosition(p - Vec2(0.0f,30.0f)); + } } } void MenuLayer2::alignMenusV() { - for (int i = 0; i < 2; i++) + for(int i=0;i<2;i++) { - auto menu = static_cast(getChildByTag(100 + i)); - menu->setPosition(_centeredMenu); - if (i == 0) + auto menu = static_cast( getChildByTag(100+i) ); + menu->setPosition( _centeredMenu ); + if(i==0) { // TIP: if no padding, padding = 5 - menu->alignItemsVertically(); + menu->alignItemsVertically(); auto p = menu->getPosition(); - menu->setPosition(p + Vec2(100.0f, 0.0f)); - } - else + menu->setPosition(p + Vec2(100.0f,0.0f)); + } + else { // TIP: but padding is configurable - menu->alignItemsVerticallyWithPadding(40); + menu->alignItemsVerticallyWithPadding(40); auto p = menu->getPosition(); - menu->setPosition(p - Vec2(100.0f, 0.0f)); - } + menu->setPosition(p - Vec2(100.0f,0.0f)); + } } } @@ -297,22 +302,22 @@ void MenuLayer2::menuCallback(Ref* sender) void MenuLayer2::menuCallbackOpacity(Ref* sender) { - auto menu = static_cast(static_cast(sender)->getParent()); + auto menu = static_cast( static_cast(sender)->getParent() ); uint8_t opacity = menu->getOpacity(); - if (opacity == 128) + if( opacity == 128 ) menu->setOpacity(255); else - menu->setOpacity(128); + menu->setOpacity(128); } void MenuLayer2::menuCallbackAlign(Ref* sender) { - _alignedH = !_alignedH; - - if (_alignedH) + _alignedH = ! _alignedH; + + if( _alignedH ) alignMenusH(); else - alignMenusV(); + alignMenusV(); } //------------------------------------------------------------------ @@ -326,47 +331,49 @@ MenuLayer3::MenuLayer3() MenuItemFont::setFontSize(28); auto label = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "Enable AtlasItem"); - auto item1 = MenuItemLabel::create(label, [&](Ref* sender) { - // CCLOG("Label clicked. Toggling AtlasSprite"); - _disabledItem->setEnabled(!_disabledItem->isEnabled()); - _disabledItem->stopAllActions(); - }); - auto item2 = MenuItemFont::create("--- Go Back ---", - [&](Ref* sender) { static_cast(_parent)->switchTo(0, false); }); + auto item1 = MenuItemLabel::create(label, [&](Ref *sender) { + //CCLOG("Label clicked. Toggling AtlasSprite"); + _disabledItem->setEnabled( ! _disabledItem->isEnabled() ); + _disabledItem->stopAllActions(); + }); + auto item2 = MenuItemFont::create("--- Go Back ---", [&](Ref *sender) { + static_cast(_parent)->switchTo(0, false); + }); - auto spriteNormal = Sprite::create(s_MenuItem, Rect(0, 23 * 2, 115, 23)); - auto spriteSelected = Sprite::create(s_MenuItem, Rect(0, 23 * 1, 115, 23)); - auto spriteDisabled = Sprite::create(s_MenuItem, Rect(0, 23 * 0, 115, 23)); - - auto item3 = MenuItemSprite::create(spriteNormal, spriteSelected, spriteDisabled, - [](Ref* sender) { log("sprite clicked!"); }); - _disabledItem = item3; - item3->retain(); - _disabledItem->setEnabled(false); - - auto menu = Menu::create(item1, item2, item3, nullptr); - menu->setPosition(Vec2(0, 0)); + auto spriteNormal = Sprite::create(s_MenuItem, Rect(0,23*2,115,23)); + auto spriteSelected = Sprite::create(s_MenuItem, Rect(0,23*1,115,23)); + auto spriteDisabled = Sprite::create(s_MenuItem, Rect(0,23*0,115,23)); + + + auto item3 = MenuItemSprite::create(spriteNormal, spriteSelected, spriteDisabled, [](Ref *sender) { + log("sprite clicked!"); + }); + _disabledItem = item3; item3->retain(); + _disabledItem->setEnabled( false ); + + auto menu = Menu::create( item1, item2, item3, nullptr); + menu->setPosition( Vec2(0,0) ); auto s = Director::getInstance()->getWinSize(); - - item1->setPosition(Vec2(s.width / 2 - 150, s.height / 2)); - item2->setPosition(Vec2(s.width / 2 - 200, s.height / 2)); - item3->setPosition(Vec2(s.width / 2, s.height / 2 - 100)); - - auto jump = JumpBy::create(3, Vec2(400, 0), 50, 4); - item2->runAction(RepeatForever::create(Sequence::create(jump, jump->reverse(), nullptr))); + + item1->setPosition( Vec2(s.width/2 - 150, s.height/2) ); + item2->setPosition( Vec2(s.width/2 - 200, s.height/2) ); + item3->setPosition( Vec2(s.width/2, s.height/2 - 100) ); + + auto jump = JumpBy::create(3, Vec2(400,0), 50, 4); + item2->runAction( RepeatForever::create(Sequence::create( jump, jump->reverse(), nullptr))); auto spin1 = RotateBy::create(3, 360); auto spin2 = spin1->clone(); auto spin3 = spin1->clone(); + + item1->runAction( RepeatForever::create(spin1) ); + item2->runAction( RepeatForever::create(spin2) ); + item3->runAction( RepeatForever::create(spin3) ); + + addChild( menu ); - item1->runAction(RepeatForever::create(spin1)); - item2->runAction(RepeatForever::create(spin2)); - item3->runAction(RepeatForever::create(spin3)); - - addChild(menu); - - menu->setPosition(Vec2(0, 0)); + menu->setPosition(Vec2(0,0)); } MenuLayer3::~MenuLayer3() @@ -385,68 +392,81 @@ MenuLayer4::MenuLayer4() MenuItemFont::setFontSize(18); auto title1 = MenuItemFont::create("Sound"); title1->setEnabled(false); - MenuItemFont::setFontName("fonts/Marker Felt.ttf"); + MenuItemFont::setFontName( "fonts/Marker Felt.ttf" ); MenuItemFont::setFontSize(34); - auto item1 = MenuItemToggle::createWithCallback(CC_CALLBACK_1(MenuLayer4::menuCallback, this), - MenuItemFont::create("On"), MenuItemFont::create("Off"), nullptr); - - MenuItemFont::setFontName("American Typewriter"); + auto item1 = MenuItemToggle::createWithCallback( CC_CALLBACK_1(MenuLayer4::menuCallback, this), + MenuItemFont::create( "On" ), + MenuItemFont::create( "Off"), + nullptr ); + + MenuItemFont::setFontName( "American Typewriter" ); MenuItemFont::setFontSize(18); - auto title2 = MenuItemFont::create("Music"); + auto title2 = MenuItemFont::create( "Music" ); title2->setEnabled(false); - MenuItemFont::setFontName("fonts/Marker Felt.ttf"); + MenuItemFont::setFontName( "fonts/Marker Felt.ttf" ); MenuItemFont::setFontSize(34); auto item2 = MenuItemToggle::createWithCallback(CC_CALLBACK_1(MenuLayer4::menuCallback, this), - MenuItemFont::create("On"), MenuItemFont::create("Off"), nullptr); - - MenuItemFont::setFontName("American Typewriter"); + MenuItemFont::create( "On" ), + MenuItemFont::create( "Off"), + nullptr ); + + MenuItemFont::setFontName( "American Typewriter" ); MenuItemFont::setFontSize(18); - auto title3 = MenuItemFont::create("Quality"); - title3->setEnabled(false); - MenuItemFont::setFontName("fonts/Marker Felt.ttf"); + auto title3 = MenuItemFont::create( "Quality" ); + title3->setEnabled( false ); + MenuItemFont::setFontName( "fonts/Marker Felt.ttf" ); MenuItemFont::setFontSize(34); auto item3 = MenuItemToggle::createWithCallback(CC_CALLBACK_1(MenuLayer4::menuCallback, this), - MenuItemFont::create("High"), MenuItemFont::create("Low"), nullptr); - - MenuItemFont::setFontName("American Typewriter"); + MenuItemFont::create( "High" ), + MenuItemFont::create( "Low" ), + nullptr ); + + MenuItemFont::setFontName( "American Typewriter" ); MenuItemFont::setFontSize(18); - auto title4 = MenuItemFont::create("Orientation"); + auto title4 = MenuItemFont::create( "Orientation" ); title4->setEnabled(false); - MenuItemFont::setFontName("fonts/Marker Felt.ttf"); + MenuItemFont::setFontName( "fonts/Marker Felt.ttf" ); MenuItemFont::setFontSize(34); auto item4 = MenuItemToggle::createWithCallback(CC_CALLBACK_1(MenuLayer4::menuCallback, this), - MenuItemFont::create("Off"), nullptr); - + MenuItemFont::create( "Off" ), + nullptr ); + // TIP: you can manipulate the items like any other MutableArray - item4->getSubItems().pushBack(MenuItemFont::create("33%")); - item4->getSubItems().pushBack(MenuItemFont::create("66%")); - item4->getSubItems().pushBack(MenuItemFont::create("100%")); - + item4->getSubItems().pushBack( MenuItemFont::create( "33%" ) ); + item4->getSubItems().pushBack( MenuItemFont::create( "66%" ) ); + item4->getSubItems().pushBack( MenuItemFont::create( "100%" ) ); + // you can change the one of the items by doing this - item4->setSelectedIndex(2); - - MenuItemFont::setFontName("fonts/Marker Felt.ttf"); - MenuItemFont::setFontSize(34); - - auto label = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "go back"); - auto back = MenuItemLabel::create(label, CC_CALLBACK_1(MenuLayer4::backCallback, this)); - - auto menu = Menu::create(title1, title2, item1, item2, title3, title4, item3, item4, back, nullptr); // 9 items. - + item4->setSelectedIndex( 2 ); + + MenuItemFont::setFontName( "fonts/Marker Felt.ttf" ); + MenuItemFont::setFontSize( 34 ); + + auto label = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "go back"); + auto back = MenuItemLabel::create(label, CC_CALLBACK_1(MenuLayer4::backCallback, this) ); + + auto menu = Menu::create( + title1, title2, + item1, item2, + title3, title4, + item3, item4, + back, nullptr ); // 9 items. + menu->alignItemsInColumns(2, 2, 2, 2, 1, NULL); - - addChild(menu); + + addChild( menu ); auto s = Director::getInstance()->getWinSize(); - menu->setPosition(Vec2(s.width / 2, s.height / 2)); + menu->setPosition(Vec2(s.width/2, s.height/2)); } -MenuLayer4::~MenuLayer4() {} +MenuLayer4::~MenuLayer4() +{ +} void MenuLayer4::menuCallback(Ref* sender) { - // CCLOG("selected item: %x index:%d", dynamic_cast(sender)->selectedItem(), - // dynamic_cast(sender)->selectedIndex() ); + //CCLOG("selected item: %x index:%d", dynamic_cast(sender)->selectedItem(), dynamic_cast(sender)->selectedIndex() ); } void MenuLayer4::backCallback(Ref* sender) @@ -457,37 +477,37 @@ void MenuLayer4::backCallback(Ref* sender) // BugsTest BugsTest::BugsTest() { - auto issue1410 = MenuItemFont::create("Issue 1410", CC_CALLBACK_1(BugsTest::issue1410MenuCallback, this)); + auto issue1410 = MenuItemFont::create("Issue 1410", CC_CALLBACK_1(BugsTest::issue1410MenuCallback, this)); auto issue1410_2 = MenuItemFont::create("Issue 1410 #2", CC_CALLBACK_1(BugsTest::issue1410v2MenuCallback, this)); - auto back = MenuItemFont::create("Back", CC_CALLBACK_1(BugsTest::backMenuCallback, this)); - + auto back = MenuItemFont::create("Back", CC_CALLBACK_1(BugsTest::backMenuCallback, this)); + auto menu = Menu::create(issue1410, issue1410_2, back, nullptr); addChild(menu); menu->alignItemsVertically(); - + auto s = Director::getInstance()->getWinSize(); - menu->setPosition(Vec2(s.width / 2, s.height / 2)); + menu->setPosition(Vec2(s.width/2, s.height/2)); } -void BugsTest::issue1410MenuCallback(Ref* sender) +void BugsTest::issue1410MenuCallback(Ref *sender) { - auto menu = static_cast(static_cast(sender)->getParent()); + auto menu = static_cast( static_cast(sender)->getParent() ); menu->setEnabled(false); menu->setEnabled(true); - + log("NO CRASHES"); } -void BugsTest::issue1410v2MenuCallback(cocos2d::Ref* pSender) +void BugsTest::issue1410v2MenuCallback(cocos2d::Ref *pSender) { - auto menu = static_cast(static_cast(pSender)->getParent()); + auto menu = static_cast( static_cast(pSender)->getParent() ); menu->setEnabled(true); menu->setEnabled(false); - + log("NO CRASHES. AND MENU SHOULD STOP WORKING"); } -void BugsTest::backMenuCallback(cocos2d::Ref* pSender) +void BugsTest::backMenuCallback(cocos2d::Ref *pSender) { static_cast(_parent)->switchTo(0, false); } @@ -495,33 +515,34 @@ void BugsTest::backMenuCallback(cocos2d::Ref* pSender) RemoveMenuItemWhenMove::RemoveMenuItemWhenMove() { auto s = Director::getInstance()->getWinSize(); - + auto label = Label::createWithTTF("click item and move, should not crash", "fonts/arial.ttf", 20); - label->setPosition(Vec2(s.width / 2, s.height - 30)); + label->setPosition(Vec2(s.width/2, s.height - 30)); addChild(label); - + item = MenuItemFont::create("item 1"); item->retain(); - + auto back = MenuItemFont::create("go back", CC_CALLBACK_1(RemoveMenuItemWhenMove::goBack, this)); - + auto menu = Menu::create(item, back, nullptr); addChild(menu); menu->alignItemsVertically(); - - menu->setPosition(Vec2(s.width / 2, s.height / 2)); - + + menu->setPosition(Vec2(s.width/2, s.height/2)); + // Register Touch Event _touchListener = EventListenerTouchOneByOne::create(); _touchListener->setSwallowTouches(false); - + _touchListener->onTouchBegan = CC_CALLBACK_2(RemoveMenuItemWhenMove::onTouchBegan, this); _touchListener->onTouchMoved = CC_CALLBACK_2(RemoveMenuItemWhenMove::onTouchMoved, this); - + _eventDispatcher->addEventListenerWithFixedPriority(_touchListener, -129); + } -void RemoveMenuItemWhenMove::goBack(Ref* pSender) +void RemoveMenuItemWhenMove::goBack(Ref *pSender) { static_cast(_parent)->switchTo(0, false); } @@ -532,12 +553,12 @@ RemoveMenuItemWhenMove::~RemoveMenuItemWhenMove() CC_SAFE_RELEASE(item); } -bool RemoveMenuItemWhenMove::onTouchBegan(Touch* touch, Event* event) +bool RemoveMenuItemWhenMove::onTouchBegan(Touch *touch, Event *event) { return true; } -void RemoveMenuItemWhenMove::onTouchMoved(Touch* touch, Event* event) +void RemoveMenuItemWhenMove::onTouchMoved(Touch *touch, Event *event) { if (item) { diff --git a/tests/cpp-tests/Classes/MenuTest/MenuTest.h b/tests/cpp-tests/Classes/MenuTest/MenuTest.h index cd505ef4be..7c6f82c517 100644 --- a/tests/cpp-tests/Classes/MenuTest/MenuTest.h +++ b/tests/cpp-tests/Classes/MenuTest/MenuTest.h @@ -43,7 +43,7 @@ public: class MenuLayerMainMenu : public cocos2d::Layer { protected: - cocos2d::MenuItem* _disabledItem; + cocos2d::MenuItem* _disabledItem; cocos2d::EventListenerTouchOneByOne* _touchListener; public: @@ -66,14 +66,14 @@ public: void onQuit(cocos2d::Ref* sender); void menuMovingCallback(cocos2d::Ref* pSender); - // CREATE_NODE(MenuLayer1); + //CREATE_NODE(MenuLayer1); }; class MenuLayer2 : public cocos2d::Layer { protected: - cocos2d::Vec2 _centeredMenu; - bool _alignedH; + cocos2d::Vec2 _centeredMenu; + bool _alignedH; void alignMenusH(); void alignMenusV(); @@ -86,13 +86,13 @@ public: void menuCallbackOpacity(cocos2d::Ref* sender); void menuCallbackAlign(cocos2d::Ref* sender); - // CREATE_NODE(MenuLayer2); + //CREATE_NODE(MenuLayer2); }; class MenuLayer3 : public cocos2d::Layer { protected: - cocos2d::MenuItem* _disabledItem; + cocos2d::MenuItem* _disabledItem; public: MenuLayer3(); @@ -113,7 +113,7 @@ class BugsTest : public cocos2d::Layer { public: BugsTest(); - + void issue1410MenuCallback(cocos2d::Ref* pSender); void issue1410v2MenuCallback(cocos2d::Ref* pSender); void backMenuCallback(cocos2d::Ref* pSender); @@ -126,11 +126,11 @@ public: ~RemoveMenuItemWhenMove(); bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event); void onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event); - + void goBack(cocos2d::Ref* pSender); - + private: - cocos2d::MenuItemFont* item; + cocos2d::MenuItemFont *item; cocos2d::EventListenerTouchOneByOne* _touchListener; }; diff --git a/tests/cpp-tests/Classes/MotionStreakTest/MotionStreakTest.cpp b/tests/cpp-tests/Classes/MotionStreakTest/MotionStreakTest.cpp index 24e21b1f66..b016c17898 100644 --- a/tests/cpp-tests/Classes/MotionStreakTest/MotionStreakTest.cpp +++ b/tests/cpp-tests/Classes/MotionStreakTest/MotionStreakTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,11 +27,10 @@ USING_NS_CC; -enum -{ - kTagLabel = 1, - kTagSprite1 = 2, - kTagSprite2 = 3, +enum { + kTagLabel = 1, + kTagSprite1 = 2, + kTagSprite2 = 3, }; MotionStreakTests::MotionStreakTests() @@ -53,41 +52,46 @@ void MotionStreakTest1::onEnter() MotionStreakTest::onEnter(); auto s = Director::getInstance()->getWinSize(); - + // the root object just rotates around _root = Sprite::create(s_pathR1); addChild(_root, 1); - _root->setPosition(Vec2(s.width / 2, s.height / 2)); - + _root->setPosition(Vec2(s.width/2, s.height/2)); + // the target object is offset from root, and the streak is moved to follow it _target = Sprite::create(s_pathR1); _root->addChild(_target); - _target->setPosition(Vec2(s.width / 4, 0.0f)); + _target->setPosition(Vec2(s.width/4, 0.0f)); // create the streak object and add it to the scene _streak = MotionStreak::create(2, 3, 32, Color3B::GREEN, s_streak); addChild(_streak); // schedule an update on each frame so we can synchronize the streak with the target schedule(CC_SCHEDULE_SELECTOR(MotionStreakTest1::onUpdate)); - + auto a1 = RotateBy::create(2, 360); auto action1 = RepeatForever::create(a1); - auto motion = MoveBy::create(2, Vec2(100, 0)); - _root->runAction(RepeatForever::create(Sequence::create(motion, motion->reverse(), nullptr))); - _root->runAction(action1); + auto motion = MoveBy::create(2, Vec2(100,0) ); + _root->runAction( RepeatForever::create(Sequence::create(motion, motion->reverse(), nullptr) ) ); + _root->runAction( action1 ); auto colorAction = RepeatForever::create(Sequence::create( - TintTo::create(0.2f, 255, 0, 0), TintTo::create(0.2f, 0, 255, 0), TintTo::create(0.2f, 0, 0, 255), - TintTo::create(0.2f, 0, 255, 255), TintTo::create(0.2f, 255, 255, 0), TintTo::create(0.2f, 255, 0, 255), - TintTo::create(0.2f, 255, 255, 255), nullptr)); + TintTo::create(0.2f, 255, 0, 0), + TintTo::create(0.2f, 0, 255, 0), + TintTo::create(0.2f, 0, 0, 255), + TintTo::create(0.2f, 0, 255, 255), + TintTo::create(0.2f, 255, 255, 0), + TintTo::create(0.2f, 255, 0, 255), + TintTo::create(0.2f, 255, 255, 255), + nullptr)); _streak->runAction(colorAction); } void MotionStreakTest1::onUpdate(float delta) { - _streak->setPosition(_target->convertToWorldSpace(Vec2::ZERO)); + _streak->setPosition( _target->convertToWorldSpace(Vec2::ZERO) ); } std::string MotionStreakTest1::title() const @@ -105,24 +109,24 @@ void MotionStreakTest2::onEnter() { MotionStreakTest::onEnter(); - auto listener = EventListenerTouchAllAtOnce::create(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesMoved = CC_CALLBACK_2(MotionStreakTest2::onTouchesMoved, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - + auto s = Director::getInstance()->getWinSize(); - + // create the streak object and add it to the scene - _streak = MotionStreak::create(3, 3, 64, Color3B::WHITE, s_streak); + _streak = MotionStreak::create(3, 3, 64, Color3B::WHITE, s_streak ); addChild(_streak); - - _streak->setPosition(Vec2(s.width / 2, s.height / 2)); + + _streak->setPosition( Vec2(s.width/2, s.height/2) ); } void MotionStreakTest2::onTouchesMoved(const std::vector& touches, Event* event) { auto touchLocation = touches[0]->getLocation(); - - _streak->setPosition(touchLocation); + + _streak->setPosition( touchLocation ); } std::string MotionStreakTest2::title() const @@ -144,25 +148,26 @@ std::string MotionStreakTest2::subtitle() const void Issue1358::onEnter() { MotionStreakTest::onEnter(); - + // ask director the the window size auto size = Director::getInstance()->getWinSize(); - + _streak = MotionStreak::create(2.0f, 1.0f, 50.0f, Color3B(255, 255, 0), "Images/Icon.png"); addChild(_streak); - - _center = Vec2(size.width / 2, size.height / 2); - _radius = size.width / 3; - _angle = 0.0f; - + + + _center = Vec2(size.width/2, size.height/2); + _radius = size.width/3; + _angle = 0.0f; + schedule(CC_SCHEDULE_SELECTOR(Issue1358::update), 0); } void Issue1358::update(float dt) { _angle += 1.0f; - _streak->setPosition( - Vec2(_center.x + cosf(_angle / 180 * M_PI) * _radius, _center.y + sinf(_angle / 180 * M_PI) * _radius)); + _streak->setPosition(Vec2(_center.x + cosf(_angle/180 * M_PI)*_radius, + _center.y + sinf(_angle/ 180 * M_PI)*_radius)); } std::string Issue1358::title() const @@ -188,14 +193,15 @@ void Issue12226::onEnter() // ask director the the window size auto size = Director::getInstance()->getWinSize(); - auto radius = size.width / 3; + auto radius = size.width/3; auto outer = Sprite::create("Images/grossini.png"); - outer->setPosition(size / 2); + outer->setPosition(size/2); addChild(outer); + _streak = MotionStreak::create(1.0f, 3, radius * 1.5f, Color3B(0xA0, 0xA0, 0xA0), "ccb/particle-smoke.png"); - // motionStreak->setOpacity(0x70); +// motionStreak->setOpacity(0x70); _streak->setPosition(outer->getPosition()); this->addChild(_streak, outer->getLocalZOrder() - 1); @@ -205,18 +211,19 @@ void Issue12226::onEnter() const uint32_t length = (radius * 0.95); std::function updateMotionStreak = [=](float dt) { - Vec2 position = - Vec2(outer->getPositionX() + length * cosf(-1 * CC_DEGREES_TO_RADIANS(outer->getRotation() + 90.0f)), - outer->getPositionY() + length * sinf(-1 * CC_DEGREES_TO_RADIANS(outer->getRotation() + 90.0f))); + + Vec2 position = Vec2(outer->getPositionX() + length * cosf(-1 * CC_DEGREES_TO_RADIANS(outer->getRotation() + 90.0f)), + outer->getPositionY() + length * sinf(-1 * CC_DEGREES_TO_RADIANS(outer->getRotation() + 90.0f))); _streak->setPosition(position); }; outer->schedule(updateMotionStreak, 1 / 240.0f, CC_REPEAT_FOREVER, 0, "motion1scheduler"); - auto rot = RotateBy::create(2, 360); + auto rot = RotateBy::create(2, 360); auto forever = RepeatForever::create(rot); outer->runAction(forever); + } std::string Issue12226::title() const @@ -235,9 +242,13 @@ std::string Issue12226::subtitle() const // //------------------------------------------------------------------ -MotionStreakTest::MotionStreakTest() {} +MotionStreakTest::MotionStreakTest() +{ +} -MotionStreakTest::~MotionStreakTest() {} +MotionStreakTest::~MotionStreakTest() +{ +} std::string MotionStreakTest::title() const { @@ -255,18 +266,19 @@ void MotionStreakTest::onEnter() auto s = Director::getInstance()->getWinSize(); - auto itemMode = MenuItemToggle::createWithCallback(CC_CALLBACK_1(MotionStreakTest::modeCallback, this), - MenuItemFont::create("Use High Quality Mode"), - MenuItemFont::create("Use Fast Mode"), nullptr); + auto itemMode = MenuItemToggle::createWithCallback( CC_CALLBACK_1(MotionStreakTest::modeCallback, this), + MenuItemFont::create("Use High Quality Mode"), + MenuItemFont::create("Use Fast Mode"), + nullptr); auto menuMode = Menu::create(itemMode, nullptr); addChild(menuMode); - menuMode->setPosition(Vec2(s.width / 2, s.height / 4)); + menuMode->setPosition(Vec2(s.width/2, s.height/4)); } -void MotionStreakTest::modeCallback(Ref* pSender) +void MotionStreakTest::modeCallback(Ref *pSender) { bool fastMode = _streak->isFastMode(); - _streak->setFastMode(!fastMode); + _streak->setFastMode(! fastMode); } diff --git a/tests/cpp-tests/Classes/MotionStreakTest/MotionStreakTest.h b/tests/cpp-tests/Classes/MotionStreakTest/MotionStreakTest.h index ae0683a682..aa6210bfd6 100644 --- a/tests/cpp-tests/Classes/MotionStreakTest/MotionStreakTest.h +++ b/tests/cpp-tests/Classes/MotionStreakTest/MotionStreakTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,6 +27,7 @@ #include "../BaseTest.h" + DEFINE_TEST_SUITE(MotionStreakTests); class MotionStreakTest : public TestCase @@ -40,7 +41,6 @@ public: virtual void onEnter() override; void modeCallback(cocos2d::Ref* sender); - protected: cocos2d::MotionStreak* _streak; }; @@ -48,8 +48,8 @@ protected: class MotionStreakTest1 : public MotionStreakTest { protected: - cocos2d::Node* _root; - cocos2d::Node* _target; + cocos2d::Node* _root; + cocos2d::Node* _target; public: CREATE_FUNC(MotionStreakTest1); @@ -61,8 +61,8 @@ public: class MotionStreakTest2 : public MotionStreakTest { protected: - cocos2d::Node* _root; - cocos2d::Node* _target; + cocos2d::Node* _root; + cocos2d::Node* _target; public: CREATE_FUNC(MotionStreakTest2); @@ -81,7 +81,6 @@ public: virtual std::string subtitle() const override; virtual void onEnter() override; virtual void update(float dt) override; - private: cocos2d::Vec2 _center; float _radius; @@ -98,4 +97,5 @@ public: virtual void onEnter() override; }; + #endif diff --git a/tests/cpp-tests/Classes/MultiTouchTest/MultiTouchTest.cpp b/tests/cpp-tests/Classes/MultiTouchTest/MultiTouchTest.cpp index d3c6c4273b..087ffe8f07 100644 --- a/tests/cpp-tests/Classes/MultiTouchTest/MultiTouchTest.cpp +++ b/tests/cpp-tests/Classes/MultiTouchTest/MultiTouchTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -31,24 +31,29 @@ MultiTouchTests::MultiTouchTests() ADD_TEST_CASE(MultiTouchTest); } -static const Color3B* s_TouchColors[5] = {&Color3B::YELLOW, &Color3B::BLUE, &Color3B::GREEN, &Color3B::RED, - &Color3B::MAGENTA}; +static const Color3B* s_TouchColors[5] = { + &Color3B::YELLOW, + &Color3B::BLUE, + &Color3B::GREEN, + &Color3B::RED, + &Color3B::MAGENTA +}; class TouchPoint : public Node { public: - TouchPoint(const Vec2& touchPoint, const Color3B& touchColor) + TouchPoint(const Vec2 &touchPoint, const Color3B &touchColor) { DrawNode* drawNode = DrawNode::create(); - auto s = Director::getInstance()->getWinSize(); - Color4F color(touchColor.r / 255.0f, touchColor.g / 255.0f, touchColor.b / 255.0f, 1.0f); + auto s = Director::getInstance()->getWinSize(); + Color4F color(touchColor.r/255.0f, touchColor.g/255.0f, touchColor.b/255.0f, 1.0f); drawNode->drawLine(Vec2(0.0f, touchPoint.y), Vec2(s.width, touchPoint.y), color); drawNode->drawLine(Vec2(touchPoint.x, 0.0f), Vec2(touchPoint.x, s.height), color); drawNode->drawDot(touchPoint, 3, color); addChild(drawNode); } - static TouchPoint* touchPointWithParent(Node* pParent, const Vec2& touchPoint, const Color3B& touchColor) + static TouchPoint* touchPointWithParent(Node* pParent, const Vec2 &touchPoint, const Color3B &touchColor) { auto pRet = new TouchPoint(touchPoint, touchColor); pRet->setContentSize(pParent->getContentSize()); @@ -62,16 +67,16 @@ bool MultiTouchTest::init() { if (TestCase::init()) { - auto listener = EventListenerTouchAllAtOnce::create(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(MultiTouchTest::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(MultiTouchTest::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(MultiTouchTest::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - + auto title = Label::createWithSystemFont("Please touch the screen!", "", 24); - title->setPosition(VisibleRect::top() + Vec2(0.0f, -40.0f)); + title->setPosition(VisibleRect::top()+Vec2(0.0f, -40.0f)); addChild(title); - + return true; } return false; @@ -79,48 +84,48 @@ bool MultiTouchTest::init() static Map s_map; -void MultiTouchTest::onTouchesBegan(const std::vector& touches, Event* event) +void MultiTouchTest::onTouchesBegan(const std::vector& touches, Event *event) { - for (auto& item : touches) + for ( auto &item: touches ) { - auto touch = item; - auto location = touch->getLocation(); - auto touchPoint = TouchPoint::touchPointWithParent(this, location, *s_TouchColors[touch->getID() % 5]); + auto touch = item; + auto location = touch->getLocation(); + auto touchPoint = TouchPoint::touchPointWithParent(this, location, *s_TouchColors[touch->getID()%5]); addChild(touchPoint); s_map.insert(touch->getID(), touchPoint); } } -void MultiTouchTest::onTouchesMoved(const std::vector& touches, Event* event) +void MultiTouchTest::onTouchesMoved(const std::vector& touches, Event *event) { - for (auto& item : touches) + for( auto &item: touches) { - auto touch = item; - auto pTP = s_map.at(touch->getID()); + auto touch = item; + auto pTP = s_map.at(touch->getID()); auto location = touch->getLocation(); - + removeChild(pTP, true); s_map.erase(touch->getID()); - - auto touchPointNew = TouchPoint::touchPointWithParent(this, location, *s_TouchColors[touch->getID() % 5]); + + auto touchPointNew = TouchPoint::touchPointWithParent(this, location, *s_TouchColors[touch->getID()%5]); addChild(touchPointNew); s_map.insert(touch->getID(), touchPointNew); } } -void MultiTouchTest::onTouchesEnded(const std::vector& touches, Event* event) +void MultiTouchTest::onTouchesEnded(const std::vector& touches, Event *event) { - for (auto& item : touches) + for ( auto &item: touches ) { auto touch = item; - auto pTP = s_map.at(touch->getID()); + auto pTP = s_map.at(touch->getID()); removeChild(pTP, true); s_map.erase(touch->getID()); } } -void MultiTouchTest::onTouchesCancelled(const std::vector& touches, Event* event) +void MultiTouchTest::onTouchesCancelled(const std::vector& touches, Event *event) { onTouchesEnded(touches, event); } diff --git a/tests/cpp-tests/Classes/MultiTouchTest/MultiTouchTest.h b/tests/cpp-tests/Classes/MultiTouchTest/MultiTouchTest.h index f16ec67e5a..94f6c65bd5 100644 --- a/tests/cpp-tests/Classes/MultiTouchTest/MultiTouchTest.h +++ b/tests/cpp-tests/Classes/MultiTouchTest/MultiTouchTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -36,10 +36,10 @@ public: virtual bool init() override; - void onTouchesBegan(const std::vector& touches, cocos2d::Event* event); - void onTouchesMoved(const std::vector& touches, cocos2d::Event* event); - void onTouchesEnded(const std::vector& touches, cocos2d::Event* event); - void onTouchesCancelled(const std::vector& touches, cocos2d::Event* event); + void onTouchesBegan(const std::vector& touches, cocos2d::Event *event); + void onTouchesMoved(const std::vector& touches, cocos2d::Event *event); + void onTouchesEnded(const std::vector& touches, cocos2d::Event *event); + void onTouchesCancelled(const std::vector& touches, cocos2d::Event *event); }; #endif /* __MULTITOUCHTEST_H__ */ diff --git a/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.cpp b/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.cpp index 7bce80fd97..6e9fa8c7f3 100644 --- a/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.cpp +++ b/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.cpp @@ -2,19 +2,19 @@ Copyright (c) 2012 cocos2d-x.org Copyright (c) 2015-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -40,7 +40,7 @@ struct AgentUserData NavMeshTests::NavMeshTests() { -#if (CC_USE_NAVMESH == 0) || (CC_USE_PHYSICS == 0) +#if ( CC_USE_NAVMESH == 0 ) || ( CC_USE_PHYSICS == 0 ) ADD_TEST_CASE(NavMeshDisabled); #else ADD_TEST_CASE(NavMeshBasicTestDemo); @@ -48,13 +48,12 @@ NavMeshTests::NavMeshTests() #endif }; -#if (CC_USE_NAVMESH == 0) || (CC_USE_PHYSICS == 0) +#if ( CC_USE_NAVMESH == 0 ) || ( CC_USE_PHYSICS == 0 ) void NavMeshDisabled::onEnter() { TTFConfig ttfConfig("fonts/arial.ttf", 16); - auto label = - Label::createWithTTF(ttfConfig, "Should define CC_USE_NAVMESH & CC_USE_PHYSICS\n to run this test case"); - + auto label = Label::createWithTTF(ttfConfig, "Should define CC_USE_NAVMESH & CC_USE_PHYSICS\n to run this test case"); + auto size = Director::getInstance()->getWinSize(); label->setPosition(Vec2(size.width / 2, size.height / 2)); @@ -64,24 +63,26 @@ void NavMeshDisabled::onEnter() } #else -NavMeshBaseTestDemo::NavMeshBaseTestDemo() : _camera(nullptr), _needMoveAgents(false) {} +NavMeshBaseTestDemo::NavMeshBaseTestDemo() + : _camera(nullptr) + , _needMoveAgents(false) +{ + +} NavMeshBaseTestDemo::~NavMeshBaseTestDemo() { - for (auto iter : _agents) - { - AgentUserData* data = static_cast(iter.first->getUserData()); + for (auto iter : _agents){ + AgentUserData *data = static_cast(iter.first->getUserData()); delete data; } } -bool NavMeshBaseTestDemo::init() +bool NavMeshBaseTestDemo::init() { - if (!TestCase::init()) - return false; + if (!TestCase::init()) return false; - if (initPhysicsWorld()) - { + if (initPhysicsWorld()) { _angle = 0.0f; @@ -102,16 +103,17 @@ bool NavMeshBaseTestDemo::init() scheduleUpdate(); } + return true; } -void NavMeshBaseTestDemo::onTouchesBegan(const std::vector& touches, cocos2d::Event* event) +void NavMeshBaseTestDemo::onTouchesBegan(const std::vector& touches, cocos2d::Event *event) { _needMoveAgents = true; touchesBegan(touches, event); } -void NavMeshBaseTestDemo::onTouchesMoved(const std::vector& touches, cocos2d::Event* event) +void NavMeshBaseTestDemo::onTouchesMoved(const std::vector& touches, cocos2d::Event *event) { if (touches.size() && _camera) { @@ -130,7 +132,7 @@ void NavMeshBaseTestDemo::onTouchesMoved(const std::vector& tou touchesMoved(touches, event); } -void NavMeshBaseTestDemo::onTouchesEnded(const std::vector& touches, cocos2d::Event* event) +void NavMeshBaseTestDemo::onTouchesEnded(const std::vector& touches, cocos2d::Event *event) { touchesEnded(touches, event); } @@ -138,7 +140,7 @@ void NavMeshBaseTestDemo::onTouchesEnded(const std::vector& tou void NavMeshBaseTestDemo::initScene() { getPhysics3DWorld()->setDebugDrawEnable(false); - // create mesh + //create mesh std::vector trianglesList = Bundle3D::getTrianglesList("NavMesh/scene.obj"); Physics3DRigidBodyDes rbDes; @@ -157,6 +159,7 @@ void NavMeshBaseTestDemo::initScene() setNavMesh(navMesh); setNavMeshDebugCamera(_camera); + auto ambientLight = AmbientLight::create(Color3B(64, 64, 64)); ambientLight->setCameraMask((unsigned short)CameraFlag::USER1); this->addChild(ambientLight); @@ -166,7 +169,7 @@ void NavMeshBaseTestDemo::initScene() this->addChild(dirLight); } -void NavMeshBaseTestDemo::createAgent(const Vec3& pos) +void NavMeshBaseTestDemo::createAgent(const Vec3 &pos) { std::string filePath = "Sprite3DTest/girl.c3b"; NavMeshAgentParam param; @@ -176,7 +179,7 @@ void NavMeshBaseTestDemo::createAgent(const Vec3& pos) auto agent = NavMeshAgent::create(param); auto agentNode = Sprite3D::create(filePath); agent->setOrientationRefAxes(Vec3(-1.0f, 0.0f, 1.0f)); - AgentUserData* data = new AgentUserData{0.0f}; + AgentUserData *data = new AgentUserData{ 0.0f }; agent->setUserData(data); agentNode->setScale(0.05f); agentNode->addComponent(agent); @@ -187,10 +190,10 @@ void NavMeshBaseTestDemo::createAgent(const Vec3& pos) node->setCameraMask((unsigned short)CameraFlag::USER1); this->addChild(node); + auto animation = Animation3D::create(filePath); auto animate = Animate3D::create(animation); - if (animate) - { + if (animate){ agentNode->runAction(RepeatForever::create(animate)); animate->setSpeed(0); } @@ -198,7 +201,7 @@ void NavMeshBaseTestDemo::createAgent(const Vec3& pos) _agents.push_back(std::make_pair(agent, animate)); } -void NavMeshBaseTestDemo::createObstacle(const Vec3& pos) +void NavMeshBaseTestDemo::createObstacle(const Vec3 &pos) { auto obstacle = NavMeshObstacle::create(2.0f, 8.0f); auto obstacleNode = Sprite3D::create("Sprite3DTest/cylinder.c3b"); @@ -220,20 +223,17 @@ Vec3 jump(const Vec3* pV1, const Vec3* pV2, float height, float t) return pOut; } -void NavMeshBaseTestDemo::moveAgents(const cocos2d::Vec3& des) +void NavMeshBaseTestDemo::moveAgents(const cocos2d::Vec3 &des) { - for (auto iter : _agents) - { - NavMeshAgent::MoveCallback callback = [](NavMeshAgent* agent, float totalTimeAfterMove) { - AgentUserData* data = static_cast(agent->getUserData()); - if (agent->isOnOffMeshLink()) - { + for (auto iter : _agents){ + NavMeshAgent::MoveCallback callback = [](NavMeshAgent *agent, float totalTimeAfterMove){ + AgentUserData *data = static_cast(agent->getUserData()); + if (agent->isOnOffMeshLink()){ agent->setAutoTraverseOffMeshLink(false); agent->setAutoOrientation(false); OffMeshLinkData linkdata = agent->getCurrentOffMeshLinkData(); - agent->getOwner()->setPosition3D( - jump(&linkdata.startPosition, &linkdata.endPosition, 10.0f, data->time)); + agent->getOwner()->setPosition3D(jump(&linkdata.startPosition, &linkdata.endPosition, 10.0f, data->time)); Vec3 dir = linkdata.endPosition - linkdata.startPosition; dir.y = 0.0f; dir.normalize(); @@ -244,8 +244,7 @@ void NavMeshBaseTestDemo::moveAgents(const cocos2d::Vec3& des) float angle = Vec3::dot(refAxes, dir); agent->getOwner()->setRotationQuat(Quaternion(axes, acosf(angle))); data->time += 0.01f; - if (1.0f < data->time) - { + if (1.0f < data->time){ agent->completeOffMeshLink(); agent->setAutoOrientation(true); data->time = 0.0f; @@ -258,16 +257,20 @@ void NavMeshBaseTestDemo::moveAgents(const cocos2d::Vec3& des) void NavMeshBaseTestDemo::update(float delta) { - for (auto iter : _agents) - { + for (auto iter : _agents){ float speed = iter.first->getCurrentVelocity().length() * 0.2f; iter.second->setSpeed(0.0f < speed ? speed : 0.0f); } } -NavMeshBasicTestDemo::NavMeshBasicTestDemo() {} +NavMeshBasicTestDemo::NavMeshBasicTestDemo() +{ -NavMeshBasicTestDemo::~NavMeshBasicTestDemo() {} +} + +NavMeshBasicTestDemo::~NavMeshBasicTestDemo() +{ +} std::string NavMeshBasicTestDemo::title() const { @@ -279,12 +282,10 @@ std::string NavMeshBasicTestDemo::subtitle() const return "Basic Test"; } -void NavMeshBasicTestDemo::touchesEnded(const std::vector& touches, cocos2d::Event* event) +void NavMeshBasicTestDemo::touchesEnded(const std::vector& touches, cocos2d::Event *event) { - if (!_needMoveAgents) - return; - if (!touches.empty()) - { + if (!_needMoveAgents) return; + if (!touches.empty()){ auto touch = touches[0]; auto location = touch->getLocationInView(); Vec3 nearP(location.x, location.y, 0.0f), farP(location.x, location.y, 1.0f); @@ -301,21 +302,18 @@ void NavMeshBasicTestDemo::touchesEnded(const std::vector& touc bool NavMeshBasicTestDemo::init() { - if (!NavMeshBaseTestDemo::init()) - return false; + if (!NavMeshBaseTestDemo::init()) return false; TTFConfig ttfConfig("fonts/arial.ttf", 15); _debugLabel = Label::createWithTTF(ttfConfig, "Debug Draw ON"); _debugLabel->retain(); - auto menuItem1 = MenuItemLabel::create(_debugLabel, [=](Ref*) { + auto menuItem1 = MenuItemLabel::create(_debugLabel, [=](Ref*){ bool enabledDebug = !getNavMesh()->isDebugDrawEnabled(); getNavMesh()->setDebugDrawEnable(enabledDebug); - if (enabledDebug) - { + if (enabledDebug){ _debugLabel->setString("Debug Draw ON"); } - else - { + else{ _debugLabel->setString("Debug Draw OFF"); } }); @@ -331,20 +329,25 @@ bool NavMeshBasicTestDemo::init() void NavMeshBasicTestDemo::onEnter() { NavMeshBaseTestDemo::onEnter(); - + Physics3DWorld::HitResult result; getPhysics3DWorld()->rayCast(Vec3(0.0f, 50.0f, 0.0f), Vec3(0.0f, -50.0f, 0.0f), &result); createAgent(result.hitPosition); } -NavMeshAdvanceTestDemo::NavMeshAdvanceTestDemo() {} +NavMeshAdvanceTestDemo::NavMeshAdvanceTestDemo() +{ -NavMeshAdvanceTestDemo::~NavMeshAdvanceTestDemo() {} +} + +NavMeshAdvanceTestDemo::~NavMeshAdvanceTestDemo() +{ + +} bool NavMeshAdvanceTestDemo::init() { - if (!NavMeshBaseTestDemo::init()) - return false; + if (!NavMeshBaseTestDemo::init()) return false; TTFConfig ttfConfig("fonts/arial.ttf", 15); _obstacleLabel = Label::createWithTTF(ttfConfig, "Create Obstacle"); @@ -354,7 +357,7 @@ bool NavMeshAdvanceTestDemo::init() _debugLabel = Label::createWithTTF(ttfConfig, "Debug Draw ON"); _debugLabel->retain(); - auto menuItem0 = MenuItemLabel::create(_obstacleLabel, [=](Ref*) { + auto menuItem0 = MenuItemLabel::create(_obstacleLabel, [=](Ref*){ float x = cocos2d::random(-50.0f, 50.0f); float z = cocos2d::random(-50.0f, 50.0f); Physics3DWorld::HitResult result; @@ -364,7 +367,7 @@ bool NavMeshAdvanceTestDemo::init() menuItem0->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); menuItem0->setPosition(Vec2(VisibleRect::left().x, VisibleRect::top().y - 50)); - auto menuItem1 = MenuItemLabel::create(_agentLabel, [=](Ref*) { + auto menuItem1 = MenuItemLabel::create(_agentLabel, [=](Ref*){ float x = cocos2d::random(-50.0f, 50.0f); float z = cocos2d::random(-50.0f, 50.0f); Physics3DWorld::HitResult result; @@ -374,15 +377,13 @@ bool NavMeshAdvanceTestDemo::init() menuItem1->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); menuItem1->setPosition(Vec2(VisibleRect::left().x, VisibleRect::top().y - 100)); - auto menuItem2 = MenuItemLabel::create(_debugLabel, [=](Ref*) { + auto menuItem2 = MenuItemLabel::create(_debugLabel, [=](Ref*){ bool enabledDebug = !getNavMesh()->isDebugDrawEnabled(); getNavMesh()->setDebugDrawEnable(enabledDebug); - if (enabledDebug) - { + if (enabledDebug){ _debugLabel->setString("Debug Draw ON"); } - else - { + else{ _debugLabel->setString("Debug Draw OFF"); } }); @@ -392,14 +393,14 @@ bool NavMeshAdvanceTestDemo::init() auto menu = Menu::create(menuItem0, menuItem1, menuItem2, nullptr); menu->setPosition(Vec2::ZERO); addChild(menu); - + return true; } void NavMeshAdvanceTestDemo::onEnter() { NavMeshBaseTestDemo::onEnter(); - + Physics3DWorld::HitResult result; getPhysics3DWorld()->rayCast(Vec3(0.0f, 50.0f, 0.0f), Vec3(0.0f, -50.0f, 0.0f), &result); createAgent(result.hitPosition); @@ -415,12 +416,10 @@ std::string NavMeshAdvanceTestDemo::subtitle() const return "Advance Test"; } -void NavMeshAdvanceTestDemo::touchesEnded(const std::vector& touches, cocos2d::Event* event) +void NavMeshAdvanceTestDemo::touchesEnded(const std::vector& touches, cocos2d::Event *event) { - if (!_needMoveAgents) - return; - if (!touches.empty()) - { + if (!_needMoveAgents) return; + if (!touches.empty()){ auto touch = touches[0]; auto location = touch->getLocationInView(); Vec3 nearP(location.x, location.y, 0.0f), farP(location.x, location.y, 1.0f); diff --git a/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.h b/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.h index 63e07ee041..fc2d1a58eb 100644 --- a/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.h +++ b/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.h @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2013 cocos2d-x.org Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -32,7 +32,7 @@ DEFINE_TEST_SUITE(NavMeshTests); -#if (CC_USE_NAVMESH == 0) || (CC_USE_PHYSICS == 0) +#if ( CC_USE_NAVMESH == 0 ) || ( CC_USE_PHYSICS == 0 ) class NavMeshDisabled : public TestCase { public: @@ -52,23 +52,24 @@ public: // overrides virtual bool init() override; virtual void update(float delta) override; - virtual void onTouchesBegan(const std::vector& touches, cocos2d::Event* event); - virtual void onTouchesMoved(const std::vector& touches, cocos2d::Event* event); - virtual void onTouchesEnded(const std::vector& touches, cocos2d::Event* event); + virtual void onTouchesBegan(const std::vector& touches, cocos2d::Event *event); + virtual void onTouchesMoved(const std::vector& touches, cocos2d::Event *event); + virtual void onTouchesEnded(const std::vector& touches, cocos2d::Event *event); protected: + void initScene(); - void createAgent(const cocos2d::Vec3& pos); - void createObstacle(const cocos2d::Vec3& pos); - void moveAgents(const cocos2d::Vec3& des); - virtual void touchesBegan(const std::vector& touches, cocos2d::Event* event){}; - virtual void touchesMoved(const std::vector& touches, cocos2d::Event* event){}; - virtual void touchesEnded(const std::vector& touches, cocos2d::Event* event){}; + void createAgent(const cocos2d::Vec3 &pos); + void createObstacle(const cocos2d::Vec3 &pos); + void moveAgents(const cocos2d::Vec3 &des); + virtual void touchesBegan(const std::vector& touches, cocos2d::Event *event){}; + virtual void touchesMoved(const std::vector& touches, cocos2d::Event *event){}; + virtual void touchesEnded(const std::vector& touches, cocos2d::Event *event){}; protected: - cocos2d::Camera* _camera; + cocos2d::Camera *_camera; float _angle; - std::vector> _agents; + std::vector > _agents; bool _needMoveAgents; }; @@ -78,21 +79,22 @@ public: CREATE_FUNC(NavMeshBasicTestDemo); NavMeshBasicTestDemo(); virtual ~NavMeshBasicTestDemo(); - + // overrides virtual bool init() override; virtual std::string title() const override; virtual std::string subtitle() const override; - + virtual void onEnter() override; + +protected: + + virtual void touchesBegan(const std::vector& touches, cocos2d::Event *event)override{}; + virtual void touchesMoved(const std::vector& touches, cocos2d::Event *event)override{}; + virtual void touchesEnded(const std::vector& touches, cocos2d::Event *event)override; protected: - virtual void touchesBegan(const std::vector& touches, cocos2d::Event* event) override{}; - virtual void touchesMoved(const std::vector& touches, cocos2d::Event* event) override{}; - virtual void touchesEnded(const std::vector& touches, cocos2d::Event* event) override; - -protected: - cocos2d::Label* _debugLabel; + cocos2d::Label *_debugLabel; }; class NavMeshAdvanceTestDemo : public NavMeshBaseTestDemo @@ -106,18 +108,19 @@ public: virtual bool init() override; virtual std::string title() const override; virtual std::string subtitle() const override; - + virtual void onEnter() override; protected: - virtual void touchesBegan(const std::vector& touches, cocos2d::Event* event) override{}; - virtual void touchesMoved(const std::vector& touches, cocos2d::Event* event) override{}; - virtual void touchesEnded(const std::vector& touches, cocos2d::Event* event) override; + + virtual void touchesBegan(const std::vector& touches, cocos2d::Event *event)override{}; + virtual void touchesMoved(const std::vector& touches, cocos2d::Event *event)override{}; + virtual void touchesEnded(const std::vector& touches, cocos2d::Event *event)override; protected: - cocos2d::Label* _obstacleLabel; - cocos2d::Label* _agentLabel; - cocos2d::Label* _debugLabel; + cocos2d::Label *_obstacleLabel; + cocos2d::Label *_agentLabel; + cocos2d::Label *_debugLabel; }; #endif diff --git a/tests/cpp-tests/Classes/NetworkTest/DownloaderTest/DownloaderTest.cpp b/tests/cpp-tests/Classes/NetworkTest/DownloaderTest/DownloaderTest.cpp index 8b63a52711..4637639153 100644 --- a/tests/cpp-tests/Classes/NetworkTest/DownloaderTest/DownloaderTest.cpp +++ b/tests/cpp-tests/Classes/NetworkTest/DownloaderTest/DownloaderTest.cpp @@ -34,13 +34,16 @@ USING_NS_CC; -static const char* sURLList[] = { - "https://www.cocos2d-x.org/attachments/802/cocos2dx_landscape.png", "https://cocos2d-x.org/images/logo.png", +static const char* sURLList[] = +{ + "https://www.cocos2d-x.org/attachments/802/cocos2dx_landscape.png", + "https://cocos2d-x.org/images/logo.png", "https://www.cocos2d-x.org/attachments/1503/no_exist.txt", // try to download no exist file - "https://cdn-fastly.obsproject.com/downloads/OBS-Studio-27.0.1-Full-Installer-x64.exe" // "https://github.com/openssl/openssl/archive/OpenSSL_1_1_1a.zip", + "https://cdn-fastly.obsproject.com/downloads/OBS-Studio-27.0.1-Full-Installer-x64.exe" // "https://github.com/openssl/openssl/archive/OpenSSL_1_1_1a.zip", }; -const static int sListSize = (sizeof(sURLList) / sizeof(sURLList[0])); -static const char* sNameList[sListSize] = { +const static int sListSize = (sizeof(sURLList)/sizeof(sURLList[0])); +static const char* sNameList[sListSize] = +{ "cocos2dx_landscape.png", "logo.png", "inexist file", @@ -50,47 +53,50 @@ static const char* sNameList[sListSize] = { struct DownloaderTest : public TestCase { CREATE_FUNC(DownloaderTest); - + virtual std::string title() const override { return "Downloader Test"; } - + std::unique_ptr downloader; - - DownloaderTest() { downloader.reset(new network::Downloader()); } - - enum + + DownloaderTest() { + downloader.reset(new network::Downloader()); + } + + enum { TAG_TITLE = 1, TAG_BUTTON, TAG_PROGRESS_BAR, TAG_STATUS, TAG_SPRITE, }; - - Node* createDownloadView(const char* name, const cocos2d::ui::Button::ccWidgetClickCallback& callback) + + Node* createDownloadView(const char *name, const cocos2d::ui::Button::ccWidgetClickCallback &callback) { Size viewSize(220, 120); float margin = 5; - + // create background auto bg = ui::Scale9Sprite::createWithSpriteFrameName("button_actived.png"); bg->setContentSize(viewSize); - + // add a title on the top - auto title = Label::createWithTTF(name, "fonts/arial.ttf", 16); + auto title = Label::createWithTTF(name,"fonts/arial.ttf",16); title->setTag(TAG_TITLE); title->setAnchorPoint(Vec2(0.5f, 1.0f)); title->setPosition(viewSize.width / 2, viewSize.height - margin); bg->addChild(title, 10); - + // add a button on the bottom - auto btn = ui::Button::create("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png"); + auto btn = ui::Button::create("cocosui/animationbuttonnormal.png", + "cocosui/animationbuttonpressed.png"); btn->setTag(TAG_BUTTON); btn->setTitleText("Download"); btn->setAnchorPoint(Vec2(0.5f, 0.0f)); btn->setPosition(Vec2(viewSize.width / 2, margin)); btn->addClickEventListener(callback); bg->addChild(btn, 10); - + // add a progress bar auto bar = ui::LoadingBar::create("ccs-res/cocosui/sliderProgress.png"); bar->setTag(TAG_PROGRESS_BAR); @@ -102,7 +108,7 @@ struct DownloaderTest : public TestCase bg->addChild(bar, 10); // add a status label - auto label = Label::createWithTTF("", "fonts/arial.ttf", 14); + auto label = Label::createWithTTF("","fonts/arial.ttf",14); label->setTag(TAG_STATUS); label->setAnchorPoint(Vec2(0.5f, 0.5f)); label->setPosition(Vec2(viewSize.width / 2, viewSize.height / 2)); @@ -110,20 +116,21 @@ struct DownloaderTest : public TestCase label->setAlignment(TextHAlignment::CENTER, TextVAlignment::CENTER); label->setDimensions(viewSize.width, viewSize.height); bg->addChild(label, 20); - + return bg; } - + virtual void onEnter() override { TestCase::onEnter(); _restartTestItem->setVisible(true); - + SpriteFrameCache::getInstance()->addSpriteFramesWithFile(s_s9s_ui_plist); // add four download view in test case - Node* topRightView = createDownloadView(sNameList[0], [this](Ref*) { - auto view = this->getChildByName(sNameList[0]); + Node* topRightView = createDownloadView(sNameList[0], [this](Ref*) + { + auto view = this->getChildByName(sNameList[0]); auto sprite = view->getChildByTag(TAG_SPRITE); if (sprite) { @@ -142,8 +149,9 @@ struct DownloaderTest : public TestCase topRightView->setPosition(VisibleRect::center()); this->addChild(topRightView); - Node* topLeftView = createDownloadView(sNameList[1], [this](Ref*) { - auto view = this->getChildByName(sNameList[1]); + Node* topLeftView = createDownloadView(sNameList[1], [this](Ref*) + { + auto view = this->getChildByName(sNameList[1]); auto sprite = view->getChildByTag(TAG_SPRITE); if (sprite) { @@ -163,8 +171,9 @@ struct DownloaderTest : public TestCase topLeftView->setPosition(VisibleRect::center()); this->addChild(topLeftView); - Node* bottomLeftView = createDownloadView(sNameList[2], [this](Ref*) { - auto view = this->getChildByName(sNameList[2]); + Node* bottomLeftView = createDownloadView(sNameList[2], [this](Ref*) + { + auto view = this->getChildByName(sNameList[2]); auto sprite = view->getChildByTag(TAG_SPRITE); if (sprite) { @@ -185,9 +194,10 @@ struct DownloaderTest : public TestCase bottomLeftView->setPosition(VisibleRect::center()); this->addChild(bottomLeftView); - Node* bottomRightView = createDownloadView(sNameList[3], [this](Ref*) { + Node* bottomRightView = createDownloadView(sNameList[3], [this](Ref*) + { auto view = this->getChildByName(sNameList[3]); - auto btn = (ui::Button*)view->getChildByTag(TAG_BUTTON); + auto btn = (ui::Button*)view->getChildByTag(TAG_BUTTON); btn->setEnabled(false); btn->setVisible(false); auto bar = (ui::LoadingBar*)view->getChildByTag(TAG_PROGRESS_BAR); @@ -195,8 +205,7 @@ struct DownloaderTest : public TestCase bar->setVisible(true); bar->setEnabled(true); auto path = FileUtils::getInstance()->getWritablePath() + "CppTests/DownloaderTest/" + sNameList[3]; - auto task = this->downloader->createDownloadFileTask(sURLList[3], path, sNameList[3], - "730cfe31b344ba77d87d0a896af710d4", false); + auto task = this->downloader->createDownloadFileTask(sURLList[3], path, sNameList[3], "730cfe31b344ba77d87d0a896af710d4", false); task->progressInfo.totalBytesExpected = 89945032; }); bottomRightView->setName(sNameList[3]); @@ -205,20 +214,22 @@ struct DownloaderTest : public TestCase this->addChild(bottomRightView); // define progress callback - downloader->onTaskProgress = [this](const network::DownloadTask& task) { - Node* view = this->getChildByName(task.identifier); - auto bar = (ui::LoadingBar*)view->getChildByTag(TAG_PROGRESS_BAR); + downloader->onTaskProgress = [this](const network::DownloadTask& task) + { + Node* view = this->getChildByName(task.identifier); + auto bar = (ui::LoadingBar*)view->getChildByTag(TAG_PROGRESS_BAR); float percent = float(task.progressInfo.totalBytesReceived * 100) / task.progressInfo.totalBytesExpected; bar->setPercent(percent); char buf[128]; - sprintf(buf, "%.1f%%[total %d KB]", percent, int(task.progressInfo.totalBytesExpected / 1024)); + sprintf(buf, "%.1f%%[total %d KB]", percent, int(task.progressInfo.totalBytesExpected/1024)); auto status = (Label*)view->getChildByTag(TAG_STATUS); status->setString(buf); }; - + // define success callback downloader->onDataTaskSuccess = [this](const cocos2d::network::DownloadTask& task, - std::vector& data) { + std::vector& data) + { // create texture from data Texture2D* texture = nullptr; do @@ -228,21 +239,21 @@ struct DownloaderTest : public TestCase { break; } - + texture = new Texture2D(); if (false == texture->initWithImage(&img)) { break; } - auto sprite = Sprite::createWithTexture(texture); - auto view = this->getChildByName(task.identifier); + auto sprite = Sprite::createWithTexture(texture); + auto view = this->getChildByName(task.identifier); auto viewSize = view->getContentSize(); sprite->setPosition(viewSize.width / 2, viewSize.height / 2); auto spriteSize = sprite->getContentSize(); float scale = MIN((viewSize.height - 20) / spriteSize.height, (viewSize.width - 20) / spriteSize.width); sprite->setScale(scale); view->addChild(sprite, 5, TAG_SPRITE); - + auto btn = (ui::Button*)view->getChildByTag(TAG_BUTTON); btn->setEnabled(true); btn->setVisible(true); @@ -251,14 +262,14 @@ struct DownloaderTest : public TestCase } while (0); CC_SAFE_RELEASE(texture); }; - - downloader->onFileTaskSuccess = [this](const cocos2d::network::DownloadTask& task) { + + downloader->onFileTaskSuccess = [this](const cocos2d::network::DownloadTask& task) + { Texture2D* texture = nullptr; do { auto view = this->getChildByName(task.identifier); - if (task.storagePath.find(".png") != std::string::npos) - { + if (task.storagePath.find(".png") != std::string::npos) { // create sprite from file auto sprite = Sprite::create(task.storagePath); auto viewSize = view->getContentSize(); @@ -269,12 +280,10 @@ struct DownloaderTest : public TestCase sprite->setScale(scale); view->addChild(sprite, 5, TAG_SPRITE); CC_SAFE_RELEASE(texture); - } - else - { + } else { // download big file success - auto msg = StringUtils::format("Download [%s] success.", task.identifier.c_str()); - auto status = (Label*)view->getChildByTag(TAG_STATUS); + auto msg = StringUtils::format("Download [%s] success.", task.identifier.c_str()); + auto status = (Label*) view->getChildByTag(TAG_STATUS); status->setString(msg); } auto btn = (ui::Button*)view->getChildByTag(TAG_BUTTON); @@ -284,16 +293,23 @@ struct DownloaderTest : public TestCase bar->setVisible(false); } while (0); }; - + // define failed callback - downloader->onTaskError = [this](const cocos2d::network::DownloadTask& task, int errorCode, - int errorCodeInternal, std::string_view errorStr) { - log("Failed to download : %s, identifier(%s) error code(%d), internal error code(%d) desc(%s)", - task.requestURL.c_str(), task.identifier.c_str(), errorCode, errorCodeInternal, errorStr.data()); - auto view = this->getChildByName(task.identifier); + downloader->onTaskError = [this](const cocos2d::network::DownloadTask& task, + int errorCode, + int errorCodeInternal, + const std::string& errorStr) + { + log("Failed to download : %s, identifier(%s) error code(%d), internal error code(%d) desc(%s)" + , task.requestURL.c_str() + , task.identifier.c_str() + , errorCode + , errorCodeInternal + , errorStr.c_str()); + auto view = this->getChildByName(task.identifier); auto status = (Label*)view->getChildByTag(TAG_STATUS); status->setString(errorStr.length() ? errorStr : "Download failed."); - + auto btn = (ui::Button*)view->getChildByTag(TAG_BUTTON); btn->setEnabled(true); btn->setVisible(true); @@ -323,22 +339,25 @@ struct DownloaderMultiTask : public TestCase char path[256]; char name[64]; // add 64 download task at same time. - for (int i = 0; i < 64; i++) - { + for(int i=0; i< 64;i++){ sprintf(name, "%d_%s", i, sNameList[0]); sprintf(path, "%sCppTests/DownloaderTest/%s", FileUtils::getInstance()->getWritablePath().c_str(), name); log("downloader task create: %s", name); this->downloader->createDownloadFileTask(sURLList[0], path, name); } - downloader->onFileTaskSuccess = - ([](const network::DownloadTask& task) { log("downloader task success: %s", task.identifier.c_str()); }); + downloader->onFileTaskSuccess = ([] (const network::DownloadTask& task) { + log("downloader task success: %s", task.identifier.c_str()); + }); - downloader->onTaskError = - ([](const network::DownloadTask& task, int errorCode, int errorCodeInternal, std::string_view errorStr) { - log("downloader task failed : %s, identifier(%s) error code(%d), internal error code(%d) desc(%s)", - task.requestURL.c_str(), task.identifier.c_str(), errorCode, errorCodeInternal, errorStr.data()); - }); + downloader->onTaskError = ([] (const network::DownloadTask& task, int errorCode, int errorCodeInternal, const std::string& errorStr) { + log("downloader task failed : %s, identifier(%s) error code(%d), internal error code(%d) desc(%s)" + , task.requestURL.c_str() + , task.identifier.c_str() + , errorCode + , errorCodeInternal + , errorStr.c_str()); + }); } }; diff --git a/tests/cpp-tests/Classes/NetworkTest/HttpClientTest/HttpClientTest.cpp b/tests/cpp-tests/Classes/NetworkTest/HttpClientTest/HttpClientTest.cpp index 5c2c8a52bb..d77782ff1e 100644 --- a/tests/cpp-tests/Classes/NetworkTest/HttpClientTest/HttpClientTest.cpp +++ b/tests/cpp-tests/Classes/NetworkTest/HttpClientTest/HttpClientTest.cpp @@ -3,17 +3,17 @@ Copyright (c) Bytedance Inc. https://adxe.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 @@ -29,9 +29,7 @@ USING_NS_CC; using namespace cocos2d::network; -#define CHROME_UA \ - "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 " \ - "Safari/537.36" +#define CHROME_UA "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" HttpClientTests::HttpClientTests() { @@ -39,7 +37,8 @@ HttpClientTests::HttpClientTests() ADD_TEST_CASE(HttpClientClearRequestsTest); } -HttpClientTest::HttpClientTest() : _labelStatusCode(nullptr) +HttpClientTest::HttpClientTest() +: _labelStatusCode(nullptr) { auto winSize = Director::getInstance()->getWinSize(); @@ -48,52 +47,51 @@ HttpClientTest::HttpClientTest() : _labelStatusCode(nullptr) auto cafile = FileUtils::getInstance()->fullPathForFilename("cacert.pem"); httpClient->setSSLVerification(cafile); httpClient->enableCookies(nullptr); - CCLOG("The http cookie will store to: %s", httpClient->getCookieFilename().data()); + CCLOG("The http cookie will store to: %s", httpClient->getCookieFilename().c_str()); const int MARGIN = 40; - const int SPACE = 35; + const int SPACE = 35; - const int LEFT = winSize.width / 2; + const int LEFT = winSize.width / 2; const int RIGHT = winSize.width / 4 * 3; - + auto menuRequest = Menu::create(); menuRequest->setPosition(Vec2::ZERO); addChild(menuRequest); - - // Get + + // Get auto labelGet = Label::createWithTTF("Test Get", "fonts/arial.ttf", 22); - auto itemGet = MenuItemLabel::create(labelGet, CC_CALLBACK_1(HttpClientTest::onMenuGetTestClicked, this)); + auto itemGet = MenuItemLabel::create(labelGet, CC_CALLBACK_1(HttpClientTest::onMenuGetTestClicked, this)); itemGet->setPosition(LEFT, winSize.height - MARGIN - SPACE); menuRequest->addChild(itemGet); - + // Post auto labelPost = Label::createWithTTF("Test Post", "fonts/arial.ttf", 22); - auto itemPost = MenuItemLabel::create(labelPost, CC_CALLBACK_1(HttpClientTest::onMenuPostTestClicked, this)); + auto itemPost = MenuItemLabel::create(labelPost, CC_CALLBACK_1(HttpClientTest::onMenuPostTestClicked, this)); itemPost->setPosition(LEFT, winSize.height - MARGIN - 2 * SPACE); menuRequest->addChild(itemPost); - + // Post Binary auto labelPostBinary = Label::createWithTTF("Test Post Binary", "fonts/arial.ttf", 22); - auto itemPostBinary = - MenuItemLabel::create(labelPostBinary, CC_CALLBACK_1(HttpClientTest::onMenuPostBinaryTestClicked, this)); + auto itemPostBinary = MenuItemLabel::create(labelPostBinary, CC_CALLBACK_1(HttpClientTest::onMenuPostBinaryTestClicked, this)); itemPostBinary->setPosition(LEFT, winSize.height - MARGIN - 3 * SPACE); menuRequest->addChild(itemPostBinary); // Put auto labelPut = Label::createWithTTF("Test Put", "fonts/arial.ttf", 22); - auto itemPut = MenuItemLabel::create(labelPut, CC_CALLBACK_1(HttpClientTest::onMenuPutTestClicked, this)); + auto itemPut = MenuItemLabel::create(labelPut, CC_CALLBACK_1(HttpClientTest::onMenuPutTestClicked, this)); itemPut->setPosition(LEFT, winSize.height - MARGIN - 4 * SPACE); menuRequest->addChild(itemPut); // Delete auto labelDelete = Label::createWithTTF("Test Delete", "fonts/arial.ttf", 22); - auto itemDelete = MenuItemLabel::create(labelDelete, CC_CALLBACK_1(HttpClientTest::onMenuDeleteTestClicked, this)); + auto itemDelete = MenuItemLabel::create(labelDelete, CC_CALLBACK_1(HttpClientTest::onMenuDeleteTestClicked, this)); itemDelete->setPosition(LEFT, winSize.height - MARGIN - 5 * SPACE); menuRequest->addChild(itemDelete); - + // Response Code Label _labelStatusCode = Label::createWithTTF("HTTP Status Code", "fonts/arial.ttf", 18); - _labelStatusCode->setPosition(winSize.width / 2, winSize.height - MARGIN - 6 * SPACE); + _labelStatusCode->setPosition(winSize.width / 2, winSize.height - MARGIN - 6 * SPACE); addChild(_labelStatusCode); } @@ -102,8 +100,8 @@ HttpClientTest::~HttpClientTest() HttpClient::destroyInstance(); } -void HttpClientTest::onMenuGetTestClicked(cocos2d::Ref* sender) -{ +void HttpClientTest::onMenuGetTestClicked(cocos2d::Ref *sender) +{ // test 1(sync request test) { HttpRequest* request = new HttpRequest(); @@ -113,8 +111,7 @@ void HttpClientTest::onMenuGetTestClicked(cocos2d::Ref* sender) // request->setResponseCallback(CC_CALLBACK_2(HttpClientTest::onHttpRequestCompleted, this)); request->setTag("GET test1"); HttpResponse* response = HttpClient::getInstance()->sendSync(request); - if (response) - { + if (response) { onHttpRequestCompleted(HttpClient::getInstance(), response); response->release(); } @@ -132,7 +129,7 @@ void HttpClientTest::onMenuGetTestClicked(cocos2d::Ref* sender) HttpClient::getInstance()->send(request); request->release(); } - + // test 3 { HttpRequest* request = new HttpRequest(); @@ -146,8 +143,8 @@ void HttpClientTest::onMenuGetTestClicked(cocos2d::Ref* sender) // don't forget to release it, pair to new request->release(); } - - // test 4 + + // test 4 { HttpRequest* request = new HttpRequest(); request->setUrl("https://httpbin.org/get"); @@ -170,12 +167,13 @@ void HttpClientTest::onMenuGetTestClicked(cocos2d::Ref* sender) HttpClient::getInstance()->send(request); request->release(); } - + // waiting _labelStatusCode->setString("waiting..."); + } -void HttpClientTest::onMenuPostTestClicked(cocos2d::Ref* sender) +void HttpClientTest::onMenuPostTestClicked(cocos2d::Ref *sender) { // test 1 { @@ -184,7 +182,7 @@ void HttpClientTest::onMenuPostTestClicked(cocos2d::Ref* sender) request->setRequestType(HttpRequest::Type::POST); request->setHeaders(std::vector{CHROME_UA}); request->setResponseCallback(CC_CALLBACK_2(HttpClientTest::onHttpRequestCompleted, this)); - + // write the post data const char* postData = "visitor=cocos2d&TestSuite=Extensions Test/NetworkTest"; request->setRequestData(postData, strlen(postData)); @@ -192,7 +190,7 @@ void HttpClientTest::onMenuPostTestClicked(cocos2d::Ref* sender) HttpClient::getInstance()->send(request); request->release(); } - + // test 2: set Content-Type { HttpRequest* request = new HttpRequest(); @@ -200,7 +198,7 @@ void HttpClientTest::onMenuPostTestClicked(cocos2d::Ref* sender) request->setRequestType(HttpRequest::Type::POST); request->setHeaders(std::vector{CHROME_UA, "Content-Type: application/json; charset=utf-8"}); request->setResponseCallback(CC_CALLBACK_2(HttpClientTest::onHttpRequestCompleted, this)); - + // write the post data const char* postData = "visitor=cocos2d&TestSuite=Extensions Test/NetworkTest"; request->setRequestData(postData, strlen(postData)); @@ -208,30 +206,32 @@ void HttpClientTest::onMenuPostTestClicked(cocos2d::Ref* sender) HttpClient::getInstance()->send(request); request->release(); } - + // waiting _labelStatusCode->setString("waiting..."); } -void HttpClientTest::onMenuPostBinaryTestClicked(cocos2d::Ref* sender) +void HttpClientTest::onMenuPostBinaryTestClicked(cocos2d::Ref *sender) { HttpRequest* request = new HttpRequest(); request->setUrl("https://httpbin.org/post"); request->setRequestType(HttpRequest::Type::POST); request->setResponseCallback(CC_CALLBACK_2(HttpClientTest::onHttpRequestCompleted, this)); - + // write the post data char postData[22] = "binary=hello\0\0cocos2d"; // including \0, the strings after \0 should not be cut in response - request->setRequestData(postData, 22); + request->setRequestData(postData, 22); request->setTag("POST Binary test"); HttpClient::getInstance()->send(request); request->release(); - + // waiting _labelStatusCode->setString("waiting..."); } -void HttpClientTest::onMenuPutTestClicked(Ref* sender) + + +void HttpClientTest::onMenuPutTestClicked(Ref *sender) { // test 1 { @@ -270,7 +270,7 @@ void HttpClientTest::onMenuPutTestClicked(Ref* sender) _labelStatusCode->setString("waiting..."); } -void HttpClientTest::onMenuDeleteTestClicked(Ref* sender) +void HttpClientTest::onMenuDeleteTestClicked(Ref *sender) { // test 1 { @@ -298,35 +298,35 @@ void HttpClientTest::onMenuDeleteTestClicked(Ref* sender) _labelStatusCode->setString("waiting..."); } -void HttpClientTest::onHttpRequestCompleted(HttpClient* sender, HttpResponse* response) +void HttpClientTest::onHttpRequestCompleted(HttpClient *sender, HttpResponse *response) { if (!response) { return; } - + // You can get original request type from: response->request->reqType - if (0 != strlen(response->getHttpRequest()->getTag())) + if (0 != strlen(response->getHttpRequest()->getTag())) { log("%s completed", response->getHttpRequest()->getTag()); } - - int32_t statusCode = response->getResponseCode(); + + int32_t statusCode = response->getResponseCode(); char statusString[64] = {}; sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag()); _labelStatusCode->setString(statusString); log("response code: %d", statusCode); - - if (response->getResponseCode() != 200) + + if (response->getResponseCode() != 200) { log("response failed"); // log("error buffer: %s", response->getErrorBuffer()); return; } - + // dump data auto buffer = response->getResponseData(); - buffer->push_back('\0'); // to c_str + buffer->push_back('\0'); // to c_str log("Http Test, dump data: %s", buffer->data()); log("\n"); if (response->getHttpRequest()->getReferenceCount() != 2) @@ -335,44 +335,43 @@ void HttpClientTest::onHttpRequestCompleted(HttpClient* sender, HttpResponse* re } } -HttpClientClearRequestsTest::HttpClientClearRequestsTest() : _labelStatusCode(nullptr) +HttpClientClearRequestsTest::HttpClientClearRequestsTest() +: _labelStatusCode(nullptr) { auto winSize = Director::getInstance()->getWinSize(); - + const int MARGIN = 40; - const int SPACE = 35; - + const int SPACE = 35; + const int CENTER = winSize.width / 2; - + auto menuRequest = Menu::create(); menuRequest->setPosition(Vec2::ZERO); addChild(menuRequest); - + // Get auto labelGet = Label::createWithTTF("Test Clear all Get", "fonts/arial.ttf", 22); - auto itemGet = - MenuItemLabel::create(labelGet, CC_CALLBACK_1(HttpClientClearRequestsTest::onMenuCancelAllClicked, this)); + auto itemGet = MenuItemLabel::create(labelGet, CC_CALLBACK_1(HttpClientClearRequestsTest::onMenuCancelAllClicked, this)); itemGet->setPosition(CENTER, winSize.height - MARGIN - SPACE); menuRequest->addChild(itemGet); - + // Post auto labelPost = Label::createWithTTF("Test Clear but only with the tag DELETE", "fonts/arial.ttf", 22); - auto itemPost = - MenuItemLabel::create(labelPost, CC_CALLBACK_1(HttpClientClearRequestsTest::onMenuCancelSomeClicked, this)); + auto itemPost = MenuItemLabel::create(labelPost, CC_CALLBACK_1(HttpClientClearRequestsTest::onMenuCancelSomeClicked, this)); itemPost->setPosition(CENTER, winSize.height - MARGIN - 2 * SPACE); menuRequest->addChild(itemPost); - + // Response Code Label _labelStatusCode = Label::createWithTTF("HTTP Status Code", "fonts/arial.ttf", 18); - _labelStatusCode->setPosition(winSize.width / 2, winSize.height - MARGIN - 6 * SPACE); + _labelStatusCode->setPosition(winSize.width / 2, winSize.height - MARGIN - 6 * SPACE); addChild(_labelStatusCode); - + // Tracking Data Label _labelTrakingData = Label::createWithTTF("Got 0 of 0 expected http requests", "fonts/arial.ttf", 16); - _labelTrakingData->setPosition(CENTER, winSize.height - MARGIN - 5 * SPACE); + _labelTrakingData->setPosition(CENTER, winSize.height - MARGIN - 5 * SPACE); addChild(_labelTrakingData); - - _totalExpectedRequests = 0; + + _totalExpectedRequests = 0; _totalProcessedRequests = 0; } @@ -381,9 +380,9 @@ HttpClientClearRequestsTest::~HttpClientClearRequestsTest() HttpClient::destroyInstance(); } -void HttpClientClearRequestsTest::onMenuCancelAllClicked(cocos2d::Ref* sender) +void HttpClientClearRequestsTest::onMenuCancelAllClicked(cocos2d::Ref *sender) { - for (int i = 0; i < 10; i++) + for (int i=0; i < 10; i++) { HttpRequest* request = new HttpRequest(); std::stringstream url; @@ -391,28 +390,28 @@ void HttpClientClearRequestsTest::onMenuCancelAllClicked(cocos2d::Ref* sender) request->setUrl(url.str()); request->setRequestType(HttpRequest::Type::GET); request->setResponseCallback(CC_CALLBACK_2(HttpClientClearRequestsTest::onHttpRequestCompleted, this)); - + url.str(""); url << "TEST_" << std::to_string(i); request->setTag(url.str()); HttpClient::getInstance()->send(request); request->release(); } - + _totalProcessedRequests = 0; - _totalExpectedRequests = 1; - + _totalExpectedRequests = 1; + HttpClient::getInstance()->setClearResponsePredicate(nullptr); HttpClient::getInstance()->clearResponseQueue(); - + // waiting _labelStatusCode->setString("waiting..."); } -void HttpClientClearRequestsTest::onMenuCancelSomeClicked(cocos2d::Ref* sender) +void HttpClientClearRequestsTest::onMenuCancelSomeClicked(cocos2d::Ref *sender) { // test 1 - for (int i = 0; i < 10; i++) + for (int i=0; i < 10; i++) { HttpRequest* request = new HttpRequest(); std::stringstream url; @@ -420,57 +419,57 @@ void HttpClientClearRequestsTest::onMenuCancelSomeClicked(cocos2d::Ref* sender) request->setUrl(url.str()); request->setRequestType(HttpRequest::Type::GET); request->setResponseCallback(CC_CALLBACK_2(HttpClientClearRequestsTest::onHttpRequestCompleted, this)); - + url.str(""); - if (i < 5) - { + if (i < 5) { url << "TEST_" << std::to_string(i); _totalExpectedRequests++; } - else - { + else { url << "DELETE_" << std::to_string(i); } request->setTag(url.str()); HttpClient::getInstance()->send(request); request->release(); } - - /* HttpClient::getInstance()->setClearRequestPredicate([&](HttpRequest* req) - { - auto r = !!strstr(req->getTag(), "DELETE_"); - return r; - });*/ + + /* HttpClient::getInstance()->setClearRequestPredicate([&](HttpRequest* req) + { + auto r = !!strstr(req->getTag(), "DELETE_"); + return r; + });*/ HttpClient::getInstance()->setClearResponsePredicate(nullptr); HttpClient::getInstance()->clearResponseQueue(); - + + // waiting _labelStatusCode->setString("waiting..."); + } -void HttpClientClearRequestsTest::onHttpRequestCompleted(HttpClient* sender, HttpResponse* response) +void HttpClientClearRequestsTest::onHttpRequestCompleted(HttpClient *sender, HttpResponse *response) { if (!response) { return; } - + // You can get original request type from: response->request->reqType if (0 != strlen(response->getHttpRequest()->getTag())) { log("%s completed", response->getHttpRequest()->getTag()); } - - int32_t statusCode = response->getResponseCode(); + + int32_t statusCode = response->getResponseCode(); char statusString[64] = {}; sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag()); _labelStatusCode->setString(statusString); log("response code: %d", statusCode); - + _totalProcessedRequests++; sprintf(statusString, "Got %d of %d expected http requests", _totalProcessedRequests, _totalExpectedRequests); _labelTrakingData->setString(statusString); - + if (!response->isSucceed()) { log("response failed"); diff --git a/tests/cpp-tests/Classes/NetworkTest/HttpClientTest/HttpClientTest.h b/tests/cpp-tests/Classes/NetworkTest/HttpClientTest/HttpClientTest.h index e188007e1c..80c85ff286 100644 --- a/tests/cpp-tests/Classes/NetworkTest/HttpClientTest/HttpClientTest.h +++ b/tests/cpp-tests/Classes/NetworkTest/HttpClientTest/HttpClientTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -39,16 +39,16 @@ public: HttpClientTest(); virtual ~HttpClientTest(); - - // Menu Callbacks - void onMenuGetTestClicked(cocos2d::Ref* sender); - void onMenuPostTestClicked(cocos2d::Ref* sender); - void onMenuPostBinaryTestClicked(cocos2d::Ref* sender); - void onMenuPutTestClicked(cocos2d::Ref* sender); - void onMenuDeleteTestClicked(cocos2d::Ref* sender); - - // Http Response Callback - void onHttpRequestCompleted(cocos2d::network::HttpClient* sender, cocos2d::network::HttpResponse* response); + + //Menu Callbacks + void onMenuGetTestClicked(cocos2d::Ref *sender); + void onMenuPostTestClicked(cocos2d::Ref *sender); + void onMenuPostBinaryTestClicked(cocos2d::Ref *sender); + void onMenuPutTestClicked(cocos2d::Ref *sender); + void onMenuDeleteTestClicked(cocos2d::Ref *sender); + + //Http Response Callback + void onHttpRequestCompleted(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response); virtual std::string title() const override { return "Http Request Test"; } @@ -60,19 +60,19 @@ class HttpClientClearRequestsTest : public TestCase { public: CREATE_FUNC(HttpClientClearRequestsTest); - + HttpClientClearRequestsTest(); virtual ~HttpClientClearRequestsTest(); - - // Menu Callbacks - void onMenuCancelAllClicked(cocos2d::Ref* sender); - void onMenuCancelSomeClicked(cocos2d::Ref* sender); - - // Http Response Callback - void onHttpRequestCompleted(cocos2d::network::HttpClient* sender, cocos2d::network::HttpResponse* response); - + + //Menu Callbacks + void onMenuCancelAllClicked(cocos2d::Ref *sender); + void onMenuCancelSomeClicked(cocos2d::Ref *sender); + + //Http Response Callback + void onHttpRequestCompleted(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response); + virtual std::string title() const override { return "Http Request Test"; } - + private: int _totalExpectedRequests; int _totalProcessedRequests; @@ -80,4 +80,4 @@ private: cocos2d::Label* _labelStatusCode; }; -#endif //__HTTPREQUESTHTTP_H +#endif //__HTTPREQUESTHTTP_H diff --git a/tests/cpp-tests/Classes/NetworkTest/NetworkTest.cpp b/tests/cpp-tests/Classes/NetworkTest/NetworkTest.cpp index 1f518130f2..4e320a70ff 100644 --- a/tests/cpp-tests/Classes/NetworkTest/NetworkTest.cpp +++ b/tests/cpp-tests/Classes/NetworkTest/NetworkTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,8 +27,7 @@ #include "HttpClientTest/HttpClientTest.h" #include "DownloaderTest/DownloaderTest.h" -NetworkTests::NetworkTests() -{ +NetworkTests::NetworkTests() { addTest("HttpClientTest", []() { return new HttpClientTests; }); addTest("DownloaderTest", []() { return new DownloaderTests; }); } diff --git a/tests/cpp-tests/Classes/NetworkTest/NetworkTest.h b/tests/cpp-tests/Classes/NetworkTest/NetworkTest.h index e0574e76c2..917e95d037 100644 --- a/tests/cpp-tests/Classes/NetworkTest/NetworkTest.h +++ b/tests/cpp-tests/Classes/NetworkTest/NetworkTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 diff --git a/tests/cpp-tests/Classes/NewAudioEngineTest/NewAudioEngineTest.cpp b/tests/cpp-tests/Classes/NewAudioEngineTest/NewAudioEngineTest.cpp index 81dc4aea80..90e304dece 100644 --- a/tests/cpp-tests/Classes/NewAudioEngineTest/NewAudioEngineTest.cpp +++ b/tests/cpp-tests/Classes/NewAudioEngineTest/NewAudioEngineTest.cpp @@ -53,153 +53,151 @@ AudioEngineTests::AudioEngineTests() ADD_TEST_CASE(AudioIssue18597Test); ADD_TEST_CASE(AudioIssue11143Test); - - // FIXME: Please keep AudioSwitchStateTest to the last position since this test case doesn't work well on each - // platforms. + + //FIXME: Please keep AudioSwitchStateTest to the last position since this test case doesn't work well on each platforms. ADD_TEST_CASE(AudioSwitchStateTest); } -namespace -{ - -class TextButton : public cocos2d::Label -{ -public: - static TextButton* create(std::string_view text, const std::function& onTriggered) +namespace { + + class TextButton : public cocos2d::Label { - auto ret = new TextButton(); - - TTFConfig ttfconfig("fonts/arial.ttf", 25); - if (ret->setTTFConfig(ttfconfig)) + public: + + static TextButton *create(const std::string& text, const std::function &onTriggered) { - ret->setString(text); - ret->_onTriggered = onTriggered; - - ret->autorelease(); - - return ret; + auto ret = new TextButton(); + + TTFConfig ttfconfig("fonts/arial.ttf",25); + if (ret->setTTFConfig(ttfconfig)) { + ret->setString(text); + ret->_onTriggered = onTriggered; + + ret->autorelease(); + + return ret; + } + + delete ret; + return nullptr; } - - delete ret; - return nullptr; - } - - void setEnabled(bool enabled) - { - _enabled = enabled; - if (_enabled) + + void setEnabled(bool enabled) { - this->setColor(Color3B::WHITE); - } - else - { - this->setColor(Color3B::GRAY); - } - } - -private: - TextButton() : _onTriggered(nullptr), _enabled(true) - { - auto listener = EventListenerTouchOneByOne::create(); - listener->setSwallowTouches(true); - - listener->onTouchBegan = CC_CALLBACK_2(TextButton::onTouchBegan, this); - listener->onTouchEnded = CC_CALLBACK_2(TextButton::onTouchEnded, this); - listener->onTouchCancelled = CC_CALLBACK_2(TextButton::onTouchCancelled, this); - - _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - } - - bool touchHits(Touch* touch) - { - auto hitPos = this->convertToNodeSpace(touch->getLocation()); - if (hitPos.x >= 0 && hitPos.y >= 0 && hitPos.x <= _contentSize.width && hitPos.y <= _contentSize.height) - { - return true; - } - return false; - } - - bool onTouchBegan(Touch* touch, Event* event) - { - auto hits = touchHits(touch); - if (hits) - { - scaleButtonTo(0.95f); - } - return hits; - } - - void onTouchEnded(Touch* touch, Event* event) - { - if (_enabled) - { - auto hits = touchHits(touch); - if (hits && _onTriggered) - { - _onTriggered(this); + _enabled = enabled; + if(_enabled){ + this->setColor(Color3B::WHITE); + } + else { + this->setColor(Color3B::GRAY); } } - - scaleButtonTo(1); - } - - void onTouchCancelled(Touch* touch, Event* event) { scaleButtonTo(1); } - - void scaleButtonTo(float scale) - { - auto action = ScaleTo::create(0.05f, scale); - action->setTag(10000); - stopActionByTag(10000); - runAction(action); - } - - std::function _onTriggered; - - bool _enabled; -}; - -class SliderEx : public Slider -{ -public: - static SliderEx* create() - { - auto ret = new SliderEx(); - if (ret->init()) + + private: + TextButton() + : _onTriggered(nullptr) + , _enabled(true) { - ret->loadBarTexture("cocosui/sliderTrack.png"); - ret->loadSlidBallTextures("cocosui/sliderThumb.png", "cocosui/sliderThumb.png", ""); - ret->loadProgressBarTexture("cocosui/sliderProgress.png"); - ret->setTouchEnabled(true); - - ret->autorelease(); - + auto listener = EventListenerTouchOneByOne::create(); + listener->setSwallowTouches(true); + + listener->onTouchBegan = CC_CALLBACK_2(TextButton::onTouchBegan, this); + listener->onTouchEnded = CC_CALLBACK_2(TextButton::onTouchEnded, this); + listener->onTouchCancelled = CC_CALLBACK_2(TextButton::onTouchCancelled, this); + + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); + + } + + bool touchHits(Touch *touch) + { + auto hitPos = this->convertToNodeSpace(touch->getLocation()); + if (hitPos.x >= 0 && hitPos.y >= 0 && hitPos.x <= _contentSize.width && hitPos.y <= _contentSize.height) { + return true; + } + return false; + } + + bool onTouchBegan(Touch *touch, Event *event) + { + auto hits = touchHits(touch); + if (hits){ + scaleButtonTo(0.95f); + } + return hits; + } + + void onTouchEnded(Touch *touch, Event *event) + { + if(_enabled) { + auto hits = touchHits(touch); + if (hits && _onTriggered){ + _onTriggered(this); + } + } + + scaleButtonTo(1); + } + + void onTouchCancelled(Touch *touch, Event *event) + { + scaleButtonTo(1); + } + + void scaleButtonTo(float scale) + { + auto action = ScaleTo::create(0.05f, scale); + action->setTag(10000); + stopActionByTag(10000); + runAction(action); + } + + std::function _onTriggered; + + bool _enabled; + }; + + class SliderEx : public Slider + { + public: + static SliderEx* create(){ + auto ret = new SliderEx(); + if (ret->init()) + { + ret->loadBarTexture("cocosui/sliderTrack.png"); + ret->loadSlidBallTextures("cocosui/sliderThumb.png", "cocosui/sliderThumb.png", ""); + ret->loadProgressBarTexture("cocosui/sliderProgress.png"); + ret->setTouchEnabled(true); + + ret->autorelease(); + + return ret; + } + CC_SAFE_DELETE(ret); return ret; } - CC_SAFE_DELETE(ret); - return ret; - } + + void setRatio(float ratio) { + ratio = clampf(ratio, 0.0f, 1.0f); + + _ratio = ratio; + setPercent(100 * _ratio); + } + + float getRatio () { + _ratio = 1.0f * _percent / _maxPercent; + return _ratio; + } + + private: + float _ratio; + }; +} - void setRatio(float ratio) - { - ratio = clampf(ratio, 0.0f, 1.0f); - - _ratio = ratio; - setPercent(100 * _ratio); - } - - float getRatio() - { - _ratio = 1.0f * _percent / _maxPercent; - return _ratio; - } - -private: - float _ratio; -}; -} // namespace - -AudioEngineTestDemo::AudioEngineTestDemo() : _isDestroyed(std::make_shared(false)) {} +AudioEngineTestDemo::AudioEngineTestDemo() +: _isDestroyed(std::make_shared(false)) +{ +} void AudioEngineTestDemo::onExit() { @@ -222,184 +220,173 @@ void AudioEngineTestDemo::onBackCallback(cocos2d::Ref* sender) // AudioControlTest bool AudioControlTest::init() { - auto ret = AudioEngineTestDemo::init(); - _audioID = AudioEngine::INVALID_AUDIO_ID; - _loopEnabled = false; - _volume = 1.0f; - _duration = AudioEngine::TIME_UNKNOWN; - _timeRatio = 0.0f; + auto ret = AudioEngineTestDemo::init(); + _audioID = AudioEngine::INVALID_AUDIO_ID; + _loopEnabled = false; + _volume = 1.0f; + _duration = AudioEngine::TIME_UNKNOWN; + _timeRatio = 0.0f; _updateTimeSlider = true; - _isStopped = false; - + _isStopped = false; + std::string fontFilePath = "fonts/arial.ttf"; - + auto& layerSize = this->getContentSize(); - + _playOverLabel = Label::createWithSystemFont("Play Over", "", 30); - _playOverLabel->setPosition(Vec2(layerSize / 2) + Vec2(0, 30)); + _playOverLabel->setPosition(Vec2(layerSize/2) + Vec2(0, 30)); _playOverLabel->setVisible(false); addChild(_playOverLabel, 99999); - auto playItem = TextButton::create("play", [&](TextButton* button) { - if (_audioID == AudioEngine::INVALID_AUDIO_ID) - { + auto playItem = TextButton::create("play", [&](TextButton* button){ + if (_audioID == AudioEngine::INVALID_AUDIO_ID) { _audioID = AudioEngine::play2d("background.mp3", _loopEnabled, _volume); - - if (_audioID != AudioEngine::INVALID_AUDIO_ID) - { + + if(_audioID != AudioEngine::INVALID_AUDIO_ID) { _isStopped = false; - + button->setEnabled(false); - AudioEngine::setFinishCallback(_audioID, [&](int id, std::string_view filePath) { + AudioEngine::setFinishCallback(_audioID, [&](int id, const std::string& filePath){ log("_audioID(%d), _isStopped:(%d), played over!!!", _audioID, _isStopped); - + _playOverLabel->setVisible(true); - - scheduleOnce([&](float dt) { _playOverLabel->setVisible(false); }, 2.0f, "hide_play_over_label"); - - assert(!_isStopped); // Stop audio should not trigger finished callback + + scheduleOnce([&](float dt){ + _playOverLabel->setVisible(false); + }, 2.0f, "hide_play_over_label"); + + assert(!_isStopped); // Stop audio should not trigger finished callback _audioID = AudioEngine::INVALID_AUDIO_ID; ((TextButton*)_playItem)->setEnabled(true); - + _timeRatio = 0.0f; ((SliderEx*)_timeSlider)->setRatio(_timeRatio); }); } } }); - _playItem = playItem; - playItem->setPosition(layerSize.width * 0.3f, layerSize.height * 0.8f); + _playItem = playItem; + playItem->setPosition(layerSize.width * 0.3f,layerSize.height * 0.8f); addChild(playItem); - - auto stopItem = TextButton::create("stop", [&](TextButton* button) { - if (_audioID != AudioEngine::INVALID_AUDIO_ID) - { + + auto stopItem = TextButton::create("stop", [&](TextButton* button){ + if (_audioID != AudioEngine::INVALID_AUDIO_ID ) { _isStopped = true; AudioEngine::stop(_audioID); - + _audioID = AudioEngine::INVALID_AUDIO_ID; ((TextButton*)_playItem)->setEnabled(true); } }); - stopItem->setPosition(layerSize.width * 0.7f, layerSize.height * 0.8f); + stopItem->setPosition(layerSize.width * 0.7f,layerSize.height * 0.8f); addChild(stopItem); - - auto pauseItem = TextButton::create("pause", [&](TextButton* button) { - if (_audioID != AudioEngine::INVALID_AUDIO_ID) - { + + auto pauseItem = TextButton::create("pause", [&](TextButton* button){ + if (_audioID != AudioEngine::INVALID_AUDIO_ID ) { AudioEngine::pause(_audioID); } }); - pauseItem->setPosition(layerSize.width * 0.3f, layerSize.height * 0.7f); + pauseItem->setPosition(layerSize.width * 0.3f,layerSize.height * 0.7f); addChild(pauseItem); - - auto resumeItem = TextButton::create("resume", [&](TextButton* button) { - if (_audioID != AudioEngine::INVALID_AUDIO_ID) - { + + auto resumeItem = TextButton::create("resume", [&](TextButton* button){ + if (_audioID != AudioEngine::INVALID_AUDIO_ID ) { AudioEngine::resume(_audioID); } }); - resumeItem->setPosition(layerSize.width * 0.7f, layerSize.height * 0.7f); + resumeItem->setPosition(layerSize.width * 0.7f,layerSize.height * 0.7f); addChild(resumeItem); - - auto loopItem = TextButton::create("enable-loop", [&](TextButton* button) { + + auto loopItem = TextButton::create("enable-loop", [&](TextButton* button){ _loopEnabled = !_loopEnabled; - if (_audioID != AudioEngine::INVALID_AUDIO_ID) - { + if (_audioID != AudioEngine::INVALID_AUDIO_ID) { AudioEngine::setLoop(_audioID, _loopEnabled); } - if (_loopEnabled) - { + if (_loopEnabled){ button->setString("disable-loop"); } - else - { + else { button->setString("enable-loop"); } }); loopItem->setPosition(layerSize.width * 0.5f, layerSize.height * 0.5f); addChild(loopItem); - + auto volumeSlider = SliderEx::create(); volumeSlider->setPercent(100); - volumeSlider->addEventListener([&](Ref* sender, Slider::EventType event) { - SliderEx* slider = dynamic_cast(sender); - _volume = slider->getRatio(); - if (_audioID != AudioEngine::INVALID_AUDIO_ID) - { + volumeSlider->addEventListener([&](Ref* sender, Slider::EventType event){ + SliderEx *slider = dynamic_cast(sender); + _volume = slider->getRatio(); + if (_audioID != AudioEngine::INVALID_AUDIO_ID ) { AudioEngine::setVolume(_audioID, _volume); } }); - volumeSlider->setPosition(Vec2(layerSize.width * 0.5f, layerSize.height * 0.35f)); + volumeSlider->setPosition(Vec2(layerSize.width * 0.5f,layerSize.height * 0.35f)); addChild(volumeSlider); - + auto timeSlider = SliderEx::create(); - timeSlider->addEventListener([&](Ref* sender, Slider::EventType event) { - SliderEx* slider = dynamic_cast(sender); - switch (event) - { - case Slider::EventType::ON_SLIDEBALL_DOWN: - _updateTimeSlider = false; - break; - case Slider::EventType::ON_SLIDEBALL_UP: - if (_audioID != AudioEngine::INVALID_AUDIO_ID && _duration != AudioEngine::TIME_UNKNOWN) - { - float ratio = (float)slider->getPercent() / 100; - ratio = clampf(ratio, 0.0f, 1.0f); - AudioEngine::setCurrentTime(_audioID, _duration * ratio); - } - case Slider::EventType::ON_SLIDEBALL_CANCEL: - _updateTimeSlider = true; - case Slider::EventType::ON_PERCENTAGE_CHANGED: - default: - // ignore - break; + timeSlider->addEventListener([&](Ref* sender, Slider::EventType event){ + SliderEx *slider = dynamic_cast(sender); + switch(event){ + case Slider::EventType::ON_SLIDEBALL_DOWN: + _updateTimeSlider = false; + break; + case Slider::EventType::ON_SLIDEBALL_UP: + if (_audioID != AudioEngine::INVALID_AUDIO_ID && _duration != AudioEngine::TIME_UNKNOWN) { + float ratio = (float)slider->getPercent() / 100; + ratio = clampf(ratio, 0.0f, 1.0f); + AudioEngine::setCurrentTime(_audioID, _duration * ratio); + } + case Slider::EventType::ON_SLIDEBALL_CANCEL: + _updateTimeSlider = true; + case Slider::EventType::ON_PERCENTAGE_CHANGED: + default: + //ignore + break; } }); - timeSlider->setPosition(Vec2(layerSize.width * 0.5f, layerSize.height * 0.25f)); + timeSlider->setPosition(Vec2(layerSize.width * 0.5f,layerSize.height * 0.25f)); addChild(timeSlider); _timeSlider = timeSlider; - + auto& volumeSliderPos = volumeSlider->getPosition(); - auto& sliderSize = volumeSlider->getContentSize(); - auto volumeLabel = Label::createWithTTF("volume: ", fontFilePath, 20); + auto& sliderSize = volumeSlider->getContentSize(); + auto volumeLabel = Label::createWithTTF("volume: ", fontFilePath, 20); volumeLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE_RIGHT); volumeLabel->setPosition(volumeSliderPos.x - sliderSize.width / 2, volumeSliderPos.y); addChild(volumeLabel); - + auto& timeSliderPos = timeSlider->getPosition(); - auto timeLabel = Label::createWithTTF("time: ", fontFilePath, 20); + auto timeLabel = Label::createWithTTF("time: ", fontFilePath, 20); timeLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE_RIGHT); timeLabel->setPosition(timeSliderPos.x - sliderSize.width / 2, timeSliderPos.y); addChild(timeLabel); - + this->schedule(CC_CALLBACK_1(AudioControlTest::update, this), 0.1f, "update_key"); - + return ret; } void AudioControlTest::update(float dt) { - if (_audioID != AudioEngine::INVALID_AUDIO_ID) - { - if (_duration == AudioEngine::TIME_UNKNOWN) - { + if (_audioID != AudioEngine::INVALID_AUDIO_ID ) { + if(_duration == AudioEngine::TIME_UNKNOWN){ _duration = AudioEngine::getDuration(_audioID); } - if (_duration != AudioEngine::TIME_UNKNOWN) - { - auto time = AudioEngine::getCurrentTime(_audioID); + if(_duration != AudioEngine::TIME_UNKNOWN){ + auto time = AudioEngine::getCurrentTime(_audioID); _timeRatio = time / _duration; - if (_updateTimeSlider) - { + if(_updateTimeSlider){ ((SliderEx*)_timeSlider)->setRatio(_timeRatio); } } } } -AudioControlTest::~AudioControlTest() {} +AudioControlTest::~AudioControlTest() +{ +} std::string AudioControlTest::title() const { @@ -416,16 +403,16 @@ bool AudioLoadTest::init() stateLabel->setPosition(layerSize.width / 2, layerSize.height * 0.7f); addChild(stateLabel); - auto preloadItem = TextButton::create("preload", [&, stateLabel](TextButton* button) { + auto preloadItem = TextButton::create("preload", [&, stateLabel](TextButton* button){ stateLabel->setString("status:loading..."); auto isDestroyed = _isDestroyed; - AudioEngine::preload("audio/SoundEffectsFX009/FX082.mp3", [isDestroyed, stateLabel](bool isSuccess) { + AudioEngine::preload("audio/SoundEffectsFX009/FX082.mp3", [isDestroyed, stateLabel](bool isSuccess){ if (*isDestroyed) { CCLOG("AudioLoadTest scene was destroyed, no need to set the label text."); return; } - + if (isSuccess) { stateLabel->setString("status:load success"); @@ -439,13 +426,13 @@ bool AudioLoadTest::init() preloadItem->setPosition(layerSize.width * 0.35f, layerSize.height * 0.5f); addChild(preloadItem); - auto uncacheItem = TextButton::create("uncache", [&, stateLabel](TextButton* button) { + auto uncacheItem = TextButton::create("uncache", [&, stateLabel](TextButton* button){ stateLabel->setString("status:uncache"); AudioEngine::uncache("audio/SoundEffectsFX009/FX082.mp3"); }); uncacheItem->setPosition(layerSize.width * 0.65f, layerSize.height * 0.5f); addChild(uncacheItem); - + return true; } @@ -458,7 +445,9 @@ std::string AudioLoadTest::title() const } // AudioWavTest -AudioWavTest::~AudioWavTest() {} +AudioWavTest::~AudioWavTest() +{ +} std::string AudioWavTest::title() const { @@ -479,26 +468,22 @@ bool AudioWavTest::init() addChild(_stateLabel); auto playPrev = TextButton::create("Play Prev", [=](TextButton* button) { - if (_curIndex > 0) - { + if (_curIndex > 0) { AudioEngine::stop(_audioID); _audioID = AudioEngine::play2d(_wavFiles[--_curIndex]); - _stateLabel->setString(StringUtils::format("[index: %d] %s", _curIndex, - FileUtils::getFileShortName(_wavFiles[_curIndex]).c_str())); + _stateLabel->setString(StringUtils::format("[index: %d] %s", _curIndex, FileUtils::getFileShortName(_wavFiles[_curIndex]).c_str())); } - }); + }); playPrev->setPosition(layerSize.width * 0.35f, layerSize.height * 0.5f); addChild(playPrev); auto playNext = TextButton::create("Play Next", [=](TextButton* button) { - if (_curIndex != -1 && _curIndex < (_wavFiles.size() - 1)) - { + if (_curIndex != -1 && _curIndex < (_wavFiles.size() - 1)) { AudioEngine::stop(_audioID); _audioID = AudioEngine::play2d(_wavFiles[++_curIndex]); - _stateLabel->setString(StringUtils::format("[index: %d] %s", _curIndex, - FileUtils::getFileShortName(_wavFiles[_curIndex]).c_str())); + _stateLabel->setString(StringUtils::format("[index: %d] %s", _curIndex, FileUtils::getFileShortName(_wavFiles[_curIndex]).c_str())); } - }); + }); playNext->setPosition(layerSize.width * 0.65f, layerSize.height * 0.5f); addChild(playNext); @@ -512,12 +497,10 @@ void AudioWavTest::onEnter() { AudioEngineTestDemo::onEnter(); - if (!_wavFiles.empty()) - { + if (!_wavFiles.empty()) { _curIndex = 0; - _audioID = AudioEngine::play2d(_wavFiles[_curIndex]); - _stateLabel->setString(StringUtils::format("[index: %d] %s", _curIndex, - FileUtils::getFileShortName(_wavFiles[_curIndex]).c_str())); + _audioID = AudioEngine::play2d(_wavFiles[_curIndex]); + _stateLabel->setString(StringUtils::format("[index: %d] %s", _curIndex, FileUtils::getFileShortName(_wavFiles[_curIndex]).c_str())); } } @@ -525,51 +508,48 @@ void AudioWavTest::onEnter() bool PlaySimultaneouslyTest::init() { auto ret = AudioEngineTestDemo::init(); - + char text[36]; int tmp = 81; - for (int index = 0; index < TEST_COUNT; ++index) - { - sprintf(text, "audio/SoundEffectsFX009/FX0%d.mp3", tmp + index); + for(int index = 0; index < TEST_COUNT; ++index){ + sprintf(text,"audio/SoundEffectsFX009/FX0%d.mp3",tmp + index); _files[index] = text; } _playingcount = 0; - - auto playItem = TextButton::create("play-simultaneously", [&](TextButton* button) { + + auto playItem = TextButton::create("play-simultaneously", [&](TextButton* button){ int audioId; _playingcount = 0; button->setEnabled(false); auto startTime = utils::gettime(); - for (int index = 0; index < TEST_COUNT; ++index) - { + for(int index = 0; index < TEST_COUNT; ++index){ audioId = AudioEngine::play2d(_files[index]); - if (audioId != AudioEngine::INVALID_AUDIO_ID) - { + if(audioId != AudioEngine::INVALID_AUDIO_ID){ _playingcount += 1; - - AudioEngine::setFinishCallback(audioId, [&](int id, std::string_view filePath) { + + AudioEngine::setFinishCallback(audioId, [&](int id, const std::string& filePath){ _playingcount -= 1; - if (_playingcount <= 0) - { + if(_playingcount <= 0){ ((TextButton*)_playItem)->setEnabled(true); } }); } - else - { - log("%s,%d,Fail to play file:%s", __FILE__, __LINE__, _files[index].c_str()); + else { + log("%s,%d,Fail to play file:%s",__FILE__,__LINE__ ,_files[index].c_str()); } } - log("diff time:%lf", utils::gettime() - startTime); + log("diff time:%lf",utils::gettime() - startTime); }); - playItem->setPositionNormalized(Vec2(0.5f, 0.5f)); + playItem->setPositionNormalized(Vec2(0.5f,0.5f)); this->addChild(playItem); _playItem = playItem; - + return ret; } -PlaySimultaneouslyTest::~PlaySimultaneouslyTest() {} +PlaySimultaneouslyTest::~PlaySimultaneouslyTest() +{ +} std::string PlaySimultaneouslyTest::title() const { @@ -580,7 +560,7 @@ std::string PlaySimultaneouslyTest::title() const bool AudioProfileTest::init() { auto ret = AudioEngineTestDemo::init(); - + char text[30]; _files[0] = "background.mp3"; #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC @@ -588,81 +568,82 @@ bool AudioProfileTest::init() #else _files[1] = "background.ogg"; #endif - + std::string fontFilePath = "fonts/arial.ttf"; - _minDelay = 1.0f; - _time = 0.0f; + _minDelay = 1.0f; + _time = 0.0f; - _audioProfile.name = "AudioProfileTest"; + _audioProfile.name = "AudioProfileTest"; _audioProfile.maxInstances = 3; - _audioProfile.minDelay = 1.0; - - Vec2 pos(0.5f, 0.7f); - for (int index = 0; index < FILE_COUNT; ++index) - { - sprintf(text, "play %s", _files[index].c_str()); - - auto playItem = TextButton::create(text, [&](TextButton* button) { + _audioProfile.minDelay = 1.0; + + Vec2 pos(0.5f,0.7f); + for(int index = 0; index < FILE_COUNT; ++index){ + sprintf(text,"play %s",_files[index].c_str()); + + auto playItem = TextButton::create(text, [&](TextButton* button){ int index = button->getTag(); - auto id = AudioEngine::play2d(_files[index], false, 1.0f, &_audioProfile); - if (id != AudioEngine::INVALID_AUDIO_ID) - { + auto id = AudioEngine::play2d(_files[index], false, 1.0f, &_audioProfile); + if(id != AudioEngine::INVALID_AUDIO_ID){ _time = _minDelay; _audioCount += 1; char show[30]; - sprintf(show, "audio count:%d", _audioCount); + sprintf(show,"audio count:%d",_audioCount); _showLabel->setString(show); - - AudioEngine::setFinishCallback(id, [&](int id, std::string_view filePath) { + + AudioEngine::setFinishCallback(id, [&](int id, const std::string& filePath){ _audioCount -= 1; char show[30]; - sprintf(show, "audio count:%d", _audioCount); + sprintf(show,"audio count:%d",_audioCount); _showLabel->setString(show); }); } + }); playItem->setTag(index); playItem->setPositionNormalized(pos); this->addChild(playItem); pos.y -= 0.15f; + } - + Vec2 origin = Director::getInstance()->getVisibleOrigin(); - Size size = Director::getInstance()->getVisibleSize(); - - auto profileInfoLabel = - Label::createWithTTF("AudioProfile Info:\n max instance:3 \n minimum delay:1.0", fontFilePath, 12); + Size size = Director::getInstance()->getVisibleSize(); + + auto profileInfoLabel = Label::createWithTTF("AudioProfile Info:\n max instance:3 \n minimum delay:1.0", fontFilePath, 12); profileInfoLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT); profileInfoLabel->setPosition(Vec2(origin.x, origin.y + size.height * 0.65f)); addChild(profileInfoLabel); - + _audioCount = 0; - _showLabel = Label::createWithTTF("audio count:0", fontFilePath, 12); + _showLabel = Label::createWithTTF("audio count:0", fontFilePath, 12); _showLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT); _showLabel->setPosition(Vec2(origin.x, origin.y + size.height * 0.5f)); addChild(_showLabel); - + auto timeSlider = SliderEx::create(); timeSlider->setEnabled(false); timeSlider->setPositionNormalized(pos); addChild(timeSlider); _timeSlider = timeSlider; - + this->schedule(CC_CALLBACK_1(AudioProfileTest::update, this), 0.05f, "update_key"); - + return ret; } void AudioProfileTest::update(float dt) { - if (_time > 0.0f) + if(_time > 0.0f) { _time -= dt; ((SliderEx*)_timeSlider)->setRatio(_time / _minDelay); } } -AudioProfileTest::~AudioProfileTest() {} +AudioProfileTest::~AudioProfileTest() +{ +} std::string AudioProfileTest::title() const { @@ -678,26 +659,29 @@ std::string AudioProfileTest::subtitle() const bool InvalidAudioFileTest::init() { auto ret = AudioEngineTestDemo::init(); - - auto playItem = TextButton::create("play unsupported media type", [&](TextButton* button) { + + auto playItem = TextButton::create("play unsupported media type", [&](TextButton* button){ #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC AudioEngine::play2d("background.ogg"); #elif CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 - AudioEngine::play2d("background.caf"); + AudioEngine::play2d("background.caf"); #endif }); playItem->setPositionNormalized(Vec2(0.5f, 0.6f)); this->addChild(playItem); - - auto playItem2 = TextButton::create("play not-existent file", - [&](TextButton* button) { AudioEngine::play2d("not-existent file.mp3"); }); + + auto playItem2 = TextButton::create("play not-existent file", [&](TextButton* button){ + AudioEngine::play2d("not-existent file.mp3"); + }); playItem2->setPositionNormalized(Vec2(0.5f, 0.4f)); this->addChild(playItem2); - + return ret; } -InvalidAudioFileTest::~InvalidAudioFileTest() {} +InvalidAudioFileTest::~InvalidAudioFileTest() +{ +} std::string InvalidAudioFileTest::title() const { @@ -713,16 +697,19 @@ std::string InvalidAudioFileTest::subtitle() const bool LargeAudioFileTest::init() { auto ret = AudioEngineTestDemo::init(); - - auto playItem = TextButton::create("play large audio file", - [&](TextButton* button) { AudioEngine::play2d("audio/LuckyDay.mp3"); }); + + auto playItem = TextButton::create("play large audio file", [&](TextButton* button){ + AudioEngine::play2d("audio/LuckyDay.mp3"); + }); playItem->setPositionNormalized(Vec2::ANCHOR_MIDDLE); this->addChild(playItem); - + return ret; } -LargeAudioFileTest::~LargeAudioFileTest() {} +LargeAudioFileTest::~LargeAudioFileTest() +{ +} std::string LargeAudioFileTest::title() const { @@ -735,33 +722,36 @@ bool AudioIssue18597Test::init() { auto& layerSize = this->getContentSize(); - // test case for https://github.com/cocos2d/cocos2d-x/issues/18597 - this->schedule( - [=](float dt) { - CCLOG("issues 18597 audio crash test"); - for (int i = 0; i < 2; ++i) - { - auto id = AudioEngine::play2d("audio/MUS_BGM_Battle_Round1_v1.caf", true, 1.0f); - this->runAction(Sequence::create(DelayTime::create(8.0f), - CallFunc::create([=]() { AudioEngine::stop(id); }), nullptr)); - } - }, - 2.0, 10000, 0.0, "audio test"); + //test case for https://github.com/cocos2d/cocos2d-x/issues/18597 + this->schedule([=](float dt) + { + CCLOG("issues 18597 audio crash test"); + for (int i = 0; i< 2;++i) + { + auto id = AudioEngine::play2d("audio/MUS_BGM_Battle_Round1_v1.caf", true, 1.0f); + this->runAction(Sequence::create( + DelayTime::create(8.0f), + CallFunc::create([=]() + { + AudioEngine::stop(id); + }), + nullptr + )); + } + }, 2.0, 10000, 0.0, "audio test"); // add label to show the side effect of "UnqueueBuffers Before alSourceStop" - _time = 0.0; + _time = 0.0; auto labelTime = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "time: "); labelTime->setPosition(layerSize.width * 0.5f, layerSize.height * 0.5f); labelTime->setTag(999); this->addChild(labelTime); // update label quickly - this->schedule( - [=](float dt) { - _time += dt; - char timeString[20] = {0}; - sprintf(timeString, "Time %2.2f", _time); - dynamic_cast(this->getChildByTag(999))->setString(timeString); - }, - 0.05, 1000000, 0, "update label quickly"); + this->schedule([=](float dt){ + _time += dt; + char timeString[20] = {0}; + sprintf(timeString, "Time %2.2f", _time); + dynamic_cast