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