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