Cycles: Remove unneeded include statements
[blender-staging.git] / intern / cycles / app / cycles_xml.cpp
1 /*
2  * Copyright 2011-2013 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
17 #include <stdio.h>
18
19 #include <sstream>
20 #include <algorithm>
21 #include <iterator>
22
23 #include "graph/node_xml.h"
24
25 #include "render/background.h"
26 #include "render/camera.h"
27 #include "render/film.h"
28 #include "render/graph.h"
29 #include "render/integrator.h"
30 #include "render/light.h"
31 #include "render/mesh.h"
32 #include "render/nodes.h"
33 #include "render/object.h"
34 #include "render/osl.h"
35 #include "render/shader.h"
36 #include "render/scene.h"
37
38 #include "subd/subd_patch.h"
39 #include "subd/subd_split.h"
40
41 #include "util/util_foreach.h"
42 #include "util/util_path.h"
43 #include "util/util_transform.h"
44 #include "util/util_xml.h"
45
46 #include "app/cycles_xml.h"
47
48 CCL_NAMESPACE_BEGIN
49
50 /* XML reading state */
51
52 struct XMLReadState : public XMLReader {
53         Scene *scene;           /* scene pointer */
54         Transform tfm;          /* current transform state */
55         bool smooth;            /* smooth normal state */
56         Shader *shader;         /* current shader */
57         string base;            /* base path to current file*/
58         float dicing_rate;      /* current dicing rate */
59
60         XMLReadState()
61           : scene(NULL),
62             smooth(false),
63             shader(NULL),
64             dicing_rate(1.0f)
65         {
66                 tfm = transform_identity();
67         }
68 };
69
70 /* Attribute Reading */
71
72 static bool xml_read_int(int *value, xml_node node, const char *name)
73 {
74         xml_attribute attr = node.attribute(name);
75
76         if(attr) {
77                 *value = atoi(attr.value());
78                 return true;
79         }
80
81         return false;
82 }
83
84 static bool xml_read_int_array(vector<int>& value, xml_node node, const char *name)
85 {
86         xml_attribute attr = node.attribute(name);
87
88         if(attr) {
89                 vector<string> tokens;
90                 string_split(tokens, attr.value());
91
92                 foreach(const string& token, tokens)
93                         value.push_back(atoi(token.c_str()));
94
95                 return true;
96         }
97
98         return false;
99 }
100
101 static bool xml_read_float(float *value, xml_node node, const char *name)
102 {
103         xml_attribute attr = node.attribute(name);
104
105         if(attr) {
106                 *value = (float)atof(attr.value());
107                 return true;
108         }
109
110         return false;
111 }
112
113 static bool xml_read_float_array(vector<float>& value, xml_node node, const char *name)
114 {
115         xml_attribute attr = node.attribute(name);
116
117         if(attr) {
118                 vector<string> tokens;
119                 string_split(tokens, attr.value());
120
121                 foreach(const string& token, tokens)
122                         value.push_back((float)atof(token.c_str()));
123
124                 return true;
125         }
126
127         return false;
128 }
129
130 static bool xml_read_float3(float3 *value, xml_node node, const char *name)
131 {
132         vector<float> array;
133
134         if(xml_read_float_array(array, node, name) && array.size() == 3) {
135                 *value = make_float3(array[0], array[1], array[2]);
136                 return true;
137         }
138
139         return false;
140 }
141
142 static bool xml_read_float3_array(vector<float3>& value, xml_node node, const char *name)
143 {
144         vector<float> array;
145
146         if(xml_read_float_array(array, node, name)) {
147                 for(size_t i = 0; i < array.size(); i += 3)
148                         value.push_back(make_float3(array[i+0], array[i+1], array[i+2]));
149
150                 return true;
151         }
152
153         return false;
154 }
155
156 static bool xml_read_float4(float4 *value, xml_node node, const char *name)
157 {
158         vector<float> array;
159
160         if(xml_read_float_array(array, node, name) && array.size() == 4) {
161                 *value = make_float4(array[0], array[1], array[2], array[3]);
162                 return true;
163         }
164
165         return false;
166 }
167
168 static bool xml_read_string(string *str, xml_node node, const char *name)
169 {
170         xml_attribute attr = node.attribute(name);
171
172         if(attr) {
173                 *str = attr.value();
174                 return true;
175         }
176
177         return false;
178 }
179
180 static bool xml_equal_string(xml_node node, const char *name, const char *value)
181 {
182         xml_attribute attr = node.attribute(name);
183
184         if(attr)
185                 return string_iequals(attr.value(), value);
186         
187         return false;
188 }
189
190 /* Camera */
191
192 static void xml_read_camera(XMLReadState& state, xml_node node)
193 {
194         Camera *cam = state.scene->camera;
195
196         xml_read_int(&cam->width, node, "width");
197         xml_read_int(&cam->height, node, "height");
198
199         cam->full_width = cam->width;
200         cam->full_height = cam->height;
201
202         xml_read_node(state, cam, node);
203
204         cam->matrix = state.tfm;
205
206         cam->need_update = true;
207         cam->update();
208 }
209
210 /* Shader */
211
212 static void xml_read_shader_graph(XMLReadState& state, Shader *shader, xml_node graph_node)
213 {
214         xml_read_node(state, shader, graph_node);
215
216         ShaderGraph *graph = new ShaderGraph();
217
218         /* local state, shader nodes can't link to nodes outside the shader graph */
219         XMLReader graph_reader;
220         graph_reader.node_map[ustring("output")] = graph->output();
221
222         for(xml_node node = graph_node.first_child(); node; node = node.next_sibling()) {
223                 ustring node_name(node.name());
224
225                 if(node_name == "connect") {
226                         /* connect nodes */
227                         vector<string> from_tokens, to_tokens;
228
229                         string_split(from_tokens, node.attribute("from").value());
230                         string_split(to_tokens, node.attribute("to").value());
231
232                         if(from_tokens.size() == 2 && to_tokens.size() == 2) {
233                                 ustring from_node_name(from_tokens[0]);
234                                 ustring from_socket_name(from_tokens[1]);
235                                 ustring to_node_name(to_tokens[0]);
236                                 ustring to_socket_name(to_tokens[1]);
237
238                                 /* find nodes and sockets */
239                                 ShaderOutput *output = NULL;
240                                 ShaderInput *input = NULL;
241
242                                 if(graph_reader.node_map.find(from_node_name) != graph_reader.node_map.end()) {
243                                         ShaderNode *fromnode = (ShaderNode*)graph_reader.node_map[from_node_name];
244
245                                         foreach(ShaderOutput *out, fromnode->outputs)
246                                                 if(string_iequals(out->socket_type.name.string(), from_socket_name.string()))
247                                                         output = out;
248
249                                         if(!output)
250                                                 fprintf(stderr, "Unknown output socket name \"%s\" on \"%s\".\n", from_node_name.c_str(), from_socket_name.c_str());
251                                 }
252                                 else
253                                         fprintf(stderr, "Unknown shader node name \"%s\".\n", from_node_name.c_str());
254
255                                 if(graph_reader.node_map.find(to_node_name) != graph_reader.node_map.end()) {
256                                         ShaderNode *tonode = (ShaderNode*)graph_reader.node_map[to_node_name];
257
258                                         foreach(ShaderInput *in, tonode->inputs)
259                                                 if(string_iequals(in->socket_type.name.string(), to_socket_name.string()))
260                                                         input = in;
261
262                                         if(!input)
263                                                 fprintf(stderr, "Unknown input socket name \"%s\" on \"%s\".\n", to_socket_name.c_str(), to_node_name.c_str());
264                                 }
265                                 else
266                                         fprintf(stderr, "Unknown shader node name \"%s\".\n", to_node_name.c_str());
267
268                                 /* connect */
269                                 if(output && input)
270                                         graph->connect(output, input);
271                         }
272                         else
273                                 fprintf(stderr, "Invalid from or to value for connect node.\n");
274
275                         continue;
276                 }
277
278                 ShaderNode *snode = NULL;
279
280 #ifdef WITH_OSL
281                 if(node_name == "osl_shader") {
282                         ShaderManager *manager = state.scene->shader_manager;
283
284                         if(manager->use_osl()) {
285                                 std::string filepath;
286
287                                 if(xml_read_string(&filepath, node, "src")) {
288                                         if(path_is_relative(filepath)) {
289                                                 filepath = path_join(state.base, filepath);
290                                         }
291
292                                         snode = ((OSLShaderManager*)manager)->osl_node(filepath);
293
294                                         if(!snode) {
295                                                 fprintf(stderr, "Failed to create OSL node from \"%s\".\n", filepath.c_str());
296                                                 continue;
297                                         }
298                                 }
299                                 else {
300                                         fprintf(stderr, "OSL node missing \"src\" attribute.\n");
301                                         continue;
302                                 }
303                         }
304                         else {
305                                 fprintf(stderr, "OSL node without using --shadingsys osl.\n");
306                                 continue;
307                         }
308                 }
309                 else
310 #endif
311                 {
312                         /* exception for name collision */
313                         if(node_name == "background")
314                                 node_name = "background_shader";
315
316                         const NodeType *node_type = NodeType::find(node_name);
317
318                         if(!node_type) {
319                                 fprintf(stderr, "Unknown shader node \"%s\".\n", node.name());
320                                 continue;
321                         }
322                         else if(node_type->type != NodeType::SHADER) {
323                                 fprintf(stderr, "Node type \"%s\" is not a shader node.\n", node_type->name.c_str());
324                                 continue;
325                         }
326
327                         snode = (ShaderNode*) node_type->create(node_type);
328                 }
329
330                 xml_read_node(graph_reader, snode, node);
331
332                 if(node_name == "image_texture") {
333                         ImageTextureNode *img = (ImageTextureNode*) snode;
334                         img->filename = path_join(state.base, img->filename.string());
335                 }
336                 else if(node_name == "environment_texture") {
337                         EnvironmentTextureNode *env = (EnvironmentTextureNode*) snode;
338                         env->filename = path_join(state.base, env->filename.string());
339                 }
340
341                 if(snode) {
342                         /* add to graph */
343                         graph->add(snode);
344                 }
345         }
346
347         shader->set_graph(graph);
348         shader->tag_update(state.scene);
349 }
350
351 static void xml_read_shader(XMLReadState& state, xml_node node)
352 {
353         Shader *shader = new Shader();
354         xml_read_shader_graph(state, shader, node);
355         state.scene->shaders.push_back(shader);
356 }
357
358 /* Background */
359
360 static void xml_read_background(XMLReadState& state, xml_node node)
361 {
362         /* Background Settings */
363         xml_read_node(state, state.scene->background, node);
364
365         /* Background Shader */
366         Shader *shader = state.scene->default_background;
367         xml_read_shader_graph(state, shader, node);
368 }
369
370 /* Mesh */
371
372 static Mesh *xml_add_mesh(Scene *scene, const Transform& tfm)
373 {
374         /* create mesh */
375         Mesh *mesh = new Mesh();
376         scene->meshes.push_back(mesh);
377
378         /* create object*/
379         Object *object = new Object();
380         object->mesh = mesh;
381         object->tfm = tfm;
382         scene->objects.push_back(object);
383
384         return mesh;
385 }
386
387 static void xml_read_mesh(const XMLReadState& state, xml_node node)
388 {
389         /* add mesh */
390         Mesh *mesh = xml_add_mesh(state.scene, state.tfm);
391         mesh->used_shaders.push_back(state.shader);
392
393         /* read state */
394         int shader = 0;
395         bool smooth = state.smooth;
396
397         /* read vertices and polygons */
398         vector<float3> P;
399         vector<float> UV;
400         vector<int> verts, nverts;
401
402         xml_read_float3_array(P, node, "P");
403         xml_read_int_array(verts, node, "verts");
404         xml_read_int_array(nverts, node, "nverts");
405
406         if(xml_equal_string(node, "subdivision", "catmull-clark")) {
407                 mesh->subdivision_type = Mesh::SUBDIVISION_CATMULL_CLARK;
408         }
409         else if(xml_equal_string(node, "subdivision", "linear")) {
410                 mesh->subdivision_type = Mesh::SUBDIVISION_LINEAR;
411         }
412
413         if(mesh->subdivision_type == Mesh::SUBDIVISION_NONE) {
414                 /* create vertices */
415                 mesh->verts = P;
416
417                 size_t num_triangles = 0;
418                 for(size_t i = 0; i < nverts.size(); i++)
419                         num_triangles += nverts[i]-2;
420                 mesh->reserve_mesh(mesh->verts.size(), num_triangles);
421
422                 /* create triangles */
423                 int index_offset = 0;
424
425                 for(size_t i = 0; i < nverts.size(); i++) {
426                         for(int j = 0; j < nverts[i]-2; j++) {
427                                 int v0 = verts[index_offset];
428                                 int v1 = verts[index_offset + j + 1];
429                                 int v2 = verts[index_offset + j + 2];
430
431                                 assert(v0 < (int)P.size());
432                                 assert(v1 < (int)P.size());
433                                 assert(v2 < (int)P.size());
434
435                                 mesh->add_triangle(v0, v1, v2, shader, smooth);
436                         }
437
438                         index_offset += nverts[i];
439                 }
440
441                 if(xml_read_float_array(UV, node, "UV")) {
442                         ustring name = ustring("UVMap");
443                         Attribute *attr = mesh->attributes.add(ATTR_STD_UV, name);
444                         float3 *fdata = attr->data_float3();
445
446                         /* loop over the triangles */
447                         index_offset = 0;
448                         for(size_t i = 0; i < nverts.size(); i++) {
449                                 for(int j = 0; j < nverts[i]-2; j++) {
450                                         int v0 = index_offset;
451                                         int v1 = index_offset + j + 1;
452                                         int v2 = index_offset + j + 2;
453
454                                         assert(v0*2+1 < (int)UV.size());
455                                         assert(v1*2+1 < (int)UV.size());
456                                         assert(v2*2+1 < (int)UV.size());
457
458                                         fdata[0] = make_float3(UV[v0*2], UV[v0*2+1], 0.0);
459                                         fdata[1] = make_float3(UV[v1*2], UV[v1*2+1], 0.0);
460                                         fdata[2] = make_float3(UV[v2*2], UV[v2*2+1], 0.0);
461                                         fdata += 3;
462                                 }
463
464                                 index_offset += nverts[i];
465                         }
466                 }
467         }
468         else {
469                 /* create vertices */
470                 mesh->verts = P;
471
472                 size_t num_ngons = 0;
473                 size_t num_corners = 0;
474                 for(size_t i = 0; i < nverts.size(); i++) {
475                         num_ngons += (nverts[i] == 4) ? 0 : 1;
476                         num_corners += nverts[i];
477                 }
478                 mesh->reserve_subd_faces(nverts.size(), num_ngons, num_corners);
479
480                 /* create subd_faces */
481                 int index_offset = 0;
482
483                 for(size_t i = 0; i < nverts.size(); i++) {
484                         mesh->add_subd_face(&verts[index_offset], nverts[i], shader, smooth);
485                         index_offset += nverts[i];
486                 }
487
488                 /* uv map */
489                 if(xml_read_float_array(UV, node, "UV")) {
490                         ustring name = ustring("UVMap");
491                         Attribute *attr = mesh->subd_attributes.add(ATTR_STD_UV, name);
492                         float3 *fdata = attr->data_float3();
493
494 #if 0
495                         if(subdivide_uvs) {
496                                 attr->flags |= ATTR_SUBDIVIDED;
497                         }
498 #endif
499
500                         index_offset = 0;
501                         for(size_t i = 0; i < nverts.size(); i++) {
502                                 for(int j = 0; j < nverts[i]; j++) {
503                                         *(fdata++) = make_float3(UV[index_offset++]);
504                                 }
505                         }
506                 }
507
508                 /* setup subd params */
509                 if(!mesh->subd_params) {
510                         mesh->subd_params = new SubdParams(mesh);
511                 }
512                 SubdParams& sdparams = *mesh->subd_params;
513
514                 sdparams.dicing_rate = state.dicing_rate;
515                 xml_read_float(&sdparams.dicing_rate, node, "dicing_rate");
516                 sdparams.dicing_rate = std::max(0.1f, sdparams.dicing_rate);
517
518                 state.scene->camera->update();
519                 sdparams.camera = state.scene->camera;
520                 sdparams.objecttoworld = state.tfm;
521         }
522
523         /* we don't yet support arbitrary attributes, for now add vertex
524          * coordinates as generated coordinates if requested */
525         if(mesh->need_attribute(state.scene, ATTR_STD_GENERATED)) {
526                 Attribute *attr = mesh->attributes.add(ATTR_STD_GENERATED);
527                 memcpy(attr->data_float3(), mesh->verts.data(), sizeof(float3)*mesh->verts.size());
528         }
529 }
530
531 /* Light */
532
533 static void xml_read_light(XMLReadState& state, xml_node node)
534 {
535         Light *light = new Light();
536
537         light->shader = state.shader;
538         xml_read_node(state, light, node);
539
540         state.scene->lights.push_back(light);
541 }
542
543 /* Transform */
544
545 static void xml_read_transform(xml_node node, Transform& tfm)
546 {
547         if(node.attribute("matrix")) {
548                 vector<float> matrix;
549                 if(xml_read_float_array(matrix, node, "matrix") && matrix.size() == 16)
550                         tfm = tfm * transform_transpose((*(Transform*)&matrix[0]));
551         }
552
553         if(node.attribute("translate")) {
554                 float3 translate = make_float3(0.0f, 0.0f, 0.0f);
555                 xml_read_float3(&translate, node, "translate");
556                 tfm = tfm * transform_translate(translate);
557         }
558
559         if(node.attribute("rotate")) {
560                 float4 rotate = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
561                 xml_read_float4(&rotate, node, "rotate");
562                 tfm = tfm * transform_rotate(DEG2RADF(rotate.x), make_float3(rotate.y, rotate.z, rotate.w));
563         }
564
565         if(node.attribute("scale")) {
566                 float3 scale = make_float3(0.0f, 0.0f, 0.0f);
567                 xml_read_float3(&scale, node, "scale");
568                 tfm = tfm * transform_scale(scale);
569         }
570 }
571
572 /* State */
573
574 static void xml_read_state(XMLReadState& state, xml_node node)
575 {
576         /* read shader */
577         string shadername;
578
579         if(xml_read_string(&shadername, node, "shader")) {
580                 bool found = false;
581
582                 foreach(Shader *shader, state.scene->shaders) {
583                         if(shader->name == shadername) {
584                                 state.shader = shader;
585                                 found = true;
586                                 break;
587                         }
588                 }
589
590                 if(!found)
591                         fprintf(stderr, "Unknown shader \"%s\".\n", shadername.c_str());
592         }
593
594         xml_read_float(&state.dicing_rate, node, "dicing_rate");
595
596         /* read smooth/flat */
597         if(xml_equal_string(node, "interpolation", "smooth"))
598                 state.smooth = true;
599         else if(xml_equal_string(node, "interpolation", "flat"))
600                 state.smooth = false;
601 }
602
603 /* Scene */
604
605 static void xml_read_include(XMLReadState& state, const string& src);
606
607 static void xml_read_scene(XMLReadState& state, xml_node scene_node)
608 {
609         for(xml_node node = scene_node.first_child(); node; node = node.next_sibling()) {
610                 if(string_iequals(node.name(), "film")) {
611                         xml_read_node(state, state.scene->film, node);
612                 }
613                 else if(string_iequals(node.name(), "integrator")) {
614                         xml_read_node(state, state.scene->integrator, node);
615                 }
616                 else if(string_iequals(node.name(), "camera")) {
617                         xml_read_camera(state, node);
618                 }
619                 else if(string_iequals(node.name(), "shader")) {
620                         xml_read_shader(state, node);
621                 }
622                 else if(string_iequals(node.name(), "background")) {
623                         xml_read_background(state, node);
624                 }
625                 else if(string_iequals(node.name(), "mesh")) {
626                         xml_read_mesh(state, node);
627                 }
628                 else if(string_iequals(node.name(), "light")) {
629                         xml_read_light(state, node);
630                 }
631                 else if(string_iequals(node.name(), "transform")) {
632                         XMLReadState substate = state;
633
634                         xml_read_transform(node, substate.tfm);
635                         xml_read_scene(substate, node);
636                 }
637                 else if(string_iequals(node.name(), "state")) {
638                         XMLReadState substate = state;
639
640                         xml_read_state(substate, node);
641                         xml_read_scene(substate, node);
642                 }
643                 else if(string_iequals(node.name(), "include")) {
644                         string src;
645
646                         if(xml_read_string(&src, node, "src"))
647                                 xml_read_include(state, src);
648                 }
649                 else
650                         fprintf(stderr, "Unknown node \"%s\".\n", node.name());
651         }
652 }
653
654 /* Include */
655
656 static void xml_read_include(XMLReadState& state, const string& src)
657 {
658         /* open XML document */
659         xml_document doc;
660         xml_parse_result parse_result;
661
662         string path = path_join(state.base, src);
663         parse_result = doc.load_file(path.c_str());
664
665         if(parse_result) {
666                 XMLReadState substate = state;
667                 substate.base = path_dirname(path);
668
669                 xml_node cycles = doc.child("cycles");
670                 xml_read_scene(substate, cycles);
671         }
672         else {
673                 fprintf(stderr, "%s read error: %s\n", src.c_str(), parse_result.description());
674                 exit(EXIT_FAILURE);
675         }
676 }
677
678 /* File */
679
680 void xml_read_file(Scene *scene, const char *filepath)
681 {
682         XMLReadState state;
683
684         state.scene = scene;
685         state.tfm = transform_identity();
686         state.shader = scene->default_surface;
687         state.smooth = false;
688         state.dicing_rate = 1.0f;
689         state.base = path_dirname(filepath);
690
691         xml_read_include(state, path_filename(filepath));
692
693         scene->params.bvh_type = SceneParams::BVH_STATIC;
694 }
695
696 CCL_NAMESPACE_END
697