text,length,is_long_context,metric_val,label_metric "/* * Copyright 2019-2021 Diligent Graphics LLC * Copyright 2015-2019 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include #include #include ""TestingEnvironment.hpp"" #include ""GraphicsAccessories.hpp"" #include ""gtest/gtest.h"" using namespace Diligent; using namespace Diligent::Testing; namespace { static constexpr char g_TrivialVSSource[] = R""( void main(out float4 pos : SV_Position) { pos = float4(0.0, 0.0, 0.0, 0.0); } )""; static constexpr char g_TrivialPSSource[] = R""( float4 main() : SV_Target { return float4(0.0, 0.0, 0.0, 0.0); } )""; static constexpr char g_TexturePSSource[] = R""( Texture2D g_Texture; float4 main() : SV_Target { return g_Texture.Load(int3(0,0,0)); } )""; static constexpr char g_TrivialMSSource[] = R""( struct VertexOut { float4 Pos : SV_Position; }; [numthreads(1,1,1)] [outputtopology(""triangle"")] void main(out indices uint3 tris[1], out vertices VertexOut verts[3]) { SetMeshOutputCounts(4, 2); tris[0] = uint3(0, 1, 2); verts[0].Pos = float4(0.0, 0.0, 0.0, 1.0); verts[1].Pos = float4(-1.0, 1.0, 0.0, 1.0); verts[2].Pos = float4(1.0, 1.0, 0.0, 1.0); } )""; static constexpr char g_TrivialCSSource[] = R""( [numthreads(8,8,1)] void main() { } )""; static constexpr char g_TrivialRGenSource[] = R""( [shader(""raygeneration"")] void main() {} )""; static constexpr char g_TrivialRMissSource[] = R""( struct RTPayload { float4 Color; }; [shader(""miss"")] void main(inout RTPayload payload) {} )""; static constexpr char g_TrivialRCHitSource[] = R""( struct RTPayload { float4 Color; }; [shader(""closesthit"")] void main(inout RTPayload payload, in BuiltInTriangleIntersectionAttributes attr) {} )""; static constexpr char g_TrivialRAHitSource[] = R""( struct RTPayload { float4 Color; }; [shader(""anyhit"")] void main(inout RTPayload payload, in BuiltInTriangleIntersectionAttributes attr) {} )""; static constexpr char g_TrivialRIntSource[] = R""( [shader(""intersection"")] void main() {} )""; static constexpr char g_TrivialRCallSource[] = R""( struct Params { float4 Col; }; [shader(""callable"")] void main(inout Params params) {} )""; class PSOCreationFailureTest : public ::testing::Test { protected: static void SetUpTestSuite() { auto* const pEnv = TestingEnvironment::GetInstance(); auto* const pDevice = pEnv->GetDevice(); const auto& deviceCaps = pDevice->GetDeviceCaps(); sm_HasMeshShader = deviceCaps.Features.MeshShaders && pEnv->HasDXCompiler(); sm_HasRayTracing = pEnv->SupportsRayTracing(); ShaderCreateInfo ShaderCI; ShaderCI.Source = g_TrivialVSSource; ShaderCI.EntryPoint = ""main""; ShaderCI.Desc.ShaderType = SHADER_TYPE_VERTEX; ShaderCI.Desc.Name = ""TrivialVS (PSOCreationFailureTest)""; ShaderCI.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL; ShaderCI.ShaderCompiler = pEnv->GetDefaultCompiler(ShaderCI.SourceLanguage); ShaderCI.UseCombinedTextureSamplers = true; pDevice->CreateShader(ShaderCI, &sm_pTrivialVS); ASSERT_TRUE(sm_pTrivialVS); ShaderCI.Source = g_TrivialPSSource; ShaderCI.Desc.ShaderType = SHADER_TYPE_PIXEL; ShaderCI.Desc.Name = ""TrivialPS (PSOCreationFailureTest)""; pDevice->CreateShader(ShaderCI, &sm_pTrivialPS); ASSERT_TRUE(sm_pTrivialPS); ShaderCI.Source = g_TexturePSSource; ShaderCI.Desc.ShaderType = SHADER_TYPE_PIXEL; ShaderCI.Desc.Name = ""TexturePS (PSOCreationFailureTest)""; pDevice->CreateShader(ShaderCI, &sm_pTexturePS); ASSERT_TRUE(sm_pTexturePS); ShaderCI.Source = g_TrivialCSSource; ShaderCI.Desc.ShaderType = SHADER_TYPE_COMPUTE; ShaderCI.Desc.Name = ""TrivialCS (PSOCreationFailureTest)""; pDevice->CreateShader(ShaderCI, &sm_pTrivialCS); ASSERT_TRUE(sm_pTrivialCS); sm_DefaultGraphicsPsoCI.PSODesc.Name = ""PSOCreationFailureTest - default graphics PSO desc""; sm_DefaultGraphicsPsoCI.GraphicsPipeline.NumRenderTargets = 1; sm_DefaultGraphicsPsoCI.GraphicsPipeline.RTVFormats[0] = TEX_FORMAT_RGBA8_UNORM; sm_DefaultGraphicsPsoCI.GraphicsPipeline.DSVFormat = TEX_FORMAT_D32_FLOAT; sm_DefaultGraphicsPsoCI.pVS = sm_pTrivialVS; sm_DefaultGraphicsPsoCI.pPS = sm_pTrivialPS; { RefCntAutoPtr pGraphicsPSO; pDevice->CreateGraphicsPipelineState(GetGraphicsPSOCreateInfo(""PSOCreationFailureTest - OK graphics PSO""), &pGraphicsPSO); ASSERT_TRUE(pGraphicsPSO); } sm_DefaultComputePsoCI.PSODesc.Name = ""PSOCreationFailureTest - default compute PSO desc""; sm_DefaultComputePsoCI.pCS = sm_pTrivialCS; { RefCntAutoPtr pComputePSO; pDevice->CreateComputePipelineState(GetComputePSOCreateInfo(""PSOCreationFailureTest - OK compute PSO""), &pComputePSO); ASSERT_TRUE(pComputePSO); } if (sm_HasMeshShader) { ShaderCI.ShaderCompiler = SHADER_COMPILER_DXC; ShaderCI.Source = g_TrivialMSSource; ShaderCI.Desc.ShaderType = SHADER_TYPE_MESH; ShaderCI.Desc.Name = ""TrivialMS DXC (PSOCreationFailureTest)""; pDevice->CreateShader(ShaderCI, &sm_pTrivialMS); ASSERT_TRUE(sm_pTrivialMS); ShaderCI.Source = g_TrivialPSSource; ShaderCI.Desc.ShaderType = SHADER_TYPE_PIXEL; ShaderCI.Desc.Name = ""TrivialPS DXC (PSOCreationFailureTest)""; pDevice->CreateShader(ShaderCI, &sm_pTrivialPS_DXC); ASSERT_TRUE(sm_pTrivialPS_DXC); sm_DefaultMeshPsoCI.PSODesc.Name = ""PSOCreationFailureTest - default mesh PSO desc""; sm_DefaultMeshPsoCI.GraphicsPipeline.NumRenderTargets = 1; sm_DefaultMeshPsoCI.GraphicsPipeline.RTVFormats[0] = TEX_FORMAT_RGBA8_UNORM; sm_DefaultMeshPsoCI.GraphicsPipeline.DSVFormat = TEX_FORMAT_D32_FLOAT; sm_DefaultMeshPsoCI.PSODesc.PipelineType = PIPELINE_TYPE_MESH; sm_DefaultMeshPsoCI.pMS = sm_pTrivialMS; sm_DefaultMeshPsoCI.pPS = sm_pTrivialPS_DXC; RefCntAutoPtr pMeshPSO; pDevice->CreateGraphicsPipelineState(GetMeshPSOCreateInfo(""PSOCreationFailureTest - OK mesh PSO""), &pMeshPSO); ASSERT_TRUE(pMeshPSO); } if (sm_HasRayTracing) { ShaderCI.ShaderCompiler = SHADER_COMPILER_DXC; ShaderCI.Source = g_TrivialRGenSource; ShaderCI.Desc.ShaderType = SHADER_TYPE_RAY_GEN; ShaderCI.Desc.Name = ""TrivialRGen (PSOCreationFailureTest)""; pDevice->CreateShader(ShaderCI, &sm_pTrivialRG); ASSERT_TRUE(sm_pTrivialRG); ShaderCI.Source = g_TrivialRMissSource; ShaderCI.Desc.ShaderType = SHADER_TYPE_RAY_MISS; ShaderCI.Desc.Name = ""TrivialRMiss (PSOCreationFailureTest)""; pDevice->CreateShader(ShaderCI, &sm_pTrivialRMiss); ASSERT_TRUE(sm_pTrivialRMiss); ShaderCI.Source = g_TrivialRCallSource; ShaderCI.Desc.ShaderType = SHADER_TYPE_CALLABLE; ShaderCI.Desc.Name = ""TrivialRCall (PSOCreationFailureTest)""; pDevice->CreateShader(ShaderCI, &sm_pTrivialRCall); ASSERT_TRUE(sm_pTrivialRCall); ShaderCI.Source = g_TrivialRCHitSource; ShaderCI.Desc.ShaderType = SHADER_TYPE_RAY_CLOSEST_HIT; ShaderCI.Desc.Name = ""TrivialRCHit (PSOCreationFailureTest)""; pDevice->CreateShader(ShaderCI, &sm_pTrivialRCHit); ASSERT_TRUE(sm_pTrivialRCHit); ShaderCI.Source = g_TrivialRAHitSource; ShaderCI.Desc.ShaderType = SHADER_TYPE_RAY_ANY_HIT; ShaderCI.Desc.Name = ""TrivialRAHit (PSOCreationFailureTest)""; pDevice->CreateShader(ShaderCI, &sm_pTrivialRAHit); ASSERT_TRUE(sm_pTrivialRAHit); ShaderCI.Source = g_TrivialRIntSource; ShaderCI.Desc.ShaderType = SHADER_TYPE_RAY_INTERSECTION; ShaderCI.Desc.Name = ""TrivialRInt (PSOCreationFailureTest)""; pDevice->CreateShader(ShaderCI, &sm_pTrivialRInt); ASSERT_TRUE(sm_pTrivialRInt); sm_DefaultRayTracingPsoCI.PSODesc.Name = ""PSOCreationFailureTest - default ray tracing PSO desc""; sm_DefaultRayTracingPsoCI.PSODesc.PipelineType = PIPELINE_TYPE_RAY_TRACING; sm_DefaultRayTracingPsoCI.RayTracingPipeline.MaxRecursionDepth = 1; sm_GeneralGroups[0] = {""Main"", sm_pTrivialRG}; sm_DefaultRayTracingPsoCI.pGeneralShaders = sm_GeneralGroups.data(); sm_DefaultRayTracingPsoCI.GeneralShaderCount = static_cast(sm_GeneralGroups.size()); RefCntAutoPtr pRayTracingPSO; pDevice->CreateGraphicsPipelineState(GetMeshPSOCreateInfo(""PSOCreationFailureTest - OK ray tracing PSO""), &pRayTracingPSO); ASSERT_TRUE(pRayTracingPSO); } RenderPassDesc RPDesc; RPDesc.Name = ""PSOCreationFailureTest - render pass""; RenderPassAttachmentDesc Attachments[2]{}; Attachments[0].Format = TEX_FORMAT_RGBA8_UNORM; Attachments[0].InitialState = RESOURCE_STATE_RENDER_TARGET; Attachments[0].FinalState = RESOURCE_STATE_RENDER_TARGET; Attachments[1].Format = TEX_FORMAT_D32_FLOAT; Attachments[1].InitialState = RESOURCE_STATE_DEPTH_WRITE; Attachments[1].FinalState = RESOURCE_STATE_DEPTH_WRITE; RPDesc.AttachmentCount = _countof(Attachments); RPDesc.pAttachments = Attachments; AttachmentReference ColorAttachmentRef{0, RESOURCE_STATE_RENDER_TARGET}; AttachmentReference DepthAttachmentRef{1, RESOURCE_STATE_DEPTH_WRITE}; SubpassDesc Subpasses[1]{}; Subpasses[0].RenderTargetAttachmentCount = 1; Subpasses[0].pRenderTargetAttachments = &ColorAttachmentRef; Subpasses[0].pDepthStencilAttachment = &DepthAttachmentRef; RPDesc.SubpassCount = _countof(Subpasses); RPDesc.pSubpasses = Subpasses; pDevice->CreateRenderPass(RPDesc, &sm_pRenderPass); ASSERT_TRUE(sm_pRenderPass); { RefCntAutoPtr pGraphicsPSO; pDevice->CreateGraphicsPipelineState(GetGraphicsPSOCreateInfo(""PSOCreationFailureTest - OK PSO with render pass"", true), &pGraphicsPSO); ASSERT_TRUE(pGraphicsPSO); } { PipelineResourceDesc Resources[] = // { PipelineResourceDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, ""g_Texture"", 1, SHADER_RESOURCE_TYPE_TEXTURE_SRV, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE} // }; ImmutableSamplerDesc ImmutableSmplers[] // { ImmutableSamplerDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, ""g_Texture_sampler"", SamplerDesc{}} // }; PipelineResourceSignatureDesc PRSDesc; PRSDesc.Name = ""PRS0""; PRSDesc.NumResources = _countof(Resources); PRSDesc.Resources = Resources; PRSDesc.NumImmutableSamplers = _countof(ImmutableSmplers); PRSDesc.ImmutableSamplers = ImmutableSmplers; pDevice->CreatePipelineResourceSignature(PRSDesc, &sm_pSignature0); ASSERT_TRUE(sm_pSignature0); } { PipelineResourceDesc Resources[] = // { PipelineResourceDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, ""g_Texture2"", 1, SHADER_RESOURCE_TYPE_TEXTURE_SRV, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE} // }; PipelineResourceSignatureDesc PRSDesc; PRSDesc.Name = ""PRS0A""; PRSDesc.NumResources = _countof(Resources); PRSDesc.Resources = Resources; pDevice->CreatePipelineResourceSignature(PRSDesc, &sm_pSignature0A); ASSERT_TRUE(sm_pSignature0A); } if (deviceCaps.Features.GeometryShaders) { PipelineResourceDesc Resources[] = // { PipelineResourceDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_GEOMETRY, ""g_Texture"", 1, SHADER_RESOURCE_TYPE_TEXTURE_SRV, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE} // }; PipelineResourceSignatureDesc PRSDesc; PRSDesc.Name = ""PRS1""; PRSDesc.BindingIndex = 1; PRSDesc.NumResources = _countof(Resources); PRSDesc.Resources = Resources; pDevice->CreatePipelineResourceSignature(PRSDesc, &sm_pSignature1); ASSERT_TRUE(sm_pSignature1); } if (deviceCaps.Features.GeometryShaders) { PipelineResourceDesc Resources[] = // { PipelineResourceDesc{SHADER_TYPE_GEOMETRY, ""g_Texture"", 1, SHADER_RESOURCE_TYPE_TEXTURE_SRV, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE} // }; ImmutableSamplerDesc ImmutableSmplers[] // { ImmutableSamplerDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_GEOMETRY, ""g_Texture_sampler"", SamplerDesc{}} // }; PipelineResourceSignatureDesc PRSDesc; PRSDesc.Name = ""PRS1A""; PRSDesc.BindingIndex = 1; PRSDesc.NumResources = _countof(Resources); PRSDesc.Resources = Resources; PRSDesc.NumImmutableSamplers = _countof(ImmutableSmplers); PRSDesc.ImmutableSamplers = ImmutableSmplers; pDevice->CreatePipelineResourceSignature(PRSDesc, &sm_pSignature1A); ASSERT_TRUE(sm_pSignature1A); } } static void TearDownTestSuite() { sm_pTrivialVS.Release(); sm_pTrivialPS.Release(); sm_pTrivialPS_DXC.Release(); sm_pTexturePS.Release(); sm_pTrivialMS.Release(); sm_pTrivialCS.Release(); sm_pTrivialRG.Release(); sm_pTrivialRMiss.Release(); sm_pTrivialRCall.Release(); sm_pTrivialRCHit.Release(); sm_pTrivialRAHit.Release(); sm_pTrivialRInt.Release(); sm_pRenderPass.Release(); sm_pSignature0.Release(); sm_pSignature0A.Release(); sm_pSignature1.Release(); sm_pSignature1A.Release(); } static GraphicsPipelineStateCreateInfo GetGraphicsPSOCreateInfo(const char* Name, bool UseRenderPass = false) { auto CI{sm_DefaultGraphicsPsoCI}; CI.PSODesc.Name = Name; if (UseRenderPass) { CI.GraphicsPipeline.NumRenderTargets = 0; CI.GraphicsPipeline.RTVFormats[0] = TEX_FORMAT_UNKNOWN; CI.GraphicsPipeline.DSVFormat = TEX_FORMAT_UNKNOWN; CI.GraphicsPipeline.pRenderPass = sm_pRenderPass; } return CI; } static GraphicsPipelineStateCreateInfo GetMeshPSOCreateInfo(const char* Name, bool UseRenderPass = false) { VERIFY_EXPR(HasMeshShader()); auto CI{sm_DefaultMeshPsoCI}; CI.PSODesc.Name = Name; if (UseRenderPass) { CI.GraphicsPipeline.NumRenderTargets = 0; CI.GraphicsPipeline.RTVFormats[0] = TEX_FORMAT_UNKNOWN; CI.GraphicsPipeline.DSVFormat = TEX_FORMAT_UNKNOWN; CI.GraphicsPipeline.pRenderPass = sm_pRenderPass; } return CI; } static ComputePipelineStateCreateInfo GetComputePSOCreateInfo(const char* Name) { auto CI{sm_DefaultComputePsoCI}; CI.PSODesc.Name = Name; return CI; } static RayTracingPipelineStateCreateInfo GetRayTracingPSOCreateInfo(const char* Name) { VERIFY_EXPR(HasRayTracing()); auto CI{sm_DefaultRayTracingPsoCI}; CI.PSODesc.Name = Name; return CI; } static IShader* GetVS() { return sm_pTrivialVS; } static IShader* GetPS() { return sm_pTrivialPS; } static IShader* GetMS() { return sm_pTrivialMS; } static IShader* GetTexturePS() { return sm_pTexturePS; } static IShader* GetRayGen() { return sm_pTrivialRG; } static IShader* GetRayMiss() { return sm_pTrivialRMiss; } static IShader* GetCallable() { return sm_pTrivialRCall; } static IShader* GetRayClosestHit() { return sm_pTrivialRCHit; } static IShader* GetRayAnyHit() { return sm_pTrivialRAHit; } static IShader* GetRayIntersection() { return sm_pTrivialRInt; } static bool HasMeshShader() { return sm_HasMeshShader; } static bool HasRayTracing() { return sm_HasRayTracing; } static void TestCreatePSOFailure(GraphicsPipelineStateCreateInfo CI, const char* ExpectedErrorSubstring) { auto* const pEnv = TestingEnvironment::GetInstance(); auto* const pDevice = pEnv->GetDevice(); RefCntAutoPtr pPSO; pEnv->SetErrorAllowance(2, ""Errors below are expected: testing PSO creation failure\\n""); pEnv->PushExpectedErrorSubstring(ExpectedErrorSubstring); pDevice->CreateGraphicsPipelineState(CI, &pPSO); ASSERT_FALSE(pPSO); CI.PSODesc.Name = nullptr; pEnv->SetErrorAllowance(2); pEnv->PushExpectedErrorSubstring(ExpectedErrorSubstring); pDevice->CreateGraphicsPipelineState(CI, &pPSO); ASSERT_FALSE(pPSO); pEnv->SetErrorAllowance(0); } static void TestCreatePSOFailure(ComputePipelineStateCreateInfo CI, const char* ExpectedErrorSubstring) { auto* const pEnv = TestingEnvironment::GetInstance(); auto* const pDevice = pEnv->GetDevice(); RefCntAutoPtr pPSO; pEnv->SetErrorAllowance(2, ""Errors below are expected: testing PSO creation failure\\n""); pEnv->PushExpectedErrorSubstring(ExpectedErrorSubstring); pDevice->CreateComputePipelineState(CI, &pPSO); ASSERT_FALSE(pPSO); CI.PSODesc.Name = nullptr; pEnv->SetErrorAllowance(2); pEnv->PushExpectedErrorSubstring(ExpectedErrorSubstring); pDevice->CreateComputePipelineState(CI, &pPSO); ASSERT_FALSE(pPSO); pEnv->SetErrorAllowance(0); } static void TestCreatePSOFailure(RayTracingPipelineStateCreateInfo CI, const char* ExpectedErrorSubstring) { auto* const pEnv = TestingEnvironment::GetInstance(); auto* const pDevice = pEnv->GetDevice(); RefCntAutoPtr pPSO; pEnv->SetErrorAllowance(2, ""Errors below are expected: testing PSO creation failure\\n""); pEnv->PushExpectedErrorSubstring(ExpectedErrorSubstring); pDevice->CreateRayTracingPipelineState(CI, &pPSO); ASSERT_FALSE(pPSO); CI.PSODesc.Name = nullptr; pEnv->SetErrorAllowance(2); pEnv->PushExpectedErrorSubstring(ExpectedErrorSubstring); pDevice->CreateRayTracingPipelineState(CI, &pPSO); ASSERT_FALSE(pPSO); pEnv->SetErrorAllowance(0); } protected: static RefCntAutoPtr sm_pSignature0; static RefCntAutoPtr sm_pSignature0A; static RefCntAutoPtr sm_pSignature1; static RefCntAutoPtr sm_pSignature1A; private: static RefCntAutoPtr sm_pTrivialVS; static RefCntAutoPtr sm_pTrivialPS; static RefCntAutoPtr sm_pTrivialPS_DXC; static RefCntAutoPtr sm_pTexturePS; static RefCntAutoPtr sm_pTrivialMS; static RefCntAutoPtr sm_pTrivialRG; static RefCntAutoPtr sm_pTrivialRMiss; static RefCntAutoPtr sm_pTrivialRCHit; static RefCntAutoPtr sm_pTrivialRAHit; static RefCntAutoPtr sm_pTrivialRInt; static RefCntAutoPtr sm_pTrivialRCall; static RefCntAutoPtr sm_pTrivialCS; static RefCntAutoPtr sm_pRenderPass; static GraphicsPipelineStateCreateInfo sm_DefaultGraphicsPsoCI; static GraphicsPipelineStateCreateInfo sm_DefaultMeshPsoCI; static ComputePipelineStateCreateInfo sm_DefaultComputePsoCI; static RayTracingPipelineStateCreateInfo sm_DefaultRayTracingPsoCI; static std::array sm_GeneralGroups; static bool sm_HasMeshShader; static bool sm_HasRayTracing; }; RefCntAutoPtr PSOCreationFailureTest::sm_pTrivialVS; RefCntAutoPtr PSOCreationFailureTest::sm_pTrivialPS; RefCntAutoPtr PSOCreationFailureTest::sm_pTexturePS; RefCntAutoPtr PSOCreationFailureTest::sm_pTrivialPS_DXC; RefCntAutoPtr PSOCreationFailureTest::sm_pTrivialMS; RefCntAutoPtr PSOCreationFailureTest::sm_pTrivialCS; RefCntAutoPtr PSOCreationFailureTest::sm_pTrivialRG; RefCntAutoPtr PSOCreationFailureTest::sm_pTrivialRMiss; RefCntAutoPtr PSOCreationFailureTest::sm_pTrivialRCHit; RefCntAutoPtr PSOCreationFailureTest::sm_pTrivialRAHit; RefCntAutoPtr PSOCreationFailureTest::sm_pTrivialRInt; RefCntAutoPtr PSOCreationFailureTest::sm_pTrivialRCall; RefCntAutoPtr PSOCreationFailureTest::sm_pRenderPass; RefCntAutoPtr PSOCreationFailureTest::sm_pSignature0; RefCntAutoPtr PSOCreationFailureTest::sm_pSignature0A; RefCntAutoPtr PSOCreationFailureTest::sm_pSignature1; RefCntAutoPtr PSOCreationFailureTest::sm_pSignature1A; GraphicsPipelineStateCreateInfo PSOCreationFailureTest::sm_DefaultGraphicsPsoCI; GraphicsPipelineStateCreateInfo PSOCreationFailureTest::sm_DefaultMeshPsoCI; ComputePipelineStateCreateInfo PSOCreationFailureTest::sm_DefaultComputePsoCI; RayTracingPipelineStateCreateInfo PSOCreationFailureTest::sm_DefaultRayTracingPsoCI; std::array PSOCreationFailureTest::sm_GeneralGroups; bool PSOCreationFailureTest::sm_HasMeshShader; bool PSOCreationFailureTest::sm_HasRayTracing; TEST_F(PSOCreationFailureTest, InvalidGraphicsPipelineType) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid Graphics Pipeline Type"")}; PsoCI.PSODesc.PipelineType = PIPELINE_TYPE_COMPUTE; TestCreatePSOFailure(PsoCI, ""Pipeline type must be GRAPHICS or MESH""); } TEST_F(PSOCreationFailureTest, NoVS) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - no VS"")}; PsoCI.pVS = nullptr; TestCreatePSOFailure(PsoCI, ""Vertex shader must not be null""); } TEST_F(PSOCreationFailureTest, IncorrectVSType) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - incorrect VS Type"")}; PsoCI.pVS = GetPS(); TestCreatePSOFailure(PsoCI, ""SHADER_TYPE_PIXEL is not a valid type for vertex shader""); } TEST_F(PSOCreationFailureTest, IncorrectPSType) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - incorrect PS Type"")}; PsoCI.pPS = GetVS(); TestCreatePSOFailure(PsoCI, ""SHADER_TYPE_VERTEX is not a valid type for pixel shader""); } TEST_F(PSOCreationFailureTest, IncorrectGSType) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - incorrect GS Type"")}; PsoCI.pGS = GetVS(); TestCreatePSOFailure(PsoCI, ""SHADER_TYPE_VERTEX is not a valid type for geometry shader""); } TEST_F(PSOCreationFailureTest, IncorrectDSType) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - incorrect DS Type"")}; PsoCI.pDS = GetVS(); TestCreatePSOFailure(PsoCI, ""SHADER_TYPE_VERTEX is not a valid type for domain shader""); } TEST_F(PSOCreationFailureTest, IncorrectHSType) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - incorrect HS Type"")}; PsoCI.pHS = GetVS(); TestCreatePSOFailure(PsoCI, ""SHADER_TYPE_VERTEX is not a valid type for hull shader""); } TEST_F(PSOCreationFailureTest, WrongSubpassIndex) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - wrong subpass index"")}; PsoCI.GraphicsPipeline.SubpassIndex = 1; TestCreatePSOFailure(PsoCI, ""Subpass index (1) must be 0""); } TEST_F(PSOCreationFailureTest, UndefinedFillMode) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Undefined Fill Mode"")}; PsoCI.GraphicsPipeline.RasterizerDesc.FillMode = FILL_MODE_UNDEFINED; TestCreatePSOFailure(PsoCI, ""RasterizerDesc.FillMode must not be FILL_MODE_UNDEFINED""); } TEST_F(PSOCreationFailureTest, UndefinedCullMode) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Undefined Cull Mode"")}; PsoCI.GraphicsPipeline.RasterizerDesc.CullMode = CULL_MODE_UNDEFINED; TestCreatePSOFailure(PsoCI, ""RasterizerDesc.CullMode must not be CULL_MODE_UNDEFINED""); } TEST_F(PSOCreationFailureTest, InvalidDepthFunc) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid Depth Func"")}; PsoCI.GraphicsPipeline.DepthStencilDesc.DepthFunc = COMPARISON_FUNC_UNKNOWN; TestCreatePSOFailure(PsoCI, ""DepthStencilDesc.DepthFunc must not be COMPARISON_FUNC_UNKNOWN""); } TEST_F(PSOCreationFailureTest, InvalidFrontStencilFailOp) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid Front Face StencilFailOp"")}; PsoCI.GraphicsPipeline.DepthStencilDesc.StencilEnable = True; PsoCI.GraphicsPipeline.DepthStencilDesc.FrontFace.StencilFailOp = STENCIL_OP_UNDEFINED; TestCreatePSOFailure(PsoCI, ""DepthStencilDesc.FrontFace.StencilFailOp must not be STENCIL_OP_UNDEFINED""); } TEST_F(PSOCreationFailureTest, InvalidBackStencilFailOp) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid Back Face StencilFailOp"")}; PsoCI.GraphicsPipeline.DepthStencilDesc.StencilEnable = True; PsoCI.GraphicsPipeline.DepthStencilDesc.BackFace.StencilFailOp = STENCIL_OP_UNDEFINED; TestCreatePSOFailure(PsoCI, ""DepthStencilDesc.BackFace.StencilFailOp must not be STENCIL_OP_UNDEFINED""); } TEST_F(PSOCreationFailureTest, InvalidFrontStencilDepthFailOp) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid Front Face StencilDepthFailOp"")}; PsoCI.GraphicsPipeline.DepthStencilDesc.StencilEnable = True; PsoCI.GraphicsPipeline.DepthStencilDesc.FrontFace.StencilDepthFailOp = STENCIL_OP_UNDEFINED; TestCreatePSOFailure(PsoCI, ""DepthStencilDesc.FrontFace.StencilDepthFailOp must not be STENCIL_OP_UNDEFINED""); } TEST_F(PSOCreationFailureTest, InvalidBackStencilDepthFailOp) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid Back Face StencilDepthFailOp"")}; PsoCI.GraphicsPipeline.DepthStencilDesc.StencilEnable = True; PsoCI.GraphicsPipeline.DepthStencilDesc.BackFace.StencilDepthFailOp = STENCIL_OP_UNDEFINED; TestCreatePSOFailure(PsoCI, ""DepthStencilDesc.BackFace.StencilDepthFailOp must not be STENCIL_OP_UNDEFINED""); } TEST_F(PSOCreationFailureTest, InvalidFrontStencilPassOp) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid Front Face StencilPassOp"")}; PsoCI.GraphicsPipeline.DepthStencilDesc.StencilEnable = True; PsoCI.GraphicsPipeline.DepthStencilDesc.FrontFace.StencilPassOp = STENCIL_OP_UNDEFINED; TestCreatePSOFailure(PsoCI, ""DepthStencilDesc.FrontFace.StencilPassOp must not be STENCIL_OP_UNDEFINED""); } TEST_F(PSOCreationFailureTest, InvalidBackStencilPassOp) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid Back Face StencilPassOp"")}; PsoCI.GraphicsPipeline.DepthStencilDesc.StencilEnable = True; PsoCI.GraphicsPipeline.DepthStencilDesc.BackFace.StencilPassOp = STENCIL_OP_UNDEFINED; TestCreatePSOFailure(PsoCI, ""DepthStencilDesc.BackFace.StencilPassOp must not be STENCIL_OP_UNDEFINED""); } TEST_F(PSOCreationFailureTest, InvalidFrontStencilFunc) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid Front Face StencilFunc"")}; PsoCI.GraphicsPipeline.DepthStencilDesc.StencilEnable = True; PsoCI.GraphicsPipeline.DepthStencilDesc.FrontFace.StencilFunc = COMPARISON_FUNC_UNKNOWN; TestCreatePSOFailure(PsoCI, ""DepthStencilDesc.FrontFace.StencilFunc must not be COMPARISON_FUNC_UNKNOWN""); } TEST_F(PSOCreationFailureTest, InvalidBackStencilFunc) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid Back Face StencilFunc"")}; PsoCI.GraphicsPipeline.DepthStencilDesc.StencilEnable = True; PsoCI.GraphicsPipeline.DepthStencilDesc.BackFace.StencilFunc = COMPARISON_FUNC_UNKNOWN; TestCreatePSOFailure(PsoCI, ""DepthStencilDesc.BackFace.StencilFunc must not be COMPARISON_FUNC_UNKNOWN""); } TEST_F(PSOCreationFailureTest, InvalidSrcBlend) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid SrcBlend"")}; PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].BlendEnable = True; PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].SrcBlend = BLEND_FACTOR_UNDEFINED; TestCreatePSOFailure(PsoCI, ""BlendDesc.RenderTargets[0].SrcBlend must not be BLEND_FACTOR_UNDEFINED""); } TEST_F(PSOCreationFailureTest, InvalidDestBlend) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid DestBlend"")}; PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].BlendEnable = True; PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].DestBlend = BLEND_FACTOR_UNDEFINED; TestCreatePSOFailure(PsoCI, ""BlendDesc.RenderTargets[0].DestBlend must not be BLEND_FACTOR_UNDEFINED""); } TEST_F(PSOCreationFailureTest, InvalidBlendOp) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid BlendOp"")}; PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].BlendEnable = True; PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].BlendOp = BLEND_OPERATION_UNDEFINED; TestCreatePSOFailure(PsoCI, ""BlendDesc.RenderTargets[0].BlendOp must not be BLEND_OPERATION_UNDEFINED""); } TEST_F(PSOCreationFailureTest, InvalidSrcBlendAlpha) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid SrcBlendAlpha"")}; PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].BlendEnable = True; PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].SrcBlendAlpha = BLEND_FACTOR_UNDEFINED; TestCreatePSOFailure(PsoCI, ""BlendDesc.RenderTargets[0].SrcBlendAlpha must not be BLEND_FACTOR_UNDEFINED""); } TEST_F(PSOCreationFailureTest, InvalidDestBlendAlpha) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid DestBlendAlpha"")}; PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].BlendEnable = True; PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].DestBlendAlpha = BLEND_FACTOR_UNDEFINED; TestCreatePSOFailure(PsoCI, ""BlendDesc.RenderTargets[0].DestBlendAlpha must not be BLEND_FACTOR_UNDEFINED""); } TEST_F(PSOCreationFailureTest, InvalidBlendOpAlpha) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid BlendOpAlpha"")}; PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].BlendEnable = True; PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].BlendOpAlpha = BLEND_OPERATION_UNDEFINED; TestCreatePSOFailure(PsoCI, ""BlendDesc.RenderTargets[0].BlendOpAlpha must not be BLEND_OPERATION_UNDEFINED""); } TEST_F(PSOCreationFailureTest, NullVariableName) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - null variable name"")}; ShaderResourceVariableDesc Variables[] // { ShaderResourceVariableDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, ""g_Texture"", SHADER_RESOURCE_VARIABLE_TYPE_STATIC}, ShaderResourceVariableDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, nullptr, SHADER_RESOURCE_VARIABLE_TYPE_STATIC} // }; PsoCI.PSODesc.ResourceLayout.Variables = Variables; PsoCI.PSODesc.ResourceLayout.NumVariables = _countof(Variables); TestCreatePSOFailure(PsoCI, ""ResourceLayout.Variables[1].Name must not be null""); } TEST_F(PSOCreationFailureTest, EmptyVariableName) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - empty variable name"")}; ShaderResourceVariableDesc Variables[] // { ShaderResourceVariableDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, ""g_Texture"", SHADER_RESOURCE_VARIABLE_TYPE_STATIC}, ShaderResourceVariableDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, """", SHADER_RESOURCE_VARIABLE_TYPE_STATIC} // }; PsoCI.PSODesc.ResourceLayout.Variables = Variables; PsoCI.PSODesc.ResourceLayout.NumVariables = _countof(Variables); TestCreatePSOFailure(PsoCI, ""ResourceLayout.Variables[1].Name must not be empty""); } TEST_F(PSOCreationFailureTest, UnknownVariableShaderStage) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - unknown variable shader stage"")}; ShaderResourceVariableDesc Variables[] // { ShaderResourceVariableDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, ""g_Texture"", SHADER_RESOURCE_VARIABLE_TYPE_STATIC}, ShaderResourceVariableDesc{SHADER_TYPE_UNKNOWN, ""g_Texture2"", SHADER_RESOURCE_VARIABLE_TYPE_STATIC} // }; PsoCI.PSODesc.ResourceLayout.Variables = Variables; PsoCI.PSODesc.ResourceLayout.NumVariables = _countof(Variables); TestCreatePSOFailure(PsoCI, ""ResourceLayout.Variables[1].ShaderStages must not be SHADER_TYPE_UNKNOWN""); } TEST_F(PSOCreationFailureTest, OverlappingVariableStages) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Overlapping Variable Stages"")}; ShaderResourceVariableDesc Variables[] // { ShaderResourceVariableDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, ""g_Texture"", SHADER_RESOURCE_VARIABLE_TYPE_STATIC}, ShaderResourceVariableDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_GEOMETRY, ""g_Texture"", SHADER_RESOURCE_VARIABLE_TYPE_STATIC} // }; PsoCI.PSODesc.ResourceLayout.Variables = Variables; PsoCI.PSODesc.ResourceLayout.NumVariables = _countof(Variables); TestCreatePSOFailure(PsoCI, ""'g_Texture' is defined in overlapping shader stages (SHADER_TYPE_VERTEX, SHADER_TYPE_GEOMETRY and SHADER_TYPE_VERTEX, SHADER_TYPE_PIXEL)""); } TEST_F(PSOCreationFailureTest, NullImmutableSamplerName) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - null immutable sampler name"")}; ImmutableSamplerDesc ImtblSamplers[] // { ImmutableSamplerDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, ""g_Texture_sampler"", SamplerDesc{}}, ImmutableSamplerDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, nullptr, SamplerDesc{}} // }; PsoCI.PSODesc.ResourceLayout.ImmutableSamplers = ImtblSamplers; PsoCI.PSODesc.ResourceLayout.NumImmutableSamplers = _countof(ImtblSamplers); TestCreatePSOFailure(PsoCI, ""ResourceLayout.ImmutableSamplers[1].SamplerOrTextureName must not be null""); } TEST_F(PSOCreationFailureTest, EmptyImmutableSamplerName) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - empty immutable sampler name"")}; ImmutableSamplerDesc ImtblSamplers[] // { ImmutableSamplerDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, ""g_Texture_sampler"", SamplerDesc{}}, ImmutableSamplerDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, """", SamplerDesc{}} // }; PsoCI.PSODesc.ResourceLayout.ImmutableSamplers = ImtblSamplers; PsoCI.PSODesc.ResourceLayout.NumImmutableSamplers = _countof(ImtblSamplers); TestCreatePSOFailure(PsoCI, ""ResourceLayout.ImmutableSamplers[1].SamplerOrTextureName must not be empty""); } TEST_F(PSOCreationFailureTest, UndefinedImmutableSamplerShaderStages) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - undefined immutable sampler shader stages"")}; ImmutableSamplerDesc ImtblSamplers[] // { ImmutableSamplerDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, ""g_Texture_sampler"", SamplerDesc{}}, ImmutableSamplerDesc{SHADER_TYPE_UNKNOWN, ""g_Texture_sampler2"", SamplerDesc{}} // }; PsoCI.PSODesc.ResourceLayout.ImmutableSamplers = ImtblSamplers; PsoCI.PSODesc.ResourceLayout.NumImmutableSamplers = _countof(ImtblSamplers); TestCreatePSOFailure(PsoCI, ""ResourceLayout.ImmutableSamplers[1].ShaderStages must not be SHADER_TYPE_UNKNOWN""); } TEST_F(PSOCreationFailureTest, OverlappingImmutableSamplerStages) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Overlapping Immutable Sampler Stages"")}; ImmutableSamplerDesc ImtblSamplers[] // { ImmutableSamplerDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, ""g_Texture_sampler"", SamplerDesc{}}, ImmutableSamplerDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_GEOMETRY, ""g_Texture_sampler"", SamplerDesc{}} // }; PsoCI.PSODesc.ResourceLayout.ImmutableSamplers = ImtblSamplers; PsoCI.PSODesc.ResourceLayout.NumImmutableSamplers = _countof(ImtblSamplers); TestCreatePSOFailure(PsoCI, ""'g_Texture_sampler' is defined in overlapping shader stages (SHADER_TYPE_VERTEX, SHADER_TYPE_GEOMETRY and SHADER_TYPE_VERTEX, SHADER_TYPE_PIXEL)""); } TEST_F(PSOCreationFailureTest, RenderPassWithNonZeroNumRenderTargets) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Render Pass With non-zero NumRenderTargets"", true)}; PsoCI.GraphicsPipeline.NumRenderTargets = 1; TestCreatePSOFailure(PsoCI, ""NumRenderTargets must be 0""); } TEST_F(PSOCreationFailureTest, RenderPassWithDSVFormat) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Render Pass With defined DSV format"", true)}; PsoCI.GraphicsPipeline.DSVFormat = TEX_FORMAT_D32_FLOAT; TestCreatePSOFailure(PsoCI, ""DSVFormat must be TEX_FORMAT_UNKNOWN""); } TEST_F(PSOCreationFailureTest, RenderPassWithRTVFormat) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Render Pass With defined RTV format"", true)}; PsoCI.GraphicsPipeline.RTVFormats[1] = TEX_FORMAT_RGBA8_UNORM; TestCreatePSOFailure(PsoCI, ""RTVFormats[1] must be TEX_FORMAT_UNKNOWN""); } TEST_F(PSOCreationFailureTest, RenderPassWithInvalidSubpassIndex) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Render Pass With invalid Subpass index"", true)}; PsoCI.GraphicsPipeline.SubpassIndex = 2; TestCreatePSOFailure(PsoCI, ""Subpass index (2) exceeds the number of subpasses (1)""); } TEST_F(PSOCreationFailureTest, NullResourceSignatures) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Null Resource Signatures"", true)}; PsoCI.ResourceSignaturesCount = 2; TestCreatePSOFailure(PsoCI, ""ppResourceSignatures is null, but ResourceSignaturesCount (2) is not zero""); } TEST_F(PSOCreationFailureTest, ZeroResourceSignaturesCount) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Zero Resource Signatures Count"", true)}; IPipelineResourceSignature* pSignatures[] = {sm_pSignature0}; PsoCI.ppResourceSignatures = pSignatures; PsoCI.ResourceSignaturesCount = 0; TestCreatePSOFailure(PsoCI, ""ppResourceSignatures is not null, but ResourceSignaturesCount is zero.""); } TEST_F(PSOCreationFailureTest, SignatureWithNonZeroNumVariables) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Resource Signature With non-zero NumVariables"", true)}; IPipelineResourceSignature* pSignatures[] = {sm_pSignature0}; PsoCI.ppResourceSignatures = pSignatures; PsoCI.ResourceSignaturesCount = _countof(pSignatures); PsoCI.PSODesc.ResourceLayout.NumVariables = 3; TestCreatePSOFailure(PsoCI, ""The number of variables defined through resource layout (3) must be zero""); } TEST_F(PSOCreationFailureTest, SignatureWithNonZeroNumImmutableSamplers) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Resource Signature With non-zero NumImmutableSamplers"", true)}; IPipelineResourceSignature* pSignatures[] = {sm_pSignature0}; PsoCI.ppResourceSignatures = pSignatures; PsoCI.ResourceSignaturesCount = _countof(pSignatures); PsoCI.PSODesc.ResourceLayout.NumImmutableSamplers = 4; TestCreatePSOFailure(PsoCI, ""The number of immutable samplers defined through resource layout (4) must be zero""); } TEST_F(PSOCreationFailureTest, NullSignature) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Null Signature"", true)}; IPipelineResourceSignature* pSignatures[] = {sm_pSignature0, nullptr}; PsoCI.ppResourceSignatures = pSignatures; PsoCI.ResourceSignaturesCount = _countof(pSignatures); TestCreatePSOFailure(PsoCI, ""signature at index 1 is null""); } TEST_F(PSOCreationFailureTest, ConflictingSignatureBindIndex) { auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Conflicting Signature Bind Index"", true)}; IPipelineResourceSignature* pSignatures[] = {sm_pSignature0, sm_pSignature0A}; PsoCI.ppResourceSignatures = pSignatures; PsoCI.ResourceSignaturesCount = _countof(pSignatures); TestCreatePSOFailure(PsoCI, ""'PRS0A' at binding index 0 conflicts with another resource signature 'PRS0'""); } TEST_F(PSOCreationFailureTest, ConflictingSignatureResourceStages) { if (!sm_pSignature1) GTEST_SKIP(); auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - conflicting signature resource stages"", true)}; IPipelineResourceSignature* pSignatures[] = {sm_pSignature0, sm_pSignature1}; PsoCI.ppResourceSignatures = pSignatures; PsoCI.ResourceSignaturesCount = _countof(pSignatures); TestCreatePSOFailure(PsoCI, ""Shader resource 'g_Texture' is found in more than one resource signature ('PRS1' and 'PRS0')""); } TEST_F(PSOCreationFailureTest, ConflictingImmutableSamplerStages) { if (!sm_pSignature1A) GTEST_SKIP(); auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - conflicting signature immutable sampler stages"", true)}; IPipelineResourceSignature* pSignatures[] = {sm_pSignature0, sm_pSignature1A}; PsoCI.ppResourceSignatures = pSignatures; PsoCI.ResourceSignaturesCount = _countof(pSignatures); // In case of non-separable programs, there is another error - a resource (""g_Texture"") is found in different signatures const auto* ExpectedError = TestingEnvironment::GetInstance()->GetDevice()->GetDeviceCaps().Features.SeparablePrograms ? ""Immutable sampler 'g_Texture_sampler' is found in more than one resource signature ('PRS1A' and 'PRS0')"" : ""shader resource 'g_Texture' is found in more than one resource signature ('PRS1A' and 'PRS0')""; TestCreatePSOFailure(PsoCI, ExpectedError); } TEST_F(PSOCreationFailureTest, InvalidComputePipelineType) { auto PsoCI{GetComputePSOCreateInfo(""PSO Create Failure - Invalid Compute Pipeline Type"")}; PsoCI.PSODesc.PipelineType = PIPELINE_TYPE_GRAPHICS; TestCreatePSOFailure(PsoCI, ""Pipeline type must be COMPUTE""); } TEST_F(PSOCreationFailureTest, NoCS) { auto PsoCI{GetComputePSOCreateInfo(""PSO Create Failure - no CS"")}; PsoCI.pCS = nullptr; TestCreatePSOFailure(PsoCI, ""Compute shader must not be null""); } TEST_F(PSOCreationFailureTest, InvalidCS) { auto PsoCI{GetComputePSOCreateInfo(""PSO Create Failure - invalid CS"")}; PsoCI.pCS = GetPS(); TestCreatePSOFailure(PsoCI, ""SHADER_TYPE_PIXEL is not a valid type for compute shader""); } TEST_F(PSOCreationFailureTest, NullMS) { if (!HasMeshShader()) GTEST_SKIP(); auto PsoCI{GetMeshPSOCreateInfo(""PSO Create Failure - null MS"")}; PsoCI.pMS = nullptr; TestCreatePSOFailure(PsoCI, ""Mesh shader must not be null""); } TEST_F(PSOCreationFailureTest, InvalidMS) { if (!HasMeshShader()) GTEST_SKIP(); auto PsoCI{GetMeshPSOCreateInfo(""PSO Create Failure - Invalid MS"")}; PsoCI.pMS = GetPS(); TestCreatePSOFailure(PsoCI, ""SHADER_TYPE_PIXEL is not a valid type for mesh shader""); } TEST_F(PSOCreationFailureTest, NullRG) { if (!HasRayTracing()) GTEST_SKIP(); auto PsoCI{GetRayTracingPSOCreateInfo(""PSO Create Failure - NUll ray-gen shader"")}; PsoCI.pGeneralShaders = nullptr; PsoCI.GeneralShaderCount = 0; TestCreatePSOFailure(PsoCI, ""At least one shader with type SHADER_TYPE_RAY_GEN must be provided""); } TEST_F(PSOCreationFailureTest, InvalidRTPipelineType) { if (!HasRayTracing()) GTEST_SKIP(); auto PsoCI{GetRayTracingPSOCreateInfo(""PSO Create Failure - Invalid RT pipeline type"")}; PsoCI.PSODesc.PipelineType = PIPELINE_TYPE_COMPUTE; TestCreatePSOFailure(PsoCI, ""Pipeline type must be RAY_TRACING""); } TEST_F(PSOCreationFailureTest, InvalidShaderRecord) { if (!HasRayTracing() || !TestingEnvironment::GetInstance()->GetDevice()->GetDeviceCaps().IsD3DDevice()) GTEST_SKIP(); auto PsoCI{GetRayTracingPSOCreateInfo(""PSO Create Failure - Invalid shader record"")}; PsoCI.pShaderRecordName = ""ShaderRecord""; PsoCI.RayTracingPipeline.ShaderRecordSize = 0; TestCreatePSOFailure(PsoCI, ""pShaderRecordName must not be null if RayTracingPipeline.ShaderRecordSize is not zero""); } TEST_F(PSOCreationFailureTest, TooBigRayRecursionDepth) { if (!HasRayTracing()) GTEST_SKIP(); auto PsoCI{GetRayTracingPSOCreateInfo(""PSO Create Failure - too big ray recursion depth"")}; PsoCI.RayTracingPipeline.MaxRecursionDepth = std::numeric_limits::max(); TestCreatePSOFailure(PsoCI, ""MaxRecursionDepth (255) exceeds device limit""); } TEST_F(PSOCreationFailureTest, NullShaderGroupName) { if (!HasRayTracing()) GTEST_SKIP(); const RayTracingGeneralShaderGroup GeneralGroups[] = {{""Main"", GetRayGen()}, {nullptr, GetRayMiss()}}; auto PsoCI{GetRayTracingPSOCreateInfo(""PSO Create Failure - null shader group name"")}; PsoCI.pGeneralShaders = GeneralGroups; PsoCI.GeneralShaderCount = _countof(GeneralGroups); TestCreatePSOFailure(PsoCI, ""pGeneralShaders[1].Name must not be null""); } TEST_F(PSOCreationFailureTest, EmptyShaderGroupName) { if (!HasRayTracing()) GTEST_SKIP(); const RayTracingGeneralShaderGroup GeneralGroups[] = {{""Main"", GetRayGen()}, {"""", GetRayMiss()}}; auto PsoCI{GetRayTracingPSOCreateInfo(""PSO Create Failure - empty shader group name"")}; PsoCI.pGeneralShaders = GeneralGroups; PsoCI.GeneralShaderCount = _countof(GeneralGroups); TestCreatePSOFailure(PsoCI, ""pGeneralShaders[1].Name must not be empty""); } TEST_F(PSOCreationFailureTest, NonUniqueShaderGroupName) { if (!HasRayTracing()) GTEST_SKIP(); const RayTracingGeneralShaderGroup GeneralGroups[] = {{""Main"", GetRayGen()}, {""Main"", GetRayMiss()}}; auto PsoCI{GetRayTracingPSOCreateInfo(""PSO Create Failure - non-unique shader group name"")}; PsoCI.pGeneralShaders = GeneralGroups; PsoCI.GeneralShaderCount = _countof(GeneralGroups); TestCreatePSOFailure(PsoCI, ""pGeneralShaders[1].Name ('Main') has already been assigned to another group. All group names must be unique.""); } TEST_F(PSOCreationFailureTest, NullGeneralShader) { if (!HasRayTracing()) GTEST_SKIP(); const RayTracingGeneralShaderGroup GeneralGroups[] = {{""Main"", GetRayGen()}, {""Entry"", nullptr}}; auto PsoCI{GetRayTracingPSOCreateInfo(""PSO Create Failure - null general shader"")}; PsoCI.pGeneralShaders = GeneralGroups; PsoCI.GeneralShaderCount = _countof(GeneralGroups); TestCreatePSOFailure(PsoCI, ""pGeneralShaders[1].pShader must not be null""); } TEST_F(PSOCreationFailureTest, NullTriHitShader) { if (!HasRayTracing()) GTEST_SKIP(); const RayTracingTriangleHitShaderGroup HitGroups[] = {{""ClosestHit"", nullptr}}; auto PsoCI{GetRayTracingPSOCreateInfo(""PSO Create Failure - null triangle closest hit shader"")}; PsoCI.pTriangleHitShaders = HitGroups; PsoCI.TriangleHitShaderCount = _countof(HitGroups); TestCreatePSOFailure(PsoCI, ""pTriangleHitShaders[0].pClosestHitShader must not be null""); } TEST_F(PSOCreationFailureTest, NullProcHitShader) { if (!HasRayTracing()) GTEST_SKIP(); const RayTracingProceduralHitShaderGroup HitGroups[] = {{""Intersection"", nullptr}}; auto PsoCI{GetRayTracingPSOCreateInfo(""PSO Create Failure - null procedural intersection shader"")}; PsoCI.pProceduralHitShaders = HitGroups; PsoCI.ProceduralHitShaderCount = _countof(HitGroups); TestCreatePSOFailure(PsoCI, ""pProceduralHitShaders[0].pIntersectionShader must not be null""); } TEST_F(PSOCreationFailureTest, InvalidShaderinGeneralGroup) { if (!HasRayTracing()) GTEST_SKIP(); const RayTracingGeneralShaderGroup GeneralGroups[] = {{""Main"", GetRayGen()}, {""Miss"", GetRayMiss()}, {""Call"", GetCallable()}, {""Hit"", GetRayClosestHit()}}; auto PsoCI{GetRayTracingPSOCreateInfo(""PSO Create Failure - invalid shader in general group"")}; PsoCI.pGeneralShaders = GeneralGroups; PsoCI.GeneralShaderCount = _countof(GeneralGroups); TestCreatePSOFailure(PsoCI, ""SHADER_TYPE_RAY_CLOSEST_HIT is not a valid type for ray tracing general shader""); } TEST_F(PSOCreationFailureTest, InvalidShaderinTriangleHitGroup1) { if (!HasRayTracing()) GTEST_SKIP(); const RayTracingTriangleHitShaderGroup HitGroups[] = { {""CHit"", GetRayClosestHit(), nullptr}, {""CHit-AHit"", GetRayClosestHit(), GetRayAnyHit()}, {""Miss"", GetRayMiss()} // }; auto PsoCI{GetRayTracingPSOCreateInfo(""PSO Create Failure - invalid shader in triangle hit group - 1"")}; PsoCI.pTriangleHitShaders = HitGroups; PsoCI.TriangleHitShaderCount = _countof(HitGroups); TestCreatePSOFailure(PsoCI, ""SHADER_TYPE_RAY_MISS is not a valid type for ray tracing triangle closest hit""); } TEST_F(PSOCreationFailureTest, InvalidShaderinTriangleHitGroup2) { if (!HasRayTracing()) GTEST_SKIP(); const RayTracingTriangleHitShaderGroup HitGroups[] = { {""CHit"", GetRayClosestHit(), nullptr}, {""CHit-AHit"", GetRayClosestHit(), GetRayAnyHit()}, {""CHit-Miss"", GetRayClosestHit(), GetRayIntersection()} // }; auto PsoCI{GetRayTracingPSOCreateInfo(""PSO Create Failure - invalid shader in triangle hit group - 2"")}; PsoCI.pTriangleHitShaders = HitGroups; PsoCI.TriangleHitShaderCount = _countof(HitGroups); TestCreatePSOFailure(PsoCI, ""SHADER_TYPE_RAY_INTERSECTION is not a valid type for ray tracing triangle any hit""); } TEST_F(PSOCreationFailureTest, InvalidShaderinProceduralHitGroup1) { if (!HasRayTracing()) GTEST_SKIP(); const RayTracingProceduralHitShaderGroup HitGroups[] = { {""Int"", GetRayIntersection(), nullptr, nullptr}, {""Int-CHit"", GetRayIntersection(), GetRayClosestHit(), nullptr}, {""Int-CHit-AHit"", GetRayIntersection(), GetRayClosestHit(), GetRayAnyHit()}, {""Call"", GetCallable(), nullptr, nullptr} // }; auto PsoCI{GetRayTracingPSOCreateInfo(""PSO Create Failure - invalid shader in procedural hit group - 1"")}; PsoCI.pProceduralHitShaders = HitGroups; PsoCI.ProceduralHitShaderCount = _countof(HitGroups); TestCreatePSOFailure(PsoCI, ""SHADER_TYPE_CALLABLE is not a valid type for ray tracing procedural intersection""); } TEST_F(PSOCreationFailureTest, InvalidShaderinProceduralHitGroup2) { if (!HasRayTracing()) GTEST_SKIP(); const RayTracingProceduralHitShaderGroup HitGroups[] = { {""Int"", GetRayIntersection(), nullptr, nullptr}, {""Int-CHit"", GetRayIntersection(), GetRayClosestHit(), nullptr}, {""Int-CHit-AHit"", GetRayIntersection(), GetRayClosestHit(), GetRayAnyHit()}, {""Int-RG"", GetRayIntersection(), GetRayGen(), nullptr} // }; auto PsoCI{GetRayTracingPSOCreateInfo(""PSO Create Failure - invalid shader in procedural hit group - 2"")}; PsoCI.pProceduralHitShaders = HitGroups; PsoCI.ProceduralHitShaderCount = _countof(HitGroups); TestCreatePSOFailure(PsoCI, ""SHADER_TYPE_RAY_GEN is not a valid type for ray tracing procedural closest hit""); } TEST_F(PSOCreationFailureTest, InvalidShaderinProceduralHitGroup3) { if (!HasRayTracing()) GTEST_SKIP(); const RayTracingProceduralHitShaderGroup HitGroups[] = { {""Int"", GetRayIntersection(), nullptr, nullptr}, {""Int-CHit"", GetRayIntersection(), GetRayClosestHit(), nullptr}, {""Int-CHit-AHit"", GetRayIntersection(), GetRayClosestHit(), GetRayAnyHit()}, {""Int-CHit-CHit"", GetRayIntersection(), GetRayClosestHit(), GetRayClosestHit()} // }; auto PsoCI{GetRayTracingPSOCreateInfo(""PSO Create Failure - invalid shader in procedural hit group - 3"")}; PsoCI.pProceduralHitShaders = HitGroups; PsoCI.ProceduralHitShaderCount = _countof(HitGroups); TestCreatePSOFailure(PsoCI, ""SHADER_TYPE_RAY_CLOSEST_HIT is not a valid type for ray tracing procedural any hit""); } TEST_F(PSOCreationFailureTest, MissingResource) { PipelineResourceSignatureDesc PRSDesc; PRSDesc.Name = ""PSO Create Failure - missing resource""; PipelineResourceDesc Resources[]{ {SHADER_TYPE_PIXEL, ""g_AnotherTexture"", 1, SHADER_RESOURCE_TYPE_TEXTURE_SRV, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE}}; PRSDesc.UseCombinedTextureSamplers = true; PRSDesc.Resources = Resources; PRSDesc.NumResources = _countof(Resources); auto* pDevice = TestingEnvironment::GetInstance()->GetDevice(); RefCntAutoPtr pPRS; pDevice->CreatePipelineResourceSignature(PRSDesc, &pPRS); ASSERT_NE(pPRS, nullptr); IPipelineResourceSignature* ppSignatures[] = {pPRS}; auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - missing resource"")}; PsoCI.ppResourceSignatures = ppSignatures; PsoCI.ResourceSignaturesCount = _countof(ppSignatures); PsoCI.pPS = GetTexturePS(); std::string ExpectedErrorString = ""contains resource 'g_Texture' that is not present in any pipeline resource signature""; if (pDevice->GetDeviceCaps().Features.SeparablePrograms) ExpectedErrorString = std::string{""Shader 'TexturePS (PSOCreationFailureTest)' ""} + ExpectedErrorString; // In non-separable programs case, PSO name is used instead of the shader name TestCreatePSOFailure(PsoCI, ExpectedErrorString.c_str()); } TEST_F(PSOCreationFailureTest, InvalidResourceType) { PipelineResourceSignatureDesc PRSDesc; PRSDesc.Name = ""PSO Create Failure - Invalid Resource Type""; PipelineResourceDesc Resources[]{ {SHADER_TYPE_PIXEL, ""g_Texture"", 1, SHADER_RESOURCE_TYPE_BUFFER_SRV, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE}}; PRSDesc.UseCombinedTextureSamplers = true; PRSDesc.Resources = Resources; PRSDesc.NumResources = _countof(Resources); auto* pDevice = TestingEnvironment::GetInstance()->GetDevice(); RefCntAutoPtr pPRS; pDevice->CreatePipelineResourceSignature(PRSDesc, &pPRS); ASSERT_NE(pPRS, nullptr); IPipelineResourceSignature* ppSignatures[] = {pPRS}; auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid Resource Type"")}; PsoCI.ppResourceSignatures = ppSignatures; PsoCI.ResourceSignaturesCount = _countof(ppSignatures); PsoCI.pPS = GetTexturePS(); std::string ExpectedErrorString = ""contains resource with name 'g_Texture' and type 'texture SRV' that is not compatible with type 'buffer SRV'""; if (pDevice->GetDeviceCaps().Features.SeparablePrograms) ExpectedErrorString = std::string{""Shader 'TexturePS (PSOCreationFailureTest)' ""} + ExpectedErrorString; // In non-separable programs case, PSO name is used of the shader name TestCreatePSOFailure(PsoCI, ExpectedErrorString.c_str()); } TEST_F(PSOCreationFailureTest, InvalidArraySize) { static constexpr char PSSource[] = R""( Texture2D g_Texture[3]; float4 main() : SV_Target { return g_Texture[0].Load(int3(0,0,0)) + g_Texture[1].Load(int3(0,0,0)) + g_Texture[2].Load(int3(0,0,0)); } )""; auto* const pEnv = TestingEnvironment::GetInstance(); auto* const pDevice = pEnv->GetDevice(); ShaderCreateInfo ShaderCI; ShaderCI.Source = PSSource; ShaderCI.Desc.ShaderType = SHADER_TYPE_PIXEL; ShaderCI.Desc.Name = ""Invalid Array Size (PSOCreationFailureTest)""; ShaderCI.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL; ShaderCI.ShaderCompiler = pEnv->GetDefaultCompiler(ShaderCI.SourceLanguage); ShaderCI.UseCombinedTextureSamplers = true; RefCntAutoPtr pPS; pDevice->CreateShader(ShaderCI, &pPS); PipelineResourceSignatureDesc PRSDesc; PRSDesc.Name = ""PSO Create Failure - Invalid Array Size""; PipelineResourceDesc Resources[]{ {SHADER_TYPE_PIXEL, ""g_Texture"", 2, SHADER_RESOURCE_TYPE_TEXTURE_SRV, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE}}; PRSDesc.UseCombinedTextureSamplers = true; PRSDesc.Resources = Resources; PRSDesc.NumResources = _countof(Resources); RefCntAutoPtr pPRS; pDevice->CreatePipelineResourceSignature(PRSDesc, &pPRS); ASSERT_NE(pPRS, nullptr); IPipelineResourceSignature* ppSignatures[] = {pPRS}; auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid Array Size"")}; PsoCI.ppResourceSignatures = ppSignatures; PsoCI.ResourceSignaturesCount = _countof(ppSignatures); PsoCI.pPS = pPS; std::string ExpectedErrorString = ""contains resource 'g_Texture' whose array size (3) is greater than the array size (2)""; if (pDevice->GetDeviceCaps().Features.SeparablePrograms) ExpectedErrorString = std::string{""Shader 'Invalid Array Size (PSOCreationFailureTest)' ""} + ExpectedErrorString; // In non-separable programs case, PSO name is used TestCreatePSOFailure(PsoCI, ExpectedErrorString.c_str()); } TEST_F(PSOCreationFailureTest, InvalidRunTimeArray) { auto* const pEnv = TestingEnvironment::GetInstance(); auto* const pDevice = pEnv->GetDevice(); const auto& deviceCaps = pDevice->GetDeviceCaps(); if (!pDevice->GetDeviceCaps().Features.ShaderResourceRuntimeArray) { GTEST_SKIP(); } static constexpr char PSSource_HLSL[] = R""( Texture2D g_Texture[]; cbuffer ConstBuffer { uint Index; } float4 main() : SV_Target { return g_Texture[Index].Load(int3(0,0,0)); } )""; static constexpr char PSSource_GLSL[] = R""( #version 460 core #extension GL_EXT_nonuniform_qualifier : require #extension GL_EXT_samplerless_texture_functions : require uniform texture2D g_Texture[]; layout(std140) uniform ConstBuffer { uint Index; }; layout(location=0) out vec4 out_Color; void main() { out_Color = texelFetch(g_Texture[nonuniformEXT(Index)], ivec2(0,0), 0); } )""; ShaderCreateInfo ShaderCI; ShaderCI.Desc.ShaderType = SHADER_TYPE_PIXEL; ShaderCI.Desc.Name = ""Invalid Run-Time Array (PSOCreationFailureTest)""; ShaderCI.ShaderCompiler = pEnv->GetDefaultCompiler(ShaderCI.SourceLanguage); if (deviceCaps.IsD3DDevice()) { ShaderCI.Source = PSSource_HLSL; ShaderCI.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL; } else { ShaderCI.Source = PSSource_GLSL; ShaderCI.SourceLanguage = SHADER_SOURCE_LANGUAGE_GLSL_VERBATIM; } ShaderCI.UseCombinedTextureSamplers = true; ShaderCI.CompileFlags = SHADER_COMPILE_FLAG_ENABLE_UNBOUNDED_ARRAYS; RefCntAutoPtr pPS; pDevice->CreateShader(ShaderCI, &pPS); PipelineResourceSignatureDesc PRSDesc; PRSDesc.Name = ""PSO Create Failure - Invalid Run-Time Array""; PipelineResourceDesc Resources[]{ {SHADER_TYPE_PIXEL, ""ConstBuffer"", 1, SHADER_RESOURCE_TYPE_CONSTANT_BUFFER, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE}, {SHADER_TYPE_PIXEL, ""g_Texture"", 2, SHADER_RESOURCE_TYPE_TEXTURE_SRV, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE}}; PRSDesc.UseCombinedTextureSamplers = true; PRSDesc.Resources = Resources; PRSDesc.NumResources = _countof(Resources); RefCntAutoPtr pPRS; pDevice->CreatePipelineResourceSignature(PRSDesc, &pPRS); ASSERT_NE(pPRS, nullptr); IPipelineResourceSignature* ppSignatures[] = {pPRS}; auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Invalid Run-Time Array"")}; PsoCI.ppResourceSignatures = ppSignatures; PsoCI.ResourceSignaturesCount = _countof(ppSignatures); PsoCI.pPS = pPS; TestCreatePSOFailure(PsoCI, ""Shader 'Invalid Run-Time Array (PSOCreationFailureTest)' contains resource 'g_Texture' that is a runtime-sized array, "" ""but in the resource signature 'PSO Create Failure - Invalid Run-Time Array' the resource is defined without the PIPELINE_RESOURCE_FLAG_RUNTIME_ARRAY flag.""); } TEST_F(PSOCreationFailureTest, NonSeparablePrograms_SeparateResources) { if (TestingEnvironment::GetInstance()->GetDevice()->GetDeviceCaps().Features.SeparablePrograms) { GTEST_SKIP(); } auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Non Separable Programs - Separate Resources"")}; ShaderResourceVariableDesc Variables[] // { ShaderResourceVariableDesc{SHADER_TYPE_VERTEX, ""g_Texture"", SHADER_RESOURCE_VARIABLE_TYPE_STATIC}, ShaderResourceVariableDesc{SHADER_TYPE_PIXEL, ""g_Texture"", SHADER_RESOURCE_VARIABLE_TYPE_STATIC} // }; PsoCI.PSODesc.ResourceLayout.Variables = Variables; PsoCI.PSODesc.ResourceLayout.NumVariables = _countof(Variables); TestCreatePSOFailure(PsoCI, ""there are separate resources with the name 'g_Texture' in shader stages SHADER_TYPE_PIXEL and SHADER_TYPE_VERTEX""); } TEST_F(PSOCreationFailureTest, NonSeparablePrograms_SeparateImmutableSamplers) { if (TestingEnvironment::GetInstance()->GetDevice()->GetDeviceCaps().Features.SeparablePrograms) { GTEST_SKIP(); } auto PsoCI{GetGraphicsPSOCreateInfo(""PSO Create Failure - Non Separable Programs - Separate Immutable Samplers"")}; ImmutableSamplerDesc ImtblSamplers[] // { ImmutableSamplerDesc{SHADER_TYPE_VERTEX, ""g_Texture_sampler"", SamplerDesc{}}, ImmutableSamplerDesc{SHADER_TYPE_PIXEL, ""g_Texture_sampler"", SamplerDesc{}} // }; PsoCI.PSODesc.ResourceLayout.ImmutableSamplers = ImtblSamplers; PsoCI.PSODesc.ResourceLayout.NumImmutableSamplers = _countof(ImtblSamplers); TestCreatePSOFailure(PsoCI, ""there are separate immutable samplers with the name 'g_Texture_sampler' in shader stages SHADER_TYPE_PIXEL and SHADER_TYPE_VERTEX""); } } // namespace ",16370,True,3264.0526637249454,median "[[box-component]] = Box Component //THIS FILE IS COPIED: EDIT THE SOURCE FILE: :page-source: components/camel-box/camel-box-component/src/main/docs/box-component.adoc :docTitle: Box :artifactId: camel-box :description: Upload, download and manage files, folders, groups, collaborations, etc. on box.com. :since: 2.14 :supportLevel: Stable :component-header: Both producer and consumer are supported include::{cq-version}@camel-quarkus:ROOT:partial$reference/components/box.adoc[opts=optional] *Since Camel {since}* *{component-header}* The Box component provides access to all of the Box.com APIs accessible using https://github.com/box/box-java-sdk/[https://github.com/box/box-java-sdk]. It allows producing messages to upload and download files, create, edit, and manage folders, etc. It also supports APIs that allow polling for updates to user accounts and even changes to enterprise accounts, etc. Box.com requires the use of OAuth2.0 for all client application authentication. In order to use camel-box with your account, you'll need to create a new application within Box.com at https://developer.box.com/[https://developer.box.com]. The Box application's client id and secret will allow access to Box APIs which require a current user. A user access token is generated and managed by the API for an end user. Maven users will need to add the following dependency to their pom.xml for this component: [source,xml] ---- org.apache.camel camel-box ${camel-version} ---- == Connection Authentication Types The Box component supports three different types of authenticated connections. === Standard Authentication *Standard Authentication* uses the *OAuth 2.0 three-legged authentication process* to authenticate its connections with Box.com. This type of authentication enables Box *managed users* and *external users* to access, edit, and save their Box content through the Box component. === App Enterprise Authentication *App Enterprise Authentication* uses the *OAuth 2.0 with JSON Web Tokens (JWT)* to authenticate its connections as a *Service Account* for a *Box Application*. This type of authentication enables a service account to access, edit, and save the Box content of its *Box Application* through the Box component. === App User Authentication *App User Authentication* uses the *OAuth 2.0 with JSON Web Tokens (JWT)* to authenticate its connections as an *App User* for a *Box Application*. This type of authentication enables app users to access, edit, and save their Box content in its *Box Application* through the Box component. == Box Options // component options: START The Box component supports 19 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *clientId* (common) | Box application client ID | | String | *configuration* (common) | To use the shared configuration | | BoxConfiguration | *enterpriseId* (common) | The enterprise ID to use for an App Enterprise. | | String | *userId* (common) | The user ID to use for an App User. | | String | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *autowiredEnabled* (advanced) | Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | *httpParams* (advanced) | Custom HTTP params for settings like proxy host | | Map | *authenticationType* (authentication) | The type of authentication for connection. Types of Authentication: STANDARD_AUTHENTICATION - OAuth 2.0 (3-legged) SERVER_AUTHENTICATION - OAuth 2.0 with JSON Web Tokens | APP_USER_AUTHENTICATION | String | *accessTokenCache* (security) | Custom Access Token Cache for storing and retrieving access tokens. | | IAccessTokenCache | *clientSecret* (security) | Box application client secret | | String | *encryptionAlgorithm* (security) | The type of encryption algorithm for JWT. Supported Algorithms: RSA_SHA_256 RSA_SHA_384 RSA_SHA_512. There are 3 enums and the value can be one of: RSA_SHA_256, RSA_SHA_384, RSA_SHA_512 | RSA_SHA_256 | EncryptionAlgorithm | *maxCacheEntries* (security) | The maximum number of access tokens in cache. | 100 | int | *privateKeyFile* (security) | The private key for generating the JWT signature. | | String | *privateKeyPassword* (security) | The password for the private key. | | String | *publicKeyId* (security) | The ID for public key for validating the JWT signature. | | String | *sslContextParameters* (security) | To configure security using SSLContextParameters. | | SSLContextParameters | *userName* (security) | Box user name, MUST be provided | | String | *userPassword* (security) | Box user password, MUST be provided if authSecureStorage is not set, or returns null on first call | | String |=== // component options: END // endpoint options: START The Box endpoint is configured using URI syntax: ---- box:apiName/methodName ---- with the following path and query parameters: === Path Parameters (2 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *apiName* | *Required* What kind of operation to perform. There are 10 enums and the value can be one of: COLLABORATIONS, COMMENTS, EVENT_LOGS, FILES, FOLDERS, GROUPS, EVENTS, SEARCH, TASKS, USERS | | BoxApiName | *methodName* | *Required* What sub operation to use for the selected operation | | String |=== === Query Parameters (19 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *clientId* (common) | Box application client ID | | String | *enterpriseId* (common) | The enterprise ID to use for an App Enterprise. | | String | *inBody* (common) | Sets the name of a parameter to be passed in the exchange In Body | | String | *userId* (common) | The user ID to use for an App User. | | String | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *httpParams* (advanced) | Custom HTTP params for settings like proxy host | | Map | *authenticationType* (authentication) | The type of authentication for connection. Types of Authentication: STANDARD_AUTHENTICATION - OAuth 2.0 (3-legged) SERVER_AUTHENTICATION - OAuth 2.0 with JSON Web Tokens | APP_USER_AUTHENTICATION | String | *accessTokenCache* (security) | Custom Access Token Cache for storing and retrieving access tokens. | | IAccessTokenCache | *clientSecret* (security) | Box application client secret | | String | *encryptionAlgorithm* (security) | The type of encryption algorithm for JWT. Supported Algorithms: RSA_SHA_256 RSA_SHA_384 RSA_SHA_512. There are 3 enums and the value can be one of: RSA_SHA_256, RSA_SHA_384, RSA_SHA_512 | RSA_SHA_256 | EncryptionAlgorithm | *maxCacheEntries* (security) | The maximum number of access tokens in cache. | 100 | int | *privateKeyFile* (security) | The private key for generating the JWT signature. | | String | *privateKeyPassword* (security) | The password for the private key. | | String | *publicKeyId* (security) | The ID for public key for validating the JWT signature. | | String | *sslContextParameters* (security) | To configure security using SSLContextParameters. | | SSLContextParameters | *userName* (security) | Box user name, MUST be provided | | String | *userPassword* (security) | Box user password, MUST be provided if authSecureStorage is not set, or returns null on first call | | String |=== === API Parameters (10 APIs): The Box endpoint is an API based component and has additional parameters based on which API name and API method is used. The API name and API method is located in the endpoint URI as the apiName/methodName path parameters: ---- box:apiName/methodName ---- There are 10 API names as listed in the table below: [width=""100%"",cols=""2,2,6"",options=""header""] |=== | API Name | Type | Description | *collaborations* | Producer | Provides operations to manage Box collaborations | *comments* | Producer | Provides operations to manage Box comments | *event-logs* | Producer | Provides operations to read Box enterprise (admin) event logs | *events* | Consumer | Provides operations to manage Box events | *files* | Producer | Provides operations to manage Box files | *folders* | Producer | Provides operations to manage Box folders | *groups* | Producer | Provides operations to manage Box groups | *search* | Producer | Provides operations to manage Box searches | *tasks* | Producer | Provides operations to manage Box tasks | *users* | Producer | Provides operations to manage Box users |=== Each API is documented in the following sections to come. ==== API: collaborations *Only producer is supported* The collaborations API has 6 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxCollaboration addFolderCollaboration(String folderId, com.box.sdk.BoxCollaborator collaborator, com.box.sdk.BoxCollaboration.Role role); com.box.sdk.BoxCollaboration addFolderCollaborationByEmail(String folderId, String email, com.box.sdk.BoxCollaboration.Role role); void deleteCollaboration(String collaborationId); com.box.sdk.BoxCollaboration.Info getCollaborationInfo(String collaborationId); java.util.Collection getFolderCollaborations(String folderId); com.box.sdk.BoxCollaboration updateCollaborationInfo(String collaborationId, com.box.sdk.BoxCollaboration.Info info); ---- The collaborations API is defined in the syntax as follows: ---- box:collaborations/methodName?[parameters] ---- The 6 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addFolderCollaboration* | add | Add a collaboration to this folder | *addFolderCollaborationByEmail* | addByEmail | Add a collaboration to this folder | *deleteCollaboration* | delete | Delete collaboration | *getCollaborationInfo* | info | Get collaboration information | *getFolderCollaborations* | collaborations | Get information about all of the collaborations for folder | *updateCollaborationInfo* | updateInfo | Update collaboration information |=== The collaborations API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addFolderCollaboration | *collaborator* | The collaborator to add | BoxCollaborator | addFolderCollaboration | *folderId* | The id of folder to add collaboration to | String | addFolderCollaboration | *role* | The role of the collaborator | Role | addFolderCollaborationByEmail | *email* | The email address of the collaborator to add | String | addFolderCollaborationByEmail | *folderId* | The id of folder to add collaboration to | String | addFolderCollaborationByEmail | *role* | The role of the collaborator | Role | deleteCollaboration | *collaborationId* | The id of comment to change | String | getCollaborationInfo | *collaborationId* | The id of collaboration | String | getFolderCollaborations | *folderId* | The id of folder to get collaborations information on | String | updateCollaborationInfo | *collaborationId* | The id of collaboration | String | updateCollaborationInfo | *info* | Collaboration information to update | Info |=== In addition to the parameters above, the collaborations API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: comments *Only producer is supported* The comments API has 6 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxFile addFileComment(String fileId, String message); com.box.sdk.BoxComment changeCommentMessage(String commentId, String message); void deleteComment(String commentId); com.box.sdk.BoxComment.Info getCommentInfo(String commentId); java.util.List getFileComments(String fileId); com.box.sdk.BoxComment replyToComment(String commentId, String message); ---- The comments API is defined in the syntax as follows: ---- box:comments/methodName?[parameters] ---- The 6 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addFileComment* | add | Add comment to file | *changeCommentMessage* | updateMessage | Change comment message | *deleteComment* | delete | Delete comment | *getCommentInfo* | info | Get comment information | *getFileComments* | comments | Get a list of any comments on this file | *replyToComment* | reply | Reply to a comment |=== The comments API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addFileComment | *fileId* | The id of file | String | addFileComment | *message* | The comment's message | String | changeCommentMessage | *commentId* | The id of comment to change | String | changeCommentMessage | *message* | The new message for the comment | String | deleteComment | *commentId* | The id of comment to delete | String | getCommentInfo | *commentId* | The id of comment | String | getFileComments | *fileId* | The id of file | String | replyToComment | *commentId* | The id of comment to reply to | String | replyToComment | *message* | The message for the reply | String |=== In addition to the parameters above, the comments API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: event-logs *Only producer is supported* The event-logs API has 1 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- java.util.List getEnterpriseEvents(String position, java.util.Date after, java.util.Date before, com.box.sdk.BoxEvent.Type[] types); ---- The event-logs API is defined in the syntax as follows: ---- box:event-logs/methodName?[parameters] ---- The 1 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *getEnterpriseEvents* | events | Create an event stream with optional starting initial position and add listener that will be notified when an event is received |=== The event-logs API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | getEnterpriseEvents | *after* | The lower bound on the timestamp of the events returned | Date | getEnterpriseEvents | *before* | The upper bound on the timestamp of the events returned | Date | getEnterpriseEvents | *position* | *Optional* The starting position of the event stream. May be null in which case all events within bounds returned. | String | getEnterpriseEvents | *types* | *Optional* An optional list of event types to filter by | Type[] |=== In addition to the parameters above, the event-logs API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: events *Only consumer is supported* The events API has 1 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- void listen(com.box.sdk.EventListener listener, Long startingPosition); ---- The events API is defined in the syntax as follows: ---- box:events/methodName?[parameters] ---- The 1 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *listen* | | Create an event stream with optional starting initial position and add listener that will be notified when an event is received |=== The events API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | listen | *startingPosition* | *Optional* The starting position of the event stream | Long |=== In addition to the parameters above, the events API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: files *Only producer is supported* The files API has 22 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- void checkUpload(String fileName, String parentFolderId, Long size); com.box.sdk.BoxFile copyFile(String fileId, String destinationFolderId, String newName); com.box.sdk.Metadata createFileMetadata(String fileId, com.box.sdk.Metadata metadata, String typeName); com.box.sdk.BoxSharedLink createFileSharedLink(String fileId, com.box.sdk.BoxSharedLink.Access access, java.util.Date unshareDate, com.box.sdk.BoxSharedLink.Permissions permissions); void deleteFile(String fileId); void deleteFileMetadata(String fileId); void deleteFileVersion(String fileId, Integer version); java.io.OutputStream downloadFile(String fileId, java.io.OutputStream output, Long rangeStart, Long rangeEnd, com.box.sdk.ProgressListener listener); java.io.OutputStream downloadPreviousFileVersion(String fileId, Integer version, java.io.OutputStream output, com.box.sdk.ProgressListener listener); java.net.URL getDownloadURL(String fileId); com.box.sdk.BoxFile.Info getFileInfo(String fileId, String[] fields); com.box.sdk.Metadata getFileMetadata(String fileId, String typeName); java.net.URL getFilePreviewLink(String fileId); byte[] getFileThumbnail(String fileId, com.box.sdk.BoxFile.ThumbnailFileType fileType, Integer minWidth, Integer minHeight, Integer maxWidth, Integer maxHeight); java.util.Collection getFileVersions(String fileId); com.box.sdk.BoxFile moveFile(String fileId, String destinationFolderId, String newName); com.box.sdk.BoxFileVersion promoteFileVersion(String fileId, Integer version); com.box.sdk.BoxFile renameFile(String fileId, String newFileName); com.box.sdk.BoxFile updateFileInfo(String fileId, com.box.sdk.BoxFile.Info info); com.box.sdk.Metadata updateFileMetadata(String fileId, com.box.sdk.Metadata metadata); com.box.sdk.BoxFile uploadFile(String parentFolderId, java.io.InputStream content, String fileName, java.util.Date created, java.util.Date modified, Long size, Boolean check, com.box.sdk.ProgressListener listener); com.box.sdk.BoxFile uploadNewFileVersion(String fileId, java.io.InputStream fileContent, java.util.Date modified, Long fileSize, com.box.sdk.ProgressListener listener); ---- The files API is defined in the syntax as follows: ---- box:files/methodName?[parameters] ---- The 22 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *checkUpload* | canUpload | Does a pre-verification before upload, to check if the filename already exists or if there is permission to upload | *copyFile* | copy | Copy file to destination folder while optionally giving it a new name | *createFileMetadata* | createMetadata | Create metadata for file in either the global properties template or the specified template type | *createFileSharedLink* | link | Create a shared link to file | *deleteFile* | delete | Delete the file | *deleteFileMetadata* | deleteMetadata | Delete the file properties metadata | *deleteFileVersion* | deleteVersion | Delete a file version | *downloadFile* | download | Download a file | *downloadPreviousFileVersion* | downloadVersion | Download a previous version of file | *getDownloadURL* | url | Get an expiring URL for downloading a file directly from Box | *getFileInfo* | info | Get file information | *getFileMetadata* | metadata | Gets the file properties metadata | *getFilePreviewLink* | | Get an expiring URL for creating an embedded preview session | *getFileThumbnail* | thumbnail | Retrieves a thumbnail, or smaller image representation, of this file | *getFileVersions* | versions | Get any previous versions of file | *moveFile* | move | Move file to destination folder while optionally giving it a new name | *promoteFileVersion* | promoteVersion | Promote a previous version of file | *renameFile* | rename | Rename file giving it the name newName | *updateFileInfo* | updateInfo | Update file information | *updateFileMetadata* | updateMetadata | Update the file properties metadata | *uploadFile* | upload | Upload a new file to parent folder | *uploadNewFileVersion* | uploadVersion | Upload a new version of file |=== The files API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | checkUpload | *fileName* | The name to give the uploaded file | String | checkUpload | *parentFolderId* | The id of parent folder | String | checkUpload | *size* | *Optional* The size of the file's content used for monitoring the upload's progress | Long | copyFile | *destinationFolderId* | The id of the destination folder | String | copyFile | *fileId* | The id of file to copy | String | copyFile | *newName* | *Optional* The new name for copied file; if newName is null, the copied file has same name as the original. | String | createFileMetadata | *fileId* | The id of the file to create metadata for | String | createFileMetadata | *metadata* | The new metadata values | Metadata | createFileMetadata | *typeName* | *Optional* The metadata template type name; if null the global properties template type is used. | String | createFileSharedLink | *access* | The access level of the shared link | Access | createFileSharedLink | *fileId* | The id of the file to create shared link on | String | createFileSharedLink | *permissions* | *Optional* The permissions of the created link; if permissions is null then the created shared link is create with default permissions. | Permissions | createFileSharedLink | *unshareDate* | *Optional* The date and time at which time the created shared link will expire; if unsharedDate is null then a non-expiring link is created. | Date | deleteFile | *fileId* | The id of file to delete | String | deleteFileMetadata | *fileId* | The id of file to delete | String | deleteFileVersion | *fileId* | The id of file with version to delete | String | deleteFileVersion | *version* | The version of file to delete; initial version of file has value of 0, second version of file is 1 and so on. | Integer | downloadFile | *fileId* | The id of file | String | downloadFile | *listener* | *Optional* A listener for monitoring the download's progress; if null the download's progress will not be monitored. | ProgressListener | downloadFile | *output* | The stream to which the file contents will be written | OutputStream | downloadFile | *rangeEnd* | *Optional* The byte offset in file at which to stop the download; if null the entire contents of file will be downloaded. | Long | downloadFile | *rangeStart* | *Optional* The byte offset in file at which to start the download; if null the entire contents of file will be downloaded. | Long | downloadPreviousFileVersion | *fileId* | The id of file | String | downloadPreviousFileVersion | *listener* | *Optional* A listener for monitoring the download's progress; if null the download's progress will not be monitored. | ProgressListener | downloadPreviousFileVersion | *output* | The stream to which the version contents will be written | OutputStream | downloadPreviousFileVersion | *version* | The version of file to download; initial version of file has value of 0, second version of file is 1 and so on. | Integer | getDownloadURL | *fileId* | The id of file | String | getFileInfo | *fields* | *Optional* The information fields to retrieve; if null all information fields are retrieved. | String[] | getFileInfo | *fileId* | The id of file | String | getFileMetadata | *fileId* | The id of the file to retrieve metadata for | String | getFileMetadata | *typeName* | *Optional* The metadata template type name; if null the global properties template type is used. | String | getFilePreviewLink | *fileId* | The id of the file to get preview link on | String | getFileThumbnail | *fileId* | The id of the file to get thumbnail | String | getFileThumbnail | *fileType* | Either PNG of JPG | ThumbnailFileType | getFileThumbnail | *maxHeight* | Maximum height | Integer | getFileThumbnail | *maxWidth* | Maximum width | Integer | getFileThumbnail | *minHeight* | Minimum height | Integer | getFileThumbnail | *minWidth* | Minimum width | Integer | getFileVersions | *fileId* | The id of file | String | moveFile | *destinationFolderId* | The id of the destination folder | String | moveFile | *fileId* | The id of file to move | String | moveFile | *newName* | *Optional* The new name of moved file; if newName is null, the moved file has same name as the original. | String | promoteFileVersion | *fileId* | The id of file | String | promoteFileVersion | *version* | The version of file to promote; initial version of file has value of 0, second version of file is 1 and so on. | Integer | renameFile | *fileId* | The id of file to rename | String | renameFile | *newFileName* | The new name of file | String | updateFileInfo | *fileId* | The id of file to update | String | updateFileInfo | *info* | The updated information | Info | updateFileMetadata | *fileId* | The id of file to delete | String | updateFileMetadata | *metadata* | The new metadata values | Metadata | uploadFile | *check* | *Optional* If the file name is already used, call the uploadNewVersion instead. | Boolean | uploadFile | *content* | A stream containing contents of the file to upload | InputStream | uploadFile | *created* | *Optional* The content created date that will be given to the uploaded file | Date | uploadFile | *fileName* | The name to give the uploaded file | String | uploadFile | *listener* | *Optional* A listener for monitoring the upload's progress | ProgressListener | uploadFile | *modified* | *Optional* The content modified date that will be given to the uploaded file | Date | uploadFile | *parentFolderId* | The id of parent folder | String | uploadFile | *size* | *Optional* The size of the file's content used for monitoring the upload's progress | Long | uploadNewFileVersion | *fileContent* | A stream containing contents of the file to upload | InputStream | uploadNewFileVersion | *fileId* | The id of file | String | uploadNewFileVersion | *fileSize* | *Optional* The size of the file's content used for monitoring the upload's progress | Long | uploadNewFileVersion | *listener* | *Optional* A listener for monitoring the upload's progress | ProgressListener | uploadNewFileVersion | *modified* | *Optional* The content modified date that will be given to the uploaded file | Date |=== In addition to the parameters above, the files API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: folders *Only producer is supported* The folders API has 10 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxFolder copyFolder(String folderId, String destinationFolderId, String newName); com.box.sdk.BoxFolder createFolder(String parentFolderId, String folderName); com.box.sdk.BoxFolder createFolder(String parentFolderId, String[] path); com.box.sdk.BoxSharedLink createFolderSharedLink(String folderId, com.box.sdk.BoxSharedLink.Access access, java.util.Date unshareDate, com.box.sdk.BoxSharedLink.Permissions permissions); void deleteFolder(String folderId); com.box.sdk.BoxFolder getFolder(String[] path); com.box.sdk.BoxFolder.Info getFolderInfo(String folderId, String[] fields); java.util.Collection getFolderItems(String folderId, Long offset, Long limit, String[] fields); com.box.sdk.BoxFolder moveFolder(String folderId, String destinationFolderId, String newName); com.box.sdk.BoxFolder renameFolder(String folderId, String newFolderName); com.box.sdk.BoxFolder updateFolderInfo(String folderId, com.box.sdk.BoxFolder.Info info); ---- The folders API is defined in the syntax as follows: ---- box:folders/methodName?[parameters] ---- The 10 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *copyFolder* | copy | Copy folder to destination folder while optionally giving it a new name | *createFolder* | create | Create a folder specified by path from parent folder with given parentFolderId, creating intermediate directories as required | *createFolderSharedLink* | link | Create a shared link to folder | *deleteFolder* | delete | Delete folder | *getFolder* | folder | Return the Box folder referenced by path | *getFolderInfo* | info | Get folder information | *getFolderItems* | items | Returns a specific range of child items in folder and specifies which fields of each item to retrieve | *moveFolder* | move | Move folder to destination folder while optionally giving it a new name | *renameFolder* | rename | Rename folder giving it the name newName | *updateFolderInfo* | updateInfo | Update folder information |=== The folders API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | copyFolder | *destinationFolderId* | The id of the destination folder | String | copyFolder | *folderId* | The id of folder to copy | String | copyFolder | *newName* | *Optional* The new name for copied folder; if newName is null, the copied folder has same name as the original. | String | createFolder | *folderName* | The name of created folder | String | createFolder | *parentFolderId* | The id of parent folder | String | createFolder | *path* | Sequence of Box folder names from parent folder to returned folder | String[] | createFolderSharedLink | *access* | The access level of the shared link | Access | createFolderSharedLink | *folderId* | The id of folder to create shared link on | String | createFolderSharedLink | *permissions* | The permissions of the created link; if permissions is null then the created shared link is create with default permissions. | Permissions | createFolderSharedLink | *unshareDate* | The date and time at which time the created shared link will expire; if unsharedDate is null then a non-expiring link is created. | Date | deleteFolder | *folderId* | The id of folder to delete | String | getFolder | *path* | Sequence of Box folder names from root folder to returned folder | String[] | getFolderInfo | *fields* | *Optional* The information fields to retrieve; if null all information fields are retrieved. | String[] | getFolderInfo | *folderId* | The id of folder | String | getFolderItems | *fields* | *Optional* The item fields to retrieve for each child item; if null all item fields are retrieved. | String[] | getFolderItems | *folderId* | The id of folder | String | getFolderItems | *limit* | *Optional* The maximum number of children to retrieve after the offset; if null all child items are retrieved. | Long | getFolderItems | *offset* | *Optional* The index of first child item to retrieve; if null all child items are retrieved. | Long | moveFolder | *destinationFolderId* | The id of the destination folder | String | moveFolder | *folderId* | The id of folder to move | String | moveFolder | *newName* | *Optional* The new name of moved folder; if newName is null, the moved folder has same name as the original. | String | renameFolder | *folderId* | The id of folder to rename | String | renameFolder | *newFolderName* | The new name of folder | String | updateFolderInfo | *folderId* | The id of folder to update | String | updateFolderInfo | *info* | The updated information | Info |=== In addition to the parameters above, the folders API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: groups *Only producer is supported* The groups API has 9 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxGroupMembership addGroupMembership(String groupId, String userId, com.box.sdk.BoxGroupMembership.Role role); com.box.sdk.BoxGroup createGroup(String name, String provenance, String externalSyncIdentifier, String description, String invitabilityLevel, String memberViewabilityLevel); void deleteGroup(String groupId); void deleteGroupMembership(String groupMembershipId); com.box.sdk.BoxGroup.Info getGroupInfo(String groupId); com.box.sdk.BoxGroupMembership.Info getGroupMembershipInfo(String groupMembershipId); java.util.Collection getGroupMemberships(String groupId); com.box.sdk.BoxGroup updateGroupInfo(String groupId, com.box.sdk.BoxGroup.Info groupInfo); com.box.sdk.BoxGroupMembership updateGroupMembershipInfo(String groupMembershipId, com.box.sdk.BoxGroupMembership.Info info); ---- The groups API is defined in the syntax as follows: ---- box:groups/methodName?[parameters] ---- The 9 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addGroupMembership* | addMembership | Add a member to group with the specified role | *createGroup* | create | Create a new group with a specified name and optional additional parameters | *deleteGroup* | delete | Delete group | *deleteGroupMembership* | deleteMembership | Delete group membership | *getGroupInfo* | info | Get group information | *getGroupMembershipInfo* | membershipInfo | Get group membership information | *getGroupMemberships* | memberships | Get information about all of the group memberships for this group | *updateGroupInfo* | | Update group information | *updateGroupMembershipInfo* | updateMembershipInfo | Update group membership information |=== The groups API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addGroupMembership | *groupId* | The id of group | String | addGroupMembership | *role* | *Optional* The role of the user in this group. Can be null to assign the default role. | Role | addGroupMembership | *userId* | The id of user to be added to group | String | createGroup | *description* | *Optional* The description of the new group | String | createGroup | *externalSyncIdentifier* | *Optional* The external_sync_identifier of the new group | String | createGroup | *invitabilityLevel* | *Optional* The invitibility_level of the new group | String | createGroup | *memberViewabilityLevel* | *Optional* The member_viewability_level of the new group | String | createGroup | *name* | The name of the new group | String | createGroup | *provenance* | *Optional* The provenance of the new group | String | deleteGroup | *groupId* | The id of group to delete | String | deleteGroupMembership | *groupMembershipId* | The id of group membership to delete | String | getGroupInfo | *groupId* | The id of group | String | getGroupMembershipInfo | *groupMembershipId* | The id of group membership | String | getGroupMemberships | *groupId* | The id of group | String | updateGroupInfo | *groupId* | The id of group to update | String | updateGroupInfo | *groupInfo* | The updated information | Info | updateGroupMembershipInfo | *groupMembershipId* | The id of group membership to update | String | updateGroupMembershipInfo | *info* | The updated information | Info |=== In addition to the parameters above, the groups API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: search *Only producer is supported* The search API has 1 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- java.util.Collection searchFolder(String folderId, String query); ---- The search API is defined in the syntax as follows: ---- box:search/methodName?[parameters] ---- The 1 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *searchFolder* | search | Search folder and all descendant folders using the given query |=== The search API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | searchFolder | *folderId* | The id of folder searched | String | searchFolder | *query* | The search query | String |=== In addition to the parameters above, the search API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: tasks *Only producer is supported* The tasks API has 9 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxTask addAssignmentToTask(String taskId, com.box.sdk.BoxUser assignTo); com.box.sdk.BoxTask addFileTask(String fileId, com.box.sdk.BoxTask.Action action, java.util.Date dueAt, String message); void deleteTask(String taskId); void deleteTaskAssignment(String taskAssignmentId); java.util.List getFileTasks(String fileId); com.box.sdk.BoxTaskAssignment.Info getTaskAssignmentInfo(String taskAssignmentId); java.util.List getTaskAssignments(String taskId); com.box.sdk.BoxTask.Info getTaskInfo(String taskId); com.box.sdk.BoxTask updateTaskInfo(String taskId, com.box.sdk.BoxTask.Info info); ---- The tasks API is defined in the syntax as follows: ---- box:tasks/methodName?[parameters] ---- The 9 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addAssignmentToTask* | addAssignment | Add assignment for task | *addFileTask* | add | Add task to file | *deleteTask* | delete | Delete task | *deleteTaskAssignment* | deleteAssignment | Delete task assignment | *getFileTasks* | tasks | Get a list of any tasks on file | *getTaskAssignmentInfo* | assignmentInfo | Get task assignment information | *getTaskAssignments* | assignments | Get a list of any assignments for task | *getTaskInfo* | info | Get task information | *updateTaskInfo* | updateInfo | Update task information |=== The tasks API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addAssignmentToTask | *assignTo* | The user to assign to task | BoxUser | addAssignmentToTask | *taskId* | The id of task to add assignment for | String | addFileTask | *action* | The action the task assignee will be prompted to do | Action | addFileTask | *dueAt* | The day at which this task is due | Date | addFileTask | *fileId* | The id of file to add task to | String | addFileTask | *message* | *Optional* An optional message to include with the task | String | deleteTask | *taskId* | The id of task to delete | String | deleteTaskAssignment | *taskAssignmentId* | The id of task assignment to delete | String | getFileTasks | *fileId* | The id of file | String | getTaskAssignmentInfo | *taskAssignmentId* | The id of task assignment | String | getTaskAssignments | *taskId* | The id of task | String | getTaskInfo | *taskId* | The id of task | String | updateTaskInfo | *info* | The updated information | Info | updateTaskInfo | *taskId* | The id of task | String |=== In addition to the parameters above, the tasks API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: users *Only producer is supported* The users API has 10 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.EmailAlias addUserEmailAlias(String userId, String email); com.box.sdk.BoxUser createAppUser(String name, com.box.sdk.CreateUserParams params); com.box.sdk.BoxUser createEnterpriseUser(String login, String name, com.box.sdk.CreateUserParams params); void deleteUser(String userId, boolean notifyUser, boolean force); void deleteUserEmailAlias(String userId, String emailAliasId); java.util.List getAllEnterpriseOrExternalUsers(String filterTerm, String[] fields); java.util.Collection getUserEmailAlias(String userId); com.box.sdk.BoxUser.Info getUserInfo(String userId); com.box.sdk.BoxFolder.Info moveFolderToUser(String userId, String sourceUserId); com.box.sdk.BoxUser updateUserInfo(String userId, com.box.sdk.BoxUser.Info info); ---- The users API is defined in the syntax as follows: ---- box:users/methodName?[parameters] ---- The 10 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addUserEmailAlias* | addEmailAlias | Add a new email alias to user's account | *createAppUser* | create | Provision a new app user in an enterprise with additional user information using Box Developer Edition | *createEnterpriseUser* | create | Provision a new user in an enterprise with additional user information | *deleteUser* | delete | Delete user from an enterprise account | *deleteUserEmailAlias* | deleteEmailAlias | Delete an email alias from user's account | *getAllEnterpriseOrExternalUsers* | users | Get any managed users that match the filter term as well as any external users that match the filter term | *getUserEmailAlias* | emailAlias | Get a collection of all the email aliases for user | *getUserInfo* | info | Get user information | *moveFolderToUser* | | Move root folder for specified user to current user | *updateUserInfo* | updateInfo | Update user information |=== The users API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addUserEmailAlias | *email* | The email address to add as an alias | String | addUserEmailAlias | *userId* | The id of user | String | createAppUser | *name* | The name of the user | String | createAppUser | *params* | *Optional* Additional user information | CreateUserParams | createEnterpriseUser | *login* | The email address the user will use to login | String | createEnterpriseUser | *name* | The name of the user | String | createEnterpriseUser | *params* | *Optional* Additional user information | CreateUserParams | deleteUser | *force* | Whether or not this user should be deleted even if they still own files | Boolean | deleteUser | *notifyUser* | Whether or not to send an email notification to the user that their account has been deleted | Boolean | deleteUser | *userId* | The id of user to delete | String | deleteUserEmailAlias | *emailAliasId* | The id of the email alias to delete | String | deleteUserEmailAlias | *userId* | The id of user | String | getAllEnterpriseOrExternalUsers | *fields* | *Optional* The fields to retrieve. Leave this out for the standard fields. | String[] | getAllEnterpriseOrExternalUsers | *filterTerm* | *Optional* The filter term to lookup users by (login for external, login or name for managed); if null all managed users are returned. | String | getUserEmailAlias | *userId* | The id of user | String | getUserInfo | *userId* | The id of user | String | moveFolderToUser | *sourceUserId* | The user id of the user whose files will be the source for this operation | String | moveFolderToUser | *userId* | The id of user | String | updateUserInfo | *info* | The updated information | Info | updateUserInfo | *userId* | The id of user to update | String |=== In addition to the parameters above, the users API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. // endpoint options: END == Samples The following route uploads new files to the user's root folder: [source,java] ---- from(""file:..."") .to(""box://files/upload/inBody=fileUploadRequest""); ---- The following route polls user's account for updates: [source,java] ---- from(""box://events/listen?startingPosition=-1"") .to(""bean:blah""); ---- The following route uses a producer with dynamic header options. The *fileId* property has the Box file id and the *output* property has the output stream of the file contents, so they are assigned to the *CamelBox.fileId* header and *CamelBox.output* header respectively as follows: [source,java] ---- from(""direct:foo"") .setHeader(""CamelBox.fileId"", header(""fileId"")) .setHeader(""CamelBox.output"", header(""output"")) .to(""box://files/download"") .to(""file://...""); ---- === More information See more details at the Box API reference: https://developer.box.com/reference include::camel-spring-boot::page$box-starter.adoc[] ",12326,True,2565.2807709899607,median "--- title: ""FreeBSD/sparc64 5.4-RELEASE Installation Instructions"" sidenav: download --- ++++

The FreeBSD Project

Copyright © 2000, 2001, 2002, 2003, 2004 The FreeBSD Documentation Project


This article gives some brief instructions on installing FreeBSD/sparc64 5.4-RELEASE, with particular emphasis given to obtaining a FreeBSD distribution. Some notes on troubleshooting and frequently-asked questions are also given.


1 Installing FreeBSD

This section documents the process of installing a new distribution of FreeBSD. These instructions pay particular emphasis to the process of obtaining the FreeBSD 5.4-RELEASE distribution and to beginning the installation procedure. The ``Installing FreeBSD'' chapter of the FreeBSD Handbook provides more in-depth information about the installation program itself, including a guided walkthrough with screenshots.

If you are upgrading from a previous release of FreeBSD, please see Section 3 for instructions on upgrading.


1.1 Getting Started

Probably the most important pre-installation step that can be taken is that of reading the various instruction documents provided with FreeBSD. A roadmap of documents pertaining to this release of FreeBSD can be found in README.TXT, which can usually be found in the same location as this file; most of these documents, such as the release notes and the hardware compatibility list, are also accessible in the Documentation menu of the installer.

Note that on-line versions of the FreeBSD FAQ and Handbook are also available from the FreeBSD Project Web site, if you have an Internet connection.

This collection of documents may seem daunting, but the time spent reading them will likely be saved many times over. Being familiar with what resources are available can also be helpful in the event of problems during installation.

The best laid plans sometimes go awry, so if you run into trouble take a look at Section 4, which contains valuable troubleshooting information. You should also read an updated copy of ERRATA.TXT before installing, since this will alert you to any problems which have reported in the interim for your particular release.

Important: While FreeBSD does its best to safeguard against accidental loss of data, it's still more than possible to wipe out your entire disk with this installation if you make a mistake. Please do not proceed to the final FreeBSD installation menu unless you've adequately backed up any important data first.


1.2 Hardware Requirements

FreeBSD for the UltraSPARC supports the platforms described in HARDWARE.TXT.

You will need a dedicated disk for FreeBSD/sparc64. It is not possible to share a disk with another operating system at this time.

If you are not familiar with configuring hardware for FreeBSD, you should be sure to read the HARDWARE.TXT file; it contains important information on what hardware is supported by FreeBSD.


1.4 Installing FreeBSD from CDROM or the Internet

Most sparc64 systems are set up to boot automatically from disk. To install FreeBSD, you need to boot over the network or from a CDROM, which requires you to break into the PROM (OpenFirmware).

To do this, reboot the system, and wait until the boot message appears. It depends on the model, but should look about like:

Sun Blade 100 (UltraSPARC-IIe), Keyboard Present
Copyright 1998-2001 Sun Microsystems, Inc.  All rights reserved.
OpenBoot 4.2, 128 MB memory installed, Serial #51090132.
Ethernet address 0:3:ba:b:92:d4, Host ID: 830b92d4.

If your system proceeds to boot from disk at this point, you need to press L1+A or Stop+A on the keyboard, or send a BREAK over the serial console (using for example ~# in tip(1) or cu(1)) to get to the PROM prompt. It looks like this:

ok         (1)
ok {0}     (2)
(1)
This is the prompt used on systems with just one CPU.
(2)
This is the prompt used on SMP systems, the digit indicates the number of the active CPU.

At this point, place the CDROM into your drive, and from the PROM prompt, type boot cdrom.


1.5 Detail on various installation types

Once you've gotten yourself to the initial installation screen somehow, you should be able to follow the various menu prompts and go from there. If you've never used the FreeBSD installation before, you are also encouraged to read some of the documentation in the Documentation submenu as well as the general ``Usage'' instructions on the first menu.

Note: If you get stuck at a screen, press the F1 key for online documentation relevant to that specific section.

If you've never installed FreeBSD before, or even if you have, the ``Standard'' installation mode is the most recommended since it makes sure that you'll visit all the various important checklist items along the way. If you're much more comfortable with the FreeBSD installation process and know exactly what you want to do, use the ``Express'' or ``Custom'' installation options. If you're upgrading an existing system, use the ``Upgrade'' option.

The FreeBSD installer supports the direct use of floppy, DOS, tape, CDROM, FTP, NFS and UFS partitions as installation media; further tips on installing from each type of media are listed below.


1.5.1 Installing from a Network CDROM

If you simply wish to install from a local CDROM drive then see Section 1.4. If you don't have a CDROM drive on your system and wish to use a FreeBSD distribution CD in the CDROM drive of another system to which you have network connectivity, there are also several ways of going about it:

  • If you would be able to FTP install FreeBSD directly from the CDROM drive in some FreeBSD machine, it's quite easy: You ensure an FTP server is running and then simply add the following line to the password file (using the vipw(8) command):

    ftp:*:99:99::0:0:FTP:/cdrom:/sbin/nologin
    

    On the machine on which you are running the install, go to the Options menu and set Release Name to any. You may then choose a Media type of FTP and type in ftp://machine after picking ``URL'' in the ftp sites menu.

    Warning: This may allow anyone on the local network (or Internet) to make ``anonymous FTP'' connections to this machine, which may not be desirable.

  • If you would rather use NFS to export the CDROM directly to the machine(s) you'll be installing from, you need to first add an entry to the /etc/exports file (on the machine with the CDROM drive). The example below allows the machine ziggy.foo.com to mount the CDROM directly via NFS during installation:

    /cdrom          -ro             ziggy.foo.com
    

    The machine with the CDROM must also be configured as an NFS server, of course, and if you're not sure how to do that then an NFS installation is probably not the best choice for you unless you're willing to read up on rc.conf(5) and configure things appropriately. Assuming that this part goes smoothly, you should be able to enter: cdrom-host:/cdrom as the path for an NFS installation when the target machine is installed, e.g. wiggy:/cdrom.


1.5.2 Installing from Floppies

If you must install from floppy disks, either due to unsupported hardware or just because you enjoy doing things the hard way, you must first prepare some floppies for the install.

First, make your boot floppies as described in Section 1.3.

Second, peruse Section 2 and pay special attention to the ``Distribution Format'' section since it describes which files you're going to need to put onto floppy and which you can safely skip.

Next you will need, at minimum, as many 1.44MB floppies as it takes to hold all files in the bin (binary distribution) directory. If you're preparing these floppies under DOS, then these floppies must be formatted using the MS-DOS FORMAT command. If you're using Windows, use the Windows File Manager format command.

Important: Frequently, floppy disks come ``factory preformatted''. While convenient, many problems reported by users in the past have resulted from the use of improperly formatted media. Re-format them yourself, just to make sure.

If you're creating the floppies from another FreeBSD machine, a format is still not a bad idea though you don't need to put a DOS filesystem on each floppy. You can use the disklabel(8) and newfs(8) commands to put a UFS filesystem on a floppy, as the following sequence of commands illustrates:

# fdformat -f 1440 fd0
# disklabel -w fd0 floppy3
# newfs -i 65536 /dev/fd0

After you've formatted the floppies for DOS or UFS, you'll need to copy the files onto them. The distribution files are sized so that a floppy disk will hold a single file. Each distribution should go into its own subdirectory on the floppy, e.g.: a:\\bin\\bin.inf, a:\\bin\\bin.aa, a:\\bin\\bin.ab, ...

Important: The bin.inf file also needs to go on the first floppy of the bin set since it is read by the installation program in order to figure out how many additional pieces to look for when fetching and concatenating the distribution. When putting distributions onto floppies, the distname.inf file must occupy the first floppy of each distribution set.

Once you come to the Media screen of the install, select ``Floppy'' and you'll be prompted for the rest.


1.5.4 Installing from QIC/SCSI Tape

When installing from tape, the installation program expects the files to be simply tar'ed onto it, so after fetching all of the files for the distributions you're interested in, simply use tar(1) to get them onto the tape with a command something like this:

# cd /where/you/have/your/dists
# tar cvf /dev/sa0 dist1 .. dist2

When you go to do the installation, you should also make sure that you leave enough room in some temporary directory (which you'll be allowed to choose) to accommodate the full contents of the tape you've created. Due to the non-random access nature of tapes, this method of installation requires quite a bit of temporary storage. You should expect to require as much temporary storage as you have stuff written on tape.

Note: When going to do the installation, the tape must be in the drive before booting from the boot floppies. The installation ``probe'' may otherwise fail to find it.

Now create a boot floppy as described in Section 1.3 and proceed with the installation.


1.5.5 Installing over a Network using FTP or NFS

After making the boot floppies as described in the first section, you can load the rest of the installation over a network using one of 3 types of connections: serial port, parallel port, or Ethernet.


1.5.5.1 Serial Port

SLIP support is rather primitive, and is limited primarily to hard-wired links, such as a serial cable running between two computers. The link must be hard-wired because the SLIP installation doesn't currently offer a dialing capability. If you need to dial out with a modem or otherwise dialog with the link before connecting to it, then the PPP utility should be used instead.

If you're using PPP, make sure that you have your Internet Service Provider's IP address and DNS information handy as you'll need to know it fairly early in the installation process. You may also need to know your own IP address, though PPP supports dynamic address negotiation and may be able to pick up this information directly from your ISP if they support it.

You will also need to know how to use the various ``AT commands'' for dialing out with your particular brand of modem as the PPP dialer provides only a very simple terminal emulator.


1.5.5.2 Parallel Port

If a hard-wired connection to another FreeBSD or Linux machine is available, you might also consider installing over a ``laplink'' style parallel port cable. The data rate over the parallel port is much higher than what is typically possible over a serial line (up to 50k/sec), thus resulting in a quicker installation. It's not typically necessary to use ``real'' IP addresses when using a point-to-point parallel cable in this way and you can generally just use RFC 1918 style addresses for the ends of the link (e.g. 10.0.0.1, 10.0.0.2, etc).

Important: If you use a Linux machine rather than a FreeBSD machine as your PLIP peer, you will also have to specify link0 in the TCP/IP setup screen's ``extra options for ifconfig'' field in order to be compatible with Linux's slightly different PLIP protocol.


1.5.5.3 Ethernet

FreeBSD supports most common Ethernet cards; a table of supported cards is provided as part of the FreeBSD Hardware Notes (see HARDWARE.TXT in the Documentation menu on the boot floppy or the top level directory of the CDROM). If you are using one of the supported PCMCIA Ethernet cards, also be sure that it's plugged in before the laptop is powered on. FreeBSD does not, unfortunately, currently support ``hot insertion'' of PCMCIA cards during installation.

You will also need to know your IP address on the network, the netmask value for your subnet and the name of your machine. Your system administrator can tell you which values are appropriate to your particular network setup. If you will be referring to other hosts by name rather than IP address, you'll also need a name server and possibly the address of a gateway (if you're using PPP, it's your provider's IP address) to use in talking to it. If you want to install by FTP via an HTTP proxy (see below), you will also need the proxy's address.

If you do not know the answers to these questions then you should really probably talk to your system administrator first before trying this type of installation. Using a randomly chosen IP address or netmask on a live network is almost guaranteed not to work, and will probably result in a lecture from said system administrator.

Once you have a network connection of some sort working, the installation can continue over NFS or FTP.


1.5.5.4 NFS installation tips

NFS installation is fairly straight-forward: Simply copy the FreeBSD distribution files you want onto a server somewhere and then point the NFS media selection at it.

If this server supports only ``privileged port'' access (this is generally the default for Sun and Linux workstations), you may need to set this option in the Options menu before installation can proceed.

If you have a poor quality Ethernet card which suffers from very slow transfer rates, you may also wish to toggle the appropriate Options flag.

In order for NFS installation to work, the server must also support ``subdir mounts'', e.g. if your FreeBSD distribution directory lives on wiggy:/usr/archive/stuff/FreeBSD, then wiggy will have to allow the direct mounting of /usr/archive/stuff/FreeBSD, not just /usr or /usr/archive/stuff.

In FreeBSD's /etc/exports file this is controlled by the -alldirs option. Other NFS servers may have different conventions. If you are getting Permission Denied messages from the server then it's likely that you don't have this properly enabled.


1.5.5.5 FTP Installation tips

FTP installation may be done from any mirror site containing a reasonably up-to-date version of FreeBSD. A full menu of reasonable choices for almost any location in the world is provided in the FTP site menu during installation.

If you are installing from some other FTP site not listed in this menu, or you are having troubles getting your name server configured properly, you can also specify your own URL by selecting the ``URL'' choice in that menu. A URL can contain a hostname or an IP address, so something like the following would work in the absence of a name server:

ftp://216.66.64.162/pub/FreeBSD/releases/sparc64/4.2-RELEASE

There are three FTP installation modes you can use:

  • FTP: This method uses the standard ``Active'' mode for transfers, in which the server initiates a connection to the client. This will not work through most firewalls but will often work best with older FTP servers that do not support passive mode. If your connection hangs with passive mode, try this one.

  • FTP Passive: This sets the FTP ""Passive"" mode which prevents the server from opening connections to the client. This option is best for users to pass through firewalls that do not allow incoming connections on random port addresses.

  • FTP via an HTTP proxy: This option instructs FreeBSD to use HTTP to connect to a proxy for all FTP operations. The proxy will translate the requests and send them to the FTP server. This allows the user to pass through firewalls that do not allow FTP at all, but offer an HTTP proxy. You must specify the hostname of the proxy in addition to the FTP server.

    In the rare case that you have an FTP proxy that does not go through HTTP, you can specify the URL as something like:

    ftp://foo.bar.com:port/pub/FreeBSD
    

    In the URL above, port is the port number of the proxy FTP server.




2 Distribution Format

A typical FreeBSD distribution directory looks something like this (exact details may vary depending on version, architecture, and other factors):

ERRATA.HTM      README.TXT      compat1x        dict            kernel
ERRATA.TXT      RELNOTES.HTM    compat20        doc             manpages
HARDWARE.HTM    RELNOTES.TXT    compat21        docbook.css     packages
HARDWARE.TXT    base            compat22        filename.txt    ports
INSTALL.HTM     boot            compat3x        floppies        proflibs
INSTALL.TXT     catpages        compat4x        games           src
README.HTM      cdrom.inf       crypto          info            tools

These same files are contained in the first CDROM of a multi-disk set, but they are laid out slightly differently on the disk. On most architectures, the installation CDROM also contains a ``live filesystem'' in addition to the distribution files. The live filesystem is useful when repairing or troubleshooting an existing FreeBSD installation (see Section 4 for how to use this).

The floppies directory will be of particular interest to users who are unable to boot from the CDROM media (but are able to read the CDROM by other means). It is easy to generate a set of 1.44MB boot floppies from the floppies directory (see Section 1.3 for instructions on how to do this) and use these to start an installation from CDROM, FTP, or NFS. The rest of the data needed during the installation will be obtained automatically based on your selections. If you've never installed FreeBSD before, you also want to read the entirety of this document (the installation instructions) file.

If you're trying to do some other type of installation or are merely curious about how a distribution is organized, what follows is a more thorough description of some of these items in more detail:

  1. The *.TXT and *.HTM files contain documentation (for example, this document is contained in both INSTALL.TXT and INSTALL.HTM) and should be read before starting an installation. The *.TXT files are plain text, while the *.HTM files are HTML files that can be read by almost any Web browser. Some distributions may contain documentation in other formats as well, such as PDF or PostScript.

  2. docbook.css is a Cascading Style Sheet (CSS) file used by some Web browsers for formatting the HTML documentation.

  3. The base, catpages, crypto, dict, doc, games, info, manpages, proflibs, and src directories contain the primary distribution components of FreeBSD itself and are split into smaller files for easy packing onto floppies (should that be necessary).

  4. The compat1x, compat20, compat21, compat22, compat3x, and compat4x directories contain distributions for compatibility with older releases and are distributed as single gzip'd tar files - they can be installed during release time or later by running their install.sh scripts.

  5. The floppies/ subdirectory contains the floppy installation images; further information on using them can be found in Section 1.3.

  6. The packages and ports directories contain the FreeBSD Packages and Ports Collections. Packages may be installed from the packages directory by running the command:

    #/stand/sysinstall configPackages
    

    Packages can also be installed by feeding individual filenames in packages/ to the pkg_add(1) command.

    The Ports Collection may be installed like any other distribution and requires about 190MB unpacked. More information on the ports collection may be obtained from http://www.FreeBSD.org/ports/ or locally from /usr/share/doc/handbook if you've installed the doc distribution.

  7. Last of all, the tools directory contains various DOS tools for discovering disk geometries, installing boot managers and the like. It is purely optional and provided only for user convenience.



A typical distribution directory (for example, the info distribution) looks like this internally:

CHECKSUM.MD5    info.ab         info.ad         info.inf        install.sh
info.aa         info.ac         info.ae         info.mtree

The CHECKSUM.MD5 file contains MD5 signatures for each file, should data corruption be suspected, and is purely for reference. It is not used by the actual installation and does not need to be copied with the rest of the distribution files. The info.a* files are split, gzip'd tar files, the contents of which can be viewed by doing:

# cat info.a* | tar tvzf -

During installation, they are automatically concatenated and extracted by the installation procedure.

The info.inf file is also necessary since it is read by the installation program in order to figure out how many pieces to look for when fetching and concatenating the distribution. When putting distributions onto floppies, the .inf file must occupy the first floppy of each distribution set!

The info.mtree file is another non-essential file which is provided for user reference. It contains the MD5 signatures of the unpacked distribution files and can be later used with the mtree(8) program to verify the installation permissions and checksums against any possible modifications to the file. When used with the base distribution, this can be an excellent way of detecting trojan horse attacks on your system.

Finally, the install.sh file is for use by those who want to install the distribution after installation time. To install the info distribution from CDROM after a system was installed, for example, you'd do:

# cd /cdrom/info
# sh install.sh

3 Upgrading FreeBSD

These instructions describe a procedure for doing a binary upgrade from an older version of FreeBSD.

Warning: While the FreeBSD upgrade procedure does its best to safeguard against accidental loss of data, it is still more than possible to wipe out your entire disk with this installation! Please do not accept the final confirmation request unless you have adequately backed up any important data files.

Important: These notes assume that you are using the version of sysinstall(8) supplied with the version of FreeBSD to which you intend to upgrade. Using a mismatched version of sysinstall(8) is almost guaranteed to cause problems and has been known to leave systems in an unusable state. The most commonly made mistake in this regard is the use of an old copy of sysinstall(8) from an existing installation to upgrade to a newer version of FreeBSD. This is not recommended.

Warning: Binary upgrades to FreeBSD 5.4-RELEASE from FreeBSD 4-STABLE are not supported at this time. There are some files present in a FreeBSD 4-STABLE whose presence can be disruptive, but are not removed by a binary upgrade. One notable example is that an old /usr/include/g++ directory will cause C++ programs to compile incorrectly (or not at all).

These upgrade instructions are provided for the use of users upgrading from relatively recent FreeBSD 5-STABLE snapshots.


3.1 Introduction

The upgrade procedure replaces distributions selected by the user with those corresponding to the new FreeBSD release. It preserves standard system configuration data, as well as user data, installed packages and other software.

Administrators contemplating an upgrade are encouraged to study this section in its entirety before commencing an upgrade. Failure to do so may result in a failed upgrade or loss of data.


3.1.1 Upgrade Overview

Upgrading of a distribution is performed by extracting the new version of the component over the top of the previous version. Files belonging to the old distribution are not deleted.

System configuration is preserved by retaining and restoring the previous version of the following files:

Xaccel.ini, XF86Config, adduser.conf, aliases, aliases.db, amd.map, crontab, csh.cshrc, csh.login, csh.logout, cvsupfile, dhclient.conf, disktab, dm.conf, dumpdates, exports, fbtab, fstab, ftpusers, gettytab, gnats, group, hosts, hosts.allow, hosts.equiv, hosts.lpd, inetd.conf, localtime, login.access, login.conf, mail, mail.rc, make.conf, manpath.config, master.passwd, motd, namedb, networks, newsyslog.conf, nsmb.conf, nsswitch.conf, pam.conf, passwd, periodic, ppp, printcap, profile, pwd.db, rc.conf, rc.conf.local, rc.firewall, rc.local, remote, resolv.conf, rmt, sendmail.cf, sendmail.cw, services, shells, skeykeys, spwd.db, ssh, syslog.conf, ttys, uucp

The versions of these files which correspond to the new version are moved to /etc/upgrade/. The system administrator may peruse these new versions and merge components as desired. Note that many of these files are interdependent, and the best merge procedure is to copy all site-specific data from the current files into the new.

During the upgrade procedure, the administrator is prompted for a location into which all files from /etc/ are saved. In the event that local modifications have been made to other files, they may be subsequently retrieved from this location.


3.2 Procedure

This section details the upgrade procedure. Particular attention is given to items which substantially differ from a normal installation.


3.2.1 Backup

User data and system configuration should be backed up before upgrading. While the upgrade procedure does its best to prevent accidental mistakes, it is possible to partially or completely destroy data and configuration information.


3.2.2 Mount Filesystems

The disklabel editor is entered with the nominated disk's filesystem devices listed. Prior to commencing the upgrade, the administrator should make a note of the device names and corresponding mountpoints. These mountpoints should be entered here. Do not set the ``newfs flag'' for any filesystems, as this will cause data loss.


3.2.3 Select Distributions

When selecting distributions, there are no constraints on which must be selected. As a general rule, the base distribution should be selected for an update, and the man distribution if manpages are already installed. Other distributions may be selected beyond those originally installed if the administrator wishes to add additional functionality.


3.2.4 After Installation

Once the installation procedure has completed, the administrator is prompted to examine the new configuration files. At this point, checks should be made to ensure that the system configuration is valid. In particular, the /etc/rc.conf and /etc/fstab files should be checked.


3.3 Upgrading from Source Code

Those interested in an upgrade method that allows more flexibility and sophistication should take a look at The Cutting Edge in the FreeBSD Handbook. This procedure involves rebuilding all of FreeBSD from source code. It requires reliable network connectivity, extra disk space, and time, but has advantages for networks and other more complex installations. This is roughly the same procedure as is used for track the -STABLE or -CURRENT development branches.

/usr/src/UPDATING contains important information on updating a FreeBSD system from source code. It lists various issues resulting from changes in FreeBSD that may affect an upgrade.


4 Troubleshooting

4.1 Repairing an Existing FreeBSD Installation

FreeBSD features a ``fixit'' option in the top menu of the sysinstall(8) installation program. It provides a shell with common programs from the FreeBSD base system; this environment is useful for repairing or troubleshooting an existing FreeBSD installation. To use fixit mode, you will also need either the fixit.flp floppy, generated in the same fashion as the boot floppies, or the ``live filesystem'' CDROM. In multi-disk FreeBSD distributions, the live filesystem image is typically located on the installation disk. Note that some UNIX system administration experience is required to use the fixit option.

Generally, there are two ways of invoking fixit mode. Users who can boot from the FreeBSD installation CDROM, should do so and then choose the ``fixit'' item from the main sysinstall(8) menu. Then select the ``CDROM/DVD'' option from the fixit menu.

Users who cannot boot from CDROM, but can boot from floppy disk, require a few more steps. In addition to the boot.flp and kernX.flp disks required for installation, create the fixit.flp floppy disk, in the same way as the other floppy disks. Follow the instructions for booting the installation program from floppy disk until reaching the main sysinstall(8) menu. At that point, choose the ``fixit'' item from the main sysinstall(8) menu. Then select the ``Floppy'' option from the fixit menu, and insert the fixit.flp floppy disk when prompted to do so.

The CDROM and floppy fixit environments are similar, but not identical. Both offer a shell with a variety of commands available for checking, repairing and examining filesystems and their contents. The CDROM version of fixit provides all of the commands and programs available in the FreeBSD base system, through the live filesystem. By contrast, the floppy fixit environment can only offer a subset of commands due to space constraints.

In the floppy version of fixit, some standalone utilities can be found in /stand or /mnt2/stand. In the CDROM version of fixit, these same programs can be found in /stand or /mnt2/rescue (as well as the rest of the programs from the live filesystem, which can be found under /mnt).


This file, and other release-related documents, can be downloaded from ftp://ftp.FreeBSD.org/.

For questions about FreeBSD, read the documentation before contacting <questions@FreeBSD.org>.

For questions about this documentation, e-mail <doc@FreeBSD.org>.

++++ ",12272,False,2483.0047957595953,median "/**************************************************************************** Copyright (c) 2013 Zynga Inc. 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 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 ""2d/CCLabel.h"" #include #include ""2d/CCFont.h"" #include ""2d/CCFontAtlasCache.h"" #include ""2d/CCFontAtlas.h"" #include ""2d/CCSprite.h"" #include ""2d/CCSpriteBatchNode.h"" #include ""2d/CCDrawNode.h"" #include ""2d/CCCamera.h"" #include ""base/ccUTF8.h"" #include ""platform/CCFileUtils.h"" #include ""renderer/CCRenderer.h"" // #include ""renderer/ccGLStateCache.h"" #include ""renderer/CCGLProgramState.h"" #include ""base/CCDirector.h"" #include ""base/CCEventListenerCustom.h"" #include ""base/CCEventDispatcher.h"" #include ""base/CCEventCustom.h"" #include ""2d/CCFontFNT.h"" #include ""renderer/Texture2DUtils.h"" #include ""Urho3DContext.h"" #include ""renderer/Texture2DUtils.h"" #include ""Urho3DContext.h"" #include ""../../Core/Context.h"" #include ""../../Graphics/Texture2D.h"" #include ""../../Graphics/Graphics.h"" NS_CC_BEGIN /** * LabelLetter used to update the quad in texture atlas without SpriteBatchNode. */ class LabelLetter : public Sprite { public: LabelLetter() { _textureAtlas = nullptr; _letterVisible = true; } static LabelLetter* createWithTexture(Urho3D::Texture2D* texture, const Rect& rect, bool rotated = false) { auto letter = new (std::nothrow) LabelLetter(); if (letter && letter->initWithTexture(texture, rect, rotated)) { letter->Sprite::setVisible(false); letter->autorelease(); return letter; } CC_SAFE_DELETE(letter); return nullptr; } CREATE_FUNC(LabelLetter); virtual void updateTransform() override { if (isDirty()) { _transformToBatch = getNodeToParentTransform(); Size &size = _rect.size; float x1 = _offsetPosition.x; float y1 = _offsetPosition.y; float x2 = x1 + size.width; float y2 = y1 + size.height; // issue #17022: don't flip, again, the letter since they are flipped in sprite's code //if (_flippedX) std::swap(x1, x2); //if (_flippedY) std::swap(y1, y2); float x = _transformToBatch.m[12]; float y = _transformToBatch.m[13]; float cr = _transformToBatch.m[0]; float sr = _transformToBatch.m[1]; float cr2 = _transformToBatch.m[5]; float sr2 = -_transformToBatch.m[4]; float ax = x1 * cr - y1 * sr2 + x; float ay = x1 * sr + y1 * cr2 + y; float bx = x2 * cr - y1 * sr2 + x; float by = x2 * sr + y1 * cr2 + y; float cx = x2 * cr - y2 * sr2 + x; float cy = x2 * sr + y2 * cr2 + y; float dx = x1 * cr - y2 * sr2 + x; float dy = x1 * sr + y2 * cr2 + y; _quad.bl.vertices.set(SPRITE_RENDER_IN_SUBPIXEL(ax), SPRITE_RENDER_IN_SUBPIXEL(ay), _positionZ); _quad.br.vertices.set(SPRITE_RENDER_IN_SUBPIXEL(bx), SPRITE_RENDER_IN_SUBPIXEL(by), _positionZ); _quad.tl.vertices.set(SPRITE_RENDER_IN_SUBPIXEL(dx), SPRITE_RENDER_IN_SUBPIXEL(dy), _positionZ); _quad.tr.vertices.set(SPRITE_RENDER_IN_SUBPIXEL(cx), SPRITE_RENDER_IN_SUBPIXEL(cy), _positionZ); if (_textureAtlas) { _textureAtlas->updateQuad(&_quad, _atlasIndex); } _recursiveDirty = false; setDirty(false); } Node::updateTransform(); } virtual void updateColor() override { if (_textureAtlas == nullptr) { return; } auto displayedOpacity = _displayedOpacity; if(!_letterVisible) { displayedOpacity = 0.0f; } Color4B color4(_displayedColor.r, _displayedColor.g, _displayedColor.b, displayedOpacity); // special opacity for premultiplied textures if (_opacityModifyRGB) { color4.r *= displayedOpacity / 255.0f; color4.g *= displayedOpacity / 255.0f; color4.b *= displayedOpacity / 255.0f; } _quad.bl.colors = color4; _quad.br.colors = color4; _quad.tl.colors = color4; _quad.tr.colors = color4; _textureAtlas->updateQuad(&_quad, _atlasIndex); } void setVisible(bool visible) override { _letterVisible = visible; updateColor(); } bool isVisible() const override { return _letterVisible; } //LabelLetter doesn't need to draw directly. void draw(Renderer* /*renderer*/, const Mat4 & /*transform*/, uint32_t /*flags*/) override { } private: bool _letterVisible; }; Label* Label::create() { auto ret = new (std::nothrow) Label; if (ret) { ret->autorelease(); } return ret; } Label* Label::create(const std::string& text, const std::string& font, float fontSize, const Size& dimensions /* = Size::ZERO */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, TextVAlignment vAlignment /* = TextVAlignment::TOP */) { if (FileUtils::getInstance()->isFileExist(font)) { return createWithTTF(text,font,fontSize,dimensions,hAlignment,vAlignment); } else { return createWithSystemFont(text,font,fontSize,dimensions,hAlignment,vAlignment); } } Label* Label::createWithSystemFont(const std::string& text, const std::string& font, float fontSize, const Size& dimensions /* = Size::ZERO */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, TextVAlignment vAlignment /* = TextVAlignment::TOP */) { auto ret = new (std::nothrow) Label(hAlignment,vAlignment); if (ret) { ret->setSystemFontName(font); ret->setSystemFontSize(fontSize); ret->setDimensions(dimensions.width, dimensions.height); ret->setString(text); ret->autorelease(); return ret; } return nullptr; } Label* Label::createWithTTF(const std::string& text, const std::string& fontFile, float fontSize, const Size& dimensions /* = Size::ZERO */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, TextVAlignment vAlignment /* = TextVAlignment::TOP */) { auto ret = new (std::nothrow) Label(hAlignment,vAlignment); if (ret && ret->initWithTTF(text, fontFile, fontSize, dimensions, hAlignment, vAlignment)) { ret->autorelease(); return ret; } CC_SAFE_DELETE(ret); return nullptr; } Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment hAlignment /* = TextHAlignment::CENTER */, int maxLineWidth /* = 0 */) { auto ret = new (std::nothrow) Label(hAlignment); if (ret && ret->initWithTTF(ttfConfig, text, hAlignment, maxLineWidth)) { ret->autorelease(); return ret; } CC_SAFE_DELETE(ret); return nullptr; } Label* Label::createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& hAlignment /* = TextHAlignment::LEFT */, int maxLineWidth /* = 0 */, const Vec2& imageOffset /* = Vec2::ZERO */) { auto ret = new (std::nothrow) Label(hAlignment); if (ret && ret->setBMFontFilePath(bmfontFilePath,imageOffset)) { ret->setMaxLineWidth(maxLineWidth); ret->setString(text); ret->autorelease(); return ret; } delete ret; return nullptr; } Label* Label::createWithCharMap(const std::string& plistFile) { auto ret = new (std::nothrow) Label(); if (ret && ret->setCharMap(plistFile)) { ret->autorelease(); return ret; } delete ret; return nullptr; } Label* Label::createWithCharMap(Urho3D::Texture2D* texture, int itemWidth, int itemHeight, int startCharMap) { auto ret = new (std::nothrow) Label(); if (ret && ret->setCharMap(texture,itemWidth,itemHeight,startCharMap)) { ret->autorelease(); return ret; } delete ret; return nullptr; } Label* Label::createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) { auto ret = new (std::nothrow) Label(); if (ret && ret->setCharMap(charMapFile,itemWidth,itemHeight,startCharMap)) { ret->autorelease(); return ret; } delete ret; return nullptr; } bool Label::setCharMap(const std::string& plistFile) { auto newAtlas = FontAtlasCache::getFontAtlasCharMap(plistFile); if (!newAtlas) { reset(); return false; } _currentLabelType = LabelType::CHARMAP; setFontAtlas(newAtlas); return true; } bool Label::initWithTTF(const std::string& text, const std::string& fontFilePath, float fontSize, const Size& dimensions, TextHAlignment /*hAlignment*/, TextVAlignment /*vAlignment*/) { if (FileUtils::getInstance()->isFileExist(fontFilePath)) { TTFConfig ttfConfig(fontFilePath, fontSize, GlyphCollection::DYNAMIC); if (setTTFConfig(ttfConfig)) { setDimensions(dimensions.width, dimensions.height); setString(text); } return true; } return false; } bool Label::initWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment /*hAlignment*/, int maxLineWidth) { if (FileUtils::getInstance()->isFileExist(ttfConfig.fontFilePath) && setTTFConfig(ttfConfig)) { setMaxLineWidth(maxLineWidth); setString(text); return true; } return false; } bool Label::setCharMap(Urho3D::Texture2D* texture, int itemWidth, int itemHeight, int startCharMap) { auto newAtlas = FontAtlasCache::getFontAtlasCharMap(texture,itemWidth,itemHeight,startCharMap); if (!newAtlas) { reset(); return false; } _currentLabelType = LabelType::CHARMAP; setFontAtlas(newAtlas); return true; } bool Label::setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) { auto newAtlas = FontAtlasCache::getFontAtlasCharMap(charMapFile,itemWidth,itemHeight,startCharMap); if (!newAtlas) { reset(); return false; } _currentLabelType = LabelType::CHARMAP; setFontAtlas(newAtlas); return true; } Label::Label(TextHAlignment hAlignment /* = TextHAlignment::LEFT */, TextVAlignment vAlignment /* = TextVAlignment::TOP */) : _textSprite(nullptr) , _shadowNode(nullptr) , _fontAtlas(nullptr) , _reusedLetter(nullptr) , _horizontalKernings(nullptr) , _boldEnabled(false) , _underlineNode(nullptr) , _strikethroughEnabled(false) { setAnchorPoint(Vec2::ANCHOR_MIDDLE); reset(); _hAlignment = hAlignment; _vAlignment = vAlignment; #if CC_LABEL_DEBUG_DRAW _debugDrawNode = DrawNode::create(); addChild(_debugDrawNode); #endif _purgeTextureListener = EventListenerCustom::create(FontAtlas::CMD_PURGE_FONTATLAS, [this](EventCustom* event){ if (_fontAtlas && _currentLabelType == LabelType::TTF && event->getUserData() == _fontAtlas) { for (auto&& it : _letters) { it.second->setTexture(nullptr); } _batchNodes.clear(); if (_fontAtlas) { FontAtlasCache::releaseFontAtlas(_fontAtlas); } } }); _eventDispatcher->addEventListenerWithFixedPriority(_purgeTextureListener, 1); _resetTextureListener = EventListenerCustom::create(FontAtlas::CMD_RESET_FONTATLAS, [this](EventCustom* event){ if (_fontAtlas && _currentLabelType == LabelType::TTF && event->getUserData() == _fontAtlas) { _fontAtlas = nullptr; auto lineHeight = _lineHeight; this->setTTFConfig(_fontConfig); if (_currentLabelType != LabelType::STRING_TEXTURE) { setLineHeight(lineHeight); } for (auto&& it : _letters) { getLetter(it.first); } } }); _eventDispatcher->addEventListenerWithFixedPriority(_resetTextureListener, 2); } Label::~Label() { delete [] _horizontalKernings; if (_fontAtlas) { Node::removeAllChildrenWithCleanup(true); CC_SAFE_RELEASE_NULL(_reusedLetter); _batchNodes.clear(); FontAtlasCache::releaseFontAtlas(_fontAtlas); } _eventDispatcher->removeEventListener(_purgeTextureListener); _eventDispatcher->removeEventListener(_resetTextureListener); CC_SAFE_RELEASE_NULL(_textSprite); CC_SAFE_RELEASE_NULL(_shadowNode); } void Label::reset() { CC_SAFE_RELEASE_NULL(_textSprite); CC_SAFE_RELEASE_NULL(_shadowNode); Node::removeAllChildrenWithCleanup(true); CC_SAFE_RELEASE_NULL(_reusedLetter); _letters.clear(); _batchNodes.clear(); _lettersInfo.clear(); if (_fontAtlas) { FontAtlasCache::releaseFontAtlas(_fontAtlas); _fontAtlas = nullptr; } _currentLabelType = LabelType::STRING_TEXTURE; _currLabelEffect = LabelEffect::NORMAL; _contentDirty = false; _numberOfLines = 0; _lengthOfString = 0; _utf32Text.clear(); _utf8Text.clear(); TTFConfig temp; _fontConfig = temp; _outlineSize = 0.f; _bmFontPath = """"; _systemFontDirty = false; _systemFont = ""Helvetica""; _systemFontSize = CC_DEFAULT_FONT_LABEL_SIZE; if (_horizontalKernings) { delete[] _horizontalKernings; _horizontalKernings = nullptr; } _additionalKerning = 0.f; _lineHeight = 0.f; _lineSpacing = 0.f; _maxLineWidth = 0.f; _labelDimensions.width = 0.f; _labelDimensions.height = 0.f; _labelWidth = 0.f; _labelHeight = 0.f; _lineBreakWithoutSpaces = false; _hAlignment = TextHAlignment::LEFT; _vAlignment = TextVAlignment::TOP; _effectColorF = Color4F::BLACK; _textColor = Color4B::WHITE; _textColorF = Color4F::WHITE; setColor(Color3B::WHITE); _shadowDirty = false; _shadowEnabled = false; _shadowBlurRadius = 0.f; // _uniformEffectColor = -1; // _uniformEffectType = -1; // _uniformTextColor = -1; _useDistanceField = false; _useA8Shader = false; _clipEnabled = false; _blendFuncDirty = false; _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; _isOpacityModifyRGB = false; _insideBounds = true; _enableWrap = true; _bmFontSize = -1; _bmfontScale = 1.0f; _overflow = Overflow::NONE; _originalFontSize = 0.0f; _boldEnabled = false; if (_underlineNode) { removeChild(_underlineNode); _underlineNode = nullptr; } _strikethroughEnabled = false; setRotationSkewX(0); // reverse italics } // ETC1 ALPHA supports, for LabelType::BMFONT & LabelType::CHARMAP static Urho3D::Texture2D* _getTexture(Label* label) { auto fontAtlas = label->getFontAtlas(); Urho3D::Texture2D* texture = nullptr; if (fontAtlas != nullptr) { auto textures = fontAtlas->getTextures(); if(!textures.empty()) { texture = textures.begin()->second; } } return texture; } void Label::updateShaderProgram() { switch (_currLabelEffect) { case cocos2d::LabelEffect::NORMAL: if (_useDistanceField) setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_NORMAL)); else if (_useA8Shader) setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_LABEL_NORMAL)); else if (_shadowEnabled) setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR, _getTexture(this))); else setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP, _getTexture(this))); break; case cocos2d::LabelEffect::OUTLINE: setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_LABEL_OUTLINE)); //_uniformEffectColor = glGetUniformLocation(getGLProgram()->getProgram(), ""u_effectColor""); //_uniformEffectType = glGetUniformLocation(getGLProgram()->getProgram(), ""u_effectType""); break; case cocos2d::LabelEffect::GLOW: if (_useDistanceField) { setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_GLOW)); //_uniformEffectColor = glGetUniformLocation(getGLProgram()->getProgram(), ""u_effectColor""); } break; default: return; } //_uniformTextColor = glGetUniformLocation(getGLProgram()->getProgram(), ""u_textColor""); } void Label::setFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled /* = false */, bool useA8Shader /* = false */) { if(atlas) { _systemFontDirty = false; } if (atlas == _fontAtlas) return; CC_SAFE_RETAIN(atlas); if (_fontAtlas) { _batchNodes.clear(); FontAtlasCache::releaseFontAtlas(_fontAtlas); } _fontAtlas = atlas; if (_reusedLetter == nullptr) { _reusedLetter = Sprite::create(); _reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB); _reusedLetter->retain(); _reusedLetter->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); } if (_fontAtlas) { _lineHeight = _fontAtlas->getLineHeight(); _contentDirty = true; _systemFontDirty = false; } _useDistanceField = distanceFieldEnabled; _useA8Shader = useA8Shader; if (_currentLabelType != LabelType::TTF) { _currLabelEffect = LabelEffect::NORMAL; updateShaderProgram(); } } bool Label::setTTFConfig(const TTFConfig& ttfConfig) { _originalFontSize = ttfConfig.fontSize; return setTTFConfigInternal(ttfConfig); } bool Label::setBMFontFilePath(const std::string& bmfontFilePath, const Vec2& imageOffset, float fontSize) { FontAtlas *newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath,imageOffset); if (!newAtlas) { reset(); return false; } //assign the default fontSize if (std::abs(fontSize) < FLT_EPSILON) { FontFNT *bmFont = (FontFNT*)newAtlas->getFont(); if (bmFont) { float originalFontSize = bmFont->getOriginalFontSize(); _bmFontSize = originalFontSize / CC_CONTENT_SCALE_FACTOR(); } } if(fontSize > 0.0f){ _bmFontSize = fontSize; } _bmFontPath = bmfontFilePath; _currentLabelType = LabelType::BMFONT; setFontAtlas(newAtlas); return true; } void Label::setString(const std::string& text) { if (text.compare(_utf8Text)) { _utf8Text = text; _contentDirty = true; std::u32string utf32String; if (StringUtils::UTF8ToUTF32(_utf8Text, utf32String)) { _utf32Text = utf32String; } CCASSERT(_utf32Text.length() <= CC_LABEL_MAX_LENGTH, ""Length of text should be less then 16384""); if (_utf32Text.length() > CC_LABEL_MAX_LENGTH) { cocos2d::log(""Error: Label text is too long %d > %d and it will be truncated!"", _utf32Text.length(), CC_LABEL_MAX_LENGTH); _utf32Text = _utf32Text.substr(0, CC_LABEL_MAX_LENGTH); } } } void Label::setAlignment(TextHAlignment hAlignment,TextVAlignment vAlignment) { if (hAlignment != _hAlignment || vAlignment != _vAlignment) { _hAlignment = hAlignment; _vAlignment = vAlignment; _contentDirty = true; } } void Label::setMaxLineWidth(float maxLineWidth) { if (_labelWidth == 0 && _maxLineWidth != maxLineWidth) { _maxLineWidth = maxLineWidth; _contentDirty = true; } } void Label::setDimensions(float width, float height) { if(_overflow == Overflow::RESIZE_HEIGHT){ height = 0; } if (height != _labelHeight || width != _labelWidth) { _labelWidth = width; _labelHeight = height; _labelDimensions.width = width; _labelDimensions.height = height; _maxLineWidth = width; _contentDirty = true; if(_overflow == Overflow::SHRINK){ if (_originalFontSize > 0) { this->restoreFontSize(); } } } } void Label::restoreFontSize() { if(_currentLabelType == LabelType::TTF){ auto ttfConfig = this->getTTFConfig(); ttfConfig.fontSize = _originalFontSize; this->setTTFConfigInternal(ttfConfig); }else if(_currentLabelType == LabelType::BMFONT){ this->setBMFontSizeInternal(_originalFontSize); }else if(_currentLabelType == LabelType::STRING_TEXTURE){ this->setSystemFontSize(_originalFontSize); } } void Label::setLineBreakWithoutSpace(bool breakWithoutSpace) { if (breakWithoutSpace != _lineBreakWithoutSpaces) { _lineBreakWithoutSpaces = breakWithoutSpace; _contentDirty = true; } } void Label::updateLabelLetters() { if (!_letters.empty()) { Rect uvRect; LabelLetter* letterSprite; int letterIndex; for (auto it = _letters.begin(); it != _letters.end();) { letterIndex = it->first; letterSprite = (LabelLetter*)it->second; if (letterIndex >= _lengthOfString) { Node::removeChild(letterSprite, true); it = _letters.erase(it); } else { auto& letterInfo = _lettersInfo[letterIndex]; if (letterInfo.valid) { auto& letterDef = _fontAtlas->_letterDefinitions[letterInfo.utf32Char]; uvRect.size.height = letterDef.height; uvRect.size.width = letterDef.width; uvRect.origin.x = letterDef.U; uvRect.origin.y = letterDef.V; auto batchNode = _batchNodes.at(letterDef.textureID); letterSprite->setTextureAtlas(batchNode->getTextureAtlas()); letterSprite->setTexture(_fontAtlas->getTexture(letterDef.textureID)); if (letterDef.width <= 0.f || letterDef.height <= 0.f) { letterSprite->setTextureAtlas(nullptr); } else { letterSprite->setTextureRect(uvRect, false, uvRect.size); letterSprite->setTextureAtlas(_batchNodes.at(letterDef.textureID)->getTextureAtlas()); letterSprite->setAtlasIndex(_lettersInfo[letterIndex].atlasIndex); } auto px = letterInfo.positionX + letterDef.width / 2 + _linesOffsetX[letterInfo.lineIndex]; auto py = letterInfo.positionY - letterDef.height / 2 + _letterOffsetY; letterSprite->setPosition(px, py); } else { letterSprite->setTextureAtlas(nullptr); } this->updateLetterSpriteScale(letterSprite); ++it; } } } } bool Label::alignText() { if (_fontAtlas == nullptr || _utf32Text.empty()) { setContentSize(Size::ZERO); return true; } bool ret = true; do { _fontAtlas->prepareLetterDefinitions(_utf32Text); auto& textures = _fontAtlas->getTextures(); auto size = textures.size(); if (size > static_cast(_batchNodes.size())) { for (auto index = static_cast(_batchNodes.size()); index < size; ++index) { auto batchNode = SpriteBatchNode::createWithTexture(textures.at(index)); if (batchNode) { _isOpacityModifyRGB = false;// batchNode->getTexture()->hasPremultipliedAlpha(); _blendFunc = batchNode->getBlendFunc(); batchNode->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); batchNode->setPosition(Vec2::ZERO); _batchNodes.pushBack(batchNode); } } } if (_batchNodes.empty()) { return true; } // optimize for one-texture-only scenario // if multiple textures, then we should count how many chars // are per texture if (_batchNodes.size()==1) _batchNodes.at(0)->reserveCapacity(_utf32Text.size()); _reusedLetter->setBatchNode(_batchNodes.at(0)); _lengthOfString = 0; _textDesiredHeight = 0.f; _linesWidth.clear(); if (_maxLineWidth > 0.f && !_lineBreakWithoutSpaces) { multilineTextWrapByWord(); } else { multilineTextWrapByChar(); } computeAlignmentOffset(); if(_overflow == Overflow::SHRINK){ float fontSize = this->getRenderingFontSize(); if(fontSize > 0 && isVerticalClamp()){ this->shrinkLabelToContentSize(CC_CALLBACK_0(Label::isVerticalClamp, this)); } } if(!updateQuads()){ ret = false; if(_overflow == Overflow::SHRINK){ this->shrinkLabelToContentSize(CC_CALLBACK_0(Label::isHorizontalClamp, this)); } break; } updateLabelLetters(); updateColor(); }while (0); return ret; } bool Label::computeHorizontalKernings(const std::u32string& stringToRender) { if (_horizontalKernings) { delete [] _horizontalKernings; _horizontalKernings = nullptr; } int letterCount = 0; _horizontalKernings = _fontAtlas->getFont()->getHorizontalKerningForTextUTF32(stringToRender, letterCount); if(!_horizontalKernings) return false; else return true; } bool Label::isHorizontalClamped(float letterPositionX, int lineIndex) { auto wordWidth = this->_linesWidth[lineIndex]; bool letterOverClamp = (letterPositionX > _contentSize.width || letterPositionX < 0); if (!_enableWrap) { return letterOverClamp; }else{ return (wordWidth > this->_contentSize.width && letterOverClamp); } } bool Label::updateQuads() { bool ret = true; for (auto&& batchNode : _batchNodes) { batchNode->getTextureAtlas()->removeAllQuads(); } for (int ctr = 0; ctr < _lengthOfString; ++ctr) { if (_lettersInfo[ctr].valid) { auto& letterDef = _fontAtlas->_letterDefinitions[_lettersInfo[ctr].utf32Char]; _reusedRect.size.height = letterDef.height; _reusedRect.size.width = letterDef.width; _reusedRect.origin.x = letterDef.U; _reusedRect.origin.y = letterDef.V; auto py = _lettersInfo[ctr].positionY + _letterOffsetY; if (_labelHeight > 0.f) { if (py > _tailoredTopY) { auto clipTop = py - _tailoredTopY; _reusedRect.origin.y += clipTop; _reusedRect.size.height -= clipTop; py -= clipTop; } if (py - letterDef.height * _bmfontScale < _tailoredBottomY) { _reusedRect.size.height = (py < _tailoredBottomY) ? 0.f : (py - _tailoredBottomY); } } auto lineIndex = _lettersInfo[ctr].lineIndex; auto px = _lettersInfo[ctr].positionX + letterDef.width/2 * _bmfontScale + _linesOffsetX[lineIndex]; if(_labelWidth > 0.f){ if (this->isHorizontalClamped(px, lineIndex)) { if(_overflow == Overflow::CLAMP){ _reusedRect.size.width = 0; }else if(_overflow == Overflow::SHRINK){ if (_contentSize.width > letterDef.width) { ret = false; break; }else{ _reusedRect.size.width = 0; } } } } if (_reusedRect.size.height > 0.f && _reusedRect.size.width > 0.f) { _reusedLetter->setTextureRect(_reusedRect, false, _reusedRect.size); float letterPositionX = _lettersInfo[ctr].positionX + _linesOffsetX[_lettersInfo[ctr].lineIndex]; _reusedLetter->setPosition(letterPositionX, py); auto index = static_cast(_batchNodes.at(letterDef.textureID)->getTextureAtlas()->getTotalQuads()); _lettersInfo[ctr].atlasIndex = index; this->updateLetterSpriteScale(_reusedLetter); _batchNodes.at(letterDef.textureID)->insertQuadFromSprite(_reusedLetter, index); } } } return ret; } bool Label::setTTFConfigInternal(const TTFConfig& ttfConfig) { FontAtlas *newAtlas = FontAtlasCache::getFontAtlasTTF(&ttfConfig); if (!newAtlas) { reset(); return false; } _currentLabelType = LabelType::TTF; setFontAtlas(newAtlas,ttfConfig.distanceFieldEnabled,true); _fontConfig = ttfConfig; if (_fontConfig.outlineSize > 0) { _fontConfig.distanceFieldEnabled = false; _useDistanceField = false; _useA8Shader = false; _currLabelEffect = LabelEffect::OUTLINE; updateShaderProgram(); } else { _currLabelEffect = LabelEffect::NORMAL; updateShaderProgram(); } if (_fontConfig.italics) this->enableItalics(); if (_fontConfig.bold) this->enableBold(); if (_fontConfig.underline) this->enableUnderline(); if (_fontConfig.strikethrough) this->enableStrikethrough(); return true; } void Label::setBMFontSizeInternal(float fontSize) { if(_currentLabelType == LabelType::BMFONT){ this->setBMFontFilePath(_bmFontPath, Vec2::ZERO, fontSize); _contentDirty = true; } } void Label::scaleFontSizeDown(float fontSize) { bool shouldUpdateContent = true; if(_currentLabelType == LabelType::TTF){ auto ttfConfig = this->getTTFConfig(); ttfConfig.fontSize = fontSize; this->setTTFConfigInternal(ttfConfig); }else if(_currentLabelType == LabelType::BMFONT){ if (std::abs(fontSize) < FLT_EPSILON) { fontSize = 0.1f; shouldUpdateContent = false; } this->setBMFontSizeInternal(fontSize); }else if (_currentLabelType == LabelType::STRING_TEXTURE){ this->setSystemFontSize(fontSize); } if (shouldUpdateContent) { this->updateContent(); } } void Label::enableGlow(const Color4B& glowColor) { if (_currentLabelType == LabelType::TTF) { if (_fontConfig.distanceFieldEnabled == false) { auto config = _fontConfig; config.outlineSize = 0; config.distanceFieldEnabled = true; setTTFConfig(config); _contentDirty = true; } _currLabelEffect = LabelEffect::GLOW; _effectColorF.r = glowColor.r / 255.0f; _effectColorF.g = glowColor.g / 255.0f; _effectColorF.b = glowColor.b / 255.0f; _effectColorF.a = glowColor.a / 255.0f; updateShaderProgram(); } } void Label::enableOutline(const Color4B& outlineColor,int outlineSize /* = -1 */) { CCASSERT(_currentLabelType == LabelType::STRING_TEXTURE || _currentLabelType == LabelType::TTF, ""Only supported system font and TTF!""); if (outlineSize > 0 || _currLabelEffect == LabelEffect::OUTLINE) { if (_currentLabelType == LabelType::TTF) { _effectColorF.r = outlineColor.r / 255.0f; _effectColorF.g = outlineColor.g / 255.0f; _effectColorF.b = outlineColor.b / 255.0f; _effectColorF.a = outlineColor.a / 255.0f; if (outlineSize > 0 && _fontConfig.outlineSize != outlineSize) { _fontConfig.outlineSize = outlineSize; setTTFConfig(_fontConfig); } } else if (_effectColorF != outlineColor || _outlineSize != outlineSize) { _effectColorF.r = outlineColor.r / 255.f; _effectColorF.g = outlineColor.g / 255.f; _effectColorF.b = outlineColor.b / 255.f; _effectColorF.a = outlineColor.a / 255.f; _currLabelEffect = LabelEffect::OUTLINE; _contentDirty = true; } _outlineSize = outlineSize; } } void Label::enableShadow(const Color4B& shadowColor /* = Color4B::BLACK */, const Size &offset /* = Size(2 ,-2)*/, int /* blurRadius = 0 */) { _shadowEnabled = true; _shadowDirty = true; _shadowOffset.width = offset.width; _shadowOffset.height = offset.height; //TODO: support blur for shadow _shadowColor3B.r = shadowColor.r; _shadowColor3B.g = shadowColor.g; _shadowColor3B.b = shadowColor.b; _shadowOpacity = shadowColor.a; if (!_systemFontDirty && !_contentDirty && _textSprite) { auto fontDef = _getFontDefinition(); if (_shadowNode) { if (shadowColor != _shadowColor4F) { _shadowNode->release(); _shadowNode = nullptr; createShadowSpriteForSystemFont(fontDef); } else { _shadowNode->setPosition(_shadowOffset.width, _shadowOffset.height); } } else { createShadowSpriteForSystemFont(fontDef); } } _shadowColor4F.r = shadowColor.r / 255.0f; _shadowColor4F.g = shadowColor.g / 255.0f; _shadowColor4F.b = shadowColor.b / 255.0f; _shadowColor4F.a = shadowColor.a / 255.0f; if (_currentLabelType == LabelType::BMFONT || _currentLabelType == LabelType::CHARMAP) { setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(_shadowEnabled ? GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR : GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP, _getTexture(this))); } } void Label::enableItalics() { setRotationSkewX(12); } void Label::enableBold() { if (!_boldEnabled) { // bold is implemented with outline enableShadow(Color4B::WHITE, Size(0.9f, 0), 0); // add one to kerning setAdditionalKerning(_additionalKerning+1); _boldEnabled = true; } } void Label::enableUnderline() { // remove it, just in case to prevent adding two or more if (!_underlineNode) { _underlineNode = DrawNode::create(); addChild(_underlineNode, 100000); _contentDirty = true; } } void Label::enableStrikethrough() { if (!_strikethroughEnabled) { enableUnderline(); _strikethroughEnabled = true; } } void Label::disableEffect() { disableEffect(LabelEffect::ALL); } void Label::disableEffect(LabelEffect effect) { switch (effect) { case cocos2d::LabelEffect::NORMAL: break; case cocos2d::LabelEffect::OUTLINE: if (_currLabelEffect == LabelEffect::OUTLINE) { if (_currentLabelType == LabelType::TTF) { _fontConfig.outlineSize = 0; setTTFConfig(_fontConfig); } _currLabelEffect = LabelEffect::NORMAL; _contentDirty = true; } break; case cocos2d::LabelEffect::SHADOW: if (_shadowEnabled) { _shadowEnabled = false; CC_SAFE_RELEASE_NULL(_shadowNode); updateShaderProgram(); } break; case cocos2d::LabelEffect::GLOW: if (_currLabelEffect == LabelEffect::GLOW) { _currLabelEffect = LabelEffect::NORMAL; updateShaderProgram(); } break; case cocos2d::LabelEffect::ITALICS: setRotationSkewX(0); break; case cocos2d::LabelEffect::BOLD: if (_boldEnabled) { _boldEnabled = false; _additionalKerning -= 1; disableEffect(LabelEffect::SHADOW); } break; case cocos2d::LabelEffect::UNDERLINE: if (_underlineNode) { removeChild(_underlineNode); _underlineNode = nullptr; } break; case cocos2d::LabelEffect::STRIKETHROUGH: _strikethroughEnabled = false; // since it is based on underline, disable it as well disableEffect(LabelEffect::UNDERLINE); break; case LabelEffect::ALL: { disableEffect(LabelEffect::SHADOW); disableEffect(LabelEffect::GLOW); disableEffect(LabelEffect::OUTLINE); disableEffect(LabelEffect::ITALICS); disableEffect(LabelEffect::BOLD); disableEffect(LabelEffect::UNDERLINE); disableEffect(LabelEffect::STRIKETHROUGH); } break; default: break; } } void Label::createSpriteForSystemFont(const FontDefinition& fontDef) { _currentLabelType = LabelType::STRING_TEXTURE; auto texture = new (std::nothrow) Urho3D::Texture2D(GetUrho3DContext()); /*texture->i*/InitWithString(texture, _utf8Text.c_str(), fontDef); _textSprite = Sprite::createWithTexture(texture); //set camera mask using label's camera mask, because _textSprite may be null when setting camera mask to label _textSprite->setCameraMask(getCameraMask()); _textSprite->setGlobalZOrder(getGlobalZOrder()); _textSprite->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT); this->setContentSize(_textSprite->getContentSize()); //texture->release(); if (_blendFuncDirty) { _textSprite->setBlendFunc(_blendFunc); } //_textSprite->retain(); _textSprite->updateDisplayedColor(_displayedColor); _textSprite->updateDisplayedOpacity(_displayedOpacity); } void Label::createShadowSpriteForSystemFont(const FontDefinition& fontDef) { if (!fontDef._stroke._strokeEnabled && fontDef._fontFillColor == _shadowColor3B && (fontDef._fontAlpha == _shadowOpacity)) { _shadowNode = Sprite::createWithTexture(_textSprite->getTexture()); } else { FontDefinition shadowFontDefinition = fontDef; shadowFontDefinition._fontFillColor.r = _shadowColor3B.r; shadowFontDefinition._fontFillColor.g = _shadowColor3B.g; shadowFontDefinition._fontFillColor.b = _shadowColor3B.b; shadowFontDefinition._fontAlpha = _shadowOpacity; shadowFontDefinition._stroke._strokeColor = shadowFontDefinition._fontFillColor; shadowFontDefinition._stroke._strokeAlpha = shadowFontDefinition._fontAlpha; auto texture = new (std::nothrow) Urho3D::Texture2D(GetUrho3DContext()); /*texture->i*/InitWithString(texture, _utf8Text.c_str(), shadowFontDefinition); _shadowNode = Sprite::createWithTexture(texture); //texture->release(); } if (_shadowNode) { if (_blendFuncDirty) { _shadowNode->setBlendFunc(_blendFunc); } _shadowNode->setCameraMask(getCameraMask()); _shadowNode->setGlobalZOrder(getGlobalZOrder()); _shadowNode->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT); _shadowNode->setPosition(_shadowOffset.width, _shadowOffset.height); _shadowNode->retain(); _shadowNode->updateDisplayedColor(_displayedColor); _shadowNode->updateDisplayedOpacity(_displayedOpacity); } } void Label::setCameraMask(unsigned short mask, bool applyChildren) { Node::setCameraMask(mask, applyChildren); if (_textSprite) { _textSprite->setCameraMask(mask, applyChildren); } if (_shadowNode) { _shadowNode->setCameraMask(mask, applyChildren); } } void Label::setFontDefinition(const FontDefinition& textDefinition) { _systemFont = textDefinition._fontName; _systemFontSize = textDefinition._fontSize; _hAlignment = textDefinition._alignment; _vAlignment = textDefinition._vertAlignment; setDimensions(textDefinition._dimensions.width, textDefinition._dimensions.height); Color4B textColor = Color4B(textDefinition._fontFillColor); textColor.a = textDefinition._fontAlpha; setTextColor(textColor); #if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) && (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) if (textDefinition._stroke._strokeEnabled) { CCLOGERROR(""Stroke Currently only supported on iOS and Android!""); } _outlineSize = 0.f; #else if (textDefinition._stroke._strokeEnabled && textDefinition._stroke._strokeSize > 0.f) { Color4B outlineColor = Color4B(textDefinition._stroke._strokeColor); outlineColor.a = textDefinition._stroke._strokeAlpha; enableOutline(outlineColor, textDefinition._stroke._strokeSize); } #endif if (textDefinition._shadow._shadowEnabled) { enableShadow(Color4B(0, 0, 0, 255 * textDefinition._shadow._shadowOpacity), textDefinition._shadow._shadowOffset, textDefinition._shadow._shadowBlur); } } void Label::updateContent() { if (_systemFontDirty) { if (_fontAtlas) { _batchNodes.clear(); CC_SAFE_RELEASE_NULL(_reusedLetter); FontAtlasCache::releaseFontAtlas(_fontAtlas); _fontAtlas = nullptr; } _systemFontDirty = false; } CC_SAFE_RELEASE_NULL(_textSprite); CC_SAFE_RELEASE_NULL(_shadowNode); bool updateFinished = true; if (_fontAtlas) { std::u32string utf32String; if (StringUtils::UTF8ToUTF32(_utf8Text, utf32String)) { _utf32Text = utf32String; } computeHorizontalKernings(_utf32Text); updateFinished = alignText(); } else { auto fontDef = _getFontDefinition(); createSpriteForSystemFont(fontDef); if (_shadowEnabled) { createShadowSpriteForSystemFont(fontDef); } } if (_underlineNode) { _underlineNode->clear(); if (_numberOfLines) { // This is the logic for TTF fonts const float charheight = (_textDesiredHeight / _numberOfLines); _underlineNode->setLineWidth(charheight/6); // atlas font for (int i=0; i<_numberOfLines; ++i) { float offsety = 0; if (_strikethroughEnabled) offsety += charheight / 2; // FIXME: Might not work with different vertical alignments float y = (_numberOfLines - i - 1) * charheight + offsety; // Github issue #15214. Uses _displayedColor instead of _textColor for the underline. // This is to have the same behavior of SystemFonts. _underlineNode->drawLine(Vec2(_linesOffsetX[i],y), Vec2(_linesWidth[i] + _linesOffsetX[i],y), Color4F(_displayedColor)); } } else if (_textSprite) { // ...and is the logic for System fonts float y = 0; const auto spriteSize = _textSprite->getContentSize(); _underlineNode->setLineWidth(spriteSize.height/6); if (_strikethroughEnabled) // FIXME: system fonts don't report the height of the font correctly. only the size of the texture, which is POT y += spriteSize.height / 2; // FIXME: Might not work with different vertical alignments _underlineNode->drawLine(Vec2(0,y), Vec2(spriteSize.width,y), Color4F(_textSprite->getDisplayedColor())); } } if(updateFinished){ _contentDirty = false; } #if CC_LABEL_DEBUG_DRAW _debugDrawNode->clear(); Vec2 vertices[4] = { Vec2::ZERO, Vec2(_contentSize.width, 0), Vec2(_contentSize.width, _contentSize.height), Vec2(0, _contentSize.height) }; _debugDrawNode->drawPoly(vertices, 4, true, Color4F::WHITE); #endif } void Label::setBMFontSize(float fontSize) { this->setBMFontSizeInternal(fontSize); _originalFontSize = fontSize; } float Label::getBMFontSize()const { return _bmFontSize; } void Label::onDrawShadow(GLProgramState* glProgram, const Color4F& shadowColor) { auto graphics = GetUrho3DContext()->GetSubsystem(); if (_currentLabelType == LabelType::TTF) { if (_currLabelEffect == LabelEffect::OUTLINE) { graphics->SetShaderParameter(_uniformEffectType, 2.0f); graphics->SetShaderParameter(_uniformEffectColor, Urho3D::Color{ shadowColor.r, shadowColor.g, shadowColor.b, shadowColor.a }); } else { graphics->SetShaderParameter(_uniformTextColor, Urho3D::Color{ shadowColor.r, shadowColor.g, shadowColor.b, shadowColor.a }); if (_currLabelEffect == LabelEffect::GLOW) { graphics->SetShaderParameter(_uniformEffectColor, Urho3D::Color{ shadowColor.r, shadowColor.g, shadowColor.b, shadowColor.a }); } } glProgram->setUniformsForBuiltins(_shadowTransform); for (auto&& it : _letters) { it.second->updateTransform(); } for (auto&& batchNode : _batchNodes) { batchNode->getTextureAtlas()->drawQuads(); } } else { Color3B oldColor = _realColor; GLubyte oldOPacity = _displayedOpacity; _displayedOpacity = shadowColor.a * (oldOPacity / 255.0f) * 255; setColor(Color3B(shadowColor)); glProgram->setUniformsForBuiltins(_shadowTransform); for (auto&& it : _letters) { it.second->updateTransform(); } for (auto&& batchNode : _batchNodes) { batchNode->getTextureAtlas()->drawQuads(); } _displayedOpacity = oldOPacity; setColor(oldColor); } } void Label::onDraw(const Mat4& transform, bool /*transformUpdated*/) { auto graphics = GetUrho3DContext()->GetSubsystem(); auto glprogram = getGLProgramState();/*getGLProgram()*/ glprogram->apply(); //GL::blendFunc(_blendFunc.src, _blendFunc.dst); graphics->SetBlendMode(BlendCocosToUrho3D(_blendFunc)); if (_shadowEnabled) { if (_boldEnabled) onDrawShadow(glprogram, _textColorF); else onDrawShadow(glprogram, _shadowColor4F); } glprogram->setUniformsForBuiltins(transform); for (auto&& it : _letters) { it.second->updateTransform(); } if (_currentLabelType == LabelType::TTF) { switch (_currLabelEffect) { case LabelEffect::OUTLINE: // draw outline of text graphics->SetShaderParameter(_uniformEffectType, 1.0f); graphics->SetShaderParameter(_uniformEffectColor, Urho3D::Color{ _effectColorF.r, _effectColorF.g, _effectColorF.b, _effectColorF.a }); for (auto&& batchNode : _batchNodes) { batchNode->getTextureAtlas()->drawQuads(); } // draw text without outline graphics->SetShaderParameter(_uniformEffectType, 0.0f); graphics->SetShaderParameter(_uniformTextColor, Urho3D::Color{ _textColorF.r, _textColorF.g, _textColorF.b, _textColorF.a }); break; case LabelEffect::GLOW: graphics->SetShaderParameter(_uniformEffectColor, Urho3D::Color{ _effectColorF.r, _effectColorF.g, _effectColorF.b, _effectColorF.a }); case LabelEffect::NORMAL: graphics->SetShaderParameter(_uniformTextColor, Urho3D::Color{ _textColorF.r, _textColorF.g, _textColorF.b, _textColorF.a }); break; default: break; } } for (auto&& batchNode : _batchNodes) { batchNode->getTextureAtlas()->drawQuads(); } } void Label::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) { if (_batchNodes.empty() || _lengthOfString <= 0) { return; } // Don't do calculate the culling if the transform was not updated bool transformUpdated = flags & FLAGS_TRANSFORM_DIRTY; #if CC_USE_CULLING auto visitingCamera = Camera::getVisitingCamera(); auto defaultCamera = Camera::getDefaultCamera(); if (visitingCamera == defaultCamera) { _insideBounds = (transformUpdated || visitingCamera->isViewProjectionUpdated()) ? renderer->checkVisibility(transform, _contentSize) : _insideBounds; } else { _insideBounds = renderer->checkVisibility(transform, _contentSize); } if (_insideBounds) #endif { if (!_shadowEnabled && (_currentLabelType == LabelType::BMFONT || _currentLabelType == LabelType::CHARMAP)) { for (auto&& it : _letters) { it.second->updateTransform(); } // ETC1 ALPHA supports for BMFONT & CHARMAP auto textureAtlas = _batchNodes.at(0)->getTextureAtlas(); auto texture = textureAtlas->getTexture(); _quadCommand.init(_globalZOrder, texture, getGLProgramState(), _blendFunc, textureAtlas->getQuads(), textureAtlas->getTotalQuads(), transform, flags); renderer->addCommand(&_quadCommand); } else { _customCommand.init(_globalZOrder, transform, flags); _customCommand.func = CC_CALLBACK_0(Label::onDraw, this, transform, transformUpdated); renderer->addCommand(&_customCommand); } } } void Label::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags) { if (! _visible || (_utf8Text.empty() && _children.empty()) ) { return; } if (_systemFontDirty || _contentDirty) { updateContent(); } uint32_t flags = processParentFlags(parentTransform, parentFlags); if (!_utf8Text.empty() && _shadowEnabled && (_shadowDirty || (flags & FLAGS_DIRTY_MASK))) { _position.x += _shadowOffset.width; _position.y += _shadowOffset.height; _transformDirty = _inverseDirty = true; _shadowTransform = transform(parentTransform); _position.x -= _shadowOffset.width; _position.y -= _shadowOffset.height; _transformDirty = _inverseDirty = true; _shadowDirty = false; } bool visibleByCamera = isVisitableByVisitingCamera(); if (_children.empty() && !_textSprite && !visibleByCamera) { return; } // IMPORTANT: // To ease the migration to v3.0, we still support the Mat4 stack, // but it is deprecated and your code should not rely on it _director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); _director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform); if (!_children.empty()) { sortAllChildren(); int i = 0; // draw children zOrder < 0 for (auto size = _children.size(); i < size; ++i) { auto node = _children.at(i); if (node && node->getLocalZOrder() < 0) node->visit(renderer, _modelViewTransform, flags); else break; } this->drawSelf(visibleByCamera, renderer, flags); for (auto it = _children.cbegin() + i, itCend = _children.cend(); it != itCend; ++it) { (*it)->visit(renderer, _modelViewTransform, flags); } } else { this->drawSelf(visibleByCamera, renderer, flags); } _director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); } void Label::drawSelf(bool visibleByCamera, Renderer* renderer, uint32_t flags) { if (_textSprite) { if (_shadowNode) { _shadowNode->visit(renderer, _modelViewTransform, flags); } _textSprite->visit(renderer, _modelViewTransform, flags); } else if (visibleByCamera && !_utf8Text.empty()) { draw(renderer, _modelViewTransform, flags); } } void Label::setSystemFontName(const std::string& systemFont) { if (systemFont != _systemFont) { _systemFont = systemFont; _currentLabelType = LabelType::STRING_TEXTURE; _systemFontDirty = true; } } void Label::setSystemFontSize(float fontSize) { if (_systemFontSize != fontSize) { _systemFontSize = fontSize; _originalFontSize = fontSize; _currentLabelType = LabelType::STRING_TEXTURE; _systemFontDirty = true; } } ///// PROTOCOL STUFF Sprite* Label::getLetter(int letterIndex) { Sprite* letter = nullptr; do { if (_systemFontDirty || _currentLabelType == LabelType::STRING_TEXTURE) { break; } auto contentDirty = _contentDirty; if (contentDirty) { updateContent(); } if (_textSprite == nullptr && letterIndex < _lengthOfString) { const auto &letterInfo = _lettersInfo[letterIndex]; if (!letterInfo.valid || letterInfo.atlasIndex<0) { break; } if (_letters.find(letterIndex) != _letters.end()) { letter = _letters[letterIndex]; } if (letter == nullptr) { auto& letterDef = _fontAtlas->_letterDefinitions[letterInfo.utf32Char]; auto textureID = letterDef.textureID; Rect uvRect; uvRect.size.height = letterDef.height; uvRect.size.width = letterDef.width; uvRect.origin.x = letterDef.U; uvRect.origin.y = letterDef.V; if (letterDef.width <= 0.f || letterDef.height <= 0.f) { letter = LabelLetter::create(); } else { this->updateBMFontScale(); letter = LabelLetter::createWithTexture(_fontAtlas->getTexture(textureID), uvRect); letter->setTextureAtlas(_batchNodes.at(textureID)->getTextureAtlas()); letter->setAtlasIndex(letterInfo.atlasIndex); auto px = letterInfo.positionX + _bmfontScale * uvRect.size.width / 2 + _linesOffsetX[letterInfo.lineIndex]; auto py = letterInfo.positionY - _bmfontScale * uvRect.size.height / 2 + _letterOffsetY; letter->setPosition(px,py); letter->setOpacity(_realOpacity); this->updateLetterSpriteScale(letter); } addChild(letter); _letters[letterIndex] = letter; } } } while (false); return letter; } void Label::setLineHeight(float height) { CCASSERT(_currentLabelType != LabelType::STRING_TEXTURE, ""Not supported system font!""); if (_lineHeight != height) { _lineHeight = height; _contentDirty = true; } } float Label::getLineHeight() const { CCASSERT(_currentLabelType != LabelType::STRING_TEXTURE, ""Not supported system font!""); return _textSprite ? 0.0f : _lineHeight * _bmfontScale; } void Label::setLineSpacing(float height) { if (_lineSpacing != height) { _lineSpacing = height; _contentDirty = true; } } float Label::getLineSpacing() const { return _lineSpacing; } void Label::setAdditionalKerning(float space) { if (_currentLabelType != LabelType::STRING_TEXTURE) { if (_additionalKerning != space) { _additionalKerning = space; _contentDirty = true; } } else CCLOG(""Label::setAdditionalKerning not supported on LabelType::STRING_TEXTURE""); } float Label::getAdditionalKerning() const { CCASSERT(_currentLabelType != LabelType::STRING_TEXTURE, ""Not supported system font!""); return _additionalKerning; } void Label::computeStringNumLines() { int quantityOfLines = 1; if (_utf32Text.empty()) { _numberOfLines = 0; return; } // count number of lines size_t stringLen = _utf32Text.length(); for (size_t i = 0; i < stringLen - 1; ++i) { if (_utf32Text[i] == StringUtils::UnicodeCharacters::NewLine) { quantityOfLines++; } } _numberOfLines = quantityOfLines; } int Label::getStringNumLines() { if (_contentDirty) { updateContent(); } if (_currentLabelType == LabelType::STRING_TEXTURE) { computeStringNumLines(); } return _numberOfLines; } int Label::getStringLength() { _lengthOfString = static_cast(_utf32Text.length()); return _lengthOfString; } // RGBA protocol void Label::setOpacityModifyRGB(bool isOpacityModifyRGB) { if (isOpacityModifyRGB != _isOpacityModifyRGB) { _isOpacityModifyRGB = isOpacityModifyRGB; updateColor(); } } void Label::updateDisplayedColor(const Color3B& parentColor) { Node::updateDisplayedColor(parentColor); if (_textSprite) { _textSprite->updateDisplayedColor(_displayedColor); } if (_shadowNode) { _shadowNode->updateDisplayedColor(_displayedColor); } if (_underlineNode) { // FIXME: _underlineNode is not a sprite/label. It is a DrawNode // and updating its color doesn't work. it must be re-drawn, // which makes it super expensive to change update it frequently // Correct solution is to update the DrawNode directly since we know it is // a line. Returning a pointer to the line is an option _contentDirty = true; } for (auto&& it : _letters) { it.second->updateDisplayedColor(_displayedColor); } } void Label::updateDisplayedOpacity(GLubyte parentOpacity) { Node::updateDisplayedOpacity(parentOpacity); if (_textSprite) { _textSprite->updateDisplayedOpacity(_displayedOpacity); if (_shadowNode) { _shadowNode->updateDisplayedOpacity(_displayedOpacity); } } for (auto&& it : _letters) { it.second->updateDisplayedOpacity(_displayedOpacity); } } // FIXME: it is not clear what is the difference between setTextColor() and setColor() // if setTextColor() only changes the text and nothing but the text (no glow, no outline, not underline) // that's fine but it should be documented void Label::setTextColor(const Color4B &color) { CCASSERT(_currentLabelType == LabelType::TTF || _currentLabelType == LabelType::STRING_TEXTURE, ""Only supported system font and ttf!""); if (_currentLabelType == LabelType::STRING_TEXTURE && _textColor != color) { _contentDirty = true; } _textColor = color; _textColorF.r = _textColor.r / 255.0f; _textColorF.g = _textColor.g / 255.0f; _textColorF.b = _textColor.b / 255.0f; _textColorF.a = _textColor.a / 255.0f; } void Label::updateColor() { if (_batchNodes.empty()) { return; } Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity ); // special opacity for premultiplied textures if (_isOpacityModifyRGB) { color4.r *= _displayedOpacity/255.0f; color4.g *= _displayedOpacity/255.0f; color4.b *= _displayedOpacity/255.0f; } cocos2d::TextureAtlas* textureAtlas; V3F_C4B_T2F_Quad *quads; for (auto&& batchNode:_batchNodes) { textureAtlas = batchNode->getTextureAtlas(); quads = textureAtlas->getQuads(); auto count = textureAtlas->getTotalQuads(); for (int index = 0; index < count; ++index) { quads[index].bl.colors = color4; quads[index].br.colors = color4; quads[index].tl.colors = color4; quads[index].tr.colors = color4; textureAtlas->updateQuad(&quads[index], index); } } } std::string Label::getDescription() const { char tmp[50]; sprintf(tmp, ""