Fix Cycles bug rendering with multiple UV maps after recent changes.
[blender.git] / intern / cycles / blender / blender_mesh.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 "render/mesh.h"
18 #include "render/object.h"
19 #include "render/scene.h"
20 #include "render/camera.h"
21
22 #include "blender/blender_sync.h"
23 #include "blender/blender_session.h"
24 #include "blender/blender_util.h"
25
26 #include "subd/subd_patch.h"
27 #include "subd/subd_split.h"
28
29 #include "util/util_algorithm.h"
30 #include "util/util_foreach.h"
31 #include "util/util_logging.h"
32 #include "util/util_math.h"
33
34 #include "mikktspace.h"
35
36 CCL_NAMESPACE_BEGIN
37
38 /* Per-face bit flags. */
39 enum {
40         /* Face has no special flags. */
41         FACE_FLAG_NONE      = (0 << 0),
42         /* Quad face was split using 1-3 diagonal. */
43         FACE_FLAG_DIVIDE_13 = (1 << 0),
44         /* Quad face was split using 2-4 diagonal. */
45         FACE_FLAG_DIVIDE_24 = (1 << 1),
46 };
47
48 /* Get vertex indices to create triangles from a given face.
49  *
50  * Two triangles has vertex indices in the original Blender-side face.
51  * If face is already a quad tri_b will not be initialized.
52  */
53 inline void face_split_tri_indices(const int face_flag,
54                                    int tri_a[3],
55                                    int tri_b[3])
56 {
57         if(face_flag & FACE_FLAG_DIVIDE_24) {
58                 tri_a[0] = 0;
59                 tri_a[1] = 1;
60                 tri_a[2] = 3;
61
62                 tri_b[0] = 2;
63                 tri_b[1] = 3;
64                 tri_b[2] = 1;
65         }
66         else {
67                 /* Quad with FACE_FLAG_DIVIDE_13 or single triangle. */
68                 tri_a[0] = 0;
69                 tri_a[1] = 1;
70                 tri_a[2] = 2;
71
72                 tri_b[0] = 0;
73                 tri_b[1] = 2;
74                 tri_b[2] = 3;
75         }
76 }
77
78 /* Tangent Space */
79
80 struct MikkUserData {
81         MikkUserData(const BL::Mesh& b_mesh,
82                      const char *layer_name,
83                      const Mesh *mesh,
84                      float3 *tangent,
85                      float *tangent_sign)
86                 : mesh(mesh),
87                   texface(NULL),
88                   orco(NULL),
89                   tangent(tangent),
90                   tangent_sign(tangent_sign)
91         {
92                 const AttributeSet& attributes = (mesh->subd_faces.size()) ?
93                         mesh->subd_attributes : mesh->attributes;
94
95                 Attribute *attr_vN = attributes.find(ATTR_STD_VERTEX_NORMAL);
96                 vertex_normal = attr_vN->data_float3();
97
98                 if(layer_name == NULL) {
99                         Attribute *attr_orco = attributes.find(ATTR_STD_GENERATED);
100
101                         if(attr_orco) {
102                                 orco = attr_orco->data_float3();
103                                 mesh_texture_space(*(BL::Mesh*)&b_mesh, orco_loc, orco_size);
104                         }
105                 }
106                 else {
107                         Attribute *attr_uv = attributes.find(ustring(layer_name));
108                         if(attr_uv != NULL) {
109                                 texface = attr_uv->data_float2();
110                         }
111                 }
112         }
113
114         const Mesh *mesh;
115         int num_faces;
116
117         float3 *vertex_normal;
118         float2 *texface;
119         float3 *orco;
120         float3 orco_loc, orco_size;
121
122         float3 *tangent;
123         float *tangent_sign;
124 };
125
126 static int mikk_get_num_faces(const SMikkTSpaceContext *context)
127 {
128         const MikkUserData *userdata = (const MikkUserData *)context->m_pUserData;
129         if(userdata->mesh->subd_faces.size()) {
130                 return userdata->mesh->subd_faces.size();
131         }
132         else {
133                 return userdata->mesh->num_triangles();
134         }
135 }
136
137 static int mikk_get_num_verts_of_face(const SMikkTSpaceContext *context,
138                                       const int face_num)
139 {
140         const MikkUserData *userdata = (const MikkUserData *)context->m_pUserData;
141         if(userdata->mesh->subd_faces.size()) {
142                 const Mesh *mesh = userdata->mesh;
143                 return mesh->subd_faces[face_num].num_corners;
144         }
145         else {
146                 return 3;
147         }
148 }
149
150 static int mikk_vertex_index(const Mesh *mesh, const int face_num, const int vert_num)
151 {
152         if(mesh->subd_faces.size()) {
153                 const Mesh::SubdFace& face = mesh->subd_faces[face_num];
154                 return mesh->subd_face_corners[face.start_corner + vert_num];
155         }
156         else {
157                 return mesh->triangles[face_num * 3 + vert_num];
158         }
159 }
160
161 static int mikk_corner_index(const Mesh *mesh, const int face_num, const int vert_num)
162 {
163         if(mesh->subd_faces.size()) {
164                 const Mesh::SubdFace& face = mesh->subd_faces[face_num];
165                 return face.start_corner + vert_num;
166         }
167         else {
168                 return face_num * 3 + vert_num;
169         }
170 }
171
172 static void mikk_get_position(const SMikkTSpaceContext *context,
173                               float P[3],
174                               const int face_num, const int vert_num)
175 {
176         const MikkUserData *userdata = (const MikkUserData *)context->m_pUserData;
177         const Mesh *mesh = userdata->mesh;
178         const int vertex_index = mikk_vertex_index(mesh, face_num, vert_num);
179         const float3 vP = mesh->verts[vertex_index];
180         P[0] = vP.x;
181         P[1] = vP.y;
182         P[2] = vP.z;
183 }
184
185 static void mikk_get_texture_coordinate(const SMikkTSpaceContext *context,
186                                         float uv[2],
187                                         const int face_num, const int vert_num)
188 {
189         const MikkUserData *userdata = (const MikkUserData *)context->m_pUserData;
190         const Mesh *mesh = userdata->mesh;
191         if(userdata->texface != NULL) {
192                 const int corner_index = mikk_corner_index(mesh, face_num, vert_num);
193                 float2 tfuv = userdata->texface[corner_index];
194                 uv[0] = tfuv.x;
195                 uv[1] = tfuv.y;
196         }
197         else if(userdata->orco != NULL) {
198                 const int vertex_index = mikk_vertex_index(mesh, face_num, vert_num);
199                 const float3 orco_loc = userdata->orco_loc;
200                 const float3 orco_size = userdata->orco_size;
201                 const float3 orco = (userdata->orco[vertex_index] + orco_loc) / orco_size;
202
203                 const float2 tmp = map_to_sphere(orco);
204                 uv[0] = tmp.x;
205                 uv[1] = tmp.y;
206         }
207         else {
208                 uv[0] = 0.0f;
209                 uv[1] = 0.0f;
210         }
211 }
212
213 static void mikk_get_normal(const SMikkTSpaceContext *context, float N[3],
214                             const int face_num, const int vert_num)
215 {
216         const MikkUserData *userdata = (const MikkUserData *)context->m_pUserData;
217         const Mesh *mesh = userdata->mesh;
218         float3 vN;
219         if(mesh->subd_faces.size()) {
220                 const Mesh::SubdFace& face = mesh->subd_faces[face_num];
221                 if(face.smooth) {
222                         const int vertex_index = mikk_vertex_index(mesh, face_num, vert_num);
223                         vN = userdata->vertex_normal[vertex_index];
224                 }
225                 else {
226                         vN = face.normal(mesh);
227                 }
228         }
229         else {
230                 if(mesh->smooth[face_num]) {
231                         const int vertex_index = mikk_vertex_index(mesh, face_num, vert_num);
232                         vN = userdata->vertex_normal[vertex_index];
233                 }
234                 else {
235                         const Mesh::Triangle tri = mesh->get_triangle(face_num);
236                         vN = tri.compute_normal(&mesh->verts[0]);
237                 }
238         }
239         N[0] = vN.x;
240         N[1] = vN.y;
241         N[2] = vN.z;
242 }
243
244 static void mikk_set_tangent_space(const SMikkTSpaceContext *context,
245                                    const float T[],
246                                    const float sign,
247                                    const int face_num, const int vert_num)
248 {
249         MikkUserData *userdata = (MikkUserData *)context->m_pUserData;
250         const Mesh *mesh = userdata->mesh;
251         const int corner_index = mikk_corner_index(mesh, face_num, vert_num);
252         userdata->tangent[corner_index] = make_float3(T[0], T[1], T[2]);
253         if(userdata->tangent_sign != NULL) {
254                 userdata->tangent_sign[corner_index] = sign;
255         }
256 }
257
258 static void mikk_compute_tangents(const BL::Mesh& b_mesh,
259                                   const char *layer_name,
260                                   Mesh *mesh,
261                                   bool need_sign,
262                                   bool active_render)
263 {
264         /* Create tangent attributes. */
265         AttributeSet& attributes = (mesh->subd_faces.size()) ?
266                 mesh->subd_attributes : mesh->attributes;
267         Attribute *attr;
268         ustring name;
269         if(layer_name != NULL) {
270                 name = ustring((string(layer_name) + ".tangent").c_str());
271         }
272         else {
273                 name = ustring("orco.tangent");
274         }
275         if(active_render) {
276                 attr = attributes.add(ATTR_STD_UV_TANGENT, name);
277         }
278         else {
279                 attr = attributes.add(name, TypeDesc::TypeVector, ATTR_ELEMENT_CORNER);
280         }
281         float3 *tangent = attr->data_float3();
282         /* Create bitangent sign attribute. */
283         float *tangent_sign = NULL;
284         if(need_sign) {
285                 Attribute *attr_sign;
286                 ustring name_sign;
287                 if(layer_name != NULL) {
288                         name_sign = ustring((string(layer_name) +
289                                                    ".tangent_sign").c_str());
290                 }
291                 else {
292                         name_sign = ustring("orco.tangent_sign");
293                 }
294
295                 if(active_render) {
296                         attr_sign = attributes.add(ATTR_STD_UV_TANGENT_SIGN, name_sign);
297                 }
298                 else {
299                         attr_sign = attributes.add(name_sign,
300                                                    TypeDesc::TypeFloat,
301                                                    ATTR_ELEMENT_CORNER);
302                 }
303                 tangent_sign = attr_sign->data_float();
304         }
305         /* Setup userdata. */
306         MikkUserData userdata(b_mesh, layer_name, mesh, tangent, tangent_sign);
307         /* Setup interface. */
308         SMikkTSpaceInterface sm_interface;
309         memset(&sm_interface, 0, sizeof(sm_interface));
310         sm_interface.m_getNumFaces = mikk_get_num_faces;
311         sm_interface.m_getNumVerticesOfFace = mikk_get_num_verts_of_face;
312         sm_interface.m_getPosition = mikk_get_position;
313         sm_interface.m_getTexCoord = mikk_get_texture_coordinate;
314         sm_interface.m_getNormal = mikk_get_normal;
315         sm_interface.m_setTSpaceBasic = mikk_set_tangent_space;
316         /* Setup context. */
317         SMikkTSpaceContext context;
318         memset(&context, 0, sizeof(context));
319         context.m_pUserData = &userdata;
320         context.m_pInterface = &sm_interface;
321         /* Compute tangents. */
322         genTangSpaceDefault(&context);
323 }
324
325 /* Create Volume Attribute */
326
327 static void create_mesh_volume_attribute(BL::Object& b_ob,
328                                          Mesh *mesh,
329                                          ImageManager *image_manager,
330                                          AttributeStandard std,
331                                          float frame)
332 {
333         BL::SmokeDomainSettings b_domain = object_smoke_domain_find(b_ob);
334
335         if(!b_domain)
336                 return;
337
338         mesh->volume_isovalue = b_domain.clipping();
339
340         Attribute *attr = mesh->attributes.add(std);
341         VoxelAttribute *volume_data = attr->data_voxel();
342         ImageMetaData metadata;
343         bool animated = false;
344         bool use_alpha = true;
345
346         volume_data->manager = image_manager;
347         volume_data->slot = image_manager->add_image(
348                 Attribute::standard_name(std),
349                 b_ob.ptr.data,
350                 animated,
351                 frame,
352                 INTERPOLATION_LINEAR,
353                 EXTENSION_CLIP,
354                 use_alpha,
355                 metadata);
356 }
357
358 static void create_mesh_volume_attributes(Scene *scene,
359                                           BL::Object& b_ob,
360                                           Mesh *mesh,
361                                           float frame)
362 {
363         /* for smoke volume rendering */
364         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_DENSITY))
365                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_DENSITY, frame);
366         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_COLOR))
367                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_COLOR, frame);
368         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_FLAME))
369                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_FLAME, frame);
370         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_HEAT))
371                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_HEAT, frame);
372         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_TEMPERATURE))
373                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_TEMPERATURE, frame);
374         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_VELOCITY))
375                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_VELOCITY, frame);
376 }
377
378 /* Create vertex color attributes. */
379 static void attr_create_vertex_color(Scene *scene,
380                                      Mesh *mesh,
381                                      BL::Mesh& b_mesh,
382                                      const vector<int>& nverts,
383                                      const vector<int>& face_flags,
384                                      bool subdivision)
385 {
386         if(subdivision) {
387                 BL::Mesh::vertex_colors_iterator l;
388
389                 for(b_mesh.vertex_colors.begin(l); l != b_mesh.vertex_colors.end(); ++l) {
390                         if(!mesh->need_attribute(scene, ustring(l->name().c_str())))
391                                 continue;
392
393                         Attribute *attr = mesh->subd_attributes.add(ustring(l->name().c_str()),
394                                                                     TypeDesc::TypeColor,
395                                                                     ATTR_ELEMENT_CORNER_BYTE);
396
397                         BL::Mesh::polygons_iterator p;
398                         uchar4 *cdata = attr->data_uchar4();
399
400                         for(b_mesh.polygons.begin(p); p != b_mesh.polygons.end(); ++p) {
401                                 int n = p->loop_total();
402                                 for(int i = 0; i < n; i++) {
403                                         float3 color = get_float3(l->data[p->loop_start() + i].color());
404                                         /* Encode vertex color using the sRGB curve. */
405                                         *(cdata++) = color_float_to_byte(color_srgb_to_linear_v3(color));
406                                 }
407                         }
408                 }
409         }
410         else {
411                 BL::Mesh::tessface_vertex_colors_iterator l;
412                 for(b_mesh.tessface_vertex_colors.begin(l); l != b_mesh.tessface_vertex_colors.end(); ++l) {
413                         if(!mesh->need_attribute(scene, ustring(l->name().c_str())))
414                                 continue;
415
416                         Attribute *attr = mesh->attributes.add(ustring(l->name().c_str()),
417                                                                TypeDesc::TypeColor,
418                                                                ATTR_ELEMENT_CORNER_BYTE);
419
420                         BL::MeshColorLayer::data_iterator c;
421                         uchar4 *cdata = attr->data_uchar4();
422                         size_t i = 0;
423
424                         for(l->data.begin(c); c != l->data.end(); ++c, ++i) {
425                                 int tri_a[3], tri_b[3];
426                                 face_split_tri_indices(face_flags[i], tri_a, tri_b);
427
428                                 /* Encode vertex color using the sRGB curve. */
429                                 uchar4 colors[4];
430                                 colors[0] = color_float_to_byte(color_srgb_to_linear_v3(get_float3(c->color1())));
431                                 colors[1] = color_float_to_byte(color_srgb_to_linear_v3(get_float3(c->color2())));
432                                 colors[2] = color_float_to_byte(color_srgb_to_linear_v3(get_float3(c->color3())));
433                                 if(nverts[i] == 4) {
434                                         colors[3] = color_float_to_byte(color_srgb_to_linear_v3(get_float3(c->color4())));
435                                 }
436
437                                 cdata[0] = colors[tri_a[0]];
438                                 cdata[1] = colors[tri_a[1]];
439                                 cdata[2] = colors[tri_a[2]];
440
441                                 if(nverts[i] == 4) {
442                                         cdata[3] = colors[tri_b[0]];
443                                         cdata[4] = colors[tri_b[1]];
444                                         cdata[5] = colors[tri_b[2]];
445                                         cdata += 6;
446                                 }
447                                 else
448                                         cdata += 3;
449                         }
450                 }
451         }
452 }
453
454 /* Create uv map attributes. */
455 static void attr_create_uv_map(Scene *scene,
456                                Mesh *mesh,
457                                BL::Mesh& b_mesh,
458                                const vector<int>& nverts,
459                                const vector<int>& face_flags)
460 {
461         if(b_mesh.tessface_uv_textures.length() != 0) {
462                 BL::Mesh::tessface_uv_textures_iterator l;
463
464                 for(b_mesh.tessface_uv_textures.begin(l); l != b_mesh.tessface_uv_textures.end(); ++l) {
465                         const bool active_render = l->active_render();
466                         AttributeStandard uv_std = (active_render)? ATTR_STD_UV: ATTR_STD_NONE;
467                         ustring uv_name = ustring(l->name().c_str());
468                         AttributeStandard tangent_std = (active_render)? ATTR_STD_UV_TANGENT
469                                                                        : ATTR_STD_NONE;
470                         ustring tangent_name = ustring(
471                                 (string(l->name().c_str()) + ".tangent").c_str());
472
473                         /* Denotes whether UV map was requested directly. */
474                         const bool need_uv = mesh->need_attribute(scene, uv_name) ||
475                                              mesh->need_attribute(scene, uv_std);
476                         /* Denotes whether tangent was requested directly. */
477                         const bool need_tangent =
478                                mesh->need_attribute(scene, tangent_name) ||
479                                (active_render && mesh->need_attribute(scene, tangent_std));
480
481                         /* UV map */
482                         /* NOTE: We create temporary UV layer if its needed for tangent but
483                          * wasn't requested by other nodes in shaders.
484                          */
485                         Attribute *uv_attr = NULL;
486                         if(need_uv || need_tangent) {
487                                 if(active_render) {
488                                         uv_attr = mesh->attributes.add(uv_std, uv_name);
489                                 }
490                                 else {
491                                         uv_attr = mesh->attributes.add(uv_name,
492                                                                        TypeFloat2,
493                                                                        ATTR_ELEMENT_CORNER);
494                                 }
495
496                                 BL::MeshTextureFaceLayer::data_iterator t;
497                                 float2 *fdata = uv_attr->data_float2();
498                                 size_t i = 0;
499
500                                 for(l->data.begin(t); t != l->data.end(); ++t, ++i) {
501                                         int tri_a[3], tri_b[3];
502                                         face_split_tri_indices(face_flags[i], tri_a, tri_b);
503
504                                         float2 uvs[4];
505                                         uvs[0] = get_float2(t->uv1());
506                                         uvs[1] = get_float2(t->uv2());
507                                         uvs[2] = get_float2(t->uv3());
508                                         if(nverts[i] == 4) {
509                                                 uvs[3] = get_float2(t->uv4());
510                                         }
511
512                                         fdata[0] = uvs[tri_a[0]];
513                                         fdata[1] = uvs[tri_a[1]];
514                                         fdata[2] = uvs[tri_a[2]];
515                                         fdata += 3;
516
517                                         if(nverts[i] == 4) {
518                                                 fdata[0] = uvs[tri_b[0]];
519                                                 fdata[1] = uvs[tri_b[1]];
520                                                 fdata[2] = uvs[tri_b[2]];
521                                                 fdata += 3;
522                                         }
523                                 }
524                         }
525
526                         /* UV tangent */
527                         if(need_tangent) {
528                                 AttributeStandard sign_std =
529                                         (active_render)? ATTR_STD_UV_TANGENT_SIGN
530                                                        : ATTR_STD_NONE;
531                                 ustring sign_name = ustring(
532                                         (string(l->name().c_str()) + ".tangent_sign").c_str());
533                                 bool need_sign = (mesh->need_attribute(scene, sign_name) ||
534                                                   mesh->need_attribute(scene, sign_std));
535                                 mikk_compute_tangents(b_mesh,
536                                                       l->name().c_str(),
537                                                       mesh,
538                                                       need_sign,
539                                                       active_render);
540                         }
541                         /* Remove temporarily created UV attribute. */
542                         if(!need_uv && uv_attr != NULL) {
543                                 mesh->attributes.remove(uv_attr);
544                         }
545                 }
546         }
547         else if(mesh->need_attribute(scene, ATTR_STD_UV_TANGENT)) {
548                 bool need_sign = mesh->need_attribute(scene, ATTR_STD_UV_TANGENT_SIGN);
549                 mikk_compute_tangents(b_mesh, NULL, mesh, need_sign, true);
550                 if(!mesh->need_attribute(scene, ATTR_STD_GENERATED)) {
551                         mesh->attributes.remove(ATTR_STD_GENERATED);
552                 }
553         }
554 }
555
556 static void attr_create_subd_uv_map(Scene *scene,
557                                     Mesh *mesh,
558                                     BL::Mesh& b_mesh,
559                                     bool subdivide_uvs)
560 {
561         if(b_mesh.uv_layers.length() != 0) {
562                 BL::Mesh::uv_layers_iterator l;
563                 int i = 0;
564
565                 for(b_mesh.uv_layers.begin(l); l != b_mesh.uv_layers.end(); ++l, ++i) {
566                         bool active_render = b_mesh.uv_textures[i].active_render();
567                         AttributeStandard uv_std = (active_render)? ATTR_STD_UV: ATTR_STD_NONE;
568                         ustring uv_name = ustring(l->name().c_str());
569                         AttributeStandard tangent_std = (active_render)? ATTR_STD_UV_TANGENT
570                                                                        : ATTR_STD_NONE;
571                         ustring tangent_name = ustring(
572                                 (string(l->name().c_str()) + ".tangent").c_str());
573
574                         /* Denotes whether UV map was requested directly. */
575                         const bool need_uv = mesh->need_attribute(scene, uv_name) ||
576                                              mesh->need_attribute(scene, uv_std);
577                         /* Denotes whether tangent was requested directly. */
578                         const bool need_tangent =
579                                mesh->need_attribute(scene, tangent_name) ||
580                                (active_render && mesh->need_attribute(scene, tangent_std));
581
582                         Attribute *uv_attr = NULL;
583
584                         /* UV map */
585                         if(need_uv || need_tangent) {
586                                 if(active_render)
587                                         uv_attr = mesh->subd_attributes.add(uv_std, uv_name);
588                                 else
589                                         uv_attr = mesh->subd_attributes.add(uv_name, TypeFloat2, ATTR_ELEMENT_CORNER);
590
591                                 if(subdivide_uvs) {
592                                         uv_attr->flags |= ATTR_SUBDIVIDED;
593                                 }
594
595                                 BL::Mesh::polygons_iterator p;
596                                 float2 *fdata = uv_attr->data_float2();
597
598                                 for(b_mesh.polygons.begin(p); p != b_mesh.polygons.end(); ++p) {
599                                         int n = p->loop_total();
600                                         for(int j = 0; j < n; j++) {
601                                                 *(fdata++) = get_float2(l->data[p->loop_start() + j].uv());
602                                         }
603                                 }
604                         }
605
606                         /* UV tangent */
607                         if(need_tangent) {
608                                 AttributeStandard sign_std =
609                                         (active_render)? ATTR_STD_UV_TANGENT_SIGN
610                                                        : ATTR_STD_NONE;
611                                 ustring sign_name = ustring(
612                                         (string(l->name().c_str()) + ".tangent_sign").c_str());
613                                 bool need_sign = (mesh->need_attribute(scene, sign_name) ||
614                                                   mesh->need_attribute(scene, sign_std));
615                                 mikk_compute_tangents(b_mesh,
616                                                       l->name().c_str(),
617                                                       mesh,
618                                                       need_sign,
619                                                       active_render);
620                         }
621                         /* Remove temporarily created UV attribute. */
622                         if(!need_uv && uv_attr != NULL) {
623                                 mesh->subd_attributes.remove(uv_attr);
624                         }
625                 }
626         }
627         else if(mesh->need_attribute(scene, ATTR_STD_UV_TANGENT)) {
628                 bool need_sign = mesh->need_attribute(scene, ATTR_STD_UV_TANGENT_SIGN);
629                 mikk_compute_tangents(b_mesh, NULL, mesh, need_sign, true);
630                 if(!mesh->need_attribute(scene, ATTR_STD_GENERATED)) {
631                         mesh->subd_attributes.remove(ATTR_STD_GENERATED);
632                 }
633         }
634 }
635
636 /* Create vertex pointiness attributes. */
637
638 /* Compare vertices by sum of their coordinates. */
639 class VertexAverageComparator {
640 public:
641         VertexAverageComparator(const array<float3>& verts)
642                 : verts_(verts) {
643         }
644
645         bool operator()(const int& vert_idx_a, const int& vert_idx_b)
646         {
647                 const float3 &vert_a = verts_[vert_idx_a];
648                 const float3 &vert_b = verts_[vert_idx_b];
649                 if(vert_a == vert_b) {
650                         /* Special case for doubles, so we ensure ordering. */
651                         return vert_idx_a > vert_idx_b;
652                 }
653                 const float x1 = vert_a.x + vert_a.y + vert_a.z;
654                 const float x2 = vert_b.x + vert_b.y + vert_b.z;
655                 return x1 < x2;
656         }
657
658 protected:
659         const array<float3>& verts_;
660 };
661
662 static void attr_create_pointiness(Scene *scene,
663                                    Mesh *mesh,
664                                    BL::Mesh& b_mesh,
665                                    bool subdivision)
666 {
667         if(!mesh->need_attribute(scene, ATTR_STD_POINTINESS)) {
668                 return;
669         }
670         const int num_verts = b_mesh.vertices.length();
671         if(num_verts == 0) {
672                 return;
673         }
674         /* STEP 1: Find out duplicated vertices and point duplicates to a single
675          *         original vertex.
676          */
677         vector<int> sorted_vert_indeices(num_verts);
678         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
679                 sorted_vert_indeices[vert_index] = vert_index;
680         }
681         VertexAverageComparator compare(mesh->verts);
682         sort(sorted_vert_indeices.begin(), sorted_vert_indeices.end(), compare);
683         /* This array stores index of the original vertex for the given vertex
684          * index.
685          */
686         vector<int> vert_orig_index(num_verts);
687         for(int sorted_vert_index = 0;
688             sorted_vert_index < num_verts;
689             ++sorted_vert_index)
690         {
691                 const int vert_index = sorted_vert_indeices[sorted_vert_index];
692                 const float3 &vert_co = mesh->verts[vert_index];
693                 bool found = false;
694                 for(int other_sorted_vert_index = sorted_vert_index + 1;
695                     other_sorted_vert_index < num_verts;
696                     ++other_sorted_vert_index)
697                 {
698                         const int other_vert_index =
699                                 sorted_vert_indeices[other_sorted_vert_index];
700                         const float3 &other_vert_co = mesh->verts[other_vert_index];
701                         /* We are too far away now, we wouldn't have duplicate. */
702                         if((other_vert_co.x + other_vert_co.y + other_vert_co.z) -
703                            (vert_co.x + vert_co.y + vert_co.z) > 3 * FLT_EPSILON)
704                         {
705                                 break;
706                         }
707                         /* Found duplicate. */
708                         if(len_squared(other_vert_co - vert_co) < FLT_EPSILON) {
709                                 found = true;
710                                 vert_orig_index[vert_index] = other_vert_index;
711                                 break;
712                         }
713                 }
714                 if(!found) {
715                         vert_orig_index[vert_index] = vert_index;
716                 }
717         }
718         /* Make sure we always points to the very first orig vertex. */
719         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
720                 int orig_index = vert_orig_index[vert_index];
721                 while(orig_index != vert_orig_index[orig_index]) {
722                         orig_index = vert_orig_index[orig_index];
723                 }
724                 vert_orig_index[vert_index] = orig_index;
725         }
726         sorted_vert_indeices.free_memory();
727         /* STEP 2: Calculate vertex normals taking into account their possible
728          *         duplicates which gets "welded" together.
729          */
730         vector<float3> vert_normal(num_verts, make_float3(0.0f, 0.0f, 0.0f));
731         /* First we accumulate all vertex normals in the original index. */
732         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
733                 const float3 normal = get_float3(b_mesh.vertices[vert_index].normal());
734                 const int orig_index = vert_orig_index[vert_index];
735                 vert_normal[orig_index] += normal;
736         }
737         /* Then we normalize the accumulated result and flush it to all duplicates
738          * as well.
739          */
740         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
741                 const int orig_index = vert_orig_index[vert_index];
742                 vert_normal[vert_index] = normalize(vert_normal[orig_index]);
743         }
744         /* STEP 3: Calculate pointiness using single ring neighborhood. */
745         vector<int> counter(num_verts, 0);
746         vector<float> raw_data(num_verts, 0.0f);
747         vector<float3> edge_accum(num_verts, make_float3(0.0f, 0.0f, 0.0f));
748         BL::Mesh::edges_iterator e;
749         EdgeMap visited_edges;
750         int edge_index = 0;
751         memset(&counter[0], 0, sizeof(int) * counter.size());
752         for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e, ++edge_index) {
753                 const int v0 = vert_orig_index[b_mesh.edges[edge_index].vertices()[0]],
754                           v1 = vert_orig_index[b_mesh.edges[edge_index].vertices()[1]];
755                 if(visited_edges.exists(v0, v1)) {
756                         continue;
757                 }
758                 visited_edges.insert(v0, v1);
759                 float3 co0 = get_float3(b_mesh.vertices[v0].co()),
760                        co1 = get_float3(b_mesh.vertices[v1].co());
761                 float3 edge = normalize(co1 - co0);
762                 edge_accum[v0] += edge;
763                 edge_accum[v1] += -edge;
764                 ++counter[v0];
765                 ++counter[v1];
766         }
767         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
768                 const int orig_index = vert_orig_index[vert_index];
769                 if(orig_index != vert_index) {
770                         /* Skip duplicates, they'll be overwritten later on. */
771                         continue;
772                 }
773                 if(counter[vert_index] > 0) {
774                         const float3 normal = vert_normal[vert_index];
775                         const float angle =
776                                 safe_acosf(dot(normal,
777                                                edge_accum[vert_index] / counter[vert_index]));
778                         raw_data[vert_index] = angle * M_1_PI_F;
779                 }
780                 else {
781                         raw_data[vert_index] = 0.0f;
782                 }
783         }
784         /* STEP 3: Blur vertices to approximate 2 ring neighborhood. */
785         AttributeSet& attributes = (subdivision)? mesh->subd_attributes: mesh->attributes;
786         Attribute *attr = attributes.add(ATTR_STD_POINTINESS);
787         float *data = attr->data_float();
788         memcpy(data, &raw_data[0], sizeof(float) * raw_data.size());
789         memset(&counter[0], 0, sizeof(int) * counter.size());
790         edge_index = 0;
791         visited_edges.clear();
792         for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e, ++edge_index) {
793                 const int v0 = vert_orig_index[b_mesh.edges[edge_index].vertices()[0]],
794                           v1 = vert_orig_index[b_mesh.edges[edge_index].vertices()[1]];
795                 if(visited_edges.exists(v0, v1)) {
796                         continue;
797                 }
798                 visited_edges.insert(v0, v1);
799                 data[v0] += raw_data[v1];
800                 data[v1] += raw_data[v0];
801                 ++counter[v0];
802                 ++counter[v1];
803         }
804         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
805                 data[vert_index] /= counter[vert_index] + 1;
806         }
807         /* STEP 4: Copy attribute to the duplicated vertices. */
808         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
809                 const int orig_index = vert_orig_index[vert_index];
810                 data[vert_index] = data[orig_index];
811         }
812 }
813
814 /* Create Mesh */
815
816 static void create_mesh(Scene *scene,
817                         Mesh *mesh,
818                         BL::Mesh& b_mesh,
819                         const vector<Shader*>& used_shaders,
820                         bool subdivision = false,
821                         bool subdivide_uvs = true)
822 {
823         /* count vertices and faces */
824         int numverts = b_mesh.vertices.length();
825         int numfaces = (!subdivision) ? b_mesh.tessfaces.length() : b_mesh.polygons.length();
826         int numtris = 0;
827         int numcorners = 0;
828         int numngons = 0;
829         bool use_loop_normals = b_mesh.use_auto_smooth() && (mesh->subdivision_type != Mesh::SUBDIVISION_CATMULL_CLARK);
830
831         /* If no faces, create empty mesh. */
832         if(numfaces == 0) {
833                 return;
834         }
835
836         BL::Mesh::vertices_iterator v;
837         BL::Mesh::tessfaces_iterator f;
838         BL::Mesh::polygons_iterator p;
839
840         if(!subdivision) {
841                 for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f) {
842                         int4 vi = get_int4(f->vertices_raw());
843                         numtris += (vi[3] == 0)? 1: 2;
844                 }
845         }
846         else {
847                 for(b_mesh.polygons.begin(p); p != b_mesh.polygons.end(); ++p) {
848                         numngons += (p->loop_total() == 4)? 0: 1;
849                         numcorners += p->loop_total();
850                 }
851         }
852
853         /* allocate memory */
854         mesh->reserve_mesh(numverts, numtris);
855         mesh->reserve_subd_faces(numfaces, numngons, numcorners);
856
857         /* create vertex coordinates and normals */
858         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
859                 mesh->add_vertex(get_float3(v->co()));
860
861         AttributeSet& attributes = (subdivision)? mesh->subd_attributes: mesh->attributes;
862         Attribute *attr_N = attributes.add(ATTR_STD_VERTEX_NORMAL);
863         float3 *N = attr_N->data_float3();
864
865         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v, ++N)
866                 *N = get_float3(v->normal());
867         N = attr_N->data_float3();
868
869         /* create generated coordinates from undeformed coordinates */
870         const bool need_default_tangent =
871                 (subdivision == false) &&
872                 (b_mesh.tessface_uv_textures.length() == 0) &&
873                 (mesh->need_attribute(scene, ATTR_STD_UV_TANGENT));
874         if(mesh->need_attribute(scene, ATTR_STD_GENERATED) ||
875            need_default_tangent)
876         {
877                 Attribute *attr = attributes.add(ATTR_STD_GENERATED);
878                 attr->flags |= ATTR_SUBDIVIDED;
879
880                 float3 loc, size;
881                 mesh_texture_space(b_mesh, loc, size);
882
883                 float3 *generated = attr->data_float3();
884                 size_t i = 0;
885
886                 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v) {
887                         generated[i++] = get_float3(v->undeformed_co())*size - loc;
888                 }
889         }
890
891         /* create faces */
892         vector<int> nverts(numfaces);
893         vector<int> face_flags(numfaces, FACE_FLAG_NONE);
894         int fi = 0;
895
896         if(!subdivision) {
897                 for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f, ++fi) {
898                         int4 vi = get_int4(f->vertices_raw());
899                         int n = (vi[3] == 0)? 3: 4;
900                         int shader = clamp(f->material_index(), 0, used_shaders.size()-1);
901                         bool smooth = f->use_smooth() || use_loop_normals;
902
903                         if(use_loop_normals) {
904                                 BL::Array<float, 12> loop_normals = f->split_normals();
905                                 for(int i = 0; i < n; i++) {
906                                         N[vi[i]] = make_float3(loop_normals[i * 3],
907                                                                loop_normals[i * 3 + 1],
908                                                                loop_normals[i * 3 + 2]);
909                                 }
910                         }
911
912                         /* Create triangles.
913                          *
914                          * NOTE: Autosmooth is already taken care about.
915                          */
916                         if(n == 4) {
917                                 if(is_zero(cross(mesh->verts[vi[1]] - mesh->verts[vi[0]], mesh->verts[vi[2]] - mesh->verts[vi[0]])) ||
918                                    is_zero(cross(mesh->verts[vi[2]] - mesh->verts[vi[0]], mesh->verts[vi[3]] - mesh->verts[vi[0]])))
919                                 {
920                                         mesh->add_triangle(vi[0], vi[1], vi[3], shader, smooth);
921                                         mesh->add_triangle(vi[2], vi[3], vi[1], shader, smooth);
922                                         face_flags[fi] |= FACE_FLAG_DIVIDE_24;
923                                 }
924                                 else {
925                                         mesh->add_triangle(vi[0], vi[1], vi[2], shader, smooth);
926                                         mesh->add_triangle(vi[0], vi[2], vi[3], shader, smooth);
927                                         face_flags[fi] |= FACE_FLAG_DIVIDE_13;
928                                 }
929                         }
930                         else {
931                                 mesh->add_triangle(vi[0], vi[1], vi[2], shader, smooth);
932                         }
933
934                         nverts[fi] = n;
935                 }
936         }
937         else {
938                 vector<int> vi;
939
940                 for(b_mesh.polygons.begin(p); p != b_mesh.polygons.end(); ++p) {
941                         int n = p->loop_total();
942                         int shader = clamp(p->material_index(), 0, used_shaders.size()-1);
943                         bool smooth = p->use_smooth() || use_loop_normals;
944
945                         vi.resize(n);
946                         for(int i = 0; i < n; i++) {
947                                 /* NOTE: Autosmooth is already taken care about. */
948                                 vi[i] = b_mesh.loops[p->loop_start() + i].vertex_index();
949                         }
950
951                         /* create subd faces */
952                         mesh->add_subd_face(&vi[0], n, shader, smooth);
953                 }
954         }
955
956         /* Create all needed attributes.
957          * The calculate functions will check whether they're needed or not.
958          */
959         attr_create_pointiness(scene, mesh, b_mesh, subdivision);
960         attr_create_vertex_color(scene, mesh, b_mesh, nverts, face_flags, subdivision);
961
962         if(subdivision) {
963                 attr_create_subd_uv_map(scene, mesh, b_mesh, subdivide_uvs);
964         }
965         else {
966                 attr_create_uv_map(scene, mesh, b_mesh, nverts, face_flags);
967         }
968
969         /* for volume objects, create a matrix to transform from object space to
970          * mesh texture space. this does not work with deformations but that can
971          * probably only be done well with a volume grid mapping of coordinates */
972         if(mesh->need_attribute(scene, ATTR_STD_GENERATED_TRANSFORM)) {
973                 Attribute *attr = mesh->attributes.add(ATTR_STD_GENERATED_TRANSFORM);
974                 Transform *tfm = attr->data_transform();
975
976                 float3 loc, size;
977                 mesh_texture_space(b_mesh, loc, size);
978
979                 *tfm = transform_translate(-loc)*transform_scale(size);
980         }
981 }
982
983 static void create_subd_mesh(Scene *scene,
984                              Mesh *mesh,
985                              BL::Object& b_ob,
986                              BL::Mesh& b_mesh,
987                              const vector<Shader*>& used_shaders,
988                              float dicing_rate,
989                              int max_subdivisions)
990 {
991         BL::SubsurfModifier subsurf_mod(b_ob.modifiers[b_ob.modifiers.length()-1]);
992         bool subdivide_uvs = subsurf_mod.use_subsurf_uv();
993
994         create_mesh(scene, mesh, b_mesh, used_shaders, true, subdivide_uvs);
995
996         /* export creases */
997         size_t num_creases = 0;
998         BL::Mesh::edges_iterator e;
999
1000         for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e) {
1001                 if(e->crease() != 0.0f) {
1002                         num_creases++;
1003                 }
1004         }
1005
1006         mesh->subd_creases.resize(num_creases);
1007
1008         Mesh::SubdEdgeCrease* crease = mesh->subd_creases.data();
1009         for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e) {
1010                 if(e->crease() != 0.0f) {
1011                         crease->v[0] = e->vertices()[0];
1012                         crease->v[1] = e->vertices()[1];
1013                         crease->crease = e->crease();
1014
1015                         crease++;
1016                 }
1017         }
1018
1019         /* set subd params */
1020         if(!mesh->subd_params) {
1021                 mesh->subd_params = new SubdParams(mesh);
1022         }
1023         SubdParams& sdparams = *mesh->subd_params;
1024
1025         PointerRNA cobj = RNA_pointer_get(&b_ob.ptr, "cycles");
1026
1027         sdparams.dicing_rate = max(0.1f, RNA_float_get(&cobj, "dicing_rate") * dicing_rate);
1028         sdparams.max_level = max_subdivisions;
1029
1030         scene->dicing_camera->update(scene);
1031         sdparams.camera = scene->dicing_camera;
1032         sdparams.objecttoworld = get_transform(b_ob.matrix_world());
1033 }
1034
1035 /* Sync */
1036
1037 static void sync_mesh_fluid_motion(BL::Object& b_ob, Scene *scene, Mesh *mesh)
1038 {
1039         if(scene->need_motion() == Scene::MOTION_NONE)
1040                 return;
1041
1042         BL::DomainFluidSettings b_fluid_domain = object_fluid_domain_find(b_ob);
1043
1044         if(!b_fluid_domain)
1045                 return;
1046
1047         /* If the mesh has modifiers following the fluid domain we can't export motion. */
1048         if(b_fluid_domain.fluid_mesh_vertices.length() != mesh->verts.size())
1049                 return;
1050
1051         /* Find or add attribute */
1052         float3 *P = &mesh->verts[0];
1053         Attribute *attr_mP = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
1054
1055         if(!attr_mP) {
1056                 attr_mP = mesh->attributes.add(ATTR_STD_MOTION_VERTEX_POSITION);
1057         }
1058
1059         /* Only export previous and next frame, we don't have any in between data. */
1060         float motion_times[2] = {-1.0f, 1.0f};
1061         for(int step = 0; step < 2; step++) {
1062                 float relative_time = motion_times[step] * scene->motion_shutter_time() * 0.5f;
1063                 float3 *mP = attr_mP->data_float3() + step*mesh->verts.size();
1064
1065                 BL::DomainFluidSettings::fluid_mesh_vertices_iterator fvi;
1066                 int i = 0;
1067
1068                 for(b_fluid_domain.fluid_mesh_vertices.begin(fvi); fvi != b_fluid_domain.fluid_mesh_vertices.end(); ++fvi, ++i) {
1069                         mP[i] = P[i] + get_float3(fvi->velocity()) * relative_time;
1070                 }
1071         }
1072 }
1073
1074 Mesh *BlenderSync::sync_mesh(BL::Object& b_ob,
1075                              bool object_updated,
1076                              bool hide_tris)
1077 {
1078         /* When viewport display is not needed during render we can force some
1079          * caches to be releases from blender side in order to reduce peak memory
1080          * footprint during synchronization process.
1081          */
1082         const bool is_interface_locked = b_engine.render() &&
1083                                          b_engine.render().use_lock_interface();
1084         const bool can_free_caches = BlenderSession::headless || is_interface_locked;
1085
1086         /* test if we can instance or if the object is modified */
1087         BL::ID b_ob_data = b_ob.data();
1088         BL::ID key = (BKE_object_is_modified(b_ob))? b_ob: b_ob_data;
1089         BL::Material material_override = render_layer.material_override;
1090
1091         /* find shader indices */
1092         vector<Shader*> used_shaders;
1093
1094         BL::Object::material_slots_iterator slot;
1095         for(b_ob.material_slots.begin(slot); slot != b_ob.material_slots.end(); ++slot) {
1096                 if(material_override) {
1097                         find_shader(material_override, used_shaders, scene->default_surface);
1098                 }
1099                 else {
1100                         BL::ID b_material(slot->material());
1101                         find_shader(b_material, used_shaders, scene->default_surface);
1102                 }
1103         }
1104
1105         if(used_shaders.size() == 0) {
1106                 if(material_override)
1107                         find_shader(material_override, used_shaders, scene->default_surface);
1108                 else
1109                         used_shaders.push_back(scene->default_surface);
1110         }
1111
1112         /* test if we need to sync */
1113         int requested_geometry_flags = Mesh::GEOMETRY_NONE;
1114         if(render_layer.use_surfaces) {
1115                 requested_geometry_flags |= Mesh::GEOMETRY_TRIANGLES;
1116         }
1117         if(render_layer.use_hair) {
1118                 requested_geometry_flags |= Mesh::GEOMETRY_CURVES;
1119         }
1120         Mesh *mesh;
1121
1122         if(!mesh_map.sync(&mesh, key)) {
1123                 /* if transform was applied to mesh, need full update */
1124                 if(object_updated && mesh->transform_applied);
1125                 /* test if shaders changed, these can be object level so mesh
1126                  * does not get tagged for recalc */
1127                 else if(mesh->used_shaders != used_shaders);
1128                 else if(requested_geometry_flags != mesh->geometry_flags);
1129                 else {
1130                         /* even if not tagged for recalc, we may need to sync anyway
1131                          * because the shader needs different mesh attributes */
1132                         bool attribute_recalc = false;
1133
1134                         foreach(Shader *shader, mesh->used_shaders)
1135                                 if(shader->need_update_mesh)
1136                                         attribute_recalc = true;
1137
1138                         if(!attribute_recalc)
1139                                 return mesh;
1140                 }
1141         }
1142
1143         /* ensure we only sync instanced meshes once */
1144         if(mesh_synced.find(mesh) != mesh_synced.end())
1145                 return mesh;
1146
1147         mesh_synced.insert(mesh);
1148
1149         /* create derived mesh */
1150         array<int> oldtriangles;
1151         array<Mesh::SubdFace> oldsubd_faces;
1152         array<int> oldsubd_face_corners;
1153         oldtriangles.steal_data(mesh->triangles);
1154         oldsubd_faces.steal_data(mesh->subd_faces);
1155         oldsubd_face_corners.steal_data(mesh->subd_face_corners);
1156
1157         /* compares curve_keys rather than strands in order to handle quick hair
1158          * adjustments in dynamic BVH - other methods could probably do this better*/
1159         array<float3> oldcurve_keys;
1160         array<float> oldcurve_radius;
1161         oldcurve_keys.steal_data(mesh->curve_keys);
1162         oldcurve_radius.steal_data(mesh->curve_radius);
1163
1164         mesh->clear();
1165         mesh->used_shaders = used_shaders;
1166         mesh->name = ustring(b_ob_data.name().c_str());
1167
1168         if(requested_geometry_flags != Mesh::GEOMETRY_NONE) {
1169                 /* mesh objects does have special handle in the dependency graph,
1170                  * they're ensured to have properly updated.
1171                  *
1172                  * updating meshes here will end up having derived mesh referencing
1173                  * freed data from the blender side.
1174                  */
1175                 if(preview && b_ob.type() != BL::Object::type_MESH)
1176                         b_ob.update_from_editmode(b_data);
1177
1178                 bool need_undeformed = mesh->need_attribute(scene, ATTR_STD_GENERATED);
1179
1180                 mesh->subdivision_type = object_subdivision_type(b_ob, preview, experimental);
1181
1182                 /* Disable adaptive subdivision while baking as the baking system
1183                  * currently doesnt support the topology and will crash.
1184                  */
1185                 if(scene->bake_manager->get_baking()) {
1186                         mesh->subdivision_type = Mesh::SUBDIVISION_NONE;
1187                 }
1188
1189                 BL::Mesh b_mesh = object_to_mesh(b_data,
1190                                                  b_ob,
1191                                                  b_scene,
1192                                                  true,
1193                                                  !preview,
1194                                                  need_undeformed,
1195                                                  mesh->subdivision_type);
1196
1197                 if(b_mesh) {
1198                         if(render_layer.use_surfaces && !hide_tris) {
1199                                 if(mesh->subdivision_type != Mesh::SUBDIVISION_NONE)
1200                                         create_subd_mesh(scene, mesh, b_ob, b_mesh, used_shaders,
1201                                                          dicing_rate, max_subdivisions);
1202                                 else
1203                                         create_mesh(scene, mesh, b_mesh, used_shaders, false);
1204
1205                                 create_mesh_volume_attributes(scene, b_ob, mesh, b_scene.frame_current());
1206                         }
1207
1208                         if(render_layer.use_hair && mesh->subdivision_type == Mesh::SUBDIVISION_NONE)
1209                                 sync_curves(mesh, b_mesh, b_ob, false);
1210
1211                         if(can_free_caches) {
1212                                 b_ob.cache_release();
1213                         }
1214
1215                         /* free derived mesh */
1216                         b_data.meshes.remove(b_mesh, false, true, false);
1217                 }
1218         }
1219         mesh->geometry_flags = requested_geometry_flags;
1220
1221         /* fluid motion */
1222         sync_mesh_fluid_motion(b_ob, scene, mesh);
1223
1224         /* tag update */
1225         bool rebuild = (oldtriangles != mesh->triangles) ||
1226                        (oldsubd_faces != mesh->subd_faces) ||
1227                        (oldsubd_face_corners != mesh->subd_face_corners) ||
1228                        (oldcurve_keys != mesh->curve_keys) ||
1229                        (oldcurve_radius != mesh->curve_radius);
1230
1231         mesh->tag_update(scene, rebuild);
1232
1233         return mesh;
1234 }
1235
1236 void BlenderSync::sync_mesh_motion(BL::Object& b_ob,
1237                                    Object *object,
1238                                    float motion_time)
1239 {
1240         /* ensure we only sync instanced meshes once */
1241         Mesh *mesh = object->mesh;
1242
1243         if(mesh_motion_synced.find(mesh) != mesh_motion_synced.end())
1244                 return;
1245
1246         mesh_motion_synced.insert(mesh);
1247
1248         /* ensure we only motion sync meshes that also had mesh synced, to avoid
1249          * unnecessary work and to ensure that its attributes were clear */
1250         if(mesh_synced.find(mesh) == mesh_synced.end())
1251                 return;
1252
1253         /* Find time matching motion step required by mesh. */
1254         int motion_step = mesh->motion_step(motion_time);
1255         if(motion_step < 0) {
1256                 return;
1257         }
1258
1259         /* skip empty meshes */
1260         const size_t numverts = mesh->verts.size();
1261         const size_t numkeys = mesh->curve_keys.size();
1262
1263         if(!numverts && !numkeys)
1264                 return;
1265
1266         /* skip objects without deforming modifiers. this is not totally reliable,
1267          * would need a more extensive check to see which objects are animated */
1268         BL::Mesh b_mesh(PointerRNA_NULL);
1269
1270         /* fluid motion is exported immediate with mesh, skip here */
1271         BL::DomainFluidSettings b_fluid_domain = object_fluid_domain_find(b_ob);
1272         if(b_fluid_domain)
1273                 return;
1274
1275         if(ccl::BKE_object_is_deform_modified(b_ob, b_scene, preview)) {
1276                 /* get derived mesh */
1277                 b_mesh = object_to_mesh(b_data,
1278                                         b_ob,
1279                                         b_scene,
1280                                         true,
1281                                         !preview,
1282                                         false,
1283                                         Mesh::SUBDIVISION_NONE);
1284         }
1285
1286         if(!b_mesh) {
1287                 /* if we have no motion blur on this frame, but on other frames, copy */
1288                 if(numverts) {
1289                         /* triangles */
1290                         Attribute *attr_mP = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
1291
1292                         if(attr_mP) {
1293                                 Attribute *attr_mN = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_NORMAL);
1294                                 Attribute *attr_N = mesh->attributes.find(ATTR_STD_VERTEX_NORMAL);
1295                                 float3 *P = &mesh->verts[0];
1296                                 float3 *N = (attr_N)? attr_N->data_float3(): NULL;
1297
1298                                 memcpy(attr_mP->data_float3() + motion_step*numverts, P, sizeof(float3)*numverts);
1299                                 if(attr_mN)
1300                                         memcpy(attr_mN->data_float3() + motion_step*numverts, N, sizeof(float3)*numverts);
1301                         }
1302                 }
1303
1304                 if(numkeys) {
1305                         /* curves */
1306                         Attribute *attr_mP = mesh->curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
1307
1308                         if(attr_mP) {
1309                                 float3 *keys = &mesh->curve_keys[0];
1310                                 memcpy(attr_mP->data_float3() + motion_step*numkeys, keys, sizeof(float3)*numkeys);
1311                         }
1312                 }
1313
1314                 return;
1315         }
1316
1317         /* TODO(sergey): Perform preliminary check for number of verticies. */
1318         if(numverts) {
1319                 /* Find attributes. */
1320                 Attribute *attr_mP = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
1321                 Attribute *attr_mN = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_NORMAL);
1322                 Attribute *attr_N = mesh->attributes.find(ATTR_STD_VERTEX_NORMAL);
1323                 bool new_attribute = false;
1324                 /* Add new attributes if they don't exist already. */
1325                 if(!attr_mP) {
1326                         attr_mP = mesh->attributes.add(ATTR_STD_MOTION_VERTEX_POSITION);
1327                         if(attr_N)
1328                                 attr_mN = mesh->attributes.add(ATTR_STD_MOTION_VERTEX_NORMAL);
1329
1330                         new_attribute = true;
1331                 }
1332                 /* Load vertex data from mesh. */
1333                 float3 *mP = attr_mP->data_float3() + motion_step*numverts;
1334                 float3 *mN = (attr_mN)? attr_mN->data_float3() + motion_step*numverts: NULL;
1335                 /* NOTE: We don't copy more that existing amount of vertices to prevent
1336                  * possible memory corruption.
1337                  */
1338                 BL::Mesh::vertices_iterator v;
1339                 int i = 0;
1340                 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end() && i < numverts; ++v, ++i) {
1341                         mP[i] = get_float3(v->co());
1342                         if(mN)
1343                                 mN[i] = get_float3(v->normal());
1344                 }
1345                 if(new_attribute) {
1346                         /* In case of new attribute, we verify if there really was any motion. */
1347                         if(b_mesh.vertices.length() != numverts ||
1348                            memcmp(mP, &mesh->verts[0], sizeof(float3)*numverts) == 0)
1349                         {
1350                                 /* no motion, remove attributes again */
1351                                 if(b_mesh.vertices.length() != numverts) {
1352                                         VLOG(1) << "Topology differs, disabling motion blur for object "
1353                                                 << b_ob.name();
1354                                 }
1355                                 else {
1356                                         VLOG(1) << "No actual deformation motion for object "
1357                                                 << b_ob.name();
1358                                 }
1359                                 mesh->attributes.remove(ATTR_STD_MOTION_VERTEX_POSITION);
1360                                 if(attr_mN)
1361                                         mesh->attributes.remove(ATTR_STD_MOTION_VERTEX_NORMAL);
1362                         }
1363                         else if(motion_step > 0) {
1364                                 VLOG(1) << "Filling deformation motion for object " << b_ob.name();
1365                                 /* motion, fill up previous steps that we might have skipped because
1366                                  * they had no motion, but we need them anyway now */
1367                                 float3 *P = &mesh->verts[0];
1368                                 float3 *N = (attr_N)? attr_N->data_float3(): NULL;
1369                                 for(int step = 0; step < motion_step; step++) {
1370                                         memcpy(attr_mP->data_float3() + step*numverts, P, sizeof(float3)*numverts);
1371                                         if(attr_mN)
1372                                                 memcpy(attr_mN->data_float3() + step*numverts, N, sizeof(float3)*numverts);
1373                                 }
1374                         }
1375                 }
1376                 else {
1377                         if(b_mesh.vertices.length() != numverts) {
1378                                 VLOG(1) << "Topology differs, discarding motion blur for object "
1379                                         << b_ob.name() << " at time " << motion_step;
1380                                 memcpy(mP, &mesh->verts[0], sizeof(float3)*numverts);
1381                                 if(mN != NULL) {
1382                                         memcpy(mN, attr_N->data_float3(), sizeof(float3)*numverts);
1383                                 }
1384                         }
1385                 }
1386         }
1387
1388         /* hair motion */
1389         if(numkeys)
1390                 sync_curves(mesh, b_mesh, b_ob, true, motion_step);
1391
1392         /* free derived mesh */
1393         b_data.meshes.remove(b_mesh, false, true, false);
1394 }
1395
1396 CCL_NAMESPACE_END