1 /* 2 * Copyright (c) 2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef SCENE_EXT_COMPONENT_UTIL_H 17 #define SCENE_EXT_COMPONENT_UTIL_H 18 19 #include <scene/ext/intf_component_factory.h> 20 #include <scene/ext/intf_ecs_context.h> 21 #include <scene/ext/intf_ecs_object_access.h> 22 #include <scene/ext/intf_internal_scene.h> 23 #include <scene/interface/intf_scene.h> 24 SCENE_BEGIN_NAMESPACE()25SCENE_BEGIN_NAMESPACE() 26 27 template<typename Manager> 28 bool AddComponent(INode::Ptr node) 29 { 30 auto acc = interface_cast<IEcsObjectAccess>(node); 31 if (!acc) { 32 CORE_LOG_E("Invalid node, no ecs access"); 33 return false; 34 } 35 auto ecsObj = acc->GetEcsObject(); 36 if (!ecsObj) { 37 CORE_LOG_E("Invalid node, ecs object is null"); 38 return false; 39 } 40 auto entity = ecsObj->GetEntity(); 41 42 auto is = node->GetScene()->GetInternalScene(); 43 auto m = CORE_NS::GetManager<Manager>(*is->GetEcsContext().GetNativeEcs()); 44 45 if (!m->HasComponent(entity)) { 46 m->Create(entity); 47 } 48 49 auto fac = is->FindComponentFactory(Manager::UID); 50 if (!fac) { 51 CORE_LOG_E("Failed to create component factory"); 52 return false; 53 } 54 55 auto c = fac->CreateComponent(ecsObj); 56 if (!c) { 57 CORE_LOG_E("Failed to create component"); 58 return false; 59 } 60 61 auto obj = interface_cast<META_NS::IAttach>(node); 62 if (!obj) { 63 CORE_LOG_E("Failed to attach component to node"); 64 return false; 65 } 66 67 obj->Attach(c); 68 return true; 69 } 70 71 SCENE_END_NAMESPACE() 72 73 #endif 74