Merge branch 'master' into blender2.8
[blender.git] / intern / cycles / kernel / osl / osl_services.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 /* TODO(sergey): There is a bit of headers dependency hell going on
18  * here, so for now we just put here. In the future it might be better
19  * to have dedicated file for such tweaks.
20  */
21 #if (defined(__GNUC__) && !defined(__clang__)) && defined(NDEBUG)
22 #  pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
23 #  pragma GCC diagnostic ignored "-Wuninitialized"
24 #endif
25
26 #include <string.h>
27
28 #include "render/mesh.h"
29 #include "render/object.h"
30 #include "render/scene.h"
31
32 #include "kernel/osl/osl_closures.h"
33 #include "kernel/osl/osl_globals.h"
34 #include "kernel/osl/osl_services.h"
35 #include "kernel/osl/osl_shader.h"
36
37 #include "util/util_foreach.h"
38 #include "util/util_logging.h"
39 #include "util/util_string.h"
40
41 #include "kernel/kernel_compat_cpu.h"
42 #include "kernel/split/kernel_split_data_types.h"
43 #include "kernel/kernel_globals.h"
44 #include "kernel/kernel_color.h"
45 #include "kernel/kernel_random.h"
46 #include "kernel/kernel_projection.h"
47 #include "kernel/kernel_differential.h"
48 #include "kernel/kernel_montecarlo.h"
49 #include "kernel/kernel_camera.h"
50 #include "kernel/kernels/cpu/kernel_cpu_image.h"
51 #include "kernel/geom/geom.h"
52 #include "kernel/bvh/bvh.h"
53
54 #include "kernel/kernel_projection.h"
55 #include "kernel/kernel_accumulate.h"
56 #include "kernel/kernel_shader.h"
57
58 #ifdef WITH_PTEX
59 #  include <Ptexture.h>
60 #endif
61
62 CCL_NAMESPACE_BEGIN
63
64 /* RenderServices implementation */
65
66 static void copy_matrix(OSL::Matrix44& m, const Transform& tfm)
67 {
68         ProjectionTransform t = projection_transpose(ProjectionTransform(tfm));
69         memcpy((void *)&m, &t, sizeof(m));
70 }
71
72 static void copy_matrix(OSL::Matrix44& m, const ProjectionTransform& tfm)
73 {
74         ProjectionTransform t = projection_transpose(tfm);
75         memcpy((void *)&m, &t, sizeof(m));
76 }
77
78 /* static ustrings */
79 ustring OSLRenderServices::u_distance("distance");
80 ustring OSLRenderServices::u_index("index");
81 ustring OSLRenderServices::u_world("world");
82 ustring OSLRenderServices::u_camera("camera");
83 ustring OSLRenderServices::u_screen("screen");
84 ustring OSLRenderServices::u_raster("raster");
85 ustring OSLRenderServices::u_ndc("NDC");
86 ustring OSLRenderServices::u_object_location("object:location");
87 ustring OSLRenderServices::u_object_index("object:index");
88 ustring OSLRenderServices::u_geom_dupli_generated("geom:dupli_generated");
89 ustring OSLRenderServices::u_geom_dupli_uv("geom:dupli_uv");
90 ustring OSLRenderServices::u_material_index("material:index");
91 ustring OSLRenderServices::u_object_random("object:random");
92 ustring OSLRenderServices::u_particle_index("particle:index");
93 ustring OSLRenderServices::u_particle_random("particle:random");
94 ustring OSLRenderServices::u_particle_age("particle:age");
95 ustring OSLRenderServices::u_particle_lifetime("particle:lifetime");
96 ustring OSLRenderServices::u_particle_location("particle:location");
97 ustring OSLRenderServices::u_particle_rotation("particle:rotation");
98 ustring OSLRenderServices::u_particle_size("particle:size");
99 ustring OSLRenderServices::u_particle_velocity("particle:velocity");
100 ustring OSLRenderServices::u_particle_angular_velocity("particle:angular_velocity");
101 ustring OSLRenderServices::u_geom_numpolyvertices("geom:numpolyvertices");
102 ustring OSLRenderServices::u_geom_trianglevertices("geom:trianglevertices");
103 ustring OSLRenderServices::u_geom_polyvertices("geom:polyvertices");
104 ustring OSLRenderServices::u_geom_name("geom:name");
105 ustring OSLRenderServices::u_geom_undisplaced("geom:undisplaced");
106 ustring OSLRenderServices::u_is_smooth("geom:is_smooth");
107 ustring OSLRenderServices::u_is_curve("geom:is_curve");
108 ustring OSLRenderServices::u_curve_thickness("geom:curve_thickness");
109 ustring OSLRenderServices::u_curve_tangent_normal("geom:curve_tangent_normal");
110 ustring OSLRenderServices::u_curve_random("geom:curve_random");
111 ustring OSLRenderServices::u_path_ray_length("path:ray_length");
112 ustring OSLRenderServices::u_path_ray_depth("path:ray_depth");
113 ustring OSLRenderServices::u_path_diffuse_depth("path:diffuse_depth");
114 ustring OSLRenderServices::u_path_glossy_depth("path:glossy_depth");
115 ustring OSLRenderServices::u_path_transparent_depth("path:transparent_depth");
116 ustring OSLRenderServices::u_path_transmission_depth("path:transmission_depth");
117 ustring OSLRenderServices::u_trace("trace");
118 ustring OSLRenderServices::u_hit("hit");
119 ustring OSLRenderServices::u_hitdist("hitdist");
120 ustring OSLRenderServices::u_N("N");
121 ustring OSLRenderServices::u_Ng("Ng");
122 ustring OSLRenderServices::u_P("P");
123 ustring OSLRenderServices::u_I("I");
124 ustring OSLRenderServices::u_u("u");
125 ustring OSLRenderServices::u_v("v");
126 ustring OSLRenderServices::u_empty;
127 ustring OSLRenderServices::u_at_bevel("@bevel");
128 ustring OSLRenderServices::u_at_ao("@ao");
129
130 OSLRenderServices::OSLRenderServices()
131 {
132         kernel_globals = NULL;
133         osl_ts = NULL;
134
135 #ifdef WITH_PTEX
136         size_t maxmem = 16384 * 1024;
137         ptex_cache = PtexCache::create(0, maxmem);
138 #endif
139 }
140
141 OSLRenderServices::~OSLRenderServices()
142 {
143         if(osl_ts) {
144                 VLOG(2) << "OSL texture system stats:\n"
145                         << osl_ts->getstats();
146         }
147 #ifdef WITH_PTEX
148         ptex_cache->release();
149 #endif
150 }
151
152 void OSLRenderServices::thread_init(KernelGlobals *kernel_globals_, OSL::TextureSystem *osl_ts_)
153 {
154         kernel_globals = kernel_globals_;
155         osl_ts = osl_ts_;
156 }
157
158 bool OSLRenderServices::get_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, OSL::TransformationPtr xform, float time)
159 {
160         /* this is only used for shader and object space, we don't really have
161          * a concept of shader space, so we just use object space for both. */
162         if(xform) {
163                 const ShaderData *sd = (const ShaderData *)xform;
164                 KernelGlobals *kg = sd->osl_globals;
165                 int object = sd->object;
166
167                 if(object != OBJECT_NONE) {
168 #ifdef __OBJECT_MOTION__
169                         Transform tfm;
170
171                         if(time == sd->time)
172                                 tfm = sd->ob_tfm;
173                         else
174                                 tfm = object_fetch_transform_motion_test(kg, object, time, NULL);
175 #else
176                         Transform tfm = object_fetch_transform(kg, object, OBJECT_TRANSFORM);
177 #endif
178                         copy_matrix(result, tfm);
179
180                         return true;
181                 }
182                 else if(sd->type == PRIMITIVE_LAMP) {
183                         copy_matrix(result, sd->ob_tfm);
184
185                         return true;
186                 }
187         }
188
189         return false;
190 }
191
192 bool OSLRenderServices::get_inverse_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, OSL::TransformationPtr xform, float time)
193 {
194         /* this is only used for shader and object space, we don't really have
195          * a concept of shader space, so we just use object space for both. */
196         if(xform) {
197                 const ShaderData *sd = (const ShaderData *)xform;
198                 KernelGlobals *kg = sd->osl_globals;
199                 int object = sd->object;
200
201                 if(object != OBJECT_NONE) {
202 #ifdef __OBJECT_MOTION__
203                         Transform itfm;
204
205                         if(time == sd->time)
206                                 itfm = sd->ob_itfm;
207                         else
208                                 object_fetch_transform_motion_test(kg, object, time, &itfm);
209 #else
210                         Transform itfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM);
211 #endif
212                         copy_matrix(result, itfm);
213
214                         return true;
215                 }
216                 else if(sd->type == PRIMITIVE_LAMP) {
217                         copy_matrix(result, sd->ob_itfm);
218
219                         return true;
220                 }
221         }
222
223         return false;
224 }
225
226 bool OSLRenderServices::get_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, ustring from, float time)
227 {
228         KernelGlobals *kg = kernel_globals;
229
230         if(from == u_ndc) {
231                 copy_matrix(result, kernel_data.cam.ndctoworld);
232                 return true;
233         }
234         else if(from == u_raster) {
235                 copy_matrix(result, kernel_data.cam.rastertoworld);
236                 return true;
237         }
238         else if(from == u_screen) {
239                 copy_matrix(result, kernel_data.cam.screentoworld);
240                 return true;
241         }
242         else if(from == u_camera) {
243                 copy_matrix(result, kernel_data.cam.cameratoworld);
244                 return true;
245         }
246         else if(from == u_world) {
247                 result.makeIdentity();
248                 return true;
249         }
250
251         return false;
252 }
253
254 bool OSLRenderServices::get_inverse_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, ustring to, float time)
255 {
256         KernelGlobals *kg = kernel_globals;
257
258         if(to == u_ndc) {
259                 copy_matrix(result, kernel_data.cam.worldtondc);
260                 return true;
261         }
262         else if(to == u_raster) {
263                 copy_matrix(result, kernel_data.cam.worldtoraster);
264                 return true;
265         }
266         else if(to == u_screen) {
267                 copy_matrix(result, kernel_data.cam.worldtoscreen);
268                 return true;
269         }
270         else if(to == u_camera) {
271                 copy_matrix(result, kernel_data.cam.worldtocamera);
272                 return true;
273         }
274         else if(to == u_world) {
275                 result.makeIdentity();
276                 return true;
277         }
278
279         return false;
280 }
281
282 bool OSLRenderServices::get_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, OSL::TransformationPtr xform)
283 {
284         /* this is only used for shader and object space, we don't really have
285          * a concept of shader space, so we just use object space for both. */
286         if(xform) {
287                 const ShaderData *sd = (const ShaderData *)xform;
288                 int object = sd->object;
289
290                 if(object != OBJECT_NONE) {
291 #ifdef __OBJECT_MOTION__
292                         Transform tfm = sd->ob_tfm;
293 #else
294                         KernelGlobals *kg = sd->osl_globals;
295                         Transform tfm = object_fetch_transform(kg, object, OBJECT_TRANSFORM);
296 #endif
297                         copy_matrix(result, tfm);
298
299                         return true;
300                 }
301                 else if(sd->type == PRIMITIVE_LAMP) {
302                         copy_matrix(result, sd->ob_tfm);
303
304                         return true;
305                 }
306         }
307
308         return false;
309 }
310
311 bool OSLRenderServices::get_inverse_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, OSL::TransformationPtr xform)
312 {
313         /* this is only used for shader and object space, we don't really have
314          * a concept of shader space, so we just use object space for both. */
315         if(xform) {
316                 const ShaderData *sd = (const ShaderData *)xform;
317                 int object = sd->object;
318
319                 if(object != OBJECT_NONE) {
320 #ifdef __OBJECT_MOTION__
321                         Transform tfm = sd->ob_itfm;
322 #else
323                         KernelGlobals *kg = sd->osl_globals;
324                         Transform tfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM);
325 #endif
326                         copy_matrix(result, tfm);
327
328                         return true;
329                 }
330                 else if(sd->type == PRIMITIVE_LAMP) {
331                         copy_matrix(result, sd->ob_itfm);
332
333                         return true;
334                 }
335         }
336
337         return false;
338 }
339
340 bool OSLRenderServices::get_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, ustring from)
341 {
342         KernelGlobals *kg = kernel_globals;
343
344         if(from == u_ndc) {
345                 copy_matrix(result, kernel_data.cam.ndctoworld);
346                 return true;
347         }
348         else if(from == u_raster) {
349                 copy_matrix(result, kernel_data.cam.rastertoworld);
350                 return true;
351         }
352         else if(from == u_screen) {
353                 copy_matrix(result, kernel_data.cam.screentoworld);
354                 return true;
355         }
356         else if(from == u_camera) {
357                 copy_matrix(result, kernel_data.cam.cameratoworld);
358                 return true;
359         }
360
361         return false;
362 }
363
364 bool OSLRenderServices::get_inverse_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, ustring to)
365 {
366         KernelGlobals *kg = kernel_globals;
367         
368         if(to == u_ndc) {
369                 copy_matrix(result, kernel_data.cam.worldtondc);
370                 return true;
371         }
372         else if(to == u_raster) {
373                 copy_matrix(result, kernel_data.cam.worldtoraster);
374                 return true;
375         }
376         else if(to == u_screen) {
377                 copy_matrix(result, kernel_data.cam.worldtoscreen);
378                 return true;
379         }
380         else if(to == u_camera) {
381                 copy_matrix(result, kernel_data.cam.worldtocamera);
382                 return true;
383         }
384         
385         return false;
386 }
387
388 bool OSLRenderServices::get_array_attribute(OSL::ShaderGlobals *sg, bool derivatives, 
389                                             ustring object, TypeDesc type, ustring name,
390                                             int index, void *val)
391 {
392         return false;
393 }
394
395 static bool set_attribute_float3(float3 f[3], TypeDesc type, bool derivatives, void *val)
396 {
397         if(type == TypeDesc::TypePoint || type == TypeDesc::TypeVector ||
398            type == TypeDesc::TypeNormal || type == TypeDesc::TypeColor)
399         {
400                 float *fval = (float *)val;
401
402                 fval[0] = f[0].x;
403                 fval[1] = f[0].y;
404                 fval[2] = f[0].z;
405
406                 if(derivatives) {
407                         fval[3] = f[1].x;
408                         fval[4] = f[1].y;
409                         fval[5] = f[1].z;
410
411                         fval[6] = f[2].x;
412                         fval[7] = f[2].y;
413                         fval[8] = f[2].z;
414                 }
415
416                 return true;
417         }
418         else if(type == TypeDesc::TypeFloat) {
419                 float *fval = (float *)val;
420                 fval[0] = average(f[0]);
421
422                 if(derivatives) {
423                         fval[1] = average(f[1]);
424                         fval[2] = average(f[2]);
425                 }
426
427                 return true;
428         }
429
430         return false;
431 }
432
433 static bool set_attribute_float3(float3 f, TypeDesc type, bool derivatives, void *val)
434 {
435         float3 fv[3];
436
437         fv[0] = f;
438         fv[1] = make_float3(0.0f, 0.0f, 0.0f);
439         fv[2] = make_float3(0.0f, 0.0f, 0.0f);
440
441         return set_attribute_float3(fv, type, derivatives, val);
442 }
443
444 static bool set_attribute_float(float f[3], TypeDesc type, bool derivatives, void *val)
445 {
446         if(type == TypeDesc::TypePoint || type == TypeDesc::TypeVector ||
447            type == TypeDesc::TypeNormal || type == TypeDesc::TypeColor)
448         {
449                 float *fval = (float *)val;
450                 fval[0] = f[0];
451                 fval[1] = f[1];
452                 fval[2] = f[2];
453
454                 if(derivatives) {
455                         fval[3] = f[1];
456                         fval[4] = f[1];
457                         fval[5] = f[1];
458
459                         fval[6] = f[2];
460                         fval[7] = f[2];
461                         fval[8] = f[2];
462                 }
463
464                 return true;
465         }
466         else if(type == TypeDesc::TypeFloat) {
467                 float *fval = (float *)val;
468                 fval[0] = f[0];
469
470                 if(derivatives) {
471                         fval[1] = f[1];
472                         fval[2] = f[2];
473                 }
474
475                 return true;
476         }
477
478         return false;
479 }
480
481 static bool set_attribute_float(float f, TypeDesc type, bool derivatives, void *val)
482 {
483         float fv[3];
484
485         fv[0] = f;
486         fv[1] = 0.0f;
487         fv[2] = 0.0f;
488
489         return set_attribute_float(fv, type, derivatives, val);
490 }
491
492 static bool set_attribute_int(int i, TypeDesc type, bool derivatives, void *val)
493 {
494         if(type.basetype == TypeDesc::INT && type.aggregate == TypeDesc::SCALAR && type.arraylen == 0) {
495                 int *ival = (int *)val;
496                 ival[0] = i;
497
498                 if(derivatives) {
499                         ival[1] = 0;
500                         ival[2] = 0;
501                 }
502
503                 return true;
504         }
505
506         return false;
507 }
508
509 static bool set_attribute_string(ustring str, TypeDesc type, bool derivatives, void *val)
510 {
511         if(type.basetype == TypeDesc::STRING && type.aggregate == TypeDesc::SCALAR && type.arraylen == 0) {
512                 ustring *sval = (ustring *)val;
513                 sval[0] = str;
514
515                 if(derivatives) {
516                         sval[1] = OSLRenderServices::u_empty;
517                         sval[2] = OSLRenderServices::u_empty;
518                 }
519
520                 return true;
521         }
522
523         return false;
524 }
525
526 static bool set_attribute_float3_3(float3 P[3], TypeDesc type, bool derivatives, void *val)
527 {
528         if(type.vecsemantics == TypeDesc::POINT && type.arraylen >= 3) {
529                 float *fval = (float *)val;
530
531                 fval[0] = P[0].x;
532                 fval[1] = P[0].y;
533                 fval[2] = P[0].z;
534
535                 fval[3] = P[1].x;
536                 fval[4] = P[1].y;
537                 fval[5] = P[1].z;
538
539                 fval[6] = P[2].x;
540                 fval[7] = P[2].y;
541                 fval[8] = P[2].z;
542
543                 if(type.arraylen > 3)
544                         memset(fval + 3*3, 0, sizeof(float)*3*(type.arraylen - 3));
545                 if(derivatives)
546                         memset(fval + type.arraylen*3, 0, sizeof(float)*2*3*type.arraylen);
547
548                 return true;
549         }
550
551         return false;
552 }
553
554 static bool set_attribute_matrix(const Transform& tfm, TypeDesc type, void *val)
555 {
556         if(type == TypeDesc::TypeMatrix) {
557                 copy_matrix(*(OSL::Matrix44*)val, tfm);
558                 return true;
559         }
560
561         return false;
562 }
563
564 static bool get_mesh_element_attribute(KernelGlobals *kg, const ShaderData *sd, const OSLGlobals::Attribute& attr,
565                                const TypeDesc& type, bool derivatives, void *val)
566 {
567         if(attr.type == TypeDesc::TypePoint || attr.type == TypeDesc::TypeVector ||
568            attr.type == TypeDesc::TypeNormal || attr.type == TypeDesc::TypeColor)
569         {
570                 float3 fval[3];
571                 fval[0] = primitive_attribute_float3(kg, sd, attr.desc,
572                                                      (derivatives) ? &fval[1] : NULL, (derivatives) ? &fval[2] : NULL);
573                 return set_attribute_float3(fval, type, derivatives, val);
574         }
575         else if(attr.type == TypeDesc::TypeFloat) {
576                 float fval[3];
577                 fval[0] = primitive_attribute_float(kg, sd, attr.desc,
578                                                     (derivatives) ? &fval[1] : NULL, (derivatives) ? &fval[2] : NULL);
579                 return set_attribute_float(fval, type, derivatives, val);
580         }
581         else {
582                 return false;
583         }
584 }
585
586 static bool get_mesh_attribute(KernelGlobals *kg, const ShaderData *sd, const OSLGlobals::Attribute& attr,
587                                const TypeDesc& type, bool derivatives, void *val)
588 {
589         if(attr.type == TypeDesc::TypeMatrix) {
590                 Transform tfm = primitive_attribute_matrix(kg, sd, attr.desc);
591                 return set_attribute_matrix(tfm, type, val);
592         }
593         else {
594                 return false;
595         }
596 }
597
598 static void get_object_attribute(const OSLGlobals::Attribute& attr, bool derivatives, void *val)
599 {
600         size_t datasize = attr.value.datasize();
601
602         memcpy(val, attr.value.data(), datasize);
603         if(derivatives)
604                 memset((char *)val + datasize, 0, datasize * 2);
605 }
606
607 bool OSLRenderServices::get_object_standard_attribute(KernelGlobals *kg, ShaderData *sd, ustring name,
608                                                       TypeDesc type, bool derivatives, void *val)
609 {
610         /* todo: turn this into hash table? */
611
612         /* Object Attributes */
613         if(name == u_object_location) {
614                 float3 f = object_location(kg, sd);
615                 return set_attribute_float3(f, type, derivatives, val);
616         }
617         else if(name == u_object_index) {
618                 float f = object_pass_id(kg, sd->object);
619                 return set_attribute_float(f, type, derivatives, val);
620         }
621         else if(name == u_geom_dupli_generated) {
622                 float3 f = object_dupli_generated(kg, sd->object);
623                 return set_attribute_float3(f, type, derivatives, val);
624         }
625         else if(name == u_geom_dupli_uv) {
626                 float3 f = object_dupli_uv(kg, sd->object);
627                 return set_attribute_float3(f, type, derivatives, val);
628         }
629         else if(name == u_material_index) {
630                 float f = shader_pass_id(kg, sd);
631                 return set_attribute_float(f, type, derivatives, val);
632         }
633         else if(name == u_object_random) {
634                 float f = object_random_number(kg, sd->object);
635                 return set_attribute_float(f, type, derivatives, val);
636         }
637
638         /* Particle Attributes */
639         else if(name == u_particle_index) {
640                 int particle_id = object_particle_id(kg, sd->object);
641                 float f = particle_index(kg, particle_id);
642                 return set_attribute_float(f, type, derivatives, val);
643         }
644         else if(name == u_particle_random) {
645                 int particle_id = object_particle_id(kg, sd->object);
646                 float f = hash_int_01(particle_index(kg, particle_id));
647                 return set_attribute_float(f, type, derivatives, val);
648         }
649
650         else if(name == u_particle_age) {
651                 int particle_id = object_particle_id(kg, sd->object);
652                 float f = particle_age(kg, particle_id);
653                 return set_attribute_float(f, type, derivatives, val);
654         }
655         else if(name == u_particle_lifetime) {
656                 int particle_id = object_particle_id(kg, sd->object);
657                 float f = particle_lifetime(kg, particle_id);
658                 return set_attribute_float(f, type, derivatives, val);
659         }
660         else if(name == u_particle_location) {
661                 int particle_id = object_particle_id(kg, sd->object);
662                 float3 f = particle_location(kg, particle_id);
663                 return set_attribute_float3(f, type, derivatives, val);
664         }
665 #if 0   /* unsupported */
666         else if(name == u_particle_rotation) {
667                 int particle_id = object_particle_id(kg, sd->object);
668                 float4 f = particle_rotation(kg, particle_id);
669                 return set_attribute_float4(f, type, derivatives, val);
670         }
671 #endif
672         else if(name == u_particle_size) {
673                 int particle_id = object_particle_id(kg, sd->object);
674                 float f = particle_size(kg, particle_id);
675                 return set_attribute_float(f, type, derivatives, val);
676         }
677         else if(name == u_particle_velocity) {
678                 int particle_id = object_particle_id(kg, sd->object);
679                 float3 f = particle_velocity(kg, particle_id);
680                 return set_attribute_float3(f, type, derivatives, val);
681         }
682         else if(name == u_particle_angular_velocity) {
683                 int particle_id = object_particle_id(kg, sd->object);
684                 float3 f = particle_angular_velocity(kg, particle_id);
685                 return set_attribute_float3(f, type, derivatives, val);
686         }
687         
688         /* Geometry Attributes */
689         else if(name == u_geom_numpolyvertices) {
690                 return set_attribute_int(3, type, derivatives, val);
691         }
692         else if((name == u_geom_trianglevertices || name == u_geom_polyvertices)
693                      && sd->type & PRIMITIVE_ALL_TRIANGLE)
694         {
695                 float3 P[3];
696
697                 if(sd->type & PRIMITIVE_TRIANGLE)
698                         triangle_vertices(kg, sd->prim, P);
699                 else
700                         motion_triangle_vertices(kg, sd->object, sd->prim, sd->time, P);
701
702                 if(!(sd->object_flag & SD_OBJECT_TRANSFORM_APPLIED)) {
703                         object_position_transform(kg, sd, &P[0]);
704                         object_position_transform(kg, sd, &P[1]);
705                         object_position_transform(kg, sd, &P[2]);
706                 }
707
708                 return set_attribute_float3_3(P, type, derivatives, val);
709         }
710         else if(name == u_geom_name) {
711                 ustring object_name = kg->osl->object_names[sd->object];
712                 return set_attribute_string(object_name, type, derivatives, val);
713         }
714         else if(name == u_is_smooth) {
715                 float f = ((sd->shader & SHADER_SMOOTH_NORMAL) != 0);
716                 return set_attribute_float(f, type, derivatives, val);
717         }
718         /* Hair Attributes */
719         else if(name == u_is_curve) {
720                 float f = (sd->type & PRIMITIVE_ALL_CURVE) != 0;
721                 return set_attribute_float(f, type, derivatives, val);
722         }
723         else if(name == u_curve_thickness) {
724                 float f = curve_thickness(kg, sd);
725                 return set_attribute_float(f, type, derivatives, val);
726         }
727         else if(name == u_curve_tangent_normal) {
728                 float3 f = curve_tangent_normal(kg, sd);
729                 return set_attribute_float3(f, type, derivatives, val);
730         }
731         else
732                 return false;
733 }
734
735 bool OSLRenderServices::get_background_attribute(KernelGlobals *kg, ShaderData *sd, ustring name,
736                                                  TypeDesc type, bool derivatives, void *val)
737 {
738         if(name == u_path_ray_length) {
739                 /* Ray Length */
740                 float f = sd->ray_length;
741                 return set_attribute_float(f, type, derivatives, val);
742         }
743         else if(name == u_path_ray_depth) {
744                 /* Ray Depth */
745                 PathState *state = sd->osl_path_state;
746                 int f = state->bounce;
747                 return set_attribute_int(f, type, derivatives, val);
748         }
749         else if(name == u_path_diffuse_depth) {
750                 /* Diffuse Ray Depth */
751                 PathState *state = sd->osl_path_state;
752                 int f = state->diffuse_bounce;
753                 return set_attribute_int(f, type, derivatives, val);
754         }
755         else if(name == u_path_glossy_depth) {
756                 /* Glossy Ray Depth */
757                 PathState *state = sd->osl_path_state;
758                 int f = state->glossy_bounce;
759                 return set_attribute_int(f, type, derivatives, val);
760         }
761         else if(name == u_path_transmission_depth) {
762                 /* Transmission Ray Depth */
763                 PathState *state = sd->osl_path_state;
764                 int f = state->transmission_bounce;
765                 return set_attribute_int(f, type, derivatives, val);
766         }
767         else if(name == u_path_transparent_depth) {
768                 /* Transparent Ray Depth */
769                 PathState *state = sd->osl_path_state;
770                 int f = state->transparent_bounce;
771                 return set_attribute_int(f, type, derivatives, val);
772         }
773         else if(name == u_path_transmission_depth) {
774                 /* Transmission Ray Depth */
775                 PathState *state = sd->osl_path_state;
776                 int f = state->transmission_bounce;
777                 return set_attribute_int(f, type, derivatives, val);
778         }
779         else if(name == u_ndc) {
780                 /* NDC coordinates with special exception for otho */
781                 OSLThreadData *tdata = kg->osl_tdata;
782                 OSL::ShaderGlobals *globals = &tdata->globals;
783                 float3 ndc[3];
784
785                 if((globals->raytype & PATH_RAY_CAMERA) && sd->object == OBJECT_NONE && kernel_data.cam.type == CAMERA_ORTHOGRAPHIC) {
786                         ndc[0] = camera_world_to_ndc(kg, sd, sd->ray_P);
787
788                         if(derivatives) {
789                                 ndc[1] = camera_world_to_ndc(kg, sd, sd->ray_P + sd->ray_dP.dx) - ndc[0];
790                                 ndc[2] = camera_world_to_ndc(kg, sd, sd->ray_P + sd->ray_dP.dy) - ndc[0];
791                         }
792                 }
793                 else {
794                         ndc[0] = camera_world_to_ndc(kg, sd, sd->P);
795
796                         if(derivatives) {
797                                 ndc[1] = camera_world_to_ndc(kg, sd, sd->P + sd->dP.dx) - ndc[0];
798                                 ndc[2] = camera_world_to_ndc(kg, sd, sd->P + sd->dP.dy) - ndc[0];
799                         }
800                 }
801
802                 return set_attribute_float3(ndc, type, derivatives, val);
803         }
804         else
805                 return false;
806 }
807
808 bool OSLRenderServices::get_attribute(OSL::ShaderGlobals *sg, bool derivatives, ustring object_name,
809                                       TypeDesc type, ustring name, void *val)
810 {
811         if(sg == NULL || sg->renderstate == NULL)
812                 return false;
813
814         ShaderData *sd = (ShaderData *)(sg->renderstate);
815         return get_attribute(sd, derivatives, object_name, type, name, val);
816 }
817
818 bool OSLRenderServices::get_attribute(ShaderData *sd, bool derivatives, ustring object_name,
819                                       TypeDesc type, ustring name, void *val)
820 {
821         KernelGlobals *kg = sd->osl_globals;
822         int prim_type = 0;
823         int object;
824
825         /* lookup of attribute on another object */
826         if(object_name != u_empty) {
827                 OSLGlobals::ObjectNameMap::iterator it = kg->osl->object_name_map.find(object_name);
828
829                 if(it == kg->osl->object_name_map.end())
830                         return false;
831
832                 object = it->second;
833         }
834         else {
835                 object = sd->object;
836                 prim_type = attribute_primitive_type(kg, sd);
837
838                 if(object == OBJECT_NONE)
839                         return get_background_attribute(kg, sd, name, type, derivatives, val);
840         }
841
842         /* find attribute on object */
843         object = object*ATTR_PRIM_TYPES + prim_type;
844         OSLGlobals::AttributeMap& attribute_map = kg->osl->attribute_map[object];
845         OSLGlobals::AttributeMap::iterator it = attribute_map.find(name);
846
847         if(it != attribute_map.end()) {
848                 const OSLGlobals::Attribute& attr = it->second;
849
850                 if(attr.desc.element != ATTR_ELEMENT_OBJECT) {
851                         /* triangle and vertex attributes */
852                         if(get_mesh_element_attribute(kg, sd, attr, type, derivatives, val))
853                                 return true;
854                         else
855                                 return get_mesh_attribute(kg, sd, attr, type, derivatives, val);
856                 }
857                 else {
858                         /* object attribute */
859                         get_object_attribute(attr, derivatives, val);
860                         return true;
861                 }
862         }
863         else {
864                 /* not found in attribute, check standard object info */
865                 bool is_std_object_attribute = get_object_standard_attribute(kg, sd, name, type, derivatives, val);
866
867                 if(is_std_object_attribute)
868                         return true;
869
870                 return get_background_attribute(kg, sd, name, type, derivatives, val);
871         }
872
873         return false;
874 }
875
876 bool OSLRenderServices::get_userdata(bool derivatives, ustring name, TypeDesc type, 
877                                      OSL::ShaderGlobals *sg, void *val)
878 {
879         return false; /* disabled by lockgeom */
880 }
881
882 bool OSLRenderServices::has_userdata(ustring name, TypeDesc type, OSL::ShaderGlobals *sg)
883 {
884         return false; /* never called by OSL */
885 }
886
887 bool OSLRenderServices::texture(ustring filename,
888                                 TextureHandle *texture_handle,
889                                 TexturePerthread *texture_thread_info,
890                                 TextureOpt &options,
891                                 OSL::ShaderGlobals *sg,
892                                 float s, float t,
893                                 float dsdx, float dtdx, float dsdy, float dtdy,
894                                 int nchannels,
895                                 float *result,
896                                 float *dresultds,
897                                 float *dresultdt)
898 {
899         OSL::TextureSystem *ts = osl_ts;
900         ShaderData *sd = (ShaderData *)(sg->renderstate);
901         KernelGlobals *kg = sd->osl_globals;
902
903         if(texture_thread_info == NULL) {
904                 OSLThreadData *tdata = kg->osl_tdata;
905                 texture_thread_info = tdata->oiio_thread_info;
906         }
907
908 #ifdef WITH_PTEX
909         /* todo: this is just a quick hack, only works with particular files and options */
910         if(string_endswith(filename.string(), ".ptx")) {
911                 float2 uv;
912                 int faceid;
913
914                 if(!primitive_ptex(kg, sd, &uv, &faceid))
915                         return false;
916
917                 float u = uv.x;
918                 float v = uv.y;
919                 float dudx = 0.0f;
920                 float dvdx = 0.0f;
921                 float dudy = 0.0f;
922                 float dvdy = 0.0f;
923
924                 Ptex::String error;
925                 PtexPtr<PtexTexture> r(ptex_cache->get(filename.c_str(), error));
926
927                 if(!r) {
928                         //std::cerr << error.c_str() << std::endl;
929                         return false;
930                 }
931
932                 bool mipmaplerp = false;
933                 float sharpness = 1.0f;
934                 PtexFilter::Options opts(PtexFilter::f_bicubic, mipmaplerp, sharpness);
935                 PtexPtr<PtexFilter> f(PtexFilter::getFilter(r, opts));
936
937                 f->eval(result, options.firstchannel, nchannels, faceid, u, v, dudx, dvdx, dudy, dvdy);
938
939                 for(int c = r->numChannels(); c < nchannels; c++)
940                         result[c] = result[0];
941
942                 return true;
943         }
944 #endif
945         bool status = false;
946
947         if(filename.length() && filename[0] == '@') {
948                 if(filename == u_at_bevel) {
949                         /* Bevel shader hack. */
950                         if(nchannels >= 3) {
951                                 PathState *state = sd->osl_path_state;
952                                 int num_samples = (int)s;
953                                 float radius = t;
954                                 float3 N = svm_bevel(kg, sd, state, radius, num_samples);
955                                 result[0] = N.x;
956                                 result[1] = N.y;
957                                 result[2] = N.z;
958                                 status = true;
959                         }
960                 }
961                 else if(filename == u_at_ao) {
962                         /* AO shader hack. */
963                         PathState *state = sd->osl_path_state;
964                         int num_samples = (int)s;
965                         float radius = t;
966                         float3 N = make_float3(dsdx, dtdx, dsdy);
967                         int flags = 0;
968                         if((int)dtdy) {
969                                 flags |= NODE_AO_INSIDE;
970                         }
971                         if((int)options.sblur) {
972                                 flags |= NODE_AO_ONLY_LOCAL;
973                         }
974                         if((int)options.tblur) {
975                                 flags |= NODE_AO_GLOBAL_RADIUS;
976                         }
977                         result[0] = svm_ao(kg, sd, N, state, radius, num_samples, flags);
978                         status = true;
979                 }
980                 else if(filename[1] == 'l') {
981                         /* IES light. */
982                         int slot = atoi(filename.c_str() + 2);
983                         result[0] = kernel_ies_interp(kg, slot, s, t);
984                         status = true;
985                 }
986                 else {
987                         /* Packed texture. */
988                         int slot = atoi(filename.c_str() + 2);
989                         float4 rgba = kernel_tex_image_interp(kg, slot, s, 1.0f - t);
990
991                         result[0] = rgba[0];
992                         if(nchannels > 1)
993                                 result[1] = rgba[1];
994                         if(nchannels > 2)
995                                 result[2] = rgba[2];
996                         if(nchannels > 3)
997                                 result[3] = rgba[3];
998                         status = true;
999                 }
1000         }
1001         else {
1002                 if(texture_handle != NULL) {
1003                         status = ts->texture(texture_handle,
1004                                              texture_thread_info,
1005                                              options,
1006                                              s, t,
1007                                              dsdx, dtdx,
1008                                              dsdy, dtdy,
1009                                              nchannels,
1010                                              result,
1011                                              dresultds, dresultdt);
1012                 }
1013                 else {
1014                         status = ts->texture(filename,
1015                                              options,
1016                                              s, t,
1017                                              dsdx, dtdx,
1018                                              dsdy, dtdy,
1019                                              nchannels,
1020                                              result,
1021                                              dresultds, dresultdt);
1022                 }
1023         }
1024
1025         if(!status) {
1026                 if(nchannels == 3 || nchannels == 4) {
1027                         result[0] = 1.0f;
1028                         result[1] = 0.0f;
1029                         result[2] = 1.0f;
1030
1031                         if(nchannels == 4)
1032                                 result[3] = 1.0f;
1033                 }
1034                 /* This might be slow, but prevents error messages leak and
1035                  * other nasty stuff happening.
1036                  */
1037                 string err = ts->geterror();
1038                 (void)err;
1039         }
1040
1041         return status;
1042 }
1043
1044 bool OSLRenderServices::texture3d(ustring filename,
1045                                   TextureHandle *texture_handle,
1046                                   TexturePerthread *texture_thread_info,
1047                                   TextureOpt &options,
1048                                   OSL::ShaderGlobals *sg,
1049                                   const OSL::Vec3 &P,
1050                                   const OSL::Vec3 &dPdx,
1051                                   const OSL::Vec3 &dPdy,
1052                                   const OSL::Vec3 &dPdz,
1053                                   int nchannels,
1054                                   float *result,
1055                                   float *dresultds,
1056                                   float *dresultdt,
1057                                   float *dresultdr)
1058 {
1059         OSL::TextureSystem *ts = osl_ts;
1060         ShaderData *sd = (ShaderData *)(sg->renderstate);
1061         KernelGlobals *kg = sd->osl_globals;
1062
1063         if(texture_thread_info == NULL) {
1064                 OSLThreadData *tdata = kg->osl_tdata;
1065                 texture_thread_info = tdata->oiio_thread_info;
1066         }
1067
1068         bool status;
1069         if(filename.length() && filename[0] == '@') {
1070                 int slot = atoi(filename.c_str() + 1);
1071                 float4 rgba = kernel_tex_image_interp_3d(kg, slot, P.x, P.y, P.z, INTERPOLATION_NONE);
1072
1073                 result[0] = rgba[0];
1074                 if(nchannels > 1)
1075                         result[1] = rgba[1];
1076                 if(nchannels > 2)
1077                         result[2] = rgba[2];
1078                 if(nchannels > 3)
1079                         result[3] = rgba[3];
1080                 status = true;
1081         }
1082         else {
1083                 if(texture_handle != NULL) {
1084                         status = ts->texture3d(texture_handle,
1085                                                texture_thread_info,
1086                                                options,
1087                                                P,
1088                                                dPdx, dPdy, dPdz,
1089                                                nchannels,
1090                                                result,
1091                                                dresultds, dresultdt, dresultdr);
1092                 }
1093                 else {
1094                         status = ts->texture3d(filename,
1095                                                options,
1096                                                P,
1097                                                dPdx, dPdy, dPdz,
1098                                                nchannels,
1099                                                result,
1100                                                dresultds, dresultdt, dresultdr);
1101                 }
1102         }
1103
1104         if(!status) {
1105                 if(nchannels == 3 || nchannels == 4) {
1106                         result[0] = 1.0f;
1107                         result[1] = 0.0f;
1108                         result[2] = 1.0f;
1109
1110                         if(nchannels == 4)
1111                                 result[3] = 1.0f;
1112                 }
1113                 /* This might be slow, but prevents error messages leak and
1114                  * other nasty stuff happening.
1115                  */
1116                 string err = ts->geterror();
1117                 (void)err;
1118         }
1119
1120         return status;
1121 }
1122
1123 bool OSLRenderServices::environment(ustring filename, TextureOpt &options,
1124                                     OSL::ShaderGlobals *sg, const OSL::Vec3 &R,
1125                                     const OSL::Vec3 &dRdx, const OSL::Vec3 &dRdy,
1126                                     int nchannels, float *result)
1127 {
1128         OSL::TextureSystem *ts = osl_ts;
1129         ShaderData *sd = (ShaderData *)(sg->renderstate);
1130         KernelGlobals *kg = sd->osl_globals;
1131         OSLThreadData *tdata = kg->osl_tdata;
1132         OIIO::TextureSystem::Perthread *thread_info = tdata->oiio_thread_info;
1133
1134         OIIO::TextureSystem::TextureHandle *th = ts->get_texture_handle(filename, thread_info);
1135
1136         bool status = ts->environment(th, thread_info,
1137                                       options, R, dRdx, dRdy,
1138                                       nchannels, result);
1139
1140         if(!status) {
1141                 if(nchannels == 3 || nchannels == 4) {
1142                         result[0] = 1.0f;
1143                         result[1] = 0.0f;
1144                         result[2] = 1.0f;
1145
1146                         if(nchannels == 4)
1147                                 result[3] = 1.0f;
1148                 }
1149         }
1150
1151         return status;
1152 }
1153
1154 bool OSLRenderServices::get_texture_info(OSL::ShaderGlobals *sg, ustring filename, int subimage,
1155                                          ustring dataname,
1156                                          TypeDesc datatype, void *data)
1157 {
1158         OSL::TextureSystem *ts = osl_ts;
1159         return ts->get_texture_info(filename, subimage, dataname, datatype, data);
1160 }
1161
1162 int OSLRenderServices::pointcloud_search(OSL::ShaderGlobals *sg, ustring filename, const OSL::Vec3 &center,
1163                                          float radius, int max_points, bool sort,
1164                                          size_t *out_indices, float *out_distances, int derivs_offset)
1165 {
1166         return 0;
1167 }
1168
1169 int OSLRenderServices::pointcloud_get(OSL::ShaderGlobals *sg, ustring filename, size_t *indices, int count,
1170                                       ustring attr_name, TypeDesc attr_type, void *out_data)
1171 {
1172         return 0;
1173 }
1174
1175 bool OSLRenderServices::pointcloud_write(OSL::ShaderGlobals *sg,
1176                                          ustring filename, const OSL::Vec3 &pos,
1177                                          int nattribs, const ustring *names,
1178                                          const TypeDesc *types,
1179                                          const void **data)
1180 {
1181         return false;
1182 }
1183
1184 bool OSLRenderServices::trace(TraceOpt &options, OSL::ShaderGlobals *sg,
1185         const OSL::Vec3 &P, const OSL::Vec3 &dPdx,
1186         const OSL::Vec3 &dPdy, const OSL::Vec3 &R,
1187         const OSL::Vec3 &dRdx, const OSL::Vec3 &dRdy)
1188 {
1189         /* todo: options.shader support, maybe options.traceset */
1190         ShaderData *sd = (ShaderData *)(sg->renderstate);
1191
1192         /* setup ray */
1193         Ray ray;
1194
1195         ray.P = TO_FLOAT3(P);
1196         ray.D = TO_FLOAT3(R);
1197         ray.t = (options.maxdist == 1.0e30f)? FLT_MAX: options.maxdist - options.mindist;
1198         ray.time = sd->time;
1199
1200         if(options.mindist == 0.0f) {
1201                 /* avoid self-intersections */
1202                 if(ray.P == sd->P) {
1203                         bool transmit = (dot(sd->Ng, ray.D) < 0.0f);
1204                         ray.P = ray_offset(sd->P, (transmit)? -sd->Ng: sd->Ng);
1205                 }
1206         }
1207         else {
1208                 /* offset for minimum distance */
1209                 ray.P += options.mindist*ray.D;
1210         }
1211
1212         /* ray differentials */
1213         ray.dP.dx = TO_FLOAT3(dPdx);
1214         ray.dP.dy = TO_FLOAT3(dPdy);
1215         ray.dD.dx = TO_FLOAT3(dRdx);
1216         ray.dD.dy = TO_FLOAT3(dRdy);
1217
1218         /* allocate trace data */
1219         OSLTraceData *tracedata = (OSLTraceData*)sg->tracedata;
1220         tracedata->ray = ray;
1221         tracedata->setup = false;
1222         tracedata->init = true;
1223         tracedata->sd.osl_globals = sd->osl_globals;
1224
1225         /* Raytrace, leaving out shadow opaque to avoid early exit. */
1226         uint visibility = PATH_RAY_ALL_VISIBILITY - PATH_RAY_SHADOW_OPAQUE;
1227         return scene_intersect(sd->osl_globals, ray, visibility, &tracedata->isect, NULL, 0.0f, 0.0f);
1228 }
1229
1230
1231 bool OSLRenderServices::getmessage(OSL::ShaderGlobals *sg, ustring source, ustring name,
1232         TypeDesc type, void *val, bool derivatives)
1233 {
1234         OSLTraceData *tracedata = (OSLTraceData*)sg->tracedata;
1235
1236         if(source == u_trace && tracedata->init) {
1237                 if(name == u_hit) {
1238                         return set_attribute_int((tracedata->isect.prim != PRIM_NONE), type, derivatives, val);
1239                 }
1240                 else if(tracedata->isect.prim != PRIM_NONE) {
1241                         if(name == u_hitdist) {
1242                                 float f[3] = {tracedata->isect.t, 0.0f, 0.0f};
1243                                 return set_attribute_float(f, type, derivatives, val);
1244                         }
1245                         else {
1246                                 ShaderData *sd = &tracedata->sd;
1247                                 KernelGlobals *kg = sd->osl_globals;
1248
1249                                 if(!tracedata->setup) {
1250                                         /* lazy shader data setup */
1251                                         shader_setup_from_ray(kg, sd, &tracedata->isect, &tracedata->ray);
1252                                         tracedata->setup = true;
1253                                 }
1254
1255                                 if(name == u_N) {
1256                                         return set_attribute_float3(sd->N, type, derivatives, val);
1257                                 }
1258                                 else if(name == u_Ng) {
1259                                         return set_attribute_float3(sd->Ng, type, derivatives, val);
1260                                 }
1261                                 else if(name == u_P) {
1262                                         float3 f[3] = {sd->P, sd->dP.dx, sd->dP.dy};
1263                                         return set_attribute_float3(f, type, derivatives, val);
1264                                 }
1265                                 else if(name == u_I) {
1266                                         float3 f[3] = {sd->I, sd->dI.dx, sd->dI.dy};
1267                                         return set_attribute_float3(f, type, derivatives, val);
1268                                 }
1269                                 else if(name == u_u) {
1270                                         float f[3] = {sd->u, sd->du.dx, sd->du.dy};
1271                                         return set_attribute_float(f, type, derivatives, val);
1272                                 }
1273                                 else if(name == u_v) {
1274                                         float f[3] = {sd->v, sd->dv.dx, sd->dv.dy};
1275                                         return set_attribute_float(f, type, derivatives, val);
1276                                 }
1277
1278                                 return get_attribute(sd, derivatives, u_empty, type, name, val);
1279                         }
1280                 }
1281         }
1282
1283         return false;
1284 }
1285
1286 CCL_NAMESPACE_END