source: trunk/src/gpu/shader.cpp @ 2827

Last change on this file since 2827 was 2827, checked in by benlitz, 7 years ago

gpu: fixed vbo attribute binding when one of the attribute on the buffer does not exist in the shader

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Id
File size: 27.2 KB
Line 
1//
2// Lol Engine
3//
4// Copyright: (c) 2010-2013 Sam Hocevar <sam@hocevar.net>
5//   This program is free software; you can redistribute it and/or
6//   modify it under the terms of the Do What The Fuck You Want To
7//   Public License, Version 2, as published by Sam Hocevar. See
8//   http://www.wtfpl.net/ for more details.
9//
10
11#if defined HAVE_CONFIG_H
12#   include "config.h"
13#endif
14
15#include <cstring>
16#include <cstdio>
17
18#if defined WIN32 && !defined _XBOX
19#   define WIN32_LEAN_AND_MEAN
20#   include <windows.h>
21#   if defined USE_D3D9
22#       include <algorithm>
23        using std::min;
24        using std::max;
25#       include <d3d9.h>
26#       include <d3dx9shader.h>
27#   endif
28#elif defined _XBOX
29#   include <xtl.h>
30#   undef near /* Fuck Microsoft */
31#   undef far /* Fuck Microsoft again */
32#endif
33
34#include "core.h"
35#include "lolgl.h"
36
37using namespace std;
38
39namespace lol
40{
41
42/*
43 * Shader implementation class
44 */
45
46class ShaderData
47{
48    friend class Shader;
49
50private:
51#if defined USE_D3D9
52    IDirect3DDevice9 *m_dev;
53    IDirect3DVertexShader9 *vert_shader;
54    IDirect3DPixelShader9 *frag_shader;
55    ID3DXConstantTable *vert_table, *frag_table;
56#elif defined _XBOX
57    D3DDevice *m_dev;
58    D3DVertexShader *vert_shader;
59    D3DPixelShader *frag_shader;
60    ID3DXConstantTable *vert_table, *frag_table;
61#elif !defined __CELLOS_LV2__
62    GLuint prog_id, vert_id, frag_id;
63    // Benlitz: using a simple array could be faster since there is never more than a few attribute locations to store
64    Map<String, GLint> attrib_locations;
65#else
66    CGprogram vert_id, frag_id;
67#endif
68    uint32_t vert_crc, frag_crc;
69
70    /* Shader patcher */
71    static int GetVersion();
72    static void Patch(char *dst, char const *vert, char const *frag);
73
74    /* Global shader cache */
75    static Shader *shaders[];
76    static Hash<char const *> hash;
77    static int nshaders;
78};
79
80Shader *ShaderData::shaders[256];
81Hash<char const *> ShaderData::hash;
82int ShaderData::nshaders = 0;
83
84/*
85 * Public Shader class
86 */
87
88Shader *Shader::Create(char const *lolfx)
89{
90    char *src = new char[strlen(lolfx) + 2];
91    memcpy(src + 1, lolfx, strlen(lolfx) + 1);
92    src[0] = '\n';
93
94    /* Parse the crap */
95    Array<char const *, char const *> sections;
96    char *key = nullptr;
97    for (char *parser = src; *parser; )
98    {
99        if (key == nullptr && (parser[0] == '\n' || parser[0] == '\r')
100             && parser[1] == '[')
101        {
102            *parser = '\0';
103            parser += 2;
104            key = parser;
105        }
106        else if (key && parser[0] == ']')
107        {
108            *parser++ = '\0';
109        }
110        else if (key && (parser[0] == '\n' || parser[0] == '\r'))
111        {
112            sections.Push(key, parser);
113            parser++;
114            key = nullptr;
115        }
116        else
117        {
118            parser++;
119        }
120    }
121
122    char const *vert = nullptr, *frag = nullptr;
123    for (int i = 0; i < sections.Count(); i++)
124    {
125#if !defined __CELLOS_LV2__ && !defined _XBOX && !defined USE_D3D9
126        if (!strcmp(sections[i].m1, "vert.glsl"))
127            vert = sections[i].m2;
128        if (!strcmp(sections[i].m1, "frag.glsl"))
129            frag = sections[i].m2;
130#else
131        if (!strcmp(sections[i].m1, "vert.hlsl"))
132            vert = sections[i].m2;
133        if (!strcmp(sections[i].m1, "frag.hlsl"))
134            frag = sections[i].m2;
135#endif
136    }
137
138    /* FIXME: we don’t know how to handle these yet. */
139    if (!vert)
140        Log::Error("no vertex shader found… sorry, I’m gonna crash now.\n");
141    if (!frag)
142        Log::Error("no fragment shader found… sorry, I’m gonna crash now.\n");
143
144    uint32_t new_vert_crc = ShaderData::hash(vert);
145    uint32_t new_frag_crc = ShaderData::hash(frag);
146
147    for (int n = 0; n < ShaderData::nshaders; n++)
148    {
149        if (ShaderData::shaders[n]->data->vert_crc == new_vert_crc
150             && ShaderData::shaders[n]->data->frag_crc == new_frag_crc)
151        {
152            delete[] src;
153            return ShaderData::shaders[n];
154        }
155    }
156
157    Shader *ret = new Shader(vert, frag);
158    ShaderData::shaders[ShaderData::nshaders] = ret;
159    ShaderData::nshaders++;
160
161    delete[] src;
162    return ret;
163}
164
165void Shader::Destroy(Shader *shader)
166{
167    /* XXX: do nothing! the shader should remain in cache */
168    UNUSED(shader);
169}
170
171Shader::Shader(char const *vert, char const *frag)
172  : data(new ShaderData())
173{
174#if defined USE_D3D9 || defined _XBOX
175    ID3DXBuffer *shader_code, *error_msg;
176    HRESULT hr;
177    D3DXMACRO macros[] =
178    {
179#if defined _XBOX
180        { "_XBOX", "1" },
181#endif
182        { nullptr, nullptr }
183    };
184#elif !defined __CELLOS_LV2__
185    char buf[4096], errbuf[4096];
186    char const *shader = buf;
187    GLint status;
188    GLsizei len;
189#else
190    /* Initialise the runtime shader compiler. FIXME: this needs only
191     * to be done once. */
192    cgRTCgcInit();
193#endif
194
195    /* Compile vertex shader */
196    data->vert_crc = ShaderData::hash(vert);
197#if defined USE_D3D9 || defined _XBOX
198#   if defined USE_D3D9
199    data->m_dev = (IDirect3DDevice9 *)g_renderer->GetDevice();
200#   elif defined _XBOX
201    data->m_dev = (D3DDevice *)g_renderer->GetDevice();
202#   endif
203
204    hr = D3DXCompileShader(vert, (UINT)strlen(vert), macros, nullptr, "main",
205                           "vs_3_0", 0, &shader_code, &error_msg,
206                           &data->vert_table);
207    if (FAILED(hr))
208    {
209        Log::Error("failed to compile vertex shader: %s",
210                   error_msg ? error_msg->GetBufferPointer() : "error");
211        Log::Error("shader source:\n%s\n", vert);
212    }
213    data->m_dev->CreateVertexShader((DWORD *)shader_code->GetBufferPointer(),
214                                    &data->vert_shader);
215    shader_code->Release();
216#elif !defined __CELLOS_LV2__
217    ShaderData::Patch(buf, vert, nullptr);
218    data->vert_id = glCreateShader(GL_VERTEX_SHADER);
219    glShaderSource(data->vert_id, 1, &shader, nullptr);
220    glCompileShader(data->vert_id);
221
222    glGetShaderInfoLog(data->vert_id, sizeof(errbuf), &len, errbuf);
223    glGetShaderiv(data->vert_id, GL_COMPILE_STATUS, &status);
224    if (status != GL_TRUE)
225    {
226        Log::Error("failed to compile vertex shader: %s", errbuf);
227        Log::Error("shader source:\n%s\n", buf);
228    }
229    else if (len > 16)
230    {
231        Log::Debug("compile log for vertex shader: %s", errbuf);
232        Log::Debug("shader source:\n%s\n", buf);
233    }
234#else
235    data->vert_id = cgCreateProgram(cgCreateContext(), CG_SOURCE, vert,
236                                    cgGLGetLatestProfile(CG_GL_VERTEX),
237                                    nullptr, nullptr);
238    if (data->vert_id == nullptr)
239    {
240        Log::Error("failed to compile vertex shader");
241        Log::Error("shader source:\n%s\n", vert);
242    }
243#endif
244
245    /* Compile fragment shader */
246    data->frag_crc = ShaderData::hash(frag);
247#if defined USE_D3D9 || defined _XBOX
248    hr = D3DXCompileShader(frag, (UINT)strlen(frag), macros, nullptr, "main",
249                           "ps_3_0", 0, &shader_code, &error_msg,
250                           &data->frag_table);
251    if (FAILED(hr))
252    {
253        Log::Error("failed to compile fragment shader: %s",
254                   error_msg ? error_msg->GetBufferPointer() : "error");
255        Log::Error("shader source:\n%s\n", frag);
256    }
257    data->m_dev->CreatePixelShader((DWORD *)shader_code->GetBufferPointer(),
258                                   &data->frag_shader);
259    shader_code->Release();
260#elif !defined __CELLOS_LV2__
261    ShaderData::Patch(buf, nullptr, frag);
262    data->frag_id = glCreateShader(GL_FRAGMENT_SHADER);
263    glShaderSource(data->frag_id, 1, &shader, nullptr);
264    glCompileShader(data->frag_id);
265
266    glGetShaderInfoLog(data->frag_id, sizeof(errbuf), &len, errbuf);
267    glGetShaderiv(data->frag_id, GL_COMPILE_STATUS, &status);
268    if (status != GL_TRUE)
269    {
270        Log::Error("failed to compile fragment shader: %s", errbuf);
271        Log::Error("shader source:\n%s\n", buf);
272    }
273    else if (len > 16)
274    {
275        Log::Debug("compile log for fragment shader: %s", errbuf);
276        Log::Debug("shader source:\n%s\n", buf);
277    }
278#else
279    data->frag_id = cgCreateProgram(cgCreateContext(), CG_SOURCE, frag,
280                                    cgGLGetLatestProfile(CG_GL_FRAGMENT),
281                                    nullptr, nullptr);
282    if (data->frag_id == nullptr)
283    {
284        Log::Error("failed to compile fragment shader");
285        Log::Error("shader source:\n%s\n", frag);
286    }
287#endif
288
289#if defined USE_D3D9 || defined _XBOX
290    /* FIXME: this is only debug code, we don't need it. */
291    D3DXCONSTANTTABLE_DESC desc;
292    data->frag_table->GetDesc(&desc);
293    for (int i = 0; i < desc.Constants; i++)
294    {
295        D3DXCONSTANT_DESC cdesc;
296        UINT count = 1;
297        D3DXHANDLE h = data->frag_table->GetConstant(nullptr, i);
298        data->frag_table->GetConstantDesc(h, &cdesc, &count);
299    }
300    data->vert_table->GetDesc(&desc);
301    for (int i = 0; i < desc.Constants; i++)
302    {
303        D3DXCONSTANT_DESC cdesc;
304        UINT count = 1;
305        D3DXHANDLE h = data->vert_table->GetConstant(nullptr, i);
306        data->frag_table->GetConstantDesc(h, &cdesc, &count);
307    }
308#elif !defined __CELLOS_LV2__
309    /* Create program */
310    data->prog_id = glCreateProgram();
311    glAttachShader(data->prog_id, data->vert_id);
312    glAttachShader(data->prog_id, data->frag_id);
313
314    glLinkProgram(data->prog_id);
315    glGetProgramInfoLog(data->prog_id, sizeof(errbuf), &len, errbuf);
316    glGetProgramiv(data->prog_id, GL_LINK_STATUS, &status);
317    if (status != GL_TRUE)
318    {
319        Log::Error("failed to link program: %s", errbuf);
320    }
321    else if (len > 16)
322    {
323        Log::Debug("link log for program: %s", errbuf);
324    }
325    glValidateProgram(data->prog_id);
326#endif
327}
328
329ShaderAttrib Shader::GetAttribLocation(char const *attr,
330                                       VertexUsage usage, int index) const
331{
332    ShaderAttrib ret;
333    ret.m_flags = (uint64_t)(uint16_t)usage << 16;
334    ret.m_flags |= (uint64_t)(uint16_t)index;
335#if defined USE_D3D9 || defined _XBOX
336#elif !defined __CELLOS_LV2__
337    GLint l;
338
339    if (!data->attrib_locations.TryGetValue(attr, l))
340    {
341        l = glGetAttribLocation(data->prog_id, attr);
342        if (l < 0)
343        {
344            Log::Warn("tried to query invalid attribute: %s\n", attr);
345        }
346        else
347        {
348            data->attrib_locations[String(attr)] = l;
349        }
350    }
351    ret.m_flags |= (uint64_t)(uint32_t)l << 32;
352#else
353    /* FIXME: can we do this at all on the PS3? */
354#endif
355    return ret;
356}
357
358ShaderUniform Shader::GetUniformLocation(char const *uni) const
359{
360    ShaderUniform ret;
361#if defined USE_D3D9 || defined _XBOX
362    /* Global variables are prefixed with "$" */
363    String tmpname = String("$") + uni;
364    D3DXCONSTANT_DESC cdesc;
365    D3DXHANDLE hr;
366    UINT count;
367
368    count = 0;
369    hr = data->frag_table->GetConstantByName(nullptr, tmpname.C());
370    if (hr)
371        data->frag_table->GetConstantDesc(hr, &cdesc, &count);
372    if (count)
373    {
374        ret.frag = cdesc.RegisterIndex;
375        ret.flags |= 1;
376    }
377
378    count = 0;
379    hr = data->vert_table->GetConstantByName(nullptr, tmpname.C());
380    if (hr)
381        data->vert_table->GetConstantDesc(hr, &cdesc, &count);
382    if (count)
383    {
384        ret.vert = cdesc.RegisterIndex;
385        ret.flags |= 2;
386    }
387#elif !defined __CELLOS_LV2__
388    ret.frag = (uintptr_t)glGetUniformLocation(data->prog_id, uni);
389    ret.vert = 0;
390#else
391    ret.frag = (uintptr_t)cgGetNamedParameter(data->frag_id, uni);
392    ret.vert = (uintptr_t)cgGetNamedParameter(data->vert_id, uni);
393#endif
394    return ret;
395}
396
397/*
398 * Uniform setters for scalars
399 */
400
401void Shader::SetUniform(ShaderUniform const &uni, int i)
402{
403#if defined USE_D3D9 || defined _XBOX
404    SetUniform(uni, ivec4(i, 0, 0, 0));
405#elif !defined __CELLOS_LV2__
406    glUniform1i(uni.frag, i);
407#else
408    /* FIXME: does this exist at all? cgGLSetParameter1i doesn't. */
409#endif
410}
411
412void Shader::SetUniform(ShaderUniform const &uni, ivec2 const &v)
413{
414#if defined USE_D3D9 || defined _XBOX
415    SetUniform(uni, ivec4(v, 0, 0));
416#elif !defined __CELLOS_LV2__
417    glUniform2i(uni.frag, v.x, v.y);
418#else
419    /* FIXME: does this exist at all? */
420#endif
421}
422
423void Shader::SetUniform(ShaderUniform const &uni, ivec3 const &v)
424{
425#if defined USE_D3D9 || defined _XBOX
426    SetUniform(uni, ivec4(v, 0));
427#elif !defined __CELLOS_LV2__
428    glUniform3i(uni.frag, v.x, v.y, v.z);
429#else
430    /* FIXME: does this exist at all? */
431#endif
432}
433
434void Shader::SetUniform(ShaderUniform const &uni, ivec4 const &v)
435{
436#if defined USE_D3D9 || defined _XBOX
437    if (uni.flags & 1)
438        data->m_dev->SetPixelShaderConstantI((UINT)uni.frag, &v[0], 1);
439    if (uni.flags & 2)
440        data->m_dev->SetVertexShaderConstantI((UINT)uni.vert, &v[0], 1);
441#elif !defined __CELLOS_LV2__
442    glUniform4i(uni.frag, v.x, v.y, v.z, v.w);
443#else
444    /* FIXME: does this exist at all? */
445#endif
446}
447
448void Shader::SetUniform(ShaderUniform const &uni, float f)
449{
450#if defined USE_D3D9 || defined _XBOX
451    SetUniform(uni, vec4(f, 0, 0, 0));
452#elif !defined __CELLOS_LV2__
453    glUniform1f(uni.frag, f);
454#else
455    if (uni.frag)
456        cgGLSetParameter1f((CGparameter)uni.frag, f);
457    if (uni.vert)
458        cgGLSetParameter1f((CGparameter)uni.vert, f);
459#endif
460}
461
462void Shader::SetUniform(ShaderUniform const &uni, vec2 const &v)
463{
464#if defined USE_D3D9 || defined _XBOX
465    SetUniform(uni, vec4(v, 0, 0));
466#elif !defined __CELLOS_LV2__
467    glUniform2fv(uni.frag, 1, &v[0]);
468#else
469    if (uni.frag)
470        cgGLSetParameter2fv((CGparameter)uni.frag, &v[0]);
471    if (uni.vert)
472        cgGLSetParameter2fv((CGparameter)uni.vert, &v[0]);
473#endif
474}
475
476void Shader::SetUniform(ShaderUniform const &uni, vec3 const &v)
477{
478#if defined USE_D3D9 || defined _XBOX
479    SetUniform(uni, vec4(v, 0));
480#elif !defined __CELLOS_LV2__
481    glUniform3fv(uni.frag, 1, &v[0]);
482#else
483    if (uni.frag)
484        cgGLSetParameter3fv((CGparameter)uni.frag, &v[0]);
485    if (uni.vert)
486        cgGLSetParameter3fv((CGparameter)uni.vert, &v[0]);
487#endif
488}
489
490void Shader::SetUniform(ShaderUniform const &uni, vec4 const &v)
491{
492#if defined USE_D3D9 || defined _XBOX
493    if (uni.flags & 1)
494        data->m_dev->SetPixelShaderConstantF((UINT)uni.frag, &v[0], 1);
495    if (uni.flags & 2)
496        data->m_dev->SetVertexShaderConstantF((UINT)uni.vert, &v[0], 1);
497#elif !defined __CELLOS_LV2__
498    glUniform4fv(uni.frag, 1, &v[0]);
499#else
500    if (uni.frag)
501        cgGLSetParameter4fv((CGparameter)uni.frag, &v[0]);
502    if (uni.vert)
503        cgGLSetParameter4fv((CGparameter)uni.vert, &v[0]);
504#endif
505}
506
507void Shader::SetUniform(ShaderUniform const &uni, mat2 const &m)
508{
509#if defined USE_D3D9 || defined _XBOX
510    /* FIXME: do we need padding here like for the mat3 version? */
511    if (uni.flags & 1)
512        data->m_dev->SetPixelShaderConstantF((UINT)uni.frag, &m[0][0], 1);
513    if (uni.flags & 2)
514        data->m_dev->SetVertexShaderConstantF((UINT)uni.vert, &m[0][0], 1);
515#elif !defined __CELLOS_LV2__
516    glUniformMatrix2fv(uni.frag, 1, GL_FALSE, &m[0][0]);
517#else
518    mat4 tmp(m, 1.0f, 1.0f);
519    if (uni.frag)
520        cgGLSetMatrixParameterfc((CGparameter)uni.frag, &m[0][0]);
521    if (uni.vert)
522        cgGLSetMatrixParameterfc((CGparameter)uni.vert, &m[0][0]);
523#endif
524}
525
526void Shader::SetUniform(ShaderUniform const &uni, mat3 const &m)
527{
528#if defined USE_D3D9 || defined _XBOX
529    /* Padding matrix columns is necessary on DirectX. We need to create
530     * a new data structure; a 4×4 matrix will do. */
531    mat4 tmp(m, 1.0f);
532    if (uni.flags & 1)
533        data->m_dev->SetPixelShaderConstantF((UINT)uni.frag, &tmp[0][0], 3);
534    if (uni.flags & 2)
535        data->m_dev->SetVertexShaderConstantF((UINT)uni.vert, &tmp[0][0], 3);
536#elif !defined __CELLOS_LV2__
537    glUniformMatrix3fv(uni.frag, 1, GL_FALSE, &m[0][0]);
538#else
539    /* FIXME: check it's the proper way to do this */
540    mat4 tmp(m, 1.0f);
541    if (uni.frag)
542        cgGLSetMatrixParameterfc((CGparameter)uni.frag, &m[0][0]);
543    if (uni.vert)
544        cgGLSetMatrixParameterfc((CGparameter)uni.vert, &m[0][0]);
545#endif
546}
547
548void Shader::SetUniform(ShaderUniform const &uni, mat4 const &m)
549{
550#if defined USE_D3D9 || defined _XBOX
551    if (uni.flags & 1)
552        data->m_dev->SetPixelShaderConstantF((UINT)uni.frag, &m[0][0], 4);
553    if (uni.flags & 2)
554        data->m_dev->SetVertexShaderConstantF((UINT)uni.vert, &m[0][0], 4);
555#elif !defined __CELLOS_LV2__
556    glUniformMatrix4fv(uni.frag, 1, GL_FALSE, &m[0][0]);
557#else
558    if (uni.frag)
559        cgGLSetMatrixParameterfc((CGparameter)uni.frag, &m[0][0]);
560    if (uni.vert)
561        cgGLSetMatrixParameterfc((CGparameter)uni.vert, &m[0][0]);
562#endif
563}
564
565void Shader::SetUniform(ShaderUniform const &uni, ShaderTexture tex, int index)
566{
567#if defined USE_D3D9 || defined _XBOX
568    data->m_dev->SetTexture(index, (LPDIRECT3DTEXTURE9)tex.m_flags);
569    data->m_dev->SetSamplerState(index, D3DSAMP_MAGFILTER, tex.m_attrib & 0xff);
570    data->m_dev->SetSamplerState(index, D3DSAMP_MINFILTER, (tex.m_attrib >> 8) & 0xff);
571    data->m_dev->SetSamplerState(index, D3DSAMP_MIPFILTER, (tex.m_attrib >> 16) & 0xff);
572#elif !defined __CELLOS_LV2__
573    glActiveTexture(GL_TEXTURE0 + index);
574    //glEnable(GL_TEXTURE_2D);
575    glBindTexture(GL_TEXTURE_2D, (int)tex.m_flags);
576    SetUniform(uni, index);
577#else
578    /* FIXME: unimplemented */
579#endif
580}
581
582/*
583 * Uniform setters for arrays
584 */
585
586void Shader::SetUniform(ShaderUniform const &uni, Array<float> const &v)
587{
588#if defined USE_D3D9 || defined _XBOX
589    /* FIXME: this will not work properly because we don't know how tell DX9
590     * it's a bunch of floats instead of vec4. */
591    if (uni.flags & 1)
592        data->m_dev->SetPixelShaderConstantF((UINT)uni.frag,
593                                             &v[0], v.Count() / 4);
594    if (uni.flags & 2)
595        data->m_dev->SetVertexShaderConstantF((UINT)uni.vert,
596                                              &v[0], v.Count() / 4);
597#elif !defined __CELLOS_LV2__
598    glUniform1fv(uni.frag, v.Count(), &v[0]);
599#else
600    if (uni.frag)
601        cgGLSetParameterArray1f((CGparameter)uni.frag,
602                                0, v.Count(), &v[0]);
603    if (uni.vert)
604        cgGLSetParameterArray1f((CGparameter)uni.vert,
605                                0, v.Count(), &v[0]);
606#endif
607}
608
609void Shader::SetUniform(ShaderUniform const &uni, Array<vec2> const &v)
610{
611#if defined USE_D3D9 || defined _XBOX
612    /* FIXME: this will not work properly because we don't know how tell DX9
613     * it's a bunch of vec2 instead of vec4. */
614    if (uni.flags & 1)
615        data->m_dev->SetPixelShaderConstantF((UINT)uni.frag,
616                                             &v[0][0], v.Count() / 2);
617    if (uni.flags & 2)
618        data->m_dev->SetVertexShaderConstantF((UINT)uni.vert,
619                                              &v[0][0], v.Count() / 2);
620#elif !defined __CELLOS_LV2__
621    glUniform2fv(uni.frag, v.Count(), &v[0][0]);
622#else
623    if (uni.frag)
624        cgGLSetParameterArray2f((CGparameter)uni.frag,
625                                0, v.Count(), &v[0][0]);
626    if (uni.vert)
627        cgGLSetParameterArray2f((CGparameter)uni.vert,
628                                0, v.Count(), &v[0][0]);
629#endif
630}
631
632void Shader::SetUniform(ShaderUniform const &uni, Array<vec3> const &v)
633{
634#if defined USE_D3D9 || defined _XBOX
635    /* FIXME: this will not work properly because we don't know how tell DX9
636     * it's a bunch of vec3 instead of vec4. */
637    if (uni.flags & 1)
638        data->m_dev->SetPixelShaderConstantF((UINT)uni.frag,
639                                             &v[0][0], v.Count());
640    if (uni.flags & 2)
641        data->m_dev->SetVertexShaderConstantF((UINT)uni.vert,
642                                              &v[0][0], v.Count());
643#elif !defined __CELLOS_LV2__
644    glUniform3fv(uni.frag, v.Count(), &v[0][0]);
645#else
646    if (uni.frag)
647        cgGLSetParameterArray3f((CGparameter)uni.frag,
648                                0, v.Count(), &v[0][0]);
649    if (uni.vert)
650        cgGLSetParameterArray3f((CGparameter)uni.vert,
651                                0, v.Count(), &v[0][0]);
652#endif
653}
654
655void Shader::SetUniform(ShaderUniform const &uni, Array<vec4> const &v)
656{
657#if defined USE_D3D9 || defined _XBOX
658    if (uni.flags & 1)
659        data->m_dev->SetPixelShaderConstantF((UINT)uni.frag,
660                                             &v[0][0], v.Count());
661    if (uni.flags & 2)
662        data->m_dev->SetVertexShaderConstantF((UINT)uni.vert,
663                                              &v[0][0], v.Count());
664#elif !defined __CELLOS_LV2__
665    glUniform4fv(uni.frag, v.Count(), &v[0][0]);
666#else
667    if (uni.frag)
668        cgGLSetParameterArray4f((CGparameter)uni.frag,
669                                0, v.Count(), &v[0][0]);
670    if (uni.vert)
671        cgGLSetParameterArray4f((CGparameter)uni.vert,
672                                0, v.Count(), &v[0][0]);
673#endif
674}
675
676void Shader::Bind() const
677{
678#if defined USE_D3D9 || defined _XBOX
679    HRESULT hr;
680    hr = data->m_dev->SetVertexShader(data->vert_shader);
681    hr = data->m_dev->SetPixelShader(data->frag_shader);
682#elif !defined __CELLOS_LV2__
683    glUseProgram(data->prog_id);
684#else
685    cgGLEnableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));
686    cgGLBindProgram(data->vert_id);
687    cgGLEnableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));
688    cgGLBindProgram(data->frag_id);
689#endif
690}
691
692void Shader::Unbind() const
693{
694#if defined USE_D3D9 || defined _XBOX
695    HRESULT hr;
696    hr = data->m_dev->SetVertexShader(nullptr);
697    hr = data->m_dev->SetPixelShader(nullptr);
698#elif !defined __CELLOS_LV2__
699    /* FIXME: untested */
700    glUseProgram(0);
701#else
702    /* FIXME: untested */
703    cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));
704    cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));
705#endif
706}
707
708Shader::~Shader()
709{
710#if defined USE_D3D9 || defined _XBOX
711    data->vert_shader->Release();
712    data->vert_table->Release();
713    data->frag_shader->Release();
714    data->frag_table->Release();
715#elif !defined __CELLOS_LV2__
716    glDetachShader(data->prog_id, data->vert_id);
717    glDetachShader(data->prog_id, data->frag_id);
718    glDeleteShader(data->vert_id);
719    glDeleteShader(data->frag_id);
720    glDeleteProgram(data->prog_id);
721#else
722    cgDestroyProgram(data->vert_id);
723    cgDestroyProgram(data->frag_id);
724#endif
725    delete data;
726}
727
728/* Try to detect shader compiler features */
729int ShaderData::GetVersion()
730{
731    static int version = 0;
732
733#if !defined USE_D3D9 && !defined _XBOX && !defined __CELLOS_LV2__
734    if (!version)
735    {
736#if defined HAVE_GLES_2X
737        /* GLES 2.x supports #version 100, that's all. */
738        return 100;
739#else
740        char buf[4096];
741        GLsizei len;
742
743        int id = glCreateShader(GL_VERTEX_SHADER);
744
745        /* Can we compile 1.30 shaders? */
746        char const *test130 =
747            "#version 130\n"
748            "void main() { gl_Position = vec4(0.0, 0.0, 0.0, 0.0); }";
749        glShaderSource(id, 1, &test130, nullptr);
750        glCompileShader(id);
751        glGetShaderInfoLog(id, sizeof(buf), &len, buf);
752        if (len <= 0)
753            version = 130;
754
755        /* If not, can we compile 1.20 shaders? */
756        if (!version)
757        {
758            char const *test120 =
759                "#version 120\n"
760                "void main() { gl_Position = vec4(0.0, 0.0, 0.0, 0.0); }";
761            glShaderSource(id, 1, &test120, nullptr);
762            glCompileShader(id);
763            glGetShaderInfoLog(id, sizeof(buf), &len, buf);
764            if (len <= 0)
765                version = 120;
766        }
767
768        /* Otherwise, assume we can compile 1.10 shaders. */
769        if (!version)
770            version = 110;
771
772        glDeleteShader(id);
773#endif
774    }
775#endif
776
777    return version;
778}
779
780/* Simple shader source patching for old GLSL versions.
781 */
782void ShaderData::Patch(char *dst, char const *vert, char const *frag)
783{
784    int ver_driver = GetVersion();
785
786    strcpy(dst, vert ? vert : frag);
787    if (ver_driver >= 130)
788        return;
789
790    int ver_shader = 110;
791    char *parser = strstr(dst, "#version");
792    if (parser)
793        ver_shader = atoi(parser + strlen("#version"));
794
795    /* This is GL ES, we only know version 100. */
796    if (ver_shader > 100 && ver_driver == 100)
797    {
798        /* FIXME: this isn't elegant but honestly, we don't care, this
799         * whole file is going to die soon. */
800        char *p = strstr(dst, "#version");
801        if (p)
802        {
803            p += 8;
804            while (*p == ' ')
805                p++;
806            if (p[0] == '1' && p[1] && p[2])
807                p[1] = p[2] = '0';
808        }
809    }
810
811    if (ver_shader > 120 && ver_driver <= 120)
812    {
813        char const *end = dst + strlen(dst) + 1;
814
815        /* Find main() */
816        parser = strstr(dst, "main");
817        if (!parser) return;
818        parser = strstr(parser, "(");
819        if (!parser) return;
820        parser = strstr(parser, ")");
821        if (!parser) return;
822        parser = strstr(parser, "{");
823        if (!parser) return;
824        char *main = parser + 1;
825
826        /* Perform main() replaces */
827        char const * const main_replaces[] =
828        {
829#if 0
830            "in vec2 in_Vertex;", "vec2 in_Vertex = gl_Vertex.xy;",
831            "in vec3 in_Vertex;", "vec3 in_Vertex = gl_Vertex.xyz;",
832            "in vec4 in_Vertex;", "vec4 in_Vertex = gl_Vertex.xyzw;",
833
834            "in vec2 in_Color;", "vec2 in_Color = gl_Color.xy;",
835            "in vec3 in_Color;", "vec3 in_Color = gl_Color.xyz;",
836            "in vec4 in_Color;", "vec4 in_Color = gl_Color.xyzw;",
837
838            "in vec2 in_MultiTexCoord0;",
839               "vec2 in_MultiTexCoord0 = gl_MultiTexCoord0.xy;",
840            "in vec2 in_MultiTexCoord1;",
841               "vec2 in_MultiTexCoord1 = gl_MultiTexCoord1.xy;",
842            "in vec2 in_MultiTexCoord2;",
843               "vec2 in_MultiTexCoord2 = gl_MultiTexCoord2.xy;",
844            "in vec2 in_MultiTexCoord3;",
845               "vec2 in_MultiTexCoord3 = gl_MultiTexCoord3.xy;",
846            "in vec2 in_MultiTexCoord4;",
847               "vec2 in_MultiTexCoord4 = gl_MultiTexCoord4.xy;",
848            "in vec2 in_MultiTexCoord5;",
849               "vec2 in_MultiTexCoord5 = gl_MultiTexCoord5.xy;",
850            "in vec2 in_MultiTexCoord6;",
851               "vec2 in_MultiTexCoord6 = gl_MultiTexCoord6.xy;",
852            "in vec2 in_MultiTexCoord7;",
853               "vec2 in_MultiTexCoord7 = gl_MultiTexCoord7.xy;",
854#endif
855
856            nullptr
857        };
858
859        for (char const * const *rep = main_replaces; rep[0]; rep += 2)
860        {
861            char *match = strstr(dst, rep[0]);
862            if (match && match < main)
863            {
864                size_t l0 = strlen(rep[0]);
865                size_t l1 = strlen(rep[1]);
866                memmove(main + l1, main, end - main);
867                memcpy(main, rep[1], l1);
868                memset(match, ' ', l0);
869                main += l1;
870                end += l1;
871            }
872        }
873
874        /* Perform small replaces */
875        char const * const fast_replaces[] =
876        {
877            "#version 130", "#version 120",
878            "in vec2", vert ? "attribute vec2" : "varying vec2",
879            "in vec3", vert ? "attribute vec3" : "varying vec3",
880            "in vec4", vert ? "attribute vec4" : "varying vec4",
881            "in mat4", vert ? "attribute mat4" : "varying mat4",
882            "out vec2", "varying vec2",
883            "out vec3", "varying vec3",
884            "out vec4", "varying vec4",
885            "out mat4", "varying mat4",
886            nullptr
887        };
888
889        for (char const * const *rep = fast_replaces; rep[0]; rep += 2)
890        {
891            char *match;
892            while ((match = strstr(dst, rep[0])))
893            {
894                size_t l0 = strlen(rep[0]);
895                size_t l1 = strlen(rep[1]);
896
897                if (l1 > l0)
898                    memmove(match + l1, match + l0, (end - match) - l0);
899                memcpy(match, rep[1], l1);
900                if (l1 < l0)
901                    memset(match + l0, ' ', l1 - l0);
902                end += l1 - l0;
903            }
904        }
905    }
906}
907
908} /* namespace lol */
909
Note: See TracBrowser for help on using the repository browser.