[dali_2.3.21] Merge branch 'devel/master'
[platform/core/uifw/dali-toolkit.git] / dali-scene3d / public-api / loader / material-definition.cpp
1 /*
2  * Copyright (c) 2024 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali-scene3d/public-api/loader/material-definition.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali-toolkit/devel-api/builder/base64-encoding.h>
23 #include <dali/devel-api/adaptor-framework/image-loading.h>
24 #include <dali/devel-api/adaptor-framework/pixel-buffer.h>
25 #include <dali/integration-api/pixel-data-integ.h>
26
27 // INTERNAL INCLUDES
28 #include <dali-scene3d/internal/common/image-resource-loader.h>
29
30 namespace Dali
31 {
32 using namespace Toolkit;
33
34 namespace Scene3D
35 {
36 namespace Loader
37 {
38 const Matrix3 TextureDefinition::DEFAULT_TRANSFORM = Matrix3::IDENTITY;
39
40 namespace
41 {
42 constexpr SamplerFlags::Type FILTER_MODES_FROM_DALI[]{
43   SamplerFlags::FILTER_LINEAR | SamplerFlags::FILTER_MIPMAP_NEAREST,
44   SamplerFlags::FILTER_LINEAR,
45   SamplerFlags::FILTER_NEAREST,
46   SamplerFlags::FILTER_LINEAR,
47   SamplerFlags::FILTER_NEAREST | SamplerFlags::FILTER_MIPMAP_NEAREST,
48   SamplerFlags::FILTER_LINEAR | SamplerFlags::FILTER_MIPMAP_NEAREST,
49   SamplerFlags::FILTER_NEAREST | SamplerFlags::FILTER_MIPMAP_LINEAR,
50   SamplerFlags::FILTER_LINEAR | SamplerFlags::FILTER_MIPMAP_LINEAR,
51 };
52
53 constexpr SamplerFlags::Type WRAP_MODES_FROM_DALI[]{
54   SamplerFlags::WRAP_CLAMP,
55   SamplerFlags::WRAP_CLAMP,
56   SamplerFlags::WRAP_REPEAT,
57   SamplerFlags::WRAP_MIRROR,
58 };
59
60 constexpr FilterMode::Type FILTER_MODES_TO_DALI[]{
61   FilterMode::NEAREST,
62   FilterMode::LINEAR,
63   FilterMode::NEAREST_MIPMAP_NEAREST,
64   FilterMode::LINEAR_MIPMAP_NEAREST,
65   FilterMode::NEAREST_MIPMAP_LINEAR,
66   FilterMode::LINEAR_MIPMAP_LINEAR,
67 };
68
69 constexpr WrapMode::Type WRAP_MODES_TO_DALI[]{
70   WrapMode::REPEAT,
71   WrapMode::CLAMP_TO_EDGE,
72   WrapMode::MIRRORED_REPEAT};
73
74 const SamplerFlags::Type GetSingleValueSampler()
75 {
76   static const SamplerFlags::Type SINGLE_VALUE_SAMPLER = SamplerFlags::Encode(FilterMode::NEAREST, FilterMode::NEAREST, WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE);
77   return SINGLE_VALUE_SAMPLER;
78 }
79
80 static constexpr std::string_view EMBEDDED_DATA_PREFIX               = "data:";
81 static constexpr std::string_view EMBEDDED_DATA_IMAGE_MEDIA_TYPE     = "image/";
82 static constexpr std::string_view EMBEDDED_DATA_BASE64_ENCODING_TYPE = "base64,";
83
84 Dali::PixelData LoadImageResource(const std::string& resourcePath,
85                                   TextureDefinition& textureDefinition,
86                                   FittingMode::Type  fittingMode,
87                                   bool               orientationCorrection)
88 {
89   Dali::PixelData pixelData;
90   if(!textureDefinition.mTextureBuffer.empty())
91   {
92     Dali::Devel::PixelBuffer pixelBuffer = Dali::LoadImageFromBuffer(textureDefinition.mTextureBuffer.data(), textureDefinition.mTextureBuffer.size(), textureDefinition.mMinImageDimensions, fittingMode, textureDefinition.mSamplingMode, orientationCorrection);
93     if(pixelBuffer)
94     {
95       pixelData = Devel::PixelBuffer::Convert(pixelBuffer);
96     }
97   }
98   else if(textureDefinition.mImageUri.find(EMBEDDED_DATA_PREFIX.data()) == 0 && textureDefinition.mImageUri.find(EMBEDDED_DATA_IMAGE_MEDIA_TYPE.data(), EMBEDDED_DATA_PREFIX.length()) == EMBEDDED_DATA_PREFIX.length())
99   {
100     uint32_t position = textureDefinition.mImageUri.find(EMBEDDED_DATA_BASE64_ENCODING_TYPE.data(), EMBEDDED_DATA_PREFIX.length() + EMBEDDED_DATA_IMAGE_MEDIA_TYPE.length());
101     if(position != std::string::npos)
102     {
103       position += EMBEDDED_DATA_BASE64_ENCODING_TYPE.length();
104       std::string_view     data = std::string_view(textureDefinition.mImageUri).substr(position);
105       std::vector<uint8_t> buffer;
106       Dali::Toolkit::DecodeBase64FromString(data, buffer);
107       uint32_t bufferSize = buffer.size();
108
109       Dali::Devel::PixelBuffer pixelBuffer = Dali::LoadImageFromBuffer(reinterpret_cast<uint8_t*>(buffer.data()), bufferSize, textureDefinition.mMinImageDimensions, fittingMode, textureDefinition.mSamplingMode, orientationCorrection);
110       if(pixelBuffer)
111       {
112         pixelData = Dali::Devel::PixelBuffer::Convert(pixelBuffer, true);
113       }
114     }
115   }
116   else
117   {
118     textureDefinition.mDirectoryPath = resourcePath;
119     pixelData                        = Internal::ImageResourceLoader::GetCachedPixelData(resourcePath + textureDefinition.mImageUri, textureDefinition.mMinImageDimensions, fittingMode, textureDefinition.mSamplingMode, orientationCorrection);
120   }
121   return pixelData;
122 }
123 } // namespace
124
125 SamplerFlags::Type SamplerFlags::Encode(FilterMode::Type minFilter, FilterMode::Type magFilter, WrapMode::Type wrapS, WrapMode::Type wrapT)
126 {
127   return FILTER_MODES_FROM_DALI[minFilter] | ((FILTER_MODES_FROM_DALI[magFilter] & FILTER_MAG_BITS) << FILTER_MAG_SHIFT) |
128          (WRAP_MODES_FROM_DALI[wrapS] << WRAP_S_SHIFT) | (WRAP_MODES_FROM_DALI[wrapT] << WRAP_T_SHIFT);
129 }
130
131 FilterMode::Type SamplerFlags::GetMinFilter(Type flags)
132 {
133   return FILTER_MODES_TO_DALI[flags & FILTER_MIN_MASK];
134 }
135
136 FilterMode::Type SamplerFlags::GetMagFilter(Type flags)
137 {
138   return FILTER_MODES_TO_DALI[(flags >> FILTER_MAG_SHIFT) & FILTER_MAG_MASK];
139 }
140
141 WrapMode::Type SamplerFlags::GetWrapS(Type flags)
142 {
143   return WRAP_MODES_TO_DALI[(flags >> WRAP_S_SHIFT) & WRAP_S_MASK];
144 }
145
146 WrapMode::Type SamplerFlags::GetWrapT(Type flags)
147 {
148   return WRAP_MODES_TO_DALI[(flags >> WRAP_T_SHIFT) & WRAP_T_MASK];
149 }
150
151 Sampler SamplerFlags::MakeSampler(Type flags)
152 {
153   auto sampler = Sampler::New();
154   sampler.SetFilterMode(GetMinFilter(flags), GetMagFilter(flags));
155   sampler.SetWrapMode(GetWrapS(flags), GetWrapT(flags));
156   return sampler;
157 }
158
159 TextureDefinition::TextureDefinition(const std::string& imageUri, SamplerFlags::Type samplerFlags, ImageDimensions minImageDimensions, SamplingMode::Type samplingMode, Matrix3 transform)
160 : mImageUri(imageUri),
161   mSamplerFlags(samplerFlags),
162   mMinImageDimensions(minImageDimensions),
163   mSamplingMode(samplingMode),
164   mTransform(transform)
165 {
166 }
167
168 TextureDefinition::TextureDefinition(std::string&& imageUri, SamplerFlags::Type samplerFlags, ImageDimensions minImageDimensions, SamplingMode::Type samplingMode, Matrix3 transform)
169 : mImageUri(std::move(imageUri)),
170   mSamplerFlags(samplerFlags),
171   mMinImageDimensions(minImageDimensions),
172   mSamplingMode(samplingMode),
173   mTransform(transform)
174 {
175 }
176
177 TextureDefinition::TextureDefinition(std::vector<uint8_t>&& textureBuffer, SamplerFlags::Type samplerFlags, ImageDimensions minImageDimensions, SamplingMode::Type samplingMode, Matrix3 transform)
178 : mImageUri(),
179   mSamplerFlags(samplerFlags),
180   mMinImageDimensions(minImageDimensions),
181   mSamplingMode(samplingMode),
182   mTransform(transform),
183   mTextureBuffer(std::move(textureBuffer))
184 {
185 }
186
187 MaterialDefinition::RawData
188 MaterialDefinition::LoadRaw(const std::string& imagesPath)
189 {
190   RawData raw;
191
192   const bool hasTransparency = MaskMatch(mFlags, TRANSPARENCY);
193   // Why we add additional count here?
194   uint32_t numBuffers = static_cast<uint32_t>(mTextureStages.size()) + (hasTransparency ? !CheckTextures(ALBEDO) + !CheckTextures(METALLIC | ROUGHNESS) + !CheckTextures(NORMAL)
195                                                                                         : !CheckTextures(ALBEDO | METALLIC) + !CheckTextures(NORMAL | ROUGHNESS));
196   if(numBuffers == 0)
197   {
198     return raw;
199   }
200   raw.mTextures.reserve(numBuffers);
201
202   // Load textures
203   auto iTexture   = mTextureStages.begin();
204   auto checkStage = [&](uint32_t flags) {
205     return iTexture != mTextureStages.end() && MaskMatch(iTexture->mSemantic, flags);
206   };
207
208   // Check for compulsory textures: Albedo, Metallic, Roughness, Normal
209   if(checkStage(ALBEDO | METALLIC))
210   {
211     raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
212     ++iTexture;
213
214     if(checkStage(NORMAL | ROUGHNESS))
215     {
216       raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
217       ++iTexture;
218     }
219     else // single value normal-roughness
220     {
221       raw.mTextures.push_back({Dali::Scene3D::Internal::ImageResourceLoader::GetEmptyPixelDataZAxisAndAlphaRGBA(), GetSingleValueSampler()});
222     }
223   }
224   else
225   {
226     if(checkStage(ALBEDO))
227     {
228       raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
229       ++iTexture;
230     }
231     else if(mNeedAlbedoTexture) // single value albedo, albedo-alpha or albedo-metallic
232     {
233       uint32_t bufferSize = 4;
234       uint8_t* buffer     = nullptr;
235       auto     format     = Pixel::Format::RGBA8888;
236       if(hasTransparency) // albedo-alpha
237       {
238         buffer    = new uint8_t[bufferSize];
239         buffer[3] = static_cast<uint8_t>(mColor.a * 255.f);
240       }
241       else if(!checkStage(METALLIC | ROUGHNESS)) // albedo-metallic
242       {
243         buffer    = new uint8_t[bufferSize];
244         buffer[3] = 0xff; // metallic of 1.0
245       }
246       else // albedo
247       {
248         bufferSize = 3;
249         buffer     = new uint8_t[bufferSize];
250         format     = Pixel::Format::RGB888;
251       }
252       buffer[0] = static_cast<uint8_t>(mColor.r * 255.f);
253       buffer[1] = static_cast<uint8_t>(mColor.g * 255.f);
254       buffer[2] = static_cast<uint8_t>(mColor.b * 255.f);
255       raw.mTextures.push_back({Dali::Integration::NewPixelDataWithReleaseAfterUpload(buffer, bufferSize, 1, 1, 0, format, PixelData::DELETE_ARRAY), GetSingleValueSampler()});
256     }
257
258     // If we have transparency, or an image based albedo map, we will have to continue with separate metallicRoughness + normal.
259     const bool createMetallicRoughnessAndNormal = hasTransparency || std::distance(mTextureStages.begin(), iTexture) > 0;
260     if(checkStage(METALLIC | ROUGHNESS))
261     {
262       raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
263       ++iTexture;
264     }
265     else if(createMetallicRoughnessAndNormal && mNeedMetallicRoughnessTexture)
266     {
267       // NOTE: we want to set both metallic and roughness to 1.0; dli uses the R & A channels,
268       // glTF2 uses B & G, so we might as well just set all components to 1.0.
269       raw.mTextures.push_back({Dali::Scene3D::Internal::ImageResourceLoader::GetEmptyPixelDataWhiteRGBA(), GetSingleValueSampler()});
270     }
271
272     if(checkStage(NORMAL))
273     {
274       raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
275       ++iTexture;
276     }
277     else if(mNeedNormalTexture)
278     {
279       if(createMetallicRoughnessAndNormal)
280       {
281         raw.mTextures.push_back({Dali::Scene3D::Internal::ImageResourceLoader::GetEmptyPixelDataZAxisRGB(), GetSingleValueSampler()});
282       }
283       else // single-value normal-roughness
284       {
285         raw.mTextures.push_back({Dali::Scene3D::Internal::ImageResourceLoader::GetEmptyPixelDataZAxisAndAlphaRGBA(), GetSingleValueSampler()});
286       }
287     }
288   }
289
290   // Extra textures.
291   if(checkStage(SUBSURFACE))
292   {
293     raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
294     ++iTexture;
295   }
296
297   if(checkStage(OCCLUSION))
298   {
299     raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
300     ++iTexture;
301   }
302
303   if(checkStage(EMISSIVE))
304   {
305     raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
306     ++iTexture;
307   }
308
309   if(checkStage(SPECULAR))
310   {
311     raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
312     ++iTexture;
313   }
314
315   if(checkStage(SPECULAR_COLOR))
316   {
317     raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
318     ++iTexture;
319   }
320
321   return raw;
322 }
323
324 TextureSet MaterialDefinition::Load(const EnvironmentDefinition::Vector& environments, RawData&& raw) const
325 {
326   auto textureSet = TextureSet::New();
327
328   uint32_t n = 0;
329   for(auto& tData : raw.mTextures)
330   {
331     auto&   pixels = tData.mPixels;
332     Texture texture;
333     if(pixels)
334     {
335       texture = Dali::Scene3D::Internal::ImageResourceLoader::GetCachedTexture(pixels, tData.mSamplerFlags & SamplerFlags::MIPMAP_MASK);
336     }
337
338     textureSet.SetTexture(n, texture);
339     textureSet.SetSampler(n, SamplerFlags::MakeSampler(tData.mSamplerFlags));
340
341     ++n;
342   }
343
344   if(mShadowAvailable)
345   {
346     textureSet.SetTexture(n++, Dali::Scene3D::Internal::ImageResourceLoader::GetEmptyTextureWhiteRGB());
347   }
348
349   // Assign textures to slots -- starting with 2D ones, then cubemaps, if any.
350   if(mEnvironmentIdx < static_cast<Index>(environments.size()))
351   {
352     auto& envTextures = environments[mEnvironmentIdx].second;
353     // If pre-computed brdf texture is defined, set the texture.
354     if(envTextures.mBrdf)
355     {
356       textureSet.SetTexture(n, envTextures.mBrdf);
357       ++n;
358     }
359
360     if(envTextures.mDiffuse)
361     {
362       textureSet.SetTexture(n, envTextures.mDiffuse);
363       ++n;
364     }
365
366     if(envTextures.mSpecular)
367     {
368       auto specularSampler = Sampler::New();
369       specularSampler.SetWrapMode(WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE);
370       specularSampler.SetFilterMode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR);
371
372       textureSet.SetTexture(n, envTextures.mSpecular);
373       textureSet.SetSampler(n, specularSampler);
374       ++n;
375     }
376   }
377   else
378   {
379     ExceptionFlinger(ASSERT_LOCATION) << "Environment index (" << mEnvironmentIdx << ") out of bounds (" << environments.size() << ").";
380   }
381
382   return textureSet;
383 }
384
385 bool MaterialDefinition::CheckTextures(uint32_t flags) const
386 {
387   return std::find_if(mTextureStages.begin(), mTextureStages.end(), [flags](const TextureStage& ts) { return MaskMatch(ts.mSemantic, flags); }) != mTextureStages.end();
388 }
389
390 } // namespace Loader
391 } // namespace Scene3D
392 } // namespace Dali