xref: /aosp_15_r20/external/mesa3d/src/gallium/auxiliary/util/u_pstipple.c (revision 6104692788411f58d303aa86923a9ff6ecaded22)
1 /**************************************************************************
2  *
3  * Copyright 2008 VMware, Inc.
4  * Copyright 2010 VMware, Inc.
5  * All Rights Reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a
8  * copy of this software and associated documentation files (the
9  * "Software"), to deal in the Software without restriction, including
10  * without limitation the rights to use, copy, modify, merge, publish,
11  * distribute, sub license, and/or sell copies of the Software, and to
12  * permit persons to whom the Software is furnished to do so, subject to
13  * the following conditions:
14  *
15  * The above copyright notice and this permission notice (including the
16  * next paragraph) shall be included in all copies or substantial portions
17  * of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
20  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
22  * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
23  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26  *
27  **************************************************************************/
28 
29 /**
30  * Polygon stipple helper module.  Drivers/GPUs which don't support polygon
31  * stipple natively can use this module to simulate it.
32  *
33  * Basically, modify fragment shader to sample the 32x32 stipple pattern
34  * texture and do a fragment kill for the 'off' bits.
35  *
36  * This was originally a 'draw' module stage, but since we don't need
37  * vertex window coords or anything, it can be a stand-alone utility module.
38  *
39  * Authors:  Brian Paul
40  */
41 
42 
43 #include "pipe/p_context.h"
44 #include "pipe/p_defines.h"
45 #include "pipe/p_shader_tokens.h"
46 #include "util/u_inlines.h"
47 
48 #include "util/format/u_format.h"
49 #include "util/u_memory.h"
50 #include "util/u_pstipple.h"
51 #include "util/u_sampler.h"
52 
53 #include "tgsi/tgsi_transform.h"
54 #include "tgsi/tgsi_dump.h"
55 #include "tgsi/tgsi_scan.h"
56 
57 /** Approx number of new tokens for instructions in pstip_transform_inst() */
58 #define NUM_NEW_TOKENS 53
59 
60 
61 void
util_pstipple_update_stipple_texture(struct pipe_context * pipe,struct pipe_resource * tex,const uint32_t pattern[32])62 util_pstipple_update_stipple_texture(struct pipe_context *pipe,
63                                      struct pipe_resource *tex,
64                                      const uint32_t pattern[32])
65 {
66    static const unsigned bit31 = 1u << 31;
67    struct pipe_transfer *transfer;
68    uint8_t *data;
69    int i, j;
70 
71    /* map texture memory */
72    data = pipe_texture_map(pipe, tex, 0, 0,
73                             PIPE_MAP_WRITE, 0, 0, 32, 32, &transfer);
74 
75    /*
76     * Load alpha texture.
77     * Note: 0 means keep the fragment, 255 means kill it.
78     * We'll negate the texel value and use KILL_IF which kills if value
79     * is negative.
80     */
81    for (i = 0; i < 32; i++) {
82       for (j = 0; j < 32; j++) {
83          if (pattern[i] & (bit31 >> j)) {
84             /* fragment "on" */
85             data[i * transfer->stride + j] = 0;
86          }
87          else {
88             /* fragment "off" */
89             data[i * transfer->stride + j] = 255;
90          }
91       }
92    }
93 
94    /* unmap */
95    pipe->texture_unmap(pipe, transfer);
96 }
97 
98 
99 /**
100  * Create a 32x32 alpha8 texture that encodes the given stipple pattern.
101  */
102 struct pipe_resource *
util_pstipple_create_stipple_texture(struct pipe_context * pipe,const uint32_t pattern[32])103 util_pstipple_create_stipple_texture(struct pipe_context *pipe,
104                                      const uint32_t pattern[32])
105 {
106    struct pipe_screen *screen = pipe->screen;
107    struct pipe_resource templat, *tex;
108 
109    memset(&templat, 0, sizeof(templat));
110    templat.target = PIPE_TEXTURE_2D;
111    templat.format = PIPE_FORMAT_A8_UNORM;
112    templat.last_level = 0;
113    templat.width0 = 32;
114    templat.height0 = 32;
115    templat.depth0 = 1;
116    templat.array_size = 1;
117    templat.bind = PIPE_BIND_SAMPLER_VIEW;
118 
119    tex = screen->resource_create(screen, &templat);
120 
121    if (tex && pattern)
122       util_pstipple_update_stipple_texture(pipe, tex, pattern);
123 
124    return tex;
125 }
126 
127 
128 /**
129  * Create sampler view to sample the stipple texture.
130  */
131 struct pipe_sampler_view *
util_pstipple_create_sampler_view(struct pipe_context * pipe,struct pipe_resource * tex)132 util_pstipple_create_sampler_view(struct pipe_context *pipe,
133                                   struct pipe_resource *tex)
134 {
135    struct pipe_sampler_view templat, *sv;
136 
137    u_sampler_view_default_template(&templat, tex, tex->format);
138    sv = pipe->create_sampler_view(pipe, tex, &templat);
139 
140    return sv;
141 }
142 
143 
144 /**
145  * Create the sampler CSO that'll be used for stippling.
146  */
147 void *
util_pstipple_create_sampler(struct pipe_context * pipe)148 util_pstipple_create_sampler(struct pipe_context *pipe)
149 {
150    struct pipe_sampler_state templat;
151    void *s;
152 
153    memset(&templat, 0, sizeof(templat));
154    templat.wrap_s = PIPE_TEX_WRAP_REPEAT;
155    templat.wrap_t = PIPE_TEX_WRAP_REPEAT;
156    templat.wrap_r = PIPE_TEX_WRAP_REPEAT;
157    templat.min_mip_filter = PIPE_TEX_MIPFILTER_NONE;
158    templat.min_img_filter = PIPE_TEX_FILTER_NEAREST;
159    templat.mag_img_filter = PIPE_TEX_FILTER_NEAREST;
160    templat.min_lod = 0.0f;
161    templat.max_lod = 0.0f;
162 
163    s = pipe->create_sampler_state(pipe, &templat);
164    return s;
165 }
166 
167 
168 
169 /**
170  * Subclass of tgsi_transform_context, used for transforming the
171  * user's fragment shader to add the extra texture sample and fragment kill
172  * instructions.
173  */
174 struct pstip_transform_context {
175    struct tgsi_transform_context base;
176    struct tgsi_shader_info info;
177    unsigned tempsUsed;  /**< bitmask */
178    int wincoordInput;
179    unsigned wincoordFile;
180    int maxInput;
181    unsigned samplersUsed;  /**< bitfield of samplers used */
182    int freeSampler;  /** an available sampler for the pstipple */
183    int numImmed;
184    unsigned coordOrigin;
185    unsigned fixedUnit;
186    bool hasFixedUnit;
187 };
188 
189 
190 /**
191  * TGSI declaration transform callback.
192  * Track samplers used, temps used, inputs used.
193  */
194 static void
pstip_transform_decl(struct tgsi_transform_context * ctx,struct tgsi_full_declaration * decl)195 pstip_transform_decl(struct tgsi_transform_context *ctx,
196                      struct tgsi_full_declaration *decl)
197 {
198    struct pstip_transform_context *pctx =
199       (struct pstip_transform_context *) ctx;
200 
201    /* XXX we can use tgsi_shader_info instead of some of this */
202 
203    if (decl->Declaration.File == TGSI_FILE_SAMPLER) {
204       unsigned i;
205       for (i = decl->Range.First; i <= decl->Range.Last; i++) {
206          pctx->samplersUsed |= 1u << i;
207       }
208    }
209    else if (decl->Declaration.File == pctx->wincoordFile) {
210       pctx->maxInput = MAX2(pctx->maxInput, (int) decl->Range.Last);
211       if (decl->Semantic.Name == TGSI_SEMANTIC_POSITION)
212          pctx->wincoordInput = (int) decl->Range.First;
213    }
214    else if (decl->Declaration.File == TGSI_FILE_TEMPORARY) {
215       unsigned i;
216       for (i = decl->Range.First; i <= decl->Range.Last; i++) {
217          pctx->tempsUsed |= (1 << i);
218       }
219    }
220 
221    ctx->emit_declaration(ctx, decl);
222 }
223 
224 
225 static void
pstip_transform_immed(struct tgsi_transform_context * ctx,struct tgsi_full_immediate * immed)226 pstip_transform_immed(struct tgsi_transform_context *ctx,
227                       struct tgsi_full_immediate *immed)
228 {
229    struct pstip_transform_context *pctx =
230       (struct pstip_transform_context *) ctx;
231    pctx->numImmed++;
232    ctx->emit_immediate(ctx, immed);
233 }
234 
235 
236 /**
237  * Find the lowest zero bit in the given word, or -1 if bitfield is all ones.
238  */
239 static int
free_bit(unsigned bitfield)240 free_bit(unsigned bitfield)
241 {
242    return ffs(~bitfield) - 1;
243 }
244 
245 
246 /**
247  * TGSI transform prolog
248  * Before the first instruction, insert our new code to sample the
249  * stipple texture (using the fragment coord register) then kill the
250  * fragment if the stipple texture bit is off.
251  *
252  * Insert:
253  *   declare new registers
254  *   MUL texTemp, INPUT[wincoord], 1/32;
255  *   TEX texTemp, texTemp, sampler;
256  *   KILL_IF -texTemp;   # if -texTemp < 0, kill fragment
257  *   [...original code...]
258  */
259 static void
pstip_transform_prolog(struct tgsi_transform_context * ctx)260 pstip_transform_prolog(struct tgsi_transform_context *ctx)
261 {
262    struct pstip_transform_context *pctx =
263       (struct pstip_transform_context *) ctx;
264    int wincoordInput;
265    int texTemp;
266    int sampIdx;
267 
268    STATIC_ASSERT(sizeof(pctx->samplersUsed) * 8 >= PIPE_MAX_SAMPLERS);
269 
270    /* find free texture sampler */
271    pctx->freeSampler = free_bit(pctx->samplersUsed);
272    if (pctx->freeSampler < 0 || pctx->freeSampler >= PIPE_MAX_SAMPLERS)
273       pctx->freeSampler = PIPE_MAX_SAMPLERS - 1;
274 
275    if (pctx->wincoordInput < 0)
276       wincoordInput = pctx->maxInput + 1;
277    else
278       wincoordInput = pctx->wincoordInput;
279 
280    if (pctx->wincoordInput < 0) {
281       struct tgsi_full_declaration decl;
282 
283       decl = tgsi_default_full_declaration();
284       /* declare new position input reg */
285       decl.Declaration.File = pctx->wincoordFile;
286       decl.Declaration.Semantic = 1;
287       decl.Semantic.Name = TGSI_SEMANTIC_POSITION;
288       decl.Range.First =
289       decl.Range.Last = wincoordInput;
290 
291       if (pctx->wincoordFile == TGSI_FILE_INPUT) {
292          decl.Declaration.Interpolate = 1;
293          decl.Interp.Interpolate = TGSI_INTERPOLATE_LINEAR;
294       }
295 
296       ctx->emit_declaration(ctx, &decl);
297    }
298 
299    sampIdx = pctx->hasFixedUnit ? (int)pctx->fixedUnit : pctx->freeSampler;
300 
301    /* declare new sampler */
302    tgsi_transform_sampler_decl(ctx, sampIdx);
303 
304    /* if the src shader has SVIEW decl's for each SAMP decl, we
305     * need to continue the trend and ensure there is a matching
306     * SVIEW for the new SAMP we just created
307     */
308    if (pctx->info.file_max[TGSI_FILE_SAMPLER_VIEW] != -1) {
309       tgsi_transform_sampler_view_decl(ctx,
310                                        sampIdx,
311                                        TGSI_TEXTURE_2D,
312                                        TGSI_RETURN_TYPE_FLOAT);
313    }
314 
315    /* Declare temp[0] reg if not already declared.
316     * We can always use temp[0] since this code is before
317     * the rest of the shader.
318     */
319    texTemp = 0;
320    if ((pctx->tempsUsed & (1 << texTemp)) == 0) {
321       tgsi_transform_temp_decl(ctx, texTemp);
322    }
323 
324    /* emit immediate = {1/32, 1/32, 1, 1}
325     * The index/position of this immediate will be pctx->numImmed
326     */
327    tgsi_transform_immediate_decl(ctx, 1.0/32.0, 1.0/32.0, 1.0, 1.0);
328 
329    /*
330     * Insert new MUL/TEX/KILL_IF instructions at start of program
331     * Take gl_FragCoord, divide by 32 (stipple size), sample the
332     * texture and kill fragment if needed.
333     *
334     * We'd like to use non-normalized texcoords to index into a RECT
335     * texture, but we can only use REPEAT wrap mode with normalized
336     * texcoords.  Darn.
337     */
338 
339    /* XXX invert wincoord if origin isn't lower-left... */
340 
341    /* MUL texTemp, INPUT[wincoord], 1/32; */
342    tgsi_transform_op2_inst(ctx, TGSI_OPCODE_MUL,
343                            TGSI_FILE_TEMPORARY, texTemp,
344                            TGSI_WRITEMASK_XYZW,
345                            pctx->wincoordFile, wincoordInput,
346                            TGSI_FILE_IMMEDIATE, pctx->numImmed, false);
347 
348    /* TEX texTemp, texTemp, sampler, 2D; */
349    tgsi_transform_tex_inst(ctx,
350                            TGSI_FILE_TEMPORARY, texTemp,
351                            TGSI_FILE_TEMPORARY, texTemp,
352                            TGSI_TEXTURE_2D, sampIdx);
353 
354    /* KILL_IF -texTemp;   # if -texTemp < 0, kill fragment */
355    tgsi_transform_kill_inst(ctx,
356                             TGSI_FILE_TEMPORARY, texTemp,
357                             TGSI_SWIZZLE_W, true);
358 }
359 
360 
361 /**
362  * Given a fragment shader, return a new fragment shader which
363  * samples a stipple texture and executes KILL.
364  *
365  * \param samplerUnitOut  returns the index of the sampler unit which
366  *                        will be used to sample the stipple texture;
367  *                        if NULL, the fixed unit is used
368  * \param fixedUnit       fixed texture unit used for the stipple texture
369  * \param wincoordFile    TGSI_FILE_INPUT or TGSI_FILE_SYSTEM_VALUE,
370  *                        depending on which one is supported by the driver
371  *                        for TGSI_SEMANTIC_POSITION in the fragment shader
372  */
373 struct tgsi_token *
util_pstipple_create_fragment_shader(const struct tgsi_token * tokens,unsigned * samplerUnitOut,unsigned fixedUnit,unsigned wincoordFile)374 util_pstipple_create_fragment_shader(const struct tgsi_token *tokens,
375                                      unsigned *samplerUnitOut,
376                                      unsigned fixedUnit,
377                                      unsigned wincoordFile)
378 {
379    struct pstip_transform_context transform;
380    const unsigned newLen = tgsi_num_tokens(tokens) + NUM_NEW_TOKENS;
381    struct tgsi_token *new_tokens;
382 
383    /* Setup shader transformation info/context.
384     */
385    memset(&transform, 0, sizeof(transform));
386    transform.wincoordInput = -1;
387    transform.wincoordFile = wincoordFile;
388    transform.maxInput = -1;
389    transform.coordOrigin = TGSI_FS_COORD_ORIGIN_UPPER_LEFT;
390    transform.hasFixedUnit = !samplerUnitOut;
391    transform.fixedUnit = fixedUnit;
392    transform.base.prolog = pstip_transform_prolog;
393    transform.base.transform_declaration = pstip_transform_decl;
394    transform.base.transform_immediate = pstip_transform_immed;
395 
396    tgsi_scan_shader(tokens, &transform.info);
397 
398    transform.coordOrigin =
399       transform.info.properties[TGSI_PROPERTY_FS_COORD_ORIGIN];
400 
401    new_tokens = tgsi_transform_shader(tokens, newLen, &transform.base);
402    if (!new_tokens)
403       return NULL;
404 
405 #if 0 /* debug */
406    tgsi_dump(fs->tokens, 0);
407    tgsi_dump(new_fs->tokens, 0);
408 #endif
409 
410    if (samplerUnitOut) {
411       assert(transform.freeSampler < PIPE_MAX_SAMPLERS);
412       *samplerUnitOut = transform.freeSampler;
413    }
414 
415    return new_tokens;
416 }
417