add BLI_strcpy_rlen, replace strcat, which was used in misleading way.
[blender.git] / intern / cycles / render / 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 "bvh.h"
20 #include "bvh_build.h"
21
22 #include "camera.h"
23 #include "device.h"
24 #include "shader.h"
25 #include "light.h"
26 #include "mesh.h"
27 #include "object.h"
28 #include "scene.h"
29
30 #include "osl_globals.h"
31
32 #include "util_cache.h"
33 #include "util_foreach.h"
34 #include "util_progress.h"
35 #include "util_set.h"
36
37 CCL_NAMESPACE_BEGIN
38
39 /* Mesh */
40
41 Mesh::Mesh()
42 {
43         need_update = true;
44         transform_applied = false;
45         transform_negative_scaled = false;
46         transform_normal = transform_identity();
47         displacement_method = DISPLACE_BUMP;
48         bounds = BoundBox::empty;
49
50         bvh = NULL;
51
52         tri_offset = 0;
53         vert_offset = 0;
54
55         curve_offset = 0;
56         curvekey_offset = 0;
57
58         attributes.triangle_mesh = this;
59         curve_attributes.curve_mesh = this;
60 }
61
62 Mesh::~Mesh()
63 {
64         delete bvh;
65 }
66
67 void Mesh::reserve(int numverts, int numtris, int numcurves, int numcurvekeys)
68 {
69         /* reserve space to add verts and triangles later */
70         verts.resize(numverts);
71         triangles.resize(numtris);
72         shader.resize(numtris);
73         smooth.resize(numtris);
74         curve_keys.resize(numcurvekeys);
75         curves.resize(numcurves);
76
77         attributes.reserve();
78         curve_attributes.reserve();
79 }
80
81 void Mesh::clear()
82 {
83         /* clear all verts and triangles */
84         verts.clear();
85         triangles.clear();
86         shader.clear();
87         smooth.clear();
88
89         curve_keys.clear();
90         curves.clear();
91
92         attributes.clear();
93         curve_attributes.clear();
94         used_shaders.clear();
95
96         transform_applied = false;
97         transform_negative_scaled = false;
98         transform_normal = transform_identity();
99 }
100
101 void Mesh::add_triangle(int v0, int v1, int v2, int shader_, bool smooth_)
102 {
103         Triangle tri;
104         tri.v[0] = v0;
105         tri.v[1] = v1;
106         tri.v[2] = v2;
107
108         triangles.push_back(tri);
109         shader.push_back(shader_);
110         smooth.push_back(smooth_);
111 }
112
113 void Mesh::add_curve_key(float3 co, float radius)
114 {
115         CurveKey key;
116         key.co = co;
117         key.radius = radius;
118
119         curve_keys.push_back(key);
120 }
121
122 void Mesh::add_curve(int first_key, int num_keys, int shader)
123 {
124         Curve curve;
125         curve.first_key = first_key;
126         curve.num_keys = num_keys;
127         curve.shader = shader;
128
129         curves.push_back(curve);
130 }
131
132 void Mesh::compute_bounds()
133 {
134         BoundBox bnds = BoundBox::empty;
135         size_t verts_size = verts.size();
136         size_t curve_keys_size = curve_keys.size();
137
138         if(verts_size + curve_keys_size > 0) {
139                 for(size_t i = 0; i < verts_size; i++)
140                         bnds.grow(verts[i]);
141
142                 for(size_t i = 0; i < curve_keys_size; i++)
143                         bnds.grow(curve_keys[i].co, curve_keys[i].radius);
144
145                 if(!bnds.valid()) {
146                         bnds = BoundBox::empty;
147
148                         /* skip nan or inf coordinates */
149                         for(size_t i = 0; i < verts_size; i++)
150                                 bnds.grow_safe(verts[i]);
151
152                         for(size_t i = 0; i < curve_keys_size; i++)
153                                 bnds.grow_safe(curve_keys[i].co, curve_keys[i].radius);
154                 }
155         }
156
157         if(!bnds.valid()) {
158                 /* empty mesh */
159                 bnds.grow(make_float3(0.0f, 0.0f, 0.0f));
160         }
161
162         bounds = bnds;
163 }
164
165 void Mesh::add_face_normals()
166 {
167         /* don't compute if already there */
168         if(attributes.find(ATTR_STD_FACE_NORMAL))
169                 return;
170         
171         /* get attributes */
172         Attribute *attr_fN = attributes.add(ATTR_STD_FACE_NORMAL);
173         float3 *fN = attr_fN->data_float3();
174
175         /* compute face normals */
176         size_t triangles_size = triangles.size();
177         bool flip = transform_negative_scaled;
178
179         if(triangles_size) {
180                 float3 *verts_ptr = &verts[0];
181                 Triangle *triangles_ptr = &triangles[0];
182
183                 for(size_t i = 0; i < triangles_size; i++) {
184                         Triangle t = triangles_ptr[i];
185                         float3 v0 = verts_ptr[t.v[0]];
186                         float3 v1 = verts_ptr[t.v[1]];
187                         float3 v2 = verts_ptr[t.v[2]];
188
189                         float3 norm = cross(v1 - v0, v2 - v0);
190                         float normlen = len(norm);
191                         if(normlen == 0.0f)
192                                 fN[i] = make_float3(0.0f, 0.0f, 0.0f);
193                         else
194                                 fN[i] = norm / normlen;
195
196                         if(flip)
197                                 fN[i] = -fN[i];
198                 }
199         }
200
201         /* expected to be in local space */
202         if(transform_applied) {
203                 Transform ntfm = transform_inverse(transform_normal);
204
205                 for(size_t i = 0; i < triangles_size; i++)
206                         fN[i] = normalize(transform_direction(&ntfm, fN[i]));
207         }
208 }
209
210 void Mesh::add_vertex_normals()
211 {
212         /* don't compute if already there */
213         if(attributes.find(ATTR_STD_VERTEX_NORMAL))
214                 return;
215         
216         /* get attributes */
217         Attribute *attr_fN = attributes.find(ATTR_STD_FACE_NORMAL);
218         Attribute *attr_vN = attributes.add(ATTR_STD_VERTEX_NORMAL);
219
220         float3 *fN = attr_fN->data_float3();
221         float3 *vN = attr_vN->data_float3();
222
223         /* compute vertex normals */
224         memset(vN, 0, verts.size()*sizeof(float3));
225
226         size_t verts_size = verts.size();
227         size_t triangles_size = triangles.size();
228         bool flip = transform_negative_scaled;
229
230         if(triangles_size) {
231                 Triangle *triangles_ptr = &triangles[0];
232
233                 for(size_t i = 0; i < triangles_size; i++)
234                         for(size_t j = 0; j < 3; j++)
235                                 vN[triangles_ptr[i].v[j]] += fN[i];
236         }
237
238         for(size_t i = 0; i < verts_size; i++) {
239                 vN[i] = normalize(vN[i]);
240                 if(flip)
241                         vN[i] = -vN[i];
242         }
243 }
244
245 void Mesh::pack_normals(Scene *scene, float4 *normal, float4 *vnormal)
246 {
247         Attribute *attr_fN = attributes.find(ATTR_STD_FACE_NORMAL);
248         Attribute *attr_vN = attributes.find(ATTR_STD_VERTEX_NORMAL);
249
250         float3 *fN = attr_fN->data_float3();
251         float3 *vN = attr_vN->data_float3();
252         int shader_id = 0;
253         uint last_shader = -1;
254         bool last_smooth = false;
255
256         size_t triangles_size = triangles.size();
257         uint *shader_ptr = (shader.size())? &shader[0]: NULL;
258
259         bool do_transform = transform_applied;
260         Transform ntfm = transform_normal;
261
262         for(size_t i = 0; i < triangles_size; i++) {
263                 float3 fNi = fN[i];
264
265                 if(do_transform)
266                         fNi = normalize(transform_direction(&ntfm, fNi));
267
268                 normal[i].x = fNi.x;
269                 normal[i].y = fNi.y;
270                 normal[i].z = fNi.z;
271
272                 /* stuff shader id in here too */
273                 if(shader_ptr[i] != last_shader || last_smooth != smooth[i]) {
274                         last_shader = shader_ptr[i];
275                         last_smooth = smooth[i];
276                         shader_id = scene->shader_manager->get_shader_id(last_shader, this, last_smooth);
277                 }
278
279                 normal[i].w = __int_as_float(shader_id);
280         }
281
282         size_t verts_size = verts.size();
283
284         for(size_t i = 0; i < verts_size; i++) {
285                 float3 vNi = vN[i];
286
287                 if(do_transform)
288                         vNi = normalize(transform_direction(&ntfm, vNi));
289
290                 vnormal[i] = make_float4(vNi.x, vNi.y, vNi.z, 0.0f);
291         }
292 }
293
294 void Mesh::pack_verts(float4 *tri_verts, float4 *tri_vindex, size_t vert_offset)
295 {
296         size_t verts_size = verts.size();
297
298         if(verts_size) {
299                 float3 *verts_ptr = &verts[0];
300
301                 for(size_t i = 0; i < verts_size; i++) {
302                         float3 p = verts_ptr[i];
303                         tri_verts[i] = make_float4(p.x, p.y, p.z, 0.0f);
304                 }
305         }
306
307         size_t triangles_size = triangles.size();
308
309         if(triangles_size) {
310                 Triangle *triangles_ptr = &triangles[0];
311
312                 for(size_t i = 0; i < triangles_size; i++) {
313                         Triangle t = triangles_ptr[i];
314
315                         tri_vindex[i] = make_float4(
316                                 __int_as_float(t.v[0] + vert_offset),
317                                 __int_as_float(t.v[1] + vert_offset),
318                                 __int_as_float(t.v[2] + vert_offset),
319                                 0);
320                 }
321         }
322 }
323
324 void Mesh::pack_curves(Scene *scene, float4 *curve_key_co, float4 *curve_data, size_t curvekey_offset)
325 {
326         size_t curve_keys_size = curve_keys.size();
327         CurveKey *keys_ptr = NULL;
328
329         /* pack curve keys */
330         if(curve_keys_size) {
331                 keys_ptr = &curve_keys[0];
332
333                 for(size_t i = 0; i < curve_keys_size; i++) {
334                         float3 p = keys_ptr[i].co;
335                         float radius = keys_ptr[i].radius;
336
337                         curve_key_co[i] = make_float4(p.x, p.y, p.z, radius);
338                 }
339         }
340
341         /* pack curve segments */
342         size_t curve_num = curves.size();
343
344         if(curve_num) {
345                 Curve *curve_ptr = &curves[0];
346                 int shader_id = 0;
347                 
348                 for(size_t i = 0; i < curve_num; i++) {
349                         Curve curve = curve_ptr[i];
350                         shader_id = scene->shader_manager->get_shader_id(curve.shader, this, false);
351
352                         curve_data[i] = make_float4(
353                                 __int_as_float(curve.first_key + curvekey_offset),
354                                 __int_as_float(curve.num_keys),
355                                 __int_as_float(shader_id),
356                                 0.0f);
357                 }
358         }
359 }
360
361 void Mesh::compute_bvh(SceneParams *params, Progress *progress, int n, int total)
362 {
363         if(progress->get_cancel())
364                 return;
365
366         compute_bounds();
367
368         if(!transform_applied) {
369                 string msg = "Updating Mesh BVH ";
370                 if(name == "")
371                         msg += string_printf("%u/%u", (uint)(n+1), (uint)total);
372                 else
373                         msg += string_printf("%s %u/%u", name.c_str(), (uint)(n+1), (uint)total);
374
375                 Object object;
376                 object.mesh = this;
377
378                 vector<Object*> objects;
379                 objects.push_back(&object);
380
381                 if(bvh && !need_update_rebuild) {
382                         progress->set_status(msg, "Refitting BVH");
383                         bvh->objects = objects;
384                         bvh->refit(*progress);
385                 }
386                 else {
387                         progress->set_status(msg, "Building BVH");
388
389                         BVHParams bparams;
390                         bparams.use_cache = params->use_bvh_cache;
391                         bparams.use_spatial_split = params->use_bvh_spatial_split;
392                         bparams.use_qbvh = params->use_qbvh;
393
394                         delete bvh;
395                         bvh = BVH::create(bparams, objects);
396                         bvh->build(*progress);
397                 }
398         }
399
400         need_update = false;
401         need_update_rebuild = false;
402 }
403
404 void Mesh::tag_update(Scene *scene, bool rebuild)
405 {
406         need_update = true;
407
408         if(rebuild) {
409                 need_update_rebuild = true;
410                 scene->light_manager->need_update = true;
411         }
412         else {
413                 foreach(uint sindex, used_shaders)
414                         if(scene->shaders[sindex]->has_surface_emission)
415                                 scene->light_manager->need_update = true;
416         }
417
418         scene->mesh_manager->need_update = true;
419         scene->object_manager->need_update = true;
420 }
421
422 /* Mesh Manager */
423
424 MeshManager::MeshManager()
425 {
426         bvh = NULL;
427         need_update = true;
428 }
429
430 MeshManager::~MeshManager()
431 {
432         delete bvh;
433 }
434
435 void MeshManager::update_osl_attributes(Device *device, Scene *scene, vector<AttributeRequestSet>& mesh_attributes)
436 {
437 #ifdef WITH_OSL
438         /* for OSL, a hash map is used to lookup the attribute by name. */
439         OSLGlobals *og = (OSLGlobals*)device->osl_memory();
440
441         og->object_name_map.clear();
442         og->attribute_map.clear();
443         og->object_names.clear();
444
445         og->attribute_map.resize(scene->objects.size()*ATTR_PRIM_TYPES);
446
447         for(size_t i = 0; i < scene->objects.size(); i++) {
448                 /* set object name to object index map */
449                 Object *object = scene->objects[i];
450                 og->object_name_map[object->name] = i;
451                 og->object_names.push_back(object->name);
452
453                 /* set object attributes */
454                 foreach(ParamValue& attr, object->attributes) {
455                         OSLGlobals::Attribute osl_attr;
456
457                         osl_attr.type = attr.type();
458                         osl_attr.elem = ATTR_ELEMENT_VALUE;
459                         osl_attr.value = attr;
460
461                         og->attribute_map[i*ATTR_PRIM_TYPES][attr.name()] = osl_attr;
462                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][attr.name()] = osl_attr;
463                 }
464
465                 /* find mesh attributes */
466                 size_t j;
467
468                 for(j = 0; j < scene->meshes.size(); j++)
469                         if(scene->meshes[j] == object->mesh)
470                                 break;
471
472                 AttributeRequestSet& attributes = mesh_attributes[j];
473
474                 /* set object attributes */
475                 foreach(AttributeRequest& req, attributes.requests) {
476                         OSLGlobals::Attribute osl_attr;
477
478                         if(req.triangle_element != ATTR_ELEMENT_NONE) {
479                                 osl_attr.elem = req.triangle_element;
480                                 osl_attr.offset = req.triangle_offset;
481
482                                 if(req.triangle_type == TypeDesc::TypeFloat)
483                                         osl_attr.type = TypeDesc::TypeFloat;
484                                 else
485                                         osl_attr.type = TypeDesc::TypeColor;
486
487                                 if(req.std != ATTR_STD_NONE) {
488                                         /* if standard attribute, add lookup by geom: name convention */
489                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
490                                         og->attribute_map[i*ATTR_PRIM_TYPES][stdname] = osl_attr;
491                                 }
492                                 else if(req.name != ustring()) {
493                                         /* add lookup by mesh attribute name */
494                                         og->attribute_map[i*ATTR_PRIM_TYPES][req.name] = osl_attr;
495                                 }
496                         }
497
498                         if(req.curve_element != ATTR_ELEMENT_NONE) {
499                                 osl_attr.elem = req.curve_element;
500                                 osl_attr.offset = req.curve_offset;
501
502                                 if(req.curve_type == TypeDesc::TypeFloat)
503                                         osl_attr.type = TypeDesc::TypeFloat;
504                                 else
505                                         osl_attr.type = TypeDesc::TypeColor;
506
507                                 if(req.std != ATTR_STD_NONE) {
508                                         /* if standard attribute, add lookup by geom: name convention */
509                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
510                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][stdname] = osl_attr;
511                                 }
512                                 else if(req.name != ustring()) {
513                                         /* add lookup by mesh attribute name */
514                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][req.name] = osl_attr;
515                                 }
516                         }
517                 }
518         }
519 #endif
520 }
521
522 void MeshManager::update_svm_attributes(Device *device, DeviceScene *dscene, Scene *scene, vector<AttributeRequestSet>& mesh_attributes)
523 {
524         /* for SVM, the attributes_map table is used to lookup the offset of an
525          * attribute, based on a unique shader attribute id. */
526
527         /* compute array stride */
528         int attr_map_stride = 0;
529
530         for(size_t i = 0; i < scene->meshes.size(); i++)
531                 attr_map_stride = max(attr_map_stride, (mesh_attributes[i].size() + 1)*ATTR_PRIM_TYPES);
532
533         if(attr_map_stride == 0)
534                 return;
535         
536         /* create attribute map */
537         uint4 *attr_map = dscene->attributes_map.resize(attr_map_stride*scene->objects.size());
538         memset(attr_map, 0, dscene->attributes_map.size()*sizeof(uint));
539
540         for(size_t i = 0; i < scene->objects.size(); i++) {
541                 Object *object = scene->objects[i];
542                 Mesh *mesh = object->mesh;
543
544                 /* find mesh attributes */
545                 size_t j;
546
547                 for(j = 0; j < scene->meshes.size(); j++)
548                         if(scene->meshes[j] == mesh)
549                                 break;
550
551                 AttributeRequestSet& attributes = mesh_attributes[j];
552
553                 /* set object attributes */
554                 int index = i*attr_map_stride;
555
556                 foreach(AttributeRequest& req, attributes.requests) {
557                         uint id;
558
559                         if(req.std == ATTR_STD_NONE)
560                                 id = scene->shader_manager->get_attribute_id(req.name);
561                         else
562                                 id = scene->shader_manager->get_attribute_id(req.std);
563
564                         if(mesh->triangles.size()) {
565                                 attr_map[index].x = id;
566                                 attr_map[index].y = req.triangle_element;
567                                 attr_map[index].z = as_uint(req.triangle_offset);
568
569                                 if(req.triangle_type == TypeDesc::TypeFloat)
570                                         attr_map[index].w = NODE_ATTR_FLOAT;
571                                 else
572                                         attr_map[index].w = NODE_ATTR_FLOAT3;
573                         }
574
575                         index++;
576
577                         if(mesh->curves.size()) {
578                                 attr_map[index].x = id;
579                                 attr_map[index].y = req.curve_element;
580                                 attr_map[index].z = as_uint(req.curve_offset);
581
582                                 if(req.curve_type == TypeDesc::TypeFloat)
583                                         attr_map[index].w = NODE_ATTR_FLOAT;
584                                 else
585                                         attr_map[index].w = NODE_ATTR_FLOAT3;
586                         }
587
588                         index++;
589                 }
590
591                 /* terminator */
592                 attr_map[index].x = ATTR_STD_NONE;
593                 attr_map[index].y = 0;
594                 attr_map[index].z = 0;
595                 attr_map[index].w = 0;
596
597                 index++;
598
599                 attr_map[index].x = ATTR_STD_NONE;
600                 attr_map[index].y = 0;
601                 attr_map[index].z = 0;
602                 attr_map[index].w = 0;
603
604                 index++;
605         }
606
607         /* copy to device */
608         dscene->data.bvh.attributes_map_stride = attr_map_stride;
609         device->tex_alloc("__attributes_map", dscene->attributes_map);
610 }
611
612 static void update_attribute_element_offset(Mesh *mesh, vector<float>& attr_float, vector<float4>& attr_float3,
613         Attribute *mattr, TypeDesc& type, int& offset, AttributeElement& element)
614 {
615         if(mattr) {
616                 /* store element and type */
617                 element = mattr->element;
618                 type = mattr->type;
619
620                 /* store attribute data in arrays */
621                 size_t size = mattr->element_size(
622                         mesh->verts.size(),
623                         mesh->triangles.size(),
624                         mesh->curves.size(),
625                         mesh->curve_keys.size());
626
627                 if(mattr->type == TypeDesc::TypeFloat) {
628                         float *data = mattr->data_float();
629                         offset = attr_float.size();
630
631                         attr_float.resize(attr_float.size() + size);
632
633                         for(size_t k = 0; k < size; k++)
634                                 attr_float[offset+k] = data[k];
635                 }
636                 else {
637                         float3 *data = mattr->data_float3();
638                         offset = attr_float3.size();
639
640                         attr_float3.resize(attr_float3.size() + size);
641
642                         for(size_t k = 0; k < size; k++)
643                                 attr_float3[offset+k] = float3_to_float4(data[k]);
644                 }
645
646                 /* mesh vertex/curve index is global, not per object, so we sneak
647                  * a correction for that in here */
648                 if(element == ATTR_ELEMENT_VERTEX)
649                         offset -= mesh->vert_offset;
650                 else if(element == ATTR_ELEMENT_FACE)
651                         offset -= mesh->tri_offset;
652                 else if(element == ATTR_ELEMENT_CORNER)
653                         offset -= 3*mesh->tri_offset;
654                 else if(element == ATTR_ELEMENT_CURVE)
655                         offset -= mesh->curve_offset;
656                 else if(element == ATTR_ELEMENT_CURVE_KEY)
657                         offset -= mesh->curvekey_offset;
658         }
659         else {
660                 /* attribute not found */
661                 element = ATTR_ELEMENT_NONE;
662                 offset = 0;
663         }
664 }
665
666 void MeshManager::device_update_attributes(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
667 {
668         progress.set_status("Updating Mesh", "Computing attributes");
669
670         /* gather per mesh requested attributes. as meshes may have multiple
671          * shaders assigned, this merges the requested attributes that have
672          * been set per shader by the shader manager */
673         vector<AttributeRequestSet> mesh_attributes(scene->meshes.size());
674
675         for(size_t i = 0; i < scene->meshes.size(); i++) {
676                 Mesh *mesh = scene->meshes[i];
677
678                 scene->need_global_attributes(mesh_attributes[i]);
679
680                 foreach(uint sindex, mesh->used_shaders) {
681                         Shader *shader = scene->shaders[sindex];
682                         mesh_attributes[i].add(shader->attributes);
683                 }
684         }
685
686         /* mesh attribute are stored in a single array per data type. here we fill
687          * those arrays, and set the offset and element type to create attribute
688          * maps next */
689         vector<float> attr_float;
690         vector<float4> attr_float3;
691
692         for(size_t i = 0; i < scene->meshes.size(); i++) {
693                 Mesh *mesh = scene->meshes[i];
694                 AttributeRequestSet& attributes = mesh_attributes[i];
695
696                 /* todo: we now store std and name attributes from requests even if
697                  * they actually refer to the same mesh attributes, optimize */
698                 foreach(AttributeRequest& req, attributes.requests) {
699                         Attribute *triangle_mattr = mesh->attributes.find(req);
700                         Attribute *curve_mattr = mesh->curve_attributes.find(req);
701
702                         /* todo: get rid of this exception, it's only here for giving some
703                          * working texture coordinate for subdivision as we can't preserve
704                          * any attributes yet */
705                         if(!triangle_mattr && req.std == ATTR_STD_GENERATED) {
706                                 triangle_mattr = mesh->attributes.add(ATTR_STD_GENERATED);
707                                 if(mesh->verts.size())
708                                         memcpy(triangle_mattr->data_float3(), &mesh->verts[0], sizeof(float3)*mesh->verts.size());
709                         }
710
711                         update_attribute_element_offset(mesh, attr_float, attr_float3, triangle_mattr,
712                                 req.triangle_type, req.triangle_offset, req.triangle_element);
713
714                         update_attribute_element_offset(mesh, attr_float, attr_float3, curve_mattr,
715                                 req.curve_type, req.curve_offset, req.curve_element);
716         
717                         if(progress.get_cancel()) return;
718                 }
719         }
720
721         /* create attribute lookup maps */
722         if(scene->shader_manager->use_osl())
723                 update_osl_attributes(device, scene, mesh_attributes);
724         else
725                 update_svm_attributes(device, dscene, scene, mesh_attributes);
726
727         if(progress.get_cancel()) return;
728
729         /* copy to device */
730         progress.set_status("Updating Mesh", "Copying Attributes to device");
731
732         if(attr_float.size()) {
733                 dscene->attributes_float.copy(&attr_float[0], attr_float.size());
734                 device->tex_alloc("__attributes_float", dscene->attributes_float);
735         }
736         if(attr_float3.size()) {
737                 dscene->attributes_float3.copy(&attr_float3[0], attr_float3.size());
738                 device->tex_alloc("__attributes_float3", dscene->attributes_float3);
739         }
740 }
741
742 void MeshManager::device_update_mesh(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
743 {
744         /* count and update offsets */
745         size_t vert_size = 0;
746         size_t tri_size = 0;
747
748         size_t curve_key_size = 0;
749         size_t curve_size = 0;
750
751         foreach(Mesh *mesh, scene->meshes) {
752                 mesh->vert_offset = vert_size;
753                 mesh->tri_offset = tri_size;
754
755                 mesh->curvekey_offset = curve_key_size;
756                 mesh->curve_offset = curve_size;
757
758                 vert_size += mesh->verts.size();
759                 tri_size += mesh->triangles.size();
760
761                 curve_key_size += mesh->curve_keys.size();
762                 curve_size += mesh->curves.size();
763         }
764
765         if(tri_size != 0) {
766                 /* normals */
767                 progress.set_status("Updating Mesh", "Computing normals");
768
769                 float4 *normal = dscene->tri_normal.resize(tri_size);
770                 float4 *vnormal = dscene->tri_vnormal.resize(vert_size);
771                 float4 *tri_verts = dscene->tri_verts.resize(vert_size);
772                 float4 *tri_vindex = dscene->tri_vindex.resize(tri_size);
773
774                 foreach(Mesh *mesh, scene->meshes) {
775                         mesh->pack_normals(scene, &normal[mesh->tri_offset], &vnormal[mesh->vert_offset]);
776                         mesh->pack_verts(&tri_verts[mesh->vert_offset], &tri_vindex[mesh->tri_offset], mesh->vert_offset);
777
778                         if(progress.get_cancel()) return;
779                 }
780
781                 /* vertex coordinates */
782                 progress.set_status("Updating Mesh", "Copying Mesh to device");
783
784                 device->tex_alloc("__tri_normal", dscene->tri_normal);
785                 device->tex_alloc("__tri_vnormal", dscene->tri_vnormal);
786                 device->tex_alloc("__tri_verts", dscene->tri_verts);
787                 device->tex_alloc("__tri_vindex", dscene->tri_vindex);
788         }
789
790         if(curve_size != 0) {
791                 progress.set_status("Updating Mesh", "Copying Strands to device");
792
793                 float4 *curve_keys = dscene->curve_keys.resize(curve_key_size);
794                 float4 *curves = dscene->curves.resize(curve_size);
795
796                 foreach(Mesh *mesh, scene->meshes) {
797                         mesh->pack_curves(scene, &curve_keys[mesh->curvekey_offset], &curves[mesh->curve_offset], mesh->curvekey_offset);
798                         if(progress.get_cancel()) return;
799                 }
800
801                 device->tex_alloc("__curve_keys", dscene->curve_keys);
802                 device->tex_alloc("__curves", dscene->curves);
803         }
804 }
805
806 void MeshManager::device_update_bvh(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
807 {
808         /* bvh build */
809         progress.set_status("Updating Scene BVH", "Building");
810
811         BVHParams bparams;
812         bparams.top_level = true;
813         bparams.use_qbvh = scene->params.use_qbvh;
814         bparams.use_spatial_split = scene->params.use_bvh_spatial_split;
815         bparams.use_cache = scene->params.use_bvh_cache;
816
817         delete bvh;
818         bvh = BVH::create(bparams, scene->objects);
819         bvh->build(progress);
820
821         if(progress.get_cancel()) return;
822
823         /* copy to device */
824         progress.set_status("Updating Scene BVH", "Copying BVH to device");
825
826         PackedBVH& pack = bvh->pack;
827
828         if(pack.nodes.size()) {
829                 dscene->bvh_nodes.reference((float4*)&pack.nodes[0], pack.nodes.size());
830                 device->tex_alloc("__bvh_nodes", dscene->bvh_nodes);
831         }
832         if(pack.object_node.size()) {
833                 dscene->object_node.reference((uint*)&pack.object_node[0], pack.object_node.size());
834                 device->tex_alloc("__object_node", dscene->object_node);
835         }
836         if(pack.tri_woop.size()) {
837                 dscene->tri_woop.reference(&pack.tri_woop[0], pack.tri_woop.size());
838                 device->tex_alloc("__tri_woop", dscene->tri_woop);
839         }
840         if(pack.prim_segment.size()) {
841                 dscene->prim_segment.reference((uint*)&pack.prim_segment[0], pack.prim_segment.size());
842                 device->tex_alloc("__prim_segment", dscene->prim_segment);
843         }
844         if(pack.prim_visibility.size()) {
845                 dscene->prim_visibility.reference((uint*)&pack.prim_visibility[0], pack.prim_visibility.size());
846                 device->tex_alloc("__prim_visibility", dscene->prim_visibility);
847         }
848         if(pack.prim_index.size()) {
849                 dscene->prim_index.reference((uint*)&pack.prim_index[0], pack.prim_index.size());
850                 device->tex_alloc("__prim_index", dscene->prim_index);
851         }
852         if(pack.prim_object.size()) {
853                 dscene->prim_object.reference((uint*)&pack.prim_object[0], pack.prim_object.size());
854                 device->tex_alloc("__prim_object", dscene->prim_object);
855         }
856
857         dscene->data.bvh.root = pack.root_index;
858 }
859
860 void MeshManager::device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
861 {
862         if(!need_update)
863                 return;
864
865         /* update normals */
866         foreach(Mesh *mesh, scene->meshes) {
867                 foreach(uint shader, mesh->used_shaders)
868                         if(scene->shaders[shader]->need_update_attributes)
869                                 mesh->need_update = true;
870
871                 if(mesh->need_update) {
872                         mesh->add_face_normals();
873                         mesh->add_vertex_normals();
874
875                         if(progress.get_cancel()) return;
876                 }
877         }
878
879         /* device update */
880         device_free(device, dscene);
881
882         device_update_mesh(device, dscene, scene, progress);
883         if(progress.get_cancel()) return;
884
885         device_update_attributes(device, dscene, scene, progress);
886         if(progress.get_cancel()) return;
887
888         /* update displacement */
889         bool displacement_done = false;
890
891         foreach(Mesh *mesh, scene->meshes)
892                 if(mesh->need_update && displace(device, dscene, scene, mesh, progress))
893                         displacement_done = true;
894
895         /* todo: properly handle cancel halfway displacement */
896         if(progress.get_cancel()) return;
897
898         /* device re-update after displacement */
899         if(displacement_done) {
900                 device_free(device, dscene);
901
902                 device_update_mesh(device, dscene, scene, progress);
903                 if(progress.get_cancel()) return;
904
905                 device_update_attributes(device, dscene, scene, progress);
906                 if(progress.get_cancel()) return;
907         }
908
909         /* update bvh */
910         size_t i = 0, num_bvh = 0;
911
912         foreach(Mesh *mesh, scene->meshes)
913                 if(mesh->need_update && !mesh->transform_applied)
914                         num_bvh++;
915
916         TaskPool pool;
917
918         foreach(Mesh *mesh, scene->meshes) {
919                 if(mesh->need_update) {
920                         pool.push(function_bind(&Mesh::compute_bvh, mesh, &scene->params, &progress, i, num_bvh));
921                         i++;
922                 }
923         }
924
925         pool.wait_work();
926         
927         foreach(Shader *shader, scene->shaders)
928                 shader->need_update_attributes = false;
929
930         float shuttertime = scene->camera->shuttertime;
931 #ifdef __OBJECT_MOTION__
932         Scene::MotionType need_motion = scene->need_motion(device->info.advanced_shading);
933         bool motion_blur = need_motion == Scene::MOTION_BLUR;
934 #else
935         bool motion_blur = false;
936 #endif
937
938         foreach(Object *object, scene->objects)
939                 object->compute_bounds(motion_blur, shuttertime);
940
941         if(progress.get_cancel()) return;
942
943         device_update_bvh(device, dscene, scene, progress);
944
945         need_update = false;
946 }
947
948 void MeshManager::device_free(Device *device, DeviceScene *dscene)
949 {
950         device->tex_free(dscene->bvh_nodes);
951         device->tex_free(dscene->object_node);
952         device->tex_free(dscene->tri_woop);
953         device->tex_free(dscene->prim_segment);
954         device->tex_free(dscene->prim_visibility);
955         device->tex_free(dscene->prim_index);
956         device->tex_free(dscene->prim_object);
957         device->tex_free(dscene->tri_normal);
958         device->tex_free(dscene->tri_vnormal);
959         device->tex_free(dscene->tri_vindex);
960         device->tex_free(dscene->tri_verts);
961         device->tex_free(dscene->curves);
962         device->tex_free(dscene->curve_keys);
963         device->tex_free(dscene->attributes_map);
964         device->tex_free(dscene->attributes_float);
965         device->tex_free(dscene->attributes_float3);
966
967         dscene->bvh_nodes.clear();
968         dscene->object_node.clear();
969         dscene->tri_woop.clear();
970         dscene->prim_segment.clear();
971         dscene->prim_visibility.clear();
972         dscene->prim_index.clear();
973         dscene->prim_object.clear();
974         dscene->tri_normal.clear();
975         dscene->tri_vnormal.clear();
976         dscene->tri_vindex.clear();
977         dscene->tri_verts.clear();
978         dscene->curves.clear();
979         dscene->curve_keys.clear();
980         dscene->attributes_map.clear();
981         dscene->attributes_float.clear();
982         dscene->attributes_float3.clear();
983
984 #ifdef WITH_OSL
985         OSLGlobals *og = (OSLGlobals*)device->osl_memory();
986
987         if(og) {
988                 og->object_name_map.clear();
989                 og->attribute_map.clear();
990                 og->object_names.clear();
991         }
992 #endif
993 }
994
995 void MeshManager::tag_update(Scene *scene)
996 {
997         need_update = true;
998         scene->object_manager->need_update = true;
999 }
1000
1001 bool Mesh::need_attribute(Scene *scene, AttributeStandard std)
1002 {
1003         if(std == ATTR_STD_NONE)
1004                 return false;
1005         
1006         if(scene->need_global_attribute(std))
1007                 return true;
1008
1009         foreach(uint shader, used_shaders)
1010                 if(scene->shaders[shader]->attributes.find(std))
1011                         return true;
1012         
1013         return false;
1014 }
1015
1016 bool Mesh::need_attribute(Scene *scene, ustring name)
1017 {
1018         if(name == ustring())
1019                 return false;
1020
1021         foreach(uint shader, used_shaders)
1022                 if(scene->shaders[shader]->attributes.find(name))
1023                         return true;
1024         
1025         return false;
1026 }
1027
1028 CCL_NAMESPACE_END
1029