graph.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  1. /*
  2. * Copyright 2011-2016 Blender Foundation
  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. #include "render/attribute.h"
  17. #include "render/graph.h"
  18. #include "render/nodes.h"
  19. #include "render/scene.h"
  20. #include "render/shader.h"
  21. #include "render/constant_fold.h"
  22. #include "util/util_algorithm.h"
  23. #include "util/util_foreach.h"
  24. #include "util/util_logging.h"
  25. #include "util/util_md5.h"
  26. #include "util/util_queue.h"
  27. CCL_NAMESPACE_BEGIN
  28. namespace {
  29. bool check_node_inputs_has_links(const ShaderNode *node)
  30. {
  31. foreach (const ShaderInput *in, node->inputs) {
  32. if (in->link) {
  33. return true;
  34. }
  35. }
  36. return false;
  37. }
  38. bool check_node_inputs_traversed(const ShaderNode *node, const ShaderNodeSet &done)
  39. {
  40. foreach (const ShaderInput *in, node->inputs) {
  41. if (in->link) {
  42. if (done.find(in->link->parent) == done.end()) {
  43. return false;
  44. }
  45. }
  46. }
  47. return true;
  48. }
  49. } /* namespace */
  50. /* Node */
  51. ShaderNode::ShaderNode(const NodeType *type) : Node(type)
  52. {
  53. name = type->name;
  54. id = -1;
  55. bump = SHADER_BUMP_NONE;
  56. special_type = SHADER_SPECIAL_TYPE_NONE;
  57. create_inputs_outputs(type);
  58. }
  59. ShaderNode::~ShaderNode()
  60. {
  61. foreach (ShaderInput *socket, inputs)
  62. delete socket;
  63. foreach (ShaderOutput *socket, outputs)
  64. delete socket;
  65. }
  66. void ShaderNode::create_inputs_outputs(const NodeType *type)
  67. {
  68. foreach (const SocketType &socket, type->inputs) {
  69. if (socket.flags & SocketType::LINKABLE) {
  70. inputs.push_back(new ShaderInput(socket, this));
  71. }
  72. }
  73. foreach (const SocketType &socket, type->outputs) {
  74. outputs.push_back(new ShaderOutput(socket, this));
  75. }
  76. }
  77. ShaderInput *ShaderNode::input(const char *name)
  78. {
  79. foreach (ShaderInput *socket, inputs) {
  80. if (socket->name() == name)
  81. return socket;
  82. }
  83. return NULL;
  84. }
  85. ShaderOutput *ShaderNode::output(const char *name)
  86. {
  87. foreach (ShaderOutput *socket, outputs)
  88. if (socket->name() == name)
  89. return socket;
  90. return NULL;
  91. }
  92. ShaderInput *ShaderNode::input(ustring name)
  93. {
  94. foreach (ShaderInput *socket, inputs) {
  95. if (socket->name() == name)
  96. return socket;
  97. }
  98. return NULL;
  99. }
  100. ShaderOutput *ShaderNode::output(ustring name)
  101. {
  102. foreach (ShaderOutput *socket, outputs)
  103. if (socket->name() == name)
  104. return socket;
  105. return NULL;
  106. }
  107. void ShaderNode::remove_input(ShaderInput *input)
  108. {
  109. assert(input->link == NULL);
  110. delete input;
  111. inputs.erase(remove(inputs.begin(), inputs.end(), input), inputs.end());
  112. }
  113. void ShaderNode::attributes(Shader *shader, AttributeRequestSet *attributes)
  114. {
  115. foreach (ShaderInput *input, inputs) {
  116. if (!input->link) {
  117. if (input->flags() & SocketType::LINK_TEXTURE_GENERATED) {
  118. if (shader->has_surface)
  119. attributes->add(ATTR_STD_GENERATED);
  120. if (shader->has_volume)
  121. attributes->add(ATTR_STD_GENERATED_TRANSFORM);
  122. }
  123. else if (input->flags() & SocketType::LINK_TEXTURE_UV) {
  124. if (shader->has_surface)
  125. attributes->add(ATTR_STD_UV);
  126. }
  127. }
  128. }
  129. }
  130. bool ShaderNode::equals(const ShaderNode &other)
  131. {
  132. if (type != other.type || bump != other.bump) {
  133. return false;
  134. }
  135. assert(inputs.size() == other.inputs.size());
  136. /* Compare unlinkable sockets */
  137. foreach (const SocketType &socket, type->inputs) {
  138. if (!(socket.flags & SocketType::LINKABLE)) {
  139. if (!Node::equals_value(other, socket)) {
  140. return false;
  141. }
  142. }
  143. }
  144. /* Compare linkable input sockets */
  145. for (int i = 0; i < inputs.size(); ++i) {
  146. ShaderInput *input_a = inputs[i], *input_b = other.inputs[i];
  147. if (input_a->link == NULL && input_b->link == NULL) {
  148. /* Unconnected inputs are expected to have the same value. */
  149. if (!Node::equals_value(other, input_a->socket_type)) {
  150. return false;
  151. }
  152. }
  153. else if (input_a->link != NULL && input_b->link != NULL) {
  154. /* Expect links are to come from the same exact socket. */
  155. if (input_a->link != input_b->link) {
  156. return false;
  157. }
  158. }
  159. else {
  160. /* One socket has a link and another has not, inputs can't be
  161. * considered equal.
  162. */
  163. return false;
  164. }
  165. }
  166. return true;
  167. }
  168. /* Graph */
  169. ShaderGraph::ShaderGraph()
  170. {
  171. finalized = false;
  172. simplified = false;
  173. num_node_ids = 0;
  174. add(new OutputNode());
  175. }
  176. ShaderGraph::~ShaderGraph()
  177. {
  178. clear_nodes();
  179. }
  180. ShaderNode *ShaderGraph::add(ShaderNode *node)
  181. {
  182. assert(!finalized);
  183. simplified = false;
  184. node->id = num_node_ids++;
  185. nodes.push_back(node);
  186. return node;
  187. }
  188. OutputNode *ShaderGraph::output()
  189. {
  190. return (OutputNode *)nodes.front();
  191. }
  192. void ShaderGraph::connect(ShaderOutput *from, ShaderInput *to)
  193. {
  194. assert(!finalized);
  195. assert(from && to);
  196. if (to->link) {
  197. fprintf(stderr, "Cycles shader graph connect: input already connected.\n");
  198. return;
  199. }
  200. if (from->type() != to->type()) {
  201. /* can't do automatic conversion from closure */
  202. if (from->type() == SocketType::CLOSURE) {
  203. fprintf(stderr,
  204. "Cycles shader graph connect: can only connect closure to closure "
  205. "(%s.%s to %s.%s).\n",
  206. from->parent->name.c_str(),
  207. from->name().c_str(),
  208. to->parent->name.c_str(),
  209. to->name().c_str());
  210. return;
  211. }
  212. /* add automatic conversion node in case of type mismatch */
  213. ShaderNode *convert;
  214. ShaderInput *convert_in;
  215. if (to->type() == SocketType::CLOSURE) {
  216. EmissionNode *emission = new EmissionNode();
  217. emission->color = make_float3(1.0f, 1.0f, 1.0f);
  218. emission->strength = 1.0f;
  219. convert = add(emission);
  220. /* Connect float inputs to Strength to save an additional Falue->Color conversion. */
  221. if (from->type() == SocketType::FLOAT) {
  222. convert_in = convert->input("Strength");
  223. }
  224. else {
  225. convert_in = convert->input("Color");
  226. }
  227. }
  228. else {
  229. convert = add(new ConvertNode(from->type(), to->type(), true));
  230. convert_in = convert->inputs[0];
  231. }
  232. connect(from, convert_in);
  233. connect(convert->outputs[0], to);
  234. }
  235. else {
  236. /* types match, just connect */
  237. to->link = from;
  238. from->links.push_back(to);
  239. }
  240. }
  241. void ShaderGraph::disconnect(ShaderOutput *from)
  242. {
  243. assert(!finalized);
  244. simplified = false;
  245. foreach (ShaderInput *sock, from->links) {
  246. sock->link = NULL;
  247. }
  248. from->links.clear();
  249. }
  250. void ShaderGraph::disconnect(ShaderInput *to)
  251. {
  252. assert(!finalized);
  253. assert(to->link);
  254. simplified = false;
  255. ShaderOutput *from = to->link;
  256. to->link = NULL;
  257. from->links.erase(remove(from->links.begin(), from->links.end(), to), from->links.end());
  258. }
  259. void ShaderGraph::relink(ShaderInput *from, ShaderInput *to)
  260. {
  261. ShaderOutput *out = from->link;
  262. if (out) {
  263. disconnect(from);
  264. connect(out, to);
  265. }
  266. to->parent->copy_value(to->socket_type, *(from->parent), from->socket_type);
  267. }
  268. void ShaderGraph::relink(ShaderOutput *from, ShaderOutput *to)
  269. {
  270. /* Copy because disconnect modifies this list. */
  271. vector<ShaderInput *> outputs = from->links;
  272. foreach (ShaderInput *sock, outputs) {
  273. disconnect(sock);
  274. if (to)
  275. connect(to, sock);
  276. }
  277. }
  278. void ShaderGraph::relink(ShaderNode *node, ShaderOutput *from, ShaderOutput *to)
  279. {
  280. simplified = false;
  281. /* Copy because disconnect modifies this list */
  282. vector<ShaderInput *> outputs = from->links;
  283. /* Bypass node by moving all links from "from" to "to" */
  284. foreach (ShaderInput *sock, node->inputs) {
  285. if (sock->link)
  286. disconnect(sock);
  287. }
  288. foreach (ShaderInput *sock, outputs) {
  289. disconnect(sock);
  290. if (to)
  291. connect(to, sock);
  292. }
  293. }
  294. void ShaderGraph::simplify(Scene *scene)
  295. {
  296. if (!simplified) {
  297. expand();
  298. default_inputs(scene->shader_manager->use_osl());
  299. clean(scene);
  300. refine_bump_nodes();
  301. simplified = true;
  302. }
  303. }
  304. void ShaderGraph::finalize(Scene *scene, bool do_bump, bool do_simplify, bool bump_in_object_space)
  305. {
  306. /* before compiling, the shader graph may undergo a number of modifications.
  307. * currently we set default geometry shader inputs, and create automatic bump
  308. * from displacement. a graph can be finalized only once, and should not be
  309. * modified afterwards. */
  310. if (!finalized) {
  311. simplify(scene);
  312. if (do_bump)
  313. bump_from_displacement(bump_in_object_space);
  314. ShaderInput *surface_in = output()->input("Surface");
  315. ShaderInput *volume_in = output()->input("Volume");
  316. /* todo: make this work when surface and volume closures are tangled up */
  317. if (surface_in->link)
  318. transform_multi_closure(surface_in->link->parent, NULL, false);
  319. if (volume_in->link)
  320. transform_multi_closure(volume_in->link->parent, NULL, true);
  321. finalized = true;
  322. }
  323. else if (do_simplify) {
  324. simplify_settings(scene);
  325. }
  326. }
  327. void ShaderGraph::find_dependencies(ShaderNodeSet &dependencies, ShaderInput *input)
  328. {
  329. /* find all nodes that this input depends on directly and indirectly */
  330. ShaderNode *node = (input->link) ? input->link->parent : NULL;
  331. if (node != NULL && dependencies.find(node) == dependencies.end()) {
  332. foreach (ShaderInput *in, node->inputs)
  333. find_dependencies(dependencies, in);
  334. dependencies.insert(node);
  335. }
  336. }
  337. void ShaderGraph::clear_nodes()
  338. {
  339. foreach (ShaderNode *node, nodes) {
  340. delete node;
  341. }
  342. nodes.clear();
  343. }
  344. void ShaderGraph::copy_nodes(ShaderNodeSet &nodes, ShaderNodeMap &nnodemap)
  345. {
  346. /* copy a set of nodes, and the links between them. the assumption is
  347. * made that all nodes that inputs are linked to are in the set too. */
  348. /* copy nodes */
  349. foreach (ShaderNode *node, nodes) {
  350. ShaderNode *nnode = node->clone();
  351. nnodemap[node] = nnode;
  352. /* create new inputs and outputs to recreate links and ensure
  353. * that we still point to valid SocketType if the NodeType
  354. * changed in cloning, as it does for OSL nodes */
  355. nnode->inputs.clear();
  356. nnode->outputs.clear();
  357. nnode->create_inputs_outputs(nnode->type);
  358. }
  359. /* recreate links */
  360. foreach (ShaderNode *node, nodes) {
  361. foreach (ShaderInput *input, node->inputs) {
  362. if (input->link) {
  363. /* find new input and output */
  364. ShaderNode *nfrom = nnodemap[input->link->parent];
  365. ShaderNode *nto = nnodemap[input->parent];
  366. ShaderOutput *noutput = nfrom->output(input->link->name());
  367. ShaderInput *ninput = nto->input(input->name());
  368. /* connect */
  369. connect(noutput, ninput);
  370. }
  371. }
  372. }
  373. }
  374. /* Graph simplification */
  375. /* ******************** */
  376. /* Remove proxy nodes.
  377. *
  378. * These only exists temporarily when exporting groups, and we must remove them
  379. * early so that node->attributes() and default links do not see them.
  380. */
  381. void ShaderGraph::remove_proxy_nodes()
  382. {
  383. vector<bool> removed(num_node_ids, false);
  384. bool any_node_removed = false;
  385. foreach (ShaderNode *node, nodes) {
  386. if (node->special_type == SHADER_SPECIAL_TYPE_PROXY) {
  387. ConvertNode *proxy = static_cast<ConvertNode *>(node);
  388. ShaderInput *input = proxy->inputs[0];
  389. ShaderOutput *output = proxy->outputs[0];
  390. /* bypass the proxy node */
  391. if (input->link) {
  392. relink(proxy, output, input->link);
  393. }
  394. else {
  395. /* Copy because disconnect modifies this list */
  396. vector<ShaderInput *> links(output->links);
  397. foreach (ShaderInput *to, links) {
  398. /* remove any autoconvert nodes too if they lead to
  399. * sockets with an automatically set default value */
  400. ShaderNode *tonode = to->parent;
  401. if (tonode->special_type == SHADER_SPECIAL_TYPE_AUTOCONVERT) {
  402. bool all_links_removed = true;
  403. vector<ShaderInput *> links = tonode->outputs[0]->links;
  404. foreach (ShaderInput *autoin, links) {
  405. if (autoin->flags() & SocketType::DEFAULT_LINK_MASK)
  406. disconnect(autoin);
  407. else
  408. all_links_removed = false;
  409. }
  410. if (all_links_removed)
  411. removed[tonode->id] = true;
  412. }
  413. disconnect(to);
  414. /* transfer the default input value to the target socket */
  415. tonode->copy_value(to->socket_type, *proxy, input->socket_type);
  416. }
  417. }
  418. removed[proxy->id] = true;
  419. any_node_removed = true;
  420. }
  421. }
  422. /* remove nodes */
  423. if (any_node_removed) {
  424. list<ShaderNode *> newnodes;
  425. foreach (ShaderNode *node, nodes) {
  426. if (!removed[node->id])
  427. newnodes.push_back(node);
  428. else
  429. delete node;
  430. }
  431. nodes = newnodes;
  432. }
  433. }
  434. /* Constant folding.
  435. *
  436. * Try to constant fold some nodes, and pipe result directly to
  437. * the input socket of connected nodes.
  438. */
  439. void ShaderGraph::constant_fold(Scene *scene)
  440. {
  441. ShaderNodeSet done, scheduled;
  442. queue<ShaderNode *> traverse_queue;
  443. bool has_displacement = (output()->input("Displacement")->link != NULL);
  444. /* Schedule nodes which doesn't have any dependencies. */
  445. foreach (ShaderNode *node, nodes) {
  446. if (!check_node_inputs_has_links(node)) {
  447. traverse_queue.push(node);
  448. scheduled.insert(node);
  449. }
  450. }
  451. while (!traverse_queue.empty()) {
  452. ShaderNode *node = traverse_queue.front();
  453. traverse_queue.pop();
  454. done.insert(node);
  455. foreach (ShaderOutput *output, node->outputs) {
  456. if (output->links.size() == 0) {
  457. continue;
  458. }
  459. /* Schedule node which was depending on the value,
  460. * when possible. Do it before disconnect.
  461. */
  462. foreach (ShaderInput *input, output->links) {
  463. if (scheduled.find(input->parent) != scheduled.end()) {
  464. /* Node might not be optimized yet but scheduled already
  465. * by other dependencies. No need to re-schedule it.
  466. */
  467. continue;
  468. }
  469. /* Schedule node if its inputs are fully done. */
  470. if (check_node_inputs_traversed(input->parent, done)) {
  471. traverse_queue.push(input->parent);
  472. scheduled.insert(input->parent);
  473. }
  474. }
  475. /* Optimize current node. */
  476. ConstantFolder folder(this, node, output, scene);
  477. node->constant_fold(folder);
  478. }
  479. }
  480. /* Folding might have removed all nodes connected to the displacement output
  481. * even tho there is displacement to be applied, so add in a value node if
  482. * that happens to ensure there is still a valid graph for displacement.
  483. */
  484. if (has_displacement && !output()->input("Displacement")->link) {
  485. ColorNode *value = (ColorNode *)add(new ColorNode());
  486. value->value = output()->displacement;
  487. connect(value->output("Color"), output()->input("Displacement"));
  488. }
  489. }
  490. /* Simplification. */
  491. void ShaderGraph::simplify_settings(Scene *scene)
  492. {
  493. foreach (ShaderNode *node, nodes) {
  494. node->simplify_settings(scene);
  495. }
  496. }
  497. /* Deduplicate nodes with same settings. */
  498. void ShaderGraph::deduplicate_nodes()
  499. {
  500. /* NOTES:
  501. * - Deduplication happens for nodes which has same exact settings and same
  502. * exact input links configuration (either connected to same output or has
  503. * the same exact default value).
  504. * - Deduplication happens in the bottom-top manner, so we know for fact that
  505. * all traversed nodes are either can not be deduplicated at all or were
  506. * already deduplicated.
  507. */
  508. ShaderNodeSet scheduled, done;
  509. map<ustring, ShaderNodeSet> candidates;
  510. queue<ShaderNode *> traverse_queue;
  511. int num_deduplicated = 0;
  512. /* Schedule nodes which doesn't have any dependencies. */
  513. foreach (ShaderNode *node, nodes) {
  514. if (!check_node_inputs_has_links(node)) {
  515. traverse_queue.push(node);
  516. scheduled.insert(node);
  517. }
  518. }
  519. while (!traverse_queue.empty()) {
  520. ShaderNode *node = traverse_queue.front();
  521. traverse_queue.pop();
  522. done.insert(node);
  523. /* Schedule the nodes which were depending on the current node. */
  524. bool has_output_links = false;
  525. foreach (ShaderOutput *output, node->outputs) {
  526. foreach (ShaderInput *input, output->links) {
  527. has_output_links = true;
  528. if (scheduled.find(input->parent) != scheduled.end()) {
  529. /* Node might not be optimized yet but scheduled already
  530. * by other dependencies. No need to re-schedule it.
  531. */
  532. continue;
  533. }
  534. /* Schedule node if its inputs are fully done. */
  535. if (check_node_inputs_traversed(input->parent, done)) {
  536. traverse_queue.push(input->parent);
  537. scheduled.insert(input->parent);
  538. }
  539. }
  540. }
  541. /* Only need to care about nodes that are actually used */
  542. if (!has_output_links) {
  543. continue;
  544. }
  545. /* Try to merge this node with another one. */
  546. ShaderNode *merge_with = NULL;
  547. foreach (ShaderNode *other_node, candidates[node->type->name]) {
  548. if (node != other_node && node->equals(*other_node)) {
  549. merge_with = other_node;
  550. break;
  551. }
  552. }
  553. /* If found an equivalent, merge; otherwise keep node for later merges */
  554. if (merge_with != NULL) {
  555. for (int i = 0; i < node->outputs.size(); ++i) {
  556. relink(node, node->outputs[i], merge_with->outputs[i]);
  557. }
  558. num_deduplicated++;
  559. }
  560. else {
  561. candidates[node->type->name].insert(node);
  562. }
  563. }
  564. if (num_deduplicated > 0) {
  565. VLOG(1) << "Deduplicated " << num_deduplicated << " nodes.";
  566. }
  567. }
  568. /* Check whether volume output has meaningful nodes, otherwise
  569. * disconnect the output.
  570. */
  571. void ShaderGraph::verify_volume_output()
  572. {
  573. /* Check whether we can optimize the whole volume graph out. */
  574. ShaderInput *volume_in = output()->input("Volume");
  575. if (volume_in->link == NULL) {
  576. return;
  577. }
  578. bool has_valid_volume = false;
  579. ShaderNodeSet scheduled;
  580. queue<ShaderNode *> traverse_queue;
  581. /* Schedule volume output. */
  582. traverse_queue.push(volume_in->link->parent);
  583. scheduled.insert(volume_in->link->parent);
  584. /* Traverse down the tree. */
  585. while (!traverse_queue.empty()) {
  586. ShaderNode *node = traverse_queue.front();
  587. traverse_queue.pop();
  588. /* Node is fully valid for volume, can't optimize anything out. */
  589. if (node->has_volume_support()) {
  590. has_valid_volume = true;
  591. break;
  592. }
  593. foreach (ShaderInput *input, node->inputs) {
  594. if (input->link == NULL) {
  595. continue;
  596. }
  597. if (scheduled.find(input->link->parent) != scheduled.end()) {
  598. continue;
  599. }
  600. traverse_queue.push(input->link->parent);
  601. scheduled.insert(input->link->parent);
  602. }
  603. }
  604. if (!has_valid_volume) {
  605. VLOG(1) << "Disconnect meaningless volume output.";
  606. disconnect(volume_in->link);
  607. }
  608. }
  609. void ShaderGraph::break_cycles(ShaderNode *node, vector<bool> &visited, vector<bool> &on_stack)
  610. {
  611. visited[node->id] = true;
  612. on_stack[node->id] = true;
  613. foreach (ShaderInput *input, node->inputs) {
  614. if (input->link) {
  615. ShaderNode *depnode = input->link->parent;
  616. if (on_stack[depnode->id]) {
  617. /* break cycle */
  618. disconnect(input);
  619. fprintf(stderr, "Cycles shader graph: detected cycle in graph, connection removed.\n");
  620. }
  621. else if (!visited[depnode->id]) {
  622. /* visit dependencies */
  623. break_cycles(depnode, visited, on_stack);
  624. }
  625. }
  626. }
  627. on_stack[node->id] = false;
  628. }
  629. void ShaderGraph::compute_displacement_hash()
  630. {
  631. /* Compute hash of all nodes linked to displacement, to detect if we need
  632. * to recompute displacement when shader nodes change. */
  633. ShaderInput *displacement_in = output()->input("Displacement");
  634. if (!displacement_in->link) {
  635. displacement_hash = "";
  636. return;
  637. }
  638. ShaderNodeSet nodes_displace;
  639. find_dependencies(nodes_displace, displacement_in);
  640. MD5Hash md5;
  641. foreach (ShaderNode *node, nodes_displace) {
  642. node->hash(md5);
  643. foreach (ShaderInput *input, node->inputs) {
  644. int link_id = (input->link) ? input->link->parent->id : 0;
  645. md5.append((uint8_t *)&link_id, sizeof(link_id));
  646. }
  647. if (node->special_type == SHADER_SPECIAL_TYPE_OSL) {
  648. /* Hash takes into account socket values, to detect changes
  649. * in the code of the node we need an exception. */
  650. OSLNode *oslnode = static_cast<OSLNode *>(node);
  651. md5.append(oslnode->bytecode_hash);
  652. }
  653. }
  654. displacement_hash = md5.get_hex();
  655. }
  656. void ShaderGraph::clean(Scene *scene)
  657. {
  658. /* Graph simplification */
  659. /* NOTE: Remove proxy nodes was already done. */
  660. constant_fold(scene);
  661. simplify_settings(scene);
  662. deduplicate_nodes();
  663. verify_volume_output();
  664. /* we do two things here: find cycles and break them, and remove unused
  665. * nodes that don't feed into the output. how cycles are broken is
  666. * undefined, they are invalid input, the important thing is to not crash */
  667. vector<bool> visited(num_node_ids, false);
  668. vector<bool> on_stack(num_node_ids, false);
  669. /* break cycles */
  670. break_cycles(output(), visited, on_stack);
  671. /* disconnect unused nodes */
  672. foreach (ShaderNode *node, nodes) {
  673. if (!visited[node->id]) {
  674. foreach (ShaderInput *to, node->inputs) {
  675. ShaderOutput *from = to->link;
  676. if (from) {
  677. to->link = NULL;
  678. from->links.erase(remove(from->links.begin(), from->links.end(), to), from->links.end());
  679. }
  680. }
  681. }
  682. }
  683. /* remove unused nodes */
  684. list<ShaderNode *> newnodes;
  685. foreach (ShaderNode *node, nodes) {
  686. if (visited[node->id])
  687. newnodes.push_back(node);
  688. else
  689. delete node;
  690. }
  691. nodes = newnodes;
  692. }
  693. void ShaderGraph::expand()
  694. {
  695. /* Call expand on all nodes, to generate additional nodes. */
  696. foreach (ShaderNode *node, nodes) {
  697. node->expand(this);
  698. }
  699. }
  700. void ShaderGraph::default_inputs(bool do_osl)
  701. {
  702. /* nodes can specify default texture coordinates, for now we give
  703. * everything the position by default, except for the sky texture */
  704. ShaderNode *geom = NULL;
  705. ShaderNode *texco = NULL;
  706. foreach (ShaderNode *node, nodes) {
  707. foreach (ShaderInput *input, node->inputs) {
  708. if (!input->link && (!(input->flags() & SocketType::OSL_INTERNAL) || do_osl)) {
  709. if (input->flags() & SocketType::LINK_TEXTURE_GENERATED) {
  710. if (!texco)
  711. texco = new TextureCoordinateNode();
  712. connect(texco->output("Generated"), input);
  713. }
  714. if (input->flags() & SocketType::LINK_TEXTURE_NORMAL) {
  715. if (!texco)
  716. texco = new TextureCoordinateNode();
  717. connect(texco->output("Normal"), input);
  718. }
  719. else if (input->flags() & SocketType::LINK_TEXTURE_UV) {
  720. if (!texco)
  721. texco = new TextureCoordinateNode();
  722. connect(texco->output("UV"), input);
  723. }
  724. else if (input->flags() & SocketType::LINK_INCOMING) {
  725. if (!geom)
  726. geom = new GeometryNode();
  727. connect(geom->output("Incoming"), input);
  728. }
  729. else if (input->flags() & SocketType::LINK_NORMAL) {
  730. if (!geom)
  731. geom = new GeometryNode();
  732. connect(geom->output("Normal"), input);
  733. }
  734. else if (input->flags() & SocketType::LINK_POSITION) {
  735. if (!geom)
  736. geom = new GeometryNode();
  737. connect(geom->output("Position"), input);
  738. }
  739. else if (input->flags() & SocketType::LINK_TANGENT) {
  740. if (!geom)
  741. geom = new GeometryNode();
  742. connect(geom->output("Tangent"), input);
  743. }
  744. }
  745. }
  746. }
  747. if (geom)
  748. add(geom);
  749. if (texco)
  750. add(texco);
  751. }
  752. void ShaderGraph::refine_bump_nodes()
  753. {
  754. /* we transverse the node graph looking for bump nodes, when we find them,
  755. * like in bump_from_displacement(), we copy the sub-graph defined from "bump"
  756. * input to the inputs "center","dx" and "dy" What is in "bump" input is moved
  757. * to "center" input. */
  758. foreach (ShaderNode *node, nodes) {
  759. if (node->special_type == SHADER_SPECIAL_TYPE_BUMP && node->input("Height")->link) {
  760. ShaderInput *bump_input = node->input("Height");
  761. ShaderNodeSet nodes_bump;
  762. /* make 2 extra copies of the subgraph defined in Bump input */
  763. ShaderNodeMap nodes_dx;
  764. ShaderNodeMap nodes_dy;
  765. /* find dependencies for the given input */
  766. find_dependencies(nodes_bump, bump_input);
  767. copy_nodes(nodes_bump, nodes_dx);
  768. copy_nodes(nodes_bump, nodes_dy);
  769. /* mark nodes to indicate they are use for bump computation, so
  770. that any texture coordinates are shifted by dx/dy when sampling */
  771. foreach (ShaderNode *node, nodes_bump)
  772. node->bump = SHADER_BUMP_CENTER;
  773. foreach (NodePair &pair, nodes_dx)
  774. pair.second->bump = SHADER_BUMP_DX;
  775. foreach (NodePair &pair, nodes_dy)
  776. pair.second->bump = SHADER_BUMP_DY;
  777. ShaderOutput *out = bump_input->link;
  778. ShaderOutput *out_dx = nodes_dx[out->parent]->output(out->name());
  779. ShaderOutput *out_dy = nodes_dy[out->parent]->output(out->name());
  780. connect(out_dx, node->input("SampleX"));
  781. connect(out_dy, node->input("SampleY"));
  782. /* add generated nodes */
  783. foreach (NodePair &pair, nodes_dx)
  784. add(pair.second);
  785. foreach (NodePair &pair, nodes_dy)
  786. add(pair.second);
  787. /* connect what is connected is bump to samplecenter input*/
  788. connect(out, node->input("SampleCenter"));
  789. /* bump input is just for connectivity purpose for the graph input,
  790. * we re-connected this input to samplecenter, so lets disconnect it
  791. * from bump input */
  792. disconnect(bump_input);
  793. }
  794. }
  795. }
  796. void ShaderGraph::bump_from_displacement(bool use_object_space)
  797. {
  798. /* generate bump mapping automatically from displacement. bump mapping is
  799. * done using a 3-tap filter, computing the displacement at the center,
  800. * and two other positions shifted by ray differentials.
  801. *
  802. * since the input to displacement is a node graph, we need to ensure that
  803. * all texture coordinates use are shift by the ray differentials. for this
  804. * reason we make 3 copies of the node subgraph defining the displacement,
  805. * with each different geometry and texture coordinate nodes that generate
  806. * different shifted coordinates.
  807. *
  808. * these 3 displacement values are then fed into the bump node, which will
  809. * output the perturbed normal. */
  810. ShaderInput *displacement_in = output()->input("Displacement");
  811. if (!displacement_in->link)
  812. return;
  813. /* find dependencies for the given input */
  814. ShaderNodeSet nodes_displace;
  815. find_dependencies(nodes_displace, displacement_in);
  816. /* copy nodes for 3 bump samples */
  817. ShaderNodeMap nodes_center;
  818. ShaderNodeMap nodes_dx;
  819. ShaderNodeMap nodes_dy;
  820. copy_nodes(nodes_displace, nodes_center);
  821. copy_nodes(nodes_displace, nodes_dx);
  822. copy_nodes(nodes_displace, nodes_dy);
  823. /* mark nodes to indicate they are use for bump computation, so
  824. * that any texture coordinates are shifted by dx/dy when sampling */
  825. foreach (NodePair &pair, nodes_center)
  826. pair.second->bump = SHADER_BUMP_CENTER;
  827. foreach (NodePair &pair, nodes_dx)
  828. pair.second->bump = SHADER_BUMP_DX;
  829. foreach (NodePair &pair, nodes_dy)
  830. pair.second->bump = SHADER_BUMP_DY;
  831. /* add set normal node and connect the bump normal ouput to the set normal
  832. * output, so it can finally set the shader normal, note we are only doing
  833. * this for bump from displacement, this will be the only bump allowed to
  834. * overwrite the shader normal */
  835. ShaderNode *set_normal = add(new SetNormalNode());
  836. /* add bump node and connect copied graphs to it */
  837. BumpNode *bump = (BumpNode *)add(new BumpNode());
  838. bump->use_object_space = use_object_space;
  839. bump->distance = 1.0f;
  840. ShaderOutput *out = displacement_in->link;
  841. ShaderOutput *out_center = nodes_center[out->parent]->output(out->name());
  842. ShaderOutput *out_dx = nodes_dx[out->parent]->output(out->name());
  843. ShaderOutput *out_dy = nodes_dy[out->parent]->output(out->name());
  844. /* convert displacement vector to height */
  845. VectorMathNode *dot_center = (VectorMathNode *)add(new VectorMathNode());
  846. VectorMathNode *dot_dx = (VectorMathNode *)add(new VectorMathNode());
  847. VectorMathNode *dot_dy = (VectorMathNode *)add(new VectorMathNode());
  848. dot_center->type = NODE_VECTOR_MATH_DOT_PRODUCT;
  849. dot_dx->type = NODE_VECTOR_MATH_DOT_PRODUCT;
  850. dot_dy->type = NODE_VECTOR_MATH_DOT_PRODUCT;
  851. GeometryNode *geom = (GeometryNode *)add(new GeometryNode());
  852. connect(geom->output("Normal"), dot_center->input("Vector2"));
  853. connect(geom->output("Normal"), dot_dx->input("Vector2"));
  854. connect(geom->output("Normal"), dot_dy->input("Vector2"));
  855. connect(out_center, dot_center->input("Vector1"));
  856. connect(out_dx, dot_dx->input("Vector1"));
  857. connect(out_dy, dot_dy->input("Vector1"));
  858. connect(dot_center->output("Value"), bump->input("SampleCenter"));
  859. connect(dot_dx->output("Value"), bump->input("SampleX"));
  860. connect(dot_dy->output("Value"), bump->input("SampleY"));
  861. /* connect the bump out to the set normal in: */
  862. connect(bump->output("Normal"), set_normal->input("Direction"));
  863. /* connect to output node */
  864. connect(set_normal->output("Normal"), output()->input("Normal"));
  865. /* finally, add the copied nodes to the graph. we can't do this earlier
  866. * because we would create dependency cycles in the above loop */
  867. foreach (NodePair &pair, nodes_center)
  868. add(pair.second);
  869. foreach (NodePair &pair, nodes_dx)
  870. add(pair.second);
  871. foreach (NodePair &pair, nodes_dy)
  872. add(pair.second);
  873. }
  874. void ShaderGraph::transform_multi_closure(ShaderNode *node, ShaderOutput *weight_out, bool volume)
  875. {
  876. /* for SVM in multi closure mode, this transforms the shader mix/add part of
  877. * the graph into nodes that feed weights into closure nodes. this is too
  878. * avoid building a closure tree and then flattening it, and instead write it
  879. * directly to an array */
  880. if (node->special_type == SHADER_SPECIAL_TYPE_COMBINE_CLOSURE) {
  881. ShaderInput *fin = node->input("Fac");
  882. ShaderInput *cl1in = node->input("Closure1");
  883. ShaderInput *cl2in = node->input("Closure2");
  884. ShaderOutput *weight1_out, *weight2_out;
  885. if (fin) {
  886. /* mix closure: add node to mix closure weights */
  887. MixClosureWeightNode *mix_node = new MixClosureWeightNode();
  888. add(mix_node);
  889. ShaderInput *fac_in = mix_node->input("Fac");
  890. ShaderInput *weight_in = mix_node->input("Weight");
  891. if (fin->link)
  892. connect(fin->link, fac_in);
  893. else
  894. mix_node->fac = node->get_float(fin->socket_type);
  895. if (weight_out)
  896. connect(weight_out, weight_in);
  897. weight1_out = mix_node->output("Weight1");
  898. weight2_out = mix_node->output("Weight2");
  899. }
  900. else {
  901. /* add closure: just pass on any weights */
  902. weight1_out = weight_out;
  903. weight2_out = weight_out;
  904. }
  905. if (cl1in->link)
  906. transform_multi_closure(cl1in->link->parent, weight1_out, volume);
  907. if (cl2in->link)
  908. transform_multi_closure(cl2in->link->parent, weight2_out, volume);
  909. }
  910. else {
  911. ShaderInput *weight_in = node->input((volume) ? "VolumeMixWeight" : "SurfaceMixWeight");
  912. /* not a closure node? */
  913. if (!weight_in)
  914. return;
  915. /* already has a weight connected to it? add weights */
  916. float weight_value = node->get_float(weight_in->socket_type);
  917. if (weight_in->link || weight_value != 0.0f) {
  918. MathNode *math_node = new MathNode();
  919. add(math_node);
  920. if (weight_in->link)
  921. connect(weight_in->link, math_node->input("Value1"));
  922. else
  923. math_node->value1 = weight_value;
  924. if (weight_out)
  925. connect(weight_out, math_node->input("Value2"));
  926. else
  927. math_node->value2 = 1.0f;
  928. weight_out = math_node->output("Value");
  929. if (weight_in->link)
  930. disconnect(weight_in);
  931. }
  932. /* connected to closure mix weight */
  933. if (weight_out)
  934. connect(weight_out, weight_in);
  935. else
  936. node->set(weight_in->socket_type, weight_value + 1.0f);
  937. }
  938. }
  939. int ShaderGraph::get_num_closures()
  940. {
  941. int num_closures = 0;
  942. foreach (ShaderNode *node, nodes) {
  943. ClosureType closure_type = node->get_closure_type();
  944. if (closure_type == CLOSURE_NONE_ID) {
  945. continue;
  946. }
  947. else if (CLOSURE_IS_BSSRDF(closure_type)) {
  948. num_closures += 3;
  949. }
  950. else if (CLOSURE_IS_GLASS(closure_type)) {
  951. num_closures += 2;
  952. }
  953. else if (CLOSURE_IS_BSDF_MULTISCATTER(closure_type)) {
  954. num_closures += 2;
  955. }
  956. else if (CLOSURE_IS_PRINCIPLED(closure_type)) {
  957. num_closures += 8;
  958. }
  959. else if (CLOSURE_IS_VOLUME(closure_type)) {
  960. num_closures += VOLUME_STACK_SIZE;
  961. }
  962. else if (closure_type == CLOSURE_BSDF_HAIR_PRINCIPLED_ID) {
  963. num_closures += 4;
  964. }
  965. else {
  966. ++num_closures;
  967. }
  968. }
  969. return num_closures;
  970. }
  971. void ShaderGraph::dump_graph(const char *filename)
  972. {
  973. FILE *fd = fopen(filename, "w");
  974. if (fd == NULL) {
  975. printf("Error opening file for dumping the graph: %s\n", filename);
  976. return;
  977. }
  978. fprintf(fd, "digraph shader_graph {\n");
  979. fprintf(fd, "ranksep=1.5\n");
  980. fprintf(fd, "rankdir=LR\n");
  981. fprintf(fd, "splines=false\n");
  982. foreach (ShaderNode *node, nodes) {
  983. fprintf(fd, "// NODE: %p\n", node);
  984. fprintf(fd, "\"%p\" [shape=record,label=\"{", node);
  985. if (node->inputs.size()) {
  986. fprintf(fd, "{");
  987. foreach (ShaderInput *socket, node->inputs) {
  988. if (socket != node->inputs[0]) {
  989. fprintf(fd, "|");
  990. }
  991. fprintf(fd, "<IN_%p>%s", socket, socket->name().c_str());
  992. }
  993. fprintf(fd, "}|");
  994. }
  995. fprintf(fd, "%s", node->name.c_str());
  996. if (node->bump == SHADER_BUMP_CENTER) {
  997. fprintf(fd, " (bump:center)");
  998. }
  999. else if (node->bump == SHADER_BUMP_DX) {
  1000. fprintf(fd, " (bump:dx)");
  1001. }
  1002. else if (node->bump == SHADER_BUMP_DY) {
  1003. fprintf(fd, " (bump:dy)");
  1004. }
  1005. if (node->outputs.size()) {
  1006. fprintf(fd, "|{");
  1007. foreach (ShaderOutput *socket, node->outputs) {
  1008. if (socket != node->outputs[0]) {
  1009. fprintf(fd, "|");
  1010. }
  1011. fprintf(fd, "<OUT_%p>%s", socket, socket->name().c_str());
  1012. }
  1013. fprintf(fd, "}");
  1014. }
  1015. fprintf(fd, "}\"]");
  1016. }
  1017. foreach (ShaderNode *node, nodes) {
  1018. foreach (ShaderOutput *output, node->outputs) {
  1019. foreach (ShaderInput *input, output->links) {
  1020. fprintf(fd,
  1021. "// CONNECTION: OUT_%p->IN_%p (%s:%s)\n",
  1022. output,
  1023. input,
  1024. output->name().c_str(),
  1025. input->name().c_str());
  1026. fprintf(fd,
  1027. "\"%p\":\"OUT_%p\":e -> \"%p\":\"IN_%p\":w [label=\"\"]\n",
  1028. output->parent,
  1029. output,
  1030. input->parent,
  1031. input);
  1032. }
  1033. }
  1034. }
  1035. fprintf(fd, "}\n");
  1036. fclose(fd);
  1037. }
  1038. CCL_NAMESPACE_END