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