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