Cuda use streams and async to avoid busywaiting
[blender.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 "camera.h"
24 #include "film.h"
25 #include "graph.h"
26 #include "integrator.h"
27 #include "light.h"
28 #include "mesh.h"
29 #include "nodes.h"
30 #include "object.h"
31 #include "shader.h"
32 #include "scene.h"
33
34 #include "subd_mesh.h"
35 #include "subd_patch.h"
36 #include "subd_split.h"
37
38 #include "util_debug.h"
39 #include "util_foreach.h"
40 #include "util_path.h"
41 #include "util_transform.h"
42 #include "util_xml.h"
43
44 #include "cycles_xml.h"
45
46 CCL_NAMESPACE_BEGIN
47
48 /* XML reading state */
49
50 struct XMLReadState {
51         Scene *scene;           /* scene pointer */
52         Transform tfm;          /* current transform state */
53         bool smooth;            /* smooth normal state */
54         int shader;                     /* current shader */
55         string base;            /* base path to current file*/
56         float dicing_rate;      /* current dicing rate */
57         Mesh::DisplacementMethod displacement_method;
58 };
59
60 /* Attribute Reading */
61
62 static bool xml_read_bool(bool *value, pugi::xml_node node, const char *name)
63 {
64         pugi::xml_attribute attr = node.attribute(name);
65
66         if(attr) {
67                 *value = (string_iequals(attr.value(), "true")) || (atoi(attr.value()) != 0);
68                 return true;
69         }
70
71         return false;
72 }
73
74 static bool xml_read_int(int *value, pugi::xml_node node, const char *name)
75 {
76         pugi::xml_attribute attr = node.attribute(name);
77
78         if(attr) {
79                 *value = atoi(attr.value());
80                 return true;
81         }
82
83         return false;
84 }
85
86 static bool xml_read_int_array(vector<int>& value, pugi::xml_node node, const char *name)
87 {
88         pugi::xml_attribute attr = node.attribute(name);
89
90         if(attr) {
91                 vector<string> tokens;
92                 string_split(tokens, attr.value());
93
94                 foreach(const string& token, tokens)
95                         value.push_back(atoi(token.c_str()));
96
97                 return true;
98         }
99
100         return false;
101 }
102
103 static bool xml_read_float(float *value, pugi::xml_node node, const char *name)
104 {
105         pugi::xml_attribute attr = node.attribute(name);
106
107         if(attr) {
108                 *value = atof(attr.value());
109                 return true;
110         }
111
112         return false;
113 }
114
115 static bool xml_read_float_array(vector<float>& value, pugi::xml_node node, const char *name)
116 {
117         pugi::xml_attribute attr = node.attribute(name);
118
119         if(attr) {
120                 vector<string> tokens;
121                 string_split(tokens, attr.value());
122
123                 foreach(const string& token, tokens)
124                         value.push_back(atof(token.c_str()));
125
126                 return true;
127         }
128
129         return false;
130 }
131
132 static bool xml_read_float3(float3 *value, pugi::xml_node node, const char *name)
133 {
134         vector<float> array;
135
136         if(xml_read_float_array(array, node, name) && array.size() == 3) {
137                 *value = make_float3(array[0], array[1], array[2]);
138                 return true;
139         }
140
141         return false;
142 }
143
144 static bool xml_read_float3_array(vector<float3>& value, pugi::xml_node node, const char *name)
145 {
146         vector<float> array;
147
148         if(xml_read_float_array(array, node, name)) {
149                 for(size_t i = 0; i < array.size(); i += 3)
150                         value.push_back(make_float3(array[i+0], array[i+1], array[i+2]));
151
152                 return true;
153         }
154
155         return false;
156 }
157
158 static bool xml_read_float4(float4 *value, pugi::xml_node node, const char *name)
159 {
160         vector<float> array;
161
162         if(xml_read_float_array(array, node, name) && array.size() == 4) {
163                 *value = make_float4(array[0], array[1], array[2], array[3]);
164                 return true;
165         }
166
167         return false;
168 }
169
170 static bool xml_read_string(string *str, pugi::xml_node node, const char *name)
171 {
172         pugi::xml_attribute attr = node.attribute(name);
173
174         if(attr) {
175                 *str = attr.value();
176                 return true;
177         }
178
179         return false;
180 }
181
182 static bool xml_read_ustring(ustring *str, pugi::xml_node node, const char *name)
183 {
184         pugi::xml_attribute attr = node.attribute(name);
185
186         if(attr) {
187                 *str = ustring(attr.value());
188                 return true;
189         }
190
191         return false;
192 }
193
194 static bool xml_equal_string(pugi::xml_node node, const char *name, const char *value)
195 {
196         pugi::xml_attribute attr = node.attribute(name);
197
198         if(attr)
199                 return string_iequals(attr.value(), value);
200         
201         return false;
202 }
203
204 static bool xml_read_enum(ustring *str, ShaderEnum& enm, pugi::xml_node node, const char *name)
205 {
206         pugi::xml_attribute attr = node.attribute(name);
207
208         if(attr) {
209                 ustring ustr(attr.value());
210
211                 if(enm.exists(ustr)) {
212                         *str = ustr;
213                         return true;
214                 }
215                 else
216                         fprintf(stderr, "Unknown value \"%s\" for attribute \"%s\".\n", ustr.c_str(), name);
217         }
218
219         return false;
220 }
221
222 static ShaderSocketType xml_read_socket_type(pugi::xml_node node, const char *name)
223 {
224         pugi::xml_attribute attr = node.attribute(name);
225
226         if(attr) {
227                 string value = attr.value();
228                 if (string_iequals(value, "float"))
229                         return SHADER_SOCKET_FLOAT;
230                 else if (string_iequals(value, "int"))
231                         return SHADER_SOCKET_INT;
232                 else if (string_iequals(value, "color"))
233                         return SHADER_SOCKET_COLOR;
234                 else if (string_iequals(value, "vector"))
235                         return SHADER_SOCKET_VECTOR;
236                 else if (string_iequals(value, "point"))
237                         return SHADER_SOCKET_POINT;
238                 else if (string_iequals(value, "normal"))
239                         return SHADER_SOCKET_NORMAL;
240                 else if (string_iequals(value, "closure color"))
241                         return SHADER_SOCKET_CLOSURE;
242                 else if (string_iequals(value, "string"))
243                         return SHADER_SOCKET_STRING;
244                 else
245                         fprintf(stderr, "Unknown shader socket type \"%s\" for attribute \"%s\".\n", value.c_str(), name);
246         }
247         
248         return SHADER_SOCKET_UNDEFINED;
249 }
250
251 /* Film */
252
253 static void xml_read_film(const XMLReadState& state, pugi::xml_node node)
254 {
255         Film *film = state.scene->film;
256         
257         xml_read_float(&film->exposure, node, "exposure");
258
259         /* ToDo: Filter Type */
260         xml_read_float(&film->filter_width, node, "filter_width");
261 }
262
263 /* Integrator */
264
265 static void xml_read_integrator(const XMLReadState& state, pugi::xml_node node)
266 {
267         Integrator *integrator = state.scene->integrator;
268         
269         /* Branched Path */
270         bool branched = false;
271         xml_read_bool(&branched, node, "branched");
272
273         if(branched) {
274                 integrator->method = Integrator::BRANCHED_PATH;
275
276                 xml_read_int(&integrator->diffuse_samples, node, "diffuse_samples");
277                 xml_read_int(&integrator->glossy_samples, node, "glossy_samples");
278                 xml_read_int(&integrator->transmission_samples, node, "transmission_samples");
279                 xml_read_int(&integrator->ao_samples, node, "ao_samples");
280                 xml_read_int(&integrator->mesh_light_samples, node, "mesh_light_samples");
281                 xml_read_int(&integrator->subsurface_samples, node, "subsurface_samples");
282                 xml_read_int(&integrator->volume_samples, node, "volume_samples");
283         }
284         
285         /* Bounces */
286         xml_read_int(&integrator->min_bounce, node, "min_bounce");
287         xml_read_int(&integrator->max_bounce, node, "max_bounce");
288         
289         xml_read_int(&integrator->max_diffuse_bounce, node, "max_diffuse_bounce");
290         xml_read_int(&integrator->max_glossy_bounce, node, "max_glossy_bounce");
291         xml_read_int(&integrator->max_transmission_bounce, node, "max_transmission_bounce");
292         xml_read_int(&integrator->max_volume_bounce, node, "max_volume_bounce");
293         
294         /* Transparency */
295         xml_read_int(&integrator->transparent_min_bounce, node, "transparent_min_bounce");
296         xml_read_int(&integrator->transparent_max_bounce, node, "transparent_max_bounce");
297         xml_read_bool(&integrator->transparent_shadows, node, "transparent_shadows");
298         
299         /* Volume */
300         xml_read_int(&integrator->volume_homogeneous_sampling, node, "volume_homogeneous_sampling");
301         xml_read_float(&integrator->volume_step_size, node, "volume_step_size");
302         xml_read_int(&integrator->volume_max_steps, node, "volume_max_steps");
303         
304         /* Various Settings */
305         xml_read_bool(&integrator->no_caustics, node, "no_caustics");
306         xml_read_float(&integrator->filter_glossy, node, "filter_glossy");
307         
308         xml_read_int(&integrator->seed, node, "seed");
309         xml_read_float(&integrator->sample_clamp_direct, node, "sample_clamp_direct");
310         xml_read_float(&integrator->sample_clamp_indirect, node, "sample_clamp_indirect");
311 }
312
313 /* Camera */
314
315 static void xml_read_camera(const XMLReadState& state, pugi::xml_node node)
316 {
317         Camera *cam = state.scene->camera;
318
319         xml_read_int(&cam->width, node, "width");
320         xml_read_int(&cam->height, node, "height");
321
322         if(xml_read_float(&cam->fov, node, "fov"))
323                 cam->fov *= M_PI/180.0f;
324
325         xml_read_float(&cam->nearclip, node, "nearclip");
326         xml_read_float(&cam->farclip, node, "farclip");
327         xml_read_float(&cam->aperturesize, node, "aperturesize"); // 0.5*focallength/fstop
328         xml_read_float(&cam->focaldistance, node, "focaldistance");
329         xml_read_float(&cam->shuttertime, node, "shuttertime");
330
331         if(xml_equal_string(node, "type", "orthographic"))
332                 cam->type = CAMERA_ORTHOGRAPHIC;
333         else if(xml_equal_string(node, "type", "perspective"))
334                 cam->type = CAMERA_PERSPECTIVE;
335         else if(xml_equal_string(node, "type", "panorama"))
336                 cam->type = CAMERA_PANORAMA;
337
338         if(xml_equal_string(node, "panorama_type", "equirectangular"))
339                 cam->panorama_type = PANORAMA_EQUIRECTANGULAR;
340         else if(xml_equal_string(node, "panorama_type", "fisheye_equidistant"))
341                 cam->panorama_type = PANORAMA_FISHEYE_EQUIDISTANT;
342         else if(xml_equal_string(node, "panorama_type", "fisheye_equisolid"))
343                 cam->panorama_type = PANORAMA_FISHEYE_EQUISOLID;
344
345         xml_read_float(&cam->fisheye_fov, node, "fisheye_fov");
346         xml_read_float(&cam->fisheye_lens, node, "fisheye_lens");
347
348         xml_read_float(&cam->sensorwidth, node, "sensorwidth");
349         xml_read_float(&cam->sensorheight, node, "sensorheight");
350
351         cam->matrix = state.tfm;
352
353         cam->need_update = true;
354         cam->update();
355 }
356
357 /* Shader */
358
359 static string xml_socket_name(const char *name)
360 {
361         string sname = name;
362         size_t i;
363
364         while((i = sname.find(" ")) != string::npos)
365                 sname.replace(i, 1, "");
366         
367         return sname;
368 }
369
370 static void xml_read_shader_graph(const XMLReadState& state, Shader *shader, pugi::xml_node graph_node)
371 {
372         ShaderGraph *graph = new ShaderGraph();
373
374         map<string, ShaderNode*> nodemap;
375
376         nodemap["output"] = graph->output();
377
378         for(pugi::xml_node node = graph_node.first_child(); node; node = node.next_sibling()) {
379                 ShaderNode *snode = NULL;
380
381                 if(string_iequals(node.name(), "image_texture")) {
382                         ImageTextureNode *img = new ImageTextureNode();
383
384                         xml_read_string(&img->filename, node, "src");
385                         img->filename = path_join(state.base, img->filename);
386                         
387                         xml_read_enum(&img->color_space, ImageTextureNode::color_space_enum, node, "color_space");
388                         xml_read_enum(&img->projection, ImageTextureNode::projection_enum, node, "projection");
389                         xml_read_float(&img->projection_blend, node, "projection_blend");
390
391                         snode = img;
392                 }
393                 else if(string_iequals(node.name(), "environment_texture")) {
394                         EnvironmentTextureNode *env = new EnvironmentTextureNode();
395
396                         xml_read_string(&env->filename, node, "src");
397                         env->filename = path_join(state.base, env->filename);
398                         
399                         xml_read_enum(&env->color_space, EnvironmentTextureNode::color_space_enum, node, "color_space");
400                         xml_read_enum(&env->projection, EnvironmentTextureNode::projection_enum, node, "projection");
401
402                         snode = env;
403                 }
404                 else if(string_iequals(node.name(), "osl_shader")) {
405                         OSLScriptNode *osl = new OSLScriptNode();
406
407                         /* Source */
408                         xml_read_string(&osl->filepath, node, "src");
409                         osl->filepath = path_join(state.base, osl->filepath);
410
411                         /* Generate inputs/outputs from node sockets
412                          *
413                          * Note: ShaderInput/ShaderOutput store shallow string copies only!
414                          * Socket names must be stored in the extra lists instead. */
415                         /* read input values */
416                         for(pugi::xml_node param = node.first_child(); param; param = param.next_sibling()) {
417                                 if (string_iequals(param.name(), "input")) {
418                                         string name;
419                                         if (!xml_read_string(&name, param, "name"))
420                                                 continue;
421                                         
422                                         ShaderSocketType type = xml_read_socket_type(param, "type");
423                                         if (type == SHADER_SOCKET_UNDEFINED)
424                                                 continue;
425                                         
426                                         osl->input_names.push_back(ustring(name));
427                                         osl->add_input(osl->input_names.back().c_str(), type);
428                                 }
429                                 else if (string_iequals(param.name(), "output")) {
430                                         string name;
431                                         if (!xml_read_string(&name, param, "name"))
432                                                 continue;
433                                         
434                                         ShaderSocketType type = xml_read_socket_type(param, "type");
435                                         if (type == SHADER_SOCKET_UNDEFINED)
436                                                 continue;
437                                         
438                                         osl->output_names.push_back(ustring(name));
439                                         osl->add_output(osl->output_names.back().c_str(), type);
440                                 }
441                         }
442                         
443                         snode = osl;
444                 }
445                 else if(string_iequals(node.name(), "sky_texture")) {
446                         SkyTextureNode *sky = new SkyTextureNode();
447                         
448                         xml_read_enum(&sky->type, SkyTextureNode::type_enum, node, "type");
449                         xml_read_float3(&sky->sun_direction, node, "sun_direction");
450                         xml_read_float(&sky->turbidity, node, "turbidity");
451                         xml_read_float(&sky->ground_albedo, node, "ground_albedo");
452                         
453                         snode = sky;
454                 }
455                 else if(string_iequals(node.name(), "noise_texture")) {
456                         snode = new NoiseTextureNode();
457                 }
458                 else if(string_iequals(node.name(), "checker_texture")) {
459                         snode = new CheckerTextureNode();
460                 }
461                 else if(string_iequals(node.name(), "brick_texture")) {
462                         BrickTextureNode *brick = new BrickTextureNode();
463
464                         xml_read_float(&brick->offset, node, "offset");
465                         xml_read_int(&brick->offset_frequency, node, "offset_frequency");
466                         xml_read_float(&brick->squash, node, "squash");
467                         xml_read_int(&brick->squash_frequency, node, "squash_frequency");
468
469                         snode = brick;
470                 }
471                 else if(string_iequals(node.name(), "gradient_texture")) {
472                         GradientTextureNode *blend = new GradientTextureNode();
473                         xml_read_enum(&blend->type, GradientTextureNode::type_enum, node, "type");
474                         snode = blend;
475                 }
476                 else if(string_iequals(node.name(), "voronoi_texture")) {
477                         VoronoiTextureNode *voronoi = new VoronoiTextureNode();
478                         xml_read_enum(&voronoi->coloring, VoronoiTextureNode::coloring_enum, node, "coloring");
479                         snode = voronoi;
480                 }
481                 else if(string_iequals(node.name(), "musgrave_texture")) {
482                         MusgraveTextureNode *musgrave = new MusgraveTextureNode();
483                         xml_read_enum(&musgrave->type, MusgraveTextureNode::type_enum, node, "type");
484                         snode = musgrave;
485                 }
486                 else if(string_iequals(node.name(), "magic_texture")) {
487                         MagicTextureNode *magic = new MagicTextureNode();
488                         xml_read_int(&magic->depth, node, "depth");
489                         snode = magic;
490                 }
491                 else if(string_iequals(node.name(), "noise_texture")) {
492                         NoiseTextureNode *dist = new NoiseTextureNode();
493                         snode = dist;
494                 }
495                 else if(string_iequals(node.name(), "wave_texture")) {
496                         WaveTextureNode *wave = new WaveTextureNode();
497                         xml_read_enum(&wave->type, WaveTextureNode::type_enum, node, "type");
498                         snode = wave;
499                 }
500                 else if(string_iequals(node.name(), "normal")) {
501                         NormalNode *normal = new NormalNode();
502                         xml_read_float3(&normal->direction, node, "direction");
503                         snode = normal;
504                 }
505                 else if(string_iequals(node.name(), "mapping")) {
506                         snode = new MappingNode();
507                 }
508                 else if(string_iequals(node.name(), "ward_bsdf")) {
509                         snode = new WardBsdfNode();
510                 }
511                 else if(string_iequals(node.name(), "diffuse_bsdf")) {
512                         snode = new DiffuseBsdfNode();
513                 }
514                 else if(string_iequals(node.name(), "translucent_bsdf")) {
515                         snode = new TranslucentBsdfNode();
516                 }
517                 else if(string_iequals(node.name(), "transparent_bsdf")) {
518                         snode = new TransparentBsdfNode();
519                 }
520                 else if(string_iequals(node.name(), "velvet_bsdf")) {
521                         snode = new VelvetBsdfNode();
522                 }
523                 else if(string_iequals(node.name(), "toon_bsdf")) {
524                         ToonBsdfNode *toon = new ToonBsdfNode();
525                         xml_read_enum(&toon->component, ToonBsdfNode::component_enum, node, "component");
526                         snode = toon;
527                 }
528                 else if(string_iequals(node.name(), "glossy_bsdf")) {
529                         GlossyBsdfNode *glossy = new GlossyBsdfNode();
530                         xml_read_enum(&glossy->distribution, GlossyBsdfNode::distribution_enum, node, "distribution");
531                         snode = glossy;
532                 }
533                 else if(string_iequals(node.name(), "glass_bsdf")) {
534                         GlassBsdfNode *diel = new GlassBsdfNode();
535                         xml_read_enum(&diel->distribution, GlassBsdfNode::distribution_enum, node, "distribution");
536                         snode = diel;
537                 }
538                 else if(string_iequals(node.name(), "refraction_bsdf")) {
539                         RefractionBsdfNode *diel = new RefractionBsdfNode();
540                         xml_read_enum(&diel->distribution, RefractionBsdfNode::distribution_enum, node, "distribution");
541                         snode = diel;
542                 }
543                 else if(string_iequals(node.name(), "hair_bsdf")) {
544                         HairBsdfNode *hair = new HairBsdfNode();
545                         xml_read_enum(&hair->component, HairBsdfNode::component_enum, node, "component");
546                         snode = hair;
547                 }
548                 else if(string_iequals(node.name(), "emission")) {
549                         EmissionNode *emission = new EmissionNode();
550                         xml_read_bool(&emission->total_power, node, "total_power");
551                         snode = emission;
552                 }
553                 else if(string_iequals(node.name(), "ambient_occlusion")) {
554                         snode = new AmbientOcclusionNode();
555                 }
556                 else if(string_iequals(node.name(), "background")) {
557                         snode = new BackgroundNode();
558                 }
559                 else if(string_iequals(node.name(), "absorption_volume")) {
560                         snode = new AbsorptionVolumeNode();
561                 }
562                 else if(string_iequals(node.name(), "scatter_volume")) {
563                         snode = new ScatterVolumeNode();
564                 }
565                 else if(string_iequals(node.name(), "subsurface_scattering")) {
566                         SubsurfaceScatteringNode *sss = new SubsurfaceScatteringNode();
567                         //xml_read_enum(&sss->falloff, SubsurfaceScatteringNode::falloff_enum, node, "falloff");
568                         snode = sss;
569                 }
570                 else if(string_iequals(node.name(), "geometry")) {
571                         snode = new GeometryNode();
572                 }
573                 else if(string_iequals(node.name(), "texture_coordinate")) {
574                         snode = new TextureCoordinateNode();
575                 }
576                 else if(string_iequals(node.name(), "light_path")) {
577                         snode = new LightPathNode();
578                 }
579                 else if(string_iequals(node.name(), "light_falloff")) {
580                         snode = new LightFalloffNode();
581                 }
582                 else if(string_iequals(node.name(), "object_info")) {
583                         snode = new ObjectInfoNode();
584                 }
585                 else if(string_iequals(node.name(), "particle_info")) {
586                         snode = new ParticleInfoNode();
587                 }
588                 else if(string_iequals(node.name(), "hair_info")) {
589                         snode = new HairInfoNode();
590                 }
591                 else if(string_iequals(node.name(), "value")) {
592                         ValueNode *value = new ValueNode();
593                         xml_read_float(&value->value, node, "value");
594                         snode = value;
595                 }
596                 else if(string_iequals(node.name(), "color")) {
597                         ColorNode *color = new ColorNode();
598                         xml_read_float3(&color->value, node, "value");
599                         snode = color;
600                 }
601                 else if(string_iequals(node.name(), "mix_closure")) {
602                         snode = new MixClosureNode();
603                 }
604                 else if(string_iequals(node.name(), "add_closure")) {
605                         snode = new AddClosureNode();
606                 }
607                 else if(string_iequals(node.name(), "invert")) {
608                         snode = new InvertNode();
609                 }
610                 else if(string_iequals(node.name(), "mix")) {
611                         MixNode *mix = new MixNode();
612                         xml_read_enum(&mix->type, MixNode::type_enum, node, "type");
613                         xml_read_bool(&mix->use_clamp, node, "use_clamp");
614                         snode = mix;
615                 }
616                 else if(string_iequals(node.name(), "gamma")) {
617                         snode = new GammaNode();
618                 }
619                 else if(string_iequals(node.name(), "brightness")) {
620                         snode = new BrightContrastNode();
621                 }
622                 else if(string_iequals(node.name(), "combine_rgb")) {
623                         snode = new CombineRGBNode();
624                 }
625                 else if(string_iequals(node.name(), "separate_rgb")) {
626                         snode = new SeparateRGBNode();
627                 }
628                 else if(string_iequals(node.name(), "combine_hsv")) {
629                         snode = new CombineHSVNode();
630                 }
631                 else if(string_iequals(node.name(), "separate_hsv")) {
632                         snode = new SeparateHSVNode();
633                 }
634                 else if(string_iequals(node.name(), "hsv")) {
635                         snode = new HSVNode();
636                 }
637                 else if(string_iequals(node.name(), "wavelength")) {
638                         snode = new WavelengthNode();
639                 }
640                 else if(string_iequals(node.name(), "blackbody")) {
641                         snode = new BlackbodyNode();
642                 }
643                 else if(string_iequals(node.name(), "attribute")) {
644                         AttributeNode *attr = new AttributeNode();
645                         xml_read_ustring(&attr->attribute, node, "attribute");
646                         snode = attr;
647                 }
648                 else if(string_iequals(node.name(), "camera")) {
649                         snode = new CameraNode();
650                 }
651                 else if(string_iequals(node.name(), "fresnel")) {
652                         snode = new FresnelNode();
653                 }
654                 else if(string_iequals(node.name(), "layer_weight")) {
655                         snode = new LayerWeightNode();
656                 }
657                 else if(string_iequals(node.name(), "wireframe")) {
658                         WireframeNode *wire = new WireframeNode;
659                         xml_read_bool(&wire->use_pixel_size, node, "use_pixel_size");
660                         snode = wire;
661                 }
662                 else if(string_iequals(node.name(), "normal_map")) {
663                         NormalMapNode *nmap = new NormalMapNode;
664                         xml_read_ustring(&nmap->attribute, node, "attribute");
665                         xml_read_enum(&nmap->space, NormalMapNode::space_enum, node, "space");
666                         snode = nmap;
667                 }
668                 else if(string_iequals(node.name(), "tangent")) {
669                         TangentNode *tangent = new TangentNode;
670                         xml_read_ustring(&tangent->attribute, node, "attribute");
671                         xml_read_enum(&tangent->direction_type, TangentNode::direction_type_enum, node, "direction_type");
672                         xml_read_enum(&tangent->axis, TangentNode::axis_enum, node, "axis");
673                         snode = tangent;
674                 }
675                 else if(string_iequals(node.name(), "math")) {
676                         MathNode *math = new MathNode();
677                         xml_read_enum(&math->type, MathNode::type_enum, node, "type");
678                         xml_read_bool(&math->use_clamp, node, "use_clamp");
679                         snode = math;
680                 }
681                 else if(string_iequals(node.name(), "vector_math")) {
682                         VectorMathNode *vmath = new VectorMathNode();
683                         xml_read_enum(&vmath->type, VectorMathNode::type_enum, node, "type");
684                         snode = vmath;
685                 }
686                 else if(string_iequals(node.name(), "vector_transform")) {
687                         VectorTransformNode *vtransform = new VectorTransformNode();
688                         xml_read_enum(&vtransform->type, VectorTransformNode::type_enum, node, "type");
689                         xml_read_enum(&vtransform->convert_from, VectorTransformNode::convert_space_enum, node, "convert_from");
690                         xml_read_enum(&vtransform->convert_to, VectorTransformNode::convert_space_enum, node, "convert_to");
691                         snode = vtransform;
692                 }
693                 else if(string_iequals(node.name(), "connect")) {
694                         /* connect nodes */
695                         vector<string> from_tokens, to_tokens;
696
697                         string_split(from_tokens, node.attribute("from").value());
698                         string_split(to_tokens, node.attribute("to").value());
699
700                         if(from_tokens.size() == 2 && to_tokens.size() == 2) {
701                                 /* find nodes and sockets */
702                                 ShaderOutput *output = NULL;
703                                 ShaderInput *input = NULL;
704
705                                 if(nodemap.find(from_tokens[0]) != nodemap.end()) {
706                                         ShaderNode *fromnode = nodemap[from_tokens[0]];
707
708                                         foreach(ShaderOutput *out, fromnode->outputs)
709                                                 if(string_iequals(xml_socket_name(out->name), from_tokens[1]))
710                                                         output = out;
711
712                                         if(!output)
713                                                 fprintf(stderr, "Unknown output socket name \"%s\" on \"%s\".\n", from_tokens[1].c_str(), from_tokens[0].c_str());
714                                 }
715                                 else
716                                         fprintf(stderr, "Unknown shader node name \"%s\".\n", from_tokens[0].c_str());
717
718                                 if(nodemap.find(to_tokens[0]) != nodemap.end()) {
719                                         ShaderNode *tonode = nodemap[to_tokens[0]];
720
721                                         foreach(ShaderInput *in, tonode->inputs)
722                                                 if(string_iequals(xml_socket_name(in->name), to_tokens[1]))
723                                                         input = in;
724
725                                         if(!input)
726                                                 fprintf(stderr, "Unknown input socket name \"%s\" on \"%s\".\n", to_tokens[1].c_str(), to_tokens[0].c_str());
727                                 }
728                                 else
729                                         fprintf(stderr, "Unknown shader node name \"%s\".\n", to_tokens[0].c_str());
730
731                                 /* connect */
732                                 if(output && input)
733                                         graph->connect(output, input);
734                         }
735                         else
736                                 fprintf(stderr, "Invalid from or to value for connect node.\n");
737                 }
738                 else
739                         fprintf(stderr, "Unknown shader node \"%s\".\n", node.name());
740
741                 if(snode) {
742                         /* add to graph */
743                         graph->add(snode);
744
745                         /* add to map for name lookups */
746                         string name = "";
747                         xml_read_string(&name, node, "name");
748
749                         nodemap[name] = snode;
750
751                         /* read input values */
752                         for(pugi::xml_attribute attr = node.first_attribute(); attr; attr = attr.next_attribute()) {
753                                 foreach(ShaderInput *in, snode->inputs) {
754                                         if(string_iequals(in->name, attr.name())) {
755                                                 switch(in->type) {
756                                                         case SHADER_SOCKET_FLOAT:
757                                                         case SHADER_SOCKET_INT:
758                                                                 xml_read_float(&in->value.x, node, attr.name());
759                                                                 break;
760                                                         case SHADER_SOCKET_COLOR:
761                                                         case SHADER_SOCKET_VECTOR:
762                                                         case SHADER_SOCKET_POINT:
763                                                         case SHADER_SOCKET_NORMAL:
764                                                                 xml_read_float3(&in->value, node, attr.name());
765                                                                 break;
766                                                         default:
767                                                                 break;
768                                                 }
769                                         }
770                                 }
771                         }
772                 }
773         }
774
775         shader->set_graph(graph);
776         shader->tag_update(state.scene);
777 }
778
779 static void xml_read_shader(const XMLReadState& state, pugi::xml_node node)
780 {
781         Shader *shader = new Shader();
782
783         xml_read_string(&shader->name, node, "name");
784         xml_read_bool(&shader->use_mis, node, "use_mis");
785         xml_read_bool(&shader->use_transparent_shadow, node, "use_transparent_shadow");
786         xml_read_bool(&shader->heterogeneous_volume, node, "heterogeneous_volume");
787
788         xml_read_shader_graph(state, shader, node);
789         state.scene->shaders.push_back(shader);
790 }
791
792 /* Background */
793
794 static void xml_read_background(const XMLReadState& state, pugi::xml_node node)
795 {
796         Shader *shader = state.scene->shaders[state.scene->default_background];
797         
798         xml_read_bool(&shader->heterogeneous_volume, node, "heterogeneous_volume");
799
800         xml_read_shader_graph(state, shader, node);
801 }
802
803 /* Mesh */
804
805 static Mesh *xml_add_mesh(Scene *scene, const Transform& tfm)
806 {
807         /* create mesh */
808         Mesh *mesh = new Mesh();
809         scene->meshes.push_back(mesh);
810
811         /* create object*/
812         Object *object = new Object();
813         object->mesh = mesh;
814         object->tfm = tfm;
815         scene->objects.push_back(object);
816
817         return mesh;
818 }
819
820 static void xml_read_mesh(const XMLReadState& state, pugi::xml_node node)
821 {
822         /* add mesh */
823         Mesh *mesh = xml_add_mesh(state.scene, state.tfm);
824         mesh->used_shaders.push_back(state.shader);
825
826         /* read state */
827         int shader = state.shader;
828         bool smooth = state.smooth;
829
830         mesh->displacement_method = state.displacement_method;
831
832         /* read vertices and polygons, RIB style */
833         vector<float3> P;
834         vector<int> verts, nverts;
835
836         xml_read_float3_array(P, node, "P");
837         xml_read_int_array(verts, node, "verts");
838         xml_read_int_array(nverts, node, "nverts");
839
840         if(xml_equal_string(node, "subdivision", "catmull-clark")) {
841                 /* create subd mesh */
842                 SubdMesh sdmesh;
843
844                 /* create subd vertices */
845                 for(size_t i = 0; i < P.size(); i++)
846                         sdmesh.add_vert(P[i]);
847
848                 /* create subd faces */
849                 int index_offset = 0;
850
851                 for(size_t i = 0; i < nverts.size(); i++) {
852                         if(nverts[i] == 4) {
853                                 int v0 = verts[index_offset + 0];
854                                 int v1 = verts[index_offset + 1];
855                                 int v2 = verts[index_offset + 2];
856                                 int v3 = verts[index_offset + 3];
857
858                                 sdmesh.add_face(v0, v1, v2, v3);
859                         }
860                         else {
861                                 for(int j = 0; j < nverts[i]-2; j++) {
862                                         int v0 = verts[index_offset];
863                                         int v1 = verts[index_offset + j + 1];
864                                         int v2 = verts[index_offset + j + 2];
865
866                                         sdmesh.add_face(v0, v1, v2);
867                                 }
868                         }
869
870                         index_offset += nverts[i];
871                 }
872
873                 /* finalize subd mesh */
874                 sdmesh.finish();
875
876                 /* parameters */
877                 SubdParams sdparams(mesh, shader, smooth);
878                 xml_read_float(&sdparams.dicing_rate, node, "dicing_rate");
879
880                 DiagSplit dsplit(sdparams);;
881                 sdmesh.tessellate(&dsplit);
882         }
883         else {
884                 /* create vertices */
885                 mesh->verts = P;
886
887                 /* create triangles */
888                 int index_offset = 0;
889
890                 for(size_t i = 0; i < nverts.size(); i++) {
891                         for(int j = 0; j < nverts[i]-2; j++) {
892                                 int v0 = verts[index_offset];
893                                 int v1 = verts[index_offset + j + 1];
894                                 int v2 = verts[index_offset + j + 2];
895
896                                 assert(v0 < (int)P.size());
897                                 assert(v1 < (int)P.size());
898                                 assert(v2 < (int)P.size());
899
900                                 mesh->add_triangle(v0, v1, v2, shader, smooth);
901                         }
902
903                         index_offset += nverts[i];
904                 }
905         }
906
907         /* temporary for test compatibility */
908         mesh->attributes.remove(ATTR_STD_VERTEX_NORMAL);
909 }
910
911 /* Patch */
912
913 static void xml_read_patch(const XMLReadState& state, pugi::xml_node node)
914 {
915         /* read patch */
916         Patch *patch = NULL;
917
918         vector<float3> P;
919         xml_read_float3_array(P, node, "P");
920
921         if(xml_equal_string(node, "type", "bilinear")) {
922                 /* bilinear patch */
923                 if(P.size() == 4) {
924                         LinearQuadPatch *bpatch = new LinearQuadPatch();
925
926                         for(int i = 0; i < 4; i++)
927                                 P[i] = transform_point(&state.tfm, P[i]);
928                         memcpy(bpatch->hull, &P[0], sizeof(bpatch->hull));
929
930                         patch = bpatch;
931                 }
932                 else
933                         fprintf(stderr, "Invalid number of control points for bilinear patch.\n");
934         }
935         else if(xml_equal_string(node, "type", "bicubic")) {
936                 /* bicubic patch */
937                 if(P.size() == 16) {
938                         BicubicPatch *bpatch = new BicubicPatch();
939
940                         for(int i = 0; i < 16; i++)
941                                 P[i] = transform_point(&state.tfm, P[i]);
942                         memcpy(bpatch->hull, &P[0], sizeof(bpatch->hull));
943
944                         patch = bpatch;
945                 }
946                 else
947                         fprintf(stderr, "Invalid number of control points for bicubic patch.\n");
948         }
949         else
950                 fprintf(stderr, "Unknown patch type.\n");
951
952         if(patch) {
953                 /* add mesh */
954                 Mesh *mesh = xml_add_mesh(state.scene, transform_identity());
955
956                 mesh->used_shaders.push_back(state.shader);
957
958                 /* split */
959                 SubdParams sdparams(mesh, state.shader, state.smooth);
960                 xml_read_float(&sdparams.dicing_rate, node, "dicing_rate");
961
962                 DiagSplit dsplit(sdparams);
963                 dsplit.split_quad(patch);
964
965                 delete patch;
966
967                 /* temporary for test compatibility */
968                 mesh->attributes.remove(ATTR_STD_VERTEX_NORMAL);
969         }
970 }
971
972 /* Light */
973
974 static void xml_read_light(const XMLReadState& state, pugi::xml_node node)
975 {
976         Light *light = new Light();
977         light->shader = state.shader;
978
979         /* Light Type
980          * 0: Point, 1: Sun, 3: Area, 5: Spot */
981         int type = 0;
982         xml_read_int(&type, node, "type");
983         light->type = (LightType)type;
984
985         /* Spot Light */
986         xml_read_float(&light->spot_angle, node, "spot_angle");
987         xml_read_float(&light->spot_smooth, node, "spot_smooth");
988
989         /* Area Light */
990         xml_read_float(&light->sizeu, node, "sizeu");
991         xml_read_float(&light->sizev, node, "sizev");
992         xml_read_float3(&light->axisu, node, "axisu");
993         xml_read_float3(&light->axisv, node, "axisv");
994         
995         /* Generic */
996         xml_read_float(&light->size, node, "size");
997         xml_read_float3(&light->dir, node, "dir");
998         xml_read_float3(&light->co, node, "P");
999         light->co = transform_point(&state.tfm, light->co);
1000
1001         state.scene->lights.push_back(light);
1002 }
1003
1004 /* Transform */
1005
1006 static void xml_read_transform(pugi::xml_node node, Transform& tfm)
1007 {
1008         if(node.attribute("matrix")) {
1009                 vector<float> matrix;
1010                 if(xml_read_float_array(matrix, node, "matrix") && matrix.size() == 16)
1011                         tfm = tfm * transform_transpose((*(Transform*)&matrix[0]));
1012         }
1013
1014         if(node.attribute("translate")) {
1015                 float3 translate = make_float3(0.0f, 0.0f, 0.0f);
1016                 xml_read_float3(&translate, node, "translate");
1017                 tfm = tfm * transform_translate(translate);
1018         }
1019
1020         if(node.attribute("rotate")) {
1021                 float4 rotate = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
1022                 xml_read_float4(&rotate, node, "rotate");
1023                 tfm = tfm * transform_rotate(rotate.x*M_PI/180.0f, make_float3(rotate.y, rotate.z, rotate.w));
1024         }
1025
1026         if(node.attribute("scale")) {
1027                 float3 scale = make_float3(0.0f, 0.0f, 0.0f);
1028                 xml_read_float3(&scale, node, "scale");
1029                 tfm = tfm * transform_scale(scale);
1030         }
1031 }
1032
1033 /* State */
1034
1035 static void xml_read_state(XMLReadState& state, pugi::xml_node node)
1036 {
1037         /* read shader */
1038         string shadername;
1039
1040         if(xml_read_string(&shadername, node, "shader")) {
1041                 int i = 0;
1042                 bool found = false;
1043
1044                 foreach(Shader *shader, state.scene->shaders) {
1045                         if(shader->name == shadername) {
1046                                 state.shader = i;
1047                                 found = true;
1048                                 break;
1049                         }
1050
1051                         i++;
1052                 }
1053
1054                 if(!found)
1055                         fprintf(stderr, "Unknown shader \"%s\".\n", shadername.c_str());
1056         }
1057
1058         xml_read_float(&state.dicing_rate, node, "dicing_rate");
1059
1060         /* read smooth/flat */
1061         if(xml_equal_string(node, "interpolation", "smooth"))
1062                 state.smooth = true;
1063         else if(xml_equal_string(node, "interpolation", "flat"))
1064                 state.smooth = false;
1065
1066         /* read displacement method */
1067         if(xml_equal_string(node, "displacement_method", "true"))
1068                 state.displacement_method = Mesh::DISPLACE_TRUE;
1069         else if(xml_equal_string(node, "displacement_method", "bump"))
1070                 state.displacement_method = Mesh::DISPLACE_BUMP;
1071         else if(xml_equal_string(node, "displacement_method", "both"))
1072                 state.displacement_method = Mesh::DISPLACE_BOTH;
1073 }
1074
1075 /* Scene */
1076
1077 static void xml_read_include(const XMLReadState& state, const string& src);
1078
1079 static void xml_read_scene(const XMLReadState& state, pugi::xml_node scene_node)
1080 {
1081         for(pugi::xml_node node = scene_node.first_child(); node; node = node.next_sibling()) {
1082                 if(string_iequals(node.name(), "film")) {
1083                         xml_read_film(state, node);
1084                 }
1085                 else if(string_iequals(node.name(), "integrator")) {
1086                         xml_read_integrator(state, node);
1087                 }
1088                 else if(string_iequals(node.name(), "camera")) {
1089                         xml_read_camera(state, node);
1090                 }
1091                 else if(string_iequals(node.name(), "shader")) {
1092                         xml_read_shader(state, node);
1093                 }
1094                 else if(string_iequals(node.name(), "background")) {
1095                         xml_read_background(state, node);
1096                 }
1097                 else if(string_iequals(node.name(), "mesh")) {
1098                         xml_read_mesh(state, node);
1099                 }
1100                 else if(string_iequals(node.name(), "patch")) {
1101                         xml_read_patch(state, node);
1102                 }
1103                 else if(string_iequals(node.name(), "light")) {
1104                         xml_read_light(state, node);
1105                 }
1106                 else if(string_iequals(node.name(), "transform")) {
1107                         XMLReadState substate = state;
1108
1109                         xml_read_transform(node, substate.tfm);
1110                         xml_read_scene(substate, node);
1111                 }
1112                 else if(string_iequals(node.name(), "state")) {
1113                         XMLReadState substate = state;
1114
1115                         xml_read_state(substate, node);
1116                         xml_read_scene(substate, node);
1117                 }
1118                 else if(string_iequals(node.name(), "include")) {
1119                         string src;
1120
1121                         if(xml_read_string(&src, node, "src"))
1122                                 xml_read_include(state, src);
1123                 }
1124                 else
1125                         fprintf(stderr, "Unknown node \"%s\".\n", node.name());
1126         }
1127 }
1128
1129 /* Include */
1130
1131 static void xml_read_include(const XMLReadState& state, const string& src)
1132 {
1133         /* open XML document */
1134         pugi::xml_document doc;
1135         pugi::xml_parse_result parse_result;
1136
1137         string path = path_join(state.base, src);
1138         parse_result = doc.load_file(path.c_str());
1139
1140         if(parse_result) {
1141                 XMLReadState substate = state;
1142                 substate.base = path_dirname(path);
1143
1144                 xml_read_scene(substate, doc);
1145         }
1146         else {
1147                 fprintf(stderr, "%s read error: %s\n", src.c_str(), parse_result.description());
1148                 exit(EXIT_FAILURE);
1149         }
1150 }
1151
1152 /* File */
1153
1154 void xml_read_file(Scene *scene, const char *filepath)
1155 {
1156         XMLReadState state;
1157
1158         state.scene = scene;
1159         state.tfm = transform_identity();
1160         state.shader = scene->default_surface;
1161         state.smooth = false;
1162         state.dicing_rate = 0.1f;
1163         state.base = path_dirname(filepath);
1164
1165         xml_read_include(state, path_filename(filepath));
1166
1167         scene->params.bvh_type = SceneParams::BVH_STATIC;
1168 }
1169
1170 CCL_NAMESPACE_END
1171