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