7a85ff27e53e91b55930beb6802729e4df4bfa0c
[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_float3();
70                         }
71                 }
72         }
73
74         const Mesh *mesh;
75         int num_faces;
76
77         float3 *vertex_normal;
78         float3 *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                 float3 tfuv = userdata->texface[corner_index];
154                 uv[0] = tfuv.x;
155                 uv[1] = tfuv.y;
156         }
157         else if(userdata->orco != NULL) {
158                 const 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                                                                        TypeDesc::TypePoint,
434                                                                        ATTR_ELEMENT_CORNER);
435                                 }
436
437                                 BL::Mesh::loop_triangles_iterator t;
438                                 float3 *fdata = uv_attr->data_float3();
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_float3(l->data[li[0]].uv());
443                                         fdata[1] = get_float3(l->data[li[1]].uv());
444                                         fdata[2] = get_float3(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, TypeDesc::TypePoint, ATTR_ELEMENT_CORNER);
513
514                                 if(subdivide_uvs) {
515                                         uv_attr->flags |= ATTR_SUBDIVIDED;
516                                 }
517
518                                 BL::Mesh::polygons_iterator p;
519                                 float3 *fdata = uv_attr->data_float3();
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_float3(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         BL::Mesh::vertices_iterator v;
760         BL::Mesh::polygons_iterator p;
761
762         if(!subdivision) {
763                 numtris = numfaces;
764         }
765         else {
766                 for(b_mesh.polygons.begin(p); p != b_mesh.polygons.end(); ++p) {
767                         numngons += (p->loop_total() == 4)? 0: 1;
768                         numcorners += p->loop_total();
769                 }
770         }
771
772         /* allocate memory */
773         mesh->reserve_mesh(numverts, numtris);
774         mesh->reserve_subd_faces(numfaces, numngons, numcorners);
775
776         /* create vertex coordinates and normals */
777         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
778                 mesh->add_vertex(get_float3(v->co()));
779
780         AttributeSet& attributes = (subdivision)? mesh->subd_attributes: mesh->attributes;
781         Attribute *attr_N = attributes.add(ATTR_STD_VERTEX_NORMAL);
782         float3 *N = attr_N->data_float3();
783
784         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v, ++N)
785                 *N = get_float3(v->normal());
786         N = attr_N->data_float3();
787
788         /* create generated coordinates from undeformed coordinates */
789         const bool need_default_tangent =
790                 (subdivision == false) &&
791                 (b_mesh.uv_layers.length() == 0) &&
792                 (mesh->need_attribute(scene, ATTR_STD_UV_TANGENT));
793         if(mesh->need_attribute(scene, ATTR_STD_GENERATED) ||
794            need_default_tangent)
795         {
796                 Attribute *attr = attributes.add(ATTR_STD_GENERATED);
797                 attr->flags |= ATTR_SUBDIVIDED;
798
799                 float3 loc, size;
800                 mesh_texture_space(b_mesh, loc, size);
801
802                 float3 *generated = attr->data_float3();
803                 size_t i = 0;
804
805                 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v) {
806                         generated[i++] = get_float3(v->undeformed_co())*size - loc;
807                 }
808         }
809
810         /* create faces */
811         vector<int> nverts(numfaces);
812
813         if(!subdivision) {
814                 BL::Mesh::loop_triangles_iterator t;
815                 int ti = 0;
816
817                 for(b_mesh.loop_triangles.begin(t); t != b_mesh.loop_triangles.end(); ++t, ++ti) {
818                         BL::MeshPolygon p = b_mesh.polygons[t->polygon_index()];
819                         int3 vi = get_int3(t->vertices());
820
821                         int shader = clamp(p.material_index(), 0, used_shaders.size()-1);
822                         bool smooth = p.use_smooth() || use_loop_normals;
823
824                         if(use_loop_normals) {
825                                 BL::Array<float, 9> loop_normals = t->split_normals();
826                                 for(int i = 0; i < 3; i++) {
827                                         N[vi[i]] = make_float3(loop_normals[i * 3],
828                                                                loop_normals[i * 3 + 1],
829                                                                loop_normals[i * 3 + 2]);
830                                 }
831                         }
832
833                         /* Create triangles.
834                          *
835                          * NOTE: Autosmooth is already taken care about.
836                          */
837                         mesh->add_triangle(vi[0], vi[1], vi[2], shader, smooth);
838                         nverts[ti] = 3;
839                 }
840         }
841         else {
842                 vector<int> vi;
843
844                 for(b_mesh.polygons.begin(p); p != b_mesh.polygons.end(); ++p) {
845                         int n = p->loop_total();
846                         int shader = clamp(p->material_index(), 0, used_shaders.size()-1);
847                         bool smooth = p->use_smooth() || use_loop_normals;
848
849                         vi.resize(n);
850                         for(int i = 0; i < n; i++) {
851                                 /* NOTE: Autosmooth is already taken care about. */
852                                 vi[i] = b_mesh.loops[p->loop_start() + i].vertex_index();
853                         }
854
855                         /* create subd faces */
856                         mesh->add_subd_face(&vi[0], n, shader, smooth);
857                 }
858         }
859
860         /* Create all needed attributes.
861          * The calculate functions will check whether they're needed or not.
862          */
863         attr_create_pointiness(scene, mesh, b_mesh, subdivision);
864         attr_create_vertex_color(scene, mesh, b_mesh, subdivision);
865
866         if(subdivision) {
867                 attr_create_subd_uv_map(scene, mesh, b_mesh, subdivide_uvs);
868         }
869         else {
870                 attr_create_uv_map(scene, mesh, b_mesh);
871         }
872
873         /* for volume objects, create a matrix to transform from object space to
874          * mesh texture space. this does not work with deformations but that can
875          * probably only be done well with a volume grid mapping of coordinates */
876         if(mesh->need_attribute(scene, ATTR_STD_GENERATED_TRANSFORM)) {
877                 Attribute *attr = mesh->attributes.add(ATTR_STD_GENERATED_TRANSFORM);
878                 Transform *tfm = attr->data_transform();
879
880                 float3 loc, size;
881                 mesh_texture_space(b_mesh, loc, size);
882
883                 *tfm = transform_translate(-loc)*transform_scale(size);
884         }
885 }
886
887 static void create_subd_mesh(Scene *scene,
888                              Mesh *mesh,
889                              BL::Object& b_ob,
890                              BL::Mesh& b_mesh,
891                              const vector<Shader*>& used_shaders,
892                              float dicing_rate,
893                              int max_subdivisions)
894 {
895         BL::SubsurfModifier subsurf_mod(b_ob.modifiers[b_ob.modifiers.length()-1]);
896         bool subdivide_uvs = subsurf_mod.uv_smooth() != BL::SubsurfModifier::uv_smooth_NONE;
897
898         create_mesh(scene, mesh, b_mesh, used_shaders, true, subdivide_uvs);
899
900         /* export creases */
901         size_t num_creases = 0;
902         BL::Mesh::edges_iterator e;
903
904         for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e) {
905                 if(e->crease() != 0.0f) {
906                         num_creases++;
907                 }
908         }
909
910         mesh->subd_creases.resize(num_creases);
911
912         Mesh::SubdEdgeCrease* crease = mesh->subd_creases.data();
913         for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e) {
914                 if(e->crease() != 0.0f) {
915                         crease->v[0] = e->vertices()[0];
916                         crease->v[1] = e->vertices()[1];
917                         crease->crease = e->crease();
918
919                         crease++;
920                 }
921         }
922
923         /* set subd params */
924         if(!mesh->subd_params) {
925                 mesh->subd_params = new SubdParams(mesh);
926         }
927         SubdParams& sdparams = *mesh->subd_params;
928
929         PointerRNA cobj = RNA_pointer_get(&b_ob.ptr, "cycles");
930
931         sdparams.dicing_rate = max(0.1f, RNA_float_get(&cobj, "dicing_rate") * dicing_rate);
932         sdparams.max_level = max_subdivisions;
933
934         scene->dicing_camera->update(scene);
935         sdparams.camera = scene->dicing_camera;
936         sdparams.objecttoworld = get_transform(b_ob.matrix_world());
937 }
938
939 /* Sync */
940
941 static void sync_mesh_fluid_motion(BL::Object& b_ob, Scene *scene, Mesh *mesh)
942 {
943         if(scene->need_motion() == Scene::MOTION_NONE)
944                 return;
945
946         BL::DomainFluidSettings b_fluid_domain = object_fluid_domain_find(b_ob);
947
948         if(!b_fluid_domain)
949                 return;
950
951         /* If the mesh has modifiers following the fluid domain we can't export motion. */
952         if(b_fluid_domain.fluid_mesh_vertices.length() != mesh->verts.size())
953                 return;
954
955         /* Find or add attribute */
956         float3 *P = &mesh->verts[0];
957         Attribute *attr_mP = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
958
959         if(!attr_mP) {
960                 attr_mP = mesh->attributes.add(ATTR_STD_MOTION_VERTEX_POSITION);
961         }
962
963         /* Only export previous and next frame, we don't have any in between data. */
964         float motion_times[2] = {-1.0f, 1.0f};
965         for(int step = 0; step < 2; step++) {
966                 float relative_time = motion_times[step] * scene->motion_shutter_time() * 0.5f;
967                 float3 *mP = attr_mP->data_float3() + step*mesh->verts.size();
968
969                 BL::DomainFluidSettings::fluid_mesh_vertices_iterator fvi;
970                 int i = 0;
971
972                 for(b_fluid_domain.fluid_mesh_vertices.begin(fvi); fvi != b_fluid_domain.fluid_mesh_vertices.end(); ++fvi, ++i) {
973                         mP[i] = P[i] + get_float3(fvi->velocity()) * relative_time;
974                 }
975         }
976 }
977
978 Mesh *BlenderSync::sync_mesh(BL::Depsgraph& b_depsgraph,
979                              BL::Object& b_ob,
980                              BL::Object& b_ob_instance,
981                              bool object_updated,
982                              bool show_self,
983                              bool show_particles)
984 {
985         /* test if we can instance or if the object is modified */
986         BL::ID b_ob_data = b_ob.data();
987         BL::ID key = (BKE_object_is_modified(b_ob))? b_ob_instance: b_ob_data;
988         BL::Material material_override = view_layer.material_override;
989
990         /* find shader indices */
991         vector<Shader*> used_shaders;
992
993         BL::Object::material_slots_iterator slot;
994         for(b_ob.material_slots.begin(slot); slot != b_ob.material_slots.end(); ++slot) {
995                 if(material_override) {
996                         find_shader(material_override, used_shaders, scene->default_surface);
997                 }
998                 else {
999                         BL::ID b_material(slot->material());
1000                         find_shader(b_material, used_shaders, scene->default_surface);
1001                 }
1002         }
1003
1004         if(used_shaders.size() == 0) {
1005                 if(material_override)
1006                         find_shader(material_override, used_shaders, scene->default_surface);
1007                 else
1008                         used_shaders.push_back(scene->default_surface);
1009         }
1010
1011         /* test if we need to sync */
1012         int requested_geometry_flags = Mesh::GEOMETRY_NONE;
1013         if(view_layer.use_surfaces) {
1014                 requested_geometry_flags |= Mesh::GEOMETRY_TRIANGLES;
1015         }
1016         if(view_layer.use_hair) {
1017                 requested_geometry_flags |= Mesh::GEOMETRY_CURVES;
1018         }
1019         Mesh *mesh;
1020
1021         if(!mesh_map.sync(&mesh, key)) {
1022                 /* if transform was applied to mesh, need full update */
1023                 if(object_updated && mesh->transform_applied);
1024                 /* test if shaders changed, these can be object level so mesh
1025                  * does not get tagged for recalc */
1026                 else if(mesh->used_shaders != used_shaders);
1027                 else if(requested_geometry_flags != mesh->geometry_flags);
1028                 else {
1029                         /* even if not tagged for recalc, we may need to sync anyway
1030                          * because the shader needs different mesh attributes */
1031                         bool attribute_recalc = false;
1032
1033                         foreach(Shader *shader, mesh->used_shaders)
1034                                 if(shader->need_update_mesh)
1035                                         attribute_recalc = true;
1036
1037                         if(!attribute_recalc)
1038                                 return mesh;
1039                 }
1040         }
1041
1042         /* ensure we only sync instanced meshes once */
1043         if(mesh_synced.find(mesh) != mesh_synced.end())
1044                 return mesh;
1045
1046         mesh_synced.insert(mesh);
1047
1048         /* create derived mesh */
1049         array<int> oldtriangles;
1050         array<Mesh::SubdFace> oldsubd_faces;
1051         array<int> oldsubd_face_corners;
1052         oldtriangles.steal_data(mesh->triangles);
1053         oldsubd_faces.steal_data(mesh->subd_faces);
1054         oldsubd_face_corners.steal_data(mesh->subd_face_corners);
1055
1056         /* compares curve_keys rather than strands in order to handle quick hair
1057          * adjustments in dynamic BVH - other methods could probably do this better*/
1058         array<float3> oldcurve_keys;
1059         array<float> oldcurve_radius;
1060         oldcurve_keys.steal_data(mesh->curve_keys);
1061         oldcurve_radius.steal_data(mesh->curve_radius);
1062
1063         mesh->clear();
1064         mesh->used_shaders = used_shaders;
1065         mesh->name = ustring(b_ob_data.name().c_str());
1066
1067         if(requested_geometry_flags != Mesh::GEOMETRY_NONE) {
1068                 /* mesh objects does have special handle in the dependency graph,
1069                  * they're ensured to have properly updated.
1070                  *
1071                  * updating meshes here will end up having derived mesh referencing
1072                  * freed data from the blender side.
1073                  */
1074                 if(preview && b_ob.type() != BL::Object::type_MESH) {
1075                         b_ob.update_from_editmode(b_data);
1076                 }
1077
1078                 /* For some reason, meshes do not need this... */
1079                 bool apply_modifiers = (b_ob.type() != BL::Object::type_MESH);
1080                 bool need_undeformed = mesh->need_attribute(scene, ATTR_STD_GENERATED);
1081
1082                 mesh->subdivision_type = object_subdivision_type(b_ob, preview, experimental);
1083
1084                 /* Disable adaptive subdivision while baking as the baking system
1085                  * currently doesnt support the topology and will crash.
1086                  */
1087                 if(scene->bake_manager->get_baking()) {
1088                         mesh->subdivision_type = Mesh::SUBDIVISION_NONE;
1089                 }
1090
1091                 BL::Mesh b_mesh = object_to_mesh(b_data,
1092                                                  b_ob,
1093                                                  b_depsgraph,
1094                                                  apply_modifiers,
1095                                                  need_undeformed,
1096                                                  mesh->subdivision_type);
1097
1098                 if(b_mesh) {
1099                         if(view_layer.use_surfaces && show_self) {
1100                                 if(mesh->subdivision_type != Mesh::SUBDIVISION_NONE)
1101                                         create_subd_mesh(scene, mesh, b_ob, b_mesh, used_shaders,
1102                                                          dicing_rate, max_subdivisions);
1103                                 else
1104                                         create_mesh(scene, mesh, b_mesh, used_shaders, false);
1105
1106                                 create_mesh_volume_attributes(scene, b_ob, mesh, b_scene.frame_current());
1107                         }
1108
1109                         if(view_layer.use_hair && show_particles && mesh->subdivision_type == Mesh::SUBDIVISION_NONE)
1110                                 sync_curves(mesh, b_mesh, b_ob, false);
1111
1112                         /* free derived mesh */
1113                         b_data.meshes.remove(b_mesh, false, true, false);
1114                 }
1115         }
1116         mesh->geometry_flags = requested_geometry_flags;
1117
1118         /* fluid motion */
1119         sync_mesh_fluid_motion(b_ob, scene, mesh);
1120
1121         /* tag update */
1122         bool rebuild = (oldtriangles != mesh->triangles) ||
1123                        (oldsubd_faces != mesh->subd_faces) ||
1124                        (oldsubd_face_corners != mesh->subd_face_corners) ||
1125                        (oldcurve_keys != mesh->curve_keys) ||
1126                        (oldcurve_radius != mesh->curve_radius);
1127
1128         mesh->tag_update(scene, rebuild);
1129
1130         return mesh;
1131 }
1132
1133 void BlenderSync::sync_mesh_motion(BL::Depsgraph& b_depsgraph,
1134                                    BL::Object& b_ob,
1135                                    Object *object,
1136                                    float motion_time)
1137 {
1138         /* ensure we only sync instanced meshes once */
1139         Mesh *mesh = object->mesh;
1140
1141         if(mesh_motion_synced.find(mesh) != mesh_motion_synced.end())
1142                 return;
1143
1144         mesh_motion_synced.insert(mesh);
1145
1146         /* ensure we only motion sync meshes that also had mesh synced, to avoid
1147          * unnecessary work and to ensure that its attributes were clear */
1148         if(mesh_synced.find(mesh) == mesh_synced.end())
1149                 return;
1150
1151         /* Find time matching motion step required by mesh. */
1152         int motion_step = mesh->motion_step(motion_time);
1153         if(motion_step < 0) {
1154                 return;
1155         }
1156
1157         /* skip empty meshes */
1158         const size_t numverts = mesh->verts.size();
1159         const size_t numkeys = mesh->curve_keys.size();
1160
1161         if(!numverts && !numkeys)
1162                 return;
1163
1164         /* skip objects without deforming modifiers. this is not totally reliable,
1165          * would need a more extensive check to see which objects are animated */
1166         BL::Mesh b_mesh(PointerRNA_NULL);
1167
1168         /* fluid motion is exported immediate with mesh, skip here */
1169         BL::DomainFluidSettings b_fluid_domain = object_fluid_domain_find(b_ob);
1170         if(b_fluid_domain)
1171                 return;
1172
1173         if(ccl::BKE_object_is_deform_modified(b_ob, b_scene, preview)) {
1174                 /* get derived mesh */
1175                 b_mesh = object_to_mesh(b_data,
1176                                         b_ob,
1177                                         b_depsgraph,
1178                                         false,
1179                                         false,
1180                                         Mesh::SUBDIVISION_NONE);
1181         }
1182
1183         if(!b_mesh) {
1184                 /* if we have no motion blur on this frame, but on other frames, copy */
1185                 if(numverts) {
1186                         /* triangles */
1187                         Attribute *attr_mP = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
1188
1189                         if(attr_mP) {
1190                                 Attribute *attr_mN = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_NORMAL);
1191                                 Attribute *attr_N = mesh->attributes.find(ATTR_STD_VERTEX_NORMAL);
1192                                 float3 *P = &mesh->verts[0];
1193                                 float3 *N = (attr_N)? attr_N->data_float3(): NULL;
1194
1195                                 memcpy(attr_mP->data_float3() + motion_step*numverts, P, sizeof(float3)*numverts);
1196                                 if(attr_mN)
1197                                         memcpy(attr_mN->data_float3() + motion_step*numverts, N, sizeof(float3)*numverts);
1198                         }
1199                 }
1200
1201                 if(numkeys) {
1202                         /* curves */
1203                         Attribute *attr_mP = mesh->curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
1204
1205                         if(attr_mP) {
1206                                 float3 *keys = &mesh->curve_keys[0];
1207                                 memcpy(attr_mP->data_float3() + motion_step*numkeys, keys, sizeof(float3)*numkeys);
1208                         }
1209                 }
1210
1211                 return;
1212         }
1213
1214         /* TODO(sergey): Perform preliminary check for number of verticies. */
1215         if(numverts) {
1216                 /* Find attributes. */
1217                 Attribute *attr_mP = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
1218                 Attribute *attr_mN = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_NORMAL);
1219                 Attribute *attr_N = mesh->attributes.find(ATTR_STD_VERTEX_NORMAL);
1220                 bool new_attribute = false;
1221                 /* Add new attributes if they don't exist already. */
1222                 if(!attr_mP) {
1223                         attr_mP = mesh->attributes.add(ATTR_STD_MOTION_VERTEX_POSITION);
1224                         if(attr_N)
1225                                 attr_mN = mesh->attributes.add(ATTR_STD_MOTION_VERTEX_NORMAL);
1226
1227                         new_attribute = true;
1228                 }
1229                 /* Load vertex data from mesh. */
1230                 float3 *mP = attr_mP->data_float3() + motion_step*numverts;
1231                 float3 *mN = (attr_mN)? attr_mN->data_float3() + motion_step*numverts: NULL;
1232                 /* NOTE: We don't copy more that existing amount of vertices to prevent
1233                  * possible memory corruption.
1234                  */
1235                 BL::Mesh::vertices_iterator v;
1236                 int i = 0;
1237                 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end() && i < numverts; ++v, ++i) {
1238                         mP[i] = get_float3(v->co());
1239                         if(mN)
1240                                 mN[i] = get_float3(v->normal());
1241                 }
1242                 if(new_attribute) {
1243                         /* In case of new attribute, we verify if there really was any motion. */
1244                         if(b_mesh.vertices.length() != numverts ||
1245                            memcmp(mP, &mesh->verts[0], sizeof(float3)*numverts) == 0)
1246                         {
1247                                 /* no motion, remove attributes again */
1248                                 if(b_mesh.vertices.length() != numverts) {
1249                                         VLOG(1) << "Topology differs, disabling motion blur for object "
1250                                                 << b_ob.name();
1251                                 }
1252                                 else {
1253                                         VLOG(1) << "No actual deformation motion for object "
1254                                                 << b_ob.name();
1255                                 }
1256                                 mesh->attributes.remove(ATTR_STD_MOTION_VERTEX_POSITION);
1257                                 if(attr_mN)
1258                                         mesh->attributes.remove(ATTR_STD_MOTION_VERTEX_NORMAL);
1259                         }
1260                         else if(motion_step > 0) {
1261                                 VLOG(1) << "Filling deformation motion for object " << b_ob.name();
1262                                 /* motion, fill up previous steps that we might have skipped because
1263                                  * they had no motion, but we need them anyway now */
1264                                 float3 *P = &mesh->verts[0];
1265                                 float3 *N = (attr_N)? attr_N->data_float3(): NULL;
1266                                 for(int step = 0; step < motion_step; step++) {
1267                                         memcpy(attr_mP->data_float3() + step*numverts, P, sizeof(float3)*numverts);
1268                                         if(attr_mN)
1269                                                 memcpy(attr_mN->data_float3() + step*numverts, N, sizeof(float3)*numverts);
1270                                 }
1271                         }
1272                 }
1273                 else {
1274                         if(b_mesh.vertices.length() != numverts) {
1275                                 VLOG(1) << "Topology differs, discarding motion blur for object "
1276                                         << b_ob.name() << " at time " << motion_step;
1277                                 memcpy(mP, &mesh->verts[0], sizeof(float3)*numverts);
1278                                 if(mN != NULL) {
1279                                         memcpy(mN, attr_N->data_float3(), sizeof(float3)*numverts);
1280                                 }
1281                         }
1282                 }
1283         }
1284
1285         /* hair motion */
1286         if(numkeys)
1287                 sync_curves(mesh, b_mesh, b_ob, true, motion_step);
1288
1289         /* free derived mesh */
1290         b_data.meshes.remove(b_mesh, false, true, false);
1291 }
1292
1293 CCL_NAMESPACE_END