Merging r50625 through r51896 from trunk into soc-2011-tomato
[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         if(vert_num == 0)
87                 tfuv = get_float3(tf.uv1());
88         else if(vert_num == 1)
89                 tfuv = get_float3(tf.uv2());
90         else if(vert_num == 2)
91                 tfuv = get_float3(tf.uv3());
92         else
93                 tfuv = get_float3(tf.uv4());
94         
95         uv[0] = tfuv.x;
96         uv[1] = tfuv.y;
97 }
98
99 static void mikk_get_normal(const SMikkTSpaceContext *context, float N[3], const int face_num, const int vert_num)
100 {
101         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
102         BL::MeshTessFace f = userdata->mesh.tessfaces[face_num];
103         int4 vi = get_int4(f.vertices_raw());
104         BL::MeshVertex v = userdata->mesh.vertices[vi[vert_num]];
105         float3 vN = get_float3(v.normal());
106
107         N[0] = vN.x;
108         N[1] = vN.y;
109         N[2] = vN.z;
110 }
111
112 static void mikk_set_tangent_space(const SMikkTSpaceContext *context, const float T[], const float sign, const int face, const int vert)
113 {
114         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
115
116         userdata->tangent[face*4 + vert] = make_float4(T[0], T[1], T[2], sign);
117 }
118
119 static void mikk_compute_tangents(BL::Mesh b_mesh, BL::MeshTextureFaceLayer b_layer, Mesh *mesh, vector<int>& nverts)
120 {
121         /* setup userdata */
122         MikkUserData userdata(b_mesh, b_layer, nverts.size());
123
124         /* setup interface */
125         SMikkTSpaceInterface sm_interface;
126         memset(&sm_interface, 0, sizeof(sm_interface));
127         sm_interface.m_getNumFaces = mikk_get_num_faces;
128         sm_interface.m_getNumVerticesOfFace = mikk_get_num_verts_of_face;
129         sm_interface.m_getPosition = mikk_get_position;
130         sm_interface.m_getTexCoord = mikk_get_texture_coordinate;
131         sm_interface.m_getNormal = mikk_get_normal;
132         sm_interface.m_setTSpaceBasic = mikk_set_tangent_space;
133
134         /* setup context */
135         SMikkTSpaceContext context;
136         memset(&context, 0, sizeof(context));
137         context.m_pUserData = &userdata;
138         context.m_pInterface = &sm_interface;
139
140         /* compute tangents */
141         genTangSpaceDefault(&context);
142
143         /* create attribute */
144         /* todo: create float4 attribute for sign */
145         Attribute *attr = mesh->attributes.add(ATTR_STD_TANGENT, ustring("tangent"));
146         float3 *tangent = attr->data_float3();
147
148         for (int i = 0; i < nverts.size(); i++) {
149                 tangent[0] = float4_to_float3(userdata.tangent[i*4 + 0]);
150                 tangent[1] = float4_to_float3(userdata.tangent[i*4 + 1]);
151                 tangent[2] = float4_to_float3(userdata.tangent[i*4 + 2]);
152                 tangent += 3;
153
154                 if(nverts[i] == 4) {
155                         tangent[0] = float4_to_float3(userdata.tangent[i*4 + 0]);
156                         tangent[1] = float4_to_float3(userdata.tangent[i*4 + 2]);
157                         tangent[2] = float4_to_float3(userdata.tangent[i*4 + 3]);
158                         tangent += 3;
159                 }
160         }
161 }
162
163 /* Create Mesh */
164
165 static void create_mesh(Scene *scene, Mesh *mesh, BL::Mesh b_mesh, const vector<uint>& used_shaders)
166 {
167         /* create vertices */
168         BL::Mesh::vertices_iterator v;
169
170         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
171                 mesh->verts.push_back(get_float3(v->co()));
172
173         /* create vertex normals */
174         Attribute *attr_N = mesh->attributes.add(ATTR_STD_VERTEX_NORMAL);
175         float3 *N = attr_N->data_float3();
176
177         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v, ++N)
178                 *N = get_float3(v->normal());
179
180         /* create faces */
181         BL::Mesh::tessfaces_iterator f;
182         vector<int> nverts;
183
184         for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f) {
185                 int4 vi = get_int4(f->vertices_raw());
186                 int n = (vi[3] == 0)? 3: 4;
187                 int mi = clamp(f->material_index(), 0, used_shaders.size()-1);
188                 int shader = used_shaders[mi];
189                 bool smooth = f->use_smooth();
190
191                 mesh->add_triangle(vi[0], vi[1], vi[2], shader, smooth);
192
193                 if(n == 4)
194                         mesh->add_triangle(vi[0], vi[2], vi[3], shader, smooth);
195
196                 nverts.push_back(n);
197         }
198
199         /* create vertex color attributes */
200         {
201                 BL::Mesh::tessface_vertex_colors_iterator l;
202
203                 for(b_mesh.tessface_vertex_colors.begin(l); l != b_mesh.tessface_vertex_colors.end(); ++l) {
204                         if(!mesh->need_attribute(scene, ustring(l->name().c_str())))
205                                 continue;
206
207                         Attribute *attr = mesh->attributes.add(
208                                 ustring(l->name().c_str()), TypeDesc::TypeColor, Attribute::CORNER);
209
210                         BL::MeshColorLayer::data_iterator c;
211                         float3 *fdata = attr->data_float3();
212                         size_t i = 0;
213
214                         for(l->data.begin(c); c != l->data.end(); ++c, ++i) {
215                                 fdata[0] = color_srgb_to_scene_linear(get_float3(c->color1()));
216                                 fdata[1] = color_srgb_to_scene_linear(get_float3(c->color2()));
217                                 fdata[2] = color_srgb_to_scene_linear(get_float3(c->color3()));
218
219                                 if(nverts[i] == 4) {
220                                         fdata[3] = fdata[0];
221                                         fdata[4] = fdata[2];
222                                         fdata[5] = color_srgb_to_scene_linear(get_float3(c->color4()));
223                                         fdata += 6;
224                                 }
225                                 else
226                                         fdata += 3;
227                         }
228                 }
229         }
230
231         /* create uv map attributes */
232         {
233                 BL::Mesh::tessface_uv_textures_iterator l;
234
235                 for(b_mesh.tessface_uv_textures.begin(l); l != b_mesh.tessface_uv_textures.end(); ++l) {
236                         AttributeStandard std = (l->active_render())? ATTR_STD_UV: ATTR_STD_NONE;
237                         ustring name = ustring(l->name().c_str());
238
239                         if(!(mesh->need_attribute(scene, name) || mesh->need_attribute(scene, std)))
240                                 continue;
241
242                         Attribute *attr;
243
244                         if(l->active_render())
245                                 attr = mesh->attributes.add(std, name);
246                         else
247                                 attr = mesh->attributes.add(name, TypeDesc::TypePoint, Attribute::CORNER);
248
249                         BL::MeshTextureFaceLayer::data_iterator t;
250                         float3 *fdata = attr->data_float3();
251                         size_t i = 0;
252
253                         for(l->data.begin(t); t != l->data.end(); ++t, ++i) {
254                                 fdata[0] =  get_float3(t->uv1());
255                                 fdata[1] =  get_float3(t->uv2());
256                                 fdata[2] =  get_float3(t->uv3());
257                                 fdata += 3;
258
259                                 if(nverts[i] == 4) {
260                                         fdata[0] =  get_float3(t->uv1());
261                                         fdata[1] =  get_float3(t->uv3());
262                                         fdata[2] =  get_float3(t->uv4());
263                                         fdata += 3;
264                                 }
265                         }
266                 }
267         }
268
269         /* create texcoord-based tangent attributes */
270         if(mesh->need_attribute(scene, ATTR_STD_TANGENT)) {
271                 BL::Mesh::tessface_uv_textures_iterator l;
272
273                 for(b_mesh.tessface_uv_textures.begin(l); l != b_mesh.tessface_uv_textures.end(); ++l) {
274                         if(!l->active_render())
275                                 continue;
276
277                         mikk_compute_tangents(b_mesh, *l, mesh, nverts);
278                 }
279         }
280
281         /* create generated coordinates. todo: we should actually get the orco
282          * coordinates from modifiers, for now we use texspace loc/size which
283          * is available in the api. */
284         if(mesh->need_attribute(scene, ATTR_STD_GENERATED)) {
285                 Attribute *attr = mesh->attributes.add(ATTR_STD_GENERATED);
286                 float3 loc = get_float3(b_mesh.texspace_location());
287                 float3 size = get_float3(b_mesh.texspace_size());
288
289                 if(size.x != 0.0f) size.x = 0.5f/size.x;
290                 if(size.y != 0.0f) size.y = 0.5f/size.y;
291                 if(size.z != 0.0f) size.z = 0.5f/size.z;
292
293                 loc = loc*size - make_float3(0.5f, 0.5f, 0.5f);
294
295                 float3 *generated = attr->data_float3();
296                 size_t i = 0;
297
298                 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
299                         generated[i++] = get_float3(v->co())*size - loc;
300         }
301 }
302
303 static void create_subd_mesh(Mesh *mesh, BL::Mesh b_mesh, PointerRNA *cmesh, const vector<uint>& used_shaders)
304 {
305         /* create subd mesh */
306         SubdMesh sdmesh;
307
308         /* create vertices */
309         BL::Mesh::vertices_iterator v;
310
311         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
312                 sdmesh.add_vert(get_float3(v->co()));
313
314         /* create faces */
315         BL::Mesh::tessfaces_iterator f;
316
317         for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f) {
318                 int4 vi = get_int4(f->vertices_raw());
319                 int n = (vi[3] == 0) ? 3: 4;
320                 //int shader = used_shaders[f->material_index()];
321
322                 if(n == 4)
323                         sdmesh.add_face(vi[0], vi[1], vi[2], vi[3]);
324 #if 0
325                 else
326                         sdmesh.add_face(vi[0], vi[1], vi[2]);
327 #endif
328         }
329
330         /* finalize subd mesh */
331         sdmesh.link_boundary();
332
333         /* subdivide */
334         DiagSplit dsplit;
335         dsplit.camera = NULL;
336         dsplit.dicing_rate = RNA_float_get(cmesh, "dicing_rate");
337
338         sdmesh.tessellate(&dsplit, false, mesh, used_shaders[0], true);
339 }
340
341 /* Sync */
342
343 Mesh *BlenderSync::sync_mesh(BL::Object b_ob, bool object_updated)
344 {
345         /* test if we can instance or if the object is modified */
346         BL::ID b_ob_data = b_ob.data();
347         BL::ID key = (BKE_object_is_modified(b_ob))? b_ob: b_ob_data;
348         BL::Material material_override = render_layer.material_override;
349
350         /* find shader indices */
351         vector<uint> used_shaders;
352
353         BL::Object::material_slots_iterator slot;
354         for(b_ob.material_slots.begin(slot); slot != b_ob.material_slots.end(); ++slot) {
355                 if(material_override)
356                         find_shader(material_override, used_shaders, scene->default_surface);
357                 else
358                         find_shader(slot->material(), used_shaders, scene->default_surface);
359         }
360
361         if(used_shaders.size() == 0) {
362                 if(material_override)
363                         find_shader(material_override, used_shaders, scene->default_surface);
364                 else
365                         used_shaders.push_back(scene->default_surface);
366         }
367         
368         /* test if we need to sync */
369         Mesh *mesh;
370
371         if(!mesh_map.sync(&mesh, key)) {
372                 /* if transform was applied to mesh, need full update */
373                 if(object_updated && mesh->transform_applied);
374                 /* test if shaders changed, these can be object level so mesh
375                  * does not get tagged for recalc */
376                 else if(mesh->used_shaders != used_shaders);
377                 else {
378                         /* even if not tagged for recalc, we may need to sync anyway
379                          * because the shader needs different mesh attributes */
380                         bool attribute_recalc = false;
381
382                         foreach(uint shader, mesh->used_shaders)
383                                 if(scene->shaders[shader]->need_update_attributes)
384                                         attribute_recalc = true;
385
386                         if(!attribute_recalc)
387                                 return mesh;
388                 }
389         }
390
391         /* ensure we only sync instanced meshes once */
392         if(mesh_synced.find(mesh) != mesh_synced.end())
393                 return mesh;
394         
395         mesh_synced.insert(mesh);
396
397         /* create derived mesh */
398         BL::Mesh b_mesh = object_to_mesh(b_ob, b_scene, true, !preview);
399         PointerRNA cmesh = RNA_pointer_get(&b_ob_data.ptr, "cycles");
400
401         vector<Mesh::Triangle> oldtriangle = mesh->triangles;
402
403         mesh->clear();
404         mesh->used_shaders = used_shaders;
405         mesh->name = ustring(b_ob_data.name().c_str());
406
407         if(b_mesh) {
408                 if(cmesh.data && experimental && RNA_boolean_get(&cmesh, "use_subdivision"))
409                         create_subd_mesh(mesh, b_mesh, &cmesh, used_shaders);
410                 else
411                         create_mesh(scene, mesh, b_mesh, used_shaders);
412
413                 /* free derived mesh */
414                 b_data.meshes.remove(b_mesh);
415         }
416
417         /* displacement method */
418         if(cmesh.data) {
419                 int method = RNA_enum_get(&cmesh, "displacement_method");
420
421                 if(method == 0 || !experimental)
422                         mesh->displacement_method = Mesh::DISPLACE_BUMP;
423                 else if(method == 1)
424                         mesh->displacement_method = Mesh::DISPLACE_TRUE;
425                 else
426                         mesh->displacement_method = Mesh::DISPLACE_BOTH;
427         }
428
429         /* tag update */
430         bool rebuild = false;
431
432         if(oldtriangle.size() != mesh->triangles.size())
433                 rebuild = true;
434         else if(oldtriangle.size()) {
435                 if(memcmp(&oldtriangle[0], &mesh->triangles[0], sizeof(Mesh::Triangle)*oldtriangle.size()) != 0)
436                         rebuild = true;
437         }
438         
439         mesh->tag_update(scene, rebuild);
440
441         return mesh;
442 }
443
444 void BlenderSync::sync_mesh_motion(BL::Object b_ob, Mesh *mesh, int motion)
445 {
446         /* todo: displacement, subdivision */
447         size_t size = mesh->verts.size();
448
449         /* skip objects without deforming modifiers. this is not a totally reliable,
450          * would need a more extensive check to see which objects are animated */
451         if(!size || !ccl::BKE_object_is_deform_modified(b_ob, b_scene, preview))
452                 return;
453
454         /* get derived mesh */
455         BL::Mesh b_mesh = object_to_mesh(b_ob, b_scene, true, !preview);
456
457         if(b_mesh) {
458                 BL::Mesh::vertices_iterator v;
459                 AttributeStandard std = (motion == -1)? ATTR_STD_MOTION_PRE: ATTR_STD_MOTION_POST;
460                 Attribute *attr_M = mesh->attributes.add(std);
461                 float3 *M = attr_M->data_float3(), *cur_M;
462                 size_t i = 0;
463
464                 for(b_mesh.vertices.begin(v), cur_M = M; v != b_mesh.vertices.end() && i < size; ++v, cur_M++, i++)
465                         *cur_M = get_float3(v->co());
466
467                 /* if number of vertices changed, or if coordinates stayed the same, drop it */
468                 if(i != size || memcmp(M, &mesh->verts[0], sizeof(float3)*size) == 0)
469                         mesh->attributes.remove(std);
470
471                 /* free derived mesh */
472                 b_data.meshes.remove(b_mesh);
473         }
474 }
475
476 CCL_NAMESPACE_END
477