]> git.tdb.fi Git - libs/gl.git/blob - source/material.cpp
Improve allocation handling in cube map textures
[libs/gl.git] / source / material.cpp
1 #include <msp/core/hash.h>
2 #include <msp/strings/format.h>
3 #include "basicmaterial.h"
4 #include "gl.h"
5 #include "pbrmaterial.h"
6 #include "resources.h"
7 #include "texturing.h"
8 #include "uniform.h"
9
10 using namespace std;
11
12 namespace Msp {
13 namespace GL {
14
15 Program *Material::create_compatible_shader() const
16 {
17         return new Program(create_program_source());
18 }
19
20 const Program *Material::create_compatible_shader(DataFile::Collection &coll) const
21 {
22         string source = create_program_source();
23         string name = format("_material_%016x.glsl", hash64(source));
24         Program *shprog = coll.find<Program>(name);
25         if(shprog)
26                 return shprog;
27
28         shprog = new Program(create_program_source());
29         try
30         {
31                 coll.add(name, shprog);
32         }
33         catch(...)
34         {
35                 delete shprog;
36                 throw;
37         }
38
39         return shprog;
40 }
41
42 void Material::attach_texture_to(const Texture *tex, Texturing &texturing, ProgramData &tex_shdata, const string &name) const
43 {
44         if(!tex)
45                 return;
46
47         int unit = -1;
48
49         if(const Uniform *uni = tex_shdata.find_uniform(name))
50                 if(const Uniform1i *uni_int = dynamic_cast<const Uniform1i *>(uni))
51                         unit = uni_int->get();
52
53         if(unit<0)
54                 unit = texturing.find_free_unit(name);
55         if(unit<0)
56                 throw runtime_error("no free texunit");
57
58         texturing.attach(unit, *tex);
59         tex_shdata.uniform(name, unit);
60 }
61
62 Material::MaterialRegistry &Material::get_material_registry()
63 {
64         static MaterialRegistry registry;
65         static bool initialized = false;
66         if(!initialized)
67         {
68                 registry.register_type<BasicMaterial>("basic");
69                 registry.register_type<PbrMaterial>("pbr");
70         }
71         return registry;
72 }
73
74
75 DataFile::Loader::ActionMap Material::GenericLoader::shared_actions;
76
77 Material::GenericLoader::GenericLoader(DataFile::Collection *c):
78         coll(c)
79 {
80         set_actions(shared_actions);
81 }
82
83 void Material::GenericLoader::init_actions()
84 {
85         get_material_registry().add_all(*this);
86 }
87
88 } // namespace GL
89 } // namespace Msp