Depsgraph: remove EvaluationContext, pass Depsgraph instead.
[blender.git] / source / blender / render / intern / source / render_texture.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): 2004-2006, Blender Foundation, full recode
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/render/intern/source/render_texture.c
27  *  \ingroup render
28  */
29
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <math.h>
35
36 #include "BLI_math.h"
37 #include "BLI_noise.h"
38 #include "BLI_rand.h"
39 #include "BLI_utildefines.h"
40
41 #include "DNA_anim_types.h"
42 #include "DNA_texture_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_lamp_types.h"
45 #include "DNA_meshdata_types.h"
46 #include "DNA_material_types.h"
47 #include "DNA_image_types.h"
48 #include "DNA_node_types.h"
49
50 #include "IMB_imbuf_types.h"
51 #include "IMB_colormanagement.h"
52
53 #include "BKE_image.h"
54 #include "BKE_node.h"
55
56 #include "BKE_animsys.h"
57 #include "BKE_colorband.h"
58 #include "BKE_DerivedMesh.h"
59 #include "BKE_global.h"
60 #include "BKE_main.h"
61 #include "BKE_material.h"
62 #include "BKE_scene.h"
63
64 #include "BKE_texture.h"
65
66 #include "MEM_guardedalloc.h"
67
68 #include "envmap.h"
69 #include "pointdensity.h"
70 #include "voxeldata.h"
71 #include "render_types.h"
72 #include "shading.h"
73 #include "texture.h"
74 #include "texture_ocean.h"
75
76 #include "renderdatabase.h" /* needed for UV */
77
78 #include "RE_render_ext.h"
79
80 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
81 /* defined in pipeline.c, is hardcopy of active dynamic allocated Render */
82 /* only to be used here in this file, it's for speed */
83 extern struct Render R;
84 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
85
86 static RNG_THREAD_ARRAY *random_tex_array;
87
88
89 void RE_texture_rng_init(void)
90 {
91         random_tex_array = BLI_rng_threaded_new();
92 }
93
94 void RE_texture_rng_exit(void)
95 {
96         BLI_rng_threaded_free(random_tex_array);
97 }
98
99
100 static void init_render_texture(Render *re, Tex *tex)
101 {
102         /* imap test */
103         if (tex->ima && BKE_image_is_animated(tex->ima)) {
104                 BKE_image_user_frame_calc(&tex->iuser, re ? re->r.cfra : 0, re ? re->flag & R_SEC_FIELD:0);
105         }
106         
107         else if (tex->type==TEX_ENVMAP) {
108                 /* just in case */
109                 tex->imaflag |= TEX_INTERPOL | TEX_MIPMAP;
110                 tex->extend= TEX_CLIP;
111                 
112                 if (tex->env) {
113                         if (tex->env->type==ENV_PLANE)
114                                 tex->extend= TEX_EXTEND;
115                         
116                         /* only free envmap when rendermode was set to render envmaps, for previewrender */
117                         if (G.is_rendering && re) {
118                                 if (re->r.mode & R_ENVMAP)
119                                         if (tex->env->stype==ENV_ANIM)
120                                                 BKE_texture_envmap_free_data(tex->env);
121                         }
122                 }
123         }
124         
125         if (tex->nodetree && tex->use_nodes) {
126                 ntreeTexBeginExecTree(tex->nodetree); /* has internal flag to detect it only does it once */
127         }
128 }
129
130 /* ------------------------------------------------------------------------- */
131
132 void init_render_textures(Render *re)
133 {
134         Tex *tex;
135         
136         tex= re->main->tex.first;
137         while (tex) {
138                 if (tex->id.us) init_render_texture(re, tex);
139                 tex= tex->id.next;
140         }
141 }
142
143 static void end_render_texture(Tex *tex)
144 {
145         if (tex && tex->use_nodes && tex->nodetree && tex->nodetree->execdata)
146                 ntreeTexEndExecTree(tex->nodetree->execdata);
147 }
148
149 void end_render_textures(Render *re)
150 {
151         Tex *tex;
152         for (tex= re->main->tex.first; tex; tex= tex->id.next)
153                 if (tex->id.us)
154                         end_render_texture(tex);
155 }
156
157 /* ------------------------------------------------------------------------- */
158
159
160 /* this allows colorbanded textures to control normals as well */
161 static void tex_normal_derivate(Tex *tex, TexResult *texres)
162 {
163         if (tex->flag & TEX_COLORBAND) {
164                 float col[4];
165                 if (BKE_colorband_evaluate(tex->coba, texres->tin, col)) {
166                         float fac0, fac1, fac2, fac3;
167                         
168                         fac0= (col[0]+col[1]+col[2]);
169                         BKE_colorband_evaluate(tex->coba, texres->nor[0], col);
170                         fac1= (col[0]+col[1]+col[2]);
171                         BKE_colorband_evaluate(tex->coba, texres->nor[1], col);
172                         fac2= (col[0]+col[1]+col[2]);
173                         BKE_colorband_evaluate(tex->coba, texres->nor[2], col);
174                         fac3= (col[0]+col[1]+col[2]);
175                         
176                         texres->nor[0]= (fac0 - fac1) / 3.0f;
177                         texres->nor[1]= (fac0 - fac2) / 3.0f;
178                         texres->nor[2]= (fac0 - fac3) / 3.0f;
179                         
180                         return;
181                 }
182         }
183         texres->nor[0]= texres->tin - texres->nor[0];
184         texres->nor[1]= texres->tin - texres->nor[1];
185         texres->nor[2]= texres->tin - texres->nor[2];
186 }
187
188
189
190 static int blend(Tex *tex, const float texvec[3], TexResult *texres)
191 {
192         float x, y, t;
193
194         if (tex->flag & TEX_FLIPBLEND) {
195                 x= texvec[1];
196                 y= texvec[0];
197         }
198         else {
199                 x= texvec[0];
200                 y= texvec[1];
201         }
202
203         if (tex->stype==TEX_LIN) {      /* lin */
204                 texres->tin= (1.0f+x)/2.0f;
205         }
206         else if (tex->stype==TEX_QUAD) {        /* quad */
207                 texres->tin= (1.0f+x)/2.0f;
208                 if (texres->tin<0.0f) texres->tin= 0.0f;
209                 else texres->tin*= texres->tin;
210         }
211         else if (tex->stype==TEX_EASE) {        /* ease */
212                 texres->tin= (1.0f+x)/2.0f;
213                 if (texres->tin<=0.0f) texres->tin= 0.0f;
214                 else if (texres->tin>=1.0f) texres->tin= 1.0f;
215                 else {
216                         t= texres->tin*texres->tin;
217                         texres->tin= (3.0f*t-2.0f*t*texres->tin);
218                 }
219         }
220         else if (tex->stype==TEX_DIAG) { /* diag */
221                 texres->tin= (2.0f+x+y)/4.0f;
222         }
223         else if (tex->stype==TEX_RAD) { /* radial */
224                 texres->tin = (atan2f(y, x) / (float)(2 * M_PI) + 0.5f);
225         }
226         else {  /* sphere TEX_SPHERE */
227                 texres->tin = 1.0f - sqrtf(x * x + y * y + texvec[2] * texvec[2]);
228                 if (texres->tin<0.0f) texres->tin= 0.0f;
229                 if (tex->stype==TEX_HALO) texres->tin*= texres->tin;  /* halo */
230         }
231
232         BRICONT;
233
234         return TEX_INT;
235 }
236
237 /* ------------------------------------------------------------------------- */
238 /* ************************************************************************* */
239
240 /* newnoise: all noisebased types now have different noisebases to choose from */
241
242 static int clouds(Tex *tex, const float texvec[3], TexResult *texres)
243 {
244         int rv = TEX_INT;
245         
246         texres->tin = BLI_gTurbulence(tex->noisesize, texvec[0], texvec[1], texvec[2], tex->noisedepth, (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
247
248         if (texres->nor!=NULL) {
249                 /* calculate bumpnormal */
250                 texres->nor[0] = BLI_gTurbulence(tex->noisesize, texvec[0] + tex->nabla, texvec[1], texvec[2], tex->noisedepth,  (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
251                 texres->nor[1] = BLI_gTurbulence(tex->noisesize, texvec[0], texvec[1] + tex->nabla, texvec[2], tex->noisedepth,  (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
252                 texres->nor[2] = BLI_gTurbulence(tex->noisesize, texvec[0], texvec[1], texvec[2] + tex->nabla, tex->noisedepth,  (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
253                 
254                 tex_normal_derivate(tex, texres);
255                 rv |= TEX_NOR;
256         }
257
258         if (tex->stype==TEX_COLOR) {
259                 /* in this case, int. value should really be computed from color,
260                  * and bumpnormal from that, would be too slow, looks ok as is */
261                 texres->tr = texres->tin;
262                 texres->tg = BLI_gTurbulence(tex->noisesize, texvec[1], texvec[0], texvec[2], tex->noisedepth, (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
263                 texres->tb = BLI_gTurbulence(tex->noisesize, texvec[1], texvec[2], texvec[0], tex->noisedepth, (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
264                 BRICONTRGB;
265                 texres->ta = 1.0;
266                 return (rv | TEX_RGB);
267         }
268
269         BRICONT;
270
271         return rv;
272
273 }
274
275 /* creates a sine wave */
276 static float tex_sin(float a)
277 {
278         a = 0.5f + 0.5f * sinf(a);
279
280         return a;
281 }
282
283 /* creates a saw wave */
284 static float tex_saw(float a)
285 {
286         const float b = 2*M_PI;
287         
288         int n = (int)(a / b);
289         a -= n*b;
290         if (a < 0) a += b;
291         return a / b;
292 }
293
294 /* creates a triangle wave */
295 static float tex_tri(float a)
296 {
297         const float b = 2*M_PI;
298         const float rmax = 1.0;
299         
300         a = rmax - 2.0f*fabsf(floorf((a*(1.0f/b))+0.5f) - (a*(1.0f/b)));
301         
302         return a;
303 }
304
305 /* computes basic wood intensity value at x,y,z */
306 static float wood_int(Tex *tex, float x, float y, float z)
307 {
308         float wi = 0;
309         short wf = tex->noisebasis2;    /* wave form:   TEX_SIN=0,  TEX_SAW=1,  TEX_TRI=2                                                */
310         short wt = tex->stype;                  /* wood type:   TEX_BAND=0, TEX_RING=1, TEX_BANDNOISE=2, TEX_RINGNOISE=3 */
311
312         float (*waveform[3])(float);    /* create array of pointers to waveform functions */
313         waveform[0] = tex_sin;                  /* assign address of tex_sin() function to pointer array */
314         waveform[1] = tex_saw;
315         waveform[2] = tex_tri;
316         
317         if ((wf>TEX_TRI) || (wf<TEX_SIN)) wf=0; /* check to be sure noisebasis2 is initialized ahead of time */
318                 
319         if (wt==TEX_BAND) {
320                 wi = waveform[wf]((x + y + z)*10.0f);
321         }
322         else if (wt==TEX_RING) {
323                 wi = waveform[wf](sqrtf(x*x + y*y + z*z)*20.0f);
324         }
325         else if (wt==TEX_BANDNOISE) {
326                 wi = tex->turbul*BLI_gNoise(tex->noisesize, x, y, z, (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
327                 wi = waveform[wf]((x + y + z)*10.0f + wi);
328         }
329         else if (wt==TEX_RINGNOISE) {
330                 wi = tex->turbul*BLI_gNoise(tex->noisesize, x, y, z, (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
331                 wi = waveform[wf](sqrtf(x*x + y*y + z*z)*20.0f + wi);
332         }
333         
334         return wi;
335 }
336
337 static int wood(Tex *tex, const float texvec[3], TexResult *texres)
338 {
339         int rv=TEX_INT;
340
341         texres->tin = wood_int(tex, texvec[0], texvec[1], texvec[2]);
342         if (texres->nor!=NULL) {
343                 /* calculate bumpnormal */
344                 texres->nor[0] = wood_int(tex, texvec[0] + tex->nabla, texvec[1], texvec[2]);
345                 texres->nor[1] = wood_int(tex, texvec[0], texvec[1] + tex->nabla, texvec[2]);
346                 texres->nor[2] = wood_int(tex, texvec[0], texvec[1], texvec[2] + tex->nabla);
347                 
348                 tex_normal_derivate(tex, texres);
349                 rv |= TEX_NOR;
350         }
351
352         BRICONT;
353
354         return rv;
355 }
356
357 /* computes basic marble intensity at x,y,z */
358 static float marble_int(Tex *tex, float x, float y, float z)
359 {
360         float n, mi;
361         short wf = tex->noisebasis2;    /* wave form:   TEX_SIN=0,  TEX_SAW=1,  TEX_TRI=2                                               */
362         short mt = tex->stype;                  /* marble type: TEX_SOFT=0,     TEX_SHARP=1,TEX_SHAPER=2                                        */
363         
364         float (*waveform[3])(float);    /* create array of pointers to waveform functions */
365         waveform[0] = tex_sin;                  /* assign address of tex_sin() function to pointer array */
366         waveform[1] = tex_saw;
367         waveform[2] = tex_tri;
368         
369         if ((wf>TEX_TRI) || (wf<TEX_SIN)) wf=0; /* check to be sure noisebasis2 isn't initialized ahead of time */
370         
371         n = 5.0f * (x + y + z);
372         
373         mi = n + tex->turbul * BLI_gTurbulence(tex->noisesize, x, y, z, tex->noisedepth, (tex->noisetype!=TEX_NOISESOFT),  tex->noisebasis);
374
375         if (mt>=TEX_SOFT) {  /* TEX_SOFT always true */
376                 mi = waveform[wf](mi);
377                 if (mt==TEX_SHARP) {
378                         mi = sqrtf(mi);
379                 }
380                 else if (mt==TEX_SHARPER) {
381                         mi = sqrtf(sqrtf(mi));
382                 }
383         }
384
385         return mi;
386 }
387
388 static int marble(Tex *tex, const float texvec[3], TexResult *texres)
389 {
390         int rv=TEX_INT;
391
392         texres->tin = marble_int(tex, texvec[0], texvec[1], texvec[2]);
393
394         if (texres->nor!=NULL) {
395                 /* calculate bumpnormal */
396                 texres->nor[0] = marble_int(tex, texvec[0] + tex->nabla, texvec[1], texvec[2]);
397                 texres->nor[1] = marble_int(tex, texvec[0], texvec[1] + tex->nabla, texvec[2]);
398                 texres->nor[2] = marble_int(tex, texvec[0], texvec[1], texvec[2] + tex->nabla);
399                 
400                 tex_normal_derivate(tex, texres);
401                 
402                 rv |= TEX_NOR;
403         }
404
405         BRICONT;
406
407         return rv;
408 }
409
410 /* ------------------------------------------------------------------------- */
411
412 static int magic(Tex *tex, const float texvec[3], TexResult *texres)
413 {
414         float x, y, z, turb;
415         int n;
416
417         n= tex->noisedepth;
418         turb= tex->turbul/5.0f;
419
420         x =  sinf(( texvec[0] + texvec[1] + texvec[2]) * 5.0f);
421         y =  cosf((-texvec[0] + texvec[1] - texvec[2]) * 5.0f);
422         z = -cosf((-texvec[0] - texvec[1] + texvec[2]) * 5.0f);
423         if (n>0) {
424                 x*= turb;
425                 y*= turb;
426                 z*= turb;
427                 y= -cosf(x-y+z);
428                 y*= turb;
429                 if (n>1) {
430                         x= cosf(x-y-z);
431                         x*= turb;
432                         if (n>2) {
433                                 z= sinf(-x-y-z);
434                                 z*= turb;
435                                 if (n>3) {
436                                         x= -cosf(-x+y-z);
437                                         x*= turb;
438                                         if (n>4) {
439                                                 y= -sinf(-x+y+z);
440                                                 y*= turb;
441                                                 if (n>5) {
442                                                         y= -cosf(-x+y+z);
443                                                         y*= turb;
444                                                         if (n>6) {
445                                                                 x= cosf(x+y+z);
446                                                                 x*= turb;
447                                                                 if (n>7) {
448                                                                         z= sinf(x+y-z);
449                                                                         z*= turb;
450                                                                         if (n>8) {
451                                                                                 x= -cosf(-x-y+z);
452                                                                                 x*= turb;
453                                                                                 if (n>9) {
454                                                                                         y= -sinf(x-y+z);
455                                                                                         y*= turb;
456                                                                                 }
457                                                                         }
458                                                                 }
459                                                         }
460                                                 }
461                                         }
462                                 }
463                         }
464                 }
465         }
466
467         if (turb!=0.0f) {
468                 turb*= 2.0f;
469                 x/= turb; 
470                 y/= turb; 
471                 z/= turb;
472         }
473         texres->tr = 0.5f - x;
474         texres->tg = 0.5f - y;
475         texres->tb = 0.5f - z;
476
477         texres->tin= (1.0f / 3.0f) * (texres->tr + texres->tg + texres->tb);
478         
479         BRICONTRGB;
480         texres->ta = 1.0f;
481         
482         return TEX_RGB;
483 }
484
485 /* ------------------------------------------------------------------------- */
486
487 /* newnoise: stucci also modified to use different noisebasis */
488 static int stucci(Tex *tex, const float texvec[3], TexResult *texres)
489 {
490         float nor[3], b2, ofs;
491         int retval= TEX_INT;
492         
493         b2= BLI_gNoise(tex->noisesize, texvec[0], texvec[1], texvec[2], (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
494         
495         ofs= tex->turbul/200.0f;
496
497         if (tex->stype) ofs*=(b2*b2);
498         nor[0] = BLI_gNoise(tex->noisesize, texvec[0]+ofs, texvec[1], texvec[2], (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
499         nor[1] = BLI_gNoise(tex->noisesize, texvec[0], texvec[1]+ofs, texvec[2], (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
500         nor[2] = BLI_gNoise(tex->noisesize, texvec[0], texvec[1], texvec[2]+ofs, (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
501
502         texres->tin= nor[2];
503         
504         if (texres->nor) {
505                 
506                 copy_v3_v3(texres->nor, nor);
507                 tex_normal_derivate(tex, texres);
508                 
509                 if (tex->stype==TEX_WALLOUT) {
510                         texres->nor[0]= -texres->nor[0];
511                         texres->nor[1]= -texres->nor[1];
512                         texres->nor[2]= -texres->nor[2];
513                 }
514                 
515                 retval |= TEX_NOR;
516         }
517         
518         if (tex->stype==TEX_WALLOUT)
519                 texres->tin= 1.0f-texres->tin;
520         
521         if (texres->tin<0.0f)
522                 texres->tin= 0.0f;
523         
524         return retval;
525 }
526
527 /* ------------------------------------------------------------------------- */
528 /* newnoise: musgrave terrain noise types */
529
530 static float mg_mFractalOrfBmTex(Tex *tex, const float texvec[3], TexResult *texres)
531 {
532         int rv = TEX_INT;
533         float (*mgravefunc)(float, float, float, float, float, float, int);
534
535         if (tex->stype==TEX_MFRACTAL)
536                 mgravefunc = mg_MultiFractal;
537         else
538                 mgravefunc = mg_fBm;
539
540         texres->tin = tex->ns_outscale*mgravefunc(texvec[0], texvec[1], texvec[2], tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->noisebasis);
541
542         if (texres->nor!=NULL) {
543                 float offs= tex->nabla/tex->noisesize;  /* also scaling of texvec */
544
545                 /* calculate bumpnormal */
546                 texres->nor[0] = tex->ns_outscale*mgravefunc(texvec[0] + offs, texvec[1], texvec[2], tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->noisebasis);
547                 texres->nor[1] = tex->ns_outscale*mgravefunc(texvec[0], texvec[1] + offs, texvec[2], tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->noisebasis);
548                 texres->nor[2] = tex->ns_outscale*mgravefunc(texvec[0], texvec[1], texvec[2] + offs, tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->noisebasis);
549                 
550                 tex_normal_derivate(tex, texres);
551                 rv |= TEX_NOR;
552         }
553
554         BRICONT;
555
556         return rv;
557
558 }
559
560 static float mg_ridgedOrHybridMFTex(Tex *tex, const float texvec[3], TexResult *texres)
561 {
562         int rv = TEX_INT;
563         float (*mgravefunc)(float, float, float, float, float, float, float, float, int);
564
565         if (tex->stype==TEX_RIDGEDMF)
566                 mgravefunc = mg_RidgedMultiFractal;
567         else
568                 mgravefunc = mg_HybridMultiFractal;
569
570         texres->tin = tex->ns_outscale*mgravefunc(texvec[0], texvec[1], texvec[2], tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->mg_offset, tex->mg_gain, tex->noisebasis);
571
572         if (texres->nor!=NULL) {
573                 float offs= tex->nabla/tex->noisesize;  /* also scaling of texvec */
574
575                 /* calculate bumpnormal */
576                 texres->nor[0] = tex->ns_outscale*mgravefunc(texvec[0] + offs, texvec[1], texvec[2], tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->mg_offset, tex->mg_gain, tex->noisebasis);
577                 texres->nor[1] = tex->ns_outscale*mgravefunc(texvec[0], texvec[1] + offs, texvec[2], tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->mg_offset, tex->mg_gain, tex->noisebasis);
578                 texres->nor[2] = tex->ns_outscale*mgravefunc(texvec[0], texvec[1], texvec[2] + offs, tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->mg_offset, tex->mg_gain, tex->noisebasis);
579                 
580                 tex_normal_derivate(tex, texres);
581                 rv |= TEX_NOR;
582         }
583
584         BRICONT;
585
586         return rv;
587
588 }
589
590
591 static float mg_HTerrainTex(Tex *tex, const float texvec[3], TexResult *texres)
592 {
593         int rv = TEX_INT;
594
595         texres->tin = tex->ns_outscale*mg_HeteroTerrain(texvec[0], texvec[1], texvec[2], tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->mg_offset, tex->noisebasis);
596
597         if (texres->nor!=NULL) {
598                 float offs= tex->nabla/tex->noisesize;  /* also scaling of texvec */
599
600                 /* calculate bumpnormal */
601                 texres->nor[0] = tex->ns_outscale*mg_HeteroTerrain(texvec[0] + offs, texvec[1], texvec[2], tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->mg_offset, tex->noisebasis);
602                 texres->nor[1] = tex->ns_outscale*mg_HeteroTerrain(texvec[0], texvec[1] + offs, texvec[2], tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->mg_offset, tex->noisebasis);
603                 texres->nor[2] = tex->ns_outscale*mg_HeteroTerrain(texvec[0], texvec[1], texvec[2] + offs, tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->mg_offset, tex->noisebasis);
604                 
605                 tex_normal_derivate(tex, texres);
606                 rv |= TEX_NOR;
607         }
608
609         BRICONT;
610
611         return rv;
612
613 }
614
615
616 static float mg_distNoiseTex(Tex *tex, const float texvec[3], TexResult *texres)
617 {
618         int rv = TEX_INT;
619
620         texres->tin = mg_VLNoise(texvec[0], texvec[1], texvec[2], tex->dist_amount, tex->noisebasis, tex->noisebasis2);
621
622         if (texres->nor!=NULL) {
623                 float offs= tex->nabla/tex->noisesize;  /* also scaling of texvec */
624
625                 /* calculate bumpnormal */
626                 texres->nor[0] = mg_VLNoise(texvec[0] + offs, texvec[1], texvec[2], tex->dist_amount, tex->noisebasis, tex->noisebasis2);
627                 texres->nor[1] = mg_VLNoise(texvec[0], texvec[1] + offs, texvec[2], tex->dist_amount, tex->noisebasis, tex->noisebasis2);
628                 texres->nor[2] = mg_VLNoise(texvec[0], texvec[1], texvec[2] + offs, tex->dist_amount, tex->noisebasis, tex->noisebasis2);
629
630                 tex_normal_derivate(tex, texres);
631                 rv |= TEX_NOR;
632         }
633
634         BRICONT;
635
636
637         return rv;
638
639 }
640
641
642 /* ------------------------------------------------------------------------- */
643 /* newnoise: Voronoi texture type, probably the slowest, especially with minkovsky, bumpmapping, could be done another way */
644
645 static float voronoiTex(Tex *tex, const float texvec[3], TexResult *texres)
646 {
647         int rv = TEX_INT;
648         float da[4], pa[12];    /* distance and point coordinate arrays of 4 nearest neighbors */
649         float aw1 = fabsf(tex->vn_w1);
650         float aw2 = fabsf(tex->vn_w2);
651         float aw3 = fabsf(tex->vn_w3);
652         float aw4 = fabsf(tex->vn_w4);
653         float sc = (aw1 + aw2 + aw3 + aw4);
654         if (sc!=0.f) sc =  tex->ns_outscale/sc;
655
656         voronoi(texvec[0], texvec[1], texvec[2], da, pa, tex->vn_mexp, tex->vn_distm);
657         texres->tin = sc * fabsf(tex->vn_w1*da[0] + tex->vn_w2*da[1] + tex->vn_w3*da[2] + tex->vn_w4*da[3]);
658
659         if (tex->vn_coltype) {
660                 float ca[3];    /* cell color */
661                 cellNoiseV(pa[0], pa[1], pa[2], ca);
662                 texres->tr = aw1*ca[0];
663                 texres->tg = aw1*ca[1];
664                 texres->tb = aw1*ca[2];
665                 cellNoiseV(pa[3], pa[4], pa[5], ca);
666                 texres->tr += aw2*ca[0];
667                 texres->tg += aw2*ca[1];
668                 texres->tb += aw2*ca[2];
669                 cellNoiseV(pa[6], pa[7], pa[8], ca);
670                 texres->tr += aw3*ca[0];
671                 texres->tg += aw3*ca[1];
672                 texres->tb += aw3*ca[2];
673                 cellNoiseV(pa[9], pa[10], pa[11], ca);
674                 texres->tr += aw4*ca[0];
675                 texres->tg += aw4*ca[1];
676                 texres->tb += aw4*ca[2];
677                 if (tex->vn_coltype>=2) {
678                         float t1 = (da[1]-da[0])*10;
679                         if (t1>1) t1=1;
680                         if (tex->vn_coltype==3) t1*=texres->tin; else t1*=sc;
681                         texres->tr *= t1;
682                         texres->tg *= t1;
683                         texres->tb *= t1;
684                 }
685                 else {
686                         texres->tr *= sc;
687                         texres->tg *= sc;
688                         texres->tb *= sc;
689                 }
690         }
691
692         if (texres->nor!=NULL) {
693                 float offs= tex->nabla/tex->noisesize;  /* also scaling of texvec */
694
695                 /* calculate bumpnormal */
696                 voronoi(texvec[0] + offs, texvec[1], texvec[2], da, pa, tex->vn_mexp,  tex->vn_distm);
697                 texres->nor[0] = sc * fabsf(tex->vn_w1*da[0] + tex->vn_w2*da[1] + tex->vn_w3*da[2] + tex->vn_w4*da[3]);
698                 voronoi(texvec[0], texvec[1] + offs, texvec[2], da, pa, tex->vn_mexp,  tex->vn_distm);
699                 texres->nor[1] = sc * fabsf(tex->vn_w1*da[0] + tex->vn_w2*da[1] + tex->vn_w3*da[2] + tex->vn_w4*da[3]);
700                 voronoi(texvec[0], texvec[1], texvec[2] + offs, da, pa, tex->vn_mexp,  tex->vn_distm);
701                 texres->nor[2] = sc * fabsf(tex->vn_w1*da[0] + tex->vn_w2*da[1] + tex->vn_w3*da[2] + tex->vn_w4*da[3]);
702                 
703                 tex_normal_derivate(tex, texres);
704                 rv |= TEX_NOR;
705         }
706
707         if (tex->vn_coltype) {
708                 BRICONTRGB;
709                 texres->ta = 1.0;
710                 return (rv | TEX_RGB);
711         }
712         
713         BRICONT;
714
715         return rv;
716
717 }
718
719 /* ------------------------------------------------------------------------- */
720
721 static int texnoise(Tex *tex, TexResult *texres, int thread)
722 {
723         float div=3.0;
724         int val, ran, loop, shift = 29;
725         
726         ran=  BLI_rng_thread_rand(random_tex_array, thread);
727         
728         loop= tex->noisedepth;
729
730         /* start from top bits since they have more variance */
731         val= ((ran >> shift) & 3);
732         
733         while (loop--) {
734                 shift -= 2;             
735                 val *= ((ran >> shift) & 3);
736                 div *= 3.0f;
737         }
738         
739         texres->tin= ((float)val)/div;
740
741         BRICONT;
742         return TEX_INT;
743 }
744
745 /* ------------------------------------------------------------------------- */
746
747 static int cubemap_glob(const float n[3], float x, float y, float z, float *adr1, float *adr2)
748 {
749         float x1, y1, z1, nor[3];
750         int ret;
751         
752         if (n==NULL) {
753                 nor[0]= x; nor[1]= y; nor[2]= z;        /* use local render coord */
754         }
755         else {
756                 copy_v3_v3(nor, n);
757         }
758         mul_mat3_m4_v3(R.viewinv, nor);
759
760         x1 = fabsf(nor[0]);
761         y1 = fabsf(nor[1]);
762         z1 = fabsf(nor[2]);
763         
764         if (z1>=x1 && z1>=y1) {
765                 *adr1 = (x + 1.0f) / 2.0f;
766                 *adr2 = (y + 1.0f) / 2.0f;
767                 ret= 0;
768         }
769         else if (y1>=x1 && y1>=z1) {
770                 *adr1 = (x + 1.0f) / 2.0f;
771                 *adr2 = (z + 1.0f) / 2.0f;
772                 ret= 1;
773         }
774         else {
775                 *adr1 = (y + 1.0f) / 2.0f;
776                 *adr2 = (z + 1.0f) / 2.0f;
777                 ret= 2;
778         }
779         return ret;
780 }
781
782 /* ------------------------------------------------------------------------- */
783
784 /* mtex argument only for projection switches */
785 static int cubemap(
786         const MTex *mtex, VlakRen *vlr, const float n[3], float x, float y, float z, float *adr1, float *adr2)
787 {
788         int proj[4]={0, ME_PROJXY, ME_PROJXZ, ME_PROJYZ}, ret= 0;
789         
790         if (vlr) {
791                 int index;
792                 
793                 /* Mesh vertices have such flags, for others we calculate it once based on orco */
794                 if ((vlr->puno & (ME_PROJXY|ME_PROJXZ|ME_PROJYZ))==0) {
795                         /* test for v1, vlr can be faked for baking */
796                         if (vlr->v1 && vlr->v1->orco) {
797                                 float nor[3];
798                                 normal_tri_v3(nor, vlr->v1->orco, vlr->v2->orco, vlr->v3->orco);
799                                 
800                                 if      (fabsf(nor[0]) < fabsf(nor[2]) && fabsf(nor[1]) < fabsf(nor[2])) vlr->puno |= ME_PROJXY;
801                                 else if (fabsf(nor[0]) < fabsf(nor[1]) && fabsf(nor[2]) < fabsf(nor[1])) vlr->puno |= ME_PROJXZ;
802                                 else                                                                     vlr->puno |= ME_PROJYZ;
803                         }
804                         else return cubemap_glob(n, x, y, z, adr1, adr2);
805                 }
806                 
807                 if (mtex) {
808                         /* the mtex->proj{xyz} have type char. maybe this should be wider? */
809                         /* casting to int ensures that the index type is right.            */
810                         index = (int) mtex->projx;
811                         proj[index]= ME_PROJXY;
812
813                         index = (int) mtex->projy;
814                         proj[index]= ME_PROJXZ;
815
816                         index = (int) mtex->projz;
817                         proj[index]= ME_PROJYZ;
818                 }
819                 
820                 if (vlr->puno & proj[1]) {
821                         *adr1 = (x + 1.0f) / 2.0f;
822                         *adr2 = (y + 1.0f) / 2.0f;
823                 }
824                 else if (vlr->puno & proj[2]) {
825                         *adr1 = (x + 1.0f) / 2.0f;
826                         *adr2 = (z + 1.0f) / 2.0f;
827                         ret= 1;
828                 }
829                 else {
830                         *adr1 = (y + 1.0f) / 2.0f;
831                         *adr2 = (z + 1.0f) / 2.0f;
832                         ret= 2;
833                 }
834         }
835         else {
836                 return cubemap_glob(n, x, y, z, adr1, adr2);
837         }
838         
839         return ret;
840 }
841
842 /* ------------------------------------------------------------------------- */
843
844 static int cubemap_ob(Object *ob, const float n[3], float x, float y, float z, float *adr1, float *adr2)
845 {
846         float x1, y1, z1, nor[3];
847         int ret;
848         
849         if (n==NULL) return 0;
850         
851         copy_v3_v3(nor, n);
852         if (ob) mul_mat3_m4_v3(ob->imat, nor);
853         
854         x1 = fabsf(nor[0]);
855         y1 = fabsf(nor[1]);
856         z1 = fabsf(nor[2]);
857         
858         if (z1>=x1 && z1>=y1) {
859                 *adr1 = (x + 1.0f) / 2.0f;
860                 *adr2 = (y + 1.0f) / 2.0f;
861                 ret= 0;
862         }
863         else if (y1>=x1 && y1>=z1) {
864                 *adr1 = (x + 1.0f) / 2.0f;
865                 *adr2 = (z + 1.0f) / 2.0f;
866                 ret= 1;
867         }
868         else {
869                 *adr1 = (y + 1.0f) / 2.0f;
870                 *adr2 = (z + 1.0f) / 2.0f;
871                 ret= 2;
872         }
873         return ret;
874 }
875
876 /* ------------------------------------------------------------------------- */
877
878 static void do_2d_mapping(
879         const MTex *mtex, float texvec[3], VlakRen *vlr, const float n[3], float dxt[3], float dyt[3])
880 {
881         Tex *tex;
882         Object *ob= NULL;
883         float fx, fy, fac1, area[8];
884         int ok, proj, areaflag= 0, wrap, texco;
885         
886         /* mtex variables localized, only cubemap doesn't cooperate yet... */
887         wrap= mtex->mapping;
888         tex= mtex->tex;
889         ob= mtex->object;
890         texco= mtex->texco;
891
892         if (R.osa==0) {
893                 
894                 if (wrap==MTEX_FLAT) {
895                         fx = (texvec[0] + 1.0f) / 2.0f;
896                         fy = (texvec[1] + 1.0f) / 2.0f;
897                 }
898                 else if (wrap == MTEX_TUBE)   map_to_tube( &fx, &fy, texvec[0], texvec[1], texvec[2]);
899                 else if (wrap == MTEX_SPHERE) map_to_sphere(&fx, &fy, texvec[0], texvec[1], texvec[2]);
900                 else {
901                         if      (texco == TEXCO_OBJECT) cubemap_ob(ob, n, texvec[0], texvec[1], texvec[2], &fx, &fy);
902                         else if (texco == TEXCO_GLOB)   cubemap_glob(n, texvec[0], texvec[1], texvec[2], &fx, &fy);
903                         else                            cubemap(mtex, vlr, n, texvec[0], texvec[1], texvec[2], &fx, &fy);
904                 }
905                 
906                 /* repeat */
907                 if (tex->extend==TEX_REPEAT) {
908                         if (tex->xrepeat>1) {
909                                 float origf= fx *= tex->xrepeat;
910                                 
911                                 if (fx>1.0f) fx -= (int)(fx);
912                                 else if (fx<0.0f) fx+= 1-(int)(fx);
913                                 
914                                 if (tex->flag & TEX_REPEAT_XMIR) {
915                                         int orig= (int)floor(origf);
916                                         if (orig & 1)
917                                                 fx= 1.0f-fx;
918                                 }
919                         }
920                         if (tex->yrepeat>1) {
921                                 float origf= fy *= tex->yrepeat;
922                                 
923                                 if (fy>1.0f) fy -= (int)(fy);
924                                 else if (fy<0.0f) fy+= 1-(int)(fy);
925                                 
926                                 if (tex->flag & TEX_REPEAT_YMIR) {
927                                         int orig= (int)floor(origf);
928                                         if (orig & 1)
929                                                 fy= 1.0f-fy;
930                                 }
931                         }
932                 }
933                 /* crop */
934                 if (tex->cropxmin!=0.0f || tex->cropxmax!=1.0f) {
935                         fac1= tex->cropxmax - tex->cropxmin;
936                         fx= tex->cropxmin+ fx*fac1;
937                 }
938                 if (tex->cropymin!=0.0f || tex->cropymax!=1.0f) {
939                         fac1= tex->cropymax - tex->cropymin;
940                         fy= tex->cropymin+ fy*fac1;
941                 }
942
943                 texvec[0]= fx;
944                 texvec[1]= fy;
945         }
946         else {
947                 
948                 if (wrap==MTEX_FLAT) {
949                         fx= (texvec[0] + 1.0f) / 2.0f;
950                         fy= (texvec[1] + 1.0f) / 2.0f;
951                         dxt[0]/= 2.0f;
952                         dxt[1]/= 2.0f;
953                         dxt[2]/= 2.0f;
954                         dyt[0]/= 2.0f;
955                         dyt[1]/= 2.0f;
956                         dyt[2]/= 2.0f;
957                 }
958                 else if (ELEM(wrap, MTEX_TUBE, MTEX_SPHERE)) {
959                         /* exception: the seam behind (y<0.0) */
960                         ok= 1;
961                         if (texvec[1]<=0.0f) {
962                                 fx= texvec[0]+dxt[0];
963                                 fy= texvec[0]+dyt[0];
964                                 if (fx>=0.0f && fy>=0.0f && texvec[0]>=0.0f) {
965                                         /* pass */
966                                 }
967                                 else if (fx<=0.0f && fy<=0.0f && texvec[0]<=0.0f) {
968                                         /* pass */
969                                 }
970                                 else {
971                                         ok = 0;
972                                 }
973                         }
974
975                         if (ok) {
976                                 if (wrap==MTEX_TUBE) {
977                                         map_to_tube(area, area+1, texvec[0], texvec[1], texvec[2]);
978                                         map_to_tube(area + 2, area + 3, texvec[0] + dxt[0], texvec[1] + dxt[1], texvec[2] + dxt[2]);
979                                         map_to_tube(area + 4, area + 5, texvec[0] + dyt[0], texvec[1] + dyt[1], texvec[2] + dyt[2]);
980                                 }
981                                 else {
982                                         map_to_sphere(area, area+1, texvec[0], texvec[1], texvec[2]);
983                                         map_to_sphere(area + 2, area + 3, texvec[0] + dxt[0], texvec[1] + dxt[1], texvec[2] + dxt[2]);
984                                         map_to_sphere(area + 4, area + 5, texvec[0] + dyt[0], texvec[1] + dyt[1], texvec[2] + dyt[2]);
985                                 }
986                                 areaflag= 1;
987                         }
988                         else {
989                                 if (wrap==MTEX_TUBE) map_to_tube( &fx, &fy, texvec[0], texvec[1], texvec[2]);
990                                 else map_to_sphere(&fx, &fy, texvec[0], texvec[1], texvec[2]);
991                                 dxt[0]/= 2.0f;
992                                 dxt[1]/= 2.0f;
993                                 dyt[0]/= 2.0f;
994                                 dyt[1]/= 2.0f;
995                         }
996                 }
997                 else {
998
999                         if (texco==TEXCO_OBJECT) proj = cubemap_ob(ob, n, texvec[0], texvec[1], texvec[2], &fx, &fy);
1000                         else if (texco==TEXCO_GLOB) proj = cubemap_glob(n, texvec[0], texvec[1], texvec[2], &fx, &fy);
1001                         else proj = cubemap(mtex, vlr, n, texvec[0], texvec[1], texvec[2], &fx, &fy);
1002
1003                         if (proj==1) {
1004                                 SWAP(float, dxt[1], dxt[2]);
1005                                 SWAP(float, dyt[1], dyt[2]);
1006                         }
1007                         else if (proj==2) {
1008                                 float f1= dxt[0], f2= dyt[0];
1009                                 dxt[0]= dxt[1];
1010                                 dyt[0]= dyt[1];
1011                                 dxt[1]= dxt[2];
1012                                 dyt[1]= dyt[2];
1013                                 dxt[2]= f1;
1014                                 dyt[2]= f2;
1015                         }
1016
1017                         dxt[0] *= 0.5f;
1018                         dxt[1] *= 0.5f;
1019                         dxt[2] *= 0.5f;
1020
1021                         dyt[0] *= 0.5f;
1022                         dyt[1] *= 0.5f;
1023                         dyt[2] *= 0.5f;
1024
1025                 }
1026                 
1027                 /* if area, then reacalculate dxt[] and dyt[] */
1028                 if (areaflag) {
1029                         fx= area[0]; 
1030                         fy= area[1];
1031                         dxt[0]= area[2]-fx;
1032                         dxt[1]= area[3]-fy;
1033                         dyt[0]= area[4]-fx;
1034                         dyt[1]= area[5]-fy;
1035                 }
1036                 
1037                 /* repeat */
1038                 if (tex->extend==TEX_REPEAT) {
1039                         float max= 1.0f;
1040                         if (tex->xrepeat>1) {
1041                                 float origf= fx *= tex->xrepeat;
1042                                 
1043                                 /* TXF: omit mirror here, see comments in do_material_tex() after do_2d_mapping() call */
1044                                 if (tex->texfilter == TXF_BOX) {
1045                                         if (fx>1.0f) fx -= (int)(fx);
1046                                         else if (fx<0.0f) fx+= 1-(int)(fx);
1047                                 
1048                                         if (tex->flag & TEX_REPEAT_XMIR) {
1049                                                 int orig= (int)floor(origf);
1050                                                 if (orig & 1)
1051                                                         fx= 1.0f-fx;
1052                                         }
1053                                 }
1054                                 
1055                                 max= tex->xrepeat;
1056                                 
1057                                 dxt[0]*= tex->xrepeat;
1058                                 dyt[0]*= tex->xrepeat;
1059                         }
1060                         if (tex->yrepeat>1) {
1061                                 float origf= fy *= tex->yrepeat;
1062                                 
1063                                 /* TXF: omit mirror here, see comments in do_material_tex() after do_2d_mapping() call */
1064                                 if (tex->texfilter == TXF_BOX) {
1065                                         if (fy>1.0f) fy -= (int)(fy);
1066                                         else if (fy<0.0f) fy+= 1-(int)(fy);
1067                                 
1068                                         if (tex->flag & TEX_REPEAT_YMIR) {
1069                                                 int orig= (int)floor(origf);
1070                                                 if (orig & 1)
1071                                                         fy= 1.0f-fy;
1072                                         }
1073                                 }
1074                                 
1075                                 if (max<tex->yrepeat)
1076                                         max= tex->yrepeat;
1077
1078                                 dxt[1]*= tex->yrepeat;
1079                                 dyt[1]*= tex->yrepeat;
1080                         }
1081                         if (max!=1.0f) {
1082                                 dxt[2]*= max;
1083                                 dyt[2]*= max;
1084                         }
1085                         
1086                 }
1087                 /* crop */
1088                 if (tex->cropxmin!=0.0f || tex->cropxmax!=1.0f) {
1089                         fac1= tex->cropxmax - tex->cropxmin;
1090                         fx= tex->cropxmin+ fx*fac1;
1091                         dxt[0]*= fac1;
1092                         dyt[0]*= fac1;
1093                 }
1094                 if (tex->cropymin!=0.0f || tex->cropymax!=1.0f) {
1095                         fac1= tex->cropymax - tex->cropymin;
1096                         fy= tex->cropymin+ fy*fac1;
1097                         dxt[1]*= fac1;
1098                         dyt[1]*= fac1;
1099                 }
1100                 
1101                 texvec[0]= fx;
1102                 texvec[1]= fy;
1103
1104         }
1105 }
1106
1107 /* ************************************** */
1108
1109 static int multitex(Tex *tex,
1110                     float texvec[3],
1111                     float dxt[3], float dyt[3],
1112                     int osatex,
1113                     TexResult *texres,
1114                     const short thread,
1115                     const short which_output,
1116                     struct ImagePool *pool,
1117                     const bool skip_load_image,
1118                     const bool texnode_preview,
1119                     const bool use_nodes)
1120 {
1121         float tmpvec[3];
1122         int retval = 0; /* return value, int:0, col:1, nor:2, everything:3 */
1123
1124         texres->talpha = false;  /* is set when image texture returns alpha (considered premul) */
1125         
1126         if (use_nodes && tex->use_nodes && tex->nodetree) {
1127                 retval = ntreeTexExecTree(tex->nodetree, texres, texvec, dxt, dyt, osatex, thread,
1128                                           tex, which_output, R.r.cfra, texnode_preview, NULL, NULL);
1129         }
1130         else {
1131                 switch (tex->type) {
1132                         case 0:
1133                                 texres->tin= 0.0f;
1134                                 return 0;
1135                         case TEX_CLOUDS:
1136                                 retval = clouds(tex, texvec, texres);
1137                                 break;
1138                         case TEX_WOOD:
1139                                 retval = wood(tex, texvec, texres);
1140                                 break;
1141                         case TEX_MARBLE:
1142                                 retval = marble(tex, texvec, texres);
1143                                 break;
1144                         case TEX_MAGIC:
1145                                 retval = magic(tex, texvec, texres);
1146                                 break;
1147                         case TEX_BLEND:
1148                                 retval = blend(tex, texvec, texres);
1149                                 break;
1150                         case TEX_STUCCI:
1151                                 retval = stucci(tex, texvec, texres);
1152                                 break;
1153                         case TEX_NOISE:
1154                                 retval = texnoise(tex, texres, thread);
1155                                 break;
1156                         case TEX_IMAGE:
1157                                 if (osatex) retval = imagewraposa(tex, tex->ima, NULL, texvec, dxt, dyt, texres, pool, skip_load_image);
1158                                 else        retval = imagewrap(tex, tex->ima, NULL, texvec, texres, pool, skip_load_image);
1159                                 if (tex->ima) {
1160                                         BKE_image_tag_time(tex->ima);
1161                                 }
1162                                 break;
1163                         case TEX_ENVMAP:
1164                                 retval = envmaptex(tex, texvec, dxt, dyt, osatex, texres, pool, skip_load_image);
1165                                 break;
1166                         case TEX_MUSGRAVE:
1167                                 /* newnoise: musgrave types */
1168
1169                                 /* ton: added this, for Blender convention reason.
1170                                  * artificer: added the use of tmpvec to avoid scaling texvec
1171                                  */
1172                                 copy_v3_v3(tmpvec, texvec);
1173                                 mul_v3_fl(tmpvec, 1.0f / tex->noisesize);
1174
1175                                 switch (tex->stype) {
1176                                         case TEX_MFRACTAL:
1177                                         case TEX_FBM:
1178                                                 retval = mg_mFractalOrfBmTex(tex, tmpvec, texres);
1179                                                 break;
1180                                         case TEX_RIDGEDMF:
1181                                         case TEX_HYBRIDMF:
1182                                                 retval = mg_ridgedOrHybridMFTex(tex, tmpvec, texres);
1183                                                 break;
1184                                         case TEX_HTERRAIN:
1185                                                 retval = mg_HTerrainTex(tex, tmpvec, texres);
1186                                                 break;
1187                                 }
1188                                 break;
1189                                 /* newnoise: voronoi type */
1190                         case TEX_VORONOI:
1191                                 /* ton: added this, for Blender convention reason.
1192                                  * artificer: added the use of tmpvec to avoid scaling texvec
1193                                  */
1194                                 copy_v3_v3(tmpvec, texvec);
1195                                 mul_v3_fl(tmpvec, 1.0f / tex->noisesize);
1196
1197                                 retval = voronoiTex(tex, tmpvec, texres);
1198                                 break;
1199                         case TEX_DISTNOISE:
1200                                 /* ton: added this, for Blender convention reason.
1201                                  * artificer: added the use of tmpvec to avoid scaling texvec
1202                                  */
1203                                 copy_v3_v3(tmpvec, texvec);
1204                                 mul_v3_fl(tmpvec, 1.0f / tex->noisesize);
1205
1206                                 retval = mg_distNoiseTex(tex, tmpvec, texres);
1207                                 break;
1208                         case TEX_POINTDENSITY:
1209                                 retval = pointdensitytex(tex, texvec, texres);
1210                                 break;
1211                         case TEX_VOXELDATA:
1212                                 retval = voxeldatatex(tex, texvec, texres);
1213                                 break;
1214                         case TEX_OCEAN:
1215                                 retval = ocean_texture(tex, texvec, texres);
1216                                 break;
1217                 }
1218         }
1219
1220         if (tex->flag & TEX_COLORBAND) {
1221                 float col[4];
1222                 if (BKE_colorband_evaluate(tex->coba, texres->tin, col)) {
1223                         texres->talpha = true;
1224                         texres->tr= col[0];
1225                         texres->tg= col[1];
1226                         texres->tb= col[2];
1227                         texres->ta= col[3];
1228                         retval |= TEX_RGB;
1229                 }
1230         }
1231         return retval;
1232 }
1233
1234 static int multitex_nodes_intern(Tex *tex,
1235                                  float texvec[3],
1236                                  float dxt[3], float dyt[3],
1237                                  int osatex,
1238                                  TexResult *texres,
1239                                  const short thread,
1240                                  short which_output,
1241                                  ShadeInput *shi,
1242                                  MTex *mtex, struct
1243                                  ImagePool *pool,
1244                                  const bool scene_color_manage,
1245                                  const bool skip_load_image,
1246                                  const bool texnode_preview,
1247                                  const bool use_nodes)
1248 {
1249         if (tex==NULL) {
1250                 memset(texres, 0, sizeof(TexResult));
1251                 return 0;
1252         }
1253
1254         if (mtex)
1255                 which_output= mtex->which_output;
1256         
1257         if (tex->type==TEX_IMAGE) {
1258                 int rgbnor;
1259
1260                 if (mtex) {
1261                         /* we have mtex, use it for 2d mapping images only */
1262                         do_2d_mapping(mtex, texvec, shi->vlr, shi->facenor, dxt, dyt);
1263                         rgbnor = multitex(tex,
1264                                           texvec,
1265                                           dxt, dyt,
1266                                           osatex,
1267                                           texres,
1268                                           thread,
1269                                           which_output,
1270                                           pool,
1271                                           skip_load_image,
1272                                           texnode_preview,
1273                                           use_nodes);
1274
1275                         if (mtex->mapto & (MAP_COL+MAP_COLSPEC+MAP_COLMIR)) {
1276                                 ImBuf *ibuf = BKE_image_pool_acquire_ibuf(tex->ima, &tex->iuser, pool);
1277                                 
1278                                 /* don't linearize float buffers, assumed to be linear */
1279                                 if (ibuf != NULL &&
1280                                     ibuf->rect_float == NULL &&
1281                                     (rgbnor & TEX_RGB) &&
1282                                     scene_color_manage)
1283                                 {
1284                                         IMB_colormanagement_colorspace_to_scene_linear_v3(&texres->tr, ibuf->rect_colorspace);
1285                                 }
1286
1287                                 BKE_image_pool_release_ibuf(tex->ima, ibuf, pool);
1288                         }
1289                 }
1290                 else {
1291                         /* we don't have mtex, do default flat 2d projection */
1292                         MTex localmtex;
1293                         float texvec_l[3], dxt_l[3], dyt_l[3];
1294                         
1295                         localmtex.mapping= MTEX_FLAT;
1296                         localmtex.tex= tex;
1297                         localmtex.object= NULL;
1298                         localmtex.texco= TEXCO_ORCO;
1299                         
1300                         copy_v3_v3(texvec_l, texvec);
1301                         if (dxt && dyt) {
1302                                 copy_v3_v3(dxt_l, dxt);
1303                                 copy_v3_v3(dyt_l, dyt);
1304                         }
1305                         else {
1306                                 zero_v3(dxt_l);
1307                                 zero_v3(dyt_l);
1308                         }
1309                         
1310                         do_2d_mapping(&localmtex, texvec_l, NULL, NULL, dxt_l, dyt_l);
1311                         rgbnor = multitex(tex,
1312                                           texvec_l,
1313                                           dxt_l, dyt_l,
1314                                           osatex,
1315                                           texres,
1316                                           thread,
1317                                           which_output,
1318                                           pool,
1319                                           skip_load_image,
1320                                           texnode_preview,
1321                                           use_nodes);
1322
1323                         {
1324                                 ImBuf *ibuf = BKE_image_pool_acquire_ibuf(tex->ima, &tex->iuser, pool);
1325
1326                                 /* don't linearize float buffers, assumed to be linear */
1327                                 if (ibuf != NULL &&
1328                                     ibuf->rect_float == NULL &&
1329                                     (rgbnor & TEX_RGB) &&
1330                                     scene_color_manage)
1331                                 {
1332                                         IMB_colormanagement_colorspace_to_scene_linear_v3(&texres->tr, ibuf->rect_colorspace);
1333                                 }
1334
1335                                 BKE_image_pool_release_ibuf(tex->ima, ibuf, pool);
1336                         }
1337                 }
1338
1339                 return rgbnor;
1340         }
1341         else {
1342                 return multitex(tex,
1343                                 texvec,
1344                                 dxt, dyt,
1345                                 osatex,
1346                                 texres,
1347                                 thread,
1348                                 which_output,
1349                                 pool,
1350                                 skip_load_image,
1351                                 texnode_preview,
1352                                 use_nodes);
1353         }
1354 }
1355
1356 /* this is called from the shader and texture nodes
1357  * Use it from render pipeline only!
1358  */
1359 int multitex_nodes(Tex *tex, float texvec[3], float dxt[3], float dyt[3], int osatex, TexResult *texres,
1360                    const short thread, short which_output, ShadeInput *shi, MTex *mtex, struct ImagePool *pool)
1361 {
1362         return multitex_nodes_intern(tex, texvec, dxt, dyt, osatex, texres,
1363                                      thread, which_output, shi, mtex, pool, R.scene_color_manage,
1364                                      (R.r.scemode & R_NO_IMAGE_LOAD) != 0,
1365                                      (R.r.scemode & R_TEXNODE_PREVIEW) != 0,
1366                                      true);
1367 }
1368
1369 /* this is called for surface shading */
1370 static int multitex_mtex(ShadeInput *shi, MTex *mtex, float texvec[3], float dxt[3], float dyt[3], TexResult *texres, struct ImagePool *pool, const bool skip_load_image)
1371 {
1372         Tex *tex = mtex->tex;
1373         /* TODO(sergey): Texture preview should become an argument? */
1374         if (tex->use_nodes && tex->nodetree) {
1375                 /* stupid exception here .. but we have to pass shi and mtex to
1376                  * textures nodes for 2d mapping and color management for images */
1377                 return ntreeTexExecTree(tex->nodetree, texres, texvec, dxt, dyt, shi->osatex, shi->thread,
1378                                         tex, mtex->which_output, R.r.cfra, (R.r.scemode & R_TEXNODE_PREVIEW) != 0, shi, mtex);
1379         }
1380         else {
1381                 return multitex(mtex->tex,
1382                                 texvec,
1383                                 dxt, dyt,
1384                                 shi->osatex,
1385                                 texres,
1386                                 shi->thread,
1387                                 mtex->which_output,
1388                                 pool,
1389                                 skip_load_image,
1390                                 (R.r.scemode & R_TEXNODE_PREVIEW) != 0,
1391                                 true);
1392         }
1393 }
1394
1395 /* Warning, if the texres's values are not declared zero, check the return value to be sure
1396  * the color values are set before using the r/g/b values, otherwise you may use uninitialized values - Campbell
1397  *
1398  * Use it for stuff which is out of render pipeline.
1399  */
1400 int multitex_ext(Tex *tex,
1401                  float texvec[3],
1402                  float dxt[3], float dyt[3],
1403                  int osatex,
1404                  TexResult *texres,
1405                  const short thread,
1406                  struct ImagePool *pool,
1407                  bool scene_color_manage,
1408                  const bool skip_load_image)
1409 {
1410         return multitex_nodes_intern(tex,
1411                                      texvec,
1412                                      dxt, dyt,
1413                                      osatex,
1414                                      texres,
1415                                      thread,
1416                                      0,
1417                                      NULL, NULL,
1418                                      pool,
1419                                      scene_color_manage,
1420                                      skip_load_image,
1421                                      false,
1422                                      true);
1423 }
1424
1425 /* extern-tex doesn't support nodes (ntreeBeginExec() can't be called when rendering is going on)\
1426  *
1427  * Use it for stuff which is out of render pipeline.
1428  */
1429 int multitex_ext_safe(Tex *tex, float texvec[3], TexResult *texres, struct ImagePool *pool, bool scene_color_manage, const bool skip_load_image)
1430 {
1431         return multitex_nodes_intern(tex,
1432                                      texvec,
1433                                      NULL, NULL,
1434                                      0,
1435                                      texres,
1436                                      0,
1437                                      0,
1438                                      NULL, NULL,
1439                                      pool,
1440                                      scene_color_manage,
1441                                      skip_load_image,
1442                                      false,
1443                                      false);
1444 }
1445
1446
1447 /* ------------------------------------------------------------------------- */
1448
1449 /* in = destination, tex = texture, out = previous color */
1450 /* fact = texture strength, facg = button strength value */
1451 void texture_rgb_blend(float in[3], const float tex[3], const float out[3], float fact, float facg, int blendtype)
1452 {
1453         float facm;
1454         
1455         switch (blendtype) {
1456         case MTEX_BLEND:
1457                 fact*= facg;
1458                 facm= 1.0f-fact;
1459
1460                 in[0]= (fact*tex[0] + facm*out[0]);
1461                 in[1]= (fact*tex[1] + facm*out[1]);
1462                 in[2]= (fact*tex[2] + facm*out[2]);
1463                 break;
1464                 
1465         case MTEX_MUL:
1466                 fact*= facg;
1467                 facm= 1.0f-fact;
1468                 in[0]= (facm+fact*tex[0])*out[0];
1469                 in[1]= (facm+fact*tex[1])*out[1];
1470                 in[2]= (facm+fact*tex[2])*out[2];
1471                 break;
1472
1473         case MTEX_SCREEN:
1474                 fact*= facg;
1475                 facm= 1.0f-fact;
1476                 in[0]= 1.0f - (facm+fact*(1.0f-tex[0])) * (1.0f-out[0]);
1477                 in[1]= 1.0f - (facm+fact*(1.0f-tex[1])) * (1.0f-out[1]);
1478                 in[2]= 1.0f - (facm+fact*(1.0f-tex[2])) * (1.0f-out[2]);
1479                 break;
1480
1481         case MTEX_OVERLAY:
1482                 fact*= facg;
1483                 facm= 1.0f-fact;
1484                 
1485                 if (out[0] < 0.5f)
1486                         in[0] = out[0] * (facm + 2.0f*fact*tex[0]);
1487                 else
1488                         in[0] = 1.0f - (facm + 2.0f*fact*(1.0f - tex[0])) * (1.0f - out[0]);
1489                 if (out[1] < 0.5f)
1490                         in[1] = out[1] * (facm + 2.0f*fact*tex[1]);
1491                 else
1492                         in[1] = 1.0f - (facm + 2.0f*fact*(1.0f - tex[1])) * (1.0f - out[1]);
1493                 if (out[2] < 0.5f)
1494                         in[2] = out[2] * (facm + 2.0f*fact*tex[2]);
1495                 else
1496                         in[2] = 1.0f - (facm + 2.0f*fact*(1.0f - tex[2])) * (1.0f - out[2]);
1497                 break;
1498                 
1499         case MTEX_SUB:
1500                 fact= -fact;
1501                 ATTR_FALLTHROUGH;
1502         case MTEX_ADD:
1503                 fact*= facg;
1504                 in[0]= (fact*tex[0] + out[0]);
1505                 in[1]= (fact*tex[1] + out[1]);
1506                 in[2]= (fact*tex[2] + out[2]);
1507                 break;
1508
1509         case MTEX_DIV:
1510                 fact*= facg;
1511                 facm= 1.0f-fact;
1512                 
1513                 if (tex[0]!=0.0f)
1514                         in[0]= facm*out[0] + fact*out[0]/tex[0];
1515                 if (tex[1]!=0.0f)
1516                         in[1]= facm*out[1] + fact*out[1]/tex[1];
1517                 if (tex[2]!=0.0f)
1518                         in[2]= facm*out[2] + fact*out[2]/tex[2];
1519
1520                 break;
1521
1522         case MTEX_DIFF:
1523                 fact*= facg;
1524                 facm= 1.0f-fact;
1525                 in[0]= facm*out[0] + fact*fabsf(tex[0]-out[0]);
1526                 in[1]= facm*out[1] + fact*fabsf(tex[1]-out[1]);
1527                 in[2]= facm*out[2] + fact*fabsf(tex[2]-out[2]);
1528                 break;
1529
1530         case MTEX_DARK:
1531                 fact*= facg;
1532                 facm= 1.0f-fact;
1533                 
1534                 in[0] = min_ff(out[0], tex[0])*fact + out[0]*facm;
1535                 in[1] = min_ff(out[1], tex[1])*fact + out[1]*facm;
1536                 in[2] = min_ff(out[2], tex[2])*fact + out[2]*facm;
1537                 break;
1538
1539         case MTEX_LIGHT:
1540                 fact*= facg;
1541
1542                 in[0] = max_ff(fact * tex[0], out[0]);
1543                 in[1] = max_ff(fact * tex[1], out[1]);
1544                 in[2] = max_ff(fact * tex[2], out[2]);
1545                 break;
1546                 
1547         case MTEX_BLEND_HUE:
1548                 fact*= facg;
1549                 copy_v3_v3(in, out);
1550                 ramp_blend(MA_RAMP_HUE, in, fact, tex);
1551                 break;
1552         case MTEX_BLEND_SAT:
1553                 fact*= facg;
1554                 copy_v3_v3(in, out);
1555                 ramp_blend(MA_RAMP_SAT, in, fact, tex);
1556                 break;
1557         case MTEX_BLEND_VAL:
1558                 fact*= facg;
1559                 copy_v3_v3(in, out);
1560                 ramp_blend(MA_RAMP_VAL, in, fact, tex);
1561                 break;
1562         case MTEX_BLEND_COLOR:
1563                 fact*= facg;
1564                 copy_v3_v3(in, out);
1565                 ramp_blend(MA_RAMP_COLOR, in, fact, tex);
1566                 break;
1567         case MTEX_SOFT_LIGHT: 
1568                 fact*= facg; 
1569                 copy_v3_v3(in, out);
1570                 ramp_blend(MA_RAMP_SOFT, in, fact, tex);
1571                 break; 
1572         case MTEX_LIN_LIGHT: 
1573                 fact*= facg; 
1574                 copy_v3_v3(in, out);
1575                 ramp_blend(MA_RAMP_LINEAR, in, fact, tex);
1576                 break; 
1577         }
1578 }
1579
1580 float texture_value_blend(float tex, float out, float fact, float facg, int blendtype)
1581 {
1582         float in=0.0, facm, col, scf;
1583         int flip= (facg < 0.0f);
1584
1585         facg= fabsf(facg);
1586         
1587         fact*= facg;
1588         facm= 1.0f-fact;
1589         if (flip) SWAP(float, fact, facm);
1590
1591         switch (blendtype) {
1592         case MTEX_BLEND:
1593                 in= fact*tex + facm*out;
1594                 break;
1595
1596         case MTEX_MUL:
1597                 facm= 1.0f-facg;
1598                 in= (facm+fact*tex)*out;
1599                 break;
1600
1601         case MTEX_SCREEN:
1602                 facm= 1.0f-facg;
1603                 in= 1.0f-(facm+fact*(1.0f-tex))*(1.0f-out);
1604                 break;
1605
1606         case MTEX_OVERLAY:
1607                 facm= 1.0f-facg;
1608                 if (out < 0.5f)
1609                         in = out * (facm + 2.0f*fact*tex);
1610                 else
1611                         in = 1.0f - (facm + 2.0f*fact*(1.0f - tex)) * (1.0f - out);
1612                 break;
1613
1614         case MTEX_SUB:
1615                 fact= -fact;
1616                 ATTR_FALLTHROUGH;
1617         case MTEX_ADD:
1618                 in= fact*tex + out;
1619                 break;
1620
1621         case MTEX_DIV:
1622                 if (tex!=0.0f)
1623                         in= facm*out + fact*out/tex;
1624                 break;
1625
1626         case MTEX_DIFF:
1627                 in= facm*out + fact*fabsf(tex-out);
1628                 break;
1629
1630         case MTEX_DARK:
1631                 in = min_ff(out, tex)*fact + out*facm;
1632                 break;
1633
1634         case MTEX_LIGHT:
1635                 col= fact*tex;
1636                 if (col > out) in= col; else in= out;
1637                 break;
1638
1639         case MTEX_SOFT_LIGHT: 
1640                 scf=1.0f - (1.0f - tex) * (1.0f - out);
1641                 in= facm*out + fact * ((1.0f - out) * tex * out) + (out * scf);
1642                 break;       
1643
1644         case MTEX_LIN_LIGHT: 
1645                 if (tex > 0.5f)
1646                         in = out + fact*(2.0f*(tex - 0.5f));
1647                 else 
1648                         in = out + fact*(2.0f*tex - 1.0f);
1649                 break;
1650         }
1651         
1652         return in;
1653 }
1654
1655 static void texco_mapping(ShadeInput *shi, Tex *tex, MTex *mtex,
1656                           const float co[3], const float dx[3], const float dy[3], float texvec[3], float dxt[3], float dyt[3])
1657 {
1658         /* new: first swap coords, then map, then trans/scale */
1659         if (tex->type == TEX_IMAGE) {
1660                 /* placement */
1661                 texvec[0] = mtex->projx ? co[mtex->projx - 1] : 0.f;
1662                 texvec[1] = mtex->projy ? co[mtex->projy - 1] : 0.f;
1663                 texvec[2] = mtex->projz ? co[mtex->projz - 1] : 0.f;
1664
1665                 if (shi->osatex) {
1666                         if (mtex->projx) {
1667                                 dxt[0] = dx[mtex->projx - 1];
1668                                 dyt[0] = dy[mtex->projx - 1];
1669                         }
1670                         else dxt[0] = dyt[0] = 0.f;
1671                         if (mtex->projy) {
1672                                 dxt[1] = dx[mtex->projy - 1];
1673                                 dyt[1] = dy[mtex->projy - 1];
1674                         }
1675                         else dxt[1] = dyt[1] = 0.f;
1676                         if (mtex->projz) {
1677                                 dxt[2] = dx[mtex->projz - 1];
1678                                 dyt[2] = dy[mtex->projz - 1];
1679                         }
1680                         else dxt[2] = dyt[2] = 0.f;
1681                 }
1682                 do_2d_mapping(mtex, texvec, shi->vlr, shi->facenor, dxt, dyt);
1683
1684                 /* translate and scale */
1685                 texvec[0] = mtex->size[0]*(texvec[0] - 0.5f) + mtex->ofs[0] + 0.5f;
1686                 texvec[1] = mtex->size[1]*(texvec[1] - 0.5f) + mtex->ofs[1] + 0.5f;
1687                 if (shi->osatex) {
1688                         dxt[0] = mtex->size[0] * dxt[0];
1689                         dxt[1] = mtex->size[1] * dxt[1];
1690                         dyt[0] = mtex->size[0] * dyt[0];
1691                         dyt[1] = mtex->size[1] * dyt[1];
1692                 }
1693                 
1694                 /* problem: repeat-mirror is not a 'repeat' but 'extend' in imagetexture.c */
1695                 /* TXF: bug was here, only modify texvec when repeat mode set, old code affected other modes too.
1696                  * New texfilters solve mirroring differently so that it also works correctly when
1697                  * textures are scaled (sizeXYZ) as well as repeated. See also modification in do_2d_mapping().
1698                  * (since currently only done in osa mode, results will look incorrect without osa TODO) */
1699                 if (tex->extend == TEX_REPEAT && (tex->flag & TEX_REPEAT_XMIR)) {
1700                         if (tex->texfilter == TXF_BOX)
1701                                 texvec[0] -= floorf(texvec[0]);  /* this line equivalent to old code, same below */
1702                         else if (texvec[0] < 0.f || texvec[0] > 1.f) {
1703                                 const float tx = 0.5f*texvec[0];
1704                                 texvec[0] = 2.f*(tx - floorf(tx));
1705                                 if (texvec[0] > 1.f) texvec[0] = 2.f - texvec[0];
1706                         }
1707                 }
1708                 if (tex->extend == TEX_REPEAT && (tex->flag & TEX_REPEAT_YMIR)) {
1709                         if (tex->texfilter == TXF_BOX)
1710                                 texvec[1] -= floorf(texvec[1]);
1711                         else if (texvec[1] < 0.f || texvec[1] > 1.f) {
1712                                 const float ty = 0.5f*texvec[1];
1713                                 texvec[1] = 2.f*(ty - floorf(ty));
1714                                 if (texvec[1] > 1.f) texvec[1] = 2.f - texvec[1];
1715                         }
1716                 }
1717                 
1718         }
1719         else {  /* procedural */
1720                 /* placement */
1721                 texvec[0] = mtex->size[0]*(mtex->projx ? (co[mtex->projx - 1] + mtex->ofs[0]) : mtex->ofs[0]);
1722                 texvec[1] = mtex->size[1]*(mtex->projy ? (co[mtex->projy - 1] + mtex->ofs[1]) : mtex->ofs[1]);
1723                 texvec[2] = mtex->size[2]*(mtex->projz ? (co[mtex->projz - 1] + mtex->ofs[2]) : mtex->ofs[2]);
1724
1725                 if (shi->osatex) {
1726                         if (mtex->projx) {
1727                                 dxt[0] = mtex->size[0]*dx[mtex->projx - 1];
1728                                 dyt[0] = mtex->size[0]*dy[mtex->projx - 1];
1729                         }
1730                         else dxt[0] = dyt[0] = 0.f;
1731                         if (mtex->projy) {
1732                                 dxt[1] = mtex->size[1]*dx[mtex->projy - 1];
1733                                 dyt[1] = mtex->size[1]*dy[mtex->projy - 1];
1734                         }
1735                         else dxt[1] = dyt[1] = 0.f;
1736                         if (mtex->projz) {
1737                                 dxt[2] = mtex->size[2]*dx[mtex->projz - 1];
1738                                 dyt[2] = mtex->size[2]*dy[mtex->projz - 1];
1739                         }
1740                         else dxt[2]= dyt[2] = 0.f;
1741                 }
1742
1743                 if (mtex->tex->type == TEX_ENVMAP) {
1744                         EnvMap *env = tex->env;
1745                         if (!env->object) {
1746                                 // env->object is a view point for envmap rendering
1747                                 // if it's not set, return the result depending on the world_space_shading flag
1748                                 if (BKE_scene_use_world_space_shading(R.scene)) {
1749                                         mul_mat3_m4_v3(R.viewinv, texvec);
1750                                         if (shi->osatex) {
1751                                                 mul_mat3_m4_v3(R.viewinv, dxt);
1752                                                 mul_mat3_m4_v3(R.viewinv, dyt);
1753                                         }
1754                                 }
1755                         }
1756                 }
1757         }
1758 }
1759
1760 /* Bump code from 2.5 development cycle, has a number of bugs, but here for compatibility */
1761
1762 typedef struct CompatibleBump {
1763         float nu[3], nv[3], nn[3];
1764         float dudnu, dudnv, dvdnu, dvdnv;
1765         bool nunvdone;
1766 } CompatibleBump;
1767
1768 static void compatible_bump_init(CompatibleBump *compat_bump)
1769 {
1770         memset(compat_bump, 0, sizeof(*compat_bump));
1771
1772         compat_bump->dudnu = 1.0f;
1773         compat_bump->dvdnv = 1.0f;
1774 }
1775
1776 static void compatible_bump_uv_derivs(CompatibleBump *compat_bump, ShadeInput *shi, MTex *mtex, int i)
1777 {
1778         /* uvmapping only, calculation of normal tangent u/v partial derivatives
1779          * (should not be here, dudnu, dudnv, dvdnu & dvdnv should probably be part of ShadeInputUV struct,
1780          *  nu/nv in ShadeInput and this calculation should then move to shadeinput.c,
1781          * shade_input_set_shade_texco() func.) */
1782
1783         /* NOTE: test for shi->obr->ob here,
1784          * since vlr/obr/obi can be 'fake' when called from fastshade(), another reason to move it.. */
1785
1786         /* NOTE: shi->v1 is NULL when called from displace_render_vert,
1787          * assigning verts in this case is not trivial because the shi quad face side is not know. */
1788         if ((mtex->texflag & MTEX_COMPAT_BUMP) && shi->obr && shi->obr->ob && shi->v1) {
1789                 if (mtex->mapto & (MAP_NORM|MAP_WARP) && !((mtex->tex->type==TEX_IMAGE) && (mtex->tex->imaflag & TEX_NORMALMAP))) {
1790                         MTFace* tf = RE_vlakren_get_tface(shi->obr, shi->vlr, i, NULL, 0);
1791                         int j1 = shi->i1, j2 = shi->i2, j3 = shi->i3;
1792
1793                         vlr_set_uv_indices(shi->vlr, &j1, &j2, &j3);
1794
1795                         /* compute ortho basis around normal */
1796                         if (!compat_bump->nunvdone) {
1797                                 /* render normal is negated */
1798                                 compat_bump->nn[0] = -shi->vn[0];
1799                                 compat_bump->nn[1] = -shi->vn[1];
1800                                 compat_bump->nn[2] = -shi->vn[2];
1801                                 ortho_basis_v3v3_v3(compat_bump->nu, compat_bump->nv, compat_bump->nn);
1802                                 compat_bump->nunvdone = true;
1803                         }
1804
1805                         if (tf) {
1806                                 const float *uv1 = tf->uv[j1], *uv2 = tf->uv[j2], *uv3 = tf->uv[j3];
1807                                 const float an[3] = {fabsf(compat_bump->nn[0]), fabsf(compat_bump->nn[1]), fabsf(compat_bump->nn[2])};
1808                                 const int a1 = (an[0] > an[1] && an[0] > an[2]) ? 1 : 0;
1809                                 const int a2 = (an[2] > an[0] && an[2] > an[1]) ? 1 : 2;
1810                                 const float dp1_a1 = shi->v1->co[a1] - shi->v3->co[a1];
1811                                 const float dp1_a2 = shi->v1->co[a2] - shi->v3->co[a2];
1812                                 const float dp2_a1 = shi->v2->co[a1] - shi->v3->co[a1];
1813                                 const float dp2_a2 = shi->v2->co[a2] - shi->v3->co[a2];
1814                                 const float du1 = uv1[0] - uv3[0], du2 = uv2[0] - uv3[0];
1815                                 const float dv1 = uv1[1] - uv3[1], dv2 = uv2[1] - uv3[1];
1816                                 const float dpdu_a1 = dv2*dp1_a1 - dv1*dp2_a1;
1817                                 const float dpdu_a2 = dv2*dp1_a2 - dv1*dp2_a2;
1818                                 const float dpdv_a1 = du1*dp2_a1 - du2*dp1_a1;
1819                                 const float dpdv_a2 = du1*dp2_a2 - du2*dp1_a2;
1820                                 float d = dpdu_a1*dpdv_a2 - dpdv_a1*dpdu_a2;
1821                                 float uvd = du1*dv2 - dv1*du2;
1822
1823                                 if (uvd == 0.f) uvd = 1e-5f;
1824                                 if (d == 0.f) d = 1e-5f;
1825                                 d = uvd / d;
1826
1827                                 compat_bump->dudnu = (dpdv_a2*compat_bump->nu[a1] - dpdv_a1*compat_bump->nu[a2])*d;
1828                                 compat_bump->dvdnu = (dpdu_a1*compat_bump->nu[a2] - dpdu_a2*compat_bump->nu[a1])*d;
1829                                 compat_bump->dudnv = (dpdv_a2*compat_bump->nv[a1] - dpdv_a1*compat_bump->nv[a2])*d;
1830                                 compat_bump->dvdnv = (dpdu_a1*compat_bump->nv[a2] - dpdu_a2*compat_bump->nv[a1])*d;
1831                         }
1832                 }
1833         }
1834 }
1835
1836 static int compatible_bump_compute(CompatibleBump *compat_bump, ShadeInput *shi, MTex *mtex, Tex *tex, TexResult *texres,
1837                                    float Tnor, const float co[3], const float dx[3], const float dy[3], float texvec[3], float dxt[3], float dyt[3],
1838                                    struct ImagePool *pool, const bool skip_load_image)
1839 {
1840         TexResult ttexr = {0, 0, 0, 0, 0, texres->talpha, NULL};  /* temp TexResult */
1841         float tco[3], texv[3], cd, ud, vd, du, dv, idu, idv;
1842         const int fromrgb = ((tex->type == TEX_IMAGE) || ((tex->flag & TEX_COLORBAND)!=0));
1843         const float bf = -0.04f*Tnor*mtex->norfac;
1844         int rgbnor;
1845         /* disable internal bump eval */
1846         float *nvec = texres->nor;
1847         texres->nor = NULL;
1848         /* du & dv estimates, constant value defaults */
1849         du = dv = 0.01f;
1850
1851         /* compute ortho basis around normal */
1852         if (!compat_bump->nunvdone) {
1853                 /* render normal is negated */
1854                 negate_v3_v3(compat_bump->nn, shi->vn);
1855                 ortho_basis_v3v3_v3(compat_bump->nu, compat_bump->nv, compat_bump->nn);
1856                 compat_bump->nunvdone = true;
1857         }
1858
1859         /* two methods, either constant based on main image resolution,
1860          * (which also works without osa, though of course not always good (or even very bad) results),
1861          * or based on tex derivative max values (osa only). Not sure which is best... */
1862
1863         if (!shi->osatex && (tex->type == TEX_IMAGE) && tex->ima) {
1864                 /* in case we have no proper derivatives, fall back to
1865                  * computing du/dv it based on image size */
1866                 ImBuf *ibuf = BKE_image_pool_acquire_ibuf(tex->ima, &tex->iuser, pool);
1867                 if (ibuf) {
1868                         du = 1.f/(float)ibuf->x;
1869                         dv = 1.f/(float)ibuf->y;
1870                 }
1871                 BKE_image_pool_release_ibuf(tex->ima, ibuf, pool);
1872         }
1873         else if (shi->osatex) {
1874                 /* we have derivatives, can compute proper du/dv */
1875                 if (tex->type == TEX_IMAGE) {   /* 2d image, use u & v max. of dx/dy 2d vecs */
1876                         const float adx[2] = {fabsf(dx[0]), fabsf(dx[1])};
1877                         const float ady[2] = {fabsf(dy[0]), fabsf(dy[1])};
1878                         du = MAX2(adx[0], ady[0]);
1879                         dv = MAX2(adx[1], ady[1]);
1880                 }
1881                 else {  /* 3d procedural, estimate from all dx/dy elems */
1882                         const float adx[3] = {fabsf(dx[0]), fabsf(dx[1]), fabsf(dx[2])};
1883                         const float ady[3] = {fabsf(dy[0]), fabsf(dy[1]), fabsf(dy[2])};
1884                         du = max_fff(adx[0], adx[1], adx[2]);
1885                         dv = max_fff(ady[0], ady[1], ady[2]);
1886                 }
1887         }
1888
1889         /* center, main return value */
1890         texco_mapping(shi, tex, mtex, co, dx, dy, texvec, dxt, dyt);
1891         rgbnor = multitex_mtex(shi, mtex, texvec, dxt, dyt, texres, pool, skip_load_image);
1892         cd = fromrgb ? (texres->tr + texres->tg + texres->tb) / 3.0f : texres->tin;
1893
1894         if (mtex->texco == TEXCO_UV) {
1895                 /* for the uv case, use the same value for both du/dv,
1896                  * since individually scaling the normal derivatives makes them useless... */
1897                 du = min_ff(du, dv);
1898                 idu = (du < 1e-5f) ? bf : (bf/du);
1899
1900                 /* +u val */
1901                 tco[0] = co[0] + compat_bump->dudnu*du;
1902                 tco[1] = co[1] + compat_bump->dvdnu*du;
1903                 tco[2] = 0.f;
1904                 texco_mapping(shi, tex, mtex, tco, dx, dy, texv, dxt, dyt);
1905                 multitex_mtex(shi, mtex, texv, dxt, dyt, &ttexr, pool, skip_load_image);
1906                 ud = idu*(cd - (fromrgb ? (ttexr.tr + ttexr.tg + ttexr.tb) / 3.0f : ttexr.tin));
1907
1908                 /* +v val */
1909                 tco[0] = co[0] + compat_bump->dudnv*du;
1910                 tco[1] = co[1] + compat_bump->dvdnv*du;
1911                 tco[2] = 0.f;
1912                 texco_mapping(shi, tex, mtex, tco, dx, dy, texv, dxt, dyt);
1913                 multitex_mtex(shi, mtex, texv, dxt, dyt, &ttexr, pool, skip_load_image);
1914                 vd = idu*(cd - (fromrgb ? (ttexr.tr + ttexr.tg + ttexr.tb) / 3.0f : ttexr.tin));
1915         }
1916         else {
1917                 float tu[3], tv[3];
1918
1919                 copy_v3_v3(tu, compat_bump->nu);
1920                 copy_v3_v3(tv, compat_bump->nv);
1921
1922                 idu = (du < 1e-5f) ? bf : (bf/du);
1923                 idv = (dv < 1e-5f) ? bf : (bf/dv);
1924
1925                 if ((mtex->texco == TEXCO_ORCO) && shi->obr && shi->obr->ob) {
1926                         mul_mat3_m4_v3(shi->obr->ob->imat_ren, tu);
1927                         mul_mat3_m4_v3(shi->obr->ob->imat_ren, tv);
1928                         normalize_v3(tu);
1929                         normalize_v3(tv);
1930                 }
1931                 else if (mtex->texco == TEXCO_GLOB) {
1932                         mul_mat3_m4_v3(R.viewinv, tu);
1933                         mul_mat3_m4_v3(R.viewinv, tv);
1934                 }
1935                 else if (mtex->texco == TEXCO_OBJECT && mtex->object) {
1936                         mul_mat3_m4_v3(mtex->object->imat_ren, tu);
1937                         mul_mat3_m4_v3(mtex->object->imat_ren, tv);
1938                         normalize_v3(tu);
1939                         normalize_v3(tv);
1940                 }
1941
1942                 /* +u val */
1943                 tco[0] = co[0] + tu[0]*du;
1944                 tco[1] = co[1] + tu[1]*du;
1945                 tco[2] = co[2] + tu[2]*du;
1946                 texco_mapping(shi, tex, mtex, tco, dx, dy, texv, dxt, dyt);
1947                 multitex_mtex(shi, mtex, texv, dxt, dyt, &ttexr, pool, skip_load_image);
1948                 ud = idu*(cd - (fromrgb ? (ttexr.tr + ttexr.tg + ttexr.tb) / 3.0f : ttexr.tin));
1949
1950                 /* +v val */
1951                 tco[0] = co[0] + tv[0]*dv;
1952                 tco[1] = co[1] + tv[1]*dv;
1953                 tco[2] = co[2] + tv[2]*dv;
1954                 texco_mapping(shi, tex, mtex, tco, dx, dy, texv, dxt, dyt);
1955                 multitex_mtex(shi, mtex, texv, dxt, dyt, &ttexr, pool, skip_load_image);
1956                 vd = idv*(cd - (fromrgb ? (ttexr.tr + ttexr.tg + ttexr.tb) / 3.0f : ttexr.tin));
1957         }
1958
1959         /* bumped normal */
1960         compat_bump->nu[0] += ud*compat_bump->nn[0];
1961         compat_bump->nu[1] += ud*compat_bump->nn[1];
1962         compat_bump->nu[2] += ud*compat_bump->nn[2];
1963         compat_bump->nv[0] += vd*compat_bump->nn[0];
1964         compat_bump->nv[1] += vd*compat_bump->nn[1];
1965         compat_bump->nv[2] += vd*compat_bump->nn[2];
1966         cross_v3_v3v3(nvec, compat_bump->nu, compat_bump->nv);
1967
1968         nvec[0] = -nvec[0];
1969         nvec[1] = -nvec[1];
1970         nvec[2] = -nvec[2];
1971         texres->nor = nvec;
1972
1973         rgbnor |= TEX_NOR;
1974         return rgbnor;
1975 }
1976
1977 /* Improved bump code from later in 2.5 development cycle */
1978
1979 typedef struct NTapBump {
1980         int init_done;
1981         int iPrevBumpSpace;     /* 0: uninitialized, 1: objectspace, 2: texturespace, 4: viewspace */
1982         /* bumpmapping */
1983         float vNorg[3]; /* backup copy of shi->vn */
1984         float vNacc[3]; /* original surface normal minus the surface gradient of every bump map which is encountered */
1985         float vR1[3], vR2[3]; /* cross products (sigma_y, original_normal), (original_normal, sigma_x) */
1986         float sgn_det; /* sign of the determinant of the matrix {sigma_x, sigma_y, original_normal} */
1987         float fPrevMagnitude; /* copy of previous magnitude, used for multiple bumps in different spaces */
1988 } NTapBump;
1989
1990 static void ntap_bump_init(NTapBump *ntap_bump)
1991 {
1992         memset(ntap_bump, 0, sizeof(*ntap_bump));
1993 }
1994
1995 static int ntap_bump_compute(NTapBump *ntap_bump, ShadeInput *shi, MTex *mtex, Tex *tex, TexResult *texres,
1996                              float Tnor, const float co[3], const float dx[3], const float dy[3],
1997                              float texvec[3], float dxt[3], float dyt[3], struct ImagePool *pool,
1998                              const bool skip_load_image)
1999 {
2000         TexResult ttexr = {0, 0, 0, 0, 0, texres->talpha, NULL};        /* temp TexResult */
2001
2002         const int fromrgb = ((tex->type == TEX_IMAGE) || ((tex->flag & TEX_COLORBAND)!=0));
2003
2004         /* The negate on Hscale is done because the
2005          * normal in the renderer points inward which corresponds
2006          * to inverting the bump map. The normals are generated
2007          * this way in calc_vertexnormals(). Should this ever change
2008          * this negate must be removed. */
2009         float Hscale = -Tnor*mtex->norfac;
2010
2011         int dimx=512, dimy=512;
2012         const int imag_tspace_dimension_x = 1024;  /* only used for texture space variant */
2013         float aspect = 1.0f;
2014
2015         /* 2 channels for 2D texture and 3 for 3D textures. */
2016         const int nr_channels = (mtex->texco == TEXCO_UV)? 2 : 3;
2017         int c, rgbnor, iBumpSpace;
2018         float dHdx, dHdy;
2019         int found_deriv_map = (tex->type==TEX_IMAGE) && (tex->imaflag & TEX_DERIVATIVEMAP);
2020
2021         /* disable internal bump eval in sampler, save pointer */
2022         float *nvec = texres->nor;
2023         texres->nor = NULL;
2024
2025         if (found_deriv_map==0) {
2026                 if ( mtex->texflag & MTEX_BUMP_TEXTURESPACE ) {
2027                         if (tex->ima)
2028                                 Hscale *= 13.0f; /* appears to be a sensible default value */
2029                 }
2030                 else
2031                         Hscale *= 0.1f; /* factor 0.1 proved to look like the previous bump code */
2032         }
2033
2034         if ( !ntap_bump->init_done ) {
2035                 copy_v3_v3(ntap_bump->vNacc, shi->vn);
2036                 copy_v3_v3(ntap_bump->vNorg, shi->vn);
2037                 ntap_bump->fPrevMagnitude = 1.0f;
2038                 ntap_bump->iPrevBumpSpace = 0;
2039                 
2040                 ntap_bump->init_done = true;
2041         }
2042
2043         /* resolve image dimensions */
2044         if (found_deriv_map || (mtex->texflag&MTEX_BUMP_TEXTURESPACE)!=0) {
2045                 ImBuf *ibuf = BKE_image_pool_acquire_ibuf(tex->ima, &tex->iuser, pool);
2046                 if (ibuf) {
2047                         dimx = ibuf->x;
2048                         dimy = ibuf->y;
2049                         aspect = ((float) dimy) / dimx;
2050                 }
2051                 BKE_image_pool_release_ibuf(tex->ima, ibuf, pool);
2052         }
2053         
2054         if (found_deriv_map) {
2055                 float dBdu, dBdv, auto_bump = 1.0f;
2056                 float s = 1;            /* negate this if flipped texture coordinate */
2057                 texco_mapping(shi, tex, mtex, co, dx, dy, texvec, dxt, dyt);
2058                 rgbnor = multitex_mtex(shi, mtex, texvec, dxt, dyt, texres, pool, skip_load_image);
2059
2060                 if (shi->obr->ob->derivedFinal) {
2061                         auto_bump = shi->obr->ob->derivedFinal->auto_bump_scale;
2062                 }
2063
2064                 {
2065                         float fVirtDim = sqrtf(fabsf((float) (dimx*dimy)*mtex->size[0]*mtex->size[1]));
2066                         auto_bump /= MAX2(fVirtDim, FLT_EPSILON);
2067                 }
2068
2069                 /* this variant using a derivative map is described here
2070                  * http://mmikkelsen3d.blogspot.com/2011/07/derivative-maps.html */
2071                 dBdu = auto_bump*Hscale*dimx*(2*texres->tr-1);
2072                 dBdv = auto_bump*Hscale*dimy*(2*texres->tg-1);
2073
2074                 dHdx = dBdu*dxt[0] + s * dBdv*dxt[1];
2075                 dHdy = dBdu*dyt[0] + s * dBdv*dyt[1];
2076         }
2077         else if (!(mtex->texflag & MTEX_5TAP_BUMP)) {
2078                 /* compute height derivatives with respect to output image pixel coordinates x and y */
2079                 float STll[3], STlr[3], STul[3];
2080                 float Hll, Hlr, Hul;
2081
2082                 texco_mapping(shi, tex, mtex, co, dx, dy, texvec, dxt, dyt);
2083
2084                 for (c=0; c<nr_channels; c++) {
2085                         /* dx contains the derivatives (du/dx, dv/dx)
2086                          * dy contains the derivatives (du/dy, dv/dy) */
2087                         STll[c] = texvec[c];
2088                         STlr[c] = texvec[c]+dxt[c];
2089                         STul[c] = texvec[c]+dyt[c];
2090                 }
2091
2092                 /* clear unused derivatives */
2093                 for (c=nr_channels; c<3; c++) {
2094                         STll[c] = 0.0f;
2095                         STlr[c] = 0.0f;
2096                         STul[c] = 0.0f;
2097                 }
2098
2099                 /* use texres for the center sample, set rgbnor */
2100                 rgbnor = multitex_mtex(shi, mtex, STll, dxt, dyt, texres, pool, skip_load_image);
2101                 Hll = (fromrgb) ? IMB_colormanagement_get_luminance(&texres->tr) : texres->tin;
2102
2103                 /* use ttexr for the other 2 taps */
2104                 multitex_mtex(shi, mtex, STlr, dxt, dyt, &ttexr, pool, skip_load_image);
2105                 Hlr = (fromrgb) ? IMB_colormanagement_get_luminance(&ttexr.tr) : ttexr.tin;
2106
2107                 multitex_mtex(shi, mtex, STul, dxt, dyt, &ttexr, pool, skip_load_image);
2108                 Hul = (fromrgb) ? IMB_colormanagement_get_luminance(&ttexr.tr) : ttexr.tin;
2109
2110                 dHdx = Hscale*(Hlr - Hll);
2111                 dHdy = Hscale*(Hul - Hll);
2112         }
2113         else {
2114                 /* same as above, but doing 5 taps, increasing quality at cost of speed */
2115                 float STc[3], STl[3], STr[3], STd[3], STu[3];
2116                 float /* Hc, */ /* UNUSED */  Hl, Hr, Hd, Hu;
2117
2118                 texco_mapping(shi, tex, mtex, co, dx, dy, texvec, dxt, dyt);
2119
2120                 for (c=0; c<nr_channels; c++) {
2121                         STc[c] = texvec[c];
2122                         STl[c] = texvec[c] - 0.5f*dxt[c];
2123                         STr[c] = texvec[c] + 0.5f*dxt[c];
2124                         STd[c] = texvec[c] - 0.5f*dyt[c];
2125                         STu[c] = texvec[c] + 0.5f*dyt[c];
2126                 }
2127
2128                 /* clear unused derivatives */
2129                 for (c=nr_channels; c<3; c++) {
2130                         STc[c] = 0.0f;
2131                         STl[c] = 0.0f;
2132                         STr[c] = 0.0f;
2133                         STd[c] = 0.0f;
2134                         STu[c] = 0.0f;
2135                 }
2136
2137                 /* use texres for the center sample, set rgbnor */
2138                 rgbnor = multitex_mtex(shi, mtex, STc, dxt, dyt, texres, pool, skip_load_image);
2139                 /* Hc = (fromrgb) ? IMB_colormanagement_get_luminance(&texres->tr) : texres->tin; */ /* UNUSED */
2140
2141                 /* use ttexr for the other taps */
2142                 multitex_mtex(shi, mtex, STl, dxt, dyt, &ttexr, pool, skip_load_image);
2143                 Hl = (fromrgb) ? IMB_colormanagement_get_luminance(&ttexr.tr) : ttexr.tin;
2144                 multitex_mtex(shi, mtex, STr, dxt, dyt, &ttexr, pool, skip_load_image);
2145                 Hr = (fromrgb) ? IMB_colormanagement_get_luminance(&ttexr.tr) : ttexr.tin;
2146                 multitex_mtex(shi, mtex, STd, dxt, dyt, &ttexr, pool, skip_load_image);
2147                 Hd = (fromrgb) ? IMB_colormanagement_get_luminance(&ttexr.tr) : ttexr.tin;
2148                 multitex_mtex(shi, mtex, STu, dxt, dyt, &ttexr, pool, skip_load_image);
2149                 Hu = (fromrgb) ? IMB_colormanagement_get_luminance(&ttexr.tr) : ttexr.tin;
2150
2151                 dHdx = Hscale*(Hr - Hl);
2152                 dHdy = Hscale*(Hu - Hd);
2153         }
2154
2155         /* restore pointer */
2156         texres->nor = nvec;
2157
2158         /* replaced newbump with code based on listing 1 and 2 of
2159          * [Mik10] Mikkelsen M. S.: Bump Mapping Unparameterized Surfaces on the GPU.
2160          * -> http://jbit.net/~sparky/sfgrad_bump/mm_sfgrad_bump.pdf */
2161
2162         if ( mtex->texflag & MTEX_BUMP_OBJECTSPACE )
2163                 iBumpSpace = 1;
2164         else if ( mtex->texflag & MTEX_BUMP_TEXTURESPACE )
2165                 iBumpSpace = 2;
2166         else
2167                 iBumpSpace = 4; /* ViewSpace */
2168
2169         if ( ntap_bump->iPrevBumpSpace != iBumpSpace ) {
2170
2171                 /* initialize normal perturbation vectors */
2172                 int xyz;
2173                 float fDet, abs_fDet, fMagnitude;
2174                 /* object2view and inverted matrix */
2175                 float obj2view[3][3], view2obj[3][3], tmp[4][4];
2176                 /* local copies of derivatives and normal */
2177                 float dPdx[3], dPdy[3], vN[3];
2178                 copy_v3_v3(dPdx, shi->dxco);
2179                 copy_v3_v3(dPdy, shi->dyco);
2180                 copy_v3_v3(vN, ntap_bump->vNorg);
2181                 
2182                 if ( mtex->texflag & MTEX_BUMP_OBJECTSPACE ) {
2183                         /* TODO: these calculations happen for every pixel!
2184                          *      -> move to shi->obi */
2185                         mul_m4_m4m4(tmp, R.viewmat, shi->obr->ob->obmat);
2186                         copy_m3_m4(obj2view, tmp); /* use only upper left 3x3 matrix */
2187                         invert_m3_m3(view2obj, obj2view);
2188
2189                         /* generate the surface derivatives in object space */
2190                         mul_m3_v3(view2obj, dPdx);
2191                         mul_m3_v3(view2obj, dPdy);
2192                         /* generate the unit normal in object space */
2193                         mul_transposed_m3_v3(obj2view, vN);
2194                         normalize_v3(vN);
2195                 }
2196                 
2197                 cross_v3_v3v3(ntap_bump->vR1, dPdy, vN);
2198                 cross_v3_v3v3(ntap_bump->vR2, vN, dPdx);
2199                 fDet = dot_v3v3(dPdx, ntap_bump->vR1);
2200                 ntap_bump->sgn_det = (fDet < 0)? -1.0f: 1.0f;
2201                 abs_fDet = ntap_bump->sgn_det * fDet;
2202
2203                 if ( mtex->texflag & MTEX_BUMP_TEXTURESPACE ) {
2204                         if (tex->ima) {
2205                                 /* crazy hack solution that gives results similar to normal mapping - part 1 */
2206                                 normalize_v3(ntap_bump->vR1);
2207                                 normalize_v3(ntap_bump->vR2);
2208                                 abs_fDet = 1.0f;
2209                         }
2210                 }
2211                 
2212                 fMagnitude = abs_fDet;
2213                 if ( mtex->texflag & MTEX_BUMP_OBJECTSPACE ) {
2214                         /* pre do transform of texres->nor by the inverse transposed of obj2view */
2215                         mul_transposed_m3_v3(view2obj, vN);
2216                         mul_transposed_m3_v3(view2obj, ntap_bump->vR1);
2217                         mul_transposed_m3_v3(view2obj, ntap_bump->vR2);
2218                         
2219                         fMagnitude *= len_v3(vN);
2220                 }
2221                 
2222                 if (ntap_bump->fPrevMagnitude > 0.0f)
2223                         for (xyz=0; xyz<3; xyz++)
2224                                 ntap_bump->vNacc[xyz] *= fMagnitude / ntap_bump->fPrevMagnitude;
2225                 
2226                 ntap_bump->fPrevMagnitude = fMagnitude;
2227                 ntap_bump->iPrevBumpSpace = iBumpSpace;
2228         }
2229
2230         if ( mtex->texflag & MTEX_BUMP_TEXTURESPACE ) {
2231                 if (tex->ima) {
2232                         /* crazy hack solution that gives results similar to normal mapping - part 2 */
2233                         float vec[2];
2234                         const float imag_tspace_dimension_y = aspect*imag_tspace_dimension_x;
2235                         
2236                         vec[0] = imag_tspace_dimension_x*dxt[0];
2237                         vec[1] = imag_tspace_dimension_y*dxt[1];
2238                         dHdx *= 1.0f/len_v2(vec);
2239                         vec[0] = imag_tspace_dimension_x*dyt[0];
2240                         vec[1] = imag_tspace_dimension_y*dyt[1];
2241                         dHdy *= 1.0f/len_v2(vec);
2242                 }
2243         }
2244         
2245         /* subtract the surface gradient from vNacc */
2246         for (c=0; c<3; c++) {
2247                 float vSurfGrad_compi = ntap_bump->sgn_det * (dHdx * ntap_bump->vR1[c] + dHdy * ntap_bump->vR2[c]);
2248                 ntap_bump->vNacc[c] -= vSurfGrad_compi;
2249                 texres->nor[c] = ntap_bump->vNacc[c]; /* copy */
2250         }
2251
2252         rgbnor |= TEX_NOR;
2253         return rgbnor;
2254 }
2255
2256 void do_material_tex(ShadeInput *shi, Render *re)
2257 {
2258         const bool skip_load_image = (R.r.scemode & R_NO_IMAGE_LOAD) != 0;
2259         CompatibleBump compat_bump;
2260         NTapBump ntap_bump;
2261         MTex *mtex;
2262         Tex *tex;
2263         TexResult texres= {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0, NULL};
2264         float *co = NULL, *dx = NULL, *dy = NULL;
2265         float fact, facm, factt, facmm, stencilTin=1.0;
2266         float texvec[3], dxt[3], dyt[3], tempvec[3], norvec[3], warpvec[3]={0.0f, 0.0f, 0.0f}, Tnor=1.0;
2267         int tex_nr, rgbnor= 0;
2268         bool warp_done = false, use_compat_bump = false, use_ntap_bump = false;
2269         bool found_nmapping = false, found_deriv_map = false;
2270         bool iFirstTimeNMap = true;
2271
2272         compatible_bump_init(&compat_bump);
2273         ntap_bump_init(&ntap_bump);
2274
2275         if (re->r.scemode & R_NO_TEX) return;
2276         /* here: test flag if there's a tex (todo) */
2277
2278         for (tex_nr=0; tex_nr<MAX_MTEX; tex_nr++) {
2279                 
2280                 /* separate tex switching */
2281                 if (shi->mat->septex & (1<<tex_nr)) continue;
2282                 
2283                 if (shi->mat->mtex[tex_nr]) {
2284                         mtex= shi->mat->mtex[tex_nr];
2285                         
2286                         tex= mtex->tex;
2287                         if (tex == NULL) continue;
2288
2289                         found_deriv_map = (tex->type==TEX_IMAGE) && (tex->imaflag & TEX_DERIVATIVEMAP);
2290                         use_compat_bump= (mtex->texflag & MTEX_COMPAT_BUMP) != 0;
2291                         use_ntap_bump = ((mtex->texflag & (MTEX_3TAP_BUMP|MTEX_5TAP_BUMP|MTEX_BICUBIC_BUMP))!=0 || found_deriv_map!=0) ? true : false;
2292
2293                         /* XXX texture node trees don't work for this yet */
2294                         if (tex->nodetree && tex->use_nodes) {
2295                                 use_compat_bump = false;
2296                                 use_ntap_bump = false;
2297                         }
2298                         
2299                         /* case displacement mapping */
2300                         if (shi->osatex == 0 && use_ntap_bump) {
2301                                 use_ntap_bump = false;
2302                                 use_compat_bump = true;
2303                         }
2304                         
2305                         /* case ocean */
2306                         if (tex->type == TEX_OCEAN) {
2307                                 use_ntap_bump = false;
2308                                 use_compat_bump = false;
2309                         }
2310
2311                         /* which coords */
2312                         if (mtex->texco==TEXCO_ORCO) {
2313                                 if (mtex->texflag & MTEX_DUPLI_MAPTO) {
2314                                         co= shi->duplilo; dx= dxt; dy= dyt;
2315                                         dxt[0]= dxt[1]= dxt[2]= 0.0f;
2316                                         dyt[0]= dyt[1]= dyt[2]= 0.0f;
2317                                 }
2318                                 else {
2319                                         co= shi->lo; dx= shi->dxlo; dy= shi->dylo;
2320                                 }
2321                         }
2322                         else if (mtex->texco==TEXCO_OBJECT) {
2323                                 Object *ob= mtex->object;
2324                                 if (ob) {
2325                                         co= tempvec;
2326                                         dx= dxt;
2327                                         dy= dyt;
2328                                         copy_v3_v3(tempvec, shi->co);
2329                                         if (mtex->texflag & MTEX_OB_DUPLI_ORIG)
2330                                                 if (shi->obi && shi->obi->duplitexmat)
2331                                                         mul_m4_v3(shi->obi->duplitexmat, tempvec);
2332                                         mul_m4_v3(ob->imat_ren, tempvec);
2333                                         if (shi->osatex) {
2334                                                 copy_v3_v3(dxt, shi->dxco);
2335                                                 copy_v3_v3(dyt, shi->dyco);
2336                                                 mul_mat3_m4_v3(ob->imat_ren, dxt);
2337                                                 mul_mat3_m4_v3(ob->imat_ren, dyt);
2338                                         }
2339                                 }
2340                                 else {
2341                                         /* if object doesn't exist, do not use orcos (not initialized) */
2342                                         co= shi->co;
2343                                         dx= shi->dxco; dy= shi->dyco;
2344                                 }
2345                         }
2346                         else if (mtex->texco==TEXCO_REFL) {
2347                                 calc_R_ref(shi);
2348                                 co= shi->ref; dx= shi->dxref; dy= shi->dyref;
2349                         }
2350                         else if (mtex->texco==TEXCO_NORM) {
2351                                 co= shi->orn; dx= shi->dxno; dy= shi->dyno;
2352                         }
2353                         else if (mtex->texco==TEXCO_TANGENT) {
2354                                 co= shi->tang; dx= shi->dxno; dy= shi->dyno;
2355                         }
2356                         else if (mtex->texco==TEXCO_GLOB) {
2357                                 co= shi->gl; dx= shi->dxgl; dy= shi->dygl;
2358                         }
2359                         else if (mtex->texco==TEXCO_UV) {
2360                                 if (mtex->texflag & MTEX_DUPLI_MAPTO) {
2361                                         co= shi->dupliuv; dx= dxt; dy= dyt;
2362                                         dxt[0]= dxt[1]= dxt[2]= 0.0f;
2363                                         dyt[0]= dyt[1]= dyt[2]= 0.0f;
2364                                 }
2365                                 else {
2366                                         ShadeInputUV *suv= &shi->uv[shi->actuv];
2367                                         int i = shi->actuv;
2368
2369                                         if (mtex->uvname[0] != 0) {
2370                                                 for (i = 0; i < shi->totuv; i++) {
2371                                                         if (STREQ(shi->uv[i].name, mtex->uvname)) {
2372                                                                 suv= &shi->uv[i];
2373                                                                 break;
2374                                                         }
2375                                                 }
2376                                         }
2377
2378                                         co= suv->uv;
2379                                         dx= suv->dxuv;
2380                                         dy= suv->dyuv; 
2381
2382                                         compatible_bump_uv_derivs(&compat_bump, shi, mtex, i);
2383                                 }
2384                         }
2385                         else if (mtex->texco==TEXCO_WINDOW) {
2386                                 co= shi->winco; dx= shi->dxwin; dy= shi->dywin;
2387                         }
2388                         else if (mtex->texco==TEXCO_STRAND) {
2389                                 co= tempvec; dx= dxt; dy= dyt;
2390                                 co[0]= shi->strandco;
2391                                 co[1]= co[2]= 0.0f;
2392                                 dx[0]= shi->dxstrand;
2393                                 dx[1]= dx[2]= 0.0f;
2394                                 dy[0]= shi->dystrand;
2395                                 dy[1]= dy[2]= 0.0f;
2396                         }
2397                         else if (mtex->texco==TEXCO_STRESS) {
2398                                 co= tempvec; dx= dxt; dy= dyt;
2399                                 co[0]= shi->stress;
2400                                 co[1]= co[2]= 0.0f;
2401                                 dx[0]= 0.0f;
2402                                 dx[1]= dx[2]= 0.0f;
2403                                 dy[0]= 0.0f;
2404                                 dy[1]= dy[2]= 0.0f;
2405                         }
2406                         else {
2407                                 continue;  /* can happen when texco defines disappear and it renders old files */
2408                         }
2409
2410                         /* the pointer defines if bumping happens */
2411                         if (mtex->mapto & (MAP_NORM|MAP_WARP)) {
2412                                 texres.nor= norvec;
2413                                 norvec[0]= norvec[1]= norvec[2]= 0.0;
2414                         }
2415                         else texres.nor= NULL;
2416                         
2417                         if (warp_done) {
2418                                 add_v3_v3v3(tempvec, co, warpvec);
2419                                 co= tempvec;
2420                         }
2421
2422                         /* XXX texture node trees don't work for this yet */
2423                         if (texres.nor && !((tex->type==TEX_IMAGE) && (tex->imaflag & TEX_NORMALMAP))) {
2424                                 if (use_compat_bump) {
2425                                         rgbnor = compatible_bump_compute(&compat_bump, shi, mtex, tex,
2426                                                                          &texres, Tnor*stencilTin, co, dx, dy, texvec, dxt, dyt,
2427                                                                          re->pool, skip_load_image);
2428                                 }
2429                                 else if (use_ntap_bump) {
2430                                         rgbnor = ntap_bump_compute(&ntap_bump, shi, mtex, tex,
2431                                                                    &texres, Tnor*stencilTin, co, dx, dy, texvec, dxt, dyt,
2432                                                                    re->pool, skip_load_image);
2433                                 }
2434                                 else {
2435                                         texco_mapping(shi, tex, mtex, co, dx, dy, texvec, dxt, dyt);
2436                                         rgbnor = multitex_mtex(shi, mtex, texvec, dxt, dyt, &texres, re->pool, skip_load_image);
2437                                 }
2438                         }
2439                         else {
2440                                 texco_mapping(shi, tex, mtex, co, dx, dy, texvec, dxt, dyt);
2441                                 rgbnor = multitex_mtex(shi, mtex, texvec, dxt, dyt, &texres, re->pool, skip_load_image);
2442                         }
2443
2444                         /* texture output */
2445
2446                         if ((rgbnor & TEX_RGB) && (mtex->texflag & MTEX_RGBTOINT)) {
2447                                 texres.tin = IMB_colormanagement_get_luminance(&texres.tr);
2448                                 rgbnor -= TEX_RGB;
2449                         }
2450                         if (mtex->texflag & MTEX_NEGATIVE) {
2451                                 if (rgbnor & TEX_RGB) {
2452                                         texres.tr= 1.0f-texres.tr;
2453                                         texres.tg= 1.0f-texres.tg;
2454                                         texres.tb= 1.0f-texres.tb;
2455                                 }
2456                                 texres.tin= 1.0f-texres.tin;
2457                         }
2458                         if (mtex->texflag & MTEX_STENCIL) {
2459                                 if (rgbnor & TEX_RGB) {
2460                                         fact= texres.ta;
2461                                         texres.ta*= stencilTin;
2462                                         stencilTin*= fact;
2463                                 }
2464                                 else {
2465                                         fact= texres.tin;
2466                                         texres.tin*= stencilTin;
2467                                         stencilTin*= fact;
2468                                 }
2469                         }
2470                         else {
2471                                 Tnor*= stencilTin;
2472                         }
2473                         
2474                         if (texres.nor) {
2475                                 if ((rgbnor & TEX_NOR)==0) {
2476                                         /* make our own normal */
2477                                         if (rgbnor & TEX_RGB) {
2478                                                 copy_v3_v3(texres.nor, &texres.tr);
2479                                         }
2480                                         else {
2481                                                 float co_nor= 0.5f * cosf(texres.tin - 0.5f);
2482                                                 float si = 0.5f * sinf(texres.tin - 0.5f);
2483                                                 float f1, f2;
2484
2485                                                 f1= shi->vn[0];
2486                                                 f2= shi->vn[1];
2487                                                 texres.nor[0]= f1*co_nor+f2*si;
2488                                                 f1= shi->vn[1];
2489                                                 f2= shi->vn[2];
2490                                                 texres.nor[1]= f1*co_nor+f2*si;
2491                                                 texres.nor[2]= f2*co_nor-f1*si;
2492                                         }
2493                                 }
2494                                 /* warping, local space */
2495                                 if (mtex->mapto & MAP_WARP) {
2496                                         float *warpnor= texres.nor, warpnor_[3];
2497                                         
2498                                         if (use_ntap_bump) {
2499                                                 copy_v3_v3(warpnor_, texres.nor);
2500                                                 warpnor= warpnor_;
2501                                                 normalize_v3(warpnor_);
2502                                         }
2503                                         warpvec[0]= mtex->warpfac*warpnor[0];
2504                                         warpvec[1]= mtex->warpfac*warpnor[1];
2505                                         warpvec[2]= mtex->warpfac*warpnor[2];
2506                                         warp_done = true;
2507                                 }
2508 #if 0                           
2509                                 if (mtex->texflag & MTEX_VIEWSPACE) {
2510                                         /* rotate to global coords */
2511                                         if (mtex->texco==TEXCO_ORCO || mtex->texco==TEXCO_UV) {
2512                                                 if (shi->vlr && shi->obr && shi->obr->ob) {
2513                                                         float len= normalize_v3(texres.nor);
2514                                                         /* can be optimized... (ton) */
2515                                                         mul_mat3_m4_v3(shi->obr->ob->obmat, texres.nor);
2516                                                         mul_mat3_m4_v3(re->viewmat, texres.nor);
2517                                                         normalize_v3_length(texres.nor, len);
2518                                                 }
2519                                         }
2520                                 }
2521 #endif
2522                         }
2523
2524                         /* mapping */
2525                         if (mtex->mapto & (MAP_COL | MAP_COLSPEC | MAP_COLMIR)) {
2526                                 float tcol[3];
2527                                 
2528                                 /* stencil maps on the texture control slider, not texture intensity value */
2529                                 copy_v3_v3(tcol, &texres.tr);
2530
2531                                 if ((rgbnor & TEX_RGB) == 0) {
2532                                         copy_v3_v3(tcol, &mtex->r);
2533                                 }
2534                                 else if (mtex->mapto & MAP_ALPHA) {
2535                                         texres.tin = stencilTin;
2536                                 }
2537                                 else {
2538                                         texres.tin = texres.ta;
2539                                 }
2540                                 
2541                                 /* inverse gamma correction */
2542                                 if (tex->type==TEX_IMAGE) {
2543                                         Image *ima = tex->ima;
2544                                         ImBuf *ibuf = BKE_image_pool_acquire_ibuf(ima, &tex->iuser, re->pool);
2545                                         
2546                                         /* don't linearize float buffers, assumed to be linear */
2547                                         if (ibuf != NULL &&
2548                                             ibuf->rect_float == NULL &&
2549                                             (rgbnor & TEX_RGB) &&
2550                                             R.scene_color_manage)
2551                                         {
2552                                                 IMB_colormanagement_colorspace_to_scene_linear_v3(tcol, ibuf->rect_colorspace);
2553                                         }
2554
2555                                         BKE_image_pool_release_ibuf(ima, ibuf, re->pool);
2556                                 }
2557
2558                                 if (mtex->mapto & MAP_COL) {
2559                                         float colfac= mtex->colfac*stencilTin;
2560                                         texture_rgb_blend(&shi->r, tcol, &shi->r, texres.tin, colfac, mtex->blendtype);
2561                                 }
2562                                 if (mtex->mapto & MAP_COLSPEC) {
2563                                         float colspecfac= mtex->colspecfac*stencilTin;
2564                                         texture_rgb_blend(&shi->specr, tcol, &shi->specr, texres.tin, colspecfac, mtex->blendtype);
2565                                 }
2566                                 if (mtex->mapto & MAP_COLMIR) {
2567                                         float mirrfac= mtex->mirrfac*stencilTin;
2568
2569                                         /* exception for envmap only */
2570                                         if (tex->type==TEX_ENVMAP && mtex->blendtype==MTEX_BLEND) {
2571                                                 fact= texres.tin*mirrfac;
2572                                                 facm= 1.0f- fact;
2573                                                 shi->refcol[0]= fact + facm*shi->refcol[0];
2574                                                 shi->refcol[1]= fact*tcol[0] + facm*shi->refcol[1];
2575                                                 shi->refcol[2]= fact*tcol[1] + facm*shi->refcol[2];
2576                                                 shi->refcol[3]= fact*tcol[2] + facm*shi->refcol[3];
2577                                         }
2578                                         else {
2579                                                 texture_rgb_blend(&shi->mirr, tcol, &shi->mirr, texres.tin, mirrfac, mtex->blendtype);
2580                                         }
2581                                 }
2582                         }
2583                         if ( (mtex->mapto & MAP_NORM) ) {
2584                                 if (texres.nor) {
2585                                         float norfac= mtex->norfac;
2586                                         
2587                                         /* we need to code blending modes for normals too once.. now 1 exception hardcoded */
2588                                         
2589                                         if ((tex->type==TEX_IMAGE) && (tex->imaflag & TEX_NORMALMAP)) {
2590                                                 
2591                                                 found_nmapping = 1;
2592                                                 
2593                                                 /* qdn: for normalmaps, to invert the normalmap vector,
2594                                                  * it is better to negate x & y instead of subtracting the vector as was done before */
2595                                                 if (norfac < 0.0f) {
2596                                                         texres.nor[0] = -texres.nor[0];
2597                                                         texres.nor[1] = -texres.nor[1];
2598                                                 }
2599                                                 fact = Tnor*fabsf(norfac);
2600                                                 if (fact>1.f) fact = 1.f;
2601                                                 facm = 1.f-fact;
2602                                                 if (mtex->normapspace == MTEX_NSPACE_TANGENT) {
2603                                                         /* qdn: tangent space */
2604                                                         float B[3], tv[3];
2605                                                         const float *no = iFirstTimeNMap ? shi->nmapnorm : shi->vn;
2606                                                         iFirstTimeNMap = false;
2607                                                         cross_v3_v3v3(B, no, shi->nmaptang);    /* bitangent */
2608                                                         mul_v3_fl(B, shi->nmaptang[3]);
2609                                                         /* transform norvec from tangent space to object surface in camera space */
2610                                                         tv[0] = texres.nor[0]*shi->nmaptang[0] + texres.nor[1]*B[0] + texres.nor[2]*no[0];
2611                                                         tv[1] = texres.nor[0]*shi->nmaptang[1] + texres.nor[1]*B[1] + texres.nor[2]*no[1];
2612                                                         tv[2] = texres.nor[0]*shi->nmaptang[2] + texres.nor[1]*B[2] + texres.nor[2]*no[2];
2613                                                         shi->vn[0]= facm*no[0] + fact*tv[0];
2614                                                         shi->vn[1]= facm*no[1] + fact*tv[1];
2615                                                         shi->vn[2]= facm*no[2] + fact*tv[2];
2616                                                 }
2617                                                 else {
2618                                                         float nor[3];
2619
2620                                                         copy_v3_v3(nor, texres.nor);
2621
2622                                                         if (mtex->normapspace == MTEX_NSPACE_CAMERA) {
2623                                                                 /* pass */
2624                                                         }
2625                                                         else if (mtex->normapspace == MTEX_NSPACE_WORLD) {
2626                                                                 mul_mat3_m4_v3(re->viewmat, nor);
2627                                                         }
2628                                                         else if (mtex->normapspace == MTEX_NSPACE_OBJECT) {
2629                                                                 if (shi->obr && shi->obr->ob)
2630                                                                         mul_mat3_m4_v3(shi->obr->ob->obmat, nor);
2631                                                                 mul_mat3_m4_v3(re->viewmat, nor);
2632                                                         }
2633
2634                                                         normalize_v3(nor);
2635
2636                                                         /* qdn: worldspace */
2637                                                         shi->vn[0]= facm*shi->vn[0] + fact*nor[0];
2638                                                         shi->vn[1]= facm*shi->vn[1] + fact*nor[1];
2639                                                         shi->vn[2]= facm*shi->vn[2] + fact*nor[2];
2640                                                 }
2641                                         }
2642                                         else {
2643                                                 /* XXX texture node trees don't work for this yet */
2644                                                 if (use_compat_bump || use_ntap_bump) {
2645                                                         shi->vn[0] = texres.nor[0];
2646                                                         shi->vn[1] = texres.nor[1];
2647                                                         shi->vn[2] = texres.nor[2];
2648                                                 }
2649                                                 else {
2650                                                         float nor[3], dot;
2651         
2652                                                         if (shi->mat->mode & MA_TANGENT_V) {
2653                                                                 shi->tang[0]+= Tnor*norfac*texres.nor[0];
2654                                                                 shi->tang[1]+= Tnor*norfac*texres.nor[1];
2655                                                                 shi->tang[2]+= Tnor*norfac*texres.nor[2];
2656                                                         }
2657         
2658                                                         /* prevent bump to become negative normal */
2659                                                         nor[0]= Tnor*norfac*texres.nor[0];
2660                                                         nor[1]= Tnor*norfac*texres.nor[1];
2661                                                         nor[2]= Tnor*norfac*texres.nor[2];
2662                                                         
2663                                                         dot= 0.5f + 0.5f * dot_v3v3(nor, shi->vn);
2664                                                         
2665                                                         shi->vn[0]+= dot*nor[0];
2666                                                         shi->vn[1]+= dot*nor[1];
2667                                                         shi->vn[2]+= dot*nor[2];
2668                                                 }
2669                                         }
2670                                         normalize_v3(shi->vn);
2671                                         
2672                                         /* this makes sure the bump is passed on to the next texture */
2673                                         shi->orn[0]= -shi->vn[0];
2674                                         shi->orn[1]= -shi->vn[1];
2675                                         shi->orn[2]= -shi->vn[2];
2676                                 }
2677                         }
2678
2679                         if ( mtex->mapto & MAP_DISPLACE ) {
2680                                 /* Now that most textures offer both Nor and Intensity, allow  */
2681                                 /* both to work, and let user select with slider.   */
2682                                 if (texres.nor) {
2683                                         float norfac= mtex->norfac;
2684
2685                                         shi->displace[0]+= 0.2f*Tnor*norfac*texres.nor[0];
2686                                         shi->displace[1]+= 0.2f*Tnor*norfac*texres.nor[1];
2687                                         shi->displace[2]+= 0.2f*Tnor*norfac*texres.nor[2];
2688                                 }
2689                                 
2690                                 if (rgbnor & TEX_RGB) {
2691                                         texres.tin = IMB_colormanagement_get_luminance(&texres.tr);
2692                                 }
2693
2694                                 factt= (0.5f-texres.tin)*mtex->dispfac*stencilTin; facmm= 1.0f-factt;
2695
2696                                 if (mtex->blendtype==MTEX_BLEND) {
2697                                         shi->displace[0]= factt*shi->vn[0] + facmm*shi->displace[0];
2698                                         shi->displace[1]= factt*shi->vn[1] + facmm*shi->displace[1];
2699                                         shi->displace[2]= factt*shi->vn[2] + facmm*shi->displace[2];
2700                                 }
2701                                 else if (mtex->blendtype==MTEX_MUL) {
2702                                         shi->displace[0]*= factt*shi->vn[0];
2703                                         shi->displace[1]*= factt*shi->vn[1];
2704                                         shi->displace[2]*= factt*shi->vn[2];
2705                                 }
2706                                 else { /* add or sub */
2707                                         if (mtex->blendtype==MTEX_SUB) factt= -factt;
2708                                         shi->displace[0]+= factt*shi->vn[0];
2709                                         shi->displace[1]+= factt*shi->vn[1];
2710                                         shi->displace[2]+= factt*shi->vn[2];
2711                                 }
2712                         }
2713
2714                         if (mtex->mapto & MAP_VARS) {
2715                                 /* stencil maps on the texture control slider, not texture intensity value */
2716                                 
2717                                 if (rgbnor & TEX_RGB) {
2718                                         if (texres.talpha) texres.tin = texres.ta;
2719                                         else               texres.tin = IMB_colormanagement_get_luminance(&texres.tr);
2720                                 }
2721
2722                                 if (mtex->mapto & MAP_REF) {
2723                                         float difffac= mtex->difffac*stencilTin;
2724
2725                                         shi->refl= texture_value_blend(mtex->def_var, shi->refl, texres.tin, difffac, mtex->blendtype);
2726                                         if (shi->refl<0.0f) shi->refl= 0.0f;
2727                                 }
2728                                 if (mtex->mapto & MAP_SPEC) {
2729                                         float specfac= mtex->specfac*stencilTin;
2730                                         
2731