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