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 #include "geometry_definition/SphereJS.h"
17
18 #include <napi_api.h>
19
20 namespace GeometryDefinition {
21
SphereJS(float radius,uint32_t segmentCount)22 SphereJS::SphereJS(float radius, uint32_t segmentCount)
23 : GeometryDefinition(), radius_(radius), segmentCount_(segmentCount)
24 {}
25
Init(napi_env env,napi_value exports)26 void SphereJS::Init(napi_env env, napi_value exports)
27 {
28 auto ctor = [](napi_env env, napi_callback_info info) -> napi_value {
29 return NapiApi::FunctionContext(env, info).This().ToNapiValue();
30 };
31 auto getType = [](napi_env e, napi_callback_info) { return NapiApi::Env { e }.GetNumber(GeometryType::SPHERE); };
32
33 napi_value zeroFloat = nullptr;
34 napi_value zeroInt = nullptr;
35 napi_create_double(env, 0.0, &zeroFloat);
36 napi_create_uint32(env, 0, &zeroInt);
37 const auto props = BASE_NS::vector<napi_property_descriptor> {
38 // clang-format off
39 { "geometryType", nullptr, nullptr, getType, nullptr, nullptr, napi_default_jsproperty, nullptr },
40 { "radius", nullptr, nullptr, nullptr, nullptr, zeroFloat, napi_default_jsproperty, nullptr },
41 { "segmentCount", nullptr, nullptr, nullptr, nullptr, zeroInt, napi_default_jsproperty, nullptr },
42 // clang-format on
43 };
44 DefineClass(env, exports, "SphereGeometry", props, ctor);
45 }
46
FromJs(NapiApi::Object & jsDefinition)47 GeometryDefinition* SphereJS::FromJs(NapiApi::Object& jsDefinition)
48 {
49 if (auto radius = jsDefinition.Get<float>("radius"); radius.IsValid()) {
50 // It's fine for radius to be negative. Then we will just have an inside-out sphere.
51 // Check valid segmentCount range with a signed type to avoid underflow. Internally we use uint32_t.
52 if (auto segmentCount = jsDefinition.Get<int64_t>("segmentCount"); segmentCount.IsValid()) {
53 if (segmentCount >= 0) {
54 return new SphereJS(radius, segmentCount);
55 }
56 }
57 }
58 LOG_E("Unable to create SphereJS: Invalid JS object given");
59 return {};
60 }
61
CreateMesh(const SCENE_NS::ICreateMesh::Ptr & creator,const SCENE_NS::MeshConfig & config) const62 SCENE_NS::IMesh::Ptr SphereJS::CreateMesh(
63 const SCENE_NS::ICreateMesh::Ptr& creator, const SCENE_NS::MeshConfig& config) const
64 {
65 return creator->CreateSphere(config, radius_, segmentCount_, segmentCount_).GetResult();
66 }
67
68 } // namespace GeometryDefinition
69