1 /*
2  * Copyright (C) 2023 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 #include <custom/shader_input_buffer.h>
16 
17 #include <securec.h>
18 
19 #include <3d_widget_adapter_log.h>
20 
21 namespace OHOS::Render3D {
Alloc(uint32_t floatSize)22 bool ShaderInputBuffer::Alloc(uint32_t floatSize)
23 {
24     if (floatSize > max_) {
25         WIDGET_LOGE("%s alloc too much memory", __func__);
26         return false;
27     }
28 
29     if (IsValid() && (floatSize_ == floatSize)) {
30         return true;
31     }
32 
33     Delete();
34 
35     buffer_ = new float[floatSize];
36     floatSize_ = floatSize;
37     return true;
38 }
39 
Map(uint32_t floatSize) const40 const float* ShaderInputBuffer::Map(uint32_t floatSize) const
41 {
42     if (!IsValid()) {
43         return nullptr;
44     }
45 
46     if (floatSize > floatSize_) {
47         return nullptr;
48     }
49 
50     return buffer_;
51 }
52 
FloatSize() const53 uint32_t ShaderInputBuffer::FloatSize() const
54 {
55     return floatSize_;
56 }
57 
ByteSize() const58 uint32_t ShaderInputBuffer::ByteSize() const
59 {
60     return floatSize_ * floatToByte_;
61 }
62 
Delete()63 void ShaderInputBuffer::Delete()
64 {
65     if (IsValid()) {
66         delete[] buffer_;
67     }
68     buffer_ = nullptr;
69     floatSize_ = 0u;
70 }
71 
Update(float * buffer,uint32_t floatSize)72 void ShaderInputBuffer::Update(float *buffer, uint32_t floatSize)
73 {
74     if (!Map(floatSize)) {
75         WIDGET_LOGE("Update(buffer, size) map error!");
76         return;
77     }
78 
79     auto ret = memcpy_s(reinterpret_cast<void *>(buffer_), floatSize,
80         reinterpret_cast<void *>(buffer), floatSize_);
81     if (ret != EOK) {
82         WIDGET_LOGE("ShaderInputBuffer Update memory copy error");
83     }
84 }
85 
Update(float value,uint32_t index)86 void ShaderInputBuffer::Update(float value, uint32_t index)
87 {
88     if (!IsValid()) {
89         WIDGET_LOGE("shader input buffer invalid");
90     }
91 
92     if (index >= floatSize_) {
93         WIDGET_LOGE("shader input buffer update index exceed the max size");
94         return;
95     }
96 
97     buffer_[index] = value;
98 }
99 
100 
IsValid() const101 bool ShaderInputBuffer::IsValid() const
102 {
103     return buffer_ && floatSize_;
104 }
105 
~ShaderInputBuffer()106 ShaderInputBuffer::~ShaderInputBuffer()
107 {
108     Delete();
109 }
110 } // namespace OHOS::Render3D
111