material.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright (c) 2012-2017 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/dbartolini/crown/blob/master/LICENSE
  4. */
  5. #include "resource/material_resource.h"
  6. #include "resource/resource_manager.h"
  7. #include "resource/texture_resource.h"
  8. #include "world/material.h"
  9. #include "world/shader_manager.h"
  10. #include <bgfx/bgfx.h>
  11. namespace crown
  12. {
  13. void Material::bind(ResourceManager& rm, ShaderManager& sm, u8 view, s32 depth) const
  14. {
  15. using namespace material_resource;
  16. // Set samplers
  17. for (u32 i = 0; i < _resource->num_textures; ++i)
  18. {
  19. const TextureData* td = get_texture_data(_resource, i);
  20. const TextureHandle* th = get_texture_handle(_resource, i, _data);
  21. const TextureResource* teximg = (TextureResource*)rm.get(RESOURCE_TYPE_TEXTURE, td->id);
  22. bgfx::UniformHandle sampler;
  23. bgfx::TextureHandle texture;
  24. sampler.idx = th->sampler_handle;
  25. texture.idx = teximg->handle.idx;
  26. bgfx::setTexture(i
  27. , sampler
  28. , texture
  29. , sm.sampler_state(_resource->shader, td->name)
  30. );
  31. }
  32. // Set uniforms
  33. for (u32 i = 0; i < _resource->num_uniforms; ++i)
  34. {
  35. const UniformHandle* uh = get_uniform_handle(_resource, i, _data);
  36. bgfx::UniformHandle buh;
  37. buh.idx = uh->uniform_handle;
  38. bgfx::setUniform(buh, (char*)uh + sizeof(uh->uniform_handle));
  39. }
  40. sm.submit(_resource->shader, view, depth);
  41. }
  42. void Material::set_float(StringId32 name, f32 value)
  43. {
  44. char* p = (char*)material_resource::get_uniform_handle_by_name(_resource, name, _data);
  45. *(f32*)(p + sizeof(u32)) = value;
  46. }
  47. void Material::set_vector2(StringId32 name, const Vector2& value)
  48. {
  49. char* p = (char*)material_resource::get_uniform_handle_by_name(_resource, name, _data);
  50. *(Vector2*)(p + sizeof(u32)) = value;
  51. }
  52. void Material::set_vector3(StringId32 name, const Vector3& value)
  53. {
  54. char* p = (char*)material_resource::get_uniform_handle_by_name(_resource, name, _data);
  55. *(Vector3*)(p + sizeof(u32)) = value;
  56. }
  57. } // namespace crown