]> git.tdb.fi Git - libs/gl.git/blobdiff - source/material.cpp
Give materials the capability to automatically create a suitable shader
[libs/gl.git] / source / material.cpp
index 8bd6e54ca51b4bf1a48d5b86c07da3fe075d76c5..ef3662e964d8be98421e6e187256b0f028daa232 100644 (file)
@@ -1,21 +1,59 @@
+#include <msp/core/hash.h>
+#include <msp/strings/format.h>
 #include "basicmaterial.h"
 #include "gl.h"
 #include "resources.h"
 #include "texturing.h"
+#include "uniform.h"
 
 using namespace std;
 
 namespace Msp {
 namespace GL {
 
+Program *Material::create_compatible_shader() const
+{
+       return new Program(create_program_source());
+}
+
+const Program *Material::create_compatible_shader(DataFile::Collection &coll) const
+{
+       string source = create_program_source();
+       string name = format("_material_%016x.glsl", hash64(source));
+       Program *shprog = coll.find<Program>(name);
+       if(shprog)
+               return shprog;
+
+       shprog = new Program(create_program_source());
+       try
+       {
+               coll.add(name, shprog);
+       }
+       catch(...)
+       {
+               delete shprog;
+               throw;
+       }
+
+       return shprog;
+}
+
 void Material::attach_texture_to(const Texture *tex, Texturing &texturing, ProgramData &tex_shdata, const string &name) const
 {
        if(!tex)
                return;
 
-       int unit = texturing.find_free_unit(name);
+       int unit = -1;
+
+       if(const Uniform *uni = tex_shdata.find_uniform(name))
+               if(const Uniform1i *uni_int = dynamic_cast<const Uniform1i *>(uni))
+                       unit = uni_int->get();
+
+       if(unit<0)
+               unit = texturing.find_free_unit(name);
        if(unit<0)
                throw runtime_error("no free texunit");
+
        texturing.attach(unit, *tex);
        tex_shdata.uniform(name, unit);
 }