|
|
MDL Reading Example
Cornell University Program of Computer Graphics |
|
||||
|
Suppose you had the folowing text mdl file:
mdlflA20 sphr "red sphere" lmbrtn rgb 0.8 0.2 0.2 end end 0.0 0.0 0.0 1.0 % center,radius end You could read this file with the following code:
FILE *fp = fopen("red_sphere.mdla");
mdlInput inp(fp);
mdlKey k;
char *s;
float r, g, b;
float rgb[3];
k = inp.BeginChunk(); // k == "sphr"
s = inp.ReadString();
k = inp.BeginChunk(); // k == "lmbrtn"
k = inp.BeginChunk(); // k == "rgb"
r = inp.ReadFloat();
g = inp.ReadFloat();
b = inp.ReadFloat();
inp.EndChunk();
inp.EndChunk();
inp.ReadFloats(xyz, 3);
inp.EndChunk(); // You don't always have to read everything
Of course, any real code would use the keywords returned to decide what to read next. Usually one would have a switch statement that looks like this:
// Read a geometric object
mdlKey k = inp.BeginChunk();
if (k == mdlKey("sphr")) {
// Read a string, a material chunk, and four floats
}
else if (k == mdlKey("msh")) {
// Read a string and a material, then do a lot of work
}
...
else {
cerr << "I'm ignoring a chunk with the unrecognized keyword '" << k << "'." << endl;
}
inp.EndChunk();
When possible, it is preferable to have a function table whose use looks something like this:
// Read a color chunk mdlKey k = inp.BeginChunk(); (colorChunkReaders[k])(inp); inp.EndChunk();
It is recommended that the function which begins a chunk ends the chunk,
since mismatching the
| ||||||
| ||||||