-
Notifications
You must be signed in to change notification settings - Fork 347
Expand file tree
/
Copy pathTextureBuilder.cpp
More file actions
274 lines (245 loc) · 9.92 KB
/
Copy pathTextureBuilder.cpp
File metadata and controls
274 lines (245 loc) · 9.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/**
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "TextureBuilder.hpp"
#include <stb_image.h>
#include <stb_image_write.h>
#include <utils/File_Utils.hpp>
#include <utils/Image_Utils.hpp>
#include <utils/String_Utils.hpp>
#include <gltf/properties/ImageData.hpp>
#include <gltf/properties/TextureData.hpp>
// keep track of some texture data as we load them
struct TexInfo {
explicit TexInfo(int rawTexIx) : rawTexIx(rawTexIx) {}
const int rawTexIx;
int width{};
int height{};
int channels{};
uint8_t* pixels{};
};
std::shared_ptr<TextureData> TextureBuilder::combine(
const std::vector<int>& ixVec,
const std::string& tag,
const pixel_merger& computePixel,
bool includeAlphaChannel) {
const std::string key = texIndicesKey(ixVec, tag);
auto iter = textureByIndicesKey.find(key);
if (iter != textureByIndicesKey.end()) {
return iter->second;
}
int width = -1, height = -1;
std::string mergedFilename = tag;
std::vector<TexInfo> texes{};
for (const int rawTexIx : ixVec) {
TexInfo info(rawTexIx);
if (rawTexIx >= 0) {
const RawTexture& rawTex = raw.GetTexture(rawTexIx);
const std::string& fileLoc = rawTex.fileLocation;
const std::string& name = FileUtils::GetFileBase(FileUtils::GetFileName(fileLoc));
if (!fileLoc.empty()) {
info.pixels = stbi_load(fileLoc.c_str(), &info.width, &info.height, &info.channels, 0);
if (!info.pixels) {
fmt::printf("Warning: merge texture [%d](%s) could not be loaded.\n", rawTexIx, name);
} else {
if (width < 0) {
width = info.width;
height = info.height;
} else if (width != info.width || height != info.height) {
fmt::printf(
"Warning: texture %s (%d, %d) can't be merged with previous texture(s) of dimension (%d, %d)\n",
name,
info.width,
info.height,
width,
height);
// this is bad enough that we abort the whole merge
return nullptr;
}
mergedFilename += "_" + name;
}
}
}
texes.push_back(info);
}
// at the moment, the best choice of filename is also the best choice of name
const std::string mergedName = mergedFilename;
if (width < 0) {
// no textures to merge; bail
return nullptr;
}
// TODO: which channel combinations make sense in input files?
// write 3 or 4 channels depending on whether or not we need transparency
int channels = includeAlphaChannel ? 4 : 3;
std::vector<uint8_t> mergedPixels(static_cast<size_t>(channels * width * height));
for (int xx = 0; xx < width; xx++) {
for (int yy = 0; yy < height; yy++) {
std::vector<pixel> pixels(texes.size());
std::vector<const pixel*> pixelPointers(texes.size(), nullptr);
for (int jj = 0; jj < texes.size(); jj++) {
const TexInfo& tex = texes[jj];
// each texture's structure will depend on its channel count
int ii = tex.channels * (xx + yy * width);
int kk = 0;
if (tex.pixels != nullptr) {
for (; kk < tex.channels; kk++) {
pixels[jj][kk] = tex.pixels[ii++] / 255.0f;
}
}
for (; kk < pixels[jj].size(); kk++) {
pixels[jj][kk] = 1.0f;
}
pixelPointers[jj] = &pixels[jj];
}
const pixel merged = computePixel(pixelPointers);
int ii = channels * (xx + yy * width);
for (int jj = 0; jj < channels; jj++) {
mergedPixels[ii + jj] = static_cast<uint8_t>(fmax(0, fmin(255.0f, merged[jj] * 255.0f)));
}
}
}
// write a .png iff we need transparency in the destination texture
bool png = includeAlphaChannel;
std::vector<char> imgBuffer;
int res;
if (png) {
res = stbi_write_png_to_func(
WriteToVectorContext,
&imgBuffer,
width,
height,
channels,
mergedPixels.data(),
width * channels);
} else {
res = stbi_write_jpg_to_func(
WriteToVectorContext, &imgBuffer, width, height, channels, mergedPixels.data(), 80);
}
if (!res) {
fmt::printf("Warning: failed to generate merge texture '%s'.\n", mergedFilename);
return nullptr;
}
ImageData* image;
if (options.outputBinary) {
const auto bufferView =
gltf.AddRawBufferView(*gltf.defaultBuffer, imgBuffer.data(), to_uint32(imgBuffer.size()));
image = new ImageData(mergedName, *bufferView, png ? "image/png" : "image/jpeg");
} else {
const std::string imageFilename = mergedFilename + (png ? ".png" : ".jpg");
const std::string imagePath = outputFolder + imageFilename;
FILE* fp = fopen(imagePath.c_str(), "wb");
if (fp == nullptr) {
fmt::printf("Warning:: Couldn't write file '%s' for writing.\n", imagePath);
return nullptr;
}
if (fwrite(imgBuffer.data(), imgBuffer.size(), 1, fp) != 1) {
fmt::printf(
"Warning: Failed to write %lu bytes to file '%s'.\n", imgBuffer.size(), imagePath);
fclose(fp);
return nullptr;
}
fclose(fp);
if (verboseOutput) {
fmt::printf("Wrote %lu bytes to texture '%s'.\n", imgBuffer.size(), imagePath);
}
image = new ImageData(mergedName, imageFilename);
}
std::shared_ptr<TextureData> texDat = gltf.textures.hold(
new TextureData(mergedName, *gltf.defaultSampler, *gltf.images.hold(image)));
textureByIndicesKey.insert(std::make_pair(key, texDat));
return texDat;
}
/** Create a new TextureData for the given RawTexture index, or return a previously created one. */
std::shared_ptr<TextureData> TextureBuilder::simple(int rawTexIndex, const std::string& tag) {
const std::string key = texIndicesKey({rawTexIndex}, tag);
auto iter = textureByIndicesKey.find(key);
if (iter != textureByIndicesKey.end()) {
return iter->second;
}
RawTexture rawTexture = raw.GetTexture(rawTexIndex);
std::string textureName = FileUtils::GetFileBase(rawTexture.name);
std::string relativeFilename = FileUtils::GetFileName(rawTexture.fileLocation);
auto suffix = FileUtils::GetFileSuffix(rawTexture.fileLocation);
//TGAs are not supported by GLTF spec, convert to PNG
if(suffix.has_value() && suffix->compare("tga")==0) {
std::string tmpFolder;
if(outputFolder.empty())
tmpFolder = "./convertedTextures";
else
tmpFolder = outputFolder+"/convertedTextures";
//Check for existence of ImageMagick convert binary in path
if(std::system("convert -version")!=0) { //GAM TODO - Pipe to /dev/null or NUL to avoid console spew (also should check the output to make sure its really ImageMagick)
fmt::printf("Warning: Failed to find installed version of ImageMagick 'convert'. TGA conversion requires ImageMagick (https://imagemagick.org/) installation in system path)\n");
//If we can't find convert set the file path to empty string, so next step will fail and set to error texture
rawTexture.fileLocation = "";
rawTexture.name = "";
} else {
//Ensure output folder exists
std::string mkdirCmd = "mkdir -p "+tmpFolder;
std::system(mkdirCmd.c_str());
std::string baseName= FileUtils::GetFileBase(relativeFilename);
std::string tmpPath = tmpFolder+"/"+baseName+".png";
std::string cmdStr = "convert \""+rawTexture.fileLocation+"\" \""+tmpPath+"\"";//GAM TODO - Pipe to /dev/null or NUL to avoid console spew
auto res = std::system(cmdStr.c_str());
if(res==0) {
rawTexture.fileLocation = tmpPath;
rawTexture.name = baseName+".png";
if (verboseOutput) {
fmt::printf("Converted TGA texture '%s' to output folder: %s\n", rawTexture.fileLocation, tmpPath);
}
} else {
//If we fail, set the file path to empty string, so next step will fail and set to error texture
fmt::printf("Warning: Failed to convert TGA:%s to %s\n", rawTexture.fileLocation, tmpPath);
rawTexture.fileLocation = "";
rawTexture.name = "";
}
}
//Update the texture details
textureName = FileUtils::GetFileBase(rawTexture.name);
relativeFilename = FileUtils::GetFileName(rawTexture.fileLocation);
suffix = FileUtils::GetFileSuffix(rawTexture.fileLocation);
}
ImageData* image = nullptr;
if (options.outputBinary) {
auto bufferView = gltf.AddBufferViewForFile(*gltf.defaultBuffer, rawTexture.fileLocation);
if (bufferView) {
std::string mimeType;
if (suffix) {
mimeType = ImageUtils::suffixToMimeType(suffix.value());
} else {
mimeType = "image/jpeg";
fmt::printf(
"Warning: Can't deduce mime type of texture '%s'; using %s.\n",
rawTexture.fileLocation,
mimeType);
}
image = new ImageData(relativeFilename, *bufferView, mimeType);
}
} else if (!relativeFilename.empty()) {
image = new ImageData(relativeFilename, relativeFilename);
std::string outputPath = outputFolder + "/" + relativeFilename;
if (FileUtils::CopyFile(rawTexture.fileLocation, outputPath, true)) {
if (verboseOutput) {
fmt::printf("Copied texture '%s' to output folder: %s\n", textureName, outputPath);
}
} else {
// no point commenting further on read/write error; CopyFile() does enough of that, and we
// certainly want to to add an image struct to the glTF JSON, with the correct relative path
// reference, even if the copy failed.
}
}
if (!image) {
// fallback is tiny transparent PNG
image = new ImageData(
textureName,
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==");
}
std::shared_ptr<TextureData> texDat = gltf.textures.hold(
new TextureData(textureName, *gltf.defaultSampler, *gltf.images.hold(image)));
textureByIndicesKey.insert(std::make_pair(key, texDat));
return texDat;
}