027bfd719318af5d10eb2c46ee214c683b460769
[blender.git] / intern / cycles / render / object.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 "device.h"
18 #include "light.h"
19 #include "mesh.h"
20 #include "curves.h"
21 #include "object.h"
22 #include "particles.h"
23 #include "scene.h"
24
25 #include "util_foreach.h"
26 #include "util_map.h"
27 #include "util_progress.h"
28 #include "util_vector.h"
29
30 CCL_NAMESPACE_BEGIN
31
32 /* Object */
33
34 Object::Object()
35 {
36         name = "";
37         mesh = NULL;
38         tfm = transform_identity();
39         visibility = ~0;
40         random_id = 0;
41         pass_id = 0;
42         particle_system = NULL;
43         particle_index = 0;
44         bounds = BoundBox::empty;
45         motion.pre = transform_identity();
46         motion.mid = transform_identity();
47         motion.post = transform_identity();
48         use_motion = false;
49         use_holdout = false;
50         dupli_generated = make_float3(0.0f, 0.0f, 0.0f);
51         dupli_uv = make_float2(0.0f, 0.0f);
52 }
53
54 Object::~Object()
55 {
56 }
57
58 void Object::compute_bounds(bool motion_blur)
59 {
60         BoundBox mbounds = mesh->bounds;
61
62         if(motion_blur && use_motion) {
63                 DecompMotionTransform decomp;
64                 transform_motion_decompose(&decomp, &motion, &tfm);
65
66                 bounds = BoundBox::empty;
67
68                 /* todo: this is really terrible. according to pbrt there is a better
69                  * way to find this iteratively, but did not find implementation yet
70                  * or try to implement myself */
71                 for(float t = 0.0f; t < 1.0f; t += (1.0f/128.0f)) {
72                         Transform ttfm;
73
74                         transform_motion_interpolate(&ttfm, &decomp, t);
75                         bounds.grow(mbounds.transformed(&ttfm));
76                 }
77         }
78         else
79                 bounds = mbounds.transformed(&tfm);
80 }
81
82 void Object::apply_transform(bool apply_to_motion)
83 {
84         if(!mesh || tfm == transform_identity())
85                 return;
86         
87         /* triangles */
88         if(mesh->verts.size()) {
89                 /* store matrix to transform later. when accessing these as attributes we
90                  * do not want the transform to be applied for consistency between static
91                  * and dynamic BVH, so we do it on packing. */
92                 mesh->transform_normal = transform_transpose(transform_inverse(tfm));
93
94                 /* apply to mesh vertices */
95                 for(size_t i = 0; i < mesh->verts.size(); i++)
96                         mesh->verts[i] = transform_point(&tfm, mesh->verts[i]);
97                 
98                 if(apply_to_motion) {
99                         Attribute *attr = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
100
101                         if (attr) {
102                                 size_t steps_size = mesh->verts.size() * (mesh->motion_steps - 1);
103                                 float3 *vert_steps = attr->data_float3();
104
105                                 for (size_t i = 0; i < steps_size; i++)
106                                         vert_steps[i] = transform_point(&tfm, vert_steps[i]);
107                         }
108
109                         Attribute *attr_N = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_NORMAL);
110
111                         if(attr_N) {
112                                 Transform ntfm = mesh->transform_normal;
113                                 size_t steps_size = mesh->verts.size() * (mesh->motion_steps - 1);
114                                 float3 *normal_steps = attr_N->data_float3();
115
116                                 for (size_t i = 0; i < steps_size; i++)
117                                         normal_steps[i] = normalize(transform_direction(&ntfm, normal_steps[i]));
118                         }
119                 }
120         }
121
122         /* curves */
123         if(mesh->curve_keys.size()) {
124                 /* compute uniform scale */
125                 float3 c0 = transform_get_column(&tfm, 0);
126                 float3 c1 = transform_get_column(&tfm, 1);
127                 float3 c2 = transform_get_column(&tfm, 2);
128                 float scalar = pow(fabsf(dot(cross(c0, c1), c2)), 1.0f/3.0f);
129
130                 /* apply transform to curve keys */
131                 for(size_t i = 0; i < mesh->curve_keys.size(); i++) {
132                         float3 co = transform_point(&tfm, float4_to_float3(mesh->curve_keys[i]));
133                         float radius = mesh->curve_keys[i].w * scalar;
134
135                         /* scale for curve radius is only correct for uniform scale */
136                         mesh->curve_keys[i] = float3_to_float4(co);
137                         mesh->curve_keys[i].w = radius;
138                 }
139
140                 if(apply_to_motion) {
141                         Attribute *curve_attr = mesh->curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
142
143                         if (curve_attr) {
144                                 /* apply transform to motion curve keys */
145                                 size_t steps_size = mesh->curve_keys.size() * (mesh->motion_steps - 1);
146                                 float4 *key_steps = curve_attr->data_float4();
147
148                                 for (size_t i = 0; i < steps_size; i++) {
149                                         float3 co = transform_point(&tfm, float4_to_float3(key_steps[i]));
150                                         float radius = key_steps[i].w * scalar;
151
152                                         /* scale for curve radius is only correct for uniform scale */
153                                         key_steps[i] = float3_to_float4(co);
154                                         key_steps[i].w = radius;
155                                 }
156                         }
157                 }
158         }
159
160         /* we keep normals pointing in same direction on negative scale, notify
161          * mesh about this in it (re)calculates normals */
162         if(transform_negative_scale(tfm))
163                 mesh->transform_negative_scaled = true;
164
165         if(bounds.valid()) {
166                 mesh->compute_bounds();
167                 compute_bounds(false);
168         }
169
170         /* tfm is not reset to identity, all code that uses it needs to check the
171            transform_applied boolean */
172 }
173
174 void Object::tag_update(Scene *scene)
175 {
176         if(mesh) {
177                 if(mesh->transform_applied)
178                         mesh->need_update = true;
179
180                 foreach(uint sindex, mesh->used_shaders) {
181                         Shader *shader = scene->shaders[sindex];
182
183                         if(shader->use_mis && shader->has_surface_emission)
184                                 scene->light_manager->need_update = true;
185                 }
186         }
187
188         scene->curve_system_manager->need_update = true;
189         scene->mesh_manager->need_update = true;
190         scene->object_manager->need_update = true;
191 }
192
193 vector<float> Object::motion_times()
194 {
195         /* compute times at which we sample motion for this object */
196         vector<float> times;
197
198         if(!mesh || mesh->motion_steps == 1)
199                 return times;
200
201         int motion_steps = mesh->motion_steps;
202
203         for(int step = 0; step < motion_steps; step++) {
204                 if(step != motion_steps / 2) {
205                         float time = 2.0f * step / (motion_steps - 1) - 1.0f;
206                         times.push_back(time);
207                 }
208         }
209
210         return times;
211 }
212
213 /* Object Manager */
214
215 ObjectManager::ObjectManager()
216 {
217         need_update = true;
218 }
219
220 ObjectManager::~ObjectManager()
221 {
222 }
223
224 void ObjectManager::device_update_transforms(Device *device, DeviceScene *dscene, Scene *scene, uint *object_flag, Progress& progress)
225 {
226         float4 *objects;
227         float4 *objects_vector = NULL;
228         int i = 0;
229         map<Mesh*, float> surface_area_map;
230         map<ParticleSystem*, int> particle_offset;
231         Scene::MotionType need_motion = scene->need_motion(device->info.advanced_shading);
232         bool have_motion = false;
233         bool have_curves = false;
234
235         objects = dscene->objects.resize(OBJECT_SIZE*scene->objects.size());
236         if(need_motion == Scene::MOTION_PASS)
237                 objects_vector = dscene->objects_vector.resize(OBJECT_VECTOR_SIZE*scene->objects.size());
238
239         /* particle system device offsets
240          * 0 is dummy particle, index starts at 1
241          */
242         int numparticles = 1;
243         foreach(ParticleSystem *psys, scene->particle_systems) {
244                 particle_offset[psys] = numparticles;
245                 numparticles += psys->particles.size();
246         }
247
248         foreach(Object *ob, scene->objects) {
249                 Mesh *mesh = ob->mesh;
250                 uint flag = 0;
251
252                 /* compute transformations */
253                 Transform tfm = ob->tfm;
254                 Transform itfm = transform_inverse(tfm);
255
256                 /* compute surface area. for uniform scale we can do avoid the many
257                  * transform calls and share computation for instances */
258                 /* todo: correct for displacement, and move to a better place */
259                 float uniform_scale;
260                 float surface_area = 0.0f;
261                 float pass_id = ob->pass_id;
262                 float random_number = (float)ob->random_id * (1.0f/(float)0xFFFFFFFF);
263                 int particle_index = (ob->particle_system)? ob->particle_index + particle_offset[ob->particle_system]: 0;
264
265                 if(transform_uniform_scale(tfm, uniform_scale)) {
266                         map<Mesh*, float>::iterator it = surface_area_map.find(mesh);
267
268                         if(it == surface_area_map.end()) {
269                                 foreach(Mesh::Triangle& t, mesh->triangles) {
270                                         float3 p1 = mesh->verts[t.v[0]];
271                                         float3 p2 = mesh->verts[t.v[1]];
272                                         float3 p3 = mesh->verts[t.v[2]];
273
274                                         surface_area += triangle_area(p1, p2, p3);
275                                 }
276
277                                 surface_area_map[mesh] = surface_area;
278                         }
279                         else
280                                 surface_area = it->second;
281
282                         surface_area *= uniform_scale;
283                 }
284                 else {
285                         foreach(Mesh::Triangle& t, mesh->triangles) {
286                                 float3 p1 = transform_point(&tfm, mesh->verts[t.v[0]]);
287                                 float3 p2 = transform_point(&tfm, mesh->verts[t.v[1]]);
288                                 float3 p3 = transform_point(&tfm, mesh->verts[t.v[2]]);
289
290                                 surface_area += triangle_area(p1, p2, p3);
291                         }
292                 }
293
294                 /* pack in texture */
295                 int offset = i*OBJECT_SIZE;
296
297                 /* OBJECT_TRANSFORM */
298                 memcpy(&objects[offset], &tfm, sizeof(float4)*3);
299                 /* OBJECT_INVERSE_TRANSFORM */
300                 memcpy(&objects[offset+4], &itfm, sizeof(float4)*3);
301                 /* OBJECT_PROPERTIES */
302                 objects[offset+8] = make_float4(surface_area, pass_id, random_number, __int_as_float(particle_index));
303
304                 if(need_motion == Scene::MOTION_PASS) {
305                         /* motion transformations, is world/object space depending if mesh
306                          * comes with deformed position in object space, or if we transform
307                          * the shading point in world space */
308                         Transform mtfm_pre = ob->motion.pre;
309                         Transform mtfm_post = ob->motion.post;
310
311                         if(!mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION)) {
312                                 mtfm_pre = mtfm_pre * itfm;
313                                 mtfm_post = mtfm_post * itfm;
314                         }
315
316                         memcpy(&objects_vector[i*OBJECT_VECTOR_SIZE+0], &mtfm_pre, sizeof(float4)*3);
317                         memcpy(&objects_vector[i*OBJECT_VECTOR_SIZE+3], &mtfm_post, sizeof(float4)*3);
318                 }
319 #ifdef __OBJECT_MOTION__
320                 else if(need_motion == Scene::MOTION_BLUR) {
321                         if(ob->use_motion) {
322                                 /* decompose transformations for interpolation */
323                                 DecompMotionTransform decomp;
324
325                                 transform_motion_decompose(&decomp, &ob->motion, &ob->tfm);
326                                 memcpy(&objects[offset], &decomp, sizeof(float4)*8);
327                                 flag |= SD_OBJECT_MOTION;
328                                 have_motion = true;
329                         }
330                 }
331 #endif
332
333                 if(mesh->use_motion_blur)
334                         have_motion = true;
335
336                 /* dupli object coords and motion info */
337                 int totalsteps = mesh->motion_steps;
338                 int numsteps = (totalsteps - 1)/2;
339                 int numverts = mesh->verts.size();
340                 int numkeys = mesh->curve_keys.size();
341
342                 objects[offset+9] = make_float4(ob->dupli_generated[0], ob->dupli_generated[1], ob->dupli_generated[2], __int_as_float(numkeys));
343                 objects[offset+10] = make_float4(ob->dupli_uv[0], ob->dupli_uv[1], __int_as_float(numsteps), __int_as_float(numverts));
344
345                 /* object flag */
346                 if(ob->use_holdout)
347                         flag |= SD_HOLDOUT_MASK;
348                 object_flag[i] = flag;
349
350                 /* have curves */
351                 if(mesh->curves.size())
352                         have_curves = true;
353
354                 i++;
355
356                 if(progress.get_cancel()) return;
357         }
358
359         device->tex_alloc("__objects", dscene->objects);
360         if(need_motion == Scene::MOTION_PASS)
361                 device->tex_alloc("__objects_vector", dscene->objects_vector);
362
363         dscene->data.bvh.have_motion = have_motion;
364         dscene->data.bvh.have_curves = have_curves;
365         dscene->data.bvh.have_instancing = true;
366 }
367
368 void ObjectManager::device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
369 {
370         if(!need_update)
371                 return;
372         
373         device_free(device, dscene);
374
375         need_update = false;
376
377         if(scene->objects.size() == 0)
378                 return;
379
380         /* object info flag */
381         uint *object_flag = dscene->object_flag.resize(scene->objects.size());
382
383         /* set object transform matrices, before applying static transforms */
384         progress.set_status("Updating Objects", "Copying Transformations to device");
385         device_update_transforms(device, dscene, scene, object_flag, progress);
386
387         if(progress.get_cancel()) return;
388
389         /* prepare for static BVH building */
390         /* todo: do before to support getting object level coords? */
391         if(scene->params.bvh_type == SceneParams::BVH_STATIC) {
392                 progress.set_status("Updating Objects", "Applying Static Transformations");
393                 apply_static_transforms(dscene, scene, object_flag, progress);
394         }
395
396         /* allocate object flag */
397         device->tex_alloc("__object_flag", dscene->object_flag);
398 }
399
400 void ObjectManager::device_free(Device *device, DeviceScene *dscene)
401 {
402         device->tex_free(dscene->objects);
403         dscene->objects.clear();
404
405         device->tex_free(dscene->objects_vector);
406         dscene->objects_vector.clear();
407
408         device->tex_free(dscene->object_flag);
409         dscene->object_flag.clear();
410 }
411
412 void ObjectManager::apply_static_transforms(DeviceScene *dscene, Scene *scene, uint *object_flag, Progress& progress)
413 {
414         /* todo: normals and displacement should be done before applying transform! */
415         /* todo: create objects/meshes in right order! */
416
417         /* counter mesh users */
418         map<Mesh*, int> mesh_users;
419 #ifdef __OBJECT_MOTION__
420         Scene::MotionType need_motion = scene->need_motion();
421         bool motion_blur = need_motion == Scene::MOTION_BLUR;
422         bool apply_to_motion = need_motion != Scene::MOTION_PASS;
423 #else
424         bool motion_blur = false;
425 #endif
426         int i = 0;
427         bool have_instancing = false;
428
429         foreach(Object *object, scene->objects) {
430                 map<Mesh*, int>::iterator it = mesh_users.find(object->mesh);
431
432                 if(it == mesh_users.end())
433                         mesh_users[object->mesh] = 1;
434                 else
435                         it->second++;
436         }
437
438         if(progress.get_cancel()) return;
439
440         /* apply transforms for objects with single user meshes */
441         foreach(Object *object, scene->objects) {
442                 if(mesh_users[object->mesh] == 1) {
443                         if(!(motion_blur && object->use_motion)) {
444                                 if(!object->mesh->transform_applied) {
445                                         object->apply_transform(apply_to_motion);
446                                         object->mesh->transform_applied = true;
447
448                                         if(progress.get_cancel()) return;
449                                 }
450
451                                 object_flag[i] |= SD_TRANSFORM_APPLIED;
452                         }
453                         else
454                                 have_instancing = true;
455                 }
456                 else
457                         have_instancing = true;
458
459                 i++;
460         }
461
462         dscene->data.bvh.have_instancing = have_instancing;
463 }
464
465 void ObjectManager::tag_update(Scene *scene)
466 {
467         need_update = true;
468         scene->curve_system_manager->need_update = true;
469         scene->mesh_manager->need_update = true;
470         scene->light_manager->need_update = true;
471 }
472
473 CCL_NAMESPACE_END
474