5f046806bebdd327fcfe4843a2ceab72a4a55ab8
[blender.git] / source / blender / gpu / intern / gpu_material.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) 2006 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Brecht Van Lommel.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/gpu/intern/gpu_material.c
29  *  \ingroup gpu
30  */
31
32
33 #include <math.h>
34 #include <string.h>
35
36 #include "GL/glew.h"
37
38 #include "MEM_guardedalloc.h"
39
40 #include "DNA_lamp_types.h"
41 #include "DNA_material_types.h"
42 #include "DNA_object_types.h"
43 #include "DNA_scene_types.h"
44 #include "DNA_world_types.h"
45
46 #include "BLI_math.h"
47 #include "BLI_blenlib.h"
48 #include "BLI_utildefines.h"
49
50 #include "BKE_anim.h"
51 #include "BKE_colortools.h"
52 #include "BKE_DerivedMesh.h"
53 #include "BKE_global.h"
54 #include "BKE_image.h"
55 #include "BKE_main.h"
56 #include "BKE_node.h"
57 #include "BKE_scene.h"
58 #include "BKE_texture.h"
59
60 #include "IMB_imbuf_types.h"
61
62 #include "GPU_extensions.h"
63 #include "GPU_material.h"
64
65 #include "gpu_codegen.h"
66
67 #include <string.h>
68
69 /* Structs */
70
71 typedef enum DynMatProperty {
72         DYN_LAMP_CO = 1,
73         DYN_LAMP_VEC = 2,
74         DYN_LAMP_IMAT = 4,
75         DYN_LAMP_PERSMAT = 8,
76 } DynMatProperty;
77
78 struct GPUMaterial {
79         Scene *scene;
80         Material *ma;
81
82         /* for creating the material */
83         ListBase nodes;
84         GPUNodeLink *outlink;
85
86         /* for binding the material */
87         GPUPass *pass;
88         GPUVertexAttribs attribs;
89         int bound;
90         int builtins;
91         int alpha, obcolalpha;
92         int dynproperty;
93
94         /* for passing uniforms */
95         int viewmatloc, invviewmatloc;
96         int obmatloc, invobmatloc;
97         int obcolloc, obautobumpscaleloc;
98
99         ListBase lamps;
100 };
101
102 struct GPULamp {
103         Scene *scene;
104         Object *ob;
105         Object *par;
106         Lamp *la;
107
108         int type, mode, lay, hide;
109
110         float dynenergy, dyncol[3];
111         float energy, col[3];
112
113         float co[3], vec[3];
114         float dynco[3], dynvec[3];
115         float obmat[4][4];
116         float imat[4][4];
117         float dynimat[4][4];
118
119         float spotsi, spotbl, k;
120         float dist, att1, att2;
121         float shadow_color[3];
122
123         float bias, d, clipend;
124         int size;
125
126         int falloff_type;
127         struct CurveMapping *curfalloff;
128
129         float winmat[4][4];
130         float viewmat[4][4];
131         float persmat[4][4];
132         float dynpersmat[4][4];
133
134         GPUFrameBuffer *fb;
135         GPUFrameBuffer *blurfb;
136         GPUTexture *tex;
137         GPUTexture *depthtex;
138         GPUTexture *blurtex;
139
140         ListBase materials;
141 };
142
143 /* Forward declaration so shade_light_textures() can use this, while still keeping the code somewhat organized */
144 static void texture_rgb_blend(GPUMaterial *mat, GPUNodeLink *tex, GPUNodeLink *out, GPUNodeLink *fact, GPUNodeLink *facg, int blendtype, GPUNodeLink **in);
145
146 /* Functions */
147
148 static GPUMaterial *GPU_material_construct_begin(Material *ma)
149 {
150         GPUMaterial *material = MEM_callocN(sizeof(GPUMaterial), "GPUMaterial");
151
152         material->ma= ma;
153
154         return material;
155 }
156
157 static void gpu_material_set_attrib_id(GPUMaterial *material)
158 {
159         GPUVertexAttribs *attribs;
160         GPUShader *shader;
161         GPUPass *pass;
162         char name[32];
163         int a, b;
164
165         attribs= &material->attribs;
166         pass= material->pass;
167         if (!pass) {
168                 attribs->totlayer = 0;
169                 return;
170         }
171         
172         shader= GPU_pass_shader(pass);
173         if (!shader) {
174                 attribs->totlayer = 0;
175                 return;
176         }
177
178         /* convert from attribute number to the actual id assigned by opengl,
179          * in case the attrib does not get a valid index back, it was probably
180          * removed by the glsl compiler by dead code elimination */
181
182         for (a=0, b=0; a<attribs->totlayer; a++) {
183                 BLI_snprintf(name, sizeof(name), "att%d", attribs->layer[a].attribid);
184                 attribs->layer[a].glindex = GPU_shader_get_attribute(shader, name);
185
186                 if (attribs->layer[a].glindex >= 0) {
187                         attribs->layer[b] = attribs->layer[a];
188                         b++;
189                 }
190         }
191
192         attribs->totlayer = b;
193 }
194
195 static int GPU_material_construct_end(GPUMaterial *material)
196 {
197         if (material->outlink) {
198                 GPUNodeLink *outlink;
199                 GPUShader *shader;
200
201                 outlink = material->outlink;
202                 material->pass = GPU_generate_pass(&material->nodes, outlink,
203                         &material->attribs, &material->builtins, material->ma->id.name);
204
205                 if (!material->pass)
206                         return 0;
207
208                 gpu_material_set_attrib_id(material);
209                 
210                 shader = GPU_pass_shader(material->pass);
211
212                 if (material->builtins & GPU_VIEW_MATRIX)
213                         material->viewmatloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_VIEW_MATRIX));
214                 if (material->builtins & GPU_INVERSE_VIEW_MATRIX)
215                         material->invviewmatloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_INVERSE_VIEW_MATRIX));
216                 if (material->builtins & GPU_OBJECT_MATRIX)
217                         material->obmatloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_OBJECT_MATRIX));
218                 if (material->builtins & GPU_INVERSE_OBJECT_MATRIX)
219                         material->invobmatloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_INVERSE_OBJECT_MATRIX));
220                 if (material->builtins & GPU_OBCOLOR)
221                         material->obcolloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_OBCOLOR));
222                 if (material->builtins & GPU_AUTO_BUMPSCALE)
223                         material->obautobumpscaleloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_AUTO_BUMPSCALE));
224                 return 1;
225         }
226
227         return 0;
228 }
229
230 void GPU_material_free(Material *ma)
231 {
232         LinkData *link;
233         LinkData *nlink, *mlink, *next;
234
235         for (link=ma->gpumaterial.first; link; link=link->next) {
236                 GPUMaterial *material = link->data;
237
238                 if (material->pass)
239                         GPU_pass_free(material->pass);
240
241                 for (nlink=material->lamps.first; nlink; nlink=nlink->next) {
242                         GPULamp *lamp = nlink->data;
243
244                         for (mlink=lamp->materials.first; mlink; mlink=next) {
245                                 next = mlink->next;
246                                 if (mlink->data == ma)
247                                         BLI_freelinkN(&lamp->materials, mlink);
248                         }
249                 }
250
251                 BLI_freelistN(&material->lamps);
252
253                 MEM_freeN(material);
254         }
255
256         BLI_freelistN(&ma->gpumaterial);
257 }
258
259 void GPU_material_bind(GPUMaterial *material, int oblay, int viewlay, double time, int mipmap)
260 {
261         if (material->pass) {
262                 LinkData *nlink;
263                 GPULamp *lamp;
264
265                 /* handle layer lamps */
266                 for (nlink=material->lamps.first; nlink; nlink=nlink->next) {
267                         lamp= nlink->data;
268
269                         if (!lamp->hide && (lamp->lay & viewlay) && (!(lamp->mode & LA_LAYER) || (lamp->lay & oblay))) {
270                                 lamp->dynenergy = lamp->energy;
271                                 copy_v3_v3(lamp->dyncol, lamp->col);
272                         }
273                         else {
274                                 lamp->dynenergy = 0.0f;
275                                 lamp->dyncol[0]= lamp->dyncol[1]= lamp->dyncol[2] = 0.0f;
276                         }
277                 }
278
279                 GPU_pass_bind(material->pass, time, mipmap);
280                 material->bound = 1;
281         }
282 }
283
284 void GPU_material_bind_uniforms(GPUMaterial *material, float obmat[][4], float viewmat[][4], float viewinv[][4], float obcol[4], float autobumpscale)
285 {
286         if (material->pass) {
287                 GPUShader *shader = GPU_pass_shader(material->pass);
288                 LinkData *nlink;
289                 GPULamp *lamp;
290                 float invmat[4][4], col[4];
291
292                 /* handle builtins */
293                 if (material->builtins & GPU_VIEW_MATRIX) {
294                         GPU_shader_uniform_vector(shader, material->viewmatloc, 16, 1, (float*)viewmat);
295                 }
296                 if (material->builtins & GPU_INVERSE_VIEW_MATRIX) {
297                         GPU_shader_uniform_vector(shader, material->invviewmatloc, 16, 1, (float*)viewinv);
298                 }
299                 if (material->builtins & GPU_OBJECT_MATRIX) {
300                         GPU_shader_uniform_vector(shader, material->obmatloc, 16, 1, (float*)obmat);
301                 }
302                 if (material->builtins & GPU_INVERSE_OBJECT_MATRIX) {
303                         invert_m4_m4(invmat, obmat);
304                         GPU_shader_uniform_vector(shader, material->invobmatloc, 16, 1, (float*)invmat);
305                 }
306                 if (material->builtins & GPU_OBCOLOR) {
307                         copy_v4_v4(col, obcol);
308                         CLAMP(col[3], 0.0f, 1.0f);
309                         GPU_shader_uniform_vector(shader, material->obcolloc, 4, 1, col);
310                 }
311                 if (material->builtins & GPU_AUTO_BUMPSCALE) {
312                         GPU_shader_uniform_vector(shader, material->obautobumpscaleloc, 1, 1, &autobumpscale);
313                 }
314                 /* update lamps */
315                 for (nlink=material->lamps.first; nlink; nlink=nlink->next) {
316                         lamp= nlink->data;
317
318                         if (material->dynproperty & DYN_LAMP_VEC) {
319                                 copy_v3_v3(lamp->dynvec, lamp->vec);
320                                 normalize_v3(lamp->dynvec);
321                                 negate_v3(lamp->dynvec);
322                                 mul_mat3_m4_v3(viewmat, lamp->dynvec);
323                         }
324
325                         if (material->dynproperty & DYN_LAMP_CO) {
326                                 copy_v3_v3(lamp->dynco, lamp->co);
327                                 mul_m4_v3(viewmat, lamp->dynco);
328                         }
329
330                         if (material->dynproperty & DYN_LAMP_IMAT)
331                                 mult_m4_m4m4(lamp->dynimat, lamp->imat, viewinv);
332                         if (material->dynproperty & DYN_LAMP_PERSMAT)
333                         {
334                                 if (!GPU_lamp_has_shadow_buffer(lamp)) /* The lamp matrices are already updated if we're using shadow buffers */
335                                         GPU_lamp_update_buffer_mats(lamp);
336                                 mult_m4_m4m4(lamp->dynpersmat, lamp->persmat, viewinv);
337                         }
338                 }
339
340                 GPU_pass_update_uniforms(material->pass);
341         }
342 }
343
344 void GPU_material_unbind(GPUMaterial *material)
345 {
346         if (material->pass) {
347                 material->bound = 0;
348                 GPU_pass_unbind(material->pass);
349         }
350 }
351
352 int GPU_material_bound(GPUMaterial *material)
353 {
354         return material->bound;
355 }
356
357 void GPU_material_vertex_attributes(GPUMaterial *material, GPUVertexAttribs *attribs)
358 {
359         *attribs = material->attribs;
360 }
361
362 void GPU_material_output_link(GPUMaterial *material, GPUNodeLink *link)
363 {
364         if (!material->outlink)
365                 material->outlink= link;
366 }
367
368 void GPU_material_enable_alpha(GPUMaterial *material)
369 {
370         material->alpha= 1;
371 }
372
373 GPUBlendMode GPU_material_alpha_blend(GPUMaterial *material, float obcol[4])
374 {
375         if (material->alpha || (material->obcolalpha && obcol[3] < 1.0f))
376                 return GPU_BLEND_ALPHA;
377         else
378                 return GPU_BLEND_SOLID;
379 }
380
381 void gpu_material_add_node(GPUMaterial *material, GPUNode *node)
382 {
383         BLI_addtail(&material->nodes, node);
384 }
385
386 /* Code generation */
387
388 static int gpu_do_color_management(GPUMaterial *mat)
389 {
390         return ((mat->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT) &&
391            !((mat->scene->gm.flag & GAME_GLSL_NO_COLOR_MANAGEMENT)));
392 }
393
394 static GPUNodeLink *lamp_get_visibility(GPUMaterial *mat, GPULamp *lamp, GPUNodeLink **lv, GPUNodeLink **dist)
395 {
396         GPUNodeLink *visifac, *inpr;
397
398         /* from get_lamp_visibility */
399         if (lamp->type==LA_SUN || lamp->type==LA_HEMI) {
400                 mat->dynproperty |= DYN_LAMP_VEC;
401                 GPU_link(mat, "lamp_visibility_sun_hemi", GPU_dynamic_uniform(lamp->dynvec, GPU_DYNAMIC_LAMP_DYNVEC, lamp->ob), lv, dist, &visifac);
402                 return visifac;
403         }
404         else {
405                 mat->dynproperty |= DYN_LAMP_CO;
406                 GPU_link(mat, "lamp_visibility_other", GPU_builtin(GPU_VIEW_POSITION), GPU_dynamic_uniform(lamp->dynco, GPU_DYNAMIC_LAMP_DYNCO, lamp->ob), lv, dist, &visifac);
407
408                 if (lamp->type==LA_AREA)
409                         return visifac;
410
411                 switch (lamp->falloff_type) {
412                         case LA_FALLOFF_CONSTANT:
413                                 break;
414                         case LA_FALLOFF_INVLINEAR:
415                                 GPU_link(mat, "lamp_falloff_invlinear", GPU_uniform(&lamp->dist), *dist, &visifac);
416                                 break;
417                         case LA_FALLOFF_INVSQUARE:
418                                 GPU_link(mat, "lamp_falloff_invsquare", GPU_uniform(&lamp->dist), *dist, &visifac);
419                                 break;
420                         case LA_FALLOFF_SLIDERS:
421                                 GPU_link(mat, "lamp_falloff_sliders", GPU_uniform(&lamp->dist), GPU_uniform(&lamp->att1), GPU_uniform(&lamp->att2), *dist, &visifac);
422                                 break;
423                         case LA_FALLOFF_CURVE:
424                                 {
425                                         float *array;
426                                         int size;
427
428                                         curvemapping_table_RGBA(lamp->curfalloff, &array, &size);
429                                         GPU_link(mat, "lamp_falloff_curve", GPU_uniform(&lamp->dist), GPU_texture(size, array), *dist, &visifac);
430                                 }
431                                 break;
432                 }
433
434                 if (lamp->mode & LA_SPHERE)
435                         GPU_link(mat, "lamp_visibility_sphere", GPU_uniform(&lamp->dist), *dist, visifac, &visifac);
436
437                 if (lamp->type == LA_SPOT) {
438                         if (lamp->mode & LA_SQUARE) {
439                                 mat->dynproperty |= DYN_LAMP_VEC|DYN_LAMP_IMAT;
440                                 GPU_link(mat, "lamp_visibility_spot_square", GPU_dynamic_uniform(lamp->dynvec, GPU_DYNAMIC_LAMP_DYNVEC, lamp->ob), GPU_dynamic_uniform((float*)lamp->dynimat, GPU_DYNAMIC_LAMP_DYNIMAT, lamp->ob), *lv, &inpr);
441                         }
442                         else {
443                                 mat->dynproperty |= DYN_LAMP_VEC;
444                                 GPU_link(mat, "lamp_visibility_spot_circle", GPU_dynamic_uniform(lamp->dynvec, GPU_DYNAMIC_LAMP_DYNVEC, lamp->ob), *lv, &inpr);
445                         }
446                         
447                         GPU_link(mat, "lamp_visibility_spot", GPU_uniform(&lamp->spotsi), GPU_uniform(&lamp->spotbl), inpr, visifac, &visifac);
448                 }
449
450                 GPU_link(mat, "lamp_visibility_clamp", visifac, &visifac);
451
452                 return visifac;
453         }
454 }
455
456 #if 0
457 static void area_lamp_vectors(LampRen *lar)
458 {
459         float xsize= 0.5*lar->area_size, ysize= 0.5*lar->area_sizey, multifac;
460
461         /* make it smaller, so area light can be multisampled */
462         multifac= 1.0f/sqrt((float)lar->ray_totsamp);
463         xsize *= multifac;
464         ysize *= multifac;
465
466         /* corner vectors */
467         lar->area[0][0]= lar->co[0] - xsize*lar->mat[0][0] - ysize*lar->mat[1][0];
468         lar->area[0][1]= lar->co[1] - xsize*lar->mat[0][1] - ysize*lar->mat[1][1];
469         lar->area[0][2]= lar->co[2] - xsize*lar->mat[0][2] - ysize*lar->mat[1][2];
470
471         /* corner vectors */
472         lar->area[1][0]= lar->co[0] - xsize*lar->mat[0][0] + ysize*lar->mat[1][0];
473         lar->area[1][1]= lar->co[1] - xsize*lar->mat[0][1] + ysize*lar->mat[1][1];
474         lar->area[1][2]= lar->co[2] - xsize*lar->mat[0][2] + ysize*lar->mat[1][2];
475
476         /* corner vectors */
477         lar->area[2][0]= lar->co[0] + xsize*lar->mat[0][0] + ysize*lar->mat[1][0];
478         lar->area[2][1]= lar->co[1] + xsize*lar->mat[0][1] + ysize*lar->mat[1][1];
479         lar->area[2][2]= lar->co[2] + xsize*lar->mat[0][2] + ysize*lar->mat[1][2];
480
481         /* corner vectors */
482         lar->area[3][0]= lar->co[0] + xsize*lar->mat[0][0] - ysize*lar->mat[1][0];
483         lar->area[3][1]= lar->co[1] + xsize*lar->mat[0][1] - ysize*lar->mat[1][1];
484         lar->area[3][2]= lar->co[2] + xsize*lar->mat[0][2] - ysize*lar->mat[1][2];
485         /* only for correction button size, matrix size works on energy */
486         lar->areasize= lar->dist*lar->dist/(4.0*xsize*ysize);
487 }
488 #endif
489
490 static void ramp_blend(GPUMaterial *mat, GPUNodeLink *fac, GPUNodeLink *col1, GPUNodeLink *col2, int type, GPUNodeLink **outcol)
491 {
492         static const char *names[] = {"mix_blend", "mix_add", "mix_mult", "mix_sub",
493                 "mix_screen", "mix_div", "mix_diff", "mix_dark", "mix_light",
494                 "mix_overlay", "mix_dodge", "mix_burn", "mix_hue", "mix_sat",
495                 "mix_val", "mix_color", "mix_soft", "mix_linear"};
496
497         GPU_link(mat, names[type], fac, col1, col2, outcol);
498 }
499
500 static void do_colorband_blend(GPUMaterial *mat, ColorBand *coba, GPUNodeLink *fac, float rampfac, int type, GPUNodeLink *incol, GPUNodeLink **outcol)
501 {
502         GPUNodeLink *tmp, *alpha, *col;
503         float *array;
504         int size;
505
506         /* do colorband */
507         colorband_table_RGBA(coba, &array, &size);
508         GPU_link(mat, "valtorgb", fac, GPU_texture(size, array), &col, &tmp);
509
510         /* use alpha in fac */
511         GPU_link(mat, "mtex_alpha_from_col", col, &alpha);
512         GPU_link(mat, "math_multiply", alpha, GPU_uniform(&rampfac), &fac);
513
514         /* blending method */
515         ramp_blend(mat, fac, incol, col, type, outcol);
516 }
517
518 static void ramp_diffuse_result(GPUShadeInput *shi, GPUNodeLink **diff)
519 {
520         Material *ma= shi->mat;
521         GPUMaterial *mat= shi->gpumat;
522         GPUNodeLink *fac;
523
524         if (!(mat->scene->gm.flag & GAME_GLSL_NO_RAMPS)) {
525                 if (ma->ramp_col) {
526                         if (ma->rampin_col==MA_RAMP_IN_RESULT) {
527                                 GPU_link(mat, "ramp_rgbtobw", *diff, &fac);
528                                 
529                                 /* colorband + blend */
530                                 do_colorband_blend(mat, ma->ramp_col, fac, ma->rampfac_col, ma->rampblend_col, *diff, diff);
531                         }
532                 }
533         }
534 }
535
536 static void add_to_diffuse(GPUMaterial *mat, Material *ma, GPUShadeInput *shi, GPUNodeLink *is, GPUNodeLink *rgb, GPUNodeLink **diff)
537 {
538         GPUNodeLink *fac, *tmp, *addcol;
539         
540         if (!(mat->scene->gm.flag & GAME_GLSL_NO_RAMPS) &&
541            ma->ramp_col && (ma->mode & MA_RAMP_COL)) {
542                 /* MA_RAMP_IN_RESULT is exceptional */
543                 if (ma->rampin_col==MA_RAMP_IN_RESULT) {
544                         addcol = shi->rgb;
545                 }
546                 else {
547                         /* input */
548                         switch (ma->rampin_col) {
549                         case MA_RAMP_IN_ENERGY:
550                                 GPU_link(mat, "ramp_rgbtobw", rgb, &fac);
551                                 break;
552                         case MA_RAMP_IN_SHADER:
553                                 fac= is;
554                                 break;
555                         case MA_RAMP_IN_NOR:
556                                 GPU_link(mat, "vec_math_dot", shi->view, shi->vn, &tmp, &fac);
557                                 break;
558                         default:
559                                 GPU_link(mat, "set_value_zero", &fac);
560                                 break;
561                         }
562
563                         /* colorband + blend */
564                         do_colorband_blend(mat, ma->ramp_col, fac, ma->rampfac_col, ma->rampblend_col, shi->rgb, &addcol);
565                 }
566         }
567         else
568                 addcol = shi->rgb;
569
570         /* output to */
571         GPU_link(mat, "shade_madd_clamped", *diff, rgb, addcol, diff);
572 }
573
574 static void ramp_spec_result(GPUShadeInput *shi, GPUNodeLink **spec)
575 {
576         Material *ma= shi->mat;
577         GPUMaterial *mat= shi->gpumat;
578         GPUNodeLink *fac;
579
580         if (!(mat->scene->gm.flag & GAME_GLSL_NO_RAMPS) &&
581            ma->ramp_spec && ma->rampin_spec==MA_RAMP_IN_RESULT) {
582                 GPU_link(mat, "ramp_rgbtobw", *spec, &fac);
583                 
584                 /* colorband + blend */
585                 do_colorband_blend(mat, ma->ramp_spec, fac, ma->rampfac_spec, ma->rampblend_spec, *spec, spec);
586         }
587 }
588
589 static void do_specular_ramp(GPUShadeInput *shi, GPUNodeLink *is, GPUNodeLink *t, GPUNodeLink **spec)
590 {
591         Material *ma= shi->mat;
592         GPUMaterial *mat= shi->gpumat;
593         GPUNodeLink *fac, *tmp;
594
595         *spec = shi->specrgb;
596
597         /* MA_RAMP_IN_RESULT is exception */
598         if (ma->ramp_spec && (ma->rampin_spec!=MA_RAMP_IN_RESULT)) {
599                 
600                 /* input */
601                 switch (ma->rampin_spec) {
602                 case MA_RAMP_IN_ENERGY:
603                         fac = t;
604                         break;
605                 case MA_RAMP_IN_SHADER:
606                         fac = is;
607                         break;
608                 case MA_RAMP_IN_NOR:
609                         GPU_link(mat, "vec_math_dot", shi->view, shi->vn, &tmp, &fac);
610                         break;
611                 default:
612                         GPU_link(mat, "set_value_zero", &fac);
613                         break;
614                 }
615                 
616                 /* colorband + blend */
617                 do_colorband_blend(mat, ma->ramp_spec, fac, ma->rampfac_spec, ma->rampblend_spec, *spec, spec);
618         }
619 }
620
621 static void add_user_list(ListBase *list, void *data)
622 {
623         LinkData *link = MEM_callocN(sizeof(LinkData), "GPULinkData");
624         link->data = data;
625         BLI_addtail(list, link);
626 }
627
628 static void shade_light_textures(GPUMaterial *mat, GPULamp *lamp, GPUNodeLink **rgb)
629 {
630         GPUNodeLink *tex_rgb;
631         MTex *mtex = NULL;
632         int i;
633         float one = 1.f;
634
635         for (i=0; i<MAX_MTEX; ++i) {
636                 mtex = lamp->la->mtex[i];
637
638                 if (mtex && mtex->tex->type & TEX_IMAGE && mtex->tex->ima) {
639                         mat->dynproperty |= DYN_LAMP_PERSMAT;
640
641                         GPU_link(mat, "shade_light_texture",
642                                 GPU_builtin(GPU_VIEW_POSITION),
643                                 GPU_image(mtex->tex->ima, &mtex->tex->iuser),
644                                 GPU_dynamic_uniform((float*)lamp->dynpersmat, GPU_DYNAMIC_LAMP_DYNPERSMAT, lamp->ob),
645                                 &tex_rgb);
646                         texture_rgb_blend(mat, tex_rgb, *rgb, GPU_uniform(&one), GPU_uniform(&mtex->colfac), mtex->blendtype, rgb); 
647                 }
648         }
649 }
650
651 static void shade_one_light(GPUShadeInput *shi, GPUShadeResult *shr, GPULamp *lamp)
652 {
653         Material *ma= shi->mat;
654         GPUMaterial *mat= shi->gpumat;
655         GPUNodeLink *lv, *dist, *visifac, *is, *inp, *i, *vn, *view;
656         GPUNodeLink *outcol, *specfac, *t, *shadfac= NULL, *lcol;
657         float one = 1.0f;
658
659         if ((lamp->mode & LA_ONLYSHADOW) && !(ma->mode & MA_SHADOW))
660                 return;
661         
662         vn= shi->vn;
663         view= shi->view;
664
665         visifac= lamp_get_visibility(mat, lamp, &lv, &dist);
666
667         /*if (ma->mode & MA_TANGENT_V)
668                 GPU_link(mat, "shade_tangent_v", lv, GPU_attribute(CD_TANGENT, ""), &vn);*/
669         
670         GPU_link(mat, "shade_inp", vn, lv, &inp);
671
672         if (lamp->mode & LA_NO_DIFF) {
673                 GPU_link(mat, "shade_is_no_diffuse", &is);
674         }
675         else if (lamp->type == LA_HEMI) {
676                 GPU_link(mat, "shade_is_hemi", inp, &is);
677         }
678         else {
679                 if (lamp->type == LA_AREA) {
680                         float area[4][4]= {{0.0f}}, areasize= 0.0f;
681
682                         mat->dynproperty |= DYN_LAMP_VEC|DYN_LAMP_CO;
683                         GPU_link(mat, "shade_inp_area", GPU_builtin(GPU_VIEW_POSITION), GPU_dynamic_uniform(lamp->dynco, GPU_DYNAMIC_LAMP_DYNCO, lamp->ob), GPU_dynamic_uniform(lamp->dynvec, GPU_DYNAMIC_LAMP_DYNVEC, lamp->ob), vn, GPU_uniform((float*)area),
684                                 GPU_uniform(&areasize), GPU_uniform(&lamp->k), &inp);
685                 }
686
687                 is= inp; /* Lambert */
688
689                 if (!(mat->scene->gm.flag & GAME_GLSL_NO_SHADERS)) {
690                         if (ma->diff_shader==MA_DIFF_ORENNAYAR)
691                                 GPU_link(mat, "shade_diffuse_oren_nayer", inp, vn, lv, view, GPU_uniform(&ma->roughness), &is);
692                         else if (ma->diff_shader==MA_DIFF_TOON)
693                                 GPU_link(mat, "shade_diffuse_toon", vn, lv, view, GPU_uniform(&ma->param[0]), GPU_uniform(&ma->param[1]), &is);
694                         else if (ma->diff_shader==MA_DIFF_MINNAERT)
695                                 GPU_link(mat, "shade_diffuse_minnaert", inp, vn, view, GPU_uniform(&ma->darkness), &is);
696                         else if (ma->diff_shader==MA_DIFF_FRESNEL)
697                                 GPU_link(mat, "shade_diffuse_fresnel", vn, lv, view, GPU_uniform(&ma->param[0]), GPU_uniform(&ma->param[1]), &is);
698                 }
699         }
700
701         if (!(mat->scene->gm.flag & GAME_GLSL_NO_SHADERS))
702                 if (ma->shade_flag & MA_CUBIC)
703                         GPU_link(mat, "shade_cubic", is, &is);
704         
705         i = is;
706         GPU_link(mat, "shade_visifac", i, visifac, shi->refl, &i);
707         
708         GPU_link(mat, "shade_mul_value", i, GPU_dynamic_uniform(lamp->dyncol, GPU_DYNAMIC_LAMP_DYNCOL, lamp->ob), &lcol);
709         shade_light_textures(mat, lamp, &lcol);
710
711 #if 0
712         if (ma->mode & MA_TANGENT_VN)
713                 GPU_link(mat, "shade_tangent_v_spec", GPU_attribute(CD_TANGENT, ""), &vn);
714 #endif
715
716         /* this replaces if (i > 0.0) conditional until that is supported */
717         // done in shade_visifac now, GPU_link(mat, "mtex_value_clamp_positive", i, &i);
718
719         if ((ma->mode & MA_SHADOW) && GPU_lamp_has_shadow_buffer(lamp)) {
720                 if (!(mat->scene->gm.flag & GAME_GLSL_NO_SHADOWS)) {
721                         mat->dynproperty |= DYN_LAMP_PERSMAT;
722                         
723                         if (lamp->la->shadowmap_type == LA_SHADMAP_VARIANCE) {
724                                 GPU_link(mat, "test_shadowbuf_vsm",
725                                         GPU_builtin(GPU_VIEW_POSITION),
726                                         GPU_dynamic_texture(lamp->tex, GPU_DYNAMIC_SAMPLER_2DSHADOW, lamp->ob),
727                                         GPU_dynamic_uniform((float*)lamp->dynpersmat, GPU_DYNAMIC_LAMP_DYNPERSMAT, lamp->ob),
728                                         GPU_uniform(&lamp->bias), GPU_uniform(&lamp->la->bleedbias), inp, &shadfac);
729                         } else {
730                                 GPU_link(mat, "test_shadowbuf",
731                                         GPU_builtin(GPU_VIEW_POSITION),
732                                         GPU_dynamic_texture(lamp->tex, GPU_DYNAMIC_SAMPLER_2DSHADOW, lamp->ob),
733                                         GPU_dynamic_uniform((float*)lamp->dynpersmat, GPU_DYNAMIC_LAMP_DYNPERSMAT, lamp->ob),
734                                         GPU_uniform(&lamp->bias), inp, &shadfac);
735                         }
736                         
737                         if (lamp->mode & LA_ONLYSHADOW) {
738                                 GPU_link(mat, "shade_only_shadow", i, shadfac,
739                                         GPU_dynamic_uniform(&lamp->dynenergy, GPU_DYNAMIC_LAMP_DYNENERGY, lamp->ob), &shadfac);
740                                 
741                                 if (!(lamp->mode & LA_NO_DIFF)) {
742                                         GPU_link(mat, "mix_mult", shadfac, shr->diff,
743                                                 GPU_uniform(lamp->shadow_color), &shr->diff);
744                                 }
745
746                                 if (!(lamp->mode & LA_NO_SPEC))
747                                         GPU_link(mat, "shade_only_shadow_specular", shadfac, shi->specrgb,
748                                                 shr->spec, &shr->spec);
749                                 
750                                 add_user_list(&mat->lamps, lamp);
751                                 add_user_list(&lamp->materials, shi->gpumat->ma);
752                                 return;
753                         }
754                 }
755         }
756         else if ((mat->scene->gm.flag & GAME_GLSL_NO_SHADOWS) && (lamp->mode & LA_ONLYSHADOW)) {
757                 add_user_list(&mat->lamps, lamp);
758                 add_user_list(&lamp->materials, shi->gpumat->ma);
759                 return;
760         }
761         else
762                 GPU_link(mat, "set_value", GPU_uniform(&one), &shadfac);
763
764         if (GPU_link_changed(shi->refl) || ma->ref != 0.0f) {
765                 if (!(lamp->mode & LA_NO_DIFF)) {
766                         GPUNodeLink *rgb;
767                         GPU_link(mat, "shade_mul_value", i, lcol, &rgb);
768                         GPU_link(mat, "mtex_value_invert", shadfac, &shadfac);
769                         GPU_link(mat, "mix_mult",  shadfac, rgb, GPU_uniform(lamp->shadow_color), &rgb);
770                         GPU_link(mat, "mtex_value_invert", shadfac, &shadfac);
771             add_to_diffuse(mat, ma, shi, is, rgb, &shr->diff);
772                 }
773         }
774
775         if (mat->scene->gm.flag & GAME_GLSL_NO_SHADERS);
776         else if (!(lamp->mode & LA_NO_SPEC) && !(lamp->mode & LA_ONLYSHADOW) &&
777            (GPU_link_changed(shi->spec) || ma->spec != 0.0f)) {
778                 if (lamp->type == LA_HEMI) {
779                         GPU_link(mat, "shade_hemi_spec", vn, lv, view, GPU_uniform(&ma->spec), shi->har, visifac, &t);
780                         GPU_link(mat, "shade_add_spec", t, lcol, shi->specrgb, &outcol);
781                         GPU_link(mat, "shade_add_clamped", shr->spec, outcol, &shr->spec);
782                 }
783                 else {
784                         if (ma->spec_shader==MA_SPEC_PHONG)
785                                 GPU_link(mat, "shade_phong_spec", vn, lv, view, shi->har, &specfac);
786                         else if (ma->spec_shader==MA_SPEC_COOKTORR)
787                                 GPU_link(mat, "shade_cooktorr_spec", vn, lv, view, shi->har, &specfac);
788                         else if (ma->spec_shader==MA_SPEC_BLINN)
789                                 GPU_link(mat, "shade_blinn_spec", vn, lv, view, GPU_uniform(&ma->refrac), shi->har, &specfac);
790                         else if (ma->spec_shader==MA_SPEC_WARDISO)
791                                 GPU_link(mat, "shade_wardiso_spec", vn, lv, view, GPU_uniform(&ma->rms), &specfac);
792                         else
793                                 GPU_link(mat, "shade_toon_spec", vn, lv, view, GPU_uniform(&ma->param[2]), GPU_uniform(&ma->param[3]), &specfac);
794
795                         if (lamp->type==LA_AREA)
796                                 GPU_link(mat, "shade_spec_area_inp", specfac, inp, &specfac);
797
798                         GPU_link(mat, "shade_spec_t", shadfac, shi->spec, visifac, specfac, &t); 
799
800                         if (ma->mode & MA_RAMP_SPEC) {
801                                 GPUNodeLink *spec;
802                                 do_specular_ramp(shi, specfac, t, &spec);
803                                 GPU_link(mat, "shade_add_spec", t, lcol, spec, &outcol);
804                                 GPU_link(mat, "shade_add_clamped", shr->spec, outcol, &shr->spec);
805                         }
806                         else {
807                                 GPU_link(mat, "shade_add_spec", t, lcol, shi->specrgb, &outcol);
808                                 GPU_link(mat, "shade_add_clamped", shr->spec, outcol, &shr->spec);
809                         }
810                 }
811         }
812
813         add_user_list(&mat->lamps, lamp);
814         add_user_list(&lamp->materials, shi->gpumat->ma);
815 }
816
817 static void material_lights(GPUShadeInput *shi, GPUShadeResult *shr)
818 {
819         Base *base;
820         Object *ob;
821         Scene *sce_iter;
822         GPULamp *lamp;
823         
824         for (SETLOOPER(shi->gpumat->scene, sce_iter, base)) {
825                 ob= base->object;
826
827                 if (ob->type==OB_LAMP) {
828                         lamp = GPU_lamp_from_blender(shi->gpumat->scene, ob, NULL);
829                         if (lamp)
830                                 shade_one_light(shi, shr, lamp);
831                 }
832
833                 if (ob->transflag & OB_DUPLI) {
834                         DupliObject *dob;
835                         ListBase *lb = object_duplilist(shi->gpumat->scene, ob);
836                         
837                         for (dob=lb->first; dob; dob=dob->next) {
838                                 Object *ob_iter = dob->ob;
839
840                                 if (ob_iter->type==OB_LAMP) {
841                                         copy_m4_m4(ob_iter->obmat, dob->mat);
842
843                                         lamp = GPU_lamp_from_blender(shi->gpumat->scene, ob_iter, ob);
844                                         if (lamp)
845                                                 shade_one_light(shi, shr, lamp);
846                                 }
847                         }
848                         
849                         free_object_duplilist(lb);
850                 }
851         }
852 }
853
854 static void texture_rgb_blend(GPUMaterial *mat, GPUNodeLink *tex, GPUNodeLink *out, GPUNodeLink *fact, GPUNodeLink *facg, int blendtype, GPUNodeLink **in)
855 {
856         switch (blendtype) {
857         case MTEX_BLEND:
858                 GPU_link(mat, "mtex_rgb_blend", out, tex, fact, facg, in);
859                 break;
860         case MTEX_MUL:
861                 GPU_link(mat, "mtex_rgb_mul", out, tex, fact, facg, in);
862                 break;
863         case MTEX_SCREEN:
864                 GPU_link(mat, "mtex_rgb_screen", out, tex, fact, facg, in);
865                 break;
866         case MTEX_OVERLAY:
867                 GPU_link(mat, "mtex_rgb_overlay", out, tex, fact, facg, in);
868                 break;
869         case MTEX_SUB:
870                 GPU_link(mat, "mtex_rgb_sub", out, tex, fact, facg, in);
871                 break;
872         case MTEX_ADD:
873                 GPU_link(mat, "mtex_rgb_add", out, tex, fact, facg, in);
874                 break;
875         case MTEX_DIV:
876                 GPU_link(mat, "mtex_rgb_div", out, tex, fact, facg, in);
877                 break;
878         case MTEX_DIFF:
879                 GPU_link(mat, "mtex_rgb_diff", out, tex, fact, facg, in);
880                 break;
881         case MTEX_DARK:
882                 GPU_link(mat, "mtex_rgb_dark", out, tex, fact, facg, in);
883                 break;
884         case MTEX_LIGHT:
885                 GPU_link(mat, "mtex_rgb_light", out, tex, fact, facg, in);
886                 break;
887         case MTEX_BLEND_HUE:
888                 GPU_link(mat, "mtex_rgb_hue", out, tex, fact, facg, in);
889                 break;
890         case MTEX_BLEND_SAT:
891                 GPU_link(mat, "mtex_rgb_sat", out, tex, fact, facg, in);
892                 break;
893         case MTEX_BLEND_VAL:
894                 GPU_link(mat, "mtex_rgb_val", out, tex, fact, facg, in);
895                 break;
896         case MTEX_BLEND_COLOR:
897                 GPU_link(mat, "mtex_rgb_color", out, tex, fact, facg, in);
898                 break;
899         default:
900                 GPU_link(mat, "set_rgb_zero", &in);
901                 break;
902         }
903 }
904
905 static void texture_value_blend(GPUMaterial *mat, GPUNodeLink *tex, GPUNodeLink *out, GPUNodeLink *fact, GPUNodeLink *facg, int blendtype, GPUNodeLink **in)
906 {
907         switch (blendtype) {
908         case MTEX_BLEND:
909                 GPU_link(mat, "mtex_value_blend", out, tex, fact, facg, in);
910                 break;
911         case MTEX_MUL:
912                 GPU_link(mat, "mtex_value_mul", out, tex, fact, facg, in);
913                 break;
914         case MTEX_SCREEN:
915                 GPU_link(mat, "mtex_value_screen", out, tex, fact, facg, in);
916                 break;
917         case MTEX_SUB:
918                 GPU_link(mat, "mtex_value_sub", out, tex, fact, facg, in);
919                 break;
920         case MTEX_ADD:
921                 GPU_link(mat, "mtex_value_add", out, tex, fact, facg, in);
922                 break;
923         case MTEX_DIV:
924                 GPU_link(mat, "mtex_value_div", out, tex, fact, facg, in);
925                 break;
926         case MTEX_DIFF:
927                 GPU_link(mat, "mtex_value_diff", out, tex, fact, facg, in);
928                 break;
929         case MTEX_DARK:
930                 GPU_link(mat, "mtex_value_dark", out, tex, fact, facg, in);
931                 break;
932         case MTEX_LIGHT:
933                 GPU_link(mat, "mtex_value_light", out, tex, fact, facg, in);
934                 break;
935         default:
936                 GPU_link(mat, "set_value_zero", &in);
937                 break;
938         }
939 }
940
941 static void do_material_tex(GPUShadeInput *shi)
942 {
943         Material *ma= shi->mat;
944         GPUMaterial *mat= shi->gpumat;
945         MTex *mtex;
946         Tex *tex;
947         GPUNodeLink *texco, *tin, *trgb, *tnor, *tcol, *stencil, *tnorfac;
948         GPUNodeLink *texco_norm, *texco_orco, *texco_object;
949         GPUNodeLink *texco_global, *texco_uv = NULL;
950         GPUNodeLink *newnor, *orn;
951         /*char *lastuvname = NULL;*/ /*UNUSED*/
952         float one = 1.0f, norfac, ofs[3];
953         int tex_nr, rgbnor, talpha;
954         int init_done = 0, iBumpSpacePrev = 0; /* Not necessary, quiting gcc warning. */
955         GPUNodeLink *vNorg, *vNacc, *fPrevMagnitude;
956         int iFirstTimeNMap=1;
957         int found_deriv_map = 0;
958
959         GPU_link(mat, "set_value", GPU_uniform(&one), &stencil);
960
961         GPU_link(mat, "texco_norm", GPU_builtin(GPU_VIEW_NORMAL), &texco_norm);
962         GPU_link(mat, "texco_orco", GPU_attribute(CD_ORCO, ""), &texco_orco);
963         GPU_link(mat, "texco_object", GPU_builtin(GPU_INVERSE_VIEW_MATRIX),
964                 GPU_builtin(GPU_INVERSE_OBJECT_MATRIX),
965                 GPU_builtin(GPU_VIEW_POSITION), &texco_object);
966         //GPU_link(mat, "texco_tangent", GPU_attribute(CD_TANGENT, ""), &texco_tangent);
967         GPU_link(mat, "texco_global", GPU_builtin(GPU_INVERSE_VIEW_MATRIX),
968                 GPU_builtin(GPU_VIEW_POSITION), &texco_global);
969
970         orn= texco_norm;
971
972         /* go over texture slots */
973         for (tex_nr=0; tex_nr<MAX_MTEX; tex_nr++) {
974                 /* separate tex switching */
975                 if (ma->septex & (1<<tex_nr)) continue;
976                 
977                 if (ma->mtex[tex_nr]) {
978                         mtex= ma->mtex[tex_nr];
979                         
980                         tex= mtex->tex;
981                         if (tex == NULL) continue;
982
983                         /* which coords */
984                         if (mtex->texco==TEXCO_ORCO)
985                                 texco= texco_orco;
986                         else if (mtex->texco==TEXCO_OBJECT)
987                                 texco= texco_object;
988                         else if (mtex->texco==TEXCO_NORM)
989                                 texco= orn;
990                         else if (mtex->texco==TEXCO_TANGENT)
991                                 texco= texco_object;
992                         else if (mtex->texco==TEXCO_GLOB)
993                                 texco= texco_global;
994                         else if (mtex->texco==TEXCO_REFL) {
995                                 GPU_link(mat, "texco_refl", shi->vn, shi->view, &shi->ref);
996                                 texco= shi->ref;
997                         }
998                         else if (mtex->texco==TEXCO_UV) {
999                                 if (1) { //!(texco_uv && strcmp(mtex->uvname, lastuvname) == 0)) {
1000                                         GPU_link(mat, "texco_uv", GPU_attribute(CD_MTFACE, mtex->uvname), &texco_uv);
1001                                         /*lastuvname = mtex->uvname;*/ /*UNUSED*/
1002                                 }
1003                                 texco= texco_uv;
1004                         }
1005                         else
1006                                 continue;
1007
1008                         /* in case of uv, this would just undo a multiplication in texco_uv */
1009                         if (mtex->texco != TEXCO_UV)
1010                                 GPU_link(mat, "mtex_2d_mapping", texco, &texco);
1011
1012                         if (mtex->size[0] != 1.0f || mtex->size[1] != 1.0f || mtex->size[2] != 1.0f)
1013                                 GPU_link(mat, "mtex_mapping_size", texco, GPU_uniform(mtex->size), &texco);
1014
1015                         ofs[0] = mtex->ofs[0] + 0.5f - 0.5f*mtex->size[0];
1016                         ofs[1] = mtex->ofs[1] + 0.5f - 0.5f*mtex->size[1];
1017                         ofs[2] = 0.0f;
1018                         if (ofs[0] != 0.0f || ofs[1] != 0.0f || ofs[2] != 0.0f)
1019                                 GPU_link(mat, "mtex_mapping_ofs", texco, GPU_uniform(ofs), &texco);
1020
1021                         talpha = 0;
1022
1023                         if (tex && tex->type == TEX_IMAGE && tex->ima) {
1024                                 GPU_link(mat, "mtex_image", texco, GPU_image(tex->ima, &tex->iuser), &tin, &trgb);
1025                                 rgbnor= TEX_RGB;
1026
1027                                 if (tex->imaflag & TEX_USEALPHA)
1028                                         talpha= 1;
1029                         }
1030                         else continue;
1031
1032                         /* texture output */
1033                         if ((rgbnor & TEX_RGB) && (mtex->texflag & MTEX_RGBTOINT)) {
1034                                 GPU_link(mat, "mtex_rgbtoint", trgb, &tin);
1035                                 rgbnor -= TEX_RGB;
1036                         }
1037
1038                         if (mtex->texflag & MTEX_NEGATIVE) {
1039                                 if (rgbnor & TEX_RGB)
1040                                         GPU_link(mat, "mtex_rgb_invert", trgb, &trgb);
1041                                 else
1042                                         GPU_link(mat, "mtex_value_invert", tin, &tin);
1043                         }
1044
1045                         if (mtex->texflag & MTEX_STENCIL) {
1046                                 if (rgbnor & TEX_RGB)
1047                                         GPU_link(mat, "mtex_rgb_stencil", stencil, trgb, &stencil, &trgb);
1048                                 else
1049                                         GPU_link(mat, "mtex_value_stencil", stencil, tin, &stencil, &tin);
1050                         }
1051
1052                         /* mapping */
1053                         if (mtex->mapto & (MAP_COL+MAP_COLSPEC)) {
1054                                 /* stencil maps on the texture control slider, not texture intensity value */
1055                                 if ((rgbnor & TEX_RGB)==0) {
1056                                         GPU_link(mat, "set_rgb", GPU_uniform(&mtex->r), &tcol);
1057                                 }
1058                                 else {
1059                                         GPU_link(mat, "set_rgba", trgb, &tcol);
1060
1061                                         if (mtex->mapto & MAP_ALPHA)
1062                                                 GPU_link(mat, "set_value", stencil, &tin);
1063                                         else if (talpha)
1064                                                 GPU_link(mat, "mtex_alpha_from_col", trgb, &tin);
1065                                         else
1066                                                 GPU_link(mat, "set_value_one", &tin);
1067                                 }
1068
1069                                 if (tex->type==TEX_IMAGE)
1070                                         if (gpu_do_color_management(mat))
1071                                                 GPU_link(mat, "srgb_to_linearrgb", tcol, &tcol);
1072                                 
1073                                 if (mtex->mapto & MAP_COL) {
1074                                         GPUNodeLink *colfac;
1075
1076                                         if (mtex->colfac == 1.0f) colfac = stencil;
1077                                         else GPU_link(mat, "math_multiply", GPU_uniform(&mtex->colfac), stencil, &colfac);
1078
1079                                         texture_rgb_blend(mat, tcol, shi->rgb, tin, colfac, mtex->blendtype, &shi->rgb);
1080                                 }
1081                                 
1082                                 if (!(mat->scene->gm.flag & GAME_GLSL_NO_EXTRA_TEX) && (mtex->mapto & MAP_COLSPEC)) {
1083                                         GPUNodeLink *colspecfac;
1084
1085                                         if (mtex->colspecfac == 1.0f) colspecfac = stencil;
1086                                         else GPU_link(mat, "math_multiply", GPU_uniform(&mtex->colspecfac), stencil, &colspecfac);
1087
1088                                         texture_rgb_blend(mat, tcol, shi->specrgb, tin, colspecfac, mtex->blendtype, &shi->specrgb);
1089                                 }
1090                         }
1091
1092                         if (!(mat->scene->gm.flag & GAME_GLSL_NO_EXTRA_TEX) && (mtex->mapto & MAP_NORM)) {
1093                                 if (tex->type==TEX_IMAGE) {
1094                                         found_deriv_map = tex->imaflag & TEX_DERIVATIVEMAP;
1095
1096                                         if (tex->imaflag & TEX_NORMALMAP) {
1097                                                 /* normalmap image */
1098                                                 GPU_link(mat, "mtex_normal", texco, GPU_image(tex->ima, &tex->iuser), &tnor);
1099                                                 
1100                                                 if (mtex->norfac < 0.0f)
1101                                                         GPU_link(mat, "mtex_negate_texnormal", tnor, &tnor);
1102
1103                                                 if (mtex->normapspace == MTEX_NSPACE_TANGENT) {
1104                                                         if (iFirstTimeNMap != 0) {
1105                                                                 // use unnormalized normal (this is how we bake it - closer to gamedev)
1106                                                                 GPUNodeLink *vNegNorm;
1107                                                                 GPU_link(mat, "vec_math_negate", GPU_builtin(GPU_VIEW_NORMAL), &vNegNorm);
1108                                                                 GPU_link(mat, "mtex_nspace_tangent", GPU_attribute(CD_TANGENT, ""), vNegNorm, tnor, &newnor);
1109                                                                 iFirstTimeNMap = 0;
1110                                                         }
1111                                                         else { /* otherwise use accumulated perturbations */
1112                                                                 GPU_link(mat, "mtex_nspace_tangent", GPU_attribute(CD_TANGENT, ""), shi->vn, tnor, &newnor);
1113                                                         }
1114                                                 }
1115                                                 else {
1116                                                         newnor = tnor;
1117                                                 }
1118                                                 
1119                                                 norfac = minf(fabsf(mtex->norfac), 1.0f);
1120                                                 
1121                                                 if (norfac == 1.0f && !GPU_link_changed(stencil)) {
1122                                                         shi->vn = newnor;
1123                                                 }
1124                                                 else {
1125                                                         tnorfac = GPU_uniform(&norfac);
1126         
1127                                                         if (GPU_link_changed(stencil))
1128                                                                 GPU_link(mat, "math_multiply", tnorfac, stencil, &tnorfac);
1129         
1130                                                         GPU_link(mat, "mtex_blend_normal", tnorfac, shi->vn, newnor, &shi->vn);
1131                                                 }
1132                                                 
1133                                         }
1134                                         else if ( (mtex->texflag & (MTEX_3TAP_BUMP|MTEX_5TAP_BUMP|MTEX_BICUBIC_BUMP)) || found_deriv_map) {
1135                                                 /* ntap bumpmap image */
1136                                                 int iBumpSpace;
1137                                                 float ima_x, ima_y;
1138                                                 float hScale; 
1139
1140                                                 float imag_tspace_dimension_x = 1024.0f;                // only used for texture space variant
1141                                                 float aspect = 1.0f;
1142                                                 
1143                                                 GPUNodeLink *surf_pos = GPU_builtin(GPU_VIEW_POSITION);
1144                                                 GPUNodeLink *vR1, *vR2;
1145                                                 GPUNodeLink *dBs, *dBt, *fDet;
1146
1147                                                 hScale = 0.1;           // compatibility adjustment factor for all bumpspace types
1148                                                 if ( mtex->texflag & MTEX_BUMP_TEXTURESPACE )
1149                                                         hScale = 13.0f;         // factor for scaling texspace bumps
1150                                                 else if (found_deriv_map!=0)
1151                                                         hScale = 1.0f;
1152
1153                                                 // resolve texture resolution
1154                                                 if ( (mtex->texflag & MTEX_BUMP_TEXTURESPACE) || found_deriv_map ) {
1155                                                         ImBuf *ibuf= BKE_image_get_ibuf(tex->ima, &tex->iuser);
1156                                                         ima_x= 512.0f; ima_y= 512.f;            // prevent calling textureSize, glsl 1.3 only
1157                                                         if (ibuf) {
1158                                                                 ima_x= ibuf->x;
1159                                                                 ima_y= ibuf->y;
1160                                                                 aspect = ((float) ima_y) / ima_x;
1161                                                         }
1162                                                 }
1163
1164                                                 // The negate on norfac is done because the
1165                                                 // normal in the renderer points inward which corresponds
1166                                                 // to inverting the bump map. Should this ever change
1167                                                 // this negate must be removed.
1168                                                 norfac = -hScale * mtex->norfac;
1169                                                 if (found_deriv_map) {
1170                                                         float fVirtDim = sqrtf(fabsf(ima_x*mtex->size[0]*ima_y*mtex->size[1]));
1171                                                         norfac /= MAX2(fVirtDim, FLT_EPSILON);
1172                                                 }
1173
1174                                                 tnorfac = GPU_uniform(&norfac);
1175
1176                                                 if (found_deriv_map)
1177                                                         GPU_link(mat, "math_multiply", tnorfac, GPU_builtin(GPU_AUTO_BUMPSCALE), &tnorfac);
1178                                                 
1179                                                 if (GPU_link_changed(stencil))
1180                                                         GPU_link(mat, "math_multiply", tnorfac, stencil, &tnorfac);
1181                                                 
1182                                                 if ( !init_done ) {
1183                                                         // copy shi->vn to vNorg and vNacc, set magnitude to 1
1184                                                         GPU_link(mat, "mtex_bump_normals_init", shi->vn, &vNorg, &vNacc, &fPrevMagnitude);
1185                                                         iBumpSpacePrev = 0;
1186                                                         init_done = 1;
1187                                                 }
1188                                                 
1189                                                 // find current bump space
1190                                                 if ( mtex->texflag & MTEX_BUMP_OBJECTSPACE )
1191                                                         iBumpSpace = 1;
1192                                                 else if ( mtex->texflag & MTEX_BUMP_TEXTURESPACE )
1193                                                         iBumpSpace = 2;
1194                                                 else
1195                                                         iBumpSpace = 4; // ViewSpace
1196                                                 
1197                                                 // re-initialize if bump space changed
1198                                                 if ( iBumpSpacePrev != iBumpSpace ) {
1199                                                         
1200                                                         if ( mtex->texflag & MTEX_BUMP_OBJECTSPACE )
1201                                                                 GPU_link(mat, "mtex_bump_init_objspace",
1202                                                                          surf_pos, vNorg,
1203                                                                          GPU_builtin(GPU_VIEW_MATRIX), GPU_builtin(GPU_INVERSE_VIEW_MATRIX), GPU_builtin(GPU_OBJECT_MATRIX),  GPU_builtin(GPU_INVERSE_OBJECT_MATRIX),
1204                                                                          fPrevMagnitude, vNacc,
1205                                                                          &fPrevMagnitude, &vNacc,
1206                                                                          &vR1, &vR2, &fDet);
1207                                                                 
1208                                                         else if ( mtex->texflag & MTEX_BUMP_TEXTURESPACE )
1209                                                                 GPU_link(mat, "mtex_bump_init_texturespace",
1210                                                                          surf_pos, vNorg,
1211                                                                          fPrevMagnitude, vNacc,
1212                                                                          &fPrevMagnitude, &vNacc,
1213                                                                          &vR1, &vR2, &fDet);
1214                                                                 
1215                                                         else
1216                                                                 GPU_link(mat, "mtex_bump_init_viewspace",
1217                                                                          surf_pos, vNorg,
1218                                                                          fPrevMagnitude, vNacc,
1219                                                                          &fPrevMagnitude, &vNacc,
1220                                                                          &vR1, &vR2, &fDet);
1221                                                         
1222                                                         iBumpSpacePrev = iBumpSpace;
1223                                                 }
1224                                                 
1225                                                 
1226                                                 if (found_deriv_map) {
1227                                                         GPU_link(mat, "mtex_bump_deriv",
1228                                                                  texco, GPU_image(tex->ima, &tex->iuser), GPU_uniform(&ima_x), GPU_uniform(&ima_y), tnorfac,
1229                                                                  &dBs, &dBt );
1230                                                 }
1231                                                 else if ( mtex->texflag & MTEX_3TAP_BUMP)
1232                                                         GPU_link(mat, "mtex_bump_tap3",
1233                                                                  texco, GPU_image(tex->ima, &tex->iuser), tnorfac,
1234                                                                  &dBs, &dBt );
1235                                                 else if ( mtex->texflag & MTEX_5TAP_BUMP)
1236                                                         GPU_link(mat, "mtex_bump_tap5",
1237                                                                  texco, GPU_image(tex->ima, &tex->iuser), tnorfac,
1238                                                                  &dBs, &dBt );
1239                                                 else if ( mtex->texflag & MTEX_BICUBIC_BUMP ) {
1240                                                         if (GPU_bicubic_bump_support()) {
1241                                                                 GPU_link(mat, "mtex_bump_bicubic",
1242                                                                          texco, GPU_image(tex->ima, &tex->iuser), tnorfac,
1243                                                                          &dBs, &dBt);
1244                                                         }
1245                                                         else {
1246                                                                 GPU_link(mat, "mtex_bump_tap5",
1247                                                                          texco, GPU_image(tex->ima, &tex->iuser), tnorfac,
1248                                                                          &dBs, &dBt);
1249                                                         }
1250                                                 }
1251                                                 
1252                                                 
1253                                                 if ( mtex->texflag & MTEX_BUMP_TEXTURESPACE ) {
1254                                                         float imag_tspace_dimension_y = aspect*imag_tspace_dimension_x;
1255                                                         GPU_link(mat, "mtex_bump_apply_texspace",
1256                                                                  fDet, dBs, dBt, vR1, vR2,
1257                                                                  GPU_image(tex->ima, &tex->iuser), texco,
1258                                                                  GPU_uniform(&imag_tspace_dimension_x), GPU_uniform(&imag_tspace_dimension_y), vNacc,
1259                                                                  &vNacc, &shi->vn );
1260                                                 }
1261                                                 else
1262                                                         GPU_link(mat, "mtex_bump_apply",
1263                                                                  fDet, dBs, dBt, vR1, vR2, vNacc,
1264                                                                  &vNacc, &shi->vn );
1265                                                 
1266                                         }
1267                                 }
1268                                 
1269                                 GPU_link(mat, "vec_math_negate", shi->vn, &orn);
1270                         }
1271
1272                         if ((mtex->mapto & MAP_VARS)) {
1273                                 if (rgbnor & TEX_RGB) {
1274                                         if (talpha)
1275                                                 GPU_link(mat, "mtex_alpha_from_col", trgb, &tin);
1276                                         else
1277                                                 GPU_link(mat, "mtex_rgbtoint", trgb, &tin);
1278                                 }
1279
1280                                 if (!(mat->scene->gm.flag & GAME_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_REF) {
1281                                         GPUNodeLink *difffac;
1282
1283                                         if (mtex->difffac == 1.0f) difffac = stencil;
1284                                         else GPU_link(mat, "math_multiply", GPU_uniform(&mtex->difffac), stencil, &difffac);
1285
1286                                         texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->refl, tin, difffac, mtex->blendtype, &shi->refl);
1287                                         GPU_link(mat, "mtex_value_clamp_positive", shi->refl, &shi->refl);
1288                                 }
1289                                 if (!(mat->scene->gm.flag & GAME_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_SPEC) {
1290                                         GPUNodeLink *specfac;
1291
1292                                         if (mtex->specfac == 1.0f) specfac = stencil;
1293                                         else GPU_link(mat, "math_multiply", GPU_uniform(&mtex->specfac), stencil, &specfac);
1294
1295                                         texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->spec, tin, specfac, mtex->blendtype, &shi->spec);
1296                                         GPU_link(mat, "mtex_value_clamp_positive", shi->spec, &shi->spec);
1297                                 }
1298                                 if (!(mat->scene->gm.flag & GAME_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_EMIT) {
1299                                         GPUNodeLink *emitfac;
1300
1301                                         if (mtex->emitfac == 1.0f) emitfac = stencil;
1302                                         else GPU_link(mat, "math_multiply", GPU_uniform(&mtex->emitfac), stencil, &emitfac);
1303
1304                                         texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->emit, tin, emitfac, mtex->blendtype, &shi->emit);
1305                                         GPU_link(mat, "mtex_value_clamp_positive", shi->emit, &shi->emit);
1306                                 }
1307                                 if (!(mat->scene->gm.flag & GAME_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_HAR) {
1308                                         GPUNodeLink *hardfac;
1309
1310                                         if (mtex->hardfac == 1.0f) hardfac = stencil;
1311                                         else GPU_link(mat, "math_multiply", GPU_uniform(&mtex->hardfac), stencil, &hardfac);
1312
1313                                         GPU_link(mat, "mtex_har_divide", shi->har, &shi->har);
1314                                         texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->har, tin, hardfac, mtex->blendtype, &shi->har);
1315                                         GPU_link(mat, "mtex_har_multiply_clamp", shi->har, &shi->har);
1316                                 }
1317                                 if (mtex->mapto & MAP_ALPHA) {
1318                                         GPUNodeLink *alphafac;
1319
1320                                         if (mtex->alphafac == 1.0f) alphafac = stencil;
1321                                         else GPU_link(mat, "math_multiply", GPU_uniform(&mtex->alphafac), stencil, &alphafac);
1322
1323                                         texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->alpha, tin, alphafac, mtex->blendtype, &shi->alpha);
1324                                         GPU_link(mat, "mtex_value_clamp", shi->alpha, &shi->alpha);
1325                                 }
1326                                 if (!(mat->scene->gm.flag & GAME_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_AMB) {
1327                                         GPUNodeLink *ambfac;
1328
1329                                         if (mtex->ambfac == 1.0f) ambfac = stencil;
1330                                         else GPU_link(mat, "math_multiply", GPU_uniform(&mtex->ambfac), stencil, &ambfac);
1331
1332                                         texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->amb, tin, ambfac, mtex->blendtype, &shi->amb);
1333                                         GPU_link(mat, "mtex_value_clamp", shi->amb, &shi->amb);
1334                                 }
1335                         }
1336                 }
1337         }
1338 }
1339
1340 void GPU_shadeinput_set(GPUMaterial *mat, Material *ma, GPUShadeInput *shi)
1341 {
1342         float hard = ma->har;
1343
1344         memset(shi, 0, sizeof(*shi));
1345
1346         shi->gpumat = mat;
1347         shi->mat = ma;
1348
1349         GPU_link(mat, "set_rgb", GPU_uniform(&ma->r), &shi->rgb);
1350         GPU_link(mat, "set_rgb", GPU_uniform(&ma->specr), &shi->specrgb);
1351         GPU_link(mat, "shade_norm", GPU_builtin(GPU_VIEW_NORMAL), &shi->vn);
1352         GPU_link(mat, "set_value", GPU_uniform(&ma->alpha), &shi->alpha);
1353         GPU_link(mat, "set_value", GPU_uniform(&ma->ref), &shi->refl);
1354         GPU_link(mat, "set_value", GPU_uniform(&ma->spec), &shi->spec);
1355         GPU_link(mat, "set_value", GPU_uniform(&ma->emit), &shi->emit);
1356         GPU_link(mat, "set_value", GPU_uniform(&hard), &shi->har);
1357         GPU_link(mat, "set_value", GPU_uniform(&ma->amb), &shi->amb);
1358         GPU_link(mat, "shade_view", GPU_builtin(GPU_VIEW_POSITION), &shi->view);
1359         GPU_link(mat, "vcol_attribute", GPU_attribute(CD_MCOL, ""), &shi->vcol);
1360         if (gpu_do_color_management(mat))
1361                 GPU_link(mat, "srgb_to_linearrgb", shi->vcol, &shi->vcol);
1362         GPU_link(mat, "texco_refl", shi->vn, shi->view, &shi->ref);
1363 }
1364
1365 void GPU_shaderesult_set(GPUShadeInput *shi, GPUShadeResult *shr)
1366 {
1367         GPUMaterial *mat= shi->gpumat;
1368         GPUNodeLink *emit, *ulinfac, *ulogfac, *mistfac;
1369         Material *ma= shi->mat;
1370         World *world= mat->scene->world;
1371         float linfac, logfac, misttype;
1372
1373         memset(shr, 0, sizeof(*shr));
1374
1375         if (ma->mode & MA_VERTEXCOLP)
1376                 shi->rgb = shi->vcol;
1377
1378         do_material_tex(shi);
1379
1380         if ((ma->mode & MA_TRANSP) && (ma->mode & MA_ZTRANSP))
1381                 GPU_material_enable_alpha(mat);
1382
1383         if ((mat->scene->gm.flag & GAME_GLSL_NO_LIGHTS) || (ma->mode & MA_SHLESS)) {
1384                 shr->combined = shi->rgb;
1385                 shr->alpha = shi->alpha;
1386                 GPU_link(mat, "set_rgb", shi->rgb, &shr->diff);
1387                 GPU_link(mat, "set_rgb_zero", &shr->spec);
1388         }
1389         else {
1390                 if (GPU_link_changed(shi->emit) || ma->emit != 0.0f) {
1391                         if ((ma->mode & (MA_VERTEXCOL|MA_VERTEXCOLP))== MA_VERTEXCOL) {
1392                                 GPU_link(mat, "shade_add", shi->emit, shi->vcol, &emit);
1393                                 GPU_link(mat, "shade_mul", emit, shi->rgb, &shr->diff);
1394                         }
1395                         else
1396                                 GPU_link(mat, "shade_mul_value", shi->emit, shi->rgb, &shr->diff);
1397                 }
1398                 else
1399                         GPU_link(mat, "set_rgb_zero", &shr->diff);
1400
1401                 GPU_link(mat, "set_rgb_zero", &shr->spec);
1402
1403                 material_lights(shi, shr);
1404
1405                 shr->combined = shr->diff;
1406                 shr->alpha = shi->alpha;
1407
1408                 if (world) {
1409                         /* exposure correction */
1410                         if (world->exp!=0.0f || world->range!=1.0f) {
1411                                 linfac= 1.0f + powf((2.0f*world->exp + 0.5f), -10);
1412                                 logfac= logf((linfac-1.0f)/linfac)/world->range;
1413
1414                                 GPU_link(mat, "set_value", GPU_uniform(&linfac), &ulinfac);
1415                                 GPU_link(mat, "set_value", GPU_uniform(&logfac), &ulogfac);
1416
1417                                 GPU_link(mat, "shade_exposure_correct", shr->combined,
1418                                         ulinfac, ulogfac, &shr->combined);
1419                                 GPU_link(mat, "shade_exposure_correct", shr->spec,
1420                                         ulinfac, ulogfac, &shr->spec);
1421                         }
1422
1423                         /* ambient color */
1424                         if (world->ambr!=0.0f || world->ambg!=0.0f || world->ambb!=0.0f) {
1425                                 if (GPU_link_changed(shi->amb) || ma->amb != 0.0f)
1426                                         GPU_link(mat, "shade_maddf", shr->combined, GPU_uniform(&ma->amb),
1427                                                 GPU_uniform(&world->ambr), &shr->combined);
1428                         }
1429                 }
1430
1431                 if (ma->mode & MA_RAMP_COL) ramp_diffuse_result(shi, &shr->combined);
1432                 if (ma->mode & MA_RAMP_SPEC) ramp_spec_result(shi, &shr->spec);
1433
1434                 if (GPU_link_changed(shi->spec) || ma->spec != 0.0f)
1435                         GPU_link(mat, "shade_add", shr->combined, shr->spec, &shr->combined);
1436         }
1437
1438         GPU_link(mat, "mtex_alpha_to_col", shr->combined, shr->alpha, &shr->combined);
1439
1440         if (ma->shade_flag & MA_OBCOLOR)
1441                 GPU_link(mat, "shade_obcolor", shr->combined, GPU_builtin(GPU_OBCOLOR), &shr->combined);
1442
1443         if (world && (world->mode & WO_MIST) && !(ma->mode & MA_NOMIST)) {
1444                 misttype = world->mistype;
1445
1446                 GPU_link(mat, "shade_mist_factor", GPU_builtin(GPU_VIEW_POSITION),
1447                         GPU_uniform(&world->miststa), GPU_uniform(&world->mistdist),
1448                         GPU_uniform(&misttype), GPU_uniform(&world->misi), &mistfac);
1449
1450                 GPU_link(mat, "mix_blend", mistfac, shr->combined,
1451                         GPU_uniform(&world->horr), &shr->combined);
1452         }
1453
1454         if (!((ma->mode & MA_TRANSP) && (ma->mode & MA_ZTRANSP))) {
1455                 if (world && (GPU_link_changed(shr->alpha) || ma->alpha != 1.0f))
1456                         GPU_link(mat, "shade_world_mix", GPU_uniform(&world->horr),
1457                                 shr->combined, &shr->combined);
1458
1459                 GPU_link(mat, "shade_alpha_opaque", shr->combined, &shr->combined);
1460         }
1461
1462         if (ma->shade_flag & MA_OBCOLOR) {
1463                 mat->obcolalpha = 1;
1464                 GPU_link(mat, "shade_alpha_obcolor", shr->combined, GPU_builtin(GPU_OBCOLOR), &shr->combined);
1465         }
1466 }
1467
1468 static GPUNodeLink *GPU_blender_material(GPUMaterial *mat, Material *ma)
1469 {
1470         GPUShadeInput shi;
1471         GPUShadeResult shr;
1472
1473         GPU_shadeinput_set(mat, ma, &shi);
1474         GPU_shaderesult_set(&shi, &shr);
1475
1476         return shr.combined;
1477 }
1478
1479 GPUMaterial *GPU_material_from_blender(Scene *scene, Material *ma)
1480 {
1481         GPUMaterial *mat;
1482         GPUNodeLink *outlink;
1483         LinkData *link;
1484
1485         for (link=ma->gpumaterial.first; link; link=link->next)
1486                 if (((GPUMaterial*)link->data)->scene == scene)
1487                         return link->data;
1488
1489         /* allocate material */
1490         mat = GPU_material_construct_begin(ma);
1491         mat->scene = scene;
1492
1493         if (!(scene->gm.flag & GAME_GLSL_NO_NODES) && ma->nodetree && ma->use_nodes) {
1494                 /* create nodes */
1495                 ntreeGPUMaterialNodes(ma->nodetree, mat);
1496         }
1497         else {
1498                 /* create material */
1499                 outlink = GPU_blender_material(mat, ma);
1500                 GPU_material_output_link(mat, outlink);
1501         }
1502
1503         if (!scene_use_new_shading_nodes(scene)) {
1504                 if (gpu_do_color_management(mat))
1505                         if (mat->outlink)
1506                                 GPU_link(mat, "linearrgb_to_srgb", mat->outlink, &mat->outlink);
1507         }
1508
1509
1510         GPU_material_construct_end(mat);
1511
1512         /* note that even if building the shader fails in some way, we still keep
1513          * it to avoid trying to compile again and again, and simple do not use
1514          * the actual shader on drawing */
1515
1516         link = MEM_callocN(sizeof(LinkData), "GPUMaterialLink");
1517         link->data = mat;
1518         BLI_addtail(&ma->gpumaterial, link);
1519
1520         return mat;
1521 }
1522
1523 void GPU_materials_free(void)
1524 {
1525         Object *ob;
1526         Material *ma;
1527         extern Material defmaterial;
1528
1529         for (ma=G.main->mat.first; ma; ma=ma->id.next)
1530                 GPU_material_free(ma);
1531
1532         GPU_material_free(&defmaterial);
1533
1534         for (ob=G.main->object.first; ob; ob=ob->id.next)
1535                 GPU_lamp_free(ob);
1536 }
1537
1538 /* Lamps and shadow buffers */
1539
1540 void GPU_lamp_update(GPULamp *lamp, int lay, int hide, float obmat[][4])
1541 {
1542         float mat[4][4];
1543
1544         lamp->lay = lay;
1545         lamp->hide = hide;
1546
1547         copy_m4_m4(mat, obmat);
1548         normalize_m4(mat);
1549
1550         copy_v3_v3(lamp->vec, mat[2]);
1551         copy_v3_v3(lamp->co, mat[3]);
1552         copy_m4_m4(lamp->obmat, mat);
1553         invert_m4_m4(lamp->imat, mat);
1554 }
1555
1556 void GPU_lamp_update_colors(GPULamp *lamp, float r, float g, float b, float energy)
1557 {
1558         lamp->energy = energy;
1559         if (lamp->mode & LA_NEG) lamp->energy= -lamp->energy;
1560
1561         lamp->col[0]= r* lamp->energy;
1562         lamp->col[1]= g* lamp->energy;
1563         lamp->col[2]= b* lamp->energy;
1564 }
1565
1566 static void gpu_lamp_from_blender(Scene *scene, Object *ob, Object *par, Lamp *la, GPULamp *lamp)
1567 {
1568         float temp, angle, pixsize, wsize;
1569
1570         lamp->scene = scene;
1571         lamp->ob = ob;
1572         lamp->par = par;
1573         lamp->la = la;
1574
1575         /* add_render_lamp */
1576         lamp->mode = la->mode;
1577         lamp->type = la->type;
1578
1579         lamp->energy = la->energy;
1580         if (lamp->mode & LA_NEG) lamp->energy= -lamp->energy;
1581
1582         lamp->col[0]= la->r*lamp->energy;
1583         lamp->col[1]= la->g*lamp->energy;
1584         lamp->col[2]= la->b*lamp->energy;
1585
1586         GPU_lamp_update(lamp, ob->lay, (ob->restrictflag & OB_RESTRICT_RENDER), ob->obmat);
1587
1588         lamp->spotsi= la->spotsize;
1589         if (lamp->mode & LA_HALO)
1590                 if (lamp->spotsi > 170.0f)
1591                         lamp->spotsi = 170.0f;
1592         lamp->spotsi= cosf((float)M_PI*lamp->spotsi/360.0f);
1593         lamp->spotbl= (1.0f - lamp->spotsi)*la->spotblend;
1594         lamp->k= la->k;
1595
1596         lamp->dist= la->dist;
1597         lamp->falloff_type= la->falloff_type;
1598         lamp->att1= la->att1;
1599         lamp->att2= la->att2;
1600         lamp->curfalloff= la->curfalloff;
1601
1602         /* initshadowbuf */
1603         lamp->bias = 0.02f*la->bias;
1604         lamp->size = la->bufsize;
1605         lamp->d= la->clipsta;
1606         lamp->clipend= la->clipend;
1607
1608         /* arbitrary correction for the fact we do no soft transition */
1609         lamp->bias *= 0.25f;
1610
1611         /* makeshadowbuf */
1612         if (lamp->type == LA_SUN) {
1613                 wsize = la->shadow_frustum_size;
1614                 orthographic_m4( lamp->winmat,-wsize, wsize, -wsize, wsize, lamp->d, lamp->clipend);
1615         }
1616         else {
1617                 angle= saacos(lamp->spotsi);
1618                 temp= 0.5f*lamp->size*cosf(angle)/sinf(angle);
1619                 pixsize= (lamp->d)/temp;
1620                 wsize= pixsize*0.5f*lamp->size;
1621                 perspective_m4(lamp->winmat, -wsize, wsize, -wsize, wsize, lamp->d, lamp->clipend);
1622         }
1623 }
1624
1625 static void gpu_lamp_shadow_free(GPULamp *lamp)
1626 {
1627         if (lamp->tex) {
1628                 GPU_texture_free(lamp->tex);
1629                 lamp->tex= NULL;
1630         }
1631         if (lamp->depthtex) {
1632                 GPU_texture_free(lamp->depthtex);
1633                 lamp->depthtex= NULL;
1634         }
1635         if (lamp->fb) {
1636                 GPU_framebuffer_free(lamp->fb);
1637                 lamp->fb= NULL;
1638         }
1639         if(lamp->blurtex) {
1640                 GPU_texture_free(lamp->blurtex);
1641                 lamp->blurtex= NULL;
1642         }
1643         if(lamp->blurfb) {
1644                 GPU_framebuffer_free(lamp->blurfb);
1645                 lamp->blurfb= NULL;
1646         }
1647 }
1648
1649 GPULamp *GPU_lamp_from_blender(Scene *scene, Object *ob, Object *par)
1650 {
1651         Lamp *la;
1652         GPULamp *lamp;
1653         LinkData *link;
1654
1655         for (link=ob->gpulamp.first; link; link=link->next) {
1656                 lamp = (GPULamp*)link->data;
1657
1658                 if (lamp->par == par && lamp->scene == scene)
1659                         return link->data;
1660         }
1661
1662         lamp = MEM_callocN(sizeof(GPULamp), "GPULamp");
1663
1664         link = MEM_callocN(sizeof(LinkData), "GPULampLink");
1665         link->data = lamp;
1666         BLI_addtail(&ob->gpulamp, link);
1667
1668         la = ob->data;
1669         gpu_lamp_from_blender(scene, ob, par, la, lamp);
1670
1671         if ((la->type==LA_SPOT || la->type==LA_SUN) && (la->mode & LA_SHAD_BUF)) {
1672                 /* opengl */
1673                 lamp->fb = GPU_framebuffer_create();
1674                 if (!lamp->fb) {
1675                         gpu_lamp_shadow_free(lamp);
1676                         return lamp;
1677                 }
1678
1679                 if (lamp->la->shadowmap_type == LA_SHADMAP_VARIANCE) {
1680                         /* Shadow depth map */
1681                         lamp->depthtex = GPU_texture_create_depth(lamp->size, lamp->size, NULL);
1682                         if (!lamp->depthtex) {
1683                                 gpu_lamp_shadow_free(lamp);
1684                                 return lamp;
1685                         }
1686                 
1687                         if (!GPU_framebuffer_texture_attach(lamp->fb, lamp->depthtex, NULL)) {
1688                                 gpu_lamp_shadow_free(lamp);
1689                                 return lamp;
1690                         }
1691
1692                         /* Shadow color map */
1693                         lamp->tex = GPU_texture_create_vsm_shadow_map(lamp->size, NULL);
1694                         if (!lamp->tex) {
1695                                 gpu_lamp_shadow_free(lamp);
1696                                 return lamp;
1697                         }
1698
1699                         if (!GPU_framebuffer_texture_attach(lamp->fb, lamp->tex, NULL)) {
1700                                 gpu_lamp_shadow_free(lamp);
1701                                 return lamp;
1702                         }
1703
1704                         /* FBO and texture for blurring */
1705                         lamp->blurfb = GPU_framebuffer_create();
1706                         if (!lamp->blurfb) {
1707                                 gpu_lamp_shadow_free(lamp);
1708                                 return lamp;
1709                         }
1710
1711                         lamp->blurtex = GPU_texture_create_vsm_shadow_map(lamp->size*0.5, NULL);
1712                         if (!lamp->blurtex) {
1713                                 gpu_lamp_shadow_free(lamp);
1714                                 return lamp;
1715                         }
1716                 
1717                         if (!GPU_framebuffer_texture_attach(lamp->blurfb, lamp->blurtex, NULL)) {
1718                                 gpu_lamp_shadow_free(lamp);
1719                                 return lamp;
1720                         }
1721                 }
1722                 else {
1723                         lamp->tex = GPU_texture_create_depth(lamp->size, lamp->size, NULL);
1724                         if(!lamp->tex) {
1725                                 gpu_lamp_shadow_free(lamp);
1726                                 return lamp;
1727                         }
1728
1729                         if (!GPU_framebuffer_texture_attach(lamp->fb, lamp->tex, NULL)) {
1730                                 gpu_lamp_shadow_free(lamp);
1731                                 return lamp;
1732                         }
1733                 }
1734
1735                 GPU_framebuffer_restore();
1736
1737                 lamp->shadow_color[0] = la->shdwr;
1738                 lamp->shadow_color[1] = la->shdwg;
1739                 lamp->shadow_color[2] = la->shdwb;
1740         }
1741         else {
1742                 lamp->shadow_color[0] = 1.0;
1743                 lamp->shadow_color[1] = 1.0;
1744                 lamp->shadow_color[2] = 1.0;
1745         }
1746
1747         return lamp;
1748 }
1749
1750 void GPU_lamp_free(Object *ob)
1751 {
1752         GPULamp *lamp;
1753         LinkData *link;
1754         LinkData *nlink;
1755         Material *ma;
1756
1757         for (link=ob->gpulamp.first; link; link=link->next) {
1758                 lamp = link->data;
1759
1760                 while (lamp->materials.first) {
1761                         nlink = lamp->materials.first;
1762                         ma = nlink->data;
1763                         BLI_freelinkN(&lamp->materials, nlink);
1764
1765                         if (ma->gpumaterial.first)
1766                                 GPU_material_free(ma);
1767                 }
1768
1769                 gpu_lamp_shadow_free(lamp);
1770
1771                 MEM_freeN(lamp);
1772         }
1773
1774         BLI_freelistN(&ob->gpulamp);
1775 }
1776
1777 int GPU_lamp_has_shadow_buffer(GPULamp *lamp)
1778 {
1779         return (!(lamp->scene->gm.flag & GAME_GLSL_NO_SHADOWS) &&
1780                         !(lamp->scene->gm.flag & GAME_GLSL_NO_LIGHTS) &&
1781                         lamp->tex && lamp->fb);
1782 }
1783
1784 void GPU_lamp_update_buffer_mats(GPULamp *lamp)
1785 {
1786         float rangemat[4][4], persmat[4][4];
1787
1788         /* initshadowbuf */
1789         invert_m4_m4(lamp->viewmat, lamp->obmat);
1790         normalize_v3(lamp->viewmat[0]);
1791         normalize_v3(lamp->viewmat[1]);
1792         normalize_v3(lamp->viewmat[2]);
1793
1794         /* makeshadowbuf */
1795         mult_m4_m4m4(persmat, lamp->winmat, lamp->viewmat);
1796
1797         /* opengl depth buffer is range 0.0..1.0 instead of -1.0..1.0 in blender */
1798         unit_m4(rangemat);
1799         rangemat[0][0] = 0.5f;
1800         rangemat[1][1] = 0.5f;
1801         rangemat[2][2] = 0.5f;
1802         rangemat[3][0] = 0.5f;
1803         rangemat[3][1] = 0.5f;
1804         rangemat[3][2] = 0.5f;
1805
1806         mult_m4_m4m4(lamp->persmat, rangemat, persmat);
1807 }
1808
1809 void GPU_lamp_shadow_buffer_bind(GPULamp *lamp, float viewmat[][4], int *winsize, float winmat[][4])
1810 {
1811         GPU_lamp_update_buffer_mats(lamp);
1812
1813         /* opengl */
1814         glDisable(GL_SCISSOR_TEST);
1815         GPU_framebuffer_texture_bind(lamp->fb, lamp->tex,
1816                 GPU_texture_opengl_width(lamp->tex), GPU_texture_opengl_height(lamp->tex));
1817         if(lamp->la->shadowmap_type == LA_SHADMAP_VARIANCE)
1818                 GPU_shader_bind(GPU_shader_get_builtin_shader(GPU_SHADER_VSM_STORE));
1819
1820         /* set matrices */
1821         copy_m4_m4(viewmat, lamp->viewmat);
1822         copy_m4_m4(winmat, lamp->winmat);
1823         *winsize = lamp->size;
1824 }
1825
1826 void GPU_lamp_shadow_buffer_unbind(GPULamp *lamp)
1827 {
1828         if(lamp->la->shadowmap_type == LA_SHADMAP_VARIANCE) {
1829                 GPU_shader_unbind(GPU_shader_get_builtin_shader(GPU_SHADER_VSM_STORE));
1830                 GPU_framebuffer_blur(lamp->fb, lamp->tex, lamp->blurfb, lamp->blurtex);
1831         }
1832
1833         GPU_framebuffer_texture_unbind(lamp->fb, lamp->tex);
1834         GPU_framebuffer_restore();
1835         glEnable(GL_SCISSOR_TEST);
1836 }
1837
1838 int GPU_lamp_shadow_layer(GPULamp *lamp)
1839 {
1840         if (lamp->fb && lamp->tex && (lamp->mode & (LA_LAYER|LA_LAYER_SHADOW)))
1841                 return lamp->lay;
1842         else
1843                 return -1;
1844 }
1845
1846 /* export the GLSL shader */
1847
1848 GPUShaderExport *GPU_shader_export(struct Scene *scene, struct Material *ma)
1849 {
1850         static struct {
1851                 GPUBuiltin gputype;
1852                 GPUDynamicType dynamictype;
1853                 GPUDataType datatype;
1854         } builtins[] = { 
1855                 { GPU_VIEW_MATRIX, GPU_DYNAMIC_OBJECT_VIEWMAT, GPU_DATA_16F },
1856                 { GPU_INVERSE_VIEW_MATRIX, GPU_DYNAMIC_OBJECT_VIEWIMAT, GPU_DATA_16F },
1857                 { GPU_OBJECT_MATRIX, GPU_DYNAMIC_OBJECT_MAT, GPU_DATA_16F },
1858                 { GPU_INVERSE_OBJECT_MATRIX, GPU_DYNAMIC_OBJECT_IMAT, GPU_DATA_16F },
1859                 { GPU_OBCOLOR, GPU_DYNAMIC_OBJECT_COLOR, GPU_DATA_4F },
1860                 { GPU_AUTO_BUMPSCALE, GPU_DYNAMIC_OBJECT_AUTOBUMPSCALE, GPU_DATA_1F },
1861                 { 0 }
1862         };
1863
1864         GPUShaderExport *shader = NULL;
1865         GPUPass *pass;
1866         GPUInput *input;
1867         GPUMaterial *mat;
1868         GPUInputUniform *uniform;
1869         GPUInputAttribute *attribute;
1870         GLint lastbindcode;
1871         int i, liblen, fraglen;
1872
1873         if (!GPU_glsl_support())
1874                 return NULL;
1875
1876         mat = GPU_material_from_blender(scene, ma);
1877         pass = (mat)? mat->pass: NULL;
1878
1879         if (pass && pass->fragmentcode && pass->vertexcode) {
1880                 shader = MEM_callocN(sizeof(GPUShaderExport), "GPUShaderExport");
1881
1882                 for (input = pass->inputs.first; input; input = input->next) {
1883                         uniform = MEM_callocN(sizeof(GPUInputUniform), "GPUInputUniform");
1884
1885                         if (input->ima) {
1886                                 /* image sampler uniform */
1887                                 uniform->type = GPU_DYNAMIC_SAMPLER_2DIMAGE;
1888                                 uniform->datatype = GPU_DATA_1I;
1889                                 uniform->image = input->ima;
1890                                 uniform->texnumber = input->texid;
1891                                 BLI_strncpy(uniform->varname, input->shadername, sizeof(uniform->varname));
1892                         }
1893                         else if (input->tex) {
1894                                 /* generated buffer */
1895                                 uniform->texnumber = input->texid;
1896                                 uniform->datatype = GPU_DATA_1I;
1897                                 BLI_strncpy(uniform->varname, input->shadername, sizeof(uniform->varname));
1898
1899                                 switch (input->textype) {
1900                                 case GPU_SHADOW2D:
1901                                         uniform->type = GPU_DYNAMIC_SAMPLER_2DSHADOW;
1902                                         uniform->lamp = input->dynamicdata;
1903                                         break;
1904                                 case GPU_TEX2D:
1905                                         if (GPU_texture_opengl_bindcode(input->tex)) {
1906                                                 uniform->type = GPU_DYNAMIC_SAMPLER_2DBUFFER;
1907                                                 glGetIntegerv(GL_TEXTURE_BINDING_2D, &lastbindcode);
1908                                                 glBindTexture(GL_TEXTURE_2D, GPU_texture_opengl_bindcode(input->tex));
1909                                                 uniform->texsize = GPU_texture_opengl_width(input->tex) * GPU_texture_opengl_height(input->tex);
1910                                                 uniform->texpixels = MEM_mallocN(uniform->texsize*4, "RGBApixels");
1911                                                 glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, uniform->texpixels); 
1912                                                 glBindTexture(GL_TEXTURE_2D, lastbindcode);
1913                                         }
1914                                         break;
1915                                 }
1916                         }
1917                         else {
1918                                 uniform->type = input->dynamictype;
1919                                 BLI_strncpy(uniform->varname, input->shadername, sizeof(uniform->varname));
1920                                 switch (input->type) {
1921                                 case 1:
1922                                         uniform->datatype = GPU_DATA_1F;
1923                                         break;
1924                                 case 2:
1925                                         uniform->datatype = GPU_DATA_2F;
1926                                         break;
1927                                 case 3:
1928                                         uniform->datatype = GPU_DATA_3F;
1929                                         break;
1930                                 case 4:
1931                                         uniform->datatype = GPU_DATA_4F;
1932                                         break;
1933                                 case 9:
1934                                         uniform->datatype = GPU_DATA_9F;
1935                                         break;
1936                                 case 16:
1937                                         uniform->datatype = GPU_DATA_16F;
1938                                         break;
1939                                 }
1940
1941                                 if (uniform->type >= GPU_DYNAMIC_LAMP_FIRST && uniform->type <= GPU_DYNAMIC_LAMP_LAST)
1942                                         uniform->lamp = input->dynamicdata;
1943                         }
1944
1945                         if (uniform->type != GPU_DYNAMIC_NONE)
1946                                 BLI_addtail(&shader->uniforms, uniform);
1947                         else
1948                                 MEM_freeN(uniform);
1949                 }
1950
1951                 /* process builtin uniform */
1952                 for (i=0; builtins[i].gputype; i++) {
1953                         if (mat->builtins & builtins[i].gputype) {
1954                                 uniform = MEM_callocN(sizeof(GPUInputUniform), "GPUInputUniform");
1955                                 uniform->type = builtins[i].dynamictype;
1956                                 uniform->datatype = builtins[i].datatype;
1957                                 BLI_strncpy(uniform->varname, GPU_builtin_name(builtins[i].gputype), sizeof(uniform->varname));
1958                                 BLI_addtail(&shader->uniforms, uniform);
1959                         }
1960                 }
1961
1962                 /* now link fragment shader with library shader */
1963                 /* TBD: remove the function that are not used in the main function */
1964                 liblen = (pass->libcode) ? strlen(pass->libcode) : 0;
1965                 fraglen = strlen(pass->fragmentcode);
1966                 shader->fragment = (char *)MEM_mallocN(liblen+fraglen+1, "GPUFragShader");
1967                 if (pass->libcode)
1968                         memcpy(shader->fragment, pass->libcode, liblen);
1969                 memcpy(&shader->fragment[liblen], pass->fragmentcode, fraglen);
1970                 shader->fragment[liblen+fraglen] = 0;
1971
1972                 // export the attribute
1973                 for (i=0; i<mat->attribs.totlayer; i++) {
1974                         attribute = MEM_callocN(sizeof(GPUInputAttribute), "GPUInputAttribute");
1975                         attribute->type = mat->attribs.layer[i].type;
1976                         attribute->number = mat->attribs.layer[i].glindex;
1977                         BLI_snprintf(attribute->varname, sizeof(attribute->varname), "att%d", mat->attribs.layer[i].attribid);
1978
1979                         switch (attribute->type) {
1980                         case CD_TANGENT:
1981                                 attribute->datatype = GPU_DATA_4F;
1982                                 break;
1983                         case CD_MTFACE:
1984                                 attribute->datatype = GPU_DATA_2F;
1985                                 attribute->name = mat->attribs.layer[i].name;
1986                                 break;
1987                         case CD_MCOL:
1988                                 attribute->datatype = GPU_DATA_4UB;
1989                                 attribute->name = mat->attribs.layer[i].name;
1990                                 break;
1991                         case CD_ORCO:
1992                                 attribute->datatype = GPU_DATA_3F;
1993                                 break;
1994                         }
1995
1996                         if (attribute->datatype != GPU_DATA_NONE)
1997                                 BLI_addtail(&shader->attributes, attribute);
1998                         else
1999                                 MEM_freeN(attribute);
2000                 }
2001
2002                 // export the vertex shader
2003                 shader->vertex = BLI_strdup(pass->vertexcode);
2004         }
2005
2006         return shader;
2007 }
2008
2009 void GPU_free_shader_export(GPUShaderExport *shader)
2010 {
2011         GPUInputUniform *uniform;
2012
2013         if (shader == NULL)
2014                 return;
2015
2016         for (uniform = shader->uniforms.first; uniform; uniform=uniform->next)
2017                 if (uniform->texpixels)
2018                         MEM_freeN(uniform->texpixels);
2019
2020         BLI_freelistN(&shader->uniforms);
2021         BLI_freelistN(&shader->attributes);
2022
2023         if (shader->vertex)
2024                 MEM_freeN(shader->vertex);
2025         if (shader->fragment)
2026                 MEM_freeN(shader->fragment);
2027
2028         MEM_freeN(shader);
2029 }
2030