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