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