Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / space_view3d / drawmesh.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation, full update, glsl support
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/space_view3d/drawmesh.c
27  *  \ingroup spview3d
28  */
29
30 #include <string.h>
31 #include <math.h>
32
33 #include "MEM_guardedalloc.h"
34
35 #include "BLI_utildefines.h"
36 #include "BLI_bitmap.h"
37 #include "BLI_math.h"
38
39 #include "DNA_material_types.h"
40 #include "DNA_mesh_types.h"
41 #include "DNA_meshdata_types.h"
42 #include "DNA_node_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_property_types.h"
45 #include "DNA_scene_types.h"
46 #include "DNA_screen_types.h"
47 #include "DNA_view3d_types.h"
48
49 #include "BKE_DerivedMesh.h"
50 #include "BKE_global.h"
51 #include "BKE_image.h"
52 #include "BKE_material.h"
53 #include "BKE_paint.h"
54 #include "BKE_property.h"
55 #include "BKE_editmesh.h"
56 #include "BKE_scene.h"
57
58 #include "BIF_gl.h"
59 #include "BIF_glutil.h"
60
61 #include "UI_resources.h"
62
63 #include "GPU_draw.h"
64 #include "GPU_material.h"
65 #include "GPU_basic_shader.h"
66 #include "GPU_shader.h"
67
68 #include "RE_engine.h"
69
70 #include "ED_uvedit.h"
71
72 #include "view3d_intern.h"  /* own include */
73
74 /* user data structures for derived mesh callbacks */
75 typedef struct drawMeshFaceSelect_userData {
76         Mesh *me;
77         BLI_bitmap *edge_flags; /* pairs of edge options (visible, select) */
78 } drawMeshFaceSelect_userData;
79
80 typedef struct drawEMTFMapped_userData {
81         BMEditMesh *em;
82         bool has_mcol;
83         int cd_poly_tex_offset;
84         const MPoly *mpoly;
85         const MTexPoly *mtexpoly;
86 } drawEMTFMapped_userData;
87
88 typedef struct drawTFace_userData {
89         const Mesh *me;
90         const MPoly *mpoly;
91         const MTexPoly *mtexpoly;
92 } drawTFace_userData;
93
94 /**************************** Face Select Mode *******************************/
95
96 /* mainly to be less confusing */
97 BLI_INLINE int edge_vis_index(const int index) { return index * 2; }
98 BLI_INLINE int edge_sel_index(const int index) { return index * 2 + 1; }
99
100 static BLI_bitmap *get_tface_mesh_marked_edge_info(Mesh *me, bool draw_select_edges)
101 {
102         BLI_bitmap *bitmap_edge_flags = BLI_BITMAP_NEW(me->totedge * 2, __func__);
103         MPoly *mp;
104         MLoop *ml;
105         int i, j;
106         bool select_set;
107         
108         for (i = 0; i < me->totpoly; i++) {
109                 mp = &me->mpoly[i];
110
111                 if (!(mp->flag & ME_HIDE)) {
112                         select_set = (mp->flag & ME_FACE_SEL) != 0;
113
114                         ml = me->mloop + mp->loopstart;
115                         for (j = 0; j < mp->totloop; j++, ml++) {
116                                 if ((draw_select_edges == false) &&
117                                     (select_set && BLI_BITMAP_TEST(bitmap_edge_flags, edge_sel_index(ml->e))))
118                                 {
119                                         BLI_BITMAP_DISABLE(bitmap_edge_flags, edge_vis_index(ml->e));
120                                 }
121                                 else {
122                                         BLI_BITMAP_ENABLE(bitmap_edge_flags, edge_vis_index(ml->e));
123                                         if (select_set) {
124                                                 BLI_BITMAP_ENABLE(bitmap_edge_flags, edge_sel_index(ml->e));
125                                         }
126                                 }
127                         }
128                 }
129         }
130
131         return bitmap_edge_flags;
132 }
133
134
135 static DMDrawOption draw_mesh_face_select__setHiddenOpts(void *userData, int index)
136 {
137         drawMeshFaceSelect_userData *data = userData;
138         Mesh *me = data->me;
139
140         if (me->drawflag & ME_DRAWEDGES) {
141                 if ((BLI_BITMAP_TEST(data->edge_flags, edge_vis_index(index))))
142                         return DM_DRAW_OPTION_NORMAL;
143                 else
144                         return DM_DRAW_OPTION_SKIP;
145         }
146         else if (BLI_BITMAP_TEST(data->edge_flags, edge_sel_index(index)) &&
147                  BLI_BITMAP_TEST(data->edge_flags, edge_vis_index(index)))
148         {
149                 return DM_DRAW_OPTION_NORMAL;
150         }
151         else {
152                 return DM_DRAW_OPTION_SKIP;
153         }
154 }
155
156 static DMDrawOption draw_mesh_face_select__setSelectOpts(void *userData, int index)
157 {
158         drawMeshFaceSelect_userData *data = userData;
159         return (BLI_BITMAP_TEST(data->edge_flags, edge_sel_index(index)) &&
160                 BLI_BITMAP_TEST(data->edge_flags, edge_vis_index(index))) ? DM_DRAW_OPTION_NORMAL : DM_DRAW_OPTION_SKIP;
161 }
162
163 /* draws unselected */
164 static DMDrawOption draw_mesh_face_select__drawFaceOptsInv(void *userData, int index)
165 {
166         Mesh *me = (Mesh *)userData;
167
168         MPoly *mpoly = &me->mpoly[index];
169         if (!(mpoly->flag & ME_HIDE) && !(mpoly->flag & ME_FACE_SEL))
170                 return DM_DRAW_OPTION_NORMAL;
171         else
172                 return DM_DRAW_OPTION_SKIP;
173 }
174
175 void draw_mesh_face_select(RegionView3D *rv3d, Mesh *me, DerivedMesh *dm, bool draw_select_edges)
176 {
177         drawMeshFaceSelect_userData data;
178
179         data.me = me;
180         data.edge_flags = get_tface_mesh_marked_edge_info(me, draw_select_edges);
181
182         glEnable(GL_DEPTH_TEST);
183         ED_view3d_polygon_offset(rv3d, 1.0);
184
185         /* Draw (Hidden) Edges */
186         setlinestyle(1);
187         UI_ThemeColor(TH_EDGE_FACESEL);
188         dm->drawMappedEdges(dm, draw_mesh_face_select__setHiddenOpts, &data);
189         setlinestyle(0);
190
191         /* Draw Selected Faces */
192         if (me->drawflag & ME_DRAWFACES) {
193                 glEnable(GL_BLEND);
194                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
195                 /* dull unselected faces so as not to get in the way of seeing color */
196                 glColor4ub(96, 96, 96, 64);
197                 dm->drawMappedFaces(dm, draw_mesh_face_select__drawFaceOptsInv, NULL, NULL, (void *)me, DM_DRAW_SKIP_HIDDEN);
198                 glDisable(GL_BLEND);
199         }
200         
201         ED_view3d_polygon_offset(rv3d, 1.0);
202
203         /* Draw Stippled Outline for selected faces */
204         glColor3ub(255, 255, 255);
205         setlinestyle(1);
206         dm->drawMappedEdges(dm, draw_mesh_face_select__setSelectOpts, &data);
207         setlinestyle(0);
208
209         ED_view3d_polygon_offset(rv3d, 0.0);  /* resets correctly now, even after calling accumulated offsets */
210
211         MEM_freeN(data.edge_flags);
212 }
213
214 /***************************** Texture Drawing ******************************/
215
216 static Material *give_current_material_or_def(Object *ob, int matnr)
217 {
218         extern Material defmaterial;  /* render module abuse... */
219         Material *ma = give_current_material(ob, matnr);
220
221         return ma ? ma : &defmaterial;
222 }
223
224 /* Icky globals, fix with userdata parameter */
225
226 static struct TextureDrawState {
227         Object *ob;
228         Image *stencil; /* texture painting stencil */
229         Image *canvas;  /* texture painting canvas, for image mode */
230         bool use_game_mat;
231         int is_lit, is_tex;
232         int color_profile;
233         bool use_backface_culling;
234         bool two_sided_lighting;
235         unsigned char obcol[4];
236         bool is_texpaint;
237         bool texpaint_material; /* use material slots for texture painting */
238 } Gtexdraw = {NULL, NULL, NULL, false, 0, 0, 0, false, false, {0, 0, 0, 0}, false, false};
239
240 static bool set_draw_settings_cached(int clearcache, MTexPoly *texface, Material *ma, struct TextureDrawState gtexdraw)
241 {
242         static Material *c_ma;
243         static int c_textured;
244         static MTexPoly c_texface;
245         static int c_backculled;
246         static bool c_badtex;
247         static int c_lit;
248         static int c_has_texface;
249
250         int backculled = 1;
251         int alphablend = GPU_BLEND_SOLID;
252         int textured = 0;
253         int lit = 0;
254         int has_texface = texface != NULL;
255         bool need_set_tpage = false;
256         bool texpaint = ((gtexdraw.ob->mode & OB_MODE_TEXTURE_PAINT) != 0);
257
258         Image *ima = NULL;
259
260         if (ma != NULL) {
261                 if (ma->mode & MA_TRANSP) {
262                         alphablend = GPU_BLEND_ALPHA;
263                 }
264         }
265
266         if (clearcache) {
267                 c_textured = c_lit = c_backculled = -1;
268                 memset(&c_texface, 0, sizeof(c_texface));
269                 c_badtex = false;
270                 c_has_texface = -1;
271                 c_ma = NULL;
272         }
273         else {
274                 textured = gtexdraw.is_tex;
275         }
276
277         /* convert number of lights into boolean */
278         if (gtexdraw.is_lit) lit = 1;
279
280         backculled = gtexdraw.use_backface_culling;
281         if (ma) {
282                 if (ma->mode & MA_SHLESS) lit = 0;
283                 if (gtexdraw.use_game_mat) {
284                         backculled = backculled || (ma->game.flag & GEMAT_BACKCULL);
285                         alphablend = ma->game.alpha_blend;
286                 }
287         }
288
289         if (texface && !texpaint) {
290                 textured = textured && (texface->tpage);
291
292                 /* no material, render alpha if texture has depth=32 */
293                 if (!ma && BKE_image_has_alpha(texface->tpage))
294                         alphablend = GPU_BLEND_ALPHA;
295         }
296         else if (texpaint) {
297                 if (gtexdraw.texpaint_material)
298                         ima = ma && ma->texpaintslot ? ma->texpaintslot[ma->paint_active_slot].ima : NULL;
299                 else
300                         ima = gtexdraw.canvas;
301         }
302         else
303                 textured = 0;
304
305         if (backculled != c_backculled) {
306                 if (backculled) glEnable(GL_CULL_FACE);
307                 else glDisable(GL_CULL_FACE);
308
309                 c_backculled = backculled;
310         }
311
312         /* need to re-set tpage if textured flag changed or existsment of texface changed..  */
313         need_set_tpage = textured != c_textured || has_texface != c_has_texface;
314         /* ..or if settings inside texface were changed (if texface was used) */
315         need_set_tpage |= (texpaint && c_ma != ma) || (texface && memcmp(&c_texface, texface, sizeof(c_texface)));
316
317         if (need_set_tpage) {
318                 if (textured) {
319                         if (texpaint) {
320                                 c_badtex = false;
321                                 if (GPU_verify_image(ima, NULL, GL_TEXTURE_2D, 0, 1, 0, false)) {
322                                         glEnable(GL_TEXTURE_2D);
323                                         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
324                                         glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE);
325                                         glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_TEXTURE);
326                                         glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_PRIMARY_COLOR);
327                                         glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
328                                         glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_TEXTURE);
329                                         
330                                         glActiveTexture(GL_TEXTURE1);
331                                         glEnable(GL_TEXTURE_2D);
332                                         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
333                                         glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE);
334                                         glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_PREVIOUS);
335                                         glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_PRIMARY_COLOR);
336                                         glTexEnvi(GL_TEXTURE_ENV, GL_SRC2_RGB, GL_PREVIOUS);
337                                         glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_ALPHA);
338                                         glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
339                                         glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PREVIOUS);
340                                         glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]);
341                                         glActiveTexture(GL_TEXTURE0);                                   
342                                 }
343                                 else {
344                                         glActiveTexture(GL_TEXTURE1);
345                                         glDisable(GL_TEXTURE_2D);
346                                         glBindTexture(GL_TEXTURE_2D, 0);
347                                         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
348                                         glActiveTexture(GL_TEXTURE0);                                                                   
349
350                                         c_badtex = true;
351                                         GPU_clear_tpage(true);
352                                         glDisable(GL_TEXTURE_2D);
353                                         glBindTexture(GL_TEXTURE_2D, 0);
354                                         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
355                                 }
356                         }
357                         else {
358                                 c_badtex = !GPU_set_tpage(texface, !texpaint, alphablend);
359                         }
360                 }
361                 else {
362                         GPU_set_tpage(NULL, 0, 0);
363                         c_badtex = false;
364                 }
365                 c_textured = textured;
366                 c_has_texface = has_texface;
367                 if (texface)
368                         memcpy(&c_texface, texface, sizeof(c_texface));
369         }
370
371         if (c_badtex) lit = 0;
372         if (lit != c_lit || ma != c_ma) {
373                 if (lit) {
374                         int options = GPU_SHADER_LIGHTING | GPU_SHADER_USE_COLOR;
375
376                         if (gtexdraw.two_sided_lighting)
377                                 options |= GPU_SHADER_TWO_SIDED;
378                         if (c_textured && !c_badtex)
379                                 options |= GPU_SHADER_TEXTURE_2D;
380
381                         if (!ma)
382                                 ma = give_current_material_or_def(NULL, 0);  /* default material */
383
384                         float specular[3];
385                         mul_v3_v3fl(specular, &ma->specr, ma->spec);
386
387                         GPU_basic_shader_colors(NULL, specular, ma->har, 1.0f);
388                         GPU_basic_shader_bind(options);
389                 }
390                 else {
391                         GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
392                 }
393
394                 c_lit = lit;
395                 c_ma = ma;
396         }
397
398         return c_badtex;
399 }
400
401 static void draw_textured_begin(Scene *scene, View3D *v3d, RegionView3D *rv3d, Object *ob)
402 {
403         unsigned char obcol[4];
404         bool is_tex, solidtex;
405         Mesh *me = ob->data;
406         ImagePaintSettings *imapaint = &scene->toolsettings->imapaint;
407
408         /* XXX scene->obedit warning */
409
410         /* texture draw is abused for mask selection mode, do this so wire draw
411          * with face selection in weight paint is not lit. */
412         if ((v3d->drawtype <= OB_WIRE) && (ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT))) {
413                 solidtex = false;
414                 Gtexdraw.is_lit = 0;
415         }
416         else if ((ob->mode & OB_MODE_TEXTURE_PAINT) && BKE_scene_use_new_shading_nodes(scene)) {
417                 solidtex = true;
418                 if (v3d->flag2 & V3D_SHADELESS_TEX)
419                         Gtexdraw.is_lit = 0;
420                 else
421                         Gtexdraw.is_lit = -1;
422         }
423         else if ((v3d->drawtype == OB_SOLID) ||
424                  ((ob->mode & OB_MODE_EDIT) && (v3d->drawtype != OB_TEXTURE)))
425         {
426                 /* draw with default lights in solid draw mode and edit mode */
427                 solidtex = true;
428                 Gtexdraw.is_lit = -1;
429         }
430         else {
431                 /* draw with lights in the scene otherwise */
432                 solidtex = false;
433                 if (v3d->flag2 & V3D_SHADELESS_TEX)
434                         Gtexdraw.is_lit = 0;
435                 else
436                         Gtexdraw.is_lit = GPU_scene_object_lights(scene, ob, v3d->lay, rv3d->viewmat, !rv3d->is_persp);
437         }
438         
439         rgba_float_to_uchar(obcol, ob->col);
440
441         if (solidtex || v3d->drawtype == OB_TEXTURE) is_tex = true;
442         else is_tex = false;
443
444         Gtexdraw.ob = ob;
445         Gtexdraw.stencil = (imapaint->flag & IMAGEPAINT_PROJECT_LAYER_STENCIL) ? imapaint->stencil : NULL;
446         Gtexdraw.is_texpaint = (ob->mode == OB_MODE_TEXTURE_PAINT);
447         Gtexdraw.texpaint_material = (imapaint->mode == IMAGEPAINT_MODE_MATERIAL);
448         Gtexdraw.canvas = (Gtexdraw.texpaint_material) ? NULL : imapaint->canvas;
449         Gtexdraw.is_tex = is_tex;
450
451         /* naughty multitexturing hacks to quickly support stencil + shading + alpha blending 
452          * in new texpaint code. The better solution here would be to support GLSL */
453         if (Gtexdraw.is_texpaint) {                     
454                 glActiveTexture(GL_TEXTURE1);
455                 glEnable(GL_TEXTURE_2D);
456                 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
457                 glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE);
458                 glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_PREVIOUS);
459                 glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_PRIMARY_COLOR);
460                 glTexEnvi(GL_TEXTURE_ENV, GL_SRC2_RGB, GL_PREVIOUS);
461                 glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_ALPHA);
462                 glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
463                 glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PREVIOUS);
464                 
465                 /* load the stencil texture here */
466                 if (Gtexdraw.stencil != NULL) {
467                         glActiveTexture(GL_TEXTURE2);
468                         if (GPU_verify_image(Gtexdraw.stencil, NULL, GL_TEXTURE_2D, false, false, false, false)) {
469                                 float col[4] = {imapaint->stencil_col[0], imapaint->stencil_col[1], imapaint->stencil_col[2], 1.0f};
470                                 glEnable(GL_TEXTURE_2D);
471                                 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
472                                 glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE);
473                                 glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_PREVIOUS);
474                                 glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_CONSTANT);
475                                 glTexEnvi(GL_TEXTURE_ENV, GL_SRC2_RGB, GL_TEXTURE);
476                                 glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_MODULATE);
477                                 glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PREVIOUS);
478                                 glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_ALPHA, GL_TEXTURE);
479                                 glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, col);
480                                 if ((imapaint->flag & IMAGEPAINT_PROJECT_LAYER_STENCIL_INV) == 0) {
481                                         glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_ONE_MINUS_SRC_COLOR);
482                                 }
483                                 else {
484                                         glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_COLOR);
485                                 }
486                         }
487                 }
488                 glActiveTexture(GL_TEXTURE0);
489         }
490         
491         Gtexdraw.color_profile = BKE_scene_check_color_management_enabled(scene);
492         Gtexdraw.use_game_mat = (RE_engines_find(scene->r.engine)->flag & RE_GAME) != 0;
493         Gtexdraw.use_backface_culling = (v3d->flag2 & V3D_BACKFACE_CULLING) != 0;
494         Gtexdraw.two_sided_lighting = (me->flag & ME_TWOSIDED);
495
496         memcpy(Gtexdraw.obcol, obcol, sizeof(obcol));
497         set_draw_settings_cached(1, NULL, NULL, Gtexdraw);
498         glCullFace(GL_BACK);
499 }
500
501 static void draw_textured_end(void)
502 {
503         if (Gtexdraw.ob->mode & OB_MODE_TEXTURE_PAINT) {
504                 glActiveTexture(GL_TEXTURE1);
505                 glDisable(GL_TEXTURE_2D);
506                 glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_COLOR);
507                 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
508                 glBindTexture(GL_TEXTURE_2D, 0);
509
510                 if (Gtexdraw.stencil != NULL) {
511                         glActiveTexture(GL_TEXTURE2);
512                         glDisable(GL_TEXTURE_2D);
513                         glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_COLOR);
514                         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
515                         glBindTexture(GL_TEXTURE_2D, 0);
516                 }               
517                 glActiveTexture(GL_TEXTURE0);
518                 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
519                 /* manual reset, since we don't use tpage */
520                 glBindTexture(GL_TEXTURE_2D, 0);
521                 /* force switch off textures */
522                 GPU_clear_tpage(true);
523         }
524         else {
525                 /* switch off textures */
526                 GPU_set_tpage(NULL, 0, 0);
527         }
528
529         glDisable(GL_CULL_FACE);
530         GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
531
532         /* XXX, bad patch - GPU_default_lights() calls
533          * glLightfv(GL_POSITION, ...) which
534          * is transformed by the current matrix... we
535          * need to make sure that matrix is identity.
536          * 
537          * It would be better if drawmesh.c kept track
538          * of and restored the light settings it changed.
539          *  - zr
540          */
541         glPushMatrix();
542         glLoadIdentity();
543         GPU_default_lights();
544         glPopMatrix();
545 }
546
547 static DMDrawOption draw_tface__set_draw_legacy(MTexPoly *mtexpoly, const bool has_mcol, int matnr)
548 {
549         Material *ma = give_current_material(Gtexdraw.ob, matnr + 1);
550         bool invalidtexture = false;
551
552         if (ma && (ma->game.flag & GEMAT_INVISIBLE))
553                 return DM_DRAW_OPTION_SKIP;
554
555         invalidtexture = set_draw_settings_cached(0, mtexpoly, ma, Gtexdraw);
556
557         if (mtexpoly && invalidtexture) {
558                 glColor3ub(0xFF, 0x00, 0xFF);
559                 return DM_DRAW_OPTION_NO_MCOL; /* Don't set color */
560         }
561         else if (!has_mcol) {
562                 if (mtexpoly) {
563                         glColor3f(1.0, 1.0, 1.0);
564                 }
565                 else {
566                         if (ma) {
567                                 if (ma->shade_flag & MA_OBCOLOR) {
568                                         glColor3ubv(Gtexdraw.obcol);
569                                 }
570                                 else {
571                                         float col[3];
572                                         if (Gtexdraw.color_profile) linearrgb_to_srgb_v3_v3(col, &ma->r);
573                                         else copy_v3_v3(col, &ma->r);
574
575                                         glColor3fv(col);
576                                 }
577                         }
578                         else {
579                                 glColor3f(1.0, 1.0, 1.0);
580                         }
581                 }
582                 return DM_DRAW_OPTION_NORMAL; /* normal drawing (no mcols anyway, no need to turn off) */
583         }
584         else {
585                 return DM_DRAW_OPTION_NORMAL; /* Set color from mcol */
586         }
587 }
588
589 static DMDrawOption draw_tface__set_draw(MTexPoly *mtexpoly, const bool UNUSED(has_mcol), int matnr)
590 {
591         Material *ma = give_current_material(Gtexdraw.ob, matnr + 1);
592
593         if (ma && (ma->game.flag & GEMAT_INVISIBLE)) return DM_DRAW_OPTION_SKIP;
594
595         if (mtexpoly || Gtexdraw.is_texpaint)
596                 set_draw_settings_cached(0, mtexpoly, ma, Gtexdraw);
597
598         /* always use color from mcol, as set in update_tface_color_layer */
599         return DM_DRAW_OPTION_NORMAL;
600 }
601
602 static void update_tface_color_layer(DerivedMesh *dm, bool use_mcol)
603 {
604         const MPoly *mp = dm->getPolyArray(dm);
605         const int mpoly_num = dm->getNumPolys(dm);
606         MTexPoly *mtexpoly = DM_get_poly_data_layer(dm, CD_MTEXPOLY);
607         MLoopCol *finalCol;
608         int i, j;
609         MLoopCol *mloopcol = NULL;
610
611         /* cache material values to avoid a lot of lookups */
612         Material *ma = NULL;
613         short mat_nr_prev = -1;
614         enum {
615                 COPY_CALC,
616                 COPY_ORIG,
617                 COPY_PREV,
618         } copy_mode = COPY_CALC;
619
620         if (use_mcol) {
621                 mloopcol = dm->getLoopDataArray(dm, CD_PREVIEW_MLOOPCOL);
622                 if (!mloopcol)
623                         mloopcol = dm->getLoopDataArray(dm, CD_MLOOPCOL);
624         }
625
626         if (CustomData_has_layer(&dm->loopData, CD_TEXTURE_MLOOPCOL)) {
627                 finalCol = CustomData_get_layer(&dm->loopData, CD_TEXTURE_MLOOPCOL);
628         }
629         else {
630                 finalCol = MEM_mallocN(sizeof(MLoopCol) * dm->numLoopData, "add_tface_color_layer");
631                 CustomData_add_layer(&dm->loopData, CD_TEXTURE_MLOOPCOL, CD_ASSIGN, finalCol, dm->numLoopData);
632         }
633
634         for (i = mpoly_num; i--; mp++) {
635                 const short mat_nr = mp->mat_nr;
636
637                 if (UNLIKELY(mat_nr_prev != mat_nr)) {
638                         ma = give_current_material(Gtexdraw.ob, mat_nr + 1);
639                         copy_mode = COPY_CALC;
640                         mat_nr_prev = mat_nr;
641                 }
642
643                 /* avoid lookups  */
644                 if (copy_mode == COPY_ORIG) {
645                         memcpy(&finalCol[mp->loopstart], &mloopcol[mp->loopstart], sizeof(*finalCol) * mp->totloop);
646                 }
647                 else if (copy_mode == COPY_PREV) {
648                         int loop_index = mp->loopstart;
649                         const MLoopCol *lcol_prev = &finalCol[(mp - 1)->loopstart];
650                         for (j = 0; j < mp->totloop; j++, loop_index++) {
651                                 finalCol[loop_index] = *lcol_prev;
652                         }
653                 }
654
655                 /* (copy_mode == COPY_CALC) */
656                 else if (ma && (ma->game.flag & GEMAT_INVISIBLE)) {
657                         if (mloopcol) {
658                                 memcpy(&finalCol[mp->loopstart], &mloopcol[mp->loopstart], sizeof(*finalCol) * mp->totloop);
659                                 copy_mode = COPY_ORIG;
660                         }
661                         else {
662                                 memset(&finalCol[mp->loopstart], 0xff, sizeof(*finalCol) * mp->totloop);
663                                 copy_mode = COPY_PREV;
664                         }
665                 }
666                 else if (mtexpoly && set_draw_settings_cached(0, mtexpoly, ma, Gtexdraw)) {
667                         int loop_index = mp->loopstart;
668                         for (j = 0; j < mp->totloop; j++, loop_index++) {
669                                 finalCol[loop_index].r = 255;
670                                 finalCol[loop_index].g = 0;
671                                 finalCol[loop_index].b = 255;
672                         }
673                         copy_mode = COPY_PREV;
674                 }
675                 else if (ma && (ma->shade_flag & MA_OBCOLOR)) {
676                         int loop_index = mp->loopstart;
677                         for (j = 0; j < mp->totloop; j++, loop_index++) {
678                                 copy_v3_v3_uchar(&finalCol[loop_index].r, Gtexdraw.obcol);
679                         }
680                         copy_mode = COPY_PREV;
681                 }
682                 else {
683                         if (mloopcol) {
684                                 memcpy(&finalCol[mp->loopstart], &mloopcol[mp->loopstart], sizeof(*finalCol) * mp->totloop);
685                                 copy_mode = COPY_ORIG;
686                         }
687                         else if (mtexpoly) {
688                                 memset(&finalCol[mp->loopstart], 0xff, sizeof(*finalCol) * mp->totloop);
689                                 copy_mode = COPY_PREV;
690                         }
691                         else {
692                                 float col[3];
693
694                                 if (ma) {
695                                         int loop_index = mp->loopstart;
696                                         MLoopCol lcol;
697
698                                         if (Gtexdraw.color_profile) linearrgb_to_srgb_v3_v3(col, &ma->r);
699                                         else copy_v3_v3(col, &ma->r);
700                                         rgb_float_to_uchar((unsigned char *)&lcol.r, col);
701                                         lcol.a = 255;
702                                         
703                                         for (j = 0; j < mp->totloop; j++, loop_index++) {
704                                                 finalCol[loop_index] = lcol;
705                                         }
706                                 }
707                                 else {
708                                         memset(&finalCol[mp->loopstart], 0xff, sizeof(*finalCol) * mp->totloop);
709                                 }
710                                 copy_mode = COPY_PREV;
711                         }
712                 }
713         }
714
715         dm->dirty |= DM_DIRTY_MCOL_UPDATE_DRAW;
716 }
717
718 static DMDrawOption draw_tface_mapped__set_draw(void *userData, int origindex, int UNUSED(mat_nr))
719 {
720         const Mesh *me = ((drawTFace_userData *)userData)->me;
721
722         /* array checked for NULL before calling */
723         MPoly *mpoly = &me->mpoly[origindex];
724
725         BLI_assert(origindex >= 0 && origindex < me->totpoly);
726
727         if (mpoly->flag & ME_HIDE) {
728                 return DM_DRAW_OPTION_SKIP;
729         }
730         else {
731                 MTexPoly *tpoly = (me->mtpoly) ? &me->mtpoly[origindex] : NULL;
732                 int matnr = mpoly->mat_nr;
733                 
734                 return draw_tface__set_draw(tpoly, (me->mloopcol != NULL), matnr);
735         }
736 }
737
738 static DMDrawOption draw_em_tf_mapped__set_draw(void *userData, int origindex, int mat_nr)
739 {
740         drawEMTFMapped_userData *data = userData;
741         BMEditMesh *em = data->em;
742         BMFace *efa;
743
744         if (UNLIKELY(origindex >= em->bm->totface))
745                 return DM_DRAW_OPTION_NORMAL;
746
747         efa = BM_face_at_index(em->bm, origindex);
748
749         if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
750                 return DM_DRAW_OPTION_SKIP;
751         }
752         else {
753                 MTexPoly *mtexpoly = (data->cd_poly_tex_offset != -1) ?
754                         BM_ELEM_CD_GET_VOID_P(efa, data->cd_poly_tex_offset) : NULL;
755                 int matnr = (mat_nr != -1) ? mat_nr : efa->mat_nr;
756
757                 return draw_tface__set_draw_legacy(mtexpoly, data->has_mcol, matnr);
758         }
759 }
760
761 /* when face select is on, use face hidden flag */
762 static DMDrawOption wpaint__setSolidDrawOptions_facemask(void *userData, int index)
763 {
764         Mesh *me = (Mesh *)userData;
765         MPoly *mp = &me->mpoly[index];
766         if (mp->flag & ME_HIDE)
767                 return DM_DRAW_OPTION_SKIP;
768         return DM_DRAW_OPTION_NORMAL;
769 }
770
771 static void draw_mesh_text(Scene *scene, Object *ob, int glsl)
772 {
773         Mesh *me = ob->data;
774         DerivedMesh *ddm;
775         MPoly *mp, *mface  = me->mpoly;
776         MTexPoly *mtpoly   = me->mtpoly;
777         MLoopUV *mloopuv   = me->mloopuv;
778         MLoopUV *luv;
779         MLoopCol *mloopcol = me->mloopcol;  /* why does mcol exist? */
780         MLoopCol *lcol;
781
782         bProperty *prop = BKE_bproperty_object_get(ob, "Text");
783         GPUVertexAttribs gattribs;
784         int a, totpoly = me->totpoly;
785
786         /* fake values to pass to GPU_render_text() */
787         MCol  tmp_mcol[4]  = {{0}};
788         MCol *tmp_mcol_pt  = mloopcol ? tmp_mcol : NULL;
789
790         /* don't draw without tfaces */
791         if (!mtpoly || !mloopuv)
792                 return;
793
794         /* don't draw when editing */
795         if (ob->mode & OB_MODE_EDIT)
796                 return;
797         else if (ob == OBACT)
798                 if (BKE_paint_select_elem_test(ob))
799                         return;
800
801         ddm = mesh_get_derived_deform(scene, ob, CD_MASK_BAREMESH);
802
803         for (a = 0, mp = mface; a < totpoly; a++, mtpoly++, mp++) {
804                 short matnr = mp->mat_nr;
805                 const bool mf_smooth = (mp->flag & ME_SMOOTH) != 0;
806                 Material *mat = (me->mat) ? me->mat[matnr] : NULL;
807                 int mode = mat ? mat->game.flag : GEMAT_INVISIBLE;
808
809
810                 if (!(mode & GEMAT_INVISIBLE) && (mode & GEMAT_TEXT) && mp->totloop >= 3) {
811                         /* get the polygon as a tri/quad */
812                         int mp_vi[4];
813                         float   v_quad_data[4][3];
814                         const float  *v_quad[4];
815                         const float *uv_quad[4];
816                         char string[MAX_PROPSTRING];
817                         int characters, i, glattrib = -1, badtex = 0;
818
819
820                         /* TEXFACE */
821                         if (glsl) {
822                                 GPU_object_material_bind(matnr + 1, &gattribs);
823
824                                 for (i = 0; i < gattribs.totlayer; i++) {
825                                         if (gattribs.layer[i].type == CD_MTFACE) {
826                                                 glattrib = gattribs.layer[i].glindex;
827                                                 break;
828                                         }
829                                 }
830                         }
831                         else {
832                                 badtex = set_draw_settings_cached(0, mtpoly, mat, Gtexdraw);
833                                 if (badtex) {
834                                         continue;
835                                 }
836                         }
837
838                         mp_vi[0] = me->mloop[mp->loopstart + 0].v;
839                         mp_vi[1] = me->mloop[mp->loopstart + 1].v;
840                         mp_vi[2] = me->mloop[mp->loopstart + 2].v;
841                         mp_vi[3] = (mp->totloop >= 4) ? me->mloop[mp->loopstart + 3].v : 0;
842
843                         /* UV */
844                         luv = &mloopuv[mp->loopstart];
845                         uv_quad[0] = luv->uv; luv++;
846                         uv_quad[1] = luv->uv; luv++;
847                         uv_quad[2] = luv->uv; luv++;
848                         if (mp->totloop >= 4) {
849                                 uv_quad[3] = luv->uv;
850                         }
851                         else {
852                                 uv_quad[3] = NULL;
853                         }
854
855
856                         /* COLOR */
857                         if (mloopcol) {
858                                 unsigned int totloop_clamp = min_ii(4, mp->totloop);
859                                 unsigned int j;
860                                 lcol = &mloopcol[mp->loopstart];
861
862                                 for (j = 0; j < totloop_clamp; j++, lcol++) {
863                                         MESH_MLOOPCOL_TO_MCOL(lcol, &tmp_mcol[j]);
864                                 }
865                         }
866
867                         /* LOCATION */
868                         ddm->getVertCo(ddm, mp_vi[0], v_quad_data[0]);
869                         ddm->getVertCo(ddm, mp_vi[1], v_quad_data[1]);
870                         ddm->getVertCo(ddm, mp_vi[2], v_quad_data[2]);
871                         if (mp->totloop >= 4) {
872                                 ddm->getVertCo(ddm, mp_vi[3], v_quad_data[3]);
873                         }
874
875                         v_quad[0] = v_quad_data[0];
876                         v_quad[1] = v_quad_data[1];
877                         v_quad[2] = v_quad_data[2];
878                         if (mp->totloop >= 4) {
879                                 v_quad[3] = v_quad_data[2];
880                         }
881                         else {
882                                 v_quad[3] = NULL;
883                         }
884
885
886                         /* The BM_FONT handling is in the gpu module, shared with the
887                          * game engine, was duplicated previously */
888
889                         BKE_bproperty_set_valstr(prop, string);
890                         characters = strlen(string);
891                         
892                         if (!BKE_image_has_ibuf(mtpoly->tpage, NULL))
893                                 characters = 0;
894
895                         if (!mf_smooth) {
896                                 float nor[3];
897
898                                 normal_tri_v3(nor, v_quad[0], v_quad[1], v_quad[2]);
899
900                                 glNormal3fv(nor);
901                         }
902
903                         GPU_render_text(
904                                 mtpoly, mode, string, characters,
905                                 (unsigned int *)tmp_mcol_pt,
906                                 v_quad, uv_quad,
907                                 glattrib);
908                 }
909         }
910
911         ddm->release(ddm);
912 }
913
914 static int compareDrawOptions(void *userData, int cur_index, int next_index)
915 {
916         drawTFace_userData *data = userData;
917
918         if (data->mpoly && data->mpoly[cur_index].mat_nr != data->mpoly[next_index].mat_nr)
919                 return 0;
920
921         if (data->mtexpoly && data->mtexpoly[cur_index].tpage != data->mtexpoly[next_index].tpage)
922                 return 0;
923
924         return 1;
925 }
926
927
928 static int compareDrawOptionsEm(void *userData, int cur_index, int next_index)
929 {
930         drawEMTFMapped_userData *data = userData;
931
932         if (data->mpoly && data->mpoly[cur_index].mat_nr != data->mpoly[next_index].mat_nr)
933                 return 0;
934
935         if (data->mtexpoly && data->mtexpoly[cur_index].tpage != data->mtexpoly[next_index].tpage)
936                 return 0;
937
938         return 1;
939 }
940
941 static void draw_mesh_textured_old(Scene *scene, View3D *v3d, RegionView3D *rv3d,
942                                    Object *ob, DerivedMesh *dm, const int draw_flags)
943 {
944         Mesh *me = ob->data;
945
946         /* correct for negative scale */
947         if (ob->transflag & OB_NEG_SCALE) glFrontFace(GL_CW);
948         else glFrontFace(GL_CCW);
949         
950         /* draw the textured mesh */
951         draw_textured_begin(scene, v3d, rv3d, ob);
952
953         glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
954
955         if (ob->mode & OB_MODE_EDIT) {
956                 drawEMTFMapped_userData data;
957
958                 data.em = me->edit_btmesh;
959                 data.has_mcol = CustomData_has_layer(&me->edit_btmesh->bm->ldata, CD_MLOOPCOL);
960                 data.cd_poly_tex_offset = CustomData_get_offset(&me->edit_btmesh->bm->pdata, CD_MTEXPOLY);
961
962                 data.mpoly = DM_get_poly_data_layer(dm, CD_MPOLY);
963                 data.mtexpoly = DM_get_poly_data_layer(dm, CD_MTEXPOLY);
964
965                 dm->drawMappedFacesTex(dm, draw_em_tf_mapped__set_draw, compareDrawOptionsEm, &data, 0);
966         }
967         else {
968                 DMDrawFlag dm_draw_flag;
969                 drawTFace_userData userData;
970
971                 if (ob->mode & OB_MODE_TEXTURE_PAINT) {
972                         dm_draw_flag = DM_DRAW_USE_TEXPAINT_UV;
973                 }
974                 else {
975                         dm_draw_flag = DM_DRAW_USE_ACTIVE_UV;
976                 }
977
978                 if (ob == OBACT) {
979                         if (ob->mode & OB_MODE_WEIGHT_PAINT) {
980                                 dm_draw_flag |= DM_DRAW_USE_COLORS | DM_DRAW_ALWAYS_SMOOTH | DM_DRAW_SKIP_HIDDEN;
981
982                         }
983                         else if (ob->mode & OB_MODE_SCULPT) {
984                                 dm_draw_flag |= DM_DRAW_SKIP_HIDDEN;
985                         }
986                 }
987
988
989                 userData.mpoly = DM_get_poly_data_layer(dm, CD_MPOLY);
990                 userData.mtexpoly = DM_get_poly_data_layer(dm, CD_MTEXPOLY);
991
992                 if (draw_flags & DRAW_FACE_SELECT) {
993                         userData.me = me;
994
995                         dm->drawMappedFacesTex(
996                                 dm, me->mpoly ? draw_tface_mapped__set_draw : NULL, compareDrawOptions,
997                                 &userData, dm_draw_flag);
998                 }
999                 else {
1000                         userData.me = NULL;
1001
1002                         if ((ob->mode & OB_MODE_ALL_PAINT) == 0) {
1003
1004                                 /* Note: this isn't efficient and runs on every redraw,
1005                                  * its needed so material colors are used for vertex colors.
1006                                  * In the future we will likely remove 'texface' so, just avoid running this where possible,
1007                                  * (when vertex paint or weight paint are used). */
1008
1009                                 update_tface_color_layer(dm, !(ob->mode & OB_MODE_TEXTURE_PAINT));
1010                         }
1011
1012                         dm->drawFacesTex(
1013                                 dm, draw_tface__set_draw, compareDrawOptions,
1014                                 &userData, dm_draw_flag);
1015                 }
1016         }
1017
1018         /* draw game engine text hack */
1019         if (rv3d->rflag & RV3D_IS_GAME_ENGINE) {
1020                 if (BKE_bproperty_object_get(ob, "Text")) {
1021                         draw_mesh_text(scene, ob, 0);
1022                 }
1023         }
1024
1025         draw_textured_end();
1026         
1027         /* draw edges and selected faces over textured mesh */
1028         if (!(ob == scene->obedit) && (draw_flags & DRAW_FACE_SELECT)) {
1029                 bool draw_select_edges = (ob->mode & OB_MODE_TEXTURE_PAINT) == 0;
1030                 draw_mesh_face_select(rv3d, me, dm, draw_select_edges);
1031         }
1032
1033         /* reset from negative scale correction */
1034         glFrontFace(GL_CCW);
1035         
1036         /* in editmode, the blend mode needs to be set in case it was ADD */
1037         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1038 }
1039
1040 /************************** NEW SHADING NODES ********************************/
1041
1042 typedef struct TexMatCallback {
1043         Scene *scene;
1044         Object *ob;
1045         Mesh *me;
1046         DerivedMesh *dm;
1047         bool shadeless;
1048         bool two_sided_lighting;
1049 } TexMatCallback;
1050
1051 static void tex_mat_set_material_cb(void *UNUSED(userData), int mat_nr, void *attribs)
1052 {
1053         /* all we have to do here is simply enable the GLSL material, but note
1054          * that the GLSL code will give different result depending on the drawtype,
1055          * in texture draw mode it will output the active texture node, in material
1056          * draw mode it will show the full material. */
1057         GPU_object_material_bind(mat_nr, attribs);
1058 }
1059
1060 static void tex_mat_set_texture_cb(void *userData, int mat_nr, void *attribs)
1061 {
1062         /* texture draw mode without GLSL */
1063         TexMatCallback *data = (TexMatCallback *)userData;
1064         GPUVertexAttribs *gattribs = attribs;
1065         Image *ima;
1066         ImageUser *iuser;
1067         bNode *node;
1068
1069         /* draw image texture if we find one */
1070         if (ED_object_get_active_image(data->ob, mat_nr, &ima, &iuser, &node, NULL)) {
1071                 /* get openl texture */
1072                 int mipmap = 1;
1073                 int bindcode = (ima) ? GPU_verify_image(ima, iuser, GL_TEXTURE_2D, 0, 0, mipmap, false) : 0;
1074
1075                 if (bindcode) {
1076                         NodeTexBase *texbase = node->storage;
1077
1078                         /* disable existing material */
1079                         GPU_object_material_unbind();
1080
1081                         /* bind texture */
1082                         glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]);
1083
1084                         glMatrixMode(GL_TEXTURE);
1085                         glLoadMatrixf(texbase->tex_mapping.mat);
1086                         glMatrixMode(GL_MODELVIEW);
1087
1088                         /* use active UV texture layer */
1089                         memset(gattribs, 0, sizeof(*gattribs));
1090
1091                         gattribs->layer[0].type = CD_MTFACE;
1092                         gattribs->layer[0].name[0] = '\0';
1093                         gattribs->layer[0].gltexco = 1;
1094                         gattribs->totlayer = 1;
1095
1096                         /* bind material */
1097                         float diffuse[3] = {1.0f, 1.0f, 1.0f};
1098
1099                         int options = GPU_SHADER_TEXTURE_2D;
1100                         if (!data->shadeless)
1101                                 options |= GPU_SHADER_LIGHTING;
1102                         if (data->two_sided_lighting)
1103                                 options |= GPU_SHADER_TWO_SIDED;
1104
1105                         GPU_basic_shader_colors(diffuse, NULL, 0, 1.0f);
1106                         GPU_basic_shader_bind(options);
1107
1108                         return;
1109                 }
1110         }
1111
1112         /* disable texture material */
1113         GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
1114
1115         if (data->shadeless) {
1116                 glColor3f(1.0f, 1.0f, 1.0f);
1117                 memset(gattribs, 0, sizeof(*gattribs));
1118         }
1119         else {
1120                 glMatrixMode(GL_TEXTURE);
1121                 glLoadIdentity();
1122                 glMatrixMode(GL_MODELVIEW);
1123
1124                 /* enable solid material */
1125                 GPU_object_material_bind(mat_nr, attribs);
1126         }
1127 }
1128
1129 static bool tex_mat_set_face_mesh_cb(void *userData, int index)
1130 {
1131         /* faceselect mode face hiding */
1132         TexMatCallback *data = (TexMatCallback *)userData;
1133         Mesh *me = (Mesh *)data->me;
1134         MPoly *mp = &me->mpoly[index];
1135
1136         return !(mp->flag & ME_HIDE);
1137 }
1138
1139 static bool tex_mat_set_face_editmesh_cb(void *userData, int index)
1140 {
1141         /* editmode face hiding */
1142         TexMatCallback *data = (TexMatCallback *)userData;
1143         Mesh *me = (Mesh *)data->me;
1144         BMEditMesh *em = me->edit_btmesh;
1145         BMFace *efa;
1146
1147         if (UNLIKELY(index >= em->bm->totface))
1148                 return DM_DRAW_OPTION_NORMAL;
1149
1150         efa = BM_face_at_index(em->bm, index);
1151
1152         return !BM_elem_flag_test(efa, BM_ELEM_HIDDEN);
1153 }
1154
1155 void draw_mesh_textured(Scene *scene, View3D *v3d, RegionView3D *rv3d,
1156                         Object *ob, DerivedMesh *dm, const int draw_flags)
1157 {
1158         /* if not cycles, or preview-modifiers, or drawing matcaps */
1159         if ((draw_flags & DRAW_MODIFIERS_PREVIEW) ||
1160             (v3d->flag2 & V3D_SHOW_SOLID_MATCAP) ||
1161             (BKE_scene_use_new_shading_nodes(scene) == false) ||
1162             ((ob->mode & OB_MODE_TEXTURE_PAINT) && ELEM(v3d->drawtype, OB_TEXTURE, OB_SOLID)))
1163         {
1164                 draw_mesh_textured_old(scene, v3d, rv3d, ob, dm, draw_flags);
1165                 return;
1166         }
1167         else if (ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT)) {
1168                 draw_mesh_paint(v3d, rv3d, ob, dm, draw_flags);
1169                 return;
1170         }
1171
1172         /* set opengl state for negative scale & color */
1173         if (ob->transflag & OB_NEG_SCALE) glFrontFace(GL_CW);
1174         else glFrontFace(GL_CCW);
1175
1176         Mesh *me = ob->data;
1177
1178         bool shadeless = ((v3d->flag2 & V3D_SHADELESS_TEX) &&
1179             ((v3d->drawtype == OB_TEXTURE) || (ob->mode & OB_MODE_TEXTURE_PAINT)));
1180         bool two_sided_lighting = (me->flag & ME_TWOSIDED) != 0;
1181
1182         TexMatCallback data = {scene, ob, me, dm, shadeless, two_sided_lighting};
1183         bool (*set_face_cb)(void *, int);
1184         bool picking = (G.f & G_PICKSEL) != 0;
1185         
1186         /* face hiding callback depending on mode */
1187         if (ob == scene->obedit)
1188                 set_face_cb = tex_mat_set_face_editmesh_cb;
1189         else if (draw_flags & DRAW_FACE_SELECT)
1190                 set_face_cb = tex_mat_set_face_mesh_cb;
1191         else
1192                 set_face_cb = NULL;
1193
1194         /* test if we can use glsl */
1195         const int drawtype = view3d_effective_drawtype(v3d);
1196         bool glsl = (drawtype == OB_MATERIAL) && !picking;
1197
1198         GPU_begin_object_materials(v3d, rv3d, scene, ob, glsl, NULL);
1199
1200         if (glsl || picking) {
1201                 /* draw glsl or solid */
1202                 dm->drawMappedFacesMat(dm,
1203                                        tex_mat_set_material_cb,
1204                                        set_face_cb, &data);
1205         }
1206         else {
1207                 /* draw textured */
1208                 dm->drawMappedFacesMat(dm,
1209                                        tex_mat_set_texture_cb,
1210                                        set_face_cb, &data);
1211         }
1212
1213         GPU_end_object_materials();
1214
1215         /* reset opengl state */
1216         GPU_end_object_materials();
1217         GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
1218
1219         glBindTexture(GL_TEXTURE_2D, 0);
1220
1221         glFrontFace(GL_CCW);
1222
1223         glMatrixMode(GL_TEXTURE);
1224         glLoadIdentity();
1225         glMatrixMode(GL_MODELVIEW);
1226
1227         /* faceselect mode drawing over textured mesh */
1228         if (!(ob == scene->obedit) && (draw_flags & DRAW_FACE_SELECT)) {
1229                 bool draw_select_edges = (ob->mode & OB_MODE_TEXTURE_PAINT) == 0;
1230                 draw_mesh_face_select(rv3d, ob->data, dm, draw_select_edges);
1231         }
1232 }
1233
1234 /* Vertex Paint and Weight Paint */
1235 static void draw_mesh_paint_light_begin(void)
1236 {
1237         /* get material diffuse color from vertex colors but set default spec */
1238         const float specular[3] = {0.47f, 0.47f, 0.47f};
1239         GPU_basic_shader_colors(NULL, specular, 35, 1.0f);
1240         GPU_basic_shader_bind(GPU_SHADER_LIGHTING | GPU_SHADER_USE_COLOR);
1241 }
1242
1243 static void draw_mesh_paint_light_end(void)
1244 {
1245         GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
1246 }
1247
1248 void draw_mesh_paint_weight_faces(DerivedMesh *dm, const bool use_light,
1249                                   void *facemask_cb, void *user_data)
1250 {
1251         DMSetMaterial setMaterial = GPU_object_materials_check() ? GPU_object_material_bind : NULL;
1252         int flags = DM_DRAW_USE_COLORS;
1253
1254         if (use_light) {
1255                 draw_mesh_paint_light_begin();
1256                 flags |= DM_DRAW_NEED_NORMALS;
1257         }
1258
1259         dm->drawMappedFaces(dm, (DMSetDrawOptions)facemask_cb, setMaterial, NULL, user_data, flags);
1260
1261         if (use_light) {
1262                 draw_mesh_paint_light_end();
1263         }
1264 }
1265
1266 void draw_mesh_paint_vcolor_faces(DerivedMesh *dm, const bool use_light,
1267                                   void *facemask_cb, void *user_data,
1268                                   const Mesh *me)
1269 {
1270         DMSetMaterial setMaterial = GPU_object_materials_check() ? GPU_object_material_bind : NULL;
1271         int flags = 0;
1272
1273         if (use_light) {
1274                 draw_mesh_paint_light_begin();
1275                 flags |= DM_DRAW_NEED_NORMALS;
1276         }
1277
1278         if (me->mloopcol) {
1279                 dm->drawMappedFaces(dm, facemask_cb, setMaterial, NULL, user_data,
1280                                     DM_DRAW_USE_COLORS | flags);
1281         }
1282         else {
1283                 glColor3f(1.0f, 1.0f, 1.0f);
1284                 dm->drawMappedFaces(dm, facemask_cb, setMaterial, NULL, user_data, flags);
1285         }
1286
1287         if (use_light) {
1288                 draw_mesh_paint_light_end();
1289         }
1290 }
1291
1292 void draw_mesh_paint_weight_edges(RegionView3D *rv3d, DerivedMesh *dm,
1293                                   const bool use_depth, const bool use_alpha,
1294                                   void *edgemask_cb, void *user_data)
1295 {
1296         /* weight paint in solid mode, special case. focus on making the weights clear
1297          * rather than the shading, this is also forced in wire view */
1298
1299         if (use_depth) {
1300                 ED_view3d_polygon_offset(rv3d, 1.0);
1301                 glDepthMask(0);  /* disable write in zbuffer, selected edge wires show better */
1302         }
1303         else {
1304                 glDisable(GL_DEPTH_TEST);
1305         }
1306
1307         if (use_alpha) {
1308                 glEnable(GL_BLEND);
1309         }
1310
1311         glColor4ub(255, 255, 255, 96);
1312         glEnable(GL_LINE_STIPPLE);
1313         glLineStipple(1, 0xAAAA);
1314
1315         dm->drawMappedEdges(dm, (DMSetDrawOptions)edgemask_cb, user_data);
1316
1317         if (use_depth) {
1318                 ED_view3d_polygon_offset(rv3d, 0.0);
1319                 glDepthMask(1);
1320         }
1321         else {
1322                 glEnable(GL_DEPTH_TEST);
1323         }
1324
1325         glDisable(GL_LINE_STIPPLE);
1326
1327         if (use_alpha) {
1328                 glDisable(GL_BLEND);
1329         }
1330 }
1331
1332 void draw_mesh_paint(View3D *v3d, RegionView3D *rv3d,
1333                      Object *ob, DerivedMesh *dm, const int draw_flags)
1334 {
1335         DMSetDrawOptions facemask = NULL;
1336         Mesh *me = ob->data;
1337         const bool use_light = (v3d->drawtype >= OB_SOLID);
1338
1339         /* hide faces in face select mode */
1340         if (me->editflag & (ME_EDIT_PAINT_VERT_SEL | ME_EDIT_PAINT_FACE_SEL))
1341                 facemask = wpaint__setSolidDrawOptions_facemask;
1342
1343         if (ob->mode & OB_MODE_WEIGHT_PAINT) {
1344                 draw_mesh_paint_weight_faces(dm, use_light, facemask, me);
1345         }
1346         else if (ob->mode & OB_MODE_VERTEX_PAINT) {
1347                 draw_mesh_paint_vcolor_faces(dm, use_light, facemask, me, me);
1348         }
1349
1350         /* draw face selection on top */
1351         if (draw_flags & DRAW_FACE_SELECT) {
1352                 bool draw_select_edges = (ob->mode & OB_MODE_TEXTURE_PAINT) == 0;
1353                 draw_mesh_face_select(rv3d, me, dm, draw_select_edges);
1354         }
1355         else if ((use_light == false) || (ob->dtx & OB_DRAWWIRE)) {
1356                 const bool use_depth = (v3d->flag & V3D_ZBUF_SELECT) || !(ob->mode & OB_MODE_WEIGHT_PAINT);
1357                 const bool use_alpha = (ob->mode & OB_MODE_VERTEX_PAINT) == 0;
1358
1359                 if (use_alpha == false) {
1360                         set_inverted_drawing(1);
1361                 }
1362
1363                 draw_mesh_paint_weight_edges(rv3d, dm, use_depth, use_alpha, NULL, NULL);
1364
1365                 if (use_alpha == false) {
1366                         set_inverted_drawing(0);
1367                 }
1368         }
1369 }
1370