1 ! Copyright (C) 2009 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors assocs cache colors.constants destructors fry kernel
4 opengl opengl.gl combinators images grouping specialized-arrays.float
5 locals sequences math math.vectors generalizations ;
8 : gen-texture ( -- id ) [ glGenTextures ] (gen-gl-object) ;
10 : delete-texture ( id -- ) [ glDeleteTextures ] (delete-gl-object) ;
12 TUPLE: texture loc dim texture-coords texture display-list disposed ;
16 GENERIC: component-order>format ( component-order -- format type )
18 M: RGBA component-order>format drop GL_RGBA GL_UNSIGNED_BYTE ;
19 M: ARGB component-order>format drop GL_BGRA_EXT GL_UNSIGNED_INT_8_8_8_8_REV ;
20 M: BGRA component-order>format drop GL_BGRA_EXT GL_UNSIGNED_BYTE ;
22 : repeat-last ( seq n -- seq' )
23 over peek pad-tail concat ;
25 : power-of-2-bitmap ( rows dim size -- bitmap dim )
28 [ [ _ ] dip '[ _ group _ repeat-last ] map ]
33 : image-rows ( image -- rows )
36 [ component-order>> bytes-per-pixel ]
39 : power-of-2-image ( image -- image )
40 dup dim>> [ 0 = ] all? [
43 [ dim>> [ next-power-of-2 ] map ]
44 [ component-order>> bytes-per-pixel ] tri
46 [ >>bitmap ] [ >>dim ] bi*
49 :: make-texture ( image -- id )
52 GL_TEXTURE_2D swap glBindTexture
58 image component-order>> component-order>format
65 GL_TEXTURE_2D GL_TEXTURE_MAG_FILTER GL_LINEAR glTexParameteri
66 GL_TEXTURE_2D GL_TEXTURE_MIN_FILTER GL_LINEAR glTexParameteri
67 GL_TEXTURE_2D GL_TEXTURE_WRAP_S GL_REPEAT glTexParameteri
68 GL_TEXTURE_2D GL_TEXTURE_WRAP_T GL_REPEAT glTexParameteri ;
70 : draw-textured-rect ( dim texture -- )
73 GL_TEXTURE_COORD_ARRAY [
76 [ [ GL_TEXTURE_2D ] dip texture>> glBindTexture ]
77 [ init-texture texture-coords>> gl-texture-coord-pointer ] bi
78 fill-rect-vertices (gl-fill-rect)
79 GL_TEXTURE_2D 0 glBindTexture
81 ] do-enabled-client-state
85 : texture-coords ( dim -- coords )
86 [ dup next-power-of-2 /f ] map
87 { { 0 0 } { 1 0 } { 1 1 } { 0 1 } } [ v* ] with map
90 : make-texture-display-list ( texture -- dlist )
91 GL_COMPILE [ [ dim>> ] keep draw-textured-rect ] make-dlist ;
95 : <texture> ( image loc -- texture )
96 texture new swap >>loc
99 [ dim>> product 0 = ] keep '[
101 [ dim>> texture-coords >>texture-coords ]
102 [ power-of-2-image make-texture >>texture ] bi
103 dup make-texture-display-list >>display-list
107 [ texture>> [ delete-texture ] when* ]
108 [ display-list>> [ delete-dlist ] when* ] bi ;
110 : draw-texture ( texture -- )
111 display-list>> [ glCallList ] when* ;
113 : draw-scaled-texture ( dim texture -- )
114 dup texture>> [ draw-textured-rect ] [ 2drop ] if ;