2 * Copyright 2011-2013 Blender Foundation
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "render/mesh.h"
18 #include "render/object.h"
19 #include "render/scene.h"
20 #include "render/camera.h"
22 #include "blender/blender_sync.h"
23 #include "blender/blender_session.h"
24 #include "blender/blender_util.h"
26 #include "subd/subd_patch.h"
27 #include "subd/subd_split.h"
29 #include "util/util_algorithm.h"
30 #include "util/util_foreach.h"
31 #include "util/util_logging.h"
32 #include "util/util_math.h"
34 #include "mikktspace.h"
38 /* Per-face bit flags. */
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),
48 /* Get vertex indices to create triangles from a given face.
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.
53 inline void face_split_tri_indices(const int face_flag,
57 if(face_flag & FACE_FLAG_DIVIDE_24) {
67 /* Quad with FACE_FLAG_DIVIDE_13 or single triangle. */
81 MikkUserData(const BL::Mesh& b_mesh,
82 const char *layer_name,
90 tangent_sign(tangent_sign)
92 const AttributeSet& attributes = (mesh->subd_faces.size()) ?
93 mesh->subd_attributes : mesh->attributes;
95 Attribute *attr_vN = attributes.find(ATTR_STD_VERTEX_NORMAL);
96 vertex_normal = attr_vN->data_float3();
98 if(layer_name == NULL) {
99 Attribute *attr_orco = attributes.find(ATTR_STD_GENERATED);
102 orco = attr_orco->data_float3();
103 mesh_texture_space(*(BL::Mesh*)&b_mesh, orco_loc, orco_size);
107 Attribute *attr_uv = attributes.find(ustring(layer_name));
108 if(attr_uv != NULL) {
109 texface = attr_uv->data_float3();
117 float3 *vertex_normal;
120 float3 orco_loc, orco_size;
126 static int mikk_get_num_faces(const SMikkTSpaceContext *context)
128 const MikkUserData *userdata = (const MikkUserData *)context->m_pUserData;
129 if(userdata->mesh->subd_faces.size()) {
130 return userdata->mesh->subd_faces.size();
133 return userdata->mesh->num_triangles();
137 static int mikk_get_num_verts_of_face(const SMikkTSpaceContext *context,
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;
150 static int mikk_vertex_index(const Mesh *mesh, const int face_num, const int vert_num)
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];
157 return mesh->triangles[face_num * 3 + vert_num];
161 static int mikk_corner_index(const Mesh *mesh, const int face_num, const int vert_num)
163 if(mesh->subd_faces.size()) {
164 const Mesh::SubdFace& face = mesh->subd_faces[face_num];
165 return face.start_corner + vert_num;
168 return face_num * 3 + vert_num;
172 static void mikk_get_position(const SMikkTSpaceContext *context,
174 const int face_num, const int vert_num)
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];
185 static void mikk_get_texture_coordinate(const SMikkTSpaceContext *context,
187 const int face_num, const int vert_num)
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];
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;
203 const float2 tmp = map_to_sphere(orco);
213 static void mikk_get_normal(const SMikkTSpaceContext *context, float N[3],
214 const int face_num, const int vert_num)
216 const MikkUserData *userdata = (const MikkUserData *)context->m_pUserData;
217 const Mesh *mesh = userdata->mesh;
219 if(mesh->subd_faces.size()) {
220 const Mesh::SubdFace& face = mesh->subd_faces[face_num];
222 const int vertex_index = mikk_vertex_index(mesh, face_num, vert_num);
223 vN = userdata->vertex_normal[vertex_index];
226 vN = face.normal(mesh);
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];
235 const Mesh::Triangle tri = mesh->get_triangle(face_num);
236 vN = tri.compute_normal(&mesh->verts[0]);
244 static void mikk_set_tangent_space(const SMikkTSpaceContext *context,
247 const int face_num, const int vert_num)
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;
258 static void mikk_compute_tangents(const BL::Mesh& b_mesh,
259 const char *layer_name,
264 /* Create tangent attributes. */
265 AttributeSet& attributes = (mesh->subd_faces.size()) ?
266 mesh->subd_attributes : mesh->attributes;
269 if(layer_name != NULL) {
270 name = ustring((string(layer_name) + ".tangent").c_str());
273 name = ustring("orco.tangent");
276 attr = attributes.add(ATTR_STD_UV_TANGENT, name);
279 attr = attributes.add(name, TypeDesc::TypeVector, ATTR_ELEMENT_CORNER);
281 float3 *tangent = attr->data_float3();
282 /* Create bitangent sign attribute. */
283 float *tangent_sign = NULL;
285 Attribute *attr_sign;
287 if(layer_name != NULL) {
288 name_sign = ustring((string(layer_name) +
289 ".tangent_sign").c_str());
292 name_sign = ustring("orco.tangent_sign");
296 attr_sign = attributes.add(ATTR_STD_UV_TANGENT_SIGN, name_sign);
299 attr_sign = attributes.add(name_sign,
301 ATTR_ELEMENT_CORNER);
303 tangent_sign = attr_sign->data_float();
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;
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);
325 /* Create Volume Attribute */
327 static void create_mesh_volume_attribute(BL::Object& b_ob,
329 ImageManager *image_manager,
330 AttributeStandard std,
333 BL::SmokeDomainSettings b_domain = object_smoke_domain_find(b_ob);
338 Attribute *attr = mesh->attributes.add(std);
339 VoxelAttribute *volume_data = attr->data_voxel();
340 bool is_float, is_linear;
341 bool animated = false;
343 volume_data->manager = image_manager;
344 volume_data->slot = image_manager->add_image(
345 Attribute::standard_name(std),
351 INTERPOLATION_LINEAR,
356 static void create_mesh_volume_attributes(Scene *scene,
361 /* for smoke volume rendering */
362 if(mesh->need_attribute(scene, ATTR_STD_VOLUME_DENSITY))
363 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_DENSITY, frame);
364 if(mesh->need_attribute(scene, ATTR_STD_VOLUME_COLOR))
365 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_COLOR, frame);
366 if(mesh->need_attribute(scene, ATTR_STD_VOLUME_FLAME))
367 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_FLAME, frame);
368 if(mesh->need_attribute(scene, ATTR_STD_VOLUME_HEAT))
369 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_HEAT, frame);
370 if(mesh->need_attribute(scene, ATTR_STD_VOLUME_TEMPERATURE))
371 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_TEMPERATURE, frame);
372 if(mesh->need_attribute(scene, ATTR_STD_VOLUME_VELOCITY))
373 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_VELOCITY, frame);
376 /* Create vertex color attributes. */
377 static void attr_create_vertex_color(Scene *scene,
380 const vector<int>& nverts,
381 const vector<int>& face_flags,
385 BL::Mesh::vertex_colors_iterator l;
387 for(b_mesh.vertex_colors.begin(l); l != b_mesh.vertex_colors.end(); ++l) {
388 if(!mesh->need_attribute(scene, ustring(l->name().c_str())))
391 Attribute *attr = mesh->subd_attributes.add(ustring(l->name().c_str()),
393 ATTR_ELEMENT_CORNER_BYTE);
395 BL::Mesh::polygons_iterator p;
396 uchar4 *cdata = attr->data_uchar4();
398 for(b_mesh.polygons.begin(p); p != b_mesh.polygons.end(); ++p) {
399 int n = p->loop_total();
400 for(int i = 0; i < n; i++) {
401 float3 color = get_float3(l->data[p->loop_start() + i].color());
402 *(cdata++) = color_float_to_byte(color_srgb_to_scene_linear_v3(color));
408 BL::Mesh::tessface_vertex_colors_iterator l;
409 for(b_mesh.tessface_vertex_colors.begin(l); l != b_mesh.tessface_vertex_colors.end(); ++l) {
410 if(!mesh->need_attribute(scene, ustring(l->name().c_str())))
413 Attribute *attr = mesh->attributes.add(ustring(l->name().c_str()),
415 ATTR_ELEMENT_CORNER_BYTE);
417 BL::MeshColorLayer::data_iterator c;
418 uchar4 *cdata = attr->data_uchar4();
421 for(l->data.begin(c); c != l->data.end(); ++c, ++i) {
422 int tri_a[3], tri_b[3];
423 face_split_tri_indices(face_flags[i], tri_a, tri_b);
426 colors[0] = color_float_to_byte(color_srgb_to_scene_linear_v3(get_float3(c->color1())));
427 colors[1] = color_float_to_byte(color_srgb_to_scene_linear_v3(get_float3(c->color2())));
428 colors[2] = color_float_to_byte(color_srgb_to_scene_linear_v3(get_float3(c->color3())));
430 colors[3] = color_float_to_byte(color_srgb_to_scene_linear_v3(get_float3(c->color4())));
433 cdata[0] = colors[tri_a[0]];
434 cdata[1] = colors[tri_a[1]];
435 cdata[2] = colors[tri_a[2]];
438 cdata[3] = colors[tri_b[0]];
439 cdata[4] = colors[tri_b[1]];
440 cdata[5] = colors[tri_b[2]];
450 /* Create uv map attributes. */
451 static void attr_create_uv_map(Scene *scene,
454 const vector<int>& nverts,
455 const vector<int>& face_flags)
457 if(b_mesh.tessface_uv_textures.length() != 0) {
458 BL::Mesh::tessface_uv_textures_iterator l;
460 for(b_mesh.tessface_uv_textures.begin(l); l != b_mesh.tessface_uv_textures.end(); ++l) {
461 const bool active_render = l->active_render();
462 AttributeStandard uv_std = (active_render)? ATTR_STD_UV: ATTR_STD_NONE;
463 ustring uv_name = ustring(l->name().c_str());
464 AttributeStandard tangent_std = (active_render)? ATTR_STD_UV_TANGENT
466 ustring tangent_name = ustring(
467 (string(l->name().c_str()) + ".tangent").c_str());
469 /* Denotes whether UV map was requested directly. */
470 const bool need_uv = mesh->need_attribute(scene, uv_name) ||
471 mesh->need_attribute(scene, uv_std);
472 /* Denotes whether tangent was requested directly. */
473 const bool need_tangent =
474 mesh->need_attribute(scene, tangent_name) ||
475 (active_render && mesh->need_attribute(scene, tangent_std));
478 /* NOTE: We create temporary UV layer if its needed for tangent but
479 * wasn't requested by other nodes in shaders.
481 Attribute *uv_attr = NULL;
482 if(need_uv || need_tangent) {
484 uv_attr = mesh->attributes.add(uv_std, uv_name);
487 uv_attr = mesh->attributes.add(uv_name,
489 ATTR_ELEMENT_CORNER);
492 BL::MeshTextureFaceLayer::data_iterator t;
493 float3 *fdata = uv_attr->data_float3();
496 for(l->data.begin(t); t != l->data.end(); ++t, ++i) {
497 int tri_a[3], tri_b[3];
498 face_split_tri_indices(face_flags[i], tri_a, tri_b);
501 uvs[0] = get_float3(t->uv1());
502 uvs[1] = get_float3(t->uv2());
503 uvs[2] = get_float3(t->uv3());
505 uvs[3] = get_float3(t->uv4());
508 fdata[0] = uvs[tri_a[0]];
509 fdata[1] = uvs[tri_a[1]];
510 fdata[2] = uvs[tri_a[2]];
514 fdata[0] = uvs[tri_b[0]];
515 fdata[1] = uvs[tri_b[1]];
516 fdata[2] = uvs[tri_b[2]];
524 AttributeStandard sign_std =
525 (active_render)? ATTR_STD_UV_TANGENT_SIGN
527 ustring sign_name = ustring(
528 (string(l->name().c_str()) + ".tangent_sign").c_str());
529 bool need_sign = (mesh->need_attribute(scene, sign_name) ||
530 mesh->need_attribute(scene, sign_std));
531 mikk_compute_tangents(b_mesh,
537 /* Remove temporarily created UV attribute. */
538 if(!need_uv && uv_attr != NULL) {
539 mesh->attributes.remove(uv_attr);
543 else if(mesh->need_attribute(scene, ATTR_STD_UV_TANGENT)) {
544 bool need_sign = mesh->need_attribute(scene, ATTR_STD_UV_TANGENT_SIGN);
545 mikk_compute_tangents(b_mesh, NULL, mesh, need_sign, true);
546 if(!mesh->need_attribute(scene, ATTR_STD_GENERATED)) {
547 mesh->attributes.remove(ATTR_STD_GENERATED);
552 static void attr_create_subd_uv_map(Scene *scene,
557 if(b_mesh.uv_layers.length() != 0) {
558 BL::Mesh::uv_layers_iterator l;
561 for(b_mesh.uv_layers.begin(l); l != b_mesh.uv_layers.end(); ++l, ++i) {
562 bool active_render = l->active_render();
563 AttributeStandard uv_std = (active_render)? ATTR_STD_UV: ATTR_STD_NONE;
564 ustring uv_name = ustring(l->name().c_str());
565 AttributeStandard tangent_std = (active_render)? ATTR_STD_UV_TANGENT
567 ustring tangent_name = ustring(
568 (string(l->name().c_str()) + ".tangent").c_str());
570 /* Denotes whether UV map was requested directly. */
571 const bool need_uv = mesh->need_attribute(scene, uv_name) ||
572 mesh->need_attribute(scene, uv_std);
573 /* Denotes whether tangent was requested directly. */
574 const bool need_tangent =
575 mesh->need_attribute(scene, tangent_name) ||
576 (active_render && mesh->need_attribute(scene, tangent_std));
578 Attribute *uv_attr = NULL;
581 if(need_uv || need_tangent) {
583 uv_attr = mesh->subd_attributes.add(uv_std, uv_name);
585 uv_attr = mesh->subd_attributes.add(uv_name, TypeDesc::TypePoint, ATTR_ELEMENT_CORNER);
588 uv_attr->flags |= ATTR_SUBDIVIDED;
591 BL::Mesh::polygons_iterator p;
592 float3 *fdata = uv_attr->data_float3();
594 for(b_mesh.polygons.begin(p); p != b_mesh.polygons.end(); ++p) {
595 int n = p->loop_total();
596 for(int j = 0; j < n; j++) {
597 *(fdata++) = get_float3(l->data[p->loop_start() + j].uv());
604 AttributeStandard sign_std =
605 (active_render)? ATTR_STD_UV_TANGENT_SIGN
607 ustring sign_name = ustring(
608 (string(l->name().c_str()) + ".tangent_sign").c_str());
609 bool need_sign = (mesh->need_attribute(scene, sign_name) ||
610 mesh->need_attribute(scene, sign_std));
611 mikk_compute_tangents(b_mesh,
617 /* Remove temporarily created UV attribute. */
618 if(!need_uv && uv_attr != NULL) {
619 mesh->subd_attributes.remove(uv_attr);
623 else if(mesh->need_attribute(scene, ATTR_STD_UV_TANGENT)) {
624 bool need_sign = mesh->need_attribute(scene, ATTR_STD_UV_TANGENT_SIGN);
625 mikk_compute_tangents(b_mesh, NULL, mesh, need_sign, true);
626 if(!mesh->need_attribute(scene, ATTR_STD_GENERATED)) {
627 mesh->subd_attributes.remove(ATTR_STD_GENERATED);
632 /* Create vertex pointiness attributes. */
634 /* Compare vertices by sum of their coordinates. */
635 class VertexAverageComparator {
637 VertexAverageComparator(const array<float3>& verts)
641 bool operator()(const int& vert_idx_a, const int& vert_idx_b)
643 const float3 &vert_a = verts_[vert_idx_a];
644 const float3 &vert_b = verts_[vert_idx_b];
645 if(vert_a == vert_b) {
646 /* Special case for doubles, so we ensure ordering. */
647 return vert_idx_a > vert_idx_b;
649 const float x1 = vert_a.x + vert_a.y + vert_a.z;
650 const float x2 = vert_b.x + vert_b.y + vert_b.z;
655 const array<float3>& verts_;
658 static void attr_create_pointiness(Scene *scene,
663 if(!mesh->need_attribute(scene, ATTR_STD_POINTINESS)) {
666 const int num_verts = b_mesh.vertices.length();
670 /* STEP 1: Find out duplicated vertices and point duplicates to a single
673 vector<int> sorted_vert_indeices(num_verts);
674 for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
675 sorted_vert_indeices[vert_index] = vert_index;
677 VertexAverageComparator compare(mesh->verts);
678 sort(sorted_vert_indeices.begin(), sorted_vert_indeices.end(), compare);
679 /* This array stores index of the original vertex for the given vertex
682 vector<int> vert_orig_index(num_verts);
683 for(int sorted_vert_index = 0;
684 sorted_vert_index < num_verts;
687 const int vert_index = sorted_vert_indeices[sorted_vert_index];
688 const float3 &vert_co = mesh->verts[vert_index];
690 for(int other_sorted_vert_index = sorted_vert_index + 1;
691 other_sorted_vert_index < num_verts;
692 ++other_sorted_vert_index)
694 const int other_vert_index =
695 sorted_vert_indeices[other_sorted_vert_index];
696 const float3 &other_vert_co = mesh->verts[other_vert_index];
697 /* We are too far away now, we wouldn't have duplicate. */
698 if((other_vert_co.x + other_vert_co.y + other_vert_co.z) -
699 (vert_co.x + vert_co.y + vert_co.z) > 3 * FLT_EPSILON)
703 /* Found duplicate. */
704 if(len_squared(other_vert_co - vert_co) < FLT_EPSILON) {
706 vert_orig_index[vert_index] = other_vert_index;
711 vert_orig_index[vert_index] = vert_index;
714 /* Make sure we always points to the very first orig vertex. */
715 for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
716 int orig_index = vert_orig_index[vert_index];
717 while(orig_index != vert_orig_index[orig_index]) {
718 orig_index = vert_orig_index[orig_index];
720 vert_orig_index[vert_index] = orig_index;
722 sorted_vert_indeices.free_memory();
723 /* STEP 2: Calculate vertex normals taking into account their possible
724 * duplicates which gets "welded" together.
726 vector<float3> vert_normal(num_verts, make_float3(0.0f, 0.0f, 0.0f));
727 /* First we accumulate all vertex normals in the original index. */
728 for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
729 const float3 normal = get_float3(b_mesh.vertices[vert_index].normal());
730 const int orig_index = vert_orig_index[vert_index];
731 vert_normal[orig_index] += normal;
733 /* Then we normalize the accumulated result and flush it to all duplicates
736 for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
737 const int orig_index = vert_orig_index[vert_index];
738 vert_normal[vert_index] = normalize(vert_normal[orig_index]);
740 /* STEP 3: Calculate pointiness using single ring neighborhood. */
741 vector<int> counter(num_verts, 0);
742 vector<float> raw_data(num_verts, 0.0f);
743 vector<float3> edge_accum(num_verts, make_float3(0.0f, 0.0f, 0.0f));
744 BL::Mesh::edges_iterator e;
745 EdgeMap visited_edges;
747 memset(&counter[0], 0, sizeof(int) * counter.size());
748 for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e, ++edge_index) {
749 const int v0 = vert_orig_index[b_mesh.edges[edge_index].vertices()[0]],
750 v1 = vert_orig_index[b_mesh.edges[edge_index].vertices()[1]];
751 if(visited_edges.exists(v0, v1)) {
754 visited_edges.insert(v0, v1);
755 float3 co0 = get_float3(b_mesh.vertices[v0].co()),
756 co1 = get_float3(b_mesh.vertices[v1].co());
757 float3 edge = normalize(co1 - co0);
758 edge_accum[v0] += edge;
759 edge_accum[v1] += -edge;
763 for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
764 const int orig_index = vert_orig_index[vert_index];
765 if(orig_index != vert_index) {
766 /* Skip duplicates, they'll be overwritten later on. */
769 if(counter[vert_index] > 0) {
770 const float3 normal = vert_normal[vert_index];
772 safe_acosf(dot(normal,
773 edge_accum[vert_index] / counter[vert_index]));
774 raw_data[vert_index] = angle * M_1_PI_F;
777 raw_data[vert_index] = 0.0f;
780 /* STEP 3: Blur vertices to approximate 2 ring neighborhood. */
781 AttributeSet& attributes = (subdivision)? mesh->subd_attributes: mesh->attributes;
782 Attribute *attr = attributes.add(ATTR_STD_POINTINESS);
783 float *data = attr->data_float();
784 memcpy(data, &raw_data[0], sizeof(float) * raw_data.size());
785 memset(&counter[0], 0, sizeof(int) * counter.size());
787 visited_edges.clear();
788 for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e, ++edge_index) {
789 const int v0 = vert_orig_index[b_mesh.edges[edge_index].vertices()[0]],
790 v1 = vert_orig_index[b_mesh.edges[edge_index].vertices()[1]];
791 if(visited_edges.exists(v0, v1)) {
794 visited_edges.insert(v0, v1);
795 data[v0] += raw_data[v1];
796 data[v1] += raw_data[v0];
800 for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
801 data[vert_index] /= counter[vert_index] + 1;
803 /* STEP 4: Copy attribute to the duplicated vertices. */
804 for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
805 const int orig_index = vert_orig_index[vert_index];
806 data[vert_index] = data[orig_index];
812 static void create_mesh(Scene *scene,
815 const vector<Shader*>& used_shaders,
816 bool subdivision = false,
817 bool subdivide_uvs = true)
819 /* count vertices and faces */
820 int numverts = b_mesh.vertices.length();
821 int numfaces = (!subdivision) ? b_mesh.tessfaces.length() : b_mesh.polygons.length();
825 bool use_loop_normals = b_mesh.use_auto_smooth() && (mesh->subdivision_type != Mesh::SUBDIVISION_CATMULL_CLARK);
827 /* If no faces, create empty mesh. */
832 BL::Mesh::vertices_iterator v;
833 BL::Mesh::tessfaces_iterator f;
834 BL::Mesh::polygons_iterator p;
837 for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f) {
838 int4 vi = get_int4(f->vertices_raw());
839 numtris += (vi[3] == 0)? 1: 2;
843 for(b_mesh.polygons.begin(p); p != b_mesh.polygons.end(); ++p) {
844 numngons += (p->loop_total() == 4)? 0: 1;
845 numcorners += p->loop_total();
849 /* allocate memory */
850 mesh->reserve_mesh(numverts, numtris);
851 mesh->reserve_subd_faces(numfaces, numngons, numcorners);
853 /* create vertex coordinates and normals */
854 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
855 mesh->add_vertex(get_float3(v->co()));
857 AttributeSet& attributes = (subdivision)? mesh->subd_attributes: mesh->attributes;
858 Attribute *attr_N = attributes.add(ATTR_STD_VERTEX_NORMAL);
859 float3 *N = attr_N->data_float3();
861 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v, ++N)
862 *N = get_float3(v->normal());
863 N = attr_N->data_float3();
865 /* create generated coordinates from undeformed coordinates */
866 const bool need_default_tangent =
867 (subdivision == false) &&
868 (b_mesh.tessface_uv_textures.length() == 0) &&
869 (mesh->need_attribute(scene, ATTR_STD_UV_TANGENT));
870 if(mesh->need_attribute(scene, ATTR_STD_GENERATED) ||
871 need_default_tangent)
873 Attribute *attr = attributes.add(ATTR_STD_GENERATED);
874 attr->flags |= ATTR_SUBDIVIDED;
877 mesh_texture_space(b_mesh, loc, size);
879 float3 *generated = attr->data_float3();
882 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v) {
883 generated[i++] = get_float3(v->undeformed_co())*size - loc;
888 vector<int> nverts(numfaces);
889 vector<int> face_flags(numfaces, FACE_FLAG_NONE);
893 for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f, ++fi) {
894 int4 vi = get_int4(f->vertices_raw());
895 int n = (vi[3] == 0)? 3: 4;
896 int shader = clamp(f->material_index(), 0, used_shaders.size()-1);
897 bool smooth = f->use_smooth() || use_loop_normals;
899 if(use_loop_normals) {
900 BL::Array<float, 12> loop_normals = f->split_normals();
901 for(int i = 0; i < n; i++) {
902 N[vi[i]] = make_float3(loop_normals[i * 3],
903 loop_normals[i * 3 + 1],
904 loop_normals[i * 3 + 2]);
910 * NOTE: Autosmooth is already taken care about.
913 if(is_zero(cross(mesh->verts[vi[1]] - mesh->verts[vi[0]], mesh->verts[vi[2]] - mesh->verts[vi[0]])) ||
914 is_zero(cross(mesh->verts[vi[2]] - mesh->verts[vi[0]], mesh->verts[vi[3]] - mesh->verts[vi[0]])))
916 mesh->add_triangle(vi[0], vi[1], vi[3], shader, smooth);
917 mesh->add_triangle(vi[2], vi[3], vi[1], shader, smooth);
918 face_flags[fi] |= FACE_FLAG_DIVIDE_24;
921 mesh->add_triangle(vi[0], vi[1], vi[2], shader, smooth);
922 mesh->add_triangle(vi[0], vi[2], vi[3], shader, smooth);
923 face_flags[fi] |= FACE_FLAG_DIVIDE_13;
927 mesh->add_triangle(vi[0], vi[1], vi[2], shader, smooth);
936 for(b_mesh.polygons.begin(p); p != b_mesh.polygons.end(); ++p) {
937 int n = p->loop_total();
938 int shader = clamp(p->material_index(), 0, used_shaders.size()-1);
939 bool smooth = p->use_smooth() || use_loop_normals;
942 for(int i = 0; i < n; i++) {
943 /* NOTE: Autosmooth is already taken care about. */
944 vi[i] = b_mesh.loops[p->loop_start() + i].vertex_index();
947 /* create subd faces */
948 mesh->add_subd_face(&vi[0], n, shader, smooth);
952 /* Create all needed attributes.
953 * The calculate functions will check whether they're needed or not.
955 attr_create_pointiness(scene, mesh, b_mesh, subdivision);
956 attr_create_vertex_color(scene, mesh, b_mesh, nverts, face_flags, subdivision);
959 attr_create_subd_uv_map(scene, mesh, b_mesh, subdivide_uvs);
962 attr_create_uv_map(scene, mesh, b_mesh, nverts, face_flags);
965 /* for volume objects, create a matrix to transform from object space to
966 * mesh texture space. this does not work with deformations but that can
967 * probably only be done well with a volume grid mapping of coordinates */
968 if(mesh->need_attribute(scene, ATTR_STD_GENERATED_TRANSFORM)) {
969 Attribute *attr = mesh->attributes.add(ATTR_STD_GENERATED_TRANSFORM);
970 Transform *tfm = attr->data_transform();
973 mesh_texture_space(b_mesh, loc, size);
975 *tfm = transform_translate(-loc)*transform_scale(size);
979 static void create_subd_mesh(Scene *scene,
983 const vector<Shader*>& used_shaders,
985 int max_subdivisions)
987 BL::SubsurfModifier subsurf_mod(b_ob.modifiers[b_ob.modifiers.length()-1]);
988 bool subdivide_uvs = subsurf_mod.use_subsurf_uv();
990 create_mesh(scene, mesh, b_mesh, used_shaders, true, subdivide_uvs);
993 size_t num_creases = 0;
994 BL::Mesh::edges_iterator e;
996 for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e) {
997 if(e->crease() != 0.0f) {
1002 mesh->subd_creases.resize(num_creases);
1004 Mesh::SubdEdgeCrease* crease = mesh->subd_creases.data();
1005 for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e) {
1006 if(e->crease() != 0.0f) {
1007 crease->v[0] = e->vertices()[0];
1008 crease->v[1] = e->vertices()[1];
1009 crease->crease = e->crease();
1015 /* set subd params */
1016 if(!mesh->subd_params) {
1017 mesh->subd_params = new SubdParams(mesh);
1019 SubdParams& sdparams = *mesh->subd_params;
1021 PointerRNA cobj = RNA_pointer_get(&b_ob.ptr, "cycles");
1023 sdparams.dicing_rate = max(0.1f, RNA_float_get(&cobj, "dicing_rate") * dicing_rate);
1024 sdparams.max_level = max_subdivisions;
1026 scene->dicing_camera->update(scene);
1027 sdparams.camera = scene->dicing_camera;
1028 sdparams.objecttoworld = get_transform(b_ob.matrix_world());
1033 static void sync_mesh_fluid_motion(BL::Object& b_ob, Scene *scene, Mesh *mesh)
1035 if(scene->need_motion() == Scene::MOTION_NONE)
1038 BL::DomainFluidSettings b_fluid_domain = object_fluid_domain_find(b_ob);
1043 /* If the mesh has modifiers following the fluid domain we can't export motion. */
1044 if(b_fluid_domain.fluid_mesh_vertices.length() != mesh->verts.size())
1047 /* Find or add attribute */
1048 float3 *P = &mesh->verts[0];
1049 Attribute *attr_mP = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
1052 attr_mP = mesh->attributes.add(ATTR_STD_MOTION_VERTEX_POSITION);
1055 /* Only export previous and next frame, we don't have any in between data. */
1056 float motion_times[2] = {-1.0f, 1.0f};
1057 for(int step = 0; step < 2; step++) {
1058 float relative_time = motion_times[step] * scene->motion_shutter_time() * 0.5f;
1059 float3 *mP = attr_mP->data_float3() + step*mesh->verts.size();
1061 BL::DomainFluidSettings::fluid_mesh_vertices_iterator fvi;
1064 for(b_fluid_domain.fluid_mesh_vertices.begin(fvi); fvi != b_fluid_domain.fluid_mesh_vertices.end(); ++fvi, ++i) {
1065 mP[i] = P[i] + get_float3(fvi->velocity()) * relative_time;
1070 Mesh *BlenderSync::sync_mesh(BL::Depsgraph& b_depsgraph,
1072 BL::Object& b_ob_instance,
1073 bool object_updated,
1076 /* When viewport display is not needed during render we can force some
1077 * caches to be releases from blender side in order to reduce peak memory
1078 * footprint during synchronization process.
1080 const bool is_interface_locked = b_engine.render() &&
1081 b_engine.render().use_lock_interface();
1082 const bool can_free_caches = BlenderSession::headless || is_interface_locked;
1084 /* test if we can instance or if the object is modified */
1085 BL::ID b_ob_data = b_ob.data();
1086 BL::ID key = (BKE_object_is_modified(b_ob))? b_ob_instance: b_ob_data;
1087 BL::Material material_override = view_layer.material_override;
1089 /* find shader indices */
1090 vector<Shader*> used_shaders;
1092 BL::Object::material_slots_iterator slot;
1093 for(b_ob.material_slots.begin(slot); slot != b_ob.material_slots.end(); ++slot) {
1094 if(material_override) {
1095 find_shader(material_override, used_shaders, scene->default_surface);
1098 BL::ID b_material(slot->material());
1099 find_shader(b_material, used_shaders, scene->default_surface);
1103 if(used_shaders.size() == 0) {
1104 if(material_override)
1105 find_shader(material_override, used_shaders, scene->default_surface);
1107 used_shaders.push_back(scene->default_surface);
1110 /* test if we need to sync */
1111 int requested_geometry_flags = Mesh::GEOMETRY_NONE;
1112 if(view_layer.use_surfaces) {
1113 requested_geometry_flags |= Mesh::GEOMETRY_TRIANGLES;
1115 if(view_layer.use_hair) {
1116 requested_geometry_flags |= Mesh::GEOMETRY_CURVES;
1120 if(!mesh_map.sync(&mesh, key)) {
1121 /* if transform was applied to mesh, need full update */
1122 if(object_updated && mesh->transform_applied);
1123 /* test if shaders changed, these can be object level so mesh
1124 * does not get tagged for recalc */
1125 else if(mesh->used_shaders != used_shaders);
1126 else if(requested_geometry_flags != mesh->geometry_flags);
1128 /* even if not tagged for recalc, we may need to sync anyway
1129 * because the shader needs different mesh attributes */
1130 bool attribute_recalc = false;
1132 foreach(Shader *shader, mesh->used_shaders)
1133 if(shader->need_update_mesh)
1134 attribute_recalc = true;
1136 if(!attribute_recalc)
1141 /* ensure we only sync instanced meshes once */
1142 if(mesh_synced.find(mesh) != mesh_synced.end())
1145 mesh_synced.insert(mesh);
1147 /* create derived mesh */
1148 array<int> oldtriangles;
1149 array<Mesh::SubdFace> oldsubd_faces;
1150 array<int> oldsubd_face_corners;
1151 oldtriangles.steal_data(mesh->triangles);
1152 oldsubd_faces.steal_data(mesh->subd_faces);
1153 oldsubd_face_corners.steal_data(mesh->subd_face_corners);
1155 /* compares curve_keys rather than strands in order to handle quick hair
1156 * adjustments in dynamic BVH - other methods could probably do this better*/
1157 array<float3> oldcurve_keys;
1158 array<float> oldcurve_radius;
1159 oldcurve_keys.steal_data(mesh->curve_keys);
1160 oldcurve_radius.steal_data(mesh->curve_radius);
1163 mesh->used_shaders = used_shaders;
1164 mesh->name = ustring(b_ob_data.name().c_str());
1166 if(requested_geometry_flags != Mesh::GEOMETRY_NONE) {
1167 /* mesh objects does have special handle in the dependency graph,
1168 * they're ensured to have properly updated.
1170 * updating meshes here will end up having derived mesh referencing
1171 * freed data from the blender side.
1173 if(preview && b_ob.type() != BL::Object::type_MESH)
1174 b_ob.update_from_editmode();
1176 bool need_undeformed = mesh->need_attribute(scene, ATTR_STD_GENERATED);
1178 mesh->subdivision_type = object_subdivision_type(b_ob, preview, experimental);
1180 /* Disable adaptive subdivision while baking as the baking system
1181 * currently doesnt support the topology and will crash.
1183 if(scene->bake_manager->get_baking()) {
1184 mesh->subdivision_type = Mesh::SUBDIVISION_NONE;
1187 BL::Mesh b_mesh = object_to_mesh(b_data,
1190 b_depsgraph.view_layer(),
1194 mesh->subdivision_type);
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);
1202 create_mesh(scene, mesh, b_mesh, used_shaders, false);
1204 create_mesh_volume_attributes(scene, b_ob, mesh, b_scene.frame_current());
1207 if(view_layer.use_hair && mesh->subdivision_type == Mesh::SUBDIVISION_NONE)
1208 sync_curves(b_depsgraph, mesh, b_mesh, b_ob, false);
1210 if(can_free_caches) {
1211 b_ob.cache_release();
1214 /* free derived mesh */
1215 b_data.meshes.remove(b_mesh, false, true, false);
1218 mesh->geometry_flags = requested_geometry_flags;
1221 sync_mesh_fluid_motion(b_ob, scene, mesh);
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);
1230 mesh->tag_update(scene, rebuild);
1235 void BlenderSync::sync_mesh_motion(BL::Depsgraph& b_depsgraph,
1240 /* ensure we only sync instanced meshes once */
1241 Mesh *mesh = object->mesh;
1243 if(mesh_motion_synced.find(mesh) != mesh_motion_synced.end())
1246 mesh_motion_synced.insert(mesh);
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())
1253 /* for motion pass always compute, for motion blur it can be disabled */
1256 if(scene->need_motion() == Scene::MOTION_BLUR) {
1257 if(!mesh->use_motion_blur)
1260 /* see if this mesh needs motion data at this time */
1261 vector<float> object_times = object->motion_times();
1264 foreach(float object_time, object_times) {
1265 if(motion_time == object_time) {
1277 if(motion_time == -1.0f)
1279 else if(motion_time == 1.0f)
1285 /* skip empty meshes */
1286 const size_t numverts = mesh->verts.size();
1287 const size_t numkeys = mesh->curve_keys.size();
1289 if(!numverts && !numkeys)
1292 /* skip objects without deforming modifiers. this is not totally reliable,
1293 * would need a more extensive check to see which objects are animated */
1294 BL::Mesh b_mesh(PointerRNA_NULL);
1296 /* fluid motion is exported immediate with mesh, skip here */
1297 BL::DomainFluidSettings b_fluid_domain = object_fluid_domain_find(b_ob);
1301 if(ccl::BKE_object_is_deform_modified(b_ob, b_scene, preview)) {
1302 /* get derived mesh */
1303 b_mesh = object_to_mesh(b_data,
1306 b_depsgraph.view_layer(),
1310 Mesh::SUBDIVISION_NONE);
1314 /* if we have no motion blur on this frame, but on other frames, copy */
1317 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 float3 *P = &mesh->verts[0];
1323 float3 *N = (attr_N)? attr_N->data_float3(): NULL;
1325 memcpy(attr_mP->data_float3() + time_index*numverts, P, sizeof(float3)*numverts);
1327 memcpy(attr_mN->data_float3() + time_index*numverts, N, sizeof(float3)*numverts);
1333 Attribute *attr_mP = mesh->curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
1336 float3 *keys = &mesh->curve_keys[0];
1337 memcpy(attr_mP->data_float3() + time_index*numkeys, keys, sizeof(float3)*numkeys);
1344 /* TODO(sergey): Perform preliminary check for number of verticies. */
1346 /* Find attributes. */
1347 Attribute *attr_mP = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
1348 Attribute *attr_mN = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_NORMAL);
1349 Attribute *attr_N = mesh->attributes.find(ATTR_STD_VERTEX_NORMAL);
1350 bool new_attribute = false;
1351 /* Add new attributes if they don't exist already. */
1353 attr_mP = mesh->attributes.add(ATTR_STD_MOTION_VERTEX_POSITION);
1355 attr_mN = mesh->attributes.add(ATTR_STD_MOTION_VERTEX_NORMAL);
1357 new_attribute = true;
1359 /* Load vertex data from mesh. */
1360 float3 *mP = attr_mP->data_float3() + time_index*numverts;
1361 float3 *mN = (attr_mN)? attr_mN->data_float3() + time_index*numverts: NULL;
1362 /* NOTE: We don't copy more that existing amount of vertices to prevent
1363 * possible memory corruption.
1365 BL::Mesh::vertices_iterator v;
1367 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end() && i < numverts; ++v, ++i) {
1368 mP[i] = get_float3(v->co());
1370 mN[i] = get_float3(v->normal());
1373 /* In case of new attribute, we verify if there really was any motion. */
1374 if(b_mesh.vertices.length() != numverts ||
1375 memcmp(mP, &mesh->verts[0], sizeof(float3)*numverts) == 0)
1377 /* no motion, remove attributes again */
1378 if(b_mesh.vertices.length() != numverts) {
1379 VLOG(1) << "Topology differs, disabling motion blur for object "
1383 VLOG(1) << "No actual deformation motion for object "
1386 mesh->attributes.remove(ATTR_STD_MOTION_VERTEX_POSITION);
1388 mesh->attributes.remove(ATTR_STD_MOTION_VERTEX_NORMAL);
1390 else if(time_index > 0) {
1391 VLOG(1) << "Filling deformation motion for object " << b_ob.name();
1392 /* motion, fill up previous steps that we might have skipped because
1393 * they had no motion, but we need them anyway now */
1394 float3 *P = &mesh->verts[0];
1395 float3 *N = (attr_N)? attr_N->data_float3(): NULL;
1396 for(int step = 0; step < time_index; step++) {
1397 memcpy(attr_mP->data_float3() + step*numverts, P, sizeof(float3)*numverts);
1399 memcpy(attr_mN->data_float3() + step*numverts, N, sizeof(float3)*numverts);
1404 if(b_mesh.vertices.length() != numverts) {
1405 VLOG(1) << "Topology differs, discarding motion blur for object "
1406 << b_ob.name() << " at time " << time_index;
1407 memcpy(mP, &mesh->verts[0], sizeof(float3)*numverts);
1409 memcpy(mN, attr_N->data_float3(), sizeof(float3)*numverts);
1417 sync_curves(b_depsgraph, mesh, b_mesh, b_ob, true, time_index);
1419 /* free derived mesh */
1420 b_data.meshes.remove(b_mesh, false, true, false);