Blender V5.3
hydra/light.cpp
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2022 NVIDIA Corporation
2 * SPDX-FileCopyrightText: 2022 Blender Foundation
3 *
4 * SPDX-License-Identifier: Apache-2.0 */
5
6#include "hydra/light.h"
7#include "hydra/session.h"
8#include "hydra/util.h"
9#include "kernel/types.h"
10#include "scene/light.h"
11#include "scene/object.h"
12#include "scene/scene.h"
13#include "scene/shader.h"
14#include "scene/shader_graph.h"
15#include "scene/shader_nodes.h"
16#include "util/hash.h"
17#include "util/transform.h"
18
19#include <pxr/imaging/hd/lightSchema.h>
20#include <pxr/imaging/hd/sceneDelegate.h>
21#include <pxr/imaging/hd/visibilitySchema.h>
22#include <pxr/imaging/hd/xformSchema.h>
23#include <pxr/usd/sdf/assetPath.h>
24
26
27extern Transform convert_transform(const GfMatrix4d &matrix);
28
29// clang-format off
31 (visibleInPrimaryRay)
32 (treatAsPoint)
33 (falloff)
34);
35// clang-format on
36
37HdCyclesLight::HdCyclesLight(const SdfPath &sprimId, const TfToken &lightType)
38 : HdLight(sprimId), _lightType(lightType)
39{
40}
41
43
45{
46 return DirtyBits::DirtyTransform | DirtyBits::DirtyParams;
47}
48
49void HdCyclesLight::Sync(HdSceneDelegate *sceneDelegate,
50 HdRenderParam *renderParam,
51 HdDirtyBits *dirtyBits)
52{
53 if (*dirtyBits == DirtyBits::Clean) {
54 return;
55 }
56
57 Initialize(renderParam);
58
59 const SceneLock lock(renderParam);
60
61 const SdfPath &id = GetId();
62 const HdSceneIndexPrim prim = GetPrim(sceneDelegate, id);
63 const HdContainerDataSourceHandle &primDs = prim.dataSource;
64 const HdContainerDataSourceHandle lightDs = HdLightSchema::GetFromParent(primDs).GetContainer();
65
66 if (*dirtyBits & DirtyBits::DirtyTransform) {
67 const float metersPerUnit =
68 static_cast<HdCyclesSession *>(renderParam)->GetStageMetersPerUnit();
69
70 GfMatrix4d xform(1.0);
71 if (auto matrixDs = HdXformSchema::GetFromParent(primDs).GetMatrix()) {
72 xform = matrixDs->GetTypedValue(0.0f);
73 }
74
75 const Transform tfm = transform_scale(make_float3(metersPerUnit)) * convert_transform(xform);
76 _object->set_tfm(tfm);
77 }
78
79 if (*dirtyBits & DirtyBits::DirtyParams) {
80 float3 strength = make_float3(1.0f, 1.0f, 1.0f);
81
82 {
83 const GfVec3f color = GetTypedValue<GfVec3f>(
84 lightDs, HdLightTokens->color, GfVec3f(1.0f, 1.0f, 1.0f));
85 strength = make_float3(color[0], color[1], color[2]);
86 }
87
88 strength *= exp2(GetTypedValue<float>(lightDs, HdLightTokens->exposure, 0.0f));
89 strength *= GetTypedValue<float>(lightDs, HdLightTokens->intensity, 1.0f);
90
91 if (_lightType == HdPrimTypeTokens->distantLight) {
92 /* Unclear why, but approximately matches Karma. */
93 strength *= 4.0f;
94 }
95 else {
96 /* Convert from intensity to radiant flux. */
97 strength *= M_PI_F;
98 }
99
100 _light->set_normalize(GetTypedValue<bool>(lightDs, HdLightTokens->normalize, false));
101
102 if (auto ds = GetTypedDataSource<bool>(lightDs, _tokens->visibleInPrimaryRay)) {
103 if (ds->GetTypedValue(0.0f)) {
104 _object->set_visibility(_object->get_visibility() | PATH_RAY_VISIBILITY_CAMERA);
105 }
106 else {
107 _object->set_visibility(_object->get_visibility() & ~PATH_RAY_VISIBILITY_CAMERA);
108 }
109 }
110
111 if (auto ds = GetTypedDataSource<bool>(lightDs, HdLightTokens->shadowEnable)) {
112 _light->set_cast_shadow(ds->GetTypedValue(0.0f));
113 }
114
115 if (_lightType == HdPrimTypeTokens->distantLight) {
116 if (auto ds = GetTypedDataSource<float>(lightDs, HdLightTokens->angle)) {
117 static_cast<SunLight *>(_light)->set_angle(GfDegreesToRadians(ds->GetTypedValue(0.0f)));
118 }
119 }
120 else if (_lightType == HdPrimTypeTokens->diskLight) {
121 AreaLight *area_light = static_cast<AreaLight *>(_light);
122 if (auto ds = GetTypedDataSource<float>(lightDs, HdLightTokens->radius)) {
123 const float size = ds->GetTypedValue(0.0f) * 2.0f;
124 area_light->set_sizeu(size);
125 area_light->set_sizev(size);
126 }
127 }
128 else if (_lightType == HdPrimTypeTokens->rectLight) {
129 AreaLight *area_light = static_cast<AreaLight *>(_light);
130 if (auto ds = GetTypedDataSource<float>(lightDs, HdLightTokens->width)) {
131 area_light->set_sizeu(ds->GetTypedValue(0.0f));
132 }
133 if (auto ds = GetTypedDataSource<float>(lightDs, HdLightTokens->height)) {
134 area_light->set_sizev(ds->GetTypedValue(0.0f));
135 }
136 }
137 else if (_lightType == HdPrimTypeTokens->sphereLight) {
138 SpotLight *spot_light = static_cast<SpotLight *>(_light);
139 const bool treatAsPoint = GetTypedValue<bool>(lightDs, _tokens->treatAsPoint, false);
140 if (treatAsPoint) {
141 spot_light->set_radius(0.0f);
142 }
143 else if (auto ds = GetTypedDataSource<float>(lightDs, HdLightTokens->radius)) {
144 spot_light->set_radius(ds->GetTypedValue(0.0f));
145 }
146
147 bool shaping = false;
148
149 if (auto ds = GetTypedDataSource<float>(lightDs, HdLightTokens->shapingConeAngle)) {
150 spot_light->set_angle(GfDegreesToRadians(ds->GetTypedValue(0.0f)) * 2.0f);
151 shaping = true;
152 }
153
154 if (auto ds = GetTypedDataSource<float>(lightDs, HdLightTokens->shapingConeSoftness)) {
155 spot_light->set_smooth(ds->GetTypedValue(0.0f));
156 shaping = true;
157 }
158
159 _light->set_light_type(shaping ? LIGHT_SPOT : LIGHT_POINT);
160 }
161
162 bool visible = true;
163 if (auto ds = HdVisibilitySchema::GetFromParent(primDs).GetVisibility()) {
164 visible = ds->GetTypedValue(0.0f);
165 }
166 // Disable invisible lights by zeroing the strength
167 // So 'LightManager::test_enabled_lights' updates the enabled flag correctly
168 if (!visible) {
169 strength = zero_float3();
170 }
171
172 _light->set_strength(strength);
173 _light->set_is_enabled(visible);
174
175 PopulateShaderGraph(lightDs);
176 }
177 // Need to update shader graph when transform changes in case transform was baked into it
178 else if (_object->tfm_is_modified() && (_lightType == HdPrimTypeTokens->domeLight ||
179 _light->get_shader()->has_surface_spatial_varying))
180 {
181 PopulateShaderGraph(lightDs);
182 }
183
184 if (_light->is_modified()) {
185 _light->tag_update(lock.scene);
186 }
187
188 *dirtyBits = DirtyBits::Clean;
189}
190
191void HdCyclesLight::PopulateShaderGraph(const HdContainerDataSourceHandle &lightContainer)
192{
193 unique_ptr<ShaderGraph> graph = make_unique<ShaderGraph>();
194 ShaderNode *outputNode = nullptr;
195
196 if (_lightType == HdPrimTypeTokens->domeLight) {
197 BackgroundNode *bgNode = graph->create_node<BackgroundNode>();
198 // Bake strength into shader graph, since only the shader is used for background lights
199 bgNode->set_color(_light->get_strength());
200
201 graph->connect(bgNode->output("Background"), graph->output()->input("Surface"));
202
203 outputNode = bgNode;
204 }
205 else if (lightContainer) {
206 if (auto ds = HdStringDataSource::Cast(lightContainer->Get(_tokens->falloff))) {
207 const std::string strVal = ds->GetTypedValue(0.0f);
208 if (strVal == "Constant" || strVal == "Linear" || strVal == "Quadratic") {
209 LightFalloffNode *lfoNode = graph->create_node<LightFalloffNode>();
210 lfoNode->set_strength(1.f);
211 graph->connect(lfoNode->output(strVal.c_str()), graph->output()->input("Surface"));
212 outputNode = lfoNode;
213 }
214 }
215 }
216
217 if (outputNode == nullptr) {
218 EmissionNode *emissionNode = graph->create_node<EmissionNode>();
219 emissionNode->set_color(one_float3());
220 emissionNode->set_strength(1.0f);
221
222 graph->connect(emissionNode->output("Emission"), graph->output()->input("Surface"));
223
224 outputNode = emissionNode;
225 }
226
227 bool hasSpatialVarying = false;
228 bool hasColorTemperature = false;
229
230 if (lightContainer) {
231 const bool enableColorTemperature = GetTypedValue<bool>(
232 lightContainer, HdLightTokens->enableColorTemperature, false);
233
234 if (enableColorTemperature) {
235 if (auto ds = HdFloatDataSource::Cast(lightContainer->Get(HdLightTokens->colorTemperature)))
236 {
237 BlackbodyNode *blackbodyNode = graph->create_node<BlackbodyNode>();
238 blackbodyNode->set_temperature(ds->GetTypedValue(0.0f));
239
240 if (_lightType == HdPrimTypeTokens->domeLight) {
241 VectorMathNode *mathNode = graph->create_node<VectorMathNode>();
242 mathNode->set_math_type(NODE_VECTOR_MATH_MULTIPLY);
243 mathNode->set_vector2(_light->get_strength());
244
245 graph->connect(blackbodyNode->output("Color"), mathNode->input("Vector1"));
246 graph->connect(mathNode->output("Vector"), outputNode->input("Color"));
247 }
248 else {
249 graph->connect(blackbodyNode->output("Color"), outputNode->input("Color"));
250 }
251
252 hasColorTemperature = true;
253 }
254 }
255
256 if (auto ds = HdAssetPathDataSource::Cast(lightContainer->Get(HdLightTokens->shapingIesFile)))
257 {
258 const SdfAssetPath assetPath = ds->GetTypedValue(0.0f);
259 std::string filename = assetPath.GetResolvedPath();
260 if (filename.empty()) {
261 filename = assetPath.GetAssetPath();
262 }
263
264 if (!filename.empty()) {
265 TextureCoordinateNode *coordNode = graph->create_node<TextureCoordinateNode>();
266 coordNode->set_ob_tfm(_object->get_tfm());
267 coordNode->set_use_transform(true);
268
269 IESLightNode *iesNode = graph->create_node<IESLightNode>();
270 iesNode->set_filename(ustring(filename));
271
272 graph->connect(coordNode->output("Normal"), iesNode->input("Vector"));
273 graph->connect(iesNode->output("Fac"), outputNode->input("Strength"));
274
275 hasSpatialVarying = true;
276 }
277 }
278
279 if (auto ds = HdAssetPathDataSource::Cast(lightContainer->Get(HdLightTokens->textureFile))) {
280 const SdfAssetPath assetPath = ds->GetTypedValue(0.0f);
281 std::string filename = assetPath.GetResolvedPath();
282 if (filename.empty()) {
283 filename = assetPath.GetAssetPath();
284 }
285
286 if (!filename.empty()) {
287 ImageSlotTextureNode *textureNode = nullptr;
288 if (_lightType == HdPrimTypeTokens->domeLight) {
289 Transform tfm = _object->get_tfm();
290 transform_set_column(&tfm, 3, zero_float3()); // Remove translation
291
292 TextureCoordinateNode *coordNode = graph->create_node<TextureCoordinateNode>();
293 coordNode->set_ob_tfm(tfm);
294 coordNode->set_use_transform(true);
295
296 textureNode = graph->create_node<EnvironmentTextureNode>();
297 static_cast<EnvironmentTextureNode *>(textureNode)->set_filename(ustring(filename));
298
299 graph->connect(coordNode->output("Object"), textureNode->input("Vector"));
300
301 hasSpatialVarying = true;
302 }
303 else {
304 GeometryNode *coordNode = graph->create_node<GeometryNode>();
305
306 textureNode = graph->create_node<ImageTextureNode>();
307 static_cast<ImageTextureNode *>(textureNode)->set_filename(ustring(filename));
308
309 graph->connect(coordNode->output("Parametric"), textureNode->input("Vector"));
310 }
311
312 if (hasColorTemperature) {
313 VectorMathNode *mathNode = graph->create_node<VectorMathNode>();
314 mathNode->set_math_type(NODE_VECTOR_MATH_MULTIPLY);
315
316 graph->connect(textureNode->output("Color"), mathNode->input("Vector1"));
317 ShaderInput *const outputNodeInput = outputNode->input("Color");
318 graph->connect(outputNodeInput->link, mathNode->input("Vector2"));
319 graph->disconnect(outputNodeInput);
320 graph->connect(mathNode->output("Vector"), outputNodeInput);
321 }
322 else if (_lightType == HdPrimTypeTokens->domeLight) {
323 VectorMathNode *mathNode = graph->create_node<VectorMathNode>();
324 mathNode->set_math_type(NODE_VECTOR_MATH_MULTIPLY);
325 mathNode->set_vector2(_light->get_strength());
326
327 graph->connect(textureNode->output("Color"), mathNode->input("Vector1"));
328 graph->connect(mathNode->output("Vector"), outputNode->input("Color"));
329 }
330 else {
331 graph->connect(textureNode->output("Color"), outputNode->input("Color"));
332 }
333 }
334 }
335 }
336
337 Shader *const shader = _light->get_shader();
338 shader->set_graph(std::move(graph));
339 shader->tag_update((Scene *)_light->get_owner());
340
341 shader->has_surface_spatial_varying = hasSpatialVarying;
342}
343
344void HdCyclesLight::Finalize(HdRenderParam *renderParam)
345{
346 if (!_light) {
347 return;
348 }
349
350 const SceneLock lock(renderParam);
351 const bool keep_nodes = static_cast<const HdCyclesSession *>(renderParam)->keep_nodes;
352
353 if (!keep_nodes) {
354 /* Delete the object before the light, since the object references the light. */
355 lock.scene->delete_node(_object);
356 lock.scene->delete_node(_light);
357 }
358
359 _light = nullptr;
360 _object = nullptr;
361}
362
363void HdCyclesLight::Initialize(HdRenderParam *renderParam)
364{
365 if (_light) {
366 return;
367 }
368
369 const SceneLock lock(renderParam);
370
371 _object = lock.scene->create_node<Object>();
372 _object->name = GetId().GetString();
373
374 if (_lightType == HdPrimTypeTokens->domeLight) {
375 _light = lock.scene->create_node<BackgroundLight>();
376 }
377 else if (_lightType == HdPrimTypeTokens->distantLight) {
378 _light = lock.scene->create_node<SunLight>();
379 }
380 else if (_lightType == HdPrimTypeTokens->diskLight) {
381 _light = lock.scene->create_node<AreaLight>();
382 static_cast<AreaLight *>(_light)->set_ellipse(true);
383 }
384 else if (_lightType == HdPrimTypeTokens->rectLight) {
385 _light = lock.scene->create_node<AreaLight>();
386 static_cast<AreaLight *>(_light)->set_ellipse(false);
387 }
388 else if (_lightType == HdPrimTypeTokens->sphereLight) {
389 /* We can't know in advance if this is spot light or point light, so we set to derived class
390 * SpotLight and change the type later. */
391 _light = lock.scene->create_node<SpotLight>();
392 }
393
394 _light->set_use_mis(true);
395 _light->name = GetId().GetString();
396
397 _object->set_geometry(_light);
398 _object->set_random_id(hash_uint2(hash_string(_light->name.c_str()), 0));
399 _object->set_visibility(PATH_RAY_VISIBILITY_ALL & ~PATH_RAY_VISIBILITY_CAMERA);
400
401 Shader *const shader = lock.scene->create_node<Shader>();
402 array<Node *> used_shaders;
403 used_shaders.push_back_slow(shader);
404 _light->set_used_shaders(used_shaders);
405
406 // Create default shader graph
407 PopulateShaderGraph(HdContainerDataSourceHandle());
408}
409
volatile int lock
void Finalize(PXR_NS::HdRenderParam *renderParam) override
void Sync(PXR_NS::HdSceneDelegate *sceneDelegate, PXR_NS::HdRenderParam *renderParam, PXR_NS::HdDirtyBits *dirtyBits) override
~HdCyclesLight() override
HdCyclesLight(const PXR_NS::SdfPath &sprimId, const PXR_NS::TfToken &lightType)
PXR_NS::HdDirtyBits GetInitialDirtyBitsMask() const override
ShaderOutput * link
ShaderInput * input(const char *name)
ShaderOutput * output(const char *name)
bool has_surface_spatial_varying
void set_graph(unique_ptr< ShaderGraph > &&graph)
void tag_update(Scene *scene)
T GetTypedValue(const PXR_NS::HdContainerDataSourceHandle &container, const PXR_NS::TfToken &name, const T &fallback=T())
PXR_NS::HdTypedSampledDataSource< T >::Handle GetTypedDataSource(const PXR_NS::HdContainerDataSourceHandle &container, const PXR_NS::TfToken &name)
ccl_device_forceinline float3 make_float3(const float x, const float y, const float z)
uint hash_uint2(uint kx, uint ky)
#define exp2
HDCYCLES_NAMESPACE_OPEN_SCOPE Transform convert_transform(const GfMatrix4d &matrix)
#define HDCYCLES_NAMESPACE_CLOSE_SCOPE
TF_DEFINE_PRIVATE_TOKENS(_tokens,(visibleInPrimaryRay)(treatAsPoint)(falloff))
HDCYCLES_NAMESPACE_OPEN_SCOPE HdSceneIndexPrim GetPrim(HdSceneDelegate *delegate, const SdfPath &id)
@ NODE_VECTOR_MATH_MULTIPLY
@ PATH_RAY_VISIBILITY_CAMERA
@ PATH_RAY_VISIBILITY_ALL
@ LIGHT_SPOT
@ LIGHT_POINT
ccl_device_inline float3 one_float3()
Definition math_float3.h:26
CCL_NAMESPACE_BEGIN ccl_device_inline float3 zero_float3()
Definition math_float3.h:17
std::string filename(const std::string_view &str, size_t pos)
constexpr uint64_t hash_string(StringRef str)
Definition BLI_hash.hh:183
#define M_PI_F
ccl_device_inline Transform transform_scale(const float3 s)
Definition transform.h:313
ccl_device_inline void transform_set_column(Transform *t, const int column, const float3 value)
Definition transform.h:392