Merge branch 'master' into blender2.8
[blender.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/bvh.h"
18 #include "bvh/bvh_build.h"
19
20 #include "render/camera.h"
21 #include "render/curves.h"
22 #include "device/device.h"
23 #include "render/graph.h"
24 #include "render/shader.h"
25 #include "render/light.h"
26 #include "render/mesh.h"
27 #include "render/nodes.h"
28 #include "render/object.h"
29 #include "render/scene.h"
30 #include "render/stats.h"
31
32 #include "kernel/osl/osl_globals.h"
33
34 #include "subd/subd_split.h"
35 #include "subd/subd_patch_table.h"
36
37 #include "util/util_foreach.h"
38 #include "util/util_logging.h"
39 #include "util/util_progress.h"
40 #include "util/util_set.h"
41
42 #ifdef WITH_EMBREE
43 #  include "bvh/bvh_embree.h"
44 #endif
45
46 CCL_NAMESPACE_BEGIN
47
48 /* Triangle */
49
50 void Mesh::Triangle::bounds_grow(const float3 *verts, BoundBox& bounds) const
51 {
52         bounds.grow(verts[v[0]]);
53         bounds.grow(verts[v[1]]);
54         bounds.grow(verts[v[2]]);
55 }
56
57 void Mesh::Triangle::motion_verts(const float3 *verts,
58                                   const float3 *vert_steps,
59                                   size_t num_verts,
60                                   size_t num_steps,
61                                   float time,
62                                   float3 r_verts[3]) const
63 {
64         /* Figure out which steps we need to fetch and their interpolation factor. */
65         const size_t max_step = num_steps - 1;
66         const size_t step = min((int)(time * max_step), max_step - 1);
67         const float t = time*max_step - step;
68         /* Fetch vertex coordinates. */
69         float3 curr_verts[3];
70         float3 next_verts[3];
71         verts_for_step(verts,
72                        vert_steps,
73                        num_verts,
74                        num_steps,
75                        step,
76                        curr_verts);
77         verts_for_step(verts,
78                        vert_steps,
79                        num_verts,
80                        num_steps,
81                        step + 1,
82                        next_verts);
83         /* Interpolate between steps. */
84         r_verts[0] = (1.0f - t)*curr_verts[0] + t*next_verts[0];
85         r_verts[1] = (1.0f - t)*curr_verts[1] + t*next_verts[1];
86         r_verts[2] = (1.0f - t)*curr_verts[2] + t*next_verts[2];
87 }
88
89 void Mesh::Triangle::verts_for_step(const float3 *verts,
90                                     const float3 *vert_steps,
91                                     size_t num_verts,
92                                     size_t num_steps,
93                                     size_t step,
94                                     float3 r_verts[3]) const
95 {
96         const size_t center_step = ((num_steps - 1) / 2);
97         if(step == center_step) {
98                 /* Center step: regular vertex location. */
99                 r_verts[0] = verts[v[0]];
100                 r_verts[1] = verts[v[1]];
101                 r_verts[2] = verts[v[2]];
102         }
103         else {
104                 /* Center step not stored in the attribute array array. */
105                 if(step > center_step) {
106                         step--;
107                 }
108                 size_t offset = step * num_verts;
109                 r_verts[0] = vert_steps[offset + v[0]];
110                 r_verts[1] = vert_steps[offset + v[1]];
111                 r_verts[2] = vert_steps[offset + v[2]];
112         }
113 }
114
115 float3 Mesh::Triangle::compute_normal(const float3 *verts) const
116 {
117         const float3& v0 = verts[v[0]];
118         const float3& v1 = verts[v[1]];
119         const float3& v2 = verts[v[2]];
120         const float3 norm = cross(v1 - v0, v2 - v0);
121         const float normlen = len(norm);
122         if(normlen == 0.0f) {
123                 return make_float3(1.0f, 0.0f, 0.0f);
124         }
125         return norm / normlen;
126 }
127
128 bool Mesh::Triangle::valid(const float3 *verts) const
129 {
130         return isfinite3_safe(verts[v[0]]) &&
131                isfinite3_safe(verts[v[1]]) &&
132                isfinite3_safe(verts[v[2]]);
133 }
134
135 /* Curve */
136
137 void Mesh::Curve::bounds_grow(const int k, const float3 *curve_keys, const float *curve_radius, BoundBox& bounds) const
138 {
139         float3 P[4];
140
141         P[0] = curve_keys[max(first_key + k - 1,first_key)];
142         P[1] = curve_keys[first_key + k];
143         P[2] = curve_keys[first_key + k + 1];
144         P[3] = curve_keys[min(first_key + k + 2, first_key + num_keys - 1)];
145
146         float3 lower;
147         float3 upper;
148
149         curvebounds(&lower.x, &upper.x, P, 0);
150         curvebounds(&lower.y, &upper.y, P, 1);
151         curvebounds(&lower.z, &upper.z, P, 2);
152
153         float mr = max(curve_radius[first_key + k], curve_radius[first_key + k + 1]);
154
155         bounds.grow(lower, mr);
156         bounds.grow(upper, mr);
157 }
158
159 void Mesh::Curve::bounds_grow(const int k,
160                               const float3 *curve_keys,
161                               const float *curve_radius,
162                               const Transform& aligned_space,
163                               BoundBox& bounds) const
164 {
165         float3 P[4];
166
167         P[0] = curve_keys[max(first_key + k - 1,first_key)];
168         P[1] = curve_keys[first_key + k];
169         P[2] = curve_keys[first_key + k + 1];
170         P[3] = curve_keys[min(first_key + k + 2, first_key + num_keys - 1)];
171
172         P[0] = transform_point(&aligned_space, P[0]);
173         P[1] = transform_point(&aligned_space, P[1]);
174         P[2] = transform_point(&aligned_space, P[2]);
175         P[3] = transform_point(&aligned_space, P[3]);
176
177         float3 lower;
178         float3 upper;
179
180         curvebounds(&lower.x, &upper.x, P, 0);
181         curvebounds(&lower.y, &upper.y, P, 1);
182         curvebounds(&lower.z, &upper.z, P, 2);
183
184         float mr = max(curve_radius[first_key + k], curve_radius[first_key + k + 1]);
185
186         bounds.grow(lower, mr);
187         bounds.grow(upper, mr);
188 }
189
190 void Mesh::Curve::bounds_grow(float4 keys[4], BoundBox& bounds) const
191 {
192         float3 P[4] = {
193                 float4_to_float3(keys[0]),
194                 float4_to_float3(keys[1]),
195                 float4_to_float3(keys[2]),
196                 float4_to_float3(keys[3]),
197         };
198
199         float3 lower;
200         float3 upper;
201
202         curvebounds(&lower.x, &upper.x, P, 0);
203         curvebounds(&lower.y, &upper.y, P, 1);
204         curvebounds(&lower.z, &upper.z, P, 2);
205
206         float mr = max(keys[1].w, keys[2].w);
207
208         bounds.grow(lower, mr);
209         bounds.grow(upper, mr);
210 }
211
212 void Mesh::Curve::motion_keys(const float3 *curve_keys,
213                               const float *curve_radius,
214                               const float3 *key_steps,
215                               size_t num_curve_keys,
216                               size_t num_steps,
217                               float time,
218                               size_t k0, size_t k1,
219                               float4 r_keys[2]) const
220 {
221         /* Figure out which steps we need to fetch and their interpolation factor. */
222         const size_t max_step = num_steps - 1;
223         const size_t step = min((int)(time * max_step), max_step - 1);
224         const float t = time*max_step - step;
225         /* Fetch vertex coordinates. */
226         float4 curr_keys[2];
227         float4 next_keys[2];
228         keys_for_step(curve_keys,
229                       curve_radius,
230                       key_steps,
231                       num_curve_keys,
232                       num_steps,
233                       step,
234                       k0, k1,
235                       curr_keys);
236         keys_for_step(curve_keys,
237                       curve_radius,
238                       key_steps,
239                       num_curve_keys,
240                       num_steps,
241                       step + 1,
242                       k0, k1,
243                       next_keys);
244         /* Interpolate between steps. */
245         r_keys[0] = (1.0f - t)*curr_keys[0] + t*next_keys[0];
246         r_keys[1] = (1.0f - t)*curr_keys[1] + t*next_keys[1];
247 }
248
249 void Mesh::Curve::cardinal_motion_keys(const float3 *curve_keys,
250                                        const float *curve_radius,
251                                        const float3 *key_steps,
252                                        size_t num_curve_keys,
253                                        size_t num_steps,
254                                        float time,
255                                        size_t k0, size_t k1,
256                                        size_t k2, size_t k3,
257                                        float4 r_keys[4]) const
258 {
259         /* Figure out which steps we need to fetch and their interpolation factor. */
260         const size_t max_step = num_steps - 1;
261         const size_t step = min((int)(time * max_step), max_step - 1);
262         const float t = time*max_step - step;
263         /* Fetch vertex coordinates. */
264         float4 curr_keys[4];
265         float4 next_keys[4];
266         cardinal_keys_for_step(curve_keys,
267                                curve_radius,
268                                key_steps,
269                                num_curve_keys,
270                                num_steps,
271                                step,
272                                k0, k1, k2, k3,
273                                curr_keys);
274         cardinal_keys_for_step(curve_keys,
275                                curve_radius,
276                                key_steps,
277                                num_curve_keys,
278                                num_steps,
279                                step + 1,
280                                k0, k1, k2, k3,
281                                next_keys);
282         /* Interpolate between steps. */
283         r_keys[0] = (1.0f - t)*curr_keys[0] + t*next_keys[0];
284         r_keys[1] = (1.0f - t)*curr_keys[1] + t*next_keys[1];
285         r_keys[2] = (1.0f - t)*curr_keys[2] + t*next_keys[2];
286         r_keys[3] = (1.0f - t)*curr_keys[3] + t*next_keys[3];
287 }
288
289 void Mesh::Curve::keys_for_step(const float3 *curve_keys,
290                                 const float *curve_radius,
291                                 const float3 *key_steps,
292                                 size_t num_curve_keys,
293                                 size_t num_steps,
294                                 size_t step,
295                                 size_t k0, size_t k1,
296                                 float4 r_keys[2]) const
297 {
298         k0 = max(k0, 0);
299         k1 = min(k1, num_keys - 1);
300         const size_t center_step = ((num_steps - 1) / 2);
301         if(step == center_step) {
302                 /* Center step: regular key location. */
303                 /* TODO(sergey): Consider adding make_float4(float3, float)
304                  * function.
305                  */
306                 r_keys[0] = make_float4(curve_keys[first_key + k0].x,
307                                         curve_keys[first_key + k0].y,
308                                         curve_keys[first_key + k0].z,
309                                         curve_radius[first_key + k0]);
310                 r_keys[1] = make_float4(curve_keys[first_key + k1].x,
311                                         curve_keys[first_key + k1].y,
312                                         curve_keys[first_key + k1].z,
313                                         curve_radius[first_key + k1]);
314         }
315         else {
316                 /* Center step is not stored in this array. */
317                 if(step > center_step) {
318                         step--;
319                 }
320                 const size_t offset = first_key + step * num_curve_keys;
321                 r_keys[0] = make_float4(key_steps[offset + k0].x,
322                                         key_steps[offset + k0].y,
323                                         key_steps[offset + k0].z,
324                                         curve_radius[first_key + k0]);
325                 r_keys[1] = make_float4(key_steps[offset + k1].x,
326                                         key_steps[offset + k1].y,
327                                         key_steps[offset + k1].z,
328                                         curve_radius[first_key + k1]);
329         }
330 }
331
332 void Mesh::Curve::cardinal_keys_for_step(const float3 *curve_keys,
333                                          const float *curve_radius,
334                                          const float3 *key_steps,
335                                          size_t num_curve_keys,
336                                          size_t num_steps,
337                                          size_t step,
338                                          size_t k0, size_t k1,
339                                          size_t k2, size_t k3,
340                                          float4 r_keys[4]) const
341 {
342         k0 = max(k0, 0);
343         k3 = min(k3, num_keys - 1);
344         const size_t center_step = ((num_steps - 1) / 2);
345         if(step == center_step) {
346                 /* Center step: regular key location. */
347                 r_keys[0] = make_float4(curve_keys[first_key + k0].x,
348                                         curve_keys[first_key + k0].y,
349                                         curve_keys[first_key + k0].z,
350                                         curve_radius[first_key + k0]);
351                 r_keys[1] = make_float4(curve_keys[first_key + k1].x,
352                                         curve_keys[first_key + k1].y,
353                                         curve_keys[first_key + k1].z,
354                                         curve_radius[first_key + k1]);
355                 r_keys[2] = make_float4(curve_keys[first_key + k2].x,
356                                         curve_keys[first_key + k2].y,
357                                         curve_keys[first_key + k2].z,
358                                         curve_radius[first_key + k2]);
359                 r_keys[3] = make_float4(curve_keys[first_key + k3].x,
360                                         curve_keys[first_key + k3].y,
361                                         curve_keys[first_key + k3].z,
362                                         curve_radius[first_key + k3]);
363         }
364         else {
365                 /* Center step is not stored in this array. */
366                 if(step > center_step) {
367                         step--;
368                 }
369                 const size_t offset = first_key + step * num_curve_keys;
370                 r_keys[0] = make_float4(key_steps[offset + k0].x,
371                                         key_steps[offset + k0].y,
372                                         key_steps[offset + k0].z,
373                                         curve_radius[first_key + k0]);
374                 r_keys[1] = make_float4(key_steps[offset + k1].x,
375                                         key_steps[offset + k1].y,
376                                         key_steps[offset + k1].z,
377                                         curve_radius[first_key + k1]);
378                 r_keys[2] = make_float4(key_steps[offset + k2].x,
379                                         key_steps[offset + k2].y,
380                                         key_steps[offset + k2].z,
381                                         curve_radius[first_key + k2]);
382                 r_keys[3] = make_float4(key_steps[offset + k3].x,
383                                         key_steps[offset + k3].y,
384                                         key_steps[offset + k3].z,
385                                         curve_radius[first_key + k3]);
386         }
387 }
388
389 /* SubdFace */
390
391 float3 Mesh::SubdFace::normal(const Mesh *mesh) const
392 {
393         float3 v0 = mesh->verts[mesh->subd_face_corners[start_corner+0]];
394         float3 v1 = mesh->verts[mesh->subd_face_corners[start_corner+1]];
395         float3 v2 = mesh->verts[mesh->subd_face_corners[start_corner+2]];
396
397         return safe_normalize(cross(v1 - v0, v2 - v0));
398 }
399
400 /* Mesh */
401
402 NODE_DEFINE(Mesh)
403 {
404         NodeType* type = NodeType::add("mesh", create);
405
406         SOCKET_UINT(motion_steps, "Motion Steps", 3);
407         SOCKET_BOOLEAN(use_motion_blur, "Use Motion Blur", false);
408
409         SOCKET_INT_ARRAY(triangles, "Triangles", array<int>());
410         SOCKET_POINT_ARRAY(verts, "Vertices", array<float3>());
411         SOCKET_INT_ARRAY(shader, "Shader", array<int>());
412         SOCKET_BOOLEAN_ARRAY(smooth, "Smooth", array<bool>());
413
414         SOCKET_POINT_ARRAY(curve_keys, "Curve Keys", array<float3>());
415         SOCKET_FLOAT_ARRAY(curve_radius, "Curve Radius", array<float>());
416         SOCKET_INT_ARRAY(curve_first_key, "Curve First Key", array<int>());
417         SOCKET_INT_ARRAY(curve_shader, "Curve Shader", array<int>());
418
419         return type;
420 }
421
422 Mesh::Mesh()
423 : Node(node_type)
424 {
425         need_update = true;
426         need_update_rebuild = false;
427         transform_applied = false;
428         transform_negative_scaled = false;
429         transform_normal = transform_identity();
430         bounds = BoundBox::empty;
431
432         bvh = NULL;
433
434         tri_offset = 0;
435         vert_offset = 0;
436
437         curve_offset = 0;
438         curvekey_offset = 0;
439
440         patch_offset = 0;
441         face_offset = 0;
442         corner_offset = 0;
443
444         attr_map_offset = 0;
445
446         num_subd_verts = 0;
447
448         attributes.triangle_mesh = this;
449         curve_attributes.curve_mesh = this;
450         subd_attributes.subd_mesh = this;
451
452         geometry_flags = GEOMETRY_NONE;
453
454         volume_isovalue = 0.001f;
455         has_volume = false;
456         has_surface_bssrdf = false;
457
458         num_ngons = 0;
459
460         subdivision_type = SUBDIVISION_NONE;
461         subd_params = NULL;
462
463         patch_table = NULL;
464 }
465
466 Mesh::~Mesh()
467 {
468         delete bvh;
469         delete patch_table;
470         delete subd_params;
471 }
472
473 void Mesh::resize_mesh(int numverts, int numtris)
474 {
475         verts.resize(numverts);
476         triangles.resize(numtris * 3);
477         shader.resize(numtris);
478         smooth.resize(numtris);
479
480         if(subd_faces.size()) {
481                 triangle_patch.resize(numtris);
482                 vert_patch_uv.resize(numverts);
483         }
484
485         attributes.resize();
486 }
487
488 void Mesh::reserve_mesh(int numverts, int numtris)
489 {
490         /* reserve space to add verts and triangles later */
491         verts.reserve(numverts);
492         triangles.reserve(numtris * 3);
493         shader.reserve(numtris);
494         smooth.reserve(numtris);
495
496         if(subd_faces.size()) {
497                 triangle_patch.reserve(numtris);
498                 vert_patch_uv.reserve(numverts);
499         }
500
501         attributes.resize(true);
502 }
503
504 void Mesh::resize_curves(int numcurves, int numkeys)
505 {
506         curve_keys.resize(numkeys);
507         curve_radius.resize(numkeys);
508         curve_first_key.resize(numcurves);
509         curve_shader.resize(numcurves);
510
511         curve_attributes.resize();
512 }
513
514 void Mesh::reserve_curves(int numcurves, int numkeys)
515 {
516         curve_keys.reserve(numkeys);
517         curve_radius.reserve(numkeys);
518         curve_first_key.reserve(numcurves);
519         curve_shader.reserve(numcurves);
520
521         curve_attributes.resize(true);
522 }
523
524 void Mesh::resize_subd_faces(int numfaces, int num_ngons_, int numcorners)
525 {
526         subd_faces.resize(numfaces);
527         subd_face_corners.resize(numcorners);
528         num_ngons = num_ngons_;
529
530         subd_attributes.resize();
531 }
532
533 void Mesh::reserve_subd_faces(int numfaces, int num_ngons_, int numcorners)
534 {
535         subd_faces.reserve(numfaces);
536         subd_face_corners.reserve(numcorners);
537         num_ngons = num_ngons_;
538
539         subd_attributes.resize(true);
540 }
541
542 void Mesh::clear(bool preserve_voxel_data)
543 {
544         /* clear all verts and triangles */
545         verts.clear();
546         triangles.clear();
547         shader.clear();
548         smooth.clear();
549
550         triangle_patch.clear();
551         vert_patch_uv.clear();
552
553         curve_keys.clear();
554         curve_radius.clear();
555         curve_first_key.clear();
556         curve_shader.clear();
557
558         subd_faces.clear();
559         subd_face_corners.clear();
560
561         num_subd_verts = 0;
562
563         subd_creases.clear();
564
565         curve_attributes.clear();
566         subd_attributes.clear();
567         attributes.clear(preserve_voxel_data);
568
569         used_shaders.clear();
570
571         if(!preserve_voxel_data) {
572                 geometry_flags = GEOMETRY_NONE;
573         }
574
575         transform_applied = false;
576         transform_negative_scaled = false;
577         transform_normal = transform_identity();
578
579         delete patch_table;
580         patch_table = NULL;
581 }
582
583 int Mesh::split_vertex(int vertex)
584 {
585         /* copy vertex location and vertex attributes */
586         add_vertex_slow(verts[vertex]);
587
588         foreach(Attribute& attr, attributes.attributes) {
589                 if(attr.element == ATTR_ELEMENT_VERTEX) {
590                         array<char> tmp(attr.data_sizeof());
591                         memcpy(tmp.data(), attr.data() + tmp.size()*vertex, tmp.size());
592                         attr.add(tmp.data());
593                 }
594         }
595
596         foreach(Attribute& attr, subd_attributes.attributes) {
597                 if(attr.element == ATTR_ELEMENT_VERTEX) {
598                         array<char> tmp(attr.data_sizeof());
599                         memcpy(tmp.data(), attr.data() + tmp.size()*vertex, tmp.size());
600                         attr.add(tmp.data());
601                 }
602         }
603
604         return verts.size() - 1;
605 }
606
607 void Mesh::add_vertex(float3 P)
608 {
609         verts.push_back_reserved(P);
610
611         if(subd_faces.size()) {
612                 vert_patch_uv.push_back_reserved(make_float2(0.0f, 0.0f));
613         }
614 }
615
616 void Mesh::add_vertex_slow(float3 P)
617 {
618         verts.push_back_slow(P);
619
620         if(subd_faces.size()) {
621                 vert_patch_uv.push_back_slow(make_float2(0.0f, 0.0f));
622         }
623 }
624
625 void Mesh::add_triangle(int v0, int v1, int v2, int shader_, bool smooth_)
626 {
627         triangles.push_back_reserved(v0);
628         triangles.push_back_reserved(v1);
629         triangles.push_back_reserved(v2);
630         shader.push_back_reserved(shader_);
631         smooth.push_back_reserved(smooth_);
632
633         if(subd_faces.size()) {
634                 triangle_patch.push_back_reserved(-1);
635         }
636 }
637
638 void Mesh::add_curve_key(float3 co, float radius)
639 {
640         curve_keys.push_back_reserved(co);
641         curve_radius.push_back_reserved(radius);
642 }
643
644 void Mesh::add_curve(int first_key, int shader)
645 {
646         curve_first_key.push_back_reserved(first_key);
647         curve_shader.push_back_reserved(shader);
648 }
649
650 void Mesh::add_subd_face(int* corners, int num_corners, int shader_, bool smooth_)
651 {
652         int start_corner = subd_face_corners.size();
653
654         for(int i = 0; i < num_corners; i++) {
655                 subd_face_corners.push_back_reserved(corners[i]);
656         }
657
658         int ptex_offset = 0;
659
660         if(subd_faces.size()) {
661                 SubdFace& s = subd_faces[subd_faces.size()-1];
662                 ptex_offset = s.ptex_offset + s.num_ptex_faces();
663         }
664
665         SubdFace face = {start_corner, num_corners, shader_, smooth_, ptex_offset};
666         subd_faces.push_back_reserved(face);
667 }
668
669 void Mesh::compute_bounds()
670 {
671         BoundBox bnds = BoundBox::empty;
672         size_t verts_size = verts.size();
673         size_t curve_keys_size = curve_keys.size();
674
675         if(verts_size + curve_keys_size > 0) {
676                 for(size_t i = 0; i < verts_size; i++)
677                         bnds.grow(verts[i]);
678
679                 for(size_t i = 0; i < curve_keys_size; i++)
680                         bnds.grow(curve_keys[i], curve_radius[i]);
681
682                 Attribute *attr = attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
683                 if(use_motion_blur && attr) {
684                         size_t steps_size = verts.size() * (motion_steps - 1);
685                         float3 *vert_steps = attr->data_float3();
686
687                         for(size_t i = 0; i < steps_size; i++)
688                                 bnds.grow(vert_steps[i]);
689                 }
690
691                 Attribute *curve_attr = curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
692                 if(use_motion_blur && curve_attr) {
693                         size_t steps_size = curve_keys.size() * (motion_steps - 1);
694                         float3 *key_steps = curve_attr->data_float3();
695
696                         for(size_t i = 0; i < steps_size; i++)
697                                 bnds.grow(key_steps[i]);
698                 }
699
700                 if(!bnds.valid()) {
701                         bnds = BoundBox::empty;
702
703                         /* skip nan or inf coordinates */
704                         for(size_t i = 0; i < verts_size; i++)
705                                 bnds.grow_safe(verts[i]);
706
707                         for(size_t i = 0; i < curve_keys_size; i++)
708                                 bnds.grow_safe(curve_keys[i], curve_radius[i]);
709
710                         if(use_motion_blur && attr) {
711                                 size_t steps_size = verts.size() * (motion_steps - 1);
712                                 float3 *vert_steps = attr->data_float3();
713
714                                 for(size_t i = 0; i < steps_size; i++)
715                                         bnds.grow_safe(vert_steps[i]);
716                         }
717
718                         if(use_motion_blur && curve_attr) {
719                                 size_t steps_size = curve_keys.size() * (motion_steps - 1);
720                                 float3 *key_steps = curve_attr->data_float3();
721
722                                 for(size_t i = 0; i < steps_size; i++)
723                                         bnds.grow_safe(key_steps[i]);
724                         }
725                 }
726         }
727
728         if(!bnds.valid()) {
729                 /* empty mesh */
730                 bnds.grow(make_float3(0.0f, 0.0f, 0.0f));
731         }
732
733         bounds = bnds;
734 }
735
736 void Mesh::add_face_normals()
737 {
738         /* don't compute if already there */
739         if(attributes.find(ATTR_STD_FACE_NORMAL))
740                 return;
741
742         /* get attributes */
743         Attribute *attr_fN = attributes.add(ATTR_STD_FACE_NORMAL);
744         float3 *fN = attr_fN->data_float3();
745
746         /* compute face normals */
747         size_t triangles_size = num_triangles();
748
749         if(triangles_size) {
750                 float3 *verts_ptr = verts.data();
751
752                 for(size_t i = 0; i < triangles_size; i++) {
753                         fN[i] = get_triangle(i).compute_normal(verts_ptr);
754                 }
755         }
756
757         /* expected to be in local space */
758         if(transform_applied) {
759                 Transform ntfm = transform_inverse(transform_normal);
760
761                 for(size_t i = 0; i < triangles_size; i++)
762                         fN[i] = normalize(transform_direction(&ntfm, fN[i]));
763         }
764 }
765
766 void Mesh::add_vertex_normals()
767 {
768         bool flip = transform_negative_scaled;
769         size_t verts_size = verts.size();
770         size_t triangles_size = num_triangles();
771
772         /* static vertex normals */
773         if(!attributes.find(ATTR_STD_VERTEX_NORMAL) && triangles_size) {
774                 /* get attributes */
775                 Attribute *attr_fN = attributes.find(ATTR_STD_FACE_NORMAL);
776                 Attribute *attr_vN = attributes.add(ATTR_STD_VERTEX_NORMAL);
777
778                 float3 *fN = attr_fN->data_float3();
779                 float3 *vN = attr_vN->data_float3();
780
781                 /* compute vertex normals */
782                 memset(vN, 0, verts.size()*sizeof(float3));
783
784                 for(size_t i = 0; i < triangles_size; i++) {
785                         for(size_t j = 0; j < 3; j++) {
786                                 vN[get_triangle(i).v[j]] += fN[i];
787                         }
788                 }
789
790                 for(size_t i = 0; i < verts_size; i++) {
791                         vN[i] = normalize(vN[i]);
792                         if(flip) {
793                                 vN[i] = -vN[i];
794                         }
795                 }
796         }
797
798         /* motion vertex normals */
799         Attribute *attr_mP = attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
800         Attribute *attr_mN = attributes.find(ATTR_STD_MOTION_VERTEX_NORMAL);
801
802         if(has_motion_blur() && attr_mP && !attr_mN && triangles_size) {
803                 /* create attribute */
804                 attr_mN = attributes.add(ATTR_STD_MOTION_VERTEX_NORMAL);
805
806                 for(int step = 0; step < motion_steps - 1; step++) {
807                         float3 *mP = attr_mP->data_float3() + step*verts.size();
808                         float3 *mN = attr_mN->data_float3() + step*verts.size();
809
810                         /* compute */
811                         memset(mN, 0, verts.size()*sizeof(float3));
812
813                         for(size_t i = 0; i < triangles_size; i++) {
814                                 for(size_t j = 0; j < 3; j++) {
815                                         float3 fN = get_triangle(i).compute_normal(mP);
816                                         mN[get_triangle(i).v[j]] += fN;
817                                 }
818                         }
819
820                         for(size_t i = 0; i < verts_size; i++) {
821                                 mN[i] = normalize(mN[i]);
822                                 if(flip) {
823                                         mN[i] = -mN[i];
824                                 }
825                         }
826                 }
827         }
828
829         /* subd vertex normals */
830         if(!subd_attributes.find(ATTR_STD_VERTEX_NORMAL) && subd_faces.size()) {
831                 /* get attributes */
832                 Attribute *attr_vN = subd_attributes.add(ATTR_STD_VERTEX_NORMAL);
833                 float3 *vN = attr_vN->data_float3();
834
835                 /* compute vertex normals */
836                 memset(vN, 0, verts.size()*sizeof(float3));
837
838                 for(size_t i = 0; i < subd_faces.size(); i++) {
839                         SubdFace& face = subd_faces[i];
840                         float3 fN = face.normal(this);
841
842                         for(size_t j = 0; j < face.num_corners; j++) {
843                                 size_t corner = subd_face_corners[face.start_corner+j];
844                                 vN[corner] += fN;
845                         }
846                 }
847
848                 for(size_t i = 0; i < verts_size; i++) {
849                         vN[i] = normalize(vN[i]);
850                         if(flip) {
851                                 vN[i] = -vN[i];
852                         }
853                 }
854         }
855 }
856
857 void Mesh::add_undisplaced()
858 {
859         AttributeSet& attrs = (subdivision_type == SUBDIVISION_NONE) ? attributes : subd_attributes;
860
861         /* don't compute if already there */
862         if(attrs.find(ATTR_STD_POSITION_UNDISPLACED)) {
863                 return;
864         }
865
866         /* get attribute */
867         Attribute *attr = attrs.add(ATTR_STD_POSITION_UNDISPLACED);
868         attr->flags |= ATTR_SUBDIVIDED;
869
870         float3 *data = attr->data_float3();
871
872         /* copy verts */
873         size_t size = attr->buffer_size(this, (subdivision_type == SUBDIVISION_NONE) ? ATTR_PRIM_TRIANGLE : ATTR_PRIM_SUBD);
874
875         /* Center points for ngons aren't stored in Mesh::verts but are included in size since they will be
876          * calculated later, we subtract them from size here so we don't have an overflow while copying.
877          */
878         size -= num_ngons * attr->data_sizeof();
879
880         if(size) {
881                 memcpy(data, verts.data(), size);
882         }
883 }
884
885 void Mesh::pack_shaders(Scene *scene, uint *tri_shader)
886 {
887         uint shader_id = 0;
888         uint last_shader = -1;
889         bool last_smooth = false;
890
891         size_t triangles_size = num_triangles();
892         int *shader_ptr = shader.data();
893
894         for(size_t i = 0; i < triangles_size; i++) {
895                 if(shader_ptr[i] != last_shader || last_smooth != smooth[i]) {
896                         last_shader = shader_ptr[i];
897                         last_smooth = smooth[i];
898                         Shader *shader = (last_shader < used_shaders.size()) ?
899                                 used_shaders[last_shader] : scene->default_surface;
900                         shader_id = scene->shader_manager->get_shader_id(shader, last_smooth);
901                 }
902
903                 tri_shader[i] = shader_id;
904         }
905 }
906
907 void Mesh::pack_normals(float4 *vnormal)
908 {
909         Attribute *attr_vN = attributes.find(ATTR_STD_VERTEX_NORMAL);
910         if(attr_vN == NULL) {
911                 /* Happens on objects with just hair. */
912                 return;
913         }
914
915         bool do_transform = transform_applied;
916         Transform ntfm = transform_normal;
917
918         float3 *vN = attr_vN->data_float3();
919         size_t verts_size = verts.size();
920
921         for(size_t i = 0; i < verts_size; i++) {
922                 float3 vNi = vN[i];
923
924                 if(do_transform)
925                         vNi = safe_normalize(transform_direction(&ntfm, vNi));
926
927                 vnormal[i] = make_float4(vNi.x, vNi.y, vNi.z, 0.0f);
928         }
929 }
930
931 void Mesh::pack_verts(const vector<uint>& tri_prim_index,
932                       uint4 *tri_vindex,
933                       uint *tri_patch,
934                       float2 *tri_patch_uv,
935                       size_t vert_offset,
936                       size_t tri_offset)
937 {
938         size_t verts_size = verts.size();
939
940         if(verts_size && subd_faces.size()) {
941                 float2 *vert_patch_uv_ptr = vert_patch_uv.data();
942
943                 for(size_t i = 0; i < verts_size; i++) {
944                         tri_patch_uv[i] = vert_patch_uv_ptr[i];
945                 }
946         }
947
948         size_t triangles_size = num_triangles();
949
950         for(size_t i = 0; i < triangles_size; i++) {
951                 Triangle t = get_triangle(i);
952                 tri_vindex[i] = make_uint4(t.v[0] + vert_offset,
953                                            t.v[1] + vert_offset,
954                                            t.v[2] + vert_offset,
955                                            tri_prim_index[i + tri_offset]);
956
957                 tri_patch[i] = (!subd_faces.size()) ? -1 : (triangle_patch[i]*8 + patch_offset);
958         }
959 }
960
961 void Mesh::pack_curves(Scene *scene, float4 *curve_key_co, float4 *curve_data, size_t curvekey_offset)
962 {
963         size_t curve_keys_size = curve_keys.size();
964
965         /* pack curve keys */
966         if(curve_keys_size) {
967                 float3 *keys_ptr = curve_keys.data();
968                 float *radius_ptr = curve_radius.data();
969
970                 for(size_t i = 0; i < curve_keys_size; i++)
971                         curve_key_co[i] = make_float4(keys_ptr[i].x, keys_ptr[i].y, keys_ptr[i].z, radius_ptr[i]);
972         }
973
974         /* pack curve segments */
975         size_t curve_num = num_curves();
976
977         for(size_t i = 0; i < curve_num; i++) {
978                 Curve curve = get_curve(i);
979                 int shader_id = curve_shader[i];
980                 Shader *shader = (shader_id < used_shaders.size()) ?
981                         used_shaders[shader_id] : scene->default_surface;
982                 shader_id = scene->shader_manager->get_shader_id(shader, false);
983
984                 curve_data[i] = make_float4(
985                         __int_as_float(curve.first_key + curvekey_offset),
986                         __int_as_float(curve.num_keys),
987                         __int_as_float(shader_id),
988                         0.0f);
989         }
990 }
991
992 void Mesh::pack_patches(uint *patch_data, uint vert_offset, uint face_offset, uint corner_offset)
993 {
994         size_t num_faces = subd_faces.size();
995         int ngons = 0;
996
997         for(size_t f = 0; f < num_faces; f++) {
998                 SubdFace face = subd_faces[f];
999
1000                 if(face.is_quad()) {
1001                         int c[4];
1002                         memcpy(c, &subd_face_corners[face.start_corner], sizeof(int)*4);
1003
1004                         *(patch_data++) = c[0] + vert_offset;
1005                         *(patch_data++) = c[1] + vert_offset;
1006                         *(patch_data++) = c[2] + vert_offset;
1007                         *(patch_data++) = c[3] + vert_offset;
1008
1009                         *(patch_data++) = f+face_offset;
1010                         *(patch_data++) = face.num_corners;
1011                         *(patch_data++) = face.start_corner + corner_offset;
1012                         *(patch_data++) = 0;
1013                 }
1014                 else {
1015                         for(int i = 0; i < face.num_corners; i++) {
1016                                 int c[4];
1017                                 c[0] = subd_face_corners[face.start_corner + mod(i + 0, face.num_corners)];
1018                                 c[1] = subd_face_corners[face.start_corner + mod(i + 1, face.num_corners)];
1019                                 c[2] = verts.size() - num_subd_verts + ngons;
1020                                 c[3] = subd_face_corners[face.start_corner + mod(i - 1, face.num_corners)];
1021
1022                                 *(patch_data++) = c[0] + vert_offset;
1023                                 *(patch_data++) = c[1] + vert_offset;
1024                                 *(patch_data++) = c[2] + vert_offset;
1025                                 *(patch_data++) = c[3] + vert_offset;
1026
1027                                 *(patch_data++) = f+face_offset;
1028                                 *(patch_data++) = face.num_corners | (i << 16);
1029                                 *(patch_data++) = face.start_corner + corner_offset;
1030                                 *(patch_data++) = subd_face_corners.size() + ngons + corner_offset;
1031                         }
1032
1033                         ngons++;
1034                 }
1035         }
1036 }
1037
1038 void Mesh::compute_bvh(Device *device,
1039                        DeviceScene *dscene,
1040                        SceneParams *params,
1041                        Progress *progress,
1042                        int n,
1043                        int total)
1044 {
1045         if(progress->get_cancel())
1046                 return;
1047
1048         compute_bounds();
1049
1050         if(need_build_bvh()) {
1051                 string msg = "Updating Mesh BVH ";
1052                 if(name == "")
1053                         msg += string_printf("%u/%u", (uint)(n+1), (uint)total);
1054                 else
1055                         msg += string_printf("%s %u/%u", name.c_str(), (uint)(n+1), (uint)total);
1056
1057                 Object object;
1058                 object.mesh = this;
1059
1060                 vector<Object*> objects;
1061                 objects.push_back(&object);
1062
1063                 if(bvh && !need_update_rebuild) {
1064                         progress->set_status(msg, "Refitting BVH");
1065                         bvh->objects = objects;
1066                         bvh->refit(*progress);
1067                 }
1068                 else {
1069                         progress->set_status(msg, "Building BVH");
1070
1071                         BVHParams bparams;
1072                         bparams.use_spatial_split = params->use_bvh_spatial_split;
1073                         bparams.bvh_layout = BVHParams::best_bvh_layout(
1074                                 params->bvh_layout,
1075                                 device->get_bvh_layout_mask());
1076                         bparams.use_unaligned_nodes = dscene->data.bvh.have_curves &&
1077                                                       params->use_bvh_unaligned_nodes;
1078                         bparams.num_motion_triangle_steps = params->num_bvh_time_steps;
1079                         bparams.num_motion_curve_steps = params->num_bvh_time_steps;
1080                         bparams.bvh_type = params->bvh_type;
1081                         bparams.curve_flags = dscene->data.curve.curveflags;
1082                         bparams.curve_subdivisions = dscene->data.curve.subdivisions;
1083
1084                         delete bvh;
1085                         bvh = BVH::create(bparams, objects);
1086                         MEM_GUARDED_CALL(progress, bvh->build, *progress);
1087                 }
1088         }
1089
1090         need_update = false;
1091         need_update_rebuild = false;
1092 }
1093
1094 void Mesh::tag_update(Scene *scene, bool rebuild)
1095 {
1096         need_update = true;
1097
1098         if(rebuild) {
1099                 need_update_rebuild = true;
1100                 scene->light_manager->need_update = true;
1101         }
1102         else {
1103                 foreach(Shader *shader, used_shaders)
1104                         if(shader->has_surface_emission)
1105                                 scene->light_manager->need_update = true;
1106         }
1107
1108         scene->mesh_manager->need_update = true;
1109         scene->object_manager->need_update = true;
1110 }
1111
1112 bool Mesh::has_motion_blur() const
1113 {
1114         return (use_motion_blur &&
1115                 (attributes.find(ATTR_STD_MOTION_VERTEX_POSITION) ||
1116                  curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION)));
1117 }
1118
1119 bool Mesh::has_true_displacement() const
1120 {
1121         foreach(Shader *shader, used_shaders) {
1122                 if(shader->has_displacement && shader->displacement_method != DISPLACE_BUMP) {
1123                         return true;
1124                 }
1125         }
1126
1127         return false;
1128 }
1129
1130 float Mesh::motion_time(int step) const
1131 {
1132         return (motion_steps > 1) ? 2.0f * step / (motion_steps - 1) - 1.0f : 0.0f;
1133 }
1134
1135 int Mesh::motion_step(float time) const
1136 {
1137         if(motion_steps > 1) {
1138                 int attr_step = 0;
1139
1140                 for(int step = 0; step < motion_steps; step++) {
1141                         float step_time = motion_time(step);
1142                         if(step_time == time) {
1143                                 return attr_step;
1144                         }
1145
1146                         /* Center step is stored in a separate attribute. */
1147                         if(step != motion_steps / 2) {
1148                                 attr_step++;
1149                         }
1150                 }
1151         }
1152
1153         return -1;
1154 }
1155
1156 bool Mesh::need_build_bvh() const
1157 {
1158         return !transform_applied || has_surface_bssrdf;
1159 }
1160
1161 bool Mesh::is_instanced() const
1162 {
1163         /* Currently we treat subsurface objects as instanced.
1164          *
1165          * While it might be not very optimal for ray traversal, it avoids having
1166          * duplicated BVH in the memory, saving quite some space.
1167          */
1168         return !transform_applied || has_surface_bssrdf;
1169 }
1170
1171 /* Mesh Manager */
1172
1173 MeshManager::MeshManager()
1174 {
1175         need_update = true;
1176         need_flags_update = true;
1177 }
1178
1179 MeshManager::~MeshManager()
1180 {
1181 }
1182
1183 void MeshManager::update_osl_attributes(Device *device, Scene *scene, vector<AttributeRequestSet>& mesh_attributes)
1184 {
1185 #ifdef WITH_OSL
1186         /* for OSL, a hash map is used to lookup the attribute by name. */
1187         OSLGlobals *og = (OSLGlobals*)device->osl_memory();
1188
1189         og->object_name_map.clear();
1190         og->attribute_map.clear();
1191         og->object_names.clear();
1192
1193         og->attribute_map.resize(scene->objects.size()*ATTR_PRIM_TYPES);
1194
1195         for(size_t i = 0; i < scene->objects.size(); i++) {
1196                 /* set object name to object index map */
1197                 Object *object = scene->objects[i];
1198                 og->object_name_map[object->name] = i;
1199                 og->object_names.push_back(object->name);
1200
1201                 /* set object attributes */
1202                 foreach(ParamValue& attr, object->attributes) {
1203                         OSLGlobals::Attribute osl_attr;
1204
1205                         osl_attr.type = attr.type();
1206                         osl_attr.desc.element = ATTR_ELEMENT_OBJECT;
1207                         osl_attr.value = attr;
1208                         osl_attr.desc.offset = 0;
1209                         osl_attr.desc.flags = 0;
1210
1211                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_TRIANGLE][attr.name()] = osl_attr;
1212                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][attr.name()] = osl_attr;
1213                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_SUBD][attr.name()] = osl_attr;
1214                 }
1215
1216                 /* find mesh attributes */
1217                 size_t j;
1218
1219                 for(j = 0; j < scene->meshes.size(); j++)
1220                         if(scene->meshes[j] == object->mesh)
1221                                 break;
1222
1223                 AttributeRequestSet& attributes = mesh_attributes[j];
1224
1225                 /* set object attributes */
1226                 foreach(AttributeRequest& req, attributes.requests) {
1227                         OSLGlobals::Attribute osl_attr;
1228
1229                         if(req.triangle_desc.element != ATTR_ELEMENT_NONE) {
1230                                 osl_attr.desc = req.triangle_desc;
1231
1232                                 if(req.triangle_type == TypeDesc::TypeFloat)
1233                                         osl_attr.type = TypeDesc::TypeFloat;
1234                                 else if(req.triangle_type == TypeDesc::TypeMatrix)
1235                                         osl_attr.type = TypeDesc::TypeMatrix;
1236                                 else
1237                                         osl_attr.type = TypeDesc::TypeColor;
1238
1239                                 if(req.std != ATTR_STD_NONE) {
1240                                         /* if standard attribute, add lookup by geom: name convention */
1241                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
1242                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_TRIANGLE][stdname] = osl_attr;
1243                                 }
1244                                 else if(req.name != ustring()) {
1245                                         /* add lookup by mesh attribute name */
1246                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_TRIANGLE][req.name] = osl_attr;
1247                                 }
1248                         }
1249
1250                         if(req.curve_desc.element != ATTR_ELEMENT_NONE) {
1251                                 osl_attr.desc = req.curve_desc;
1252
1253                                 if(req.curve_type == TypeDesc::TypeFloat)
1254                                         osl_attr.type = TypeDesc::TypeFloat;
1255                                 else if(req.curve_type == TypeDesc::TypeMatrix)
1256                                         osl_attr.type = TypeDesc::TypeMatrix;
1257                                 else
1258                                         osl_attr.type = TypeDesc::TypeColor;
1259
1260                                 if(req.std != ATTR_STD_NONE) {
1261                                         /* if standard attribute, add lookup by geom: name convention */
1262                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
1263                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][stdname] = osl_attr;
1264                                 }
1265                                 else if(req.name != ustring()) {
1266                                         /* add lookup by mesh attribute name */
1267                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][req.name] = osl_attr;
1268                                 }
1269                         }
1270
1271                         if(req.subd_desc.element != ATTR_ELEMENT_NONE) {
1272                                 osl_attr.desc = req.subd_desc;
1273
1274                                 if(req.subd_type == TypeDesc::TypeFloat)
1275                                         osl_attr.type = TypeDesc::TypeFloat;
1276                                 else if(req.subd_type == TypeDesc::TypeMatrix)
1277                                         osl_attr.type = TypeDesc::TypeMatrix;
1278                                 else
1279                                         osl_attr.type = TypeDesc::TypeColor;
1280
1281                                 if(req.std != ATTR_STD_NONE) {
1282                                         /* if standard attribute, add lookup by geom: name convention */
1283                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
1284                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_SUBD][stdname] = osl_attr;
1285                                 }
1286                                 else if(req.name != ustring()) {
1287                                         /* add lookup by mesh attribute name */
1288                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_SUBD][req.name] = osl_attr;
1289                                 }
1290                         }
1291                 }
1292         }
1293 #else
1294         (void) device;
1295         (void) scene;
1296         (void) mesh_attributes;
1297 #endif
1298 }
1299
1300 void MeshManager::update_svm_attributes(Device *, DeviceScene *dscene, Scene *scene, vector<AttributeRequestSet>& mesh_attributes)
1301 {
1302         /* for SVM, the attributes_map table is used to lookup the offset of an
1303          * attribute, based on a unique shader attribute id. */
1304
1305         /* compute array stride */
1306         int attr_map_size = 0;
1307
1308         for(size_t i = 0; i < scene->meshes.size(); i++) {
1309                 Mesh *mesh = scene->meshes[i];
1310                 mesh->attr_map_offset = attr_map_size;
1311                 attr_map_size += (mesh_attributes[i].size() + 1)*ATTR_PRIM_TYPES;
1312         }
1313
1314         if(attr_map_size == 0)
1315                 return;
1316
1317         /* create attribute map */
1318         uint4 *attr_map = dscene->attributes_map.alloc(attr_map_size);
1319         memset(attr_map, 0, dscene->attributes_map.size()*sizeof(uint));
1320
1321         for(size_t i = 0; i < scene->meshes.size(); i++) {
1322                 Mesh *mesh = scene->meshes[i];
1323                 AttributeRequestSet& attributes = mesh_attributes[i];
1324
1325                 /* set object attributes */
1326                 int index = mesh->attr_map_offset;
1327
1328                 foreach(AttributeRequest& req, attributes.requests) {
1329                         uint id;
1330
1331                         if(req.std == ATTR_STD_NONE)
1332                                 id = scene->shader_manager->get_attribute_id(req.name);
1333                         else
1334                                 id = scene->shader_manager->get_attribute_id(req.std);
1335
1336                         if(mesh->num_triangles()) {
1337                                 attr_map[index].x = id;
1338                                 attr_map[index].y = req.triangle_desc.element;
1339                                 attr_map[index].z = as_uint(req.triangle_desc.offset);
1340
1341                                 if(req.triangle_type == TypeDesc::TypeFloat)
1342                                         attr_map[index].w = NODE_ATTR_FLOAT;
1343                                 else if(req.triangle_type == TypeDesc::TypeMatrix)
1344                                         attr_map[index].w = NODE_ATTR_MATRIX;
1345                                 else
1346                                         attr_map[index].w = NODE_ATTR_FLOAT3;
1347
1348                                 attr_map[index].w |= req.triangle_desc.flags << 8;
1349                         }
1350
1351                         index++;
1352
1353                         if(mesh->num_curves()) {
1354                                 attr_map[index].x = id;
1355                                 attr_map[index].y = req.curve_desc.element;
1356                                 attr_map[index].z = as_uint(req.curve_desc.offset);
1357
1358                                 if(req.curve_type == TypeDesc::TypeFloat)
1359                                         attr_map[index].w = NODE_ATTR_FLOAT;
1360                                 else if(req.curve_type == TypeDesc::TypeMatrix)
1361                                         attr_map[index].w = NODE_ATTR_MATRIX;
1362                                 else
1363                                         attr_map[index].w = NODE_ATTR_FLOAT3;
1364
1365                                 attr_map[index].w |= req.curve_desc.flags << 8;
1366                         }
1367
1368                         index++;
1369
1370                         if(mesh->subd_faces.size()) {
1371                                 attr_map[index].x = id;
1372                                 attr_map[index].y = req.subd_desc.element;
1373                                 attr_map[index].z = as_uint(req.subd_desc.offset);
1374
1375                                 if(req.subd_type == TypeDesc::TypeFloat)
1376                                         attr_map[index].w = NODE_ATTR_FLOAT;
1377                                 else if(req.subd_type == TypeDesc::TypeMatrix)
1378                                         attr_map[index].w = NODE_ATTR_MATRIX;
1379                                 else
1380                                         attr_map[index].w = NODE_ATTR_FLOAT3;
1381
1382                                 attr_map[index].w |= req.subd_desc.flags << 8;
1383                         }
1384
1385                         index++;
1386                 }
1387
1388                 /* terminator */
1389                 for(int j = 0; j < ATTR_PRIM_TYPES; j++) {
1390                         attr_map[index].x = ATTR_STD_NONE;
1391                         attr_map[index].y = 0;
1392                         attr_map[index].z = 0;
1393                         attr_map[index].w = 0;
1394
1395                         index++;
1396                 }
1397         }
1398
1399         /* copy to device */
1400         dscene->attributes_map.copy_to_device();
1401 }
1402
1403 static void update_attribute_element_size(Mesh *mesh,
1404                                           Attribute *mattr,
1405                                           AttributePrimitive prim,
1406                                           size_t *attr_float_size,
1407                                           size_t *attr_float3_size,
1408                                           size_t *attr_uchar4_size)
1409 {
1410         if(mattr) {
1411                 size_t size = mattr->element_size(mesh, prim);
1412
1413                 if(mattr->element == ATTR_ELEMENT_VOXEL) {
1414                         /* pass */
1415                 }
1416                 else if(mattr->element == ATTR_ELEMENT_CORNER_BYTE) {
1417                         *attr_uchar4_size += size;
1418                 }
1419                 else if(mattr->type == TypeDesc::TypeFloat) {
1420                         *attr_float_size += size;
1421                 }
1422                 else if(mattr->type == TypeDesc::TypeMatrix) {
1423                         *attr_float3_size += size * 4;
1424                 }
1425                 else {
1426                         *attr_float3_size += size;
1427                 }
1428         }
1429 }
1430
1431 static void update_attribute_element_offset(Mesh *mesh,
1432                                             device_vector<float>& attr_float,
1433                                             size_t& attr_float_offset,
1434                                             device_vector<float4>& attr_float3,
1435                                             size_t& attr_float3_offset,
1436                                             device_vector<uchar4>& attr_uchar4,
1437                                             size_t& attr_uchar4_offset,
1438                                             Attribute *mattr,
1439                                             AttributePrimitive prim,
1440                                             TypeDesc& type,
1441                                             AttributeDescriptor& desc)
1442 {
1443         if(mattr) {
1444                 /* store element and type */
1445                 desc.element = mattr->element;
1446                 desc.flags = mattr->flags;
1447                 type = mattr->type;
1448
1449                 /* store attribute data in arrays */
1450                 size_t size = mattr->element_size(mesh, prim);
1451
1452                 AttributeElement& element = desc.element;
1453                 int& offset = desc.offset;
1454
1455                 if(mattr->element == ATTR_ELEMENT_VOXEL) {
1456                         /* store slot in offset value */
1457                         VoxelAttribute *voxel_data = mattr->data_voxel();
1458                         offset = voxel_data->slot;
1459                 }
1460                 else if(mattr->element == ATTR_ELEMENT_CORNER_BYTE) {
1461                         uchar4 *data = mattr->data_uchar4();
1462                         offset = attr_uchar4_offset;
1463
1464                         assert(attr_uchar4.size() >= offset + size);
1465                         for(size_t k = 0; k < size; k++) {
1466                                 attr_uchar4[offset+k] = data[k];
1467                         }
1468                         attr_uchar4_offset += size;
1469                 }
1470                 else if(mattr->type == TypeDesc::TypeFloat) {
1471                         float *data = mattr->data_float();
1472                         offset = attr_float_offset;
1473
1474                         assert(attr_float.size() >= offset + size);
1475                         for(size_t k = 0; k < size; k++) {
1476                                 attr_float[offset+k] = data[k];
1477                         }
1478                         attr_float_offset += size;
1479                 }
1480                 else if(mattr->type == TypeDesc::TypeMatrix) {
1481                         Transform *tfm = mattr->data_transform();
1482                         offset = attr_float3_offset;
1483
1484                         assert(attr_float3.size() >= offset + size * 3);
1485                         for(size_t k = 0; k < size*3; k++) {
1486                                 attr_float3[offset+k] = (&tfm->x)[k];
1487                         }
1488                         attr_float3_offset += size * 3;
1489                 }
1490                 else {
1491                         float4 *data = mattr->data_float4();
1492                         offset = attr_float3_offset;
1493
1494                         assert(attr_float3.size() >= offset + size);
1495                         for(size_t k = 0; k < size; k++) {
1496                                 attr_float3[offset+k] = data[k];
1497                         }
1498                         attr_float3_offset += size;
1499                 }
1500
1501                 /* mesh vertex/curve index is global, not per object, so we sneak
1502                  * a correction for that in here */
1503                 if(mesh->subdivision_type == Mesh::SUBDIVISION_CATMULL_CLARK && desc.flags & ATTR_SUBDIVIDED) {
1504                         /* indices for subdivided attributes are retrieved
1505                          * from patch table so no need for correction here*/
1506                 }
1507                 else if(element == ATTR_ELEMENT_VERTEX)
1508                         offset -= mesh->vert_offset;
1509                 else if(element == ATTR_ELEMENT_VERTEX_MOTION)
1510                         offset -= mesh->vert_offset;
1511                 else if(element == ATTR_ELEMENT_FACE) {
1512                         if(prim == ATTR_PRIM_TRIANGLE)
1513                                 offset -= mesh->tri_offset;
1514                         else
1515                                 offset -= mesh->face_offset;
1516                 }
1517                 else if(element == ATTR_ELEMENT_CORNER || element == ATTR_ELEMENT_CORNER_BYTE) {
1518                         if(prim == ATTR_PRIM_TRIANGLE)
1519                                 offset -= 3*mesh->tri_offset;
1520                         else
1521                                 offset -= mesh->corner_offset;
1522                 }
1523                 else if(element == ATTR_ELEMENT_CURVE)
1524                         offset -= mesh->curve_offset;
1525                 else if(element == ATTR_ELEMENT_CURVE_KEY)
1526                         offset -= mesh->curvekey_offset;
1527                 else if(element == ATTR_ELEMENT_CURVE_KEY_MOTION)
1528                         offset -= mesh->curvekey_offset;
1529         }
1530         else {
1531                 /* attribute not found */
1532                 desc.element = ATTR_ELEMENT_NONE;
1533                 desc.offset = 0;
1534         }
1535 }
1536
1537 void MeshManager::device_update_attributes(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
1538 {
1539         progress.set_status("Updating Mesh", "Computing attributes");
1540
1541         /* gather per mesh requested attributes. as meshes may have multiple
1542          * shaders assigned, this merges the requested attributes that have
1543          * been set per shader by the shader manager */
1544         vector<AttributeRequestSet> mesh_attributes(scene->meshes.size());
1545
1546         for(size_t i = 0; i < scene->meshes.size(); i++) {
1547                 Mesh *mesh = scene->meshes[i];
1548
1549                 scene->need_global_attributes(mesh_attributes[i]);
1550
1551                 foreach(Shader *shader, mesh->used_shaders) {
1552                         mesh_attributes[i].add(shader->attributes);
1553                 }
1554         }
1555
1556         /* mesh attribute are stored in a single array per data type. here we fill
1557          * those arrays, and set the offset and element type to create attribute
1558          * maps next */
1559
1560         /* Pre-allocate attributes to avoid arrays re-allocation which would
1561          * take 2x of overall attribute memory usage.
1562          */
1563         size_t attr_float_size = 0;
1564         size_t attr_float3_size = 0;
1565         size_t attr_uchar4_size = 0;
1566         for(size_t i = 0; i < scene->meshes.size(); i++) {
1567                 Mesh *mesh = scene->meshes[i];
1568                 AttributeRequestSet& attributes = mesh_attributes[i];
1569                 foreach(AttributeRequest& req, attributes.requests) {
1570                         Attribute *triangle_mattr = mesh->attributes.find(req);
1571                         Attribute *curve_mattr = mesh->curve_attributes.find(req);
1572                         Attribute *subd_mattr = mesh->subd_attributes.find(req);
1573
1574                         update_attribute_element_size(mesh,
1575                                                       triangle_mattr,
1576                                                       ATTR_PRIM_TRIANGLE,
1577                                                       &attr_float_size,
1578                                                       &attr_float3_size,
1579                                                       &attr_uchar4_size);
1580                         update_attribute_element_size(mesh,
1581                                                       curve_mattr,
1582                                                       ATTR_PRIM_CURVE,
1583                                                       &attr_float_size,
1584                                                       &attr_float3_size,
1585                                                       &attr_uchar4_size);
1586                         update_attribute_element_size(mesh,
1587                                                       subd_mattr,
1588                                                       ATTR_PRIM_SUBD,
1589                                                       &attr_float_size,
1590                                                       &attr_float3_size,
1591                                                       &attr_uchar4_size);
1592                 }
1593         }
1594
1595         dscene->attributes_float.alloc(attr_float_size);
1596         dscene->attributes_float3.alloc(attr_float3_size);
1597         dscene->attributes_uchar4.alloc(attr_uchar4_size);
1598
1599         size_t attr_float_offset = 0;
1600         size_t attr_float3_offset = 0;
1601         size_t attr_uchar4_offset = 0;
1602
1603         /* Fill in attributes. */
1604         for(size_t i = 0; i < scene->meshes.size(); i++) {
1605                 Mesh *mesh = scene->meshes[i];
1606                 AttributeRequestSet& attributes = mesh_attributes[i];
1607
1608                 /* todo: we now store std and name attributes from requests even if
1609                  * they actually refer to the same mesh attributes, optimize */
1610                 foreach(AttributeRequest& req, attributes.requests) {
1611                         Attribute *triangle_mattr = mesh->attributes.find(req);
1612                         Attribute *curve_mattr = mesh->curve_attributes.find(req);
1613                         Attribute *subd_mattr = mesh->subd_attributes.find(req);
1614
1615                         update_attribute_element_offset(mesh,
1616                                                         dscene->attributes_float, attr_float_offset,
1617                                                         dscene->attributes_float3, attr_float3_offset,
1618                                                         dscene->attributes_uchar4, attr_uchar4_offset,
1619                                                         triangle_mattr,
1620                                                         ATTR_PRIM_TRIANGLE,
1621                                                         req.triangle_type,
1622                                                         req.triangle_desc);
1623
1624                         update_attribute_element_offset(mesh,
1625                                                         dscene->attributes_float, attr_float_offset,
1626                                                         dscene->attributes_float3, attr_float3_offset,
1627                                                         dscene->attributes_uchar4, attr_uchar4_offset,
1628                                                         curve_mattr,
1629                                                         ATTR_PRIM_CURVE,
1630                                                         req.curve_type,
1631                                                         req.curve_desc);
1632
1633                         update_attribute_element_offset(mesh,
1634                                                         dscene->attributes_float, attr_float_offset,
1635                                                         dscene->attributes_float3, attr_float3_offset,
1636                                                         dscene->attributes_uchar4, attr_uchar4_offset,
1637                                                         subd_mattr,
1638                                                         ATTR_PRIM_SUBD,
1639                                                         req.subd_type,
1640                                                         req.subd_desc);
1641
1642                         if(progress.get_cancel()) return;
1643                 }
1644         }
1645
1646         /* create attribute lookup maps */
1647         if(scene->shader_manager->use_osl())
1648                 update_osl_attributes(device, scene, mesh_attributes);
1649
1650         update_svm_attributes(device, dscene, scene, mesh_attributes);
1651
1652         if(progress.get_cancel()) return;
1653
1654         /* copy to device */
1655         progress.set_status("Updating Mesh", "Copying Attributes to device");
1656
1657         if(dscene->attributes_float.size()) {
1658                 dscene->attributes_float.copy_to_device();
1659         }
1660         if(dscene->attributes_float3.size()) {
1661                 dscene->attributes_float3.copy_to_device();
1662         }
1663         if(dscene->attributes_uchar4.size()) {
1664                 dscene->attributes_uchar4.copy_to_device();
1665         }
1666
1667         if(progress.get_cancel()) return;
1668
1669         /* After mesh attributes and patch tables have been copied to device memory,
1670          * we need to update offsets in the objects. */
1671         scene->object_manager->device_update_mesh_offsets(device, dscene, scene);
1672 }
1673
1674 void MeshManager::mesh_calc_offset(Scene *scene)
1675 {
1676         size_t vert_size = 0;
1677         size_t tri_size = 0;
1678
1679         size_t curve_key_size = 0;
1680         size_t curve_size = 0;
1681
1682         size_t patch_size = 0;
1683         size_t face_size = 0;
1684         size_t corner_size = 0;
1685
1686         foreach(Mesh *mesh, scene->meshes) {
1687                 mesh->vert_offset = vert_size;
1688                 mesh->tri_offset = tri_size;
1689
1690                 mesh->curvekey_offset = curve_key_size;
1691                 mesh->curve_offset = curve_size;
1692
1693                 mesh->patch_offset = patch_size;
1694                 mesh->face_offset = face_size;
1695                 mesh->corner_offset = corner_size;
1696
1697                 vert_size += mesh->verts.size();
1698                 tri_size += mesh->num_triangles();
1699
1700                 curve_key_size += mesh->curve_keys.size();
1701                 curve_size += mesh->num_curves();
1702
1703                 if(mesh->subd_faces.size()) {
1704                         Mesh::SubdFace& last = mesh->subd_faces[mesh->subd_faces.size()-1];
1705                         patch_size += (last.ptex_offset + last.num_ptex_faces()) * 8;
1706
1707                         /* patch tables are stored in same array so include them in patch_size */
1708                         if(mesh->patch_table) {
1709                                 mesh->patch_table_offset = patch_size;
1710                                 patch_size += mesh->patch_table->total_size();
1711                         }
1712                 }
1713                 face_size += mesh->subd_faces.size();
1714                 corner_size += mesh->subd_face_corners.size();
1715         }
1716 }
1717
1718 void MeshManager::device_update_mesh(Device *,
1719                                      DeviceScene *dscene,
1720                                      Scene *scene,
1721                                      bool for_displacement,
1722                                      Progress& progress)
1723 {
1724         /* Count. */
1725         size_t vert_size = 0;
1726         size_t tri_size = 0;
1727
1728         size_t curve_key_size = 0;
1729         size_t curve_size = 0;
1730
1731         size_t patch_size = 0;
1732
1733         foreach(Mesh *mesh, scene->meshes) {
1734                 vert_size += mesh->verts.size();
1735                 tri_size += mesh->num_triangles();
1736
1737                 curve_key_size += mesh->curve_keys.size();
1738                 curve_size += mesh->num_curves();
1739
1740                 if(mesh->subd_faces.size()) {
1741                         Mesh::SubdFace& last = mesh->subd_faces[mesh->subd_faces.size()-1];
1742                         patch_size += (last.ptex_offset + last.num_ptex_faces()) * 8;
1743
1744                         /* patch tables are stored in same array so include them in patch_size */
1745                         if(mesh->patch_table) {
1746                                 mesh->patch_table_offset = patch_size;
1747                                 patch_size += mesh->patch_table->total_size();
1748                         }
1749                 }
1750         }
1751
1752         /* Create mapping from triangle to primitive triangle array. */
1753         vector<uint> tri_prim_index(tri_size);
1754         if(for_displacement) {
1755                 /* For displacement kernels we do some trickery to make them believe
1756                  * we've got all required data ready. However, that data is different
1757                  * from final render kernels since we don't have BVH yet, so can't
1758                  * really use same semantic of arrays.
1759                  */
1760                 foreach(Mesh *mesh, scene->meshes) {
1761                         for(size_t i = 0; i < mesh->num_triangles(); ++i) {
1762                                 tri_prim_index[i + mesh->tri_offset] = 3 * (i + mesh->tri_offset);
1763                         }
1764                 }
1765         }
1766         else {
1767                 for(size_t i = 0; i < dscene->prim_index.size(); ++i) {
1768                         if((dscene->prim_type[i] & PRIMITIVE_ALL_TRIANGLE) != 0) {
1769                                 tri_prim_index[dscene->prim_index[i]] = dscene->prim_tri_index[i];
1770                         }
1771                 }
1772         }
1773
1774         /* Fill in all the arrays. */
1775         if(tri_size != 0) {
1776                 /* normals */
1777                 progress.set_status("Updating Mesh", "Computing normals");
1778
1779                 uint *tri_shader = dscene->tri_shader.alloc(tri_size);
1780                 float4 *vnormal = dscene->tri_vnormal.alloc(vert_size);
1781                 uint4 *tri_vindex = dscene->tri_vindex.alloc(tri_size);
1782                 uint *tri_patch = dscene->tri_patch.alloc(tri_size);
1783                 float2 *tri_patch_uv = dscene->tri_patch_uv.alloc(vert_size);
1784
1785                 foreach(Mesh *mesh, scene->meshes) {
1786                         mesh->pack_shaders(scene,
1787                                            &tri_shader[mesh->tri_offset]);
1788                         mesh->pack_normals(&vnormal[mesh->vert_offset]);
1789                         mesh->pack_verts(tri_prim_index,
1790                                          &tri_vindex[mesh->tri_offset],
1791                                          &tri_patch[mesh->tri_offset],
1792                                          &tri_patch_uv[mesh->vert_offset],
1793                                          mesh->vert_offset,
1794                                          mesh->tri_offset);
1795                         if(progress.get_cancel()) return;
1796                 }
1797
1798                 /* vertex coordinates */
1799                 progress.set_status("Updating Mesh", "Copying Mesh to device");
1800
1801                 dscene->tri_shader.copy_to_device();
1802                 dscene->tri_vnormal.copy_to_device();
1803                 dscene->tri_vindex.copy_to_device();
1804                 dscene->tri_patch.copy_to_device();
1805                 dscene->tri_patch_uv.copy_to_device();
1806         }
1807
1808         if(curve_size != 0) {
1809                 progress.set_status("Updating Mesh", "Copying Strands to device");
1810
1811                 float4 *curve_keys = dscene->curve_keys.alloc(curve_key_size);
1812                 float4 *curves = dscene->curves.alloc(curve_size);
1813
1814                 foreach(Mesh *mesh, scene->meshes) {
1815                         mesh->pack_curves(scene, &curve_keys[mesh->curvekey_offset], &curves[mesh->curve_offset], mesh->curvekey_offset);
1816                         if(progress.get_cancel()) return;
1817                 }
1818
1819                 dscene->curve_keys.copy_to_device();
1820                 dscene->curves.copy_to_device();
1821         }
1822
1823         if(patch_size != 0) {
1824                 progress.set_status("Updating Mesh", "Copying Patches to device");
1825
1826                 uint *patch_data = dscene->patches.alloc(patch_size);
1827
1828                 foreach(Mesh *mesh, scene->meshes) {
1829                         mesh->pack_patches(&patch_data[mesh->patch_offset], mesh->vert_offset, mesh->face_offset, mesh->corner_offset);
1830
1831                         if(mesh->patch_table) {
1832                                 mesh->patch_table->copy_adjusting_offsets(&patch_data[mesh->patch_table_offset], mesh->patch_table_offset);
1833                         }
1834
1835                         if(progress.get_cancel()) return;
1836                 }
1837
1838                 dscene->patches.copy_to_device();
1839         }
1840
1841         if(for_displacement) {
1842                 float4 *prim_tri_verts = dscene->prim_tri_verts.alloc(tri_size * 3);
1843                 foreach(Mesh *mesh, scene->meshes) {
1844                         for(size_t i = 0; i < mesh->num_triangles(); ++i) {
1845                                 Mesh::Triangle t = mesh->get_triangle(i);
1846                                 size_t offset = 3 * (i + mesh->tri_offset);
1847                                 prim_tri_verts[offset + 0] = float3_to_float4(mesh->verts[t.v[0]]);
1848                                 prim_tri_verts[offset + 1] = float3_to_float4(mesh->verts[t.v[1]]);
1849                                 prim_tri_verts[offset + 2] = float3_to_float4(mesh->verts[t.v[2]]);
1850                         }
1851                 }
1852                 dscene->prim_tri_verts.copy_to_device();
1853         }
1854 }
1855
1856 void MeshManager::device_update_bvh(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
1857 {
1858         /* bvh build */
1859         progress.set_status("Updating Scene BVH", "Building");
1860
1861         BVHParams bparams;
1862         bparams.top_level = true;
1863         bparams.bvh_layout = BVHParams::best_bvh_layout(
1864                 scene->params.bvh_layout,
1865                 device->get_bvh_layout_mask());
1866         bparams.use_spatial_split = scene->params.use_bvh_spatial_split;
1867         bparams.use_unaligned_nodes = dscene->data.bvh.have_curves &&
1868                                       scene->params.use_bvh_unaligned_nodes;
1869         bparams.num_motion_triangle_steps = scene->params.num_bvh_time_steps;
1870         bparams.num_motion_curve_steps = scene->params.num_bvh_time_steps;
1871         bparams.bvh_type = scene->params.bvh_type;
1872         bparams.curve_flags = dscene->data.curve.curveflags;
1873         bparams.curve_subdivisions = dscene->data.curve.subdivisions;
1874
1875         VLOG(1) << "Using " << bvh_layout_name(bparams.bvh_layout)
1876                 << " layout.";
1877
1878 #ifdef WITH_EMBREE
1879         if(bparams.bvh_layout == BVH_LAYOUT_EMBREE) {
1880                 if(dscene->data.bvh.scene) {
1881                         BVHEmbree::destroy(dscene->data.bvh.scene);
1882                 }
1883         }
1884 #endif
1885
1886         BVH *bvh = BVH::create(bparams, scene->objects);
1887         bvh->build(progress, &device->stats);
1888
1889         if(progress.get_cancel()) {
1890 #ifdef WITH_EMBREE
1891                 if(bparams.bvh_layout == BVH_LAYOUT_EMBREE) {
1892                         if(dscene->data.bvh.scene) {
1893                                 BVHEmbree::destroy(dscene->data.bvh.scene);
1894                         }
1895                 }
1896 #endif
1897                 delete bvh;
1898                 return;
1899         }
1900
1901         /* copy to device */
1902         progress.set_status("Updating Scene BVH", "Copying BVH to device");
1903
1904         PackedBVH& pack = bvh->pack;
1905
1906         if(pack.nodes.size()) {
1907                 dscene->bvh_nodes.steal_data(pack.nodes);
1908                 dscene->bvh_nodes.copy_to_device();
1909         }
1910         if(pack.leaf_nodes.size()) {
1911                 dscene->bvh_leaf_nodes.steal_data(pack.leaf_nodes);
1912                 dscene->bvh_leaf_nodes.copy_to_device();
1913         }
1914         if(pack.object_node.size()) {
1915                 dscene->object_node.steal_data(pack.object_node);
1916                 dscene->object_node.copy_to_device();
1917         }
1918         if(pack.prim_tri_index.size()) {
1919                 dscene->prim_tri_index.steal_data(pack.prim_tri_index);
1920                 dscene->prim_tri_index.copy_to_device();
1921         }
1922         if(pack.prim_tri_verts.size()) {
1923                 dscene->prim_tri_verts.steal_data(pack.prim_tri_verts);
1924                 dscene->prim_tri_verts.copy_to_device();
1925         }
1926         if(pack.prim_type.size()) {
1927                 dscene->prim_type.steal_data(pack.prim_type);
1928                 dscene->prim_type.copy_to_device();
1929         }
1930         if(pack.prim_visibility.size()) {
1931                 dscene->prim_visibility.steal_data(pack.prim_visibility);
1932                 dscene->prim_visibility.copy_to_device();
1933         }
1934         if(pack.prim_index.size()) {
1935                 dscene->prim_index.steal_data(pack.prim_index);
1936                 dscene->prim_index.copy_to_device();
1937         }
1938         if(pack.prim_object.size()) {
1939                 dscene->prim_object.steal_data(pack.prim_object);
1940                 dscene->prim_object.copy_to_device();
1941         }
1942         if(pack.prim_time.size()) {
1943                 dscene->prim_time.steal_data(pack.prim_time);
1944                 dscene->prim_time.copy_to_device();
1945         }
1946
1947         dscene->data.bvh.root = pack.root_index;
1948         dscene->data.bvh.bvh_layout = bparams.bvh_layout;
1949         dscene->data.bvh.use_bvh_steps = (scene->params.num_bvh_time_steps != 0);
1950
1951
1952 #ifdef WITH_EMBREE
1953         if(bparams.bvh_layout == BVH_LAYOUT_EMBREE) {
1954                 dscene->data.bvh.scene = ((BVHEmbree*)bvh)->scene;
1955         }
1956         else {
1957                 dscene->data.bvh.scene = NULL;
1958         }
1959 #endif
1960
1961         delete bvh;
1962 }
1963
1964 void MeshManager::device_update_preprocess(Device *device,
1965                                            Scene *scene,
1966                                            Progress& progress)
1967 {
1968         if(!need_update && !need_flags_update) {
1969                 return;
1970         }
1971
1972         progress.set_status("Updating Meshes Flags");
1973
1974         /* Update flags. */
1975         bool volume_images_updated = false;
1976
1977         foreach(Mesh *mesh, scene->meshes) {
1978                 mesh->has_volume = false;
1979
1980                 foreach(const Shader *shader, mesh->used_shaders) {
1981                         if(shader->has_volume) {
1982                                 mesh->has_volume = true;
1983                         }
1984                         if(shader->has_surface_bssrdf) {
1985                                 mesh->has_surface_bssrdf = true;
1986                         }
1987                 }
1988
1989                 if(need_update && mesh->has_volume) {
1990                         /* Create volume meshes if there is voxel data. */
1991                         bool has_voxel_attributes = false;
1992
1993                         foreach(Attribute& attr, mesh->attributes.attributes) {
1994                                 if(attr.element == ATTR_ELEMENT_VOXEL) {
1995                                         has_voxel_attributes = true;
1996                                 }
1997                         }
1998
1999                         if(has_voxel_attributes) {
2000                                 if(!volume_images_updated) {
2001                                         progress.set_status("Updating Meshes Volume Bounds");
2002                                         device_update_volume_images(device, scene, progress);
2003                                         volume_images_updated = true;
2004                                 }
2005
2006                                 create_volume_mesh(scene, mesh, progress);
2007                         }
2008                 }
2009         }
2010
2011         need_flags_update = false;
2012 }
2013
2014 void MeshManager::device_update_displacement_images(Device *device,
2015                                                     Scene *scene,
2016                                                     Progress& progress)
2017 {
2018         progress.set_status("Updating Displacement Images");
2019         TaskPool pool;
2020         ImageManager *image_manager = scene->image_manager;
2021         set<int> bump_images;
2022         foreach(Mesh *mesh, scene->meshes) {
2023                 if(mesh->need_update) {
2024                         foreach(Shader *shader, mesh->used_shaders) {
2025                                 if(!shader->has_displacement || shader->displacement_method == DISPLACE_BUMP) {
2026                                         continue;
2027                                 }
2028                                 foreach(ShaderNode* node, shader->graph->nodes) {
2029                                         if(node->special_type != SHADER_SPECIAL_TYPE_IMAGE_SLOT) {
2030                                                 continue;
2031                                         }
2032
2033                                         ImageSlotTextureNode *image_node = static_cast<ImageSlotTextureNode*>(node);
2034                                         int slot = image_node->slot;
2035                                         if(slot != -1) {
2036                                                 bump_images.insert(slot);
2037                                         }
2038                                 }
2039                         }
2040                 }
2041         }
2042         foreach(int slot, bump_images) {
2043                 pool.push(function_bind(&ImageManager::device_update_slot,
2044                                         image_manager,
2045                                         device,
2046                                         scene,
2047                                         slot,
2048                                         &progress));
2049         }
2050         pool.wait_work();
2051 }
2052
2053 void MeshManager::device_update_volume_images(Device *device,
2054                                               Scene *scene,
2055                                               Progress& progress)
2056 {
2057         progress.set_status("Updating Volume Images");
2058         TaskPool pool;
2059         ImageManager *image_manager = scene->image_manager;
2060         set<int> volume_images;
2061
2062         foreach(Mesh *mesh, scene->meshes) {
2063                 if(!mesh->need_update) {
2064                         continue;
2065                 }
2066
2067                 foreach(Attribute& attr, mesh->attributes.attributes) {
2068                         if(attr.element != ATTR_ELEMENT_VOXEL) {
2069                                 continue;
2070                         }
2071
2072                         VoxelAttribute *voxel = attr.data_voxel();
2073
2074                         if(voxel->slot != -1) {
2075                                 volume_images.insert(voxel->slot);
2076                         }
2077                 }
2078         }
2079
2080         foreach(int slot, volume_images) {
2081                 pool.push(function_bind(&ImageManager::device_update_slot,
2082                                         image_manager,
2083                                         device,
2084                                         scene,
2085                                         slot,
2086                                         &progress));
2087         }
2088         pool.wait_work();
2089 }
2090
2091 void MeshManager::device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
2092 {
2093         if(!need_update)
2094                 return;
2095
2096         VLOG(1) << "Total " << scene->meshes.size() << " meshes.";
2097
2098         bool true_displacement_used = false;
2099         size_t total_tess_needed = 0;
2100
2101         foreach(Mesh *mesh, scene->meshes) {
2102                 foreach(Shader *shader, mesh->used_shaders) {
2103                         if(shader->need_update_mesh)
2104                                 mesh->need_update = true;
2105                 }
2106
2107                 if(mesh->need_update) {
2108                         /* Update normals. */
2109                         mesh->add_face_normals();
2110                         mesh->add_vertex_normals();
2111
2112                         if(mesh->need_attribute(scene, ATTR_STD_POSITION_UNDISPLACED)) {
2113                                 mesh->add_undisplaced();
2114                         }
2115
2116                         /* Test if we need tesselation. */
2117                         if(mesh->subdivision_type != Mesh::SUBDIVISION_NONE &&
2118                            mesh->num_subd_verts == 0 &&
2119                            mesh->subd_params)
2120                         {
2121                                 total_tess_needed++;
2122                         }
2123
2124                         /* Test if we need displacement. */
2125                         if(mesh->has_true_displacement()) {
2126                                 true_displacement_used = true;
2127                         }
2128
2129                         if(progress.get_cancel()) return;
2130                 }
2131         }
2132
2133         /* Tessellate meshes that are using subdivision */
2134         if(total_tess_needed) {
2135                 size_t i = 0;
2136                 foreach(Mesh *mesh, scene->meshes) {
2137                         if(mesh->need_update &&
2138                            mesh->subdivision_type != Mesh::SUBDIVISION_NONE &&
2139                            mesh->num_subd_verts == 0 &&
2140                            mesh->subd_params)
2141                         {
2142                                 string msg = "Tessellating ";
2143                                 if(mesh->name == "")
2144                                         msg += string_printf("%u/%u", (uint)(i+1), (uint)total_tess_needed);
2145                                 else
2146                                         msg += string_printf("%s %u/%u", mesh->name.c_str(), (uint)(i+1), (uint)total_tess_needed);
2147
2148                                 progress.set_status("Updating Mesh", msg);
2149
2150                                 DiagSplit dsplit(*mesh->subd_params);
2151                                 mesh->tessellate(&dsplit);
2152
2153                                 i++;
2154
2155                                 if(progress.get_cancel()) return;
2156                         }
2157
2158                 }
2159         }
2160
2161         /* Update images needed for true displacement. */
2162         bool old_need_object_flags_update = false;
2163         if(true_displacement_used) {
2164                 VLOG(1) << "Updating images used for true displacement.";
2165                 device_update_displacement_images(device, scene, progress);
2166                 old_need_object_flags_update = scene->object_manager->need_flags_update;
2167                 scene->object_manager->device_update_flags(device,
2168                                                            dscene,
2169                                                            scene,
2170                                                            progress,
2171                                                            false);
2172         }
2173
2174         /* Device update. */
2175         device_free(device, dscene);
2176
2177         mesh_calc_offset(scene);
2178         if(true_displacement_used) {
2179                 device_update_mesh(device, dscene, scene, true, progress);
2180         }
2181         if(progress.get_cancel()) return;
2182
2183         device_update_attributes(device, dscene, scene, progress);
2184         if(progress.get_cancel()) return;
2185
2186         /* Update displacement. */
2187         bool displacement_done = false;
2188         size_t num_bvh = 0;
2189
2190         foreach(Mesh *mesh, scene->meshes) {
2191                 if(mesh->need_update) {
2192                         if(displace(device, dscene, scene, mesh, progress)) {
2193                                 displacement_done = true;
2194                         }
2195
2196                         if(mesh->need_build_bvh()) {
2197                                 num_bvh++;
2198                         }
2199                 }
2200
2201                 if(progress.get_cancel()) return;
2202         }
2203
2204         /* Device re-update after displacement. */
2205         if(displacement_done) {
2206                 device_free(device, dscene);
2207
2208                 device_update_attributes(device, dscene, scene, progress);
2209                 if(progress.get_cancel()) return;
2210         }
2211
2212         TaskPool pool;
2213
2214         size_t i = 0;
2215         foreach(Mesh *mesh, scene->meshes) {
2216                 if(mesh->need_update) {
2217                         pool.push(function_bind(&Mesh::compute_bvh,
2218                                                 mesh,
2219                                                 device,
2220                                                 dscene,
2221                                                 &scene->params,
2222                                                 &progress,
2223                                                 i,
2224                                                 num_bvh));
2225                         if(mesh->need_build_bvh()) {
2226                                 i++;
2227                         }
2228                 }
2229         }
2230
2231         TaskPool::Summary summary;
2232         pool.wait_work(&summary);
2233         VLOG(2) << "Objects BVH build pool statistics:\n"
2234                 << summary.full_report();
2235
2236         foreach(Shader *shader, scene->shaders) {
2237                 shader->need_update_mesh = false;
2238         }
2239
2240         Scene::MotionType need_motion = scene->need_motion();
2241         bool motion_blur = need_motion == Scene::MOTION_BLUR;
2242
2243         /* Update objects. */
2244         vector<Object *> volume_objects;
2245         foreach(Object *object, scene->objects) {
2246                 object->compute_bounds(motion_blur);
2247         }
2248
2249         if(progress.get_cancel()) return;
2250
2251         device_update_bvh(device, dscene, scene, progress);
2252         if(progress.get_cancel()) return;
2253
2254         device_update_mesh(device, dscene, scene, false, progress);
2255         if(progress.get_cancel()) return;
2256
2257         need_update = false;
2258
2259         if(true_displacement_used) {
2260                 /* Re-tag flags for update, so they're re-evaluated
2261                  * for meshes with correct bounding boxes.
2262                  *
2263                  * This wouldn't cause wrong results, just true
2264                  * displacement might be less optimal ot calculate.
2265                  */
2266                 scene->object_manager->need_flags_update = old_need_object_flags_update;
2267         }
2268 }
2269
2270 void MeshManager::device_free(Device *device, DeviceScene *dscene)
2271 {
2272         dscene->bvh_nodes.free();
2273         dscene->bvh_leaf_nodes.free();
2274         dscene->object_node.free();
2275         dscene->prim_tri_verts.free();
2276         dscene->prim_tri_index.free();
2277         dscene->prim_type.free();
2278         dscene->prim_visibility.free();
2279         dscene->prim_index.free();
2280         dscene->prim_object.free();
2281         dscene->prim_time.free();
2282         dscene->tri_shader.free();
2283         dscene->tri_vnormal.free();
2284         dscene->tri_vindex.free();
2285         dscene->tri_patch.free();
2286         dscene->tri_patch_uv.free();
2287         dscene->curves.free();
2288         dscene->curve_keys.free();
2289         dscene->patches.free();
2290         dscene->attributes_map.free();
2291         dscene->attributes_float.free();
2292         dscene->attributes_float3.free();
2293         dscene->attributes_uchar4.free();
2294
2295 #ifdef WITH_OSL
2296         OSLGlobals *og = (OSLGlobals*)device->osl_memory();
2297
2298         if(og) {
2299                 og->object_name_map.clear();
2300                 og->attribute_map.clear();
2301                 og->object_names.clear();
2302         }
2303 #else
2304         (void) device;
2305 #endif
2306 }
2307
2308 void MeshManager::tag_update(Scene *scene)
2309 {
2310         need_update = true;
2311         scene->object_manager->need_update = true;
2312 }
2313
2314 void MeshManager::collect_statistics(const Scene *scene, RenderStats *stats)
2315 {
2316         foreach(Mesh *mesh, scene->meshes) {
2317                 stats->mesh.geometry.add_entry(
2318                         NamedSizeEntry(string(mesh->name.c_str()),
2319                                        mesh->get_total_size_in_bytes()));
2320         }
2321 }
2322
2323 bool Mesh::need_attribute(Scene *scene, AttributeStandard std)
2324 {
2325         if(std == ATTR_STD_NONE)
2326                 return false;
2327
2328         if(scene->need_global_attribute(std))
2329                 return true;
2330
2331         foreach(Shader *shader, used_shaders)
2332                 if(shader->attributes.find(std))
2333                         return true;
2334
2335         return false;
2336 }
2337
2338 bool Mesh::need_attribute(Scene * /*scene*/, ustring name)
2339 {
2340         if(name == ustring())
2341                 return false;
2342
2343         foreach(Shader *shader, used_shaders)
2344                 if(shader->attributes.find(name))
2345                         return true;
2346
2347         return false;
2348 }
2349
2350 CCL_NAMESPACE_END