Fix #35969: blender internal and cycles not updating mesh while in edit mode.
[blender.git] / intern / cycles / blender / blender_mesh.cpp
1 /*
2  * Copyright 2011, Blender Foundation.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  */
18
19  
20 #include "mesh.h"
21 #include "object.h"
22 #include "scene.h"
23
24 #include "blender_sync.h"
25 #include "blender_util.h"
26
27 #include "subd_mesh.h"
28 #include "subd_patch.h"
29 #include "subd_split.h"
30
31 #include "util_foreach.h"
32
33 #include "mikktspace.h"
34
35 CCL_NAMESPACE_BEGIN
36
37 /* Tangent Space */
38
39 struct MikkUserData {
40         MikkUserData(const BL::Mesh mesh_, const BL::MeshTextureFaceLayer layer_, int num_faces_)
41         : mesh(mesh_), layer(layer_), num_faces(num_faces_)
42         {
43                 tangent.resize(num_faces*4);
44         }
45
46         BL::Mesh mesh;
47         BL::MeshTextureFaceLayer layer;
48         int num_faces;
49         vector<float4> tangent;
50 };
51
52 static int mikk_get_num_faces(const SMikkTSpaceContext *context)
53 {
54         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
55         return userdata->num_faces;
56 }
57
58 static int mikk_get_num_verts_of_face(const SMikkTSpaceContext *context, const int face_num)
59 {
60         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
61         BL::MeshTessFace f = userdata->mesh.tessfaces[face_num];
62         int4 vi = get_int4(f.vertices_raw());
63
64         return (vi[3] == 0)? 3: 4;
65 }
66
67 static void mikk_get_position(const SMikkTSpaceContext *context, float P[3], const int face_num, const int vert_num)
68 {
69         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
70         BL::MeshTessFace f = userdata->mesh.tessfaces[face_num];
71         int4 vi = get_int4(f.vertices_raw());
72         BL::MeshVertex v = userdata->mesh.vertices[vi[vert_num]];
73         float3 vP = get_float3(v.co());
74
75         P[0] = vP.x;
76         P[1] = vP.y;
77         P[2] = vP.z;
78 }
79
80 static void mikk_get_texture_coordinate(const SMikkTSpaceContext *context, float uv[2], const int face_num, const int vert_num)
81 {
82         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
83         BL::MeshTextureFace tf = userdata->layer.data[face_num];
84         float3 tfuv;
85         
86         switch (vert_num) {
87                 case 0:
88                         tfuv = get_float3(tf.uv1());
89                         break;
90                 case 1:
91                         tfuv = get_float3(tf.uv2());
92                         break;
93                 case 2:
94                         tfuv = get_float3(tf.uv3());
95                         break;
96                 default:
97                         tfuv = get_float3(tf.uv4());
98                         break;
99         }
100         
101         uv[0] = tfuv.x;
102         uv[1] = tfuv.y;
103 }
104
105 static void mikk_get_normal(const SMikkTSpaceContext *context, float N[3], const int face_num, const int vert_num)
106 {
107         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
108         BL::MeshTessFace f = userdata->mesh.tessfaces[face_num];
109         float3 vN;
110
111         if(f.use_smooth()) {
112                 int4 vi = get_int4(f.vertices_raw());
113                 BL::MeshVertex v = userdata->mesh.vertices[vi[vert_num]];
114                 vN = get_float3(v.normal());
115         }
116         else {
117                 vN = get_float3(f.normal());
118         }
119
120         N[0] = vN.x;
121         N[1] = vN.y;
122         N[2] = vN.z;
123 }
124
125 static void mikk_set_tangent_space(const SMikkTSpaceContext *context, const float T[], const float sign, const int face, const int vert)
126 {
127         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
128
129         userdata->tangent[face*4 + vert] = make_float4(T[0], T[1], T[2], sign);
130 }
131
132 static void mikk_compute_tangents(BL::Mesh b_mesh, BL::MeshTextureFaceLayer b_layer, Mesh *mesh, vector<int>& nverts, bool need_sign, bool active_render)
133 {
134         /* setup userdata */
135         MikkUserData userdata(b_mesh, b_layer, nverts.size());
136
137         /* setup interface */
138         SMikkTSpaceInterface sm_interface;
139         memset(&sm_interface, 0, sizeof(sm_interface));
140         sm_interface.m_getNumFaces = mikk_get_num_faces;
141         sm_interface.m_getNumVerticesOfFace = mikk_get_num_verts_of_face;
142         sm_interface.m_getPosition = mikk_get_position;
143         sm_interface.m_getTexCoord = mikk_get_texture_coordinate;
144         sm_interface.m_getNormal = mikk_get_normal;
145         sm_interface.m_setTSpaceBasic = mikk_set_tangent_space;
146
147         /* setup context */
148         SMikkTSpaceContext context;
149         memset(&context, 0, sizeof(context));
150         context.m_pUserData = &userdata;
151         context.m_pInterface = &sm_interface;
152
153         /* compute tangents */
154         genTangSpaceDefault(&context);
155
156         /* create tangent attributes */
157         Attribute *attr;
158         ustring name = ustring((string(b_layer.name().c_str()) + ".tangent").c_str());
159
160         if(active_render)
161                 attr = mesh->attributes.add(ATTR_STD_UV_TANGENT, name);
162         else
163                 attr = mesh->attributes.add(name, TypeDesc::TypeVector, ATTR_ELEMENT_CORNER);
164
165         float3 *tangent = attr->data_float3();
166
167         /* create bitangent sign attribute */
168         float *tangent_sign = NULL;
169
170         if(need_sign) {
171                 Attribute *attr_sign;
172                 ustring name_sign = ustring((string(b_layer.name().c_str()) + ".tangent_sign").c_str());
173
174                 if(active_render)
175                         attr_sign = mesh->attributes.add(ATTR_STD_UV_TANGENT_SIGN, name_sign);
176                 else
177                         attr_sign = mesh->attributes.add(name_sign, TypeDesc::TypeFloat, ATTR_ELEMENT_CORNER);
178
179                 tangent_sign = attr_sign->data_float();
180         }
181
182         for(int i = 0; i < nverts.size(); i++) {
183                 tangent[0] = float4_to_float3(userdata.tangent[i*4 + 0]);
184                 tangent[1] = float4_to_float3(userdata.tangent[i*4 + 1]);
185                 tangent[2] = float4_to_float3(userdata.tangent[i*4 + 2]);
186                 tangent += 3;
187
188                 if(tangent_sign) {
189                         tangent_sign[0] = userdata.tangent[i*4 + 0].w;
190                         tangent_sign[1] = userdata.tangent[i*4 + 1].w;
191                         tangent_sign[2] = userdata.tangent[i*4 + 2].w;
192                         tangent_sign += 3;
193                 }
194
195                 if(nverts[i] == 4) {
196                         tangent[0] = float4_to_float3(userdata.tangent[i*4 + 0]);
197                         tangent[1] = float4_to_float3(userdata.tangent[i*4 + 2]);
198                         tangent[2] = float4_to_float3(userdata.tangent[i*4 + 3]);
199                         tangent += 3;
200
201                         if(tangent_sign) {
202                                 tangent_sign[0] = userdata.tangent[i*4 + 0].w;
203                                 tangent_sign[1] = userdata.tangent[i*4 + 2].w;
204                                 tangent_sign[2] = userdata.tangent[i*4 + 3].w;
205                                 tangent_sign += 3;
206                         }
207                 }
208         }
209 }
210
211 /* Create Mesh */
212
213 static void create_mesh(Scene *scene, Mesh *mesh, BL::Mesh b_mesh, const vector<uint>& used_shaders)
214 {
215         /* create vertices */
216         BL::Mesh::vertices_iterator v;
217
218         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
219                 mesh->verts.push_back(get_float3(v->co()));
220
221         /* create vertex normals */
222         Attribute *attr_N = mesh->attributes.add(ATTR_STD_VERTEX_NORMAL);
223         float3 *N = attr_N->data_float3();
224
225         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v, ++N)
226                 *N = get_float3(v->normal());
227
228         /* create faces */
229         BL::Mesh::tessfaces_iterator f;
230         vector<int> nverts;
231
232         for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f) {
233                 int4 vi = get_int4(f->vertices_raw());
234                 int n = (vi[3] == 0)? 3: 4;
235                 int mi = clamp(f->material_index(), 0, used_shaders.size()-1);
236                 int shader = used_shaders[mi];
237                 bool smooth = f->use_smooth();
238
239                 if(n == 4) {
240                         if(len_squared(cross(mesh->verts[vi[1]] - mesh->verts[vi[0]], mesh->verts[vi[2]] - mesh->verts[vi[0]])) == 0.0f ||
241                                 len_squared(cross(mesh->verts[vi[2]] - mesh->verts[vi[0]], mesh->verts[vi[3]] - mesh->verts[vi[0]])) == 0.0f) {
242                                 mesh->add_triangle(vi[0], vi[1], vi[3], shader, smooth);
243                                 mesh->add_triangle(vi[2], vi[3], vi[1], shader, smooth);
244                         }
245                         else {
246                                 mesh->add_triangle(vi[0], vi[1], vi[2], shader, smooth);
247                                 mesh->add_triangle(vi[0], vi[2], vi[3], shader, smooth);
248                         }
249                 }
250                 else
251                         mesh->add_triangle(vi[0], vi[1], vi[2], shader, smooth);
252
253                 nverts.push_back(n);
254         }
255
256         /* create vertex color attributes */
257         {
258                 BL::Mesh::tessface_vertex_colors_iterator l;
259
260                 for(b_mesh.tessface_vertex_colors.begin(l); l != b_mesh.tessface_vertex_colors.end(); ++l) {
261                         if(!mesh->need_attribute(scene, ustring(l->name().c_str())))
262                                 continue;
263
264                         Attribute *attr = mesh->attributes.add(
265                                 ustring(l->name().c_str()), TypeDesc::TypeColor, ATTR_ELEMENT_CORNER);
266
267                         BL::MeshColorLayer::data_iterator c;
268                         float3 *fdata = attr->data_float3();
269                         size_t i = 0;
270
271                         for(l->data.begin(c); c != l->data.end(); ++c, ++i) {
272                                 fdata[0] = color_srgb_to_scene_linear(get_float3(c->color1()));
273                                 fdata[1] = color_srgb_to_scene_linear(get_float3(c->color2()));
274                                 fdata[2] = color_srgb_to_scene_linear(get_float3(c->color3()));
275
276                                 if(nverts[i] == 4) {
277                                         fdata[3] = fdata[0];
278                                         fdata[4] = fdata[2];
279                                         fdata[5] = color_srgb_to_scene_linear(get_float3(c->color4()));
280                                         fdata += 6;
281                                 }
282                                 else
283                                         fdata += 3;
284                         }
285                 }
286         }
287
288         /* create uv map attributes */
289         {
290                 BL::Mesh::tessface_uv_textures_iterator l;
291
292                 for(b_mesh.tessface_uv_textures.begin(l); l != b_mesh.tessface_uv_textures.end(); ++l) {
293                         bool active_render = l->active_render();
294                         AttributeStandard std = (active_render)? ATTR_STD_UV: ATTR_STD_NONE;
295                         ustring name = ustring(l->name().c_str());
296
297                         /* UV map */
298                         if(mesh->need_attribute(scene, name) || mesh->need_attribute(scene, std)) {
299                                 Attribute *attr;
300
301                                 if(active_render)
302                                         attr = mesh->attributes.add(std, name);
303                                 else
304                                         attr = mesh->attributes.add(name, TypeDesc::TypePoint, ATTR_ELEMENT_CORNER);
305
306                                 BL::MeshTextureFaceLayer::data_iterator t;
307                                 float3 *fdata = attr->data_float3();
308                                 size_t i = 0;
309
310                                 for(l->data.begin(t); t != l->data.end(); ++t, ++i) {
311                                         fdata[0] =  get_float3(t->uv1());
312                                         fdata[1] =  get_float3(t->uv2());
313                                         fdata[2] =  get_float3(t->uv3());
314                                         fdata += 3;
315
316                                         if(nverts[i] == 4) {
317                                                 fdata[0] =  get_float3(t->uv1());
318                                                 fdata[1] =  get_float3(t->uv3());
319                                                 fdata[2] =  get_float3(t->uv4());
320                                                 fdata += 3;
321                                         }
322                                 }
323                         }
324
325                         /* UV tangent */
326                         std = (active_render)? ATTR_STD_UV_TANGENT: ATTR_STD_NONE;
327                         name = ustring((string(l->name().c_str()) + ".tangent").c_str());
328
329                         if(mesh->need_attribute(scene, name) || (active_render && mesh->need_attribute(scene, std))) {
330                                 std = (active_render)? ATTR_STD_UV_TANGENT_SIGN: ATTR_STD_NONE;
331                                 name = ustring((string(l->name().c_str()) + ".tangent_sign").c_str());
332                                 bool need_sign = (mesh->need_attribute(scene, name) || mesh->need_attribute(scene, std));
333
334                                 mikk_compute_tangents(b_mesh, *l, mesh, nverts, need_sign, active_render);
335                         }
336                 }
337         }
338
339         /* create generated coordinates. todo: we should actually get the orco
340          * coordinates from modifiers, for now we use texspace loc/size which
341          * is available in the api. */
342         if(mesh->need_attribute(scene, ATTR_STD_GENERATED)) {
343                 Attribute *attr = mesh->attributes.add(ATTR_STD_GENERATED);
344
345                 float3 loc, size;
346                 mesh_texture_space(b_mesh, loc, size);
347
348                 float3 *generated = attr->data_float3();
349                 size_t i = 0;
350
351                 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
352                         generated[i++] = get_float3(v->undeformed_co())*size - loc;
353         }
354 }
355
356 static void create_subd_mesh(Mesh *mesh, BL::Mesh b_mesh, PointerRNA *cmesh, const vector<uint>& used_shaders)
357 {
358         /* create subd mesh */
359         SubdMesh sdmesh;
360
361         /* create vertices */
362         BL::Mesh::vertices_iterator v;
363
364         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
365                 sdmesh.add_vert(get_float3(v->co()));
366
367         /* create faces */
368         BL::Mesh::tessfaces_iterator f;
369
370         for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f) {
371                 int4 vi = get_int4(f->vertices_raw());
372                 int n = (vi[3] == 0) ? 3: 4;
373                 //int shader = used_shaders[f->material_index()];
374
375                 if(n == 4)
376                         sdmesh.add_face(vi[0], vi[1], vi[2], vi[3]);
377 #if 0
378                 else
379                         sdmesh.add_face(vi[0], vi[1], vi[2]);
380 #endif
381         }
382
383         /* finalize subd mesh */
384         sdmesh.link_boundary();
385
386         /* subdivide */
387         DiagSplit dsplit;
388         dsplit.camera = NULL;
389         dsplit.dicing_rate = RNA_float_get(cmesh, "dicing_rate");
390
391         sdmesh.tessellate(&dsplit, false, mesh, used_shaders[0], true);
392 }
393
394 /* Sync */
395
396 Mesh *BlenderSync::sync_mesh(BL::Object b_ob, bool object_updated, bool hide_tris)
397 {
398         /* test if we can instance or if the object is modified */
399         BL::ID b_ob_data = b_ob.data();
400         BL::ID key = (BKE_object_is_modified(b_ob))? b_ob: b_ob_data;
401         BL::Material material_override = render_layer.material_override;
402
403         /* find shader indices */
404         vector<uint> used_shaders;
405
406         BL::Object::material_slots_iterator slot;
407         for(b_ob.material_slots.begin(slot); slot != b_ob.material_slots.end(); ++slot) {
408                 if(material_override)
409                         find_shader(material_override, used_shaders, scene->default_surface);
410                 else
411                         find_shader(slot->material(), used_shaders, scene->default_surface);
412         }
413
414         if(used_shaders.size() == 0) {
415                 if(material_override)
416                         find_shader(material_override, used_shaders, scene->default_surface);
417                 else
418                         used_shaders.push_back(scene->default_surface);
419         }
420         
421         /* test if we need to sync */
422         Mesh *mesh;
423
424         if(!mesh_map.sync(&mesh, key)) {
425                 /* if transform was applied to mesh, need full update */
426                 if(object_updated && mesh->transform_applied);
427                 /* test if shaders changed, these can be object level so mesh
428                  * does not get tagged for recalc */
429                 else if(mesh->used_shaders != used_shaders);
430                 else {
431                         /* even if not tagged for recalc, we may need to sync anyway
432                          * because the shader needs different mesh attributes */
433                         bool attribute_recalc = false;
434
435                         foreach(uint shader, mesh->used_shaders)
436                                 if(scene->shaders[shader]->need_update_attributes)
437                                         attribute_recalc = true;
438
439                         if(!attribute_recalc)
440                                 return mesh;
441                 }
442         }
443
444         /* ensure we only sync instanced meshes once */
445         if(mesh_synced.find(mesh) != mesh_synced.end())
446                 return mesh;
447         
448         mesh_synced.insert(mesh);
449
450         /* create derived mesh */
451         bool need_undeformed = mesh->need_attribute(scene, ATTR_STD_GENERATED);
452         PointerRNA cmesh = RNA_pointer_get(&b_ob_data.ptr, "cycles");
453
454         vector<Mesh::Triangle> oldtriangle = mesh->triangles;
455         
456         /* compares curve_keys rather than strands in order to handle quick hair
457          * adjustsments in dynamic BVH - other methods could probably do this better*/
458         vector<Mesh::CurveKey> oldcurve_keys = mesh->curve_keys;
459
460         mesh->clear();
461         mesh->used_shaders = used_shaders;
462         mesh->name = ustring(b_ob_data.name().c_str());
463
464         if(render_layer.use_surfaces || render_layer.use_hair) {
465                 if(preview)
466                         b_ob.update_from_editmode();
467
468                 BL::Mesh b_mesh = object_to_mesh(b_data, b_ob, b_scene, true, !preview, need_undeformed);
469
470                 if(b_mesh) {
471                         if(render_layer.use_surfaces && !(hide_tris && experimental)) {
472                                 if(cmesh.data && experimental && RNA_boolean_get(&cmesh, "use_subdivision"))
473                                         create_subd_mesh(mesh, b_mesh, &cmesh, used_shaders);
474                                 else
475                                         create_mesh(scene, mesh, b_mesh, used_shaders);
476                         }
477
478                         if(render_layer.use_hair && experimental)
479                                 sync_curves(mesh, b_mesh, b_ob, object_updated);
480
481                         /* free derived mesh */
482                         b_data.meshes.remove(b_mesh);
483                 }
484         }
485
486         /* displacement method */
487         if(cmesh.data) {
488                 const int method = RNA_enum_get(&cmesh, "displacement_method");
489
490                 if(method == 0 || !experimental)
491                         mesh->displacement_method = Mesh::DISPLACE_BUMP;
492                 else if(method == 1)
493                         mesh->displacement_method = Mesh::DISPLACE_TRUE;
494                 else
495                         mesh->displacement_method = Mesh::DISPLACE_BOTH;
496         }
497
498         /* tag update */
499         bool rebuild = false;
500
501         if(oldtriangle.size() != mesh->triangles.size())
502                 rebuild = true;
503         else if(oldtriangle.size()) {
504                 if(memcmp(&oldtriangle[0], &mesh->triangles[0], sizeof(Mesh::Triangle)*oldtriangle.size()) != 0)
505                         rebuild = true;
506         }
507
508         if(oldcurve_keys.size() != mesh->curve_keys.size())
509                 rebuild = true;
510         else if(oldcurve_keys.size()) {
511                 if(memcmp(&oldcurve_keys[0], &mesh->curve_keys[0], sizeof(Mesh::CurveKey)*oldcurve_keys.size()) != 0)
512                         rebuild = true;
513         }
514         
515         mesh->tag_update(scene, rebuild);
516
517         return mesh;
518 }
519
520 void BlenderSync::sync_mesh_motion(BL::Object b_ob, Mesh *mesh, int motion)
521 {
522         /* todo: displacement, subdivision */
523         size_t size = mesh->verts.size();
524
525         /* skip objects without deforming modifiers. this is not a totally reliable,
526          * would need a more extensive check to see which objects are animated */
527         if(!size || !ccl::BKE_object_is_deform_modified(b_ob, b_scene, preview))
528                 return;
529
530         /* get derived mesh */
531         BL::Mesh b_mesh = object_to_mesh(b_data, b_ob, b_scene, true, !preview, false);
532
533         if(b_mesh) {
534                 BL::Mesh::vertices_iterator v;
535                 AttributeStandard std = (motion == -1)? ATTR_STD_MOTION_PRE: ATTR_STD_MOTION_POST;
536                 Attribute *attr_M = mesh->attributes.add(std);
537                 float3 *M = attr_M->data_float3(), *cur_M;
538                 size_t i = 0;
539
540                 for(b_mesh.vertices.begin(v), cur_M = M; v != b_mesh.vertices.end() && i < size; ++v, cur_M++, i++)
541                         *cur_M = get_float3(v->co());
542
543                 /* if number of vertices changed, or if coordinates stayed the same, drop it */
544                 if(i != size || memcmp(M, &mesh->verts[0], sizeof(float3)*size) == 0)
545                         mesh->attributes.remove(std);
546
547                 /* free derived mesh */
548                 b_data.meshes.remove(b_mesh);
549         }
550 }
551
552 CCL_NAMESPACE_END
553