]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/texwindow.cpp
* moved zeroradiant (1.6) into trunk
[xonotic/netradiant.git] / radiant / texwindow.cpp
1 /*
2 Copyright (C) 1999-2007 id Software, Inc. and contributors.
3 For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5 This file is part of GtkRadiant.
6
7 GtkRadiant is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 GtkRadiant is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GtkRadiant; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20 */
21
22 //
23 // Texture Window
24 //
25 // Leonardo Zide (leo@lokigames.com)
26 //
27
28 /*!\todo
29 Clean up texture menu.
30 - Remove all global variables and use some objects instead.
31 - Create an interface for a plugin to add texture menu items.
32 - Make sure the interface is not dependent on gtk.
33 */
34
35 #ifdef _WIN32
36 //#include <gdk/win32/gdkwin32.h> 
37 #include <gdk/gdkwin32.h> 
38 #endif
39 #if defined (__linux__) || defined (__APPLE__)
40 #include <gdk/gdkx.h>
41 #include <dirent.h>
42 #endif
43 #include <gtk/gtk.h>
44 #include <assert.h>
45 #include <sys/stat.h>
46 #include "stdafx.h"
47 #include "texwindow.h"
48 #include "str.h"
49 #include "missing.h"
50 #include "texmanip.h"
51
52 #define TYP_MIPTEX      68
53 static unsigned tex_palette[256];
54
55 #define FONT_HEIGHT     10
56
57 //int           texture_mode = GL_NEAREST;
58 //int           texture_mode = GL_NEAREST_MIPMAP_NEAREST;
59 //int           texture_mode = GL_NEAREST_MIPMAP_LINEAR;
60 //int           texture_mode = GL_LINEAR;
61 //int           texture_mode = GL_LINEAR_MIPMAP_NEAREST;
62 int             texture_mode = GL_LINEAR_MIPMAP_LINEAR;
63
64 int g_nTextureOffset = 0;
65
66 // current active texture directory
67 //++timo FIXME: I'm not sure this is used anymore
68 char            texture_directory[128];
69 // if true, the texture window will only display in-use shaders
70 // if false, all the shaders in memory are displayed
71 qboolean g_bShowAllShaders;
72
73 bool g_bFilterEnabled = false;
74 CString g_strFilter;
75
76 // texture layout functions
77 // TTimo: now based on shaders
78 int     nActiveShadersCount;
79 int     nCurrentShader;
80 IShader*  pCurrentShader;
81 qtexture_t  *current_texture = NULL;
82 int     current_x, current_y, current_row;
83
84 // globals for textures
85 int     texture_nummenus;
86 char    texture_menunames[MAX_TEXTUREDIRS][128];
87
88 // the list of scripts/*.shader files we need to work with
89 // those are listed in shaderlist file
90 // FIXME TTimo I get the feeling that those would need to move to the shaders module
91 //   for now it's still more simple to just keep it here
92 GSList *l_shaderfiles = NULL;
93
94 void SelectTexture (int mx, int my, bool bShift, bool bFitScale=false);
95
96 void  Texture_MouseDown (int x, int y, int buttons);
97 void  Texture_MouseMoved (int x, int y, int buttons);
98
99 CPtrArray g_lstSkinCache;
100
101 // TTimo: modifed to add a qtexture_t, Texture_LoadSkin loads using the shader API / QERApp_TryTexture_ForName
102 // m_strName is a copy of qtex->name
103 struct SkinInfo
104 {
105   CString m_strName;
106   int m_nTextureBind;
107   qtexture_t *m_qtex;
108   SkinInfo(const char *pName, int n, qtexture_t *qtex)
109   {
110     m_strName = pName;
111     m_nTextureBind = n;
112     m_qtex = qtex;
113   };
114   SkinInfo(){};
115 };
116
117 // =============================================================================
118 // global functions
119
120 // gets active texture extension
121 //
122 // FIXME: fix this to be generic from project file
123 //
124 int GetTextureExtensionCount()
125 {
126   // hardcoded hack for png support
127   if (g_pGameDescription->mGameFile == "sof2.game")
128     return 3;
129   else
130     return 2;
131 }
132
133 const char* GetTextureExtension(int nIndex)
134 {
135   switch(nIndex)
136   {
137     case 0:
138       return "tga";
139       break;
140     case 1:
141       return "jpg";
142       break;
143     case 2:
144       return "png";
145       break;
146     default:
147       return NULL;
148   }
149 }
150
151 /*
152 ==============
153 Texture_InitPalette
154 ==============
155 */
156 void Texture_InitPalette (byte *pal)
157 {
158   int   r,g,b;
159   int   i;
160   int   inf;
161   byte  gammatable[256];
162   float gamma;
163
164   gamma = g_qeglobals.d_savedinfo.fGamma;
165
166   if (gamma == 1.0)
167   {
168     for (i=0 ; i<256 ; i++)
169       gammatable[i] = i;
170   } else
171   {
172     for (i=0 ; i<256 ; i++)
173     {
174       inf = (int)( 255.0f * pow( ( i + 0.5f ) / 255.5f , gamma ) + 0.5f );
175       if (inf < 0)
176         inf = 0;
177       if (inf > 255)
178         inf = 255;
179       gammatable[i] = inf;
180     }
181   }
182
183   for (i=0 ; i<256 ; i++)
184   {
185     r = gammatable[pal[0]];
186     g = gammatable[pal[1]];
187     b = gammatable[pal[2]];
188     pal += 3;
189
190     //v = (r<<24) + (g<<16) + (b<<8) + 255;
191     //v = BigLong (v);
192
193     //tex_palette[i] = v;
194     tex_palette[i*3+0] = r;
195     tex_palette[i*3+1] = g;
196     tex_palette[i*3+2] = b;
197   }
198 }
199
200 void SetTexParameters (void)
201 {
202   qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture_mode );
203
204   switch ( texture_mode )
205   {
206   case GL_NEAREST:
207   case GL_NEAREST_MIPMAP_NEAREST:
208   case GL_NEAREST_MIPMAP_LINEAR:
209     qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
210     break;
211   case GL_LINEAR:
212   case GL_LINEAR_MIPMAP_NEAREST:
213   case GL_LINEAR_MIPMAP_LINEAR:
214     qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
215     break;
216   }
217 }
218
219 /*
220 ============
221 Texture_SetMode
222 ============
223 */
224 void Texture_SetMode(int iMenu)
225 {
226   int iMode;
227   qboolean texturing = true;
228   gpointer item = NULL;
229
230   switch (iMenu)
231   {
232   case ID_VIEW_NEAREST:
233     item = g_object_get_data (G_OBJECT (g_pParentWnd->m_pWidget), "menu_view_nearest");
234     iMode = GL_NEAREST;
235     break;
236   case ID_VIEW_NEARESTMIPMAP:
237     item = g_object_get_data (G_OBJECT (g_pParentWnd->m_pWidget), "menu_view_nearestmipmap");
238     iMode = GL_NEAREST_MIPMAP_NEAREST;
239     break;
240   case ID_VIEW_LINEAR:
241     item = g_object_get_data (G_OBJECT (g_pParentWnd->m_pWidget), "menu_view_linear");
242     iMode = GL_LINEAR;
243     break;
244   case ID_VIEW_BILINEAR:
245     item = g_object_get_data (G_OBJECT (g_pParentWnd->m_pWidget), "menu_view_bilinear");
246     iMode = GL_NEAREST_MIPMAP_LINEAR;
247     break;
248   case ID_VIEW_BILINEARMIPMAP:
249     item = g_object_get_data (G_OBJECT (g_pParentWnd->m_pWidget), "menu_view_bilinearmipmap");
250     iMode = GL_LINEAR_MIPMAP_NEAREST;
251     break;
252   case ID_VIEW_TRILINEAR:
253     item = g_object_get_data (G_OBJECT (g_pParentWnd->m_pWidget), "menu_view_trilinear");
254     iMode = GL_LINEAR_MIPMAP_LINEAR;
255     break;
256   case ID_TEXTURES_WIREFRAME:
257     item = g_object_get_data (G_OBJECT (g_pParentWnd->m_pWidget), "menu_view_wireframe");
258     iMode = -1;
259     texturing = false;
260     break;
261   case ID_TEXTURES_FLATSHADE:
262     item = g_object_get_data (G_OBJECT (g_pParentWnd->m_pWidget), "menu_view_flatshade");
263     iMode = -1;
264     texturing = false;
265     break;
266   }
267
268   g_qeglobals.d_savedinfo.iTexMenu = iMenu;
269   // NOTE: texture_mode is a GLenum used directly in glTexParameter
270   if(iMode!=-1) texture_mode = iMode;
271
272   g_bIgnoreCommands++;
273   if (item != NULL)
274     gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (item), TRUE);
275   g_bIgnoreCommands--;
276
277   if (texturing)
278     SetTexParameters ();
279
280   if ( !texturing && iMenu == ID_TEXTURES_WIREFRAME)
281   {
282     g_pParentWnd->GetCamWnd()->Camera()->draw_mode = cd_wire;
283     Map_BuildBrushData();
284     Sys_UpdateWindows (W_ALL);
285     return;
286   } else if ( !texturing && iMenu == ID_TEXTURES_FLATSHADE)
287   {
288     g_pParentWnd->GetCamWnd()->Camera()->draw_mode = cd_solid;
289     Map_BuildBrushData();
290     Sys_UpdateWindows (W_ALL);
291     return;
292   }
293
294   for (qtexture_t *q = g_qeglobals.d_qtextures; q; q = q->next)
295   {
296     qglBindTexture (GL_TEXTURE_2D, q->texture_number);
297     SetTexParameters ();
298   }
299
300   // select the default texture
301   qglBindTexture( GL_TEXTURE_2D, 0 );
302
303   qglFinish();
304
305   if (g_pParentWnd->GetCamWnd()->Camera()->draw_mode != cd_texture)
306   {
307     g_pParentWnd->GetCamWnd()->Camera()->draw_mode = cd_texture;
308     Map_BuildBrushData();
309   }
310
311   Sys_UpdateWindows (W_ALL);
312 }
313
314 /*!
315 gamma correction stuff
316 took out of QERApp_LoadTextureRGBA for clarity
317 */
318 byte g_gammatable[256];
319 void ResampleGamma(float fGamma)
320 {
321   int i,inf;
322   if (fGamma == 1.0)
323   {
324     for (i = 0; i < 256; i++)
325       g_gammatable[i] = i;
326   } else
327   {
328     for (i = 0; i < 256; i++)
329     {
330       inf = (int)( 255.0f * pow( (i + 0.5f) / 255.5f , fGamma ) + 0.5f );
331       if (inf < 0)
332         inf = 0;
333       if (inf > 255)
334         inf = 255;
335       g_gammatable[i] = inf;
336     }
337   }
338 }
339
340 /*!
341 this function does the actual processing of raw RGBA data into a GL texture
342 it will also generate the mipmaps
343 it looks like pPixels nWidth nHeight are the only relevant parameters
344 */
345 qtexture_t *QERApp_LoadTextureRGBA(unsigned char* pPixels, int nWidth, int nHeight)
346 {
347   static float fGamma = -1;
348   float total[3];
349   byte  *outpixels = NULL;
350   int   i, j, resampled, width2, height2, width3, height3;
351   int   max_tex_size = 0, mip = 0;
352   int   nCount = nWidth * nHeight;
353
354   if (fGamma != g_qeglobals.d_savedinfo.fGamma)
355   {
356     fGamma = g_qeglobals.d_savedinfo.fGamma;
357     ResampleGamma(fGamma);
358   }
359
360   qglGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex_size);
361   if (!max_tex_size)
362     max_tex_size = 1024;
363
364   qtexture_t *q = (qtexture_t*)g_malloc(sizeof(*q));
365   q->width = nWidth;
366   q->height = nHeight;
367
368   total[0] = total[1] = total[2] = 0.0f;
369
370   // resample texture gamma according to user settings
371   for (i = 0; i < (nCount * 4); i += 4)
372   {
373     for (j = 0; j < 3; j++)
374     {
375       total[j] += (pPixels + i)[j];
376       byte b = (pPixels + i)[j];
377       (pPixels + i)[j] = g_gammatable[b];
378     }
379   }
380
381   q->color[0] = total[0] / (nCount * 255);
382   q->color[1] = total[1] / (nCount * 255);
383   q->color[2] = total[2] / (nCount * 255);
384
385   qglGenTextures (1, &q->texture_number);
386
387   qglBindTexture( GL_TEXTURE_2D, q->texture_number );
388
389   SetTexParameters();
390
391   width2 = 1; while (width2 < nWidth) width2 <<= 1;
392   height2 = 1; while (height2 < nHeight) height2 <<= 1;
393
394   width3 = width2;
395   height3 = height2;
396   while (width3 > max_tex_size) width3 >>= 1;
397   while (height3 > max_tex_size) height3 >>= 1;
398   if (width3 < 1) width3 = 1;
399   if (height3 < 1) height3 = 1;
400
401   if (!(width2 == nWidth && height2 == nHeight)) {
402     resampled = 1;
403     outpixels = (byte *)malloc(width2 * height2 * 4);
404     R_ResampleTexture(pPixels, nWidth, nHeight, outpixels, width2, height2, 4);
405   } else {
406     resampled = 0;
407     outpixels = pPixels;
408   }
409
410   while (width2 > width3 || height2 > height3)
411   {
412     GL_MipReduce(outpixels, outpixels, width2, height2, width3, height3);
413
414     if (width2 > width3)
415       width2 >>= 1;
416     if (height2 > height3)
417       height2 >>= 1;
418   }
419
420   qglTexImage2D(GL_TEXTURE_2D, mip++, g_qeglobals.texture_components, width2, height2, 0, GL_RGBA, GL_UNSIGNED_BYTE, outpixels);
421   while (width2 > 1 || height2 > 1)
422   {
423     GL_MipReduce(outpixels, outpixels, width2, height2, 1, 1);
424
425     if (width2 > 1)
426       width2 >>= 1;
427     if (height2 > 1)
428       height2 >>= 1;
429
430     qglTexImage2D(GL_TEXTURE_2D, mip++, g_qeglobals.texture_components, width2, height2, 0, GL_RGBA, GL_UNSIGNED_BYTE, outpixels);
431   }
432
433   qglBindTexture(GL_TEXTURE_2D, 0);
434   if (resampled)
435     free(outpixels);
436
437   return q;
438 }
439
440 /*
441 ==================
442 DumpUnreferencedShaders
443 usefull function: dumps the list of .shader files that are not referenced to the console
444 ==================
445 */
446 void DumpUnreferencedShaders()
447 {
448   GSList *lst, *sh, *files;
449   bool bFound = false;
450
451   files = vfsGetFileList ("scripts", "shader");
452   for (lst = files; lst; lst = lst->next)
453   {
454     bool listed = false;
455
456     for (sh = l_shaderfiles; sh != NULL; sh = g_slist_next (sh))
457       if (!strcmp ((char*)sh->data, (char*)lst->data))
458       {
459         listed = true;
460         break;
461       }
462
463     if (!listed)
464     {
465       if (!bFound)
466       {
467         bFound = true;
468         Sys_FPrintf (SYS_WRN, "Following shader files are not referenced in shaderlist.txt:\n");
469       }
470       Sys_FPrintf (SYS_WRN, "%s\n", (char*)lst->data);
471     }
472   }
473
474   vfsClearFileDirList (&files);
475 }
476
477 /*
478 ==================
479 BuildShaderList
480 build a CStringList of shader names
481 ==================
482 */
483 void BuildShaderList()
484 {
485   int count;
486   char filename[1024];
487   char *pBuff;
488   char dirstring[NAME_MAX];
489   int nLen;
490   if (l_shaderfiles!=NULL)
491   {
492     g_slist_free(l_shaderfiles);
493     l_shaderfiles = NULL;
494   }
495
496   if (g_pGameDescription->mGameFile != "hl.game")
497   {
498     strcpy(filename, g_pGameDescription->mShaderlist.GetBuffer());
499     count = vfsGetFileCount(filename, 0 );
500     if (count==0)
501     {
502       Sys_FPrintf(SYS_ERR, "Couldn't find '%s'\n", g_pGameDescription->mShaderlist.GetBuffer());
503       return;
504     }
505     // NOTE TTimo we use vfsGetFullPath solely to get the full path of the shader list we are gonna load
506     //   but we actually send the relative path to vfsLoadFile
507     //   so let's hope there is no disparity between the two functions
508     if (!vfsGetFullPath(filename, 0, 0))
509     {
510       Sys_FPrintf(SYS_ERR, "Couldn't find full path for '%s'\n", g_pGameDescription->mShaderlist.GetBuffer());
511       Sys_FPrintf(SYS_ERR, "did you hit bug http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=130 ?\n");
512       return;
513     }
514     Sys_Printf("Parsing shader files from %s\n", vfsGetFullPath(filename, 0, 0));
515     nLen = vfsLoadFile (filename, reinterpret_cast<void**>(&pBuff), 0);
516     if (nLen > 0)
517     {
518       StartTokenParsing(pBuff);
519       nLen = 0;
520       while (GetToken(true))
521       {
522         GSList *tmp;
523         bool found = false;
524         
525         // each token should be a shader filename
526         sprintf(dirstring, "%s.shader", token);
527         
528         for (tmp = l_shaderfiles; tmp != NULL; tmp = tmp->next)
529         {
530           if (!strcmp (dirstring, (char*)tmp->data))
531           {
532             found = true;
533             Sys_FPrintf(SYS_WRN, "duplicate entry \"%s\" in shaderlist.txt\n", (char*)tmp->data);
534             break;
535           }
536         }
537         
538         if (!found)
539         {
540           l_shaderfiles = g_slist_append (l_shaderfiles, strdup (dirstring));
541           nLen++;
542         }
543       }
544       g_free(pBuff);
545     }
546   }
547 }
548
549 /*
550 ==================
551 FillTextureMenu
552
553 ==================
554 */
555 void ClearGSList (GSList* lst)
556 {
557   GSList *p = lst;
558   while (p)
559   {
560     free (p->data);
561     p = g_slist_remove (p, p->data);
562   }
563 }
564
565 void FillTextureMenu (GSList** pArray)
566 {
567   GtkWidget *menu, *sep, *item; // point to the Textures GtkMenu and to the last separator
568   GList *lst;
569   GSList *texdirs = NULL;
570   GSList *texdirs_tmp = NULL;
571   GSList *p;
572   char dirRoot[NAME_MAX];
573   // this is an index used to count the number of texture items (for splitting/avoiding to get out of window)
574   // we start with a != 0 value to compensate for the initial number of items in the texture menu
575   int nMenuCount = 12;
576
577   // delete everything
578   menu = GTK_WIDGET (g_object_get_data (G_OBJECT (g_qeglobals_gui.d_main_window), "menu_textures"));
579   sep = GTK_WIDGET (g_object_get_data (G_OBJECT (g_qeglobals_gui.d_main_window), "menu_textures_separator"));
580   lst = g_list_find (gtk_container_children (GTK_CONTAINER (menu)), sep);
581   while (lst->next)
582   {
583     // these delete functions are recursive, it's gonna free all submenus
584     gtk_widget_destroy (GTK_WIDGET (lst->next->data));
585     // lst is no longer relevant, need to get it again
586     lst = g_list_find (gtk_container_children (GTK_CONTAINER (menu)), sep);
587   }
588
589   texture_nummenus = 0;
590
591   // add everything
592   if (!g_qeglobals.d_project_entity)
593     return;
594
595   // scan texture dirs and pak files only if not restricting to shaderlist
596   if (!g_PrefsDlg.m_bTexturesShaderlistOnly)
597   {
598     texdirs_tmp = vfsGetDirList ("textures/");
599     for (p=texdirs_tmp; p; p=g_slist_next(p))
600     {
601       // Hydra: erm, this didn't used to do anything except leak memory...
602       // For Halflife support this is required to work however.
603       // g_slist_append(texdirs, p->data);
604       texdirs = g_slist_append(texdirs, strdup((char *)p->data));
605     }
606     vfsClearFileDirList (&texdirs_tmp);
607   }
608
609   // scan the shaders in shaderlist.txt
610   BuildShaderList ();
611   PreloadShaders ();
612   DumpUnreferencedShaders ();
613   while (l_shaderfiles != NULL)
614   {
615     char shaderfile[PATH_MAX];
616     gboolean found = FALSE;
617
618     ExtractFileName ((char*)l_shaderfiles->data, shaderfile);
619     StripExtension (shaderfile);
620     g_strdown (shaderfile);
621
622     for (GSList *tmp = texdirs; tmp; tmp = g_slist_next (tmp))
623       if (!strcasecmp ((char*)tmp->data, shaderfile))
624       {
625               found = TRUE;
626               break;
627       }
628
629     if (!found)
630       texdirs = g_slist_prepend (texdirs, strdup (shaderfile));
631
632     free (l_shaderfiles->data);
633     l_shaderfiles = g_slist_remove (l_shaderfiles, l_shaderfiles->data);
634   }
635
636   // sort the list
637   texdirs = g_slist_sort (texdirs, (GCompareFunc)strcmp);
638
639   GSList *temp = texdirs;
640   while (temp)
641   {
642     char* ptr = strchr ((char*)temp->data, '_');
643
644     // do we shrink the menus?
645     if (ptr != NULL)
646     {
647       // extract the root
648       strcpy (dirRoot, (char*)temp->data);
649       dirRoot[ptr - (char*)temp->data + 1] = 0;
650
651       // we shrink only if we have at least two things to shrink :-)
652       if (temp->next && (strstr ((char*)temp->next->data, dirRoot) == (char*)temp->next->data))
653       {
654               GtkWidget *pSubMenu = gtk_menu_new ();
655         GtkWidget *pSubMenuRef = pSubMenu;
656               // keep going...
657               do
658               {
659                 item = gtk_menu_item_new_with_label ((char*)temp->data);
660                 gtk_widget_show (item);
661           CheckMenuSplitting (pSubMenu);
662                 gtk_container_add (GTK_CONTAINER (pSubMenu), item);
663                 gtk_signal_connect (GTK_OBJECT (item), "activate", GTK_SIGNAL_FUNC (HandleCommand),
664                                     GINT_TO_POINTER (CMD_TEXTUREWAD+texture_nummenus));
665
666                 strcpy (texture_menunames[texture_nummenus], (char*)temp->data);
667                 strcat (texture_menunames[texture_nummenus], "/");
668                 if (pArray)
669                   *pArray = g_slist_append (*pArray, strdup ((char*)temp->data));
670                 if (++texture_nummenus == MAX_TEXTUREDIRS)
671                 {
672                   Sys_Printf("WARNING: max texture directories count has been reached!\n");
673                   // push submenu and get out
674                   item = gtk_menu_item_new_with_label (dirRoot);
675                   gtk_widget_show (item);
676                   gtk_container_add (GTK_CONTAINER (menu), item);
677                   gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), pSubMenu);
678                   ClearGSList (texdirs);
679                   return;
680                 }
681                 temp = temp->next;
682               }
683         while (temp && (strstr((char*)temp->data, dirRoot)==temp->data));
684
685         ptr = strchr (dirRoot, '_');
686         *ptr = 0;
687               item = gtk_menu_item_new_with_label (dirRoot);
688               gtk_widget_show (item);
689               CheckMenuSplitting (menu);
690               gtk_container_add (GTK_CONTAINER (menu), item);
691         gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), pSubMenuRef);
692               continue;
693       }
694     }
695
696     item = gtk_menu_item_new_with_label ((char*)temp->data);
697     gtk_widget_show (item);
698     CheckMenuSplitting (menu);
699     gtk_container_add (GTK_CONTAINER (menu), item);
700     gtk_signal_connect (GTK_OBJECT (item), "activate", GTK_SIGNAL_FUNC (HandleCommand),
701                         GINT_TO_POINTER (CMD_TEXTUREWAD+texture_nummenus));
702
703     strcpy (texture_menunames[texture_nummenus], (char*)temp->data);
704     strcat (texture_menunames[texture_nummenus], "/");
705     if (pArray)
706       *pArray = g_slist_append (*pArray, strdup ((char*)temp->data));
707     if (++texture_nummenus == MAX_TEXTUREDIRS)
708     {
709       Sys_Printf("WARNING: max texture directories count has been reached!\n");
710       ClearGSList (texdirs);
711       return;
712     }
713
714     temp = temp->next;
715   }
716   ClearGSList (texdirs);
717 }
718
719 /*
720 ==============
721 Texture_ShowDirectory
722 relies on texture_directory global for the directory to use
723 called by
724   void Texture_ShowDirectory (int menunum, bool bLinked)
725   void  Texture_ShowDirectory (char* pPath, bool bLinked)
726 1) Load the shaders for the given directory
727 2) Scan the remaining texture, load them and assign them a default shader (the "noshader" shader)
728 NOTE: when writing a texture plugin, or some texture extensions, this function may need to be overriden, and made
729   available through the IShaders interface
730 NOTE: for texture window layout:
731   all shaders are stored with alphabetical order after load
732   previously loaded and displayed stuff is hidden, only in-use and newly loaded is shown
733   ( the GL textures are not flushed though)
734 ==============
735 */
736 void Texture_ShowDirectory ()
737 {
738   char  name[1024];
739   char  dirstring[1024];
740   CString strTemp;
741   int shaders_count = 0;
742   int textures_count = 0;
743   GSList *files = NULL, *temp;
744
745   g_bScreenUpdates = false;
746
747   // refresh the in-use textures: that will clear the IsDisplayed flag on unused stuff
748   // and leave it on in-use so they'll still be displayed
749   Texture_ShowInuse();
750   // and textures loaded in the following lines will be displayed as well...
751   // NOTE: shaders that are not in use but have been loaded previously are still in memory. But they don't get displayed.
752
753   g_qeglobals.d_texturewin.originy = 0;
754   // load texture_directory.shader
755   // NOTE: because of above call to Texture_ClearInuse, g_ActiveShaders will have the newly loaded shaders only
756   // we'll use that later to check if textures have a shader associated or not
757   // NOTE: all shaders loaded through QERApp_LoadShadersFromDir will get their InUse flag to True, we'll need a call to Texture_ShowInUse for later cleanup/adjustment
758   // NOTE: QERApp_LoadShadersFromDir has two criterions for loading a shader:
759   //   the shaderfile is texture_directory (like "museum" will load everything in museum.shader)
760   //   the shader name contains texture_directory (like "base_floor" will load museum.shader::base_floor/concfloor_rain)
761   shaders_count = QERApp_LoadShadersFromDir(texture_directory);
762   // load remaining texture files
763   // if a texture is already in use to represent a shader, ignore it
764
765   // need this function "GSList *lst SynapseServer::GetMinorList(char *major_name);"
766   
767   sprintf (dirstring, "textures/%s", texture_directory);
768   g_ImageManager.BeginExtensionsScan();
769   const char* ext;
770   while(ext=g_ImageManager.GetNextExtension())
771   {
772     files = g_slist_concat(files, vfsGetFileList (dirstring, ext));
773   }
774
775   for (temp = files; temp; temp = temp->next)
776   {
777     sprintf(name, "%s%s", texture_directory, (char*)temp->data);
778
779       StripExtension (name);
780       strTemp = name;
781       strTemp.MakeLower();
782
783     if (strTemp.Find(".specular") >= 0 ||
784          strTemp.Find(".glow") >= 0 ||
785          strTemp.Find(".bump") >= 0 ||
786          strTemp.Find(".diffuse") >= 0 ||
787          strTemp.Find(".blend") >= 0 ||
788                strTemp.Find(".alpha") >= 0)
789          continue;
790
791     // avoid ever loading a texture name with spaces
792     if (strTemp.Find(" ") >= 0)
793     {
794       Sys_FPrintf(SYS_WRN, "WARNING: Skipping texture name with spaces [%s]\n", strTemp.GetBuffer());
795       continue;
796     }
797
798     // build a texture name that fits the conventions for qtexture_t::name
799     char stdName[1024];
800     sprintf( stdName, "textures/%s", name );
801     // check if this texture doesn't have a shader
802     if (!QERApp_ActiveShader_ForTextureName( stdName ))
803     {
804       QERApp_CreateShader_ForTextureName (stdName);
805       textures_count++;
806     }
807   }
808
809   Sys_Printf("Loaded %d shaders and created default shader for %d orphan textures.\n",
810              shaders_count, textures_count );
811
812   vfsClearFileDirList (&files);
813
814   // sort for displaying
815   QERApp_SortActiveShaders();
816
817   sprintf (name, "Textures: %s", texture_directory);
818   gtk_window_set_title (GTK_WINDOW (g_qeglobals_gui.d_entity), name);
819
820   // select the first texture in the list
821   if (!g_qeglobals.d_texturewin.texdef.GetName()[0])
822     SelectTexture (16, g_qeglobals.d_texturewin.height -16, false);
823
824   g_bScreenUpdates = true;
825
826   Sys_UpdateWindows (W_TEXTURE);
827 }
828
829 /*
830 ==============
831 Texture_ShowDirectory
832 1) Load the shaders for the given directory
833 2) Scan the remaining texture, load them and assign them a default shader (the "noshader" shader)
834 NOTE: when writing a texture plugin, or some texture extensions, this function may need to be overriden, and made
835   available through the IShaders interface
836 ==============
837 */
838 void Texture_ShowDirectory (int menunum)
839 {
840   strcpy (texture_directory, texture_menunames[menunum-CMD_TEXTUREWAD]);
841   Texture_ShowDirectory();
842 }
843
844 // scroll origin so the current texture is completely on screen
845 // if current texture is not displayed, nothing is changed
846 void Texture_ResetPosition()
847 {
848   qtexture_t  *q;
849   int  x,y;
850
851   //this shouldn't ever happen, we startup with notex
852   if (!g_qeglobals.d_texturewin.texdef.GetName()[0]) {
853     return;
854   }
855
856   // otherwise position with current texture shown
857   // this used to be in Texture_SetTexture
858   Texture_StartPos ();
859   while (1)
860   {
861     // NOTE: return value is == pCurrentShader and pCurrentShader->getTexture == current_texture
862     Texture_NextPos (&x, &y);
863     q = current_texture;
864     // if the current texture never found (because // 'show shaders' is off,
865     // for example), do nothing
866     if (!q) 
867       break;
868     
869     int nHeight = (int)(q->height * ((float)g_PrefsDlg.m_nTextureScale / 100));
870     // we have found when texdef->name and the shader name match
871     // NOTE: as everywhere else for our comparisons, we are not case sensitive
872     if (!strcmpi( g_qeglobals.d_texturewin.texdef.GetName(), pCurrentShader->getName() ))
873     {
874       // take care of calls before initialized
875       if ( !g_qeglobals.d_texturewin.height) {
876         g_qeglobals.d_texturewin.originy = 0;
877         break;
878       }
879       // if the bottom of our selected texture will fit with origin 0, use that
880       // to prevent scrolling uglyness (stuff scrolled off screen when 
881       // everything would fit)
882       if ( -(y -nHeight-2*FONT_HEIGHT) <  g_qeglobals.d_texturewin.height) {
883         g_qeglobals.d_texturewin.originy = 0;
884         break;
885       }
886       // if current is off the top of the window, move it to the top
887       if (y > g_qeglobals.d_texturewin.originy)
888       {
889         g_qeglobals.d_texturewin.originy = y;
890         break;
891       }
892
893       // if current is off the bottom, put it on the bottom
894       if (y-nHeight-2*FONT_HEIGHT < g_qeglobals.d_texturewin.originy-g_qeglobals.d_texturewin.height)
895       {
896         g_qeglobals.d_texturewin.originy = y-nHeight-2*FONT_HEIGHT+g_qeglobals.d_texturewin.height;
897         break;
898       }
899       // if we made it here, it should already be in view
900       break;
901     }
902   }
903   Sys_UpdateWindows (W_TEXTURE);
904 }
905
906 /*
907 ==============
908 Texture_ShowAll
909 will set the IsDisplayed flag on all the active shaders, so we see everything that's currently in memory
910 ==============
911 */
912 void Texture_ShowAll()
913 {
914   char name[1024];
915
916 #ifdef _DEBUG
917   if (g_bShowAllShaders)
918     Sys_Printf("WARNING: already showing all shaders\n");
919 #endif
920   QERApp_ActiveShaders_SetDisplayed(true);
921   g_bShowAllShaders = true;
922   // put some information in the texture window title?
923   sprintf (name, "Textures: in use");
924   gtk_window_set_title (GTK_WINDOW (g_qeglobals_gui.d_entity), name);
925   Sys_UpdateWindows (W_TEXTURE);
926 }
927
928 /*
929 ==============
930 Texture_ShowInuse
931 clear all IsDisplayed flags
932 scan the map, set IsInUse (will set IsDisplayed on the way)
933 NOTE: don't sort the textures, don't update the windows (it's used in several contexts, not always necessary to do either)
934 ==============
935 */
936 void WINAPI Texture_ShowInuse (void)
937 {
938   face_t  *f;
939   brush_t *b;
940   char  name[1024];
941
942   g_qeglobals.d_texturewin.originy = 0;
943
944   // purge
945   QERApp_ActiveShaders_SetDisplayed(false);
946   // scan and only display in-use stuff
947   Sys_Status("Selecting active textures", 0);
948
949   for (b=active_brushes.next ; b != NULL && b != &active_brushes ; b=b->next)
950   {
951     if (b->patchBrush)
952     {
953       b->pPatch->pShader->SetInUse(true);
954     } else
955     {
956       for (f=b->brush_faces ; f ; f=f->next)
957       {
958         f->pShader->SetInUse(true);
959       }
960     }
961   }
962   for (b=selected_brushes.next ; b != NULL && b != &selected_brushes ; b=b->next)
963   {
964     if (b->patchBrush)
965     {
966       b->pPatch->pShader->SetInUse(true);
967     } else
968     {
969       for (f=b->brush_faces ; f ; f=f->next)
970       {
971         f->pShader->SetInUse(true);
972       }
973     }
974   }
975
976   // we are no longer showing everything
977   g_bShowAllShaders = false;
978   // put some information in the texture window title?
979   sprintf (name, "Textures: in use");
980   gtk_window_set_title (GTK_WINDOW (g_qeglobals_gui.d_entity), name);
981
982
983   // select the first texture in the list
984   if (!g_qeglobals.d_texturewin.texdef.GetName()[0])
985   {
986     SelectTexture (16, g_qeglobals.d_texturewin.height -16, false);
987   }
988 }
989
990 void Texture_ShowStartupShaders()
991 {
992   if (g_PrefsDlg.m_nShader == PrefsDlg::SHADER_COMMON)
993   {
994     // RIANT
995     // HACK FOR JK2 SUPPORT
996     if (g_pGameDescription->mGameFile == "jk2.game" || g_pGameDescription->mGameFile == "ja.game")
997     {
998       strcpy (texture_directory, "system/");
999     }
1000     // RIANT
1001     // HACK FOR SOF2 SUPPORT
1002     else if (g_pGameDescription->mGameFile == "sof2.game")
1003     {
1004       strcpy (texture_directory, "tools/");
1005     }
1006     else strcpy (texture_directory, "common/");
1007     Texture_ShowDirectory ();
1008   }
1009
1010   if (g_PrefsDlg.m_nShader == PrefsDlg::SHADER_ALL) {
1011     int    count;
1012     char   filename[1024];
1013     char   *pBuff;
1014     char   dirstring[NAME_MAX];
1015     int    nLen;
1016     GSList *shaderfiles = NULL;
1017
1018     strcpy(filename, g_pGameDescription->mShaderlist.GetBuffer());
1019     count = vfsGetFileCount(filename, 0);
1020     if (count == 0)
1021     {
1022       Sys_FPrintf(SYS_ERR, "Couldn't find '%s'\n", g_pGameDescription->mShaderlist.GetBuffer());
1023       return;
1024     }
1025
1026     if (!vfsGetFullPath(filename, 0, 0))
1027     {
1028       Sys_FPrintf(SYS_ERR, "Couldn't find full path for '%s'\n", g_pGameDescription->mShaderlist.GetBuffer());
1029       Sys_FPrintf(SYS_ERR, "did you hit bug http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=130 ?\n");
1030       return;
1031     }
1032
1033     Sys_Printf("Parsing shader files from %s\n", vfsGetFullPath(filename, 0, 0));
1034     nLen = vfsLoadFile (filename, reinterpret_cast<void**>(&pBuff), 0);
1035     if (nLen > 0)
1036     {
1037       StartTokenParsing(pBuff);
1038       nLen = 0;
1039       while (GetToken(true))
1040       {
1041         GSList *tmp;
1042         bool found = false;
1043
1044         // each token should be a shader filename
1045         sprintf(dirstring, "%s.shader", token);
1046
1047         for (tmp = shaderfiles; tmp != NULL; tmp = tmp->next)
1048         {
1049           if (!strcmp (dirstring, (char*)tmp->data))
1050           {
1051             found = true;
1052             Sys_FPrintf(SYS_WRN, "duplicate entry \"%s\" in shaderlist.txt\n", (char*)tmp->data);
1053             break;
1054           }
1055         }
1056
1057         if (!found)
1058         {
1059           shaderfiles = g_slist_append (l_shaderfiles, strdup (dirstring));
1060           strcpy (texture_directory, dirstring);
1061           Texture_ShowDirectory ();
1062           nLen++;
1063         }
1064       }
1065       g_free(pBuff);
1066     }
1067   }
1068 }
1069
1070 /*
1071 ============================================================================
1072
1073 TEXTURE LAYOUT
1074
1075 TTimo: now based on a rundown through all the shaders
1076 nActiveShadersCount: number of shader that have a qtexture_t and may be displayed in the tex window
1077 nCurrentShader: index of active shader that has the current_texture
1078 pCurrentShader: IShader* for current shader
1079 NOTE: we expect the Active shaders count doesn't change during a Texture_StartPos .. Texture_NextPos cycle
1080   otherwise we may need to rely on a list instead of an array storage
1081 ============================================================================
1082 */
1083
1084 void Texture_StartPos (void)
1085 {
1086   //++timo TODO: check use of current_texture and current_row?
1087   current_x = 8;
1088   current_y = -8;
1089   current_row = 0;
1090   nActiveShadersCount = QERApp_GetActiveShaderCount();
1091   nCurrentShader = -1;
1092   current_texture = NULL;
1093   pCurrentShader = NULL;
1094 }
1095
1096 // if texture_showinuse jump over non in-use textures
1097 // it's not very clear what should be done here and what in Texture_Draw .. maybe merging the two would do good
1098 IShader* Texture_NextPos (int *x, int *y)
1099 {
1100   qtexture_t* q;
1101   while (1)
1102   {
1103     if (nCurrentShader >= nActiveShadersCount - 1)
1104     {
1105       // no more shaders
1106       current_texture = NULL;
1107       pCurrentShader = NULL;
1108       return NULL;
1109     }
1110     nCurrentShader++;
1111     pCurrentShader = QERApp_ActiveShader_ForIndex(nCurrentShader);
1112     if (pCurrentShader == NULL)
1113     {
1114       Sys_Printf("ERROR: unexpected pCurrentShader == NULL in Texture_NextPos\n");
1115       return NULL;
1116     }
1117     current_texture = pCurrentShader->getTexture();
1118     q = current_texture;
1119
1120     if (!q)
1121     {
1122       Sys_Printf("WARNING: found an IShader without qtexture_t in Texture_NextPos\n");
1123       return NULL;
1124     }
1125
1126     /*
1127     Never show anything other than "textures/" path,
1128     This is for q1/q2/q3 .map format, which expects "textures/" path on everything we apply
1129     */
1130     if(strncmp(pCurrentShader->getName(), "textures/", 9) != 0)
1131       continue;
1132
1133     // don't show shaders?
1134     if (!(g_PrefsDlg.m_bShowShaders || pCurrentShader->IsDefault()))
1135       continue;
1136
1137     if (g_PrefsDlg.m_bTextureWindow)
1138     {
1139       // some basic filtering
1140       if (!g_pParentWnd->GetTexWnd()->CheckFilter( pCurrentShader->getName() ))
1141         continue;
1142     }
1143
1144     //++timo FIXME: texture_showinuse is useless? with the menu and reload we just refresh the IsDisplayed flag
1145     // but the IsInUse is only relevant to draw the green outline
1146     if (pCurrentShader->IsDisplayed())
1147       break;
1148
1149     continue;
1150   }
1151
1152   int nWidth = (int)(q->width * ((float)g_PrefsDlg.m_nTextureScale / 100));
1153   int nHeight = (int)(q->height * ((float)g_PrefsDlg.m_nTextureScale / 100));
1154   if (current_x + nWidth > g_qeglobals.d_texturewin.width-8 && current_row)
1155   { // go to the next row unless the texture is the first on the row
1156     current_x = 8;
1157     current_y -= current_row + FONT_HEIGHT + 4;
1158     current_row = 0;
1159   }
1160
1161   *x = current_x;
1162   *y = current_y;
1163
1164   // Is our texture larger than the row? If so, grow the
1165   // row height to match it
1166
1167   if (current_row < nHeight)
1168     current_row = nHeight;
1169
1170   // never go less than 64, or the names get all crunched up
1171   current_x += nWidth < 64 ? 64 : nWidth;
1172   current_x += 8;
1173
1174   return pCurrentShader;
1175 }
1176
1177 /*
1178 ============================================================================
1179
1180   MOUSE ACTIONS
1181
1182 ============================================================================
1183 */
1184
1185 static  int textures_cursorx, textures_cursory;
1186
1187 /*
1188 ============
1189 Texture_SetTexture
1190
1191 brushprimit_texdef must be understood as a qtexture_t with width=2 height=2 ( the default one )
1192 ============
1193 */
1194
1195 //++timo NOTE: this is a mix of Shader module stuff and texture explorer
1196 // it might need to be split in parts or moved out .. dunno
1197 void WINAPI Texture_SetTexture (texdef_t *texdef, brushprimit_texdef_t *brushprimit_texdef, bool bFitScale, IPluginTexdef *pTexdef, bool bSetSelection )
1198 {
1199   if (texdef->GetName()[0] == '(')
1200   {
1201     Sys_Status("Can't select an entity texture", 0);
1202     return;
1203   }
1204   g_qeglobals.d_texturewin.texdef = *texdef;
1205   g_qeglobals.d_texturewin.texdef.flags &= ~SURF_KEEP;
1206   g_qeglobals.d_texturewin.texdef.contents &= ~CONTENTS_KEEP;
1207   // store the shader pointer
1208   // NOTE: maybe passing the shader pointer would help?
1209   g_qeglobals.d_texturewin.pShader->DecRef();
1210   g_qeglobals.d_texturewin.pShader = QERApp_Shader_ForName(texdef->GetName());
1211   g_qeglobals.d_texturewin.pShader->IncRef();
1212   // set this shader as in use
1213   g_qeglobals.d_texturewin.pShader->SetInUse( true );
1214   // store the texture coordinates for new brush primitive mode
1215   // be sure that all the callers are using the default 2x2 texture
1216   if (g_qeglobals.m_bBrushPrimitMode)
1217   {
1218     g_qeglobals.d_texturewin.brushprimit_texdef = *brushprimit_texdef;
1219   }
1220
1221   g_dlgFind.updateTextures(texdef->GetName());
1222   if (!g_dlgFind.isOpen() && bSetSelection)
1223   {
1224     Select_SetTexture(texdef,brushprimit_texdef,bFitScale);
1225   }
1226
1227   //plugins: send a message telling that the selected texture may have changed
1228   DispatchRadiantMsg( RADIANT_TEXTURE );
1229
1230   // scroll origin so the texture is completely on screen
1231   // takes texdef from g_qeglobals.d_texturewin.texdef, set above
1232   Texture_ResetPosition();
1233 }
1234
1235 void ViewShader(const char *pFile, const char *pName)
1236 {
1237   //  ask the vfs to build the full path to the file
1238   // (i.e. the first one found)
1239   char *fullName = vfsGetFullPath(pFile,0,0);
1240   if (fullName == NULL)
1241   {
1242     Sys_FPrintf (SYS_ERR, "Couldn't get a full path to the shader file: %s\n", pFile);
1243     return;
1244   }
1245
1246   char* pBuff = NULL;
1247   int nSize = vfsLoadFullPathFile(fullName, reinterpret_cast<void**>(&pBuff));
1248   if (nSize <= 0)
1249   {
1250     Sys_FPrintf (SYS_ERR, "Failed to load shader file %s\n", fullName);
1251     return;
1252   }
1253   // look for the shader declaration
1254   int nStart;
1255   CString strFind = pName;
1256   CString strLook = pBuff;
1257   strLook.MakeLower();
1258   strFind.MakeLower();
1259   // offset used when jumping over commented out definitions
1260   int nOffset = 0;
1261   while (true)
1262   {
1263     nStart = strLook.Find(strFind, nOffset);
1264     if (nStart == -1)
1265       break;
1266     // we have found something, maybe it's a commented out shader name?
1267     char *strCheck = new char[strLook.GetLength()+1];
1268     strcpy( strCheck, strLook.GetBuffer() );
1269     strCheck[nStart] = 0;
1270     char *pCheck = strrchr( strCheck, '\n' );
1271     // if there's a commentary sign in-between we'll continue
1272     if (pCheck && strstr( pCheck, "//" ))
1273     {
1274       delete[] strCheck;
1275       nOffset = nStart + 1;
1276       continue;
1277     }
1278     delete[] strCheck;
1279     nOffset = nStart;
1280     break;
1281   }
1282   // now close the file
1283   g_free(pBuff);
1284
1285   DoTextEditor (fullName, nOffset);
1286 }
1287
1288 /*
1289 ==============
1290 SelectTexture
1291
1292   By mouse click
1293 ==============
1294 */
1295 void SelectTexture (int mx, int my, bool bShift, bool bFitScale)
1296 {
1297   int   x, y;
1298   qtexture_t  *q;
1299   texdef_t  tex;
1300   brushprimit_texdef_t brushprimit_tex;
1301
1302   my += g_qeglobals.d_texturewin.originy-g_qeglobals.d_texturewin.height;
1303
1304   Texture_StartPos ();
1305   while (1)
1306   {
1307     // NOTE: return value is == pCurrentShader and pCurrentShader->getTexture == current_texture
1308     Texture_NextPos (&x, &y);
1309     q = current_texture;
1310     if (!q)
1311       break;
1312     int nWidth = (int)(q->width * ((float)g_PrefsDlg.m_nTextureScale / 100));
1313     int nHeight = (int)(q->height * ((float)g_PrefsDlg.m_nTextureScale / 100));
1314     if (mx > x && mx - x < nWidth
1315       && my < y && y - my < nHeight + FONT_HEIGHT)
1316     {
1317       if (bShift)
1318       {
1319         if (pCurrentShader->IsDefault())
1320           Sys_Printf("ERROR: %s is not a shader, it's a texture.\n", pCurrentShader->getName() );
1321         else
1322           ViewShader( pCurrentShader->getShaderFileName(), pCurrentShader->getName() );
1323       }
1324       else
1325       {
1326         memset (&tex, 0, sizeof(tex));
1327         memset (&brushprimit_tex, 0, sizeof(brushprimit_tex));
1328         if (g_qeglobals.m_bBrushPrimitMode)
1329         {
1330           // brushprimit fitted to a 2x2 texture
1331           brushprimit_tex.coords[0][0] = 1.0f;
1332           brushprimit_tex.coords[1][1] = 1.0f;
1333         }
1334         else
1335         {
1336           tex.scale[0] = g_pGameDescription->mTextureDefaultScale;
1337           tex.scale[1] = g_pGameDescription->mTextureDefaultScale;
1338         }
1339         tex.flags = pCurrentShader->getFlags();
1340         // TTimo - shader code cleanup
1341         // texdef.name is the name of the shader, not the name of the actual texture file
1342         tex.SetName(pCurrentShader->getName());
1343         // NOTE WARNING: Texture_SetTexture uses Texture_NextPos stuff to move the window position on to the texture
1344         // if there's some kind of fuckup in Texture_SetTexture you may end up with different pCurrentShader or even pCurrentShader == NULL
1345         // so we just consider pCurrentShader and current_texture are not valid after this point
1346         IShader *pAuxShader = pCurrentShader;
1347         Texture_SetTexture ( &tex, &brushprimit_tex, bFitScale, NULL); // Nurail
1348         CString strTex;
1349         CString strName;
1350         // if shader, print shader name, otherwise texture name
1351         //++timo FIXME: maybe CShader needs some properties between color / default / actual shader
1352 #ifdef _DEBUG
1353         // this one is never supposed to be set as current one
1354         if (pAuxShader->IsColor())
1355           Sys_Printf("ERROR: unexpected pCurrentShader->IsColor() in SelectTexture\n");
1356 #endif
1357         // NOTE: IsColor is false, IsDefault the only remaining property
1358         if (pAuxShader->IsDefault())
1359         {
1360           strName = q->name;
1361           // remove the "textures/" if needed
1362           if (strName.Find("textures/")!=-1)
1363             strName = strName.Mid(9);
1364         }
1365         else
1366         {
1367           strName = pAuxShader->getName();
1368         }
1369         strTex.Format("%s W: %i H: %i", strName.GetBuffer(), q->width, q->height);
1370         g_pParentWnd->SetStatusText(3, strTex);
1371       }
1372       return;
1373     }
1374   }
1375   
1376   Sys_Status("Did not select a texture", 0);
1377 }
1378
1379 /*
1380 ==============
1381 Texture_MouseDown
1382 ==============
1383 */
1384 void Texture_MouseDown (int x, int y, int buttons)
1385 {
1386   Sys_GetCursorPos (&textures_cursorx, &textures_cursory);
1387
1388   // lbutton = select texture
1389   if (buttons == MK_LBUTTON || buttons == (MK_LBUTTON | MK_SHIFT) || buttons == (MK_LBUTTON | MK_CONTROL))
1390   {
1391     SelectTexture (x, g_qeglobals.d_texturewin.height - 1 - y, buttons & MK_SHIFT, buttons & MK_CONTROL);
1392     UpdateSurfaceDialog();
1393     UpdatePatchInspector();
1394   }
1395 }
1396
1397 /*
1398 ==============
1399 Texture_MouseMoved
1400 ==============
1401 */
1402
1403 void Texture_MouseMoved (int x, int y, int buttons)
1404 {
1405   int scale = 1;
1406
1407   if ( buttons & MK_SHIFT )
1408     scale = 4;
1409
1410   // rbutton = drag texture origin
1411   if (buttons & MK_RBUTTON)
1412   {
1413     Sys_GetCursorPos (&x, &y);
1414     if ( y != textures_cursory)
1415     {
1416       g_qeglobals.d_texturewin.originy += ( y-textures_cursory) * scale;
1417       if (g_qeglobals.d_texturewin.originy > 0)
1418         g_qeglobals.d_texturewin.originy = 0;
1419       Sys_SetCursorPos (textures_cursorx, textures_cursory);
1420
1421       // (g_PrefsDlg.m_bTextureScrollbar && g_qeglobals_gui.d_texture_scroll != NULL)
1422       // fixes broken texture scrolling when scrollbar is disabled
1423       GtkAdjustment *vadjustment = gtk_range_get_adjustment (GTK_RANGE (g_qeglobals_gui.d_texture_scroll));
1424       gtk_adjustment_set_value (vadjustment, abs(g_qeglobals.d_texturewin.originy));
1425       //
1426     }
1427     return;
1428   }
1429 }
1430
1431 /*
1432 ============================================================================
1433
1434 DRAWING
1435
1436 ============================================================================
1437 */
1438
1439 int imax(int iFloor, int i) { if (i>iFloor) return iFloor;return i;}
1440
1441 /*
1442 ============
1443 Texture_Draw
1444 TTimo: relying on the shaders list to display the textures
1445 we must query all qtexture_t* to manage and display through the IShaders interface
1446 this allows a plugin to completely override the texture system
1447 ============
1448 */
1449 void Texture_Draw (int width, int height)
1450 {
1451   int x, y, last_y = 0, last_height = 0, nWidth, nHeight;
1452   qtexture_t *q;
1453   char *name;
1454
1455   qglClearColor (g_qeglobals.d_savedinfo.colors[COLOR_TEXTUREBACK][0],
1456                  g_qeglobals.d_savedinfo.colors[COLOR_TEXTUREBACK][1],
1457                  g_qeglobals.d_savedinfo.colors[COLOR_TEXTUREBACK][2], 0);
1458   qglViewport (0,0,width,height);
1459   qglMatrixMode(GL_PROJECTION);
1460   qglLoadIdentity ();
1461
1462   qglClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1463   qglDisable (GL_DEPTH_TEST);
1464   qglDisable(GL_BLEND);
1465   qglOrtho (0, width, g_qeglobals.d_texturewin.originy-height, g_qeglobals.d_texturewin.originy, -100, 100);
1466   qglEnable (GL_TEXTURE_2D);
1467
1468   qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
1469   g_qeglobals.d_texturewin.width = width;
1470   g_qeglobals.d_texturewin.height = height;
1471
1472   Texture_StartPos();
1473   for (;;)
1474   {
1475     // NOTE: return value is == pCurrentShader and pCurrentShader->getTexture == current_texture
1476     Texture_NextPos (&x, &y);
1477     q = current_texture;
1478     if (!q)
1479       break;
1480
1481     nWidth = (int)(q->width * ((float)g_PrefsDlg.m_nTextureScale / 100));
1482     nHeight = (int)(q->height * ((float)g_PrefsDlg.m_nTextureScale / 100));
1483
1484     if (y != last_y)
1485     {
1486       last_y = y;
1487       last_height = 0;
1488     }
1489     last_height = MAX (nHeight, last_height);
1490
1491     // Is this texture visible?
1492     if ((y-nHeight-FONT_HEIGHT < g_qeglobals.d_texturewin.originy)
1493         && (y > g_qeglobals.d_texturewin.originy - height))
1494     {
1495       // borders rules:
1496       // if it's the current texture, draw a thick red line, else:
1497       // shaders have a white border, simple textures don't
1498       // if !texture_showinuse: (some textures displayed may not be in use)
1499       // draw an additional square around with 0.5 1 0.5 color
1500       if (!strcmpi(g_qeglobals.d_texturewin.texdef.GetName(), pCurrentShader->getName()))
1501       {
1502               qglLineWidth (3);
1503               qglColor3f (1,0,0);
1504               qglDisable (GL_TEXTURE_2D);
1505
1506               qglBegin (GL_LINE_LOOP);
1507               qglVertex2f (x-4,y-FONT_HEIGHT+4);
1508               qglVertex2f (x-4,y-FONT_HEIGHT-nHeight-4);
1509               qglVertex2f (x+4+nWidth,y-FONT_HEIGHT-nHeight-4);
1510               qglVertex2f (x+4+nWidth,y-FONT_HEIGHT+4);
1511               qglEnd ();
1512
1513               qglEnable (GL_TEXTURE_2D);
1514               qglLineWidth (1);
1515       }
1516       else
1517       {
1518               qglLineWidth (1);
1519               // shader border:
1520               if (!pCurrentShader->IsDefault())
1521               {
1522                 qglColor3f (1,1,1);
1523                 qglDisable (GL_TEXTURE_2D);
1524
1525                 qglBegin (GL_LINE_LOOP);
1526                 qglVertex2f (x-1,y+1-FONT_HEIGHT);
1527                 qglVertex2f (x-1,y-nHeight-1-FONT_HEIGHT);
1528                 qglVertex2f (x+1+nWidth,y-nHeight-1-FONT_HEIGHT);
1529                 qglVertex2f (x+1+nWidth,y+1-FONT_HEIGHT);
1530                 qglEnd ();
1531                 qglEnable (GL_TEXTURE_2D);
1532               }
1533
1534               // highlight in-use textures
1535               if (pCurrentShader->IsInUse())
1536               {
1537                 qglColor3f (0.5,1,0.5);
1538                 qglDisable (GL_TEXTURE_2D);
1539                 qglBegin (GL_LINE_LOOP);
1540                 qglVertex2f (x-3,y+3-FONT_HEIGHT);
1541                 qglVertex2f (x-3,y-nHeight-3-FONT_HEIGHT);
1542                 qglVertex2f (x+3+nWidth,y-nHeight-3-FONT_HEIGHT);
1543                 qglVertex2f (x+3+nWidth,y+3-FONT_HEIGHT);
1544                 qglEnd ();
1545                 qglEnable (GL_TEXTURE_2D);
1546               }
1547       }
1548
1549       // Draw the texture
1550       qglBindTexture (GL_TEXTURE_2D, q->texture_number);
1551       QE_CheckOpenGLForErrors();
1552       qglColor3f (1,1,1);
1553       qglBegin (GL_QUADS);
1554       qglTexCoord2f (0,0);
1555       qglVertex2f (x,y-FONT_HEIGHT);
1556       qglTexCoord2f (1,0);
1557       qglVertex2f (x+nWidth,y-FONT_HEIGHT);
1558       qglTexCoord2f (1,1);
1559       qglVertex2f (x+nWidth,y-FONT_HEIGHT-nHeight);
1560       qglTexCoord2f (0,1);
1561       qglVertex2f (x,y-FONT_HEIGHT-nHeight);
1562       qglEnd ();
1563
1564       // draw the texture name
1565       qglDisable (GL_TEXTURE_2D);
1566       qglColor3f (1,1,1);
1567
1568       qglRasterPos2f (x, y-FONT_HEIGHT+2);
1569
1570       // don't draw the directory name
1571       name = (char*)pCurrentShader->getName();
1572       name += strlen(name);
1573       while(name != (char*)pCurrentShader->getName() && *(name-1) != '/' && *(name-1) != '\\')
1574         name--;
1575
1576       gtk_glwidget_print_string(name);
1577       qglEnable (GL_TEXTURE_2D);
1578     }
1579   }
1580
1581   g_qeglobals.d_texturewin.m_nTotalHeight = abs(y) + last_height + FONT_HEIGHT + 4;
1582
1583   // reset the current texture
1584   qglBindTexture(GL_TEXTURE_2D, 0);
1585   qglFinish();
1586 }
1587
1588 //++timo seems we only know hard inits now..
1589 //void Texture_Init (bool bHardInit)
1590 void Texture_Init()
1591 {
1592   g_qeglobals.d_qtextures = NULL;
1593   // initialize the qtexture map
1594   if (g_qeglobals.d_qtexmap)
1595   {
1596     Sys_FPrintf(SYS_ERR, "TODO: delete g_qeglobals.d_qtexmap in Texture_Init\n");
1597   }
1598   g_qeglobals.d_qtexmap = g_hash_table_new (g_str_hash, g_str_equal);
1599   // initialize .. in some cases if no default texture / project loaded it crashes
1600   memset( &g_qeglobals.d_texturewin.texdef, 0, sizeof(g_qeglobals.d_texturewin.texdef) );
1601   g_qeglobals.d_texturewin.texdef.SetName(SHADER_NOT_FOUND);
1602   g_qeglobals.d_texturewin.pShader = QERApp_Shader_ForName(SHADER_NOT_FOUND);
1603 }
1604
1605 // FIXME TTimo this needs to move to the shader module along with l_shaderlist move
1606 // preload shader files that have been listed in shaderlist.txt
1607 void PreloadShaders()
1608 {
1609   GSList *lst = l_shaderfiles;
1610   Str shadername;
1611   while (lst)
1612   {
1613     shadername = g_pGameDescription->mShaderPath;
1614     shadername += (char*)lst->data;
1615     QERApp_LoadShaderFile(shadername.GetBuffer());
1616     lst = lst->next;
1617   }
1618 }
1619
1620 // TTimo: modified to expect the reletive path to the skin as input
1621 // will look into pak files if necessary
1622 // uses the shader code to load the texture Try_Texture_ForName
1623 // modified SkinInfo accordingly to store the qtexture_t and shader name (reletive version)
1624 // the .md3 have bundled filetype extension, but they don't fit with the actual data
1625 //   ex: models/mapobjects/gargoyle.tga doesn't exist, but models/mapobjects/gargoyle.jpg can be used instead
1626 //   so we remove the extension before load attempt
1627 int WINAPI Texture_LoadSkin(char *pName, int *pnWidth, int *pnHeight)
1628 {
1629   //  byte *pic = NULL;
1630   //  byte *pic32 = NULL;
1631   int nTex = -1;
1632   qtexture_t *qtex;
1633   SkinInfo *pInfo;
1634   const char *pCleanName;
1635
1636   int nSize = g_lstSkinCache.GetSize();
1637   pCleanName = QERApp_CleanTextureName( pName, false );
1638   for (int i = 0; i < nSize; i++)
1639   {
1640     SkinInfo *pInfo = reinterpret_cast<SkinInfo*>(g_lstSkinCache.GetAt(i));
1641     if (pInfo)
1642     {
1643       if (stricmp(pCleanName, pInfo->m_strName) == 0)
1644       {
1645         return pInfo->m_nTextureBind;
1646       }
1647     }
1648   }
1649
1650   // if the load is successfull, we get back a qtexture_t
1651   // we don't need to free it, it's in g_qeglobals.d_qtextures
1652   // NOTE: we need to free the SkinInfo though..
1653   qtex = QERApp_Try_Texture_ForName( pCleanName );
1654   if (qtex)
1655   {
1656     nTex = qtex->texture_number;
1657     pInfo = new SkinInfo(qtex->name, nTex, qtex);
1658   } else
1659   {
1660     pInfo = new SkinInfo(pCleanName, -1, NULL);
1661   }
1662   g_lstSkinCache.Add(pInfo);
1663
1664   return nTex;
1665 }
1666
1667 bool TexWnd::CheckFilter( const char* name )
1668 {
1669   const char* buf = gtk_entry_get_text (GTK_ENTRY (m_pFilter));
1670   if (strstr( name, buf ) != 0)
1671     return true;
1672   return false;
1673 }
1674
1675 // =============================================================================
1676 // static functions
1677
1678 static void vertical_scroll (GtkWidget *widget, gpointer data)
1679 {
1680   ((TexWnd*)data)->OnVScroll ();
1681 }
1682
1683 static void filter_changed (GtkWidget *widget, gpointer data)
1684 {
1685   CString str;
1686   str = gtk_entry_get_text (GTK_ENTRY (widget));
1687   ((TexWnd*)data)->UpdateFilter (str);
1688 }
1689
1690 // =============================================================================
1691 // TexWnd class
1692
1693 TexWnd::TexWnd()
1694 : GLWindow (FALSE)
1695 {
1696   m_pFilter = NULL;
1697   m_bNeedRange = true;
1698 }
1699
1700 TexWnd::~TexWnd()
1701 {
1702 }
1703
1704 void TexWnd::OnCreate ()
1705 {
1706   if (!MakeCurrent ())
1707     Error ("glMakeCurrent in TexWnd::OnCreate failed");
1708
1709   g_qeglobals_gui.d_texture = m_pWidget;
1710   g_nTextureOffset = 0;
1711
1712   GtkAdjustment *vadjustment = gtk_range_get_adjustment (GTK_RANGE (g_qeglobals_gui.d_texture_scroll));
1713   gtk_signal_connect (GTK_OBJECT (vadjustment), "value_changed", GTK_SIGNAL_FUNC (vertical_scroll), this);
1714
1715   if (g_PrefsDlg.m_bTextureScrollbar)
1716     gtk_widget_show (g_qeglobals_gui.d_texture_scroll);
1717   else
1718     gtk_widget_hide (g_qeglobals_gui.d_texture_scroll);
1719   m_bNeedRange = true;
1720
1721   gtk_signal_connect (GTK_OBJECT (m_pFilter), "changed", GTK_SIGNAL_FUNC (filter_changed), this);
1722   if (g_PrefsDlg.m_bTextureWindow)
1723     gtk_widget_show (m_pFilter);
1724 }
1725
1726 void TexWnd::UpdateFilter(const char* pFilter)
1727 {
1728   g_bFilterEnabled = false;
1729   if (pFilter)
1730   {
1731     g_strFilter = pFilter;
1732     if (g_strFilter.GetLength() > 0)
1733       g_bFilterEnabled = true;
1734     QERApp_SortActiveShaders();
1735   }
1736   Sys_UpdateWindows (W_TEXTURE);
1737 }
1738
1739 void TexWnd::OnSize (int cx, int cy)
1740 {
1741   m_bNeedRange = true;
1742 }
1743
1744 void TexWnd::OnExpose ()
1745 {
1746   int nOld = g_qeglobals.d_texturewin.m_nTotalHeight;
1747   if (!MakeCurrent ())
1748   {
1749     Sys_Printf("ERROR: glXMakeCurrent failed..\n ");
1750     Sys_Printf("Please restart Radiant if the Texture view is not working\n");
1751   } else
1752   {
1753     QE_CheckOpenGLForErrors();
1754     Texture_Draw (m_pWidget->allocation.width, m_pWidget->allocation.height - g_nTextureOffset);
1755     QE_CheckOpenGLForErrors();
1756     SwapBuffers ();
1757   }
1758   if (g_PrefsDlg.m_bTextureScrollbar && (m_bNeedRange || g_qeglobals.d_texturewin.m_nTotalHeight != nOld))
1759   {
1760     GtkAdjustment *vadjustment = gtk_range_get_adjustment (GTK_RANGE (g_qeglobals_gui.d_texture_scroll));
1761
1762     vadjustment->value = -g_qeglobals.d_texturewin.originy;
1763     vadjustment->page_size = m_pWidget->allocation.height;
1764     vadjustment->page_increment = m_pWidget->allocation.height/2;
1765     vadjustment->step_increment = 20;
1766     vadjustment->lower = 0;
1767     vadjustment->upper = g_qeglobals.d_texturewin.m_nTotalHeight;
1768
1769     gtk_signal_emit_by_name (GTK_OBJECT (vadjustment), "changed");
1770
1771     m_bNeedRange = false;
1772   }
1773 }
1774
1775 void TexWnd::OnLButtonDown (guint32 flags, int pointx, int pointy)
1776 {
1777   SetCapture ();
1778   Texture_MouseDown (pointx, pointy - g_nTextureOffset, flags);
1779 }
1780
1781 void TexWnd::OnRButtonDown (guint32 flags, int pointx, int pointy)
1782 {
1783   SetCapture ();
1784   Texture_MouseDown (pointx, pointy - g_nTextureOffset, flags);
1785 }
1786
1787 void TexWnd::OnMButtonDown (guint32 flags, int pointx, int pointy)
1788 {
1789   SetCapture ();
1790   Texture_MouseDown (pointx, pointy - g_nTextureOffset, flags);
1791 }
1792
1793 void TexWnd::OnLButtonUp (guint32 flags, int pointx, int pointy)
1794 {
1795   ReleaseCapture ();
1796   // NOTE TTimo http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=23
1797   DragDropTexture (flags, pointx, pointy);
1798 }
1799
1800 void TexWnd::OnRButtonUp (guint32 flags, int pointx, int pointy)
1801 {
1802   ReleaseCapture ();
1803 }
1804
1805 void TexWnd::OnMButtonUp (guint32 flags, int pointx, int pointy)
1806 {
1807   ReleaseCapture ();
1808 }
1809
1810 void TexWnd::OnMouseMove (guint32 flags, int pointx, int pointy)
1811 {
1812   Texture_MouseMoved (pointx, pointy - g_nTextureOffset, flags);
1813   // if scrollbar is hidden, we don't seem to get an update
1814   if( !g_PrefsDlg.m_bTextureScrollbar )
1815     RedrawWindow ();
1816 }
1817
1818 void TexWnd::OnVScroll ()
1819 {
1820   GtkAdjustment *vadjustment = gtk_range_get_adjustment (GTK_RANGE (g_qeglobals_gui.d_texture_scroll));
1821
1822   g_qeglobals.d_texturewin.originy = - (int)vadjustment->value;
1823   RedrawWindow ();
1824 }
1825
1826 void TexWnd::UpdatePrefs()
1827 {
1828   if (g_PrefsDlg.m_bTextureWindow)
1829     gtk_widget_show (m_pFilter);
1830   else
1831     gtk_widget_hide (m_pFilter);
1832
1833   if (g_PrefsDlg.m_bTextureScrollbar)
1834     gtk_widget_show (g_qeglobals_gui.d_texture_scroll);
1835   else
1836     gtk_widget_hide (g_qeglobals_gui.d_texture_scroll);
1837   m_bNeedRange = true;
1838   RedrawWindow ();
1839 }
1840
1841 void TexWnd::FocusEdit()
1842 {
1843   if (GTK_WIDGET_VISIBLE (m_pFilter))
1844     gtk_window_set_focus (GTK_WINDOW (g_pParentWnd->m_pWidget), m_pFilter);
1845 }
1846
1847 void TexWnd::OnMouseWheel(bool bUp)
1848 {
1849   if (bUp)
1850   {
1851     if(g_qeglobals.d_texturewin.originy < 0) {
1852       g_qeglobals.d_texturewin.originy += g_PrefsDlg.m_nWheelInc;
1853       // clamp so we don't get jiggle if moved by less than scrollwheel increment
1854       if(g_qeglobals.d_texturewin.originy > 0) {
1855         g_qeglobals.d_texturewin.originy = 0;
1856       }
1857     }
1858   }
1859   else
1860   {
1861     if(g_qeglobals.d_texturewin.originy > (-g_qeglobals.d_texturewin.m_nTotalHeight + g_qeglobals.d_texturewin.height))
1862       g_qeglobals.d_texturewin.originy -= g_PrefsDlg.m_nWheelInc;
1863   }
1864   GtkAdjustment *vadjustment = gtk_range_get_adjustment (GTK_RANGE (g_qeglobals_gui.d_texture_scroll));
1865   gtk_adjustment_set_value (vadjustment, abs(g_qeglobals.d_texturewin.originy));
1866
1867   RedrawWindow();
1868 }
1869
1870 // NOTE TTimo
1871 // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=23
1872 void TexWnd::DragDropTexture (guint32 flags, int pointx, int pointy)
1873 {
1874   // This gets called from leftmouse up event. We see if the mouseup is above
1875   // the camwindow. If this is the case do a trace for a surface. If we hit a
1876   // surface, texture it with the current texture.
1877
1878   int     m_ptXcheck, m_ptYcheck;
1879   int     m_ptX, m_ptY;
1880   GtkWidget *widget;
1881   gint x, y;
1882   vec3_t  dir;
1883   float   f, r, u;
1884   int     i;
1885
1886   // we only want to catch a plain mouseevent
1887   if (flags)
1888     return;
1889
1890   // see if we are above the camwindow
1891   Sys_GetCursorPos (&m_ptX, &m_ptY);
1892
1893   if (g_pParentWnd->CurrentStyle() == MainFrame::eFloating)
1894     widget = g_pParentWnd->GetCamWnd()->m_pParent;
1895   else
1896     widget = g_pParentWnd->GetCamWnd()->GetWidget();
1897
1898   get_window_pos (widget, &x, &y);
1899
1900   if (m_ptX < x || m_ptY < y ||
1901       m_ptX > x + widget->allocation.width ||
1902       m_ptY > y + widget->allocation.height)
1903     return;
1904
1905   // check if the camwindow isn't being partially hidden by another window at this point
1906   // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=187
1907   m_ptXcheck = m_ptX;
1908   m_ptYcheck = m_ptY;
1909
1910   if( g_pParentWnd->GetCamWnd()->GetWidget()->window != gdk_window_at_pointer( &m_ptXcheck, &m_ptYcheck ) )
1911     return;
1912
1913   // calc ray direction
1914   x = m_ptX - x;
1915   y = g_pParentWnd->GetCamWnd()->Camera()->height - 1 - (m_ptY - y);
1916   u = (float)( y - ( g_pParentWnd->GetCamWnd()->Camera()->height * .5f ) ) / ( g_pParentWnd->GetCamWnd()->Camera()->height * .5f );
1917   r = (float)( x - ( g_pParentWnd->GetCamWnd()->Camera()->width * .5f ) ) / ( g_pParentWnd->GetCamWnd()->Camera()->width * .5f );
1918   f = 1;
1919
1920   for (i=0 ; i<3 ; i++)
1921     dir[i] = g_pParentWnd->GetCamWnd()->Camera()->vpn[i] * f +
1922         g_pParentWnd->GetCamWnd()->Camera()->vright[i] * r +
1923         g_pParentWnd->GetCamWnd()->Camera()->vup[i] * u;
1924   VectorNormalize (dir, dir);
1925
1926   // do a trace for a surface
1927         trace_t t;
1928
1929         t = Test_Ray (g_pParentWnd->GetCamWnd()->Camera()->origin, dir, SF_SINGLEFACE);
1930
1931   if (t.brush)
1932   {
1933     texdef_t  tex;
1934     brushprimit_texdef_t brushprimit_tex;
1935
1936     memset (&tex, 0, sizeof(tex));
1937     memset (&brushprimit_tex, 0, sizeof(brushprimit_tex));
1938     if (g_qeglobals.m_bBrushPrimitMode)
1939     {
1940       // brushprimit fitted to a 2x2 texture
1941       brushprimit_tex.coords[0][0] = 1.0f;
1942       brushprimit_tex.coords[1][1] = 1.0f;
1943     } else
1944     {
1945       tex.scale[0] = g_pGameDescription->mTextureDefaultScale;
1946       tex.scale[1] = g_pGameDescription->mTextureDefaultScale;
1947     }
1948     tex.flags = g_qeglobals.d_texturewin.texdef.flags;
1949     tex.value = g_qeglobals.d_texturewin.texdef.value;
1950     tex.contents = g_qeglobals.d_texturewin.texdef.contents;
1951     // TTimo - shader code cleanup
1952     // texdef.name is the name of the shader, not the name of the actual texture file
1953     tex.SetName(g_qeglobals.d_texturewin.texdef.GetName());
1954
1955     Undo_Start("set face textures");
1956           Undo_AddBrush(t.brush);
1957           SetFaceTexdef (t.face, &tex, &brushprimit_tex, false, NULL );
1958           Brush_Build(t.brush, false);
1959           Undo_EndBrush(t.brush);
1960           Undo_End();
1961
1962     Sys_UpdateWindows (W_CAMERA);
1963     g_pParentWnd->OnTimer ();
1964   }
1965 }