HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
TextureBaker.h
Go to the documentation of this file.
1 //
2 // Copyright Contributors to the MaterialX Project
3 // SPDX-License-Identifier: Apache-2.0
4 //
5 
6 #ifndef MATERIALX_TEXTUREBAKER
7 #define MATERIALX_TEXTUREBAKER
8 
9 /// @file
10 /// Texture baking functionality
11 
12 #include <iostream>
13 
14 #include <MaterialXCore/Unit.h>
15 
16 #include <MaterialXRender/Export.h>
17 #include <MaterialXFormat/File.h>
20 
22 
23 /// A vector of baked documents with their associated names.
24 using BakedDocumentVec = std::vector<std::pair<std::string, DocumentPtr>>;
25 
26 /// @class TextureBaker
27 /// A helper class for baking procedural material content to textures.
28 /// TODO: Add support for graphs containing geometric nodes such as position
29 /// and normal.
30 template <typename Renderer, typename ShaderGen>
31 class TextureBaker : public Renderer
32 {
33  public:
34  /// Set the file extension for baked textures.
35  void setExtension(const string& extension)
36  {
38  }
39 
40  /// Return the file extension for baked textures.
41  const string& getExtension() const
42  {
43  return _extension;
44  }
45 
46  /// Set the color space in which color textures are encoded.
47  ///
48  /// By default, this color space is srgb_texture, and color inputs are
49  /// automatically transformed to this space by the baker. If another color
50  /// space is set, then the input graph is responsible for transforming
51  /// colors to this space.
52  void setColorSpace(const string& colorSpace)
53  {
54  _colorSpace = colorSpace;
55  }
56 
57  /// Return the color space in which color textures are encoded.
58  const string& getColorSpace() const
59  {
60  return _colorSpace;
61  }
62 
63  /// Set the distance unit to which textures are baked. Defaults to meters.
64  void setDistanceUnit(const string& unitSpace)
65  {
66  _distanceUnit = unitSpace;
67  }
68 
69  /// Return the distance unit to which textures are baked.
70  const string& getDistanceUnit() const
71  {
72  return _distanceUnit;
73  }
74 
75  /// Set whether images should be averaged to generate constants. Defaults to false.
76  void setAverageImages(bool enable)
77  {
78  _averageImages = enable;
79  }
80 
81  /// Return whether images should be averaged to generate constants.
82  bool getAverageImages() const
83  {
84  return _averageImages;
85  }
86 
87  /// Set whether uniform textures should be stored as constants. Defaults to true.
88  void setOptimizeConstants(bool enable)
89  {
90  _optimizeConstants = enable;
91  }
92 
93  /// Return whether uniform textures should be stored as constants.
94  bool getOptimizeConstants() const
95  {
96  return _optimizeConstants;
97  }
98 
99  /// Set the output location for baked texture images. Defaults to the root folder
100  /// of the destination material.
101  void setOutputImagePath(const FilePath& outputImagePath)
102  {
103  _outputImagePath = outputImagePath;
104  }
105 
106  /// Get the current output location for baked texture images.
108  {
109  return _outputImagePath;
110  }
111 
112  /// Set the name of the baked graph element.
113  void setBakedGraphName(const string& name)
114  {
116  }
117 
118  /// Return the name of the baked graph element.
119  const string& getBakedGraphName() const
120  {
121  return _bakedGraphName;
122  }
123 
124  /// Set the name of the baked geometry info element.
125  void setBakedGeomInfoName(const string& name)
126  {
128  }
129 
130  /// Return the name of the baked geometry info element.
131  const string& getBakedGeomInfoName() const
132  {
133  return _bakedGeomInfoName;
134  }
135 
136  /// Get the texture filename template.
137  const string& getTextureFilenameTemplate() const
138  {
140  }
141 
142  /// Set the texture filename template.
143  void setTextureFilenameTemplate(const string& filenameTemplate)
144  {
145  _textureFilenameTemplate = (filenameTemplate.find("$EXTENSION") == string::npos) ?
146  filenameTemplate + ".$EXTENSION" : filenameTemplate;
147  }
148 
149  /// Set texFilenameOverrides if template variable exists.
150  void setFilenameTemplateVarOverride(const string& key, const string& value)
151  {
152  if (_permittedOverrides.count(key))
153  {
155  }
156  }
157 
158  /// Set the output stream for reporting progress and warnings. Defaults to std::cout.
159  void setOutputStream(std::ostream* outputStream)
160  {
161  _outputStream = outputStream;
162  }
163 
164  /// Return the output stream for reporting progress and warnings.
165  std::ostream* getOutputStream() const
166  {
167  return _outputStream;
168  }
169 
170  /// Set whether to create a short name for baked images by hashing the baked image filenames
171  /// This is useful for file systems which may have a maximum limit on filename size.
172  /// By default names are not hashed.
173  void setHashImageNames(bool enable)
174  {
175  _hashImageNames = enable;
176  }
177 
178  /// Return whether automatic baked texture resolution is set.
179  bool getHashImageNames() const
180  {
181  return _hashImageNames;
182  }
183 
184  /// Set the minimum texcoords used in texture baking. Defaults to 0, 0.
186  {
188  }
189 
190  /// Return the minimum texcoords used in texture baking.
192  {
193  return _textureSpaceMin;
194  }
195 
196  /// Set the maximum texcoords used in texture baking. Defaults to 1, 1.
198  {
200  }
201 
202  /// Return the maximum texcoords used in texture baking.
204  {
205  return _textureSpaceMax;
206  }
207 
208  /// Set up the unit definitions to be used in baking.
209  void setupUnitSystem(DocumentPtr unitDefinitions);
210 
211  /// Bake textures for all graph inputs of the given shader.
212  void bakeShaderInputs(NodePtr material, NodePtr shader, GenContext& context, const string& udim = EMPTY_STRING);
213 
214  /// Bake a texture for the given graph output.
215  void bakeGraphOutput(OutputPtr output, GenContext& context, const StringMap& filenameTemplateMap);
216 
217  /// Optimize baked textures before writing.
219 
220  /// Bake material to document in memory and write baked textures to disk.
221  DocumentPtr bakeMaterialToDoc(DocumentPtr doc, const FileSearchPath& searchPath, const string& materialPath,
222  const StringVec& udimSet, std::string& documentName);
223 
224  /// Bake materials in the given document and write them to disk. If multiple documents are written,
225  /// then the given output filename will be used as a template.
226  void bakeAllMaterials(DocumentPtr doc, const FileSearchPath& searchPath, const FilePath& outputFileName);
227 
228  /// Set whether to write a separate document per material when calling bakeAllMaterials.
229  /// By default separate documents are written.
231  {
233  }
234 
235  string getValueStringFromColor(const Color4& color, const string& type);
236 
237  protected:
239  {
240  public:
243  bool isUniform = false;
244  };
246  {
247  public:
249  bool isDefault = false;
250  };
251  using BakedImageVec = vector<BakedImage>;
252  using BakedImageMap = std::unordered_map<OutputPtr, BakedImageVec>;
253  using BakedConstantMap = std::unordered_map<OutputPtr, BakedConstant>;
254 
255  protected:
256  TextureBaker(unsigned int width, unsigned int height, Image::BaseType baseType, bool flipSavedImage);
257 
258  // Populate file template variable naming map
260 
261  // Find first occurence of variable in filename from start index onwards
262  size_t findVarInTemplate(const string& filename, const string& var, size_t start = 0);
263 
264  // Generate a texture filename for the given graph output.
265  FilePath generateTextureFilename(const StringMap& fileTemplateMap);
266 
267  // Create document that links shader outputs to a material.
269 
270  // Write a baked image to disk, returning true if the write was successful.
271  bool writeBakedImage(const BakedImage& baked, ImagePtr image);
272 
273  protected:
274  string _extension;
275  string _colorSpace;
283  std::ostream* _outputStream;
287 
296 
297  std::unordered_map<string, NodePtr> _worldSpaceNodes;
298 
300 
303 };
304 
306 
308 
309 #endif
string _bakedGeomInfoName
Definition: TextureBaker.h:281
void setTextureSpaceMax(const Vector2 &max)
Set the maximum texcoords used in texture baking. Defaults to 1, 1.
Definition: TextureBaker.h:197
void setColorSpace(const string &colorSpace)
Definition: TextureBaker.h:52
ConstNodePtr _material
Definition: TextureBaker.h:289
shared_ptr< Output > OutputPtr
A shared pointer to an Output.
Definition: Interface.h:36
GT_API const UT_StringHolder filename
bool getOptimizeConstants() const
Return whether uniform textures should be stored as constants.
Definition: TextureBaker.h:94
Vector2 _textureSpaceMax
Definition: TextureBaker.h:286
Definition: File.h:26
#define MATERIALX_NAMESPACE_BEGIN
Definition: Generated.h:25
void setDistanceUnit(const string &unitSpace)
Set the distance unit to which textures are baked. Defaults to meters.
Definition: TextureBaker.h:64
vector< string > StringVec
A vector of strings.
Definition: Library.h:57
bool _writeDocumentPerMaterial
Definition: TextureBaker.h:301
GLuint start
Definition: glcorearb.h:475
std::unordered_map< OutputPtr, BakedConstant > BakedConstantMap
Definition: TextureBaker.h:253
GLsizei const GLchar *const * string
Definition: glcorearb.h:814
GLsizei const GLfloat * value
Definition: glcorearb.h:824
void setAverageImages(bool enable)
Set whether images should be averaged to generate constants. Defaults to false.
Definition: TextureBaker.h:76
const string & getDistanceUnit() const
Return the distance unit to which textures are baked.
Definition: TextureBaker.h:70
void setBakedGeomInfoName(const string &name)
Set the name of the baked geometry info element.
Definition: TextureBaker.h:125
string _extension
Definition: TextureBaker.h:274
string _distanceUnit
Definition: TextureBaker.h:276
MATERIALX_NAMESPACE_BEGIN MX_CORE_API const string EMPTY_STRING
void setOutputImagePath(const FilePath &outputImagePath)
Definition: TextureBaker.h:101
bool getAverageImages() const
Return whether images should be averaged to generate constants.
Definition: TextureBaker.h:82
void setOutputStream(std::ostream *outputStream)
Set the output stream for reporting progress and warnings. Defaults to std::cout. ...
Definition: TextureBaker.h:159
shared_ptr< const Node > ConstNodePtr
A shared pointer to a const Node.
Definition: Node.h:26
const string & getBakedGraphName() const
Return the name of the baked graph element.
Definition: TextureBaker.h:119
const string & getTextureFilenameTemplate() const
Get the texture filename template.
Definition: TextureBaker.h:137
string _bakedGraphName
Definition: TextureBaker.h:280
ImageBuf OIIO_API min(Image_or_Const A, Image_or_Const B, ROI roi={}, int nthreads=0)
Vector2 getTextureSpaceMax() const
Return the maximum texcoords used in texture baking.
Definition: TextureBaker.h:203
GLenum GLenum GLsizei void * image
Definition: glad.h:5132
bool _flipSavedImage
Definition: TextureBaker.h:299
bool writeBakedImage(const BakedImage &baked, ImagePtr image)
std::vector< std::pair< std::string, DocumentPtr >> BakedDocumentVec
A vector of baked documents with their associated names.
Definition: TextureBaker.h:24
BakedImageMap _bakedImageMap
Definition: TextureBaker.h:291
string getValueStringFromColor(const Color4 &color, const string &type)
StringMap initializeFileTemplateMap(InputPtr input, NodePtr shader, const string &udim=EMPTY_STRING)
Vector2 _textureSpaceMin
Definition: TextureBaker.h:285
void bakeAllMaterials(DocumentPtr doc, const FileSearchPath &searchPath, const FilePath &outputFileName)
void writeDocumentPerMaterial(bool value)
Definition: TextureBaker.h:230
DocumentPtr _bakedTextureDoc
Definition: TextureBaker.h:302
GLint GLsizei GLsizei height
Definition: glcorearb.h:103
bool _optimizeConstants
Definition: TextureBaker.h:278
BaseType
Definition: Image.h:48
const string & getExtension() const
Return the file extension for baked textures.
Definition: TextureBaker.h:41
bool getHashImageNames() const
Return whether automatic baked texture resolution is set.
Definition: TextureBaker.h:179
const string & getColorSpace() const
Return the color space in which color textures are encoded.
Definition: TextureBaker.h:58
std::ostream * _outputStream
Definition: TextureBaker.h:283
std::ostream * getOutputStream() const
Return the output stream for reporting progress and warnings.
Definition: TextureBaker.h:165
void bakeGraphOutput(OutputPtr output, GenContext &context, const StringMap &filenameTemplateMap)
Bake a texture for the given graph output.
TextureBaker(unsigned int width, unsigned int height, Image::BaseType baseType, bool flipSavedImage)
void setExtension(const string &extension)
Set the file extension for baked textures.
Definition: TextureBaker.h:35
shared_ptr< Document > DocumentPtr
A shared pointer to a Document.
Definition: Document.h:22
Definition: Types.h:285
void setTextureSpaceMin(const Vector2 &min)
Set the minimum texcoords used in texture baking. Defaults to 0, 0.
Definition: TextureBaker.h:185
void optimizeBakedTextures(NodePtr shader)
Optimize baked textures before writing.
FilePath _outputImagePath
Definition: TextureBaker.h:279
DocumentPtr bakeMaterialToDoc(DocumentPtr doc, const FileSearchPath &searchPath, const string &materialPath, const StringVec &udimSet, std::string &documentName)
Bake material to document in memory and write baked textures to disk.
GLuint const GLchar * name
Definition: glcorearb.h:786
ImagePtr _frameCaptureImage
Definition: TextureBaker.h:290
std::unordered_map< string, NodePtr > _worldSpaceNodes
Definition: TextureBaker.h:297
shared_ptr< Input > InputPtr
A shared pointer to an Input.
Definition: Interface.h:31
size_t findVarInTemplate(const string &filename, const string &var, size_t start=0)
StringSet _permittedOverrides
Definition: TextureBaker.h:293
GLuint shader
Definition: glcorearb.h:785
FilePath generateTextureFilename(const StringMap &fileTemplateMap)
GLuint color
Definition: glcorearb.h:1261
bool _hashImageNames
Definition: TextureBaker.h:284
Vector2 getTextureSpaceMin() const
Return the minimum texcoords used in texture baking.
Definition: TextureBaker.h:191
bool _averageImages
Definition: TextureBaker.h:277
void setHashImageNames(bool enable)
Definition: TextureBaker.h:173
DocumentPtr generateNewDocumentFromShader(NodePtr shader, const StringVec &udimSet)
string _colorSpace
Definition: TextureBaker.h:275
ImageBuf OIIO_API max(Image_or_Const A, Image_or_Const B, ROI roi={}, int nthreads=0)
std::unordered_map< string, string > StringMap
An unordered map with strings as both keys and values.
Definition: Library.h:59
ShaderGeneratorPtr _generator
Definition: TextureBaker.h:288
GLint GLsizei width
Definition: glcorearb.h:103
const FilePath & getOutputImagePath()
Get the current output location for baked texture images.
Definition: TextureBaker.h:107
void setBakedGraphName(const string &name)
Set the name of the baked graph element.
Definition: TextureBaker.h:113
std::set< string > StringSet
A set of strings.
Definition: Library.h:61
void bakeShaderInputs(NodePtr material, NodePtr shader, GenContext &context, const string &udim=EMPTY_STRING)
Bake textures for all graph inputs of the given shader.
void setTextureFilenameTemplate(const string &filenameTemplate)
Set the texture filename template.
Definition: TextureBaker.h:143
Definition: core.h:1131
#define MATERIALX_NAMESPACE_END
Definition: Generated.h:26
std::unordered_map< OutputPtr, BakedImageVec > BakedImageMap
Definition: TextureBaker.h:252
void setOptimizeConstants(bool enable)
Set whether uniform textures should be stored as constants. Defaults to true.
Definition: TextureBaker.h:88
void setFilenameTemplateVarOverride(const string &key, const string &value)
Set texFilenameOverrides if template variable exists.
Definition: TextureBaker.h:150
shared_ptr< Image > ImagePtr
A shared pointer to an image.
Definition: Image.h:23
StringMap _bakedInputMap
Definition: TextureBaker.h:295
type
Definition: core.h:1059
shared_ptr< ShaderGenerator > ShaderGeneratorPtr
Shared pointer to a ShaderGenerator.
Definition: Library.h:38
void setupUnitSystem(DocumentPtr unitDefinitions)
Set up the unit definitions to be used in baking.
BakedConstantMap _bakedConstantMap
Definition: TextureBaker.h:292
string _textureFilenameTemplate
Definition: TextureBaker.h:282
OIIO_UTIL_API std::string extension(string_view filepath, bool include_dot=true) noexcept
StringMap _texTemplateOverrides
Definition: TextureBaker.h:294
const string & getBakedGeomInfoName() const
Return the name of the baked geometry info element.
Definition: TextureBaker.h:131
shared_ptr< Node > NodePtr
A shared pointer to a Node.
Definition: Node.h:24