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