Added support for recording the RescaleIntecept and RescaleSlope from the dicome files and passing these values onto osgVolume::ImageLayer

This commit is contained in:
Robert Osfield 2009-09-01 10:48:32 +00:00
parent ea43bc7d52
commit 43e3089417
4 changed files with 460 additions and 318 deletions

View File

@ -91,8 +91,8 @@ struct ProcessRow
virtual ~ProcessRow() {} virtual ~ProcessRow() {}
virtual void operator() (unsigned int num, virtual void operator() (unsigned int num,
GLenum source_pixelFormat, unsigned char* source, GLenum source_pixelFormat, unsigned char* source,
GLenum dest_pixelFormat, unsigned char* dest) const GLenum dest_pixelFormat, unsigned char* dest) const
{ {
switch(source_pixelFormat) switch(source_pixelFormat)
{ {
@ -100,7 +100,7 @@ struct ProcessRow
case(GL_ALPHA): case(GL_ALPHA):
switch(dest_pixelFormat) switch(dest_pixelFormat)
{ {
case(GL_LUMINANCE): case(GL_LUMINANCE):
case(GL_ALPHA): A_to_A(num, source, dest); break; case(GL_ALPHA): A_to_A(num, source, dest); break;
case(GL_LUMINANCE_ALPHA): A_to_LA(num, source, dest); break; case(GL_LUMINANCE_ALPHA): A_to_LA(num, source, dest); break;
case(GL_RGB): A_to_RGB(num, source, dest); break; case(GL_RGB): A_to_RGB(num, source, dest); break;
@ -110,7 +110,7 @@ struct ProcessRow
case(GL_LUMINANCE_ALPHA): case(GL_LUMINANCE_ALPHA):
switch(dest_pixelFormat) switch(dest_pixelFormat)
{ {
case(GL_LUMINANCE): case(GL_LUMINANCE):
case(GL_ALPHA): LA_to_A(num, source, dest); break; case(GL_ALPHA): LA_to_A(num, source, dest); break;
case(GL_LUMINANCE_ALPHA): LA_to_LA(num, source, dest); break; case(GL_LUMINANCE_ALPHA): LA_to_LA(num, source, dest); break;
case(GL_RGB): LA_to_RGB(num, source, dest); break; case(GL_RGB): LA_to_RGB(num, source, dest); break;
@ -120,7 +120,7 @@ struct ProcessRow
case(GL_RGB): case(GL_RGB):
switch(dest_pixelFormat) switch(dest_pixelFormat)
{ {
case(GL_LUMINANCE): case(GL_LUMINANCE):
case(GL_ALPHA): RGB_to_A(num, source, dest); break; case(GL_ALPHA): RGB_to_A(num, source, dest); break;
case(GL_LUMINANCE_ALPHA): RGB_to_LA(num, source, dest); break; case(GL_LUMINANCE_ALPHA): RGB_to_LA(num, source, dest); break;
case(GL_RGB): RGB_to_RGB(num, source, dest); break; case(GL_RGB): RGB_to_RGB(num, source, dest); break;
@ -130,7 +130,7 @@ struct ProcessRow
case(GL_RGBA): case(GL_RGBA):
switch(dest_pixelFormat) switch(dest_pixelFormat)
{ {
case(GL_LUMINANCE): case(GL_LUMINANCE):
case(GL_ALPHA): RGBA_to_A(num, source, dest); break; case(GL_ALPHA): RGBA_to_A(num, source, dest); break;
case(GL_LUMINANCE_ALPHA): RGBA_to_LA(num, source, dest); break; case(GL_LUMINANCE_ALPHA): RGBA_to_LA(num, source, dest); break;
case(GL_RGB): RGBA_to_RGB(num, source, dest); break; case(GL_RGB): RGBA_to_RGB(num, source, dest); break;
@ -141,7 +141,7 @@ struct ProcessRow
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// alpha sources.. // alpha sources..
virtual void A_to_A(unsigned int num, unsigned char* source, unsigned char* dest) const virtual void A_to_A(unsigned int num, unsigned char* source, unsigned char* dest) const
{ {
for(unsigned int i=0;i<num;++i) for(unsigned int i=0;i<num;++i)
@ -158,7 +158,7 @@ struct ProcessRow
*dest++ = *source++; *dest++ = *source++;
} }
} }
virtual void A_to_RGB(unsigned int num, unsigned char* source, unsigned char* dest) const virtual void A_to_RGB(unsigned int num, unsigned char* source, unsigned char* dest) const
{ {
for(unsigned int i=0;i<num;++i) for(unsigned int i=0;i<num;++i)
@ -181,7 +181,7 @@ struct ProcessRow
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// alpha luminance sources.. // alpha luminance sources..
virtual void LA_to_A(unsigned int num, unsigned char* source, unsigned char* dest) const virtual void LA_to_A(unsigned int num, unsigned char* source, unsigned char* dest) const
{ {
for(unsigned int i=0;i<num;++i) for(unsigned int i=0;i<num;++i)
@ -199,7 +199,7 @@ struct ProcessRow
*dest++ = *source++; *dest++ = *source++;
} }
} }
virtual void LA_to_RGB(unsigned int num, unsigned char* source, unsigned char* dest) const virtual void LA_to_RGB(unsigned int num, unsigned char* source, unsigned char* dest) const
{ {
for(unsigned int i=0;i<num;++i) for(unsigned int i=0;i<num;++i)
@ -223,7 +223,7 @@ struct ProcessRow
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// RGB sources.. // RGB sources..
virtual void RGB_to_A(unsigned int num, unsigned char* source, unsigned char* dest) const virtual void RGB_to_A(unsigned int num, unsigned char* source, unsigned char* dest) const
{ {
for(unsigned int i=0;i<num;++i) for(unsigned int i=0;i<num;++i)
@ -244,7 +244,7 @@ struct ProcessRow
source += 3; source += 3;
} }
} }
virtual void RGB_to_RGB(unsigned int num, unsigned char* source, unsigned char* dest) const virtual void RGB_to_RGB(unsigned int num, unsigned char* source, unsigned char* dest) const
{ {
for(unsigned int i=0;i<num;++i) for(unsigned int i=0;i<num;++i)
@ -268,7 +268,7 @@ struct ProcessRow
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// RGBA sources.. // RGBA sources..
virtual void RGBA_to_A(unsigned int num, unsigned char* source, unsigned char* dest) const virtual void RGBA_to_A(unsigned int num, unsigned char* source, unsigned char* dest) const
{ {
for(unsigned int i=0;i<num;++i) for(unsigned int i=0;i<num;++i)
@ -288,7 +288,7 @@ struct ProcessRow
*dest++ = *source++; *dest++ = *source++;
} }
} }
virtual void RGBA_to_RGB(unsigned int num, unsigned char* source, unsigned char* dest) const virtual void RGBA_to_RGB(unsigned int num, unsigned char* source, unsigned char* dest) const
{ {
for(unsigned int i=0;i<num;++i) for(unsigned int i=0;i<num;++i)
@ -330,8 +330,8 @@ void clampToNearestValidPowerOfTwo(int& sizeX, int& sizeY, int& sizeZ, int s_max
sizeZ = r_nearestPowerOfTwo; sizeZ = r_nearestPowerOfTwo;
} }
osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow, osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow,
unsigned int numComponentsDesired, unsigned int numComponentsDesired,
int s_maximumTextureSize, int s_maximumTextureSize,
int t_maximumTextureSize, int t_maximumTextureSize,
int r_maximumTextureSize, int r_maximumTextureSize,
@ -348,11 +348,11 @@ osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow,
{ {
osg::Image* image = itr->get(); osg::Image* image = itr->get();
GLenum pixelFormat = image->getPixelFormat(); GLenum pixelFormat = image->getPixelFormat();
if (pixelFormat==GL_ALPHA || if (pixelFormat==GL_ALPHA ||
pixelFormat==GL_INTENSITY || pixelFormat==GL_INTENSITY ||
pixelFormat==GL_LUMINANCE || pixelFormat==GL_LUMINANCE ||
pixelFormat==GL_LUMINANCE_ALPHA || pixelFormat==GL_LUMINANCE_ALPHA ||
pixelFormat==GL_RGB || pixelFormat==GL_RGB ||
pixelFormat==GL_RGBA) pixelFormat==GL_RGBA)
{ {
max_s = osg::maximum(image->s(), max_s); max_s = osg::maximum(image->s(), max_s);
@ -365,9 +365,9 @@ osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow,
osg::notify(osg::NOTICE)<<"Image "<<image->getFileName()<<" has unsuitable pixel format"<< std::hex<< pixelFormat << std::dec << std::endl; osg::notify(osg::NOTICE)<<"Image "<<image->getFileName()<<" has unsuitable pixel format"<< std::hex<< pixelFormat << std::dec << std::endl;
} }
} }
if (numComponentsDesired!=0) max_components = numComponentsDesired; if (numComponentsDesired!=0) max_components = numComponentsDesired;
GLenum desiredPixelFormat = 0; GLenum desiredPixelFormat = 0;
switch(max_components) switch(max_components)
{ {
@ -387,11 +387,11 @@ osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow,
osg::notify(osg::NOTICE)<<"desiredPixelFormat = GL_RGBA" << std::endl; osg::notify(osg::NOTICE)<<"desiredPixelFormat = GL_RGBA" << std::endl;
desiredPixelFormat = GL_RGBA; desiredPixelFormat = GL_RGBA;
break; break;
} }
if (desiredPixelFormat==0) return 0; if (desiredPixelFormat==0) return 0;
// compute nearest powers of two for each axis. // compute nearest powers of two for each axis.
int s_nearestPowerOfTwo = 1; int s_nearestPowerOfTwo = 1;
int t_nearestPowerOfTwo = 1; int t_nearestPowerOfTwo = 1;
int r_nearestPowerOfTwo = 1; int r_nearestPowerOfTwo = 1;
@ -412,12 +412,12 @@ osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow,
t_nearestPowerOfTwo = max_t; t_nearestPowerOfTwo = max_t;
r_nearestPowerOfTwo = total_r; r_nearestPowerOfTwo = total_r;
} }
// now allocate the 3d texture; // now allocate the 3d texture;
osg::ref_ptr<osg::Image> image_3d = new osg::Image; osg::ref_ptr<osg::Image> image_3d = new osg::Image;
image_3d->allocateImage(s_nearestPowerOfTwo,t_nearestPowerOfTwo,r_nearestPowerOfTwo, image_3d->allocateImage(s_nearestPowerOfTwo,t_nearestPowerOfTwo,r_nearestPowerOfTwo,
desiredPixelFormat,GL_UNSIGNED_BYTE); desiredPixelFormat,GL_UNSIGNED_BYTE);
unsigned int r_offset = (total_r<r_nearestPowerOfTwo) ? r_nearestPowerOfTwo/2 - total_r/2 : 0; unsigned int r_offset = (total_r<r_nearestPowerOfTwo) ? r_nearestPowerOfTwo/2 - total_r/2 : 0;
@ -430,18 +430,18 @@ osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow,
{ {
osg::Image* image = itr->get(); osg::Image* image = itr->get();
GLenum pixelFormat = image->getPixelFormat(); GLenum pixelFormat = image->getPixelFormat();
if (pixelFormat==GL_ALPHA || if (pixelFormat==GL_ALPHA ||
pixelFormat==GL_LUMINANCE || pixelFormat==GL_LUMINANCE ||
pixelFormat==GL_INTENSITY || pixelFormat==GL_INTENSITY ||
pixelFormat==GL_LUMINANCE_ALPHA || pixelFormat==GL_LUMINANCE_ALPHA ||
pixelFormat==GL_RGB || pixelFormat==GL_RGB ||
pixelFormat==GL_RGBA) pixelFormat==GL_RGBA)
{ {
int num_r = osg::minimum(image->r(), (image_3d->r() - curr_dest_r)); int num_r = osg::minimum(image->r(), (image_3d->r() - curr_dest_r));
int num_t = osg::minimum(image->t(), image_3d->t()); int num_t = osg::minimum(image->t(), image_3d->t());
int num_s = osg::minimum(image->s(), image_3d->s()); int num_s = osg::minimum(image->s(), image_3d->s());
unsigned int s_offset_dest = (image->s()<s_nearestPowerOfTwo) ? s_nearestPowerOfTwo/2 - image->s()/2 : 0; unsigned int s_offset_dest = (image->s()<s_nearestPowerOfTwo) ? s_nearestPowerOfTwo/2 - image->s()/2 : 0;
unsigned int t_offset_dest = (image->t()<t_nearestPowerOfTwo) ? t_nearestPowerOfTwo/2 - image->t()/2 : 0; unsigned int t_offset_dest = (image->t()<t_nearestPowerOfTwo) ? t_nearestPowerOfTwo/2 - image->t()/2 : 0;
@ -456,7 +456,7 @@ osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow,
} }
} }
} }
} }
return image_3d.release(); return image_3d.release();
} }
@ -466,14 +466,14 @@ struct ScaleOperator
ScaleOperator():_scale(1.0f) {} ScaleOperator():_scale(1.0f) {}
ScaleOperator(float scale):_scale(scale) {} ScaleOperator(float scale):_scale(scale) {}
ScaleOperator(const ScaleOperator& so):_scale(so._scale) {} ScaleOperator(const ScaleOperator& so):_scale(so._scale) {}
ScaleOperator& operator = (const ScaleOperator& so) { _scale = so._scale; return *this; } ScaleOperator& operator = (const ScaleOperator& so) { _scale = so._scale; return *this; }
float _scale; float _scale;
inline void luminance(float& l) const { l*= _scale; } inline void luminance(float& l) const { l*= _scale; }
inline void alpha(float& a) const { a*= _scale; } inline void alpha(float& a) const { a*= _scale; }
inline void luminance_alpha(float& l,float& a) const { l*= _scale; a*= _scale; } inline void luminance_alpha(float& l,float& a) const { l*= _scale; a*= _scale; }
inline void rgb(float& r,float& g,float& b) const { r*= _scale; g*=_scale; b*=_scale; } inline void rgb(float& r,float& g,float& b) const { r*= _scale; g*=_scale; b*=_scale; }
inline void rgba(float& r,float& g,float& b,float& a) const { r*= _scale; g*=_scale; b*=_scale; a*=_scale; } inline void rgba(float& r,float& g,float& b,float& a) const { r*= _scale; g*=_scale; b*=_scale; a*=_scale; }
}; };
@ -484,10 +484,10 @@ struct RecordRowOperator
mutable std::vector<osg::Vec4> _colours; mutable std::vector<osg::Vec4> _colours;
mutable unsigned int _pos; mutable unsigned int _pos;
inline void luminance(float l) const { rgba(l,l,l,1.0f); } inline void luminance(float l) const { rgba(l,l,l,1.0f); }
inline void alpha(float a) const { rgba(1.0f,1.0f,1.0f,a); } inline void alpha(float a) const { rgba(1.0f,1.0f,1.0f,a); }
inline void luminance_alpha(float l,float a) const { rgba(l,l,l,a); } inline void luminance_alpha(float l,float a) const { rgba(l,l,l,a); }
inline void rgb(float r,float g,float b) const { rgba(r,g,b,1.0f); } inline void rgb(float r,float g,float b) const { rgba(r,g,b,1.0f); }
inline void rgba(float r,float g,float b,float a) const { _colours[_pos++].set(r,g,b,a); } inline void rgba(float r,float g,float b,float a) const { _colours[_pos++].set(r,g,b,a); }
}; };
@ -499,10 +499,10 @@ struct WriteRowOperator
std::vector<osg::Vec4> _colours; std::vector<osg::Vec4> _colours;
mutable unsigned int _pos; mutable unsigned int _pos;
inline void luminance(float& l) const { l = _colours[_pos++].r(); } inline void luminance(float& l) const { l = _colours[_pos++].r(); }
inline void alpha(float& a) const { a = _colours[_pos++].a(); } inline void alpha(float& a) const { a = _colours[_pos++].a(); }
inline void luminance_alpha(float& l,float& a) const { l = _colours[_pos].r(); a = _colours[_pos++].a(); } inline void luminance_alpha(float& l,float& a) const { l = _colours[_pos].r(); a = _colours[_pos++].a(); }
inline void rgb(float& r,float& g,float& b) const { r = _colours[_pos].r(); g = _colours[_pos].g(); b = _colours[_pos].b(); } inline void rgb(float& r,float& g,float& b) const { r = _colours[_pos].r(); g = _colours[_pos].g(); b = _colours[_pos].b(); }
inline void rgba(float& r,float& g,float& b,float& a) const { r = _colours[_pos].r(); g = _colours[_pos].g(); b = _colours[_pos].b(); a = _colours[_pos++].a(); } inline void rgba(float& r,float& g,float& b,float& a) const { r = _colours[_pos].r(); g = _colours[_pos].g(); b = _colours[_pos].b(); a = _colours[_pos++].a(); }
}; };
@ -524,20 +524,20 @@ osg::Image* readRaw(int sizeX, int sizeY, int sizeZ, int numberBytesPerComponent
return 0; return 0;
} }
GLenum dataType; GLenum dataType;
switch(numberBytesPerComponent) switch(numberBytesPerComponent)
{ {
case 1 : dataType = GL_UNSIGNED_BYTE; break; case 1 : dataType = GL_UNSIGNED_BYTE; break;
case 2 : dataType = GL_UNSIGNED_SHORT; break; case 2 : dataType = GL_UNSIGNED_SHORT; break;
case 4 : dataType = GL_UNSIGNED_INT; break; case 4 : dataType = GL_UNSIGNED_INT; break;
default : default :
osg::notify(osg::NOTICE)<<"Error: numberBytesPerComponent="<<numberBytesPerComponent<<" not supported, only 1,2 or 4 are supported."<<std::endl; osg::notify(osg::NOTICE)<<"Error: numberBytesPerComponent="<<numberBytesPerComponent<<" not supported, only 1,2 or 4 are supported."<<std::endl;
return 0; return 0;
} }
int s_maximumTextureSize=256, t_maximumTextureSize=256, r_maximumTextureSize=256; int s_maximumTextureSize=256, t_maximumTextureSize=256, r_maximumTextureSize=256;
int sizeS = sizeX; int sizeS = sizeX;
int sizeT = sizeY; int sizeT = sizeY;
int sizeR = sizeZ; int sizeR = sizeZ;
@ -545,12 +545,12 @@ osg::Image* readRaw(int sizeX, int sizeY, int sizeZ, int numberBytesPerComponent
osg::ref_ptr<osg::Image> image = new osg::Image; osg::ref_ptr<osg::Image> image = new osg::Image;
image->allocateImage(sizeS, sizeT, sizeR, pixelFormat, dataType); image->allocateImage(sizeS, sizeT, sizeR, pixelFormat, dataType);
bool endianSwap = (osg::getCpuByteOrder()==osg::BigEndian) ? (endian!="big") : (endian=="big"); bool endianSwap = (osg::getCpuByteOrder()==osg::BigEndian) ? (endian!="big") : (endian=="big");
unsigned int r_offset = (sizeZ<sizeR) ? sizeR/2 - sizeZ/2 : 0; unsigned int r_offset = (sizeZ<sizeR) ? sizeR/2 - sizeZ/2 : 0;
int offset = endianSwap ? numberBytesPerComponent : 0; int offset = endianSwap ? numberBytesPerComponent : 0;
int delta = endianSwap ? -1 : 1; int delta = endianSwap ? -1 : 1;
for(int r=0;r<sizeZ;++r) for(int r=0;r<sizeZ;++r)
@ -561,7 +561,7 @@ osg::Image* readRaw(int sizeX, int sizeY, int sizeZ, int numberBytesPerComponent
for(int s=0;s<sizeX;++s) for(int s=0;s<sizeX;++s)
{ {
if (!fin) return 0; if (!fin) return 0;
for(int c=0;c<numberOfComponents;++c) for(int c=0;c<numberOfComponents;++c)
{ {
char* ptr = data+offset; char* ptr = data+offset;
@ -582,19 +582,19 @@ osg::Image* readRaw(int sizeX, int sizeY, int sizeZ, int numberBytesPerComponent
// compute range of values // compute range of values
osg::Vec4 minValue, maxValue; osg::Vec4 minValue, maxValue;
osg::computeMinMax(image.get(), minValue, maxValue); osg::computeMinMax(image.get(), minValue, maxValue);
osg::modifyImage(image.get(),ScaleOperator(1.0f/maxValue.r())); osg::modifyImage(image.get(),ScaleOperator(1.0f/maxValue.r()));
} }
fin.close(); fin.close();
if (dataType!=GL_UNSIGNED_BYTE) if (dataType!=GL_UNSIGNED_BYTE)
{ {
// need to convert to ubyte // need to convert to ubyte
osg::ref_ptr<osg::Image> new_image = new osg::Image; osg::ref_ptr<osg::Image> new_image = new osg::Image;
new_image->allocateImage(sizeS, sizeT, sizeR, pixelFormat, GL_UNSIGNED_BYTE); new_image->allocateImage(sizeS, sizeT, sizeR, pixelFormat, GL_UNSIGNED_BYTE);
RecordRowOperator readOp(sizeS); RecordRowOperator readOp(sizeS);
WriteRowOperator writeOp; WriteRowOperator writeOp;
@ -605,26 +605,26 @@ osg::Image* readRaw(int sizeX, int sizeY, int sizeZ, int numberBytesPerComponent
// reset the indices to beginning // reset the indices to beginning
readOp._pos = 0; readOp._pos = 0;
writeOp._pos = 0; writeOp._pos = 0;
// read the pixels into readOp's _colour array // read the pixels into readOp's _colour array
osg::readRow(sizeS, pixelFormat, dataType, image->data(0,t,r), readOp); osg::readRow(sizeS, pixelFormat, dataType, image->data(0,t,r), readOp);
// pass readOp's _colour array contents over to writeOp (note this is just a pointer swap). // pass readOp's _colour array contents over to writeOp (note this is just a pointer swap).
writeOp._colours.swap(readOp._colours); writeOp._colours.swap(readOp._colours);
osg::modifyRow(sizeS, pixelFormat, GL_UNSIGNED_BYTE, new_image->data(0,t,r), writeOp); osg::modifyRow(sizeS, pixelFormat, GL_UNSIGNED_BYTE, new_image->data(0,t,r), writeOp);
// return readOp's _colour array contents back to its rightful owner. // return readOp's _colour array contents back to its rightful owner.
writeOp._colours.swap(readOp._colours); writeOp._colours.swap(readOp._colours);
} }
} }
image = new_image; image = new_image;
} }
return image.release(); return image.release();
} }
enum ColourSpaceOperation enum ColourSpaceOperation
@ -640,9 +640,9 @@ struct ModulateAlphaByLuminanceOperator
{ {
ModulateAlphaByLuminanceOperator() {} ModulateAlphaByLuminanceOperator() {}
inline void luminance(float&) const {} inline void luminance(float&) const {}
inline void alpha(float&) const {} inline void alpha(float&) const {}
inline void luminance_alpha(float& l,float& a) const { a*= l; } inline void luminance_alpha(float& l,float& a) const { a*= l; }
inline void rgb(float&,float&,float&) const {} inline void rgb(float&,float&,float&) const {}
inline void rgba(float& r,float& g,float& b,float& a) const { float l = (r+g+b)*0.3333333; a *= l;} inline void rgba(float& r,float& g,float& b,float& a) const { float l = (r+g+b)*0.3333333; a *= l;}
}; };
@ -650,13 +650,13 @@ struct ModulateAlphaByLuminanceOperator
struct ModulateAlphaByColourOperator struct ModulateAlphaByColourOperator
{ {
ModulateAlphaByColourOperator(const osg::Vec4& colour):_colour(colour) { _lum = _colour.length(); } ModulateAlphaByColourOperator(const osg::Vec4& colour):_colour(colour) { _lum = _colour.length(); }
osg::Vec4 _colour; osg::Vec4 _colour;
float _lum; float _lum;
inline void luminance(float&) const {} inline void luminance(float&) const {}
inline void alpha(float&) const {} inline void alpha(float&) const {}
inline void luminance_alpha(float& l,float& a) const { a*= l*_lum; } inline void luminance_alpha(float& l,float& a) const { a*= l*_lum; }
inline void rgb(float&,float&,float&) const {} inline void rgb(float&,float&,float&) const {}
inline void rgba(float& r,float& g,float& b,float& a) const { a = (r*_colour.r()+g*_colour.g()+b*_colour.b()+a*_colour.a()); } inline void rgba(float& r,float& g,float& b,float& a) const { a = (r*_colour.r()+g*_colour.g()+b*_colour.b()+a*_colour.a()); }
}; };
@ -665,9 +665,9 @@ struct ReplaceAlphaWithLuminanceOperator
{ {
ReplaceAlphaWithLuminanceOperator() {} ReplaceAlphaWithLuminanceOperator() {}
inline void luminance(float&) const {} inline void luminance(float&) const {}
inline void alpha(float&) const {} inline void alpha(float&) const {}
inline void luminance_alpha(float& l,float& a) const { a= l; } inline void luminance_alpha(float& l,float& a) const { a= l; }
inline void rgb(float&,float&,float&) const { } inline void rgb(float&,float&,float&) const { }
inline void rgba(float& r,float& g,float& b,float& a) const { float l = (r+g+b)*0.3333333; a = l; } inline void rgba(float& r,float& g,float& b,float& a) const { float l = (r+g+b)*0.3333333; a = l; }
}; };
@ -679,19 +679,19 @@ osg::Image* doColourSpaceConversion(ColourSpaceOperation op, osg::Image* image,
case (MODULATE_ALPHA_BY_LUMINANCE): case (MODULATE_ALPHA_BY_LUMINANCE):
{ {
std::cout<<"doing conversion MODULATE_ALPHA_BY_LUMINANCE"<<std::endl; std::cout<<"doing conversion MODULATE_ALPHA_BY_LUMINANCE"<<std::endl;
osg::modifyImage(image,ModulateAlphaByLuminanceOperator()); osg::modifyImage(image,ModulateAlphaByLuminanceOperator());
return image; return image;
} }
case (MODULATE_ALPHA_BY_COLOUR): case (MODULATE_ALPHA_BY_COLOUR):
{ {
std::cout<<"doing conversion MODULATE_ALPHA_BY_COLOUR"<<std::endl; std::cout<<"doing conversion MODULATE_ALPHA_BY_COLOUR"<<std::endl;
osg::modifyImage(image,ModulateAlphaByColourOperator(colour)); osg::modifyImage(image,ModulateAlphaByColourOperator(colour));
return image; return image;
} }
case (REPLACE_ALPHA_WITH_LUMINANCE): case (REPLACE_ALPHA_WITH_LUMINANCE):
{ {
std::cout<<"doing conversion REPLACE_ALPHA_WITH_LUMINANCE"<<std::endl; std::cout<<"doing conversion REPLACE_ALPHA_WITH_LUMINANCE"<<std::endl;
osg::modifyImage(image,ReplaceAlphaWithLuminanceOperator()); osg::modifyImage(image,ReplaceAlphaWithLuminanceOperator());
return image; return image;
} }
case (REPLACE_RGB_WITH_LUMINANCE): case (REPLACE_RGB_WITH_LUMINANCE):
@ -700,7 +700,7 @@ osg::Image* doColourSpaceConversion(ColourSpaceOperation op, osg::Image* image,
osg::Image* newImage = new osg::Image; osg::Image* newImage = new osg::Image;
newImage->allocateImage(image->s(), image->t(), image->r(), GL_LUMINANCE, image->getDataType()); newImage->allocateImage(image->s(), image->t(), image->r(), GL_LUMINANCE, image->getDataType());
osg::copyImage(image, 0, 0, 0, image->s(), image->t(), image->r(), osg::copyImage(image, 0, 0, 0, image->s(), image->t(), image->r(),
newImage, 0, 0, 0, false); newImage, 0, 0, 0, false);
return newImage; return newImage;
} }
default: default:
@ -712,12 +712,12 @@ osg::Image* doColourSpaceConversion(ColourSpaceOperation op, osg::Image* image,
osg::TransferFunction1D* readTransferFunctionFile(const std::string& filename) osg::TransferFunction1D* readTransferFunctionFile(const std::string& filename)
{ {
std::string foundFile = osgDB::findDataFile(filename); std::string foundFile = osgDB::findDataFile(filename);
if (foundFile.empty()) if (foundFile.empty())
{ {
std::cout<<"Error: could not find transfer function file : "<<filename<<std::endl; std::cout<<"Error: could not find transfer function file : "<<filename<<std::endl;
return 0; return 0;
} }
std::cout<<"Reading transfer function "<<filename<<std::endl; std::cout<<"Reading transfer function "<<filename<<std::endl;
osg::TransferFunction1D::ColorMap colorMap; osg::TransferFunction1D::ColorMap colorMap;
@ -726,22 +726,22 @@ osg::TransferFunction1D* readTransferFunctionFile(const std::string& filename)
{ {
float value, red, green, blue, alpha; float value, red, green, blue, alpha;
fin >> value >> red >> green >> blue >> alpha; fin >> value >> red >> green >> blue >> alpha;
if (fin) if (fin)
{ {
std::cout<<"value = "<<value<<" ("<<red<<", "<<green<<", "<<blue<<", "<<alpha<<")"<<std::endl; std::cout<<"value = "<<value<<" ("<<red<<", "<<green<<", "<<blue<<", "<<alpha<<")"<<std::endl;
colorMap[value] = osg::Vec4(red,green,blue,alpha); colorMap[value] = osg::Vec4(red,green,blue,alpha);
} }
} }
if (colorMap.empty()) if (colorMap.empty())
{ {
std::cout<<"Error: No values read from transfer function file: "<<filename<<std::endl; std::cout<<"Error: No values read from transfer function file: "<<filename<<std::endl;
return 0; return 0;
} }
osg::TransferFunction1D* tf = new osg::TransferFunction1D; osg::TransferFunction1D* tf = new osg::TransferFunction1D;
tf->assign(colorMap); tf->assign(colorMap);
return tf; return tf;
} }
@ -761,10 +761,10 @@ public:
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(mutex); OpenThreads::ScopedLock<OpenThreads::Mutex> lock(mutex);
glGetIntegerv( GL_MAX_3D_TEXTURE_SIZE, &maximumTextureSize ); glGetIntegerv( GL_MAX_3D_TEXTURE_SIZE, &maximumTextureSize );
osg::notify(osg::NOTICE)<<"Max texture size="<<maximumTextureSize<<std::endl; osg::notify(osg::NOTICE)<<"Max texture size="<<maximumTextureSize<<std::endl;
} }
OpenThreads::Mutex mutex; OpenThreads::Mutex mutex;
bool supported; bool supported;
std::string errorMessage; std::string errorMessage;
@ -840,7 +840,7 @@ int main( int argc, char **argv )
{ {
// use an ArgumentParser object to manage the program arguments. // use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv); osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program. // set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of 3D textures."); arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of 3D textures.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
@ -884,12 +884,12 @@ int main( int argc, char **argv )
// add the window size toggle handler // add the window size toggle handler
viewer.addEventHandler(new osgViewer::WindowSizeHandler); viewer.addEventHandler(new osgViewer::WindowSizeHandler);
{ {
osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator; osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() ); keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
osgGA::FlightManipulator* flightManipulator = new osgGA::FlightManipulator(); osgGA::FlightManipulator* flightManipulator = new osgGA::FlightManipulator();
flightManipulator->setYawControlMode(osgGA::FlightManipulator::NO_AUTOMATIC_YAW); flightManipulator->setYawControlMode(osgGA::FlightManipulator::NO_AUTOMATIC_YAW);
keyswitchManipulator->addMatrixManipulator( '2', "Flight", flightManipulator ); keyswitchManipulator->addMatrixManipulator( '2', "Flight", flightManipulator );
@ -920,7 +920,7 @@ int main( int argc, char **argv )
{ {
transferFunction = readTransferFunctionFile(tranferFunctionFile); transferFunction = readTransferFunctionFile(tranferFunctionFile);
} }
while(arguments.read("--test")) while(arguments.read("--test"))
{ {
transferFunction = new osg::TransferFunction1D; transferFunction = new osg::TransferFunction1D;
@ -940,8 +940,8 @@ int main( int argc, char **argv )
unsigned int numSlices=500; unsigned int numSlices=500;
while (arguments.read("-s",numSlices)) {} while (arguments.read("-s",numSlices)) {}
float sliceEnd=1.0f; float sliceEnd=1.0f;
while (arguments.read("--clip",sliceEnd)) {} while (arguments.read("--clip",sliceEnd)) {}
@ -949,7 +949,7 @@ int main( int argc, char **argv )
while (arguments.read("--alphaFunc",alphaFunc)) {} while (arguments.read("--alphaFunc",alphaFunc)) {}
ShadingModel shadingModel = Standard; ShadingModel shadingModel = Standard;
while(arguments.read("--mip")) shadingModel = MaximumIntensityProjection; while(arguments.read("--mip")) shadingModel = MaximumIntensityProjection;
@ -964,7 +964,7 @@ int main( int argc, char **argv )
osg::ref_ptr<TestSupportOperation> testSupportOperation = new TestSupportOperation; osg::ref_ptr<TestSupportOperation> testSupportOperation = new TestSupportOperation;
viewer.setRealizeOperation(testSupportOperation.get()); viewer.setRealizeOperation(testSupportOperation.get());
viewer.realize(); viewer.realize();
int maximumTextureSize = testSupportOperation->maximumTextureSize; int maximumTextureSize = testSupportOperation->maximumTextureSize;
@ -987,8 +987,8 @@ int main( int argc, char **argv )
while(arguments.read("--compressed-dxt1")) { internalFormatMode = osg::Texture::USE_S3TC_DXT1_COMPRESSION; } while(arguments.read("--compressed-dxt1")) { internalFormatMode = osg::Texture::USE_S3TC_DXT1_COMPRESSION; }
while(arguments.read("--compressed-dxt3")) { internalFormatMode = osg::Texture::USE_S3TC_DXT3_COMPRESSION; } while(arguments.read("--compressed-dxt3")) { internalFormatMode = osg::Texture::USE_S3TC_DXT3_COMPRESSION; }
while(arguments.read("--compressed-dxt5")) { internalFormatMode = osg::Texture::USE_S3TC_DXT5_COMPRESSION; } while(arguments.read("--compressed-dxt5")) { internalFormatMode = osg::Texture::USE_S3TC_DXT5_COMPRESSION; }
// set up colour space operation. // set up colour space operation.
ColourSpaceOperation colourSpaceOperation = NO_COLOUR_SPACE_OPERATION; ColourSpaceOperation colourSpaceOperation = NO_COLOUR_SPACE_OPERATION;
osg::Vec4 colourModulate(0.25f,0.25f,0.25f,0.25f); osg::Vec4 colourModulate(0.25f,0.25f,0.25f,0.25f);
@ -1004,61 +1004,61 @@ int main( int argc, char **argv )
RESCALE_TO_ZERO_TO_ONE_RANGE, RESCALE_TO_ZERO_TO_ONE_RANGE,
SHIFT_MIN_TO_ZERO SHIFT_MIN_TO_ZERO
}; };
RescaleOperation rescaleOperation = RESCALE_TO_ZERO_TO_ONE_RANGE; RescaleOperation rescaleOperation = RESCALE_TO_ZERO_TO_ONE_RANGE;
while(arguments.read("--no-rescale")) rescaleOperation = NO_RESCALE; while(arguments.read("--no-rescale")) rescaleOperation = NO_RESCALE;
while(arguments.read("--rescale")) rescaleOperation = RESCALE_TO_ZERO_TO_ONE_RANGE; while(arguments.read("--rescale")) rescaleOperation = RESCALE_TO_ZERO_TO_ONE_RANGE;
while(arguments.read("--shift-min-to-zero")) rescaleOperation = SHIFT_MIN_TO_ZERO; while(arguments.read("--shift-min-to-zero")) rescaleOperation = SHIFT_MIN_TO_ZERO;
bool resizeToPowerOfTwo = false; bool resizeToPowerOfTwo = false;
unsigned int numComponentsDesired = 0; unsigned int numComponentsDesired = 0;
while(arguments.read("--num-components", numComponentsDesired)) {} while(arguments.read("--num-components", numComponentsDesired)) {}
bool useManipulator = false; bool useManipulator = false;
while(arguments.read("--manipulator") || arguments.read("-m")) { useManipulator = true; } while(arguments.read("--manipulator") || arguments.read("-m")) { useManipulator = true; }
bool useShader = true; bool useShader = true;
while(arguments.read("--shader")) { useShader = true; } while(arguments.read("--shader")) { useShader = true; }
while(arguments.read("--no-shader")) { useShader = false; } while(arguments.read("--no-shader")) { useShader = false; }
bool gpuTransferFunction = true; bool gpuTransferFunction = true;
while(arguments.read("--gpu-tf")) { gpuTransferFunction = true; } while(arguments.read("--gpu-tf")) { gpuTransferFunction = true; }
while(arguments.read("--cpu-tf")) { gpuTransferFunction = false; } while(arguments.read("--cpu-tf")) { gpuTransferFunction = false; }
double sequenceLength = 10.0; double sequenceLength = 10.0;
while(arguments.read("--sequence-duration", sequenceLength) || while(arguments.read("--sequence-duration", sequenceLength) ||
arguments.read("--sd", sequenceLength)) {} arguments.read("--sd", sequenceLength)) {}
typedef std::list< osg::ref_ptr<osg::Image> > Images; typedef std::list< osg::ref_ptr<osg::Image> > Images;
Images images; Images images;
std::string vh_filename; std::string vh_filename;
while (arguments.read("--vh", vh_filename)) while (arguments.read("--vh", vh_filename))
{ {
std::string raw_filename, transfer_filename; std::string raw_filename, transfer_filename;
int xdim(0), ydim(0), zdim(0); int xdim(0), ydim(0), zdim(0);
osgDB::ifstream header(vh_filename.c_str()); osgDB::ifstream header(vh_filename.c_str());
if (header) if (header)
{ {
header >> raw_filename >> transfer_filename >> xdim >> ydim >> zdim >> xSize >> ySize >> zSize; header >> raw_filename >> transfer_filename >> xdim >> ydim >> zdim >> xSize >> ySize >> zSize;
} }
if (xdim*ydim*zdim==0) if (xdim*ydim*zdim==0)
{ {
std::cout<<"Error in reading volume header "<<vh_filename<<std::endl; std::cout<<"Error in reading volume header "<<vh_filename<<std::endl;
return 1; return 1;
} }
if (!raw_filename.empty()) if (!raw_filename.empty())
{ {
images.push_back(readRaw(xdim, ydim, zdim, 1, 1, "little", raw_filename)); images.push_back(readRaw(xdim, ydim, zdim, 1, 1, "little", raw_filename));
} }
if (!transfer_filename.empty()) if (!transfer_filename.empty())
{ {
osgDB::ifstream fin(transfer_filename.c_str()); osgDB::ifstream fin(transfer_filename.c_str());
@ -1070,7 +1070,7 @@ int main( int argc, char **argv )
{ {
float red, green, blue, alpha; float red, green, blue, alpha;
fin >> red >> green >> blue >> alpha; fin >> red >> green >> blue >> alpha;
if (fin) if (fin)
{ {
colorMap[value] = osg::Vec4(red/255.0f,green/255.0f,blue/255.0f,alpha/255.0f); colorMap[value] = osg::Vec4(red/255.0f,green/255.0f,blue/255.0f,alpha/255.0f);
std::cout<<"value = "<<value<<" ("<<red<<", "<<green<<", "<<blue<<", "<<alpha<<")"; std::cout<<"value = "<<value<<" ("<<red<<", "<<green<<", "<<blue<<", "<<alpha<<")";
@ -1091,11 +1091,11 @@ int main( int argc, char **argv )
} }
} }
int sizeX, sizeY, sizeZ, numberBytesPerComponent, numberOfComponents; int sizeX, sizeY, sizeZ, numberBytesPerComponent, numberOfComponents;
std::string endian, raw_filename; std::string endian, raw_filename;
while (arguments.read("--raw", sizeX, sizeY, sizeZ, numberBytesPerComponent, numberOfComponents, endian, raw_filename)) while (arguments.read("--raw", sizeX, sizeY, sizeZ, numberBytesPerComponent, numberOfComponents, endian, raw_filename))
{ {
images.push_back(readRaw(sizeX, sizeY, sizeZ, numberBytesPerComponent, numberOfComponents, endian, raw_filename)); images.push_back(readRaw(sizeX, sizeY, sizeZ, numberBytesPerComponent, numberOfComponents, endian, raw_filename));
} }
@ -1115,9 +1115,9 @@ int main( int argc, char **argv )
imageList.push_back(image); imageList.push_back(image);
} }
} }
arguments.remove(images_pos, pos-images_pos); arguments.remove(images_pos, pos-images_pos);
// pack the textures into a single texture. // pack the textures into a single texture.
ProcessRow processRow; ProcessRow processRow;
images.push_back(createTexture3D(imageList, processRow, numComponentsDesired, s_maximumTextureSize, t_maximumTextureSize, r_maximumTextureSize, resizeToPowerOfTwo)); images.push_back(createTexture3D(imageList, processRow, numComponentsDesired, s_maximumTextureSize, t_maximumTextureSize, r_maximumTextureSize, resizeToPowerOfTwo));
@ -1133,7 +1133,7 @@ int main( int argc, char **argv )
arguments.writeErrorMessages(std::cout); arguments.writeErrorMessages(std::cout);
return 1; return 1;
} }
// assume remaining arguments are file names of textures. // assume remaining arguments are file names of textures.
for(int pos=1;pos<arguments.argc();++pos) for(int pos=1;pos<arguments.argc();++pos)
@ -1161,11 +1161,11 @@ int main( int argc, char **argv )
if (fileType == osgDB::DIRECTORY) if (fileType == osgDB::DIRECTORY)
{ {
osg::Image *image = osgDB::readImageFile(filename+".dicom"); osg::Image *image = osgDB::readImageFile(filename+".dicom");
if(image) if(image)
{ {
images.push_back(image); images.push_back(image);
} }
} }
else if (fileType == osgDB::REGULAR_FILE) else if (fileType == osgDB::REGULAR_FILE)
{ {
@ -1177,11 +1177,11 @@ int main( int argc, char **argv )
osg::notify(osg::NOTICE)<<"Error: could not find file: "<<filename<<std::endl; osg::notify(osg::NOTICE)<<"Error: could not find file: "<<filename<<std::endl;
return 1; return 1;
} }
} }
} }
} }
if (images.empty()) if (images.empty())
{ {
std::cout<<"No model loaded, please specify and volumetric image file on the command line."<<std::endl; std::cout<<"No model loaded, please specify and volumetric image file on the command line."<<std::endl;
return 1; return 1;
@ -1196,7 +1196,7 @@ int main( int argc, char **argv )
for(;sizeItr != images.end(); ++sizeItr) for(;sizeItr != images.end(); ++sizeItr)
{ {
if ((*sizeItr)->s() != image_s || if ((*sizeItr)->s() != image_s ||
(*sizeItr)->t() != image_t || (*sizeItr)->t() != image_t ||
(*sizeItr)->r() != image_r) (*sizeItr)->r() != image_r)
{ {
@ -1206,14 +1206,15 @@ int main( int argc, char **argv )
} }
osg::ref_ptr<osg::RefMatrix> matrix = dynamic_cast<osg::RefMatrix*>(images.front()->getUserData()); osg::ref_ptr<osgVolume::ImageDetails> details = dynamic_cast<osgVolume::ImageDetails*>(images.front()->getUserData());
osg::ref_ptr<osg::RefMatrix> matrix = details ? details->getMatrix() : dynamic_cast<osg::RefMatrix*>(images.front()->getUserData());
if (!matrix) if (!matrix)
{ {
if (xSize==0.0) xSize = static_cast<float>(image_s); if (xSize==0.0) xSize = static_cast<float>(image_s);
if (ySize==0.0) ySize = static_cast<float>(image_t); if (ySize==0.0) ySize = static_cast<float>(image_t);
if (zSize==0.0) zSize = static_cast<float>(image_r); if (zSize==0.0) zSize = static_cast<float>(image_r);
matrix = new osg::RefMatrix(xSize, 0.0, 0.0, 0.0, matrix = new osg::RefMatrix(xSize, 0.0, 0.0, 0.0,
0.0, ySize, 0.0, 0.0, 0.0, ySize, 0.0, 0.0,
0.0, 0.0, zSize, 0.0, 0.0, 0.0, zSize, 0.0,
@ -1245,7 +1246,7 @@ int main( int argc, char **argv )
computeMinMax = true; computeMinMax = true;
} }
} }
if (computeMinMax) if (computeMinMax)
{ {
osg::notify(osg::NOTICE)<<"Min value "<<minValue<<std::endl; osg::notify(osg::NOTICE)<<"Min value "<<minValue<<std::endl;
@ -1261,7 +1262,7 @@ int main( int argc, char **argv )
maxComponent = osg::maximum(maxComponent,maxValue[2]); maxComponent = osg::maximum(maxComponent,maxValue[2]);
maxComponent = osg::maximum(maxComponent,maxValue[3]); maxComponent = osg::maximum(maxComponent,maxValue[3]);
#if 0
switch(rescaleOperation) switch(rescaleOperation)
{ {
case(NO_RESCALE): case(NO_RESCALE):
@ -1275,8 +1276,8 @@ int main( int argc, char **argv )
for(Images::iterator itr = images.begin(); for(Images::iterator itr = images.begin();
itr != images.end(); itr != images.end();
++itr) ++itr)
{ {
osg::offsetAndScaleImage(itr->get(), osg::offsetAndScaleImage(itr->get(),
osg::Vec4(offset, offset, offset, offset), osg::Vec4(offset, offset, offset, offset),
osg::Vec4(scale, scale, scale, scale)); osg::Vec4(scale, scale, scale, scale));
} }
@ -1289,38 +1290,38 @@ int main( int argc, char **argv )
for(Images::iterator itr = images.begin(); for(Images::iterator itr = images.begin();
itr != images.end(); itr != images.end();
++itr) ++itr)
{ {
osg::offsetAndScaleImage(itr->get(), osg::offsetAndScaleImage(itr->get(),
osg::Vec4(offset, offset, offset, offset), osg::Vec4(offset, offset, offset, offset),
osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f)); osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f));
} }
break; break;
} }
}; };
#endif
} }
if (colourSpaceOperation!=NO_COLOUR_SPACE_OPERATION) if (colourSpaceOperation!=NO_COLOUR_SPACE_OPERATION)
{ {
for(Images::iterator itr = images.begin(); for(Images::iterator itr = images.begin();
itr != images.end(); itr != images.end();
++itr) ++itr)
{ {
(*itr) = doColourSpaceConversion(colourSpaceOperation, itr->get(), colourModulate); (*itr) = doColourSpaceConversion(colourSpaceOperation, itr->get(), colourModulate);
} }
} }
if (!gpuTransferFunction && transferFunction.valid()) if (!gpuTransferFunction && transferFunction.valid())
{ {
for(Images::iterator itr = images.begin(); for(Images::iterator itr = images.begin();
itr != images.end(); itr != images.end();
++itr) ++itr)
{ {
*itr = osgVolume::applyTransferFunction(itr->get(), transferFunction.get()); *itr = osgVolume::applyTransferFunction(itr->get(), transferFunction.get());
} }
} }
osg::ref_ptr<osg::Image> image_3d = 0; osg::ref_ptr<osg::Image> image_3d = 0;
if (images.size()==1) if (images.size()==1)
@ -1331,24 +1332,47 @@ int main( int argc, char **argv )
else else
{ {
osg::notify(osg::NOTICE)<<"Creating sequence of "<<images.size()<<" volumes."<<std::endl; osg::notify(osg::NOTICE)<<"Creating sequence of "<<images.size()<<" volumes."<<std::endl;
osg::ref_ptr<osg::ImageSequence> imageSequence = new osg::ImageSequence; osg::ref_ptr<osg::ImageSequence> imageSequence = new osg::ImageSequence;
imageSequence->setLength(sequenceLength); imageSequence->setLength(sequenceLength);
image_3d = imageSequence.get(); image_3d = imageSequence.get();
for(Images::iterator itr = images.begin(); for(Images::iterator itr = images.begin();
itr != images.end(); itr != images.end();
++itr) ++itr)
{ {
imageSequence->addImage(itr->get()); imageSequence->addImage(itr->get());
} }
imageSequence->play(); imageSequence->play();
} }
osg::ref_ptr<osgVolume::Volume> volume = new osgVolume::Volume; osg::ref_ptr<osgVolume::Volume> volume = new osgVolume::Volume;
osg::ref_ptr<osgVolume::VolumeTile> tile = new osgVolume::VolumeTile; osg::ref_ptr<osgVolume::VolumeTile> tile = new osgVolume::VolumeTile;
volume->addChild(tile.get()); volume->addChild(tile.get());
osg::ref_ptr<osgVolume::Layer> layer = new osgVolume::ImageLayer(image_3d.get()); osg::ref_ptr<osgVolume::ImageLayer> layer = new osgVolume::ImageLayer(image_3d.get());
if (details)
{
layer->setRescaleIntercept(details->getRescaleIntercept());
layer->setRescaleSlope(details->getRescaleSlope());
}
switch(rescaleOperation)
{
case(NO_RESCALE):
break;
case(RESCALE_TO_ZERO_TO_ONE_RANGE):
{
layer->rescaleToZeroToOneRange();
break;
}
case(SHIFT_MIN_TO_ZERO):
{
layer->translateMinToZero();
break;
}
};
layer->setLocator(new osgVolume::Locator(*matrix)); layer->setLocator(new osgVolume::Locator(*matrix));
tile->setLocator(new osgVolume::Locator(*matrix)); tile->setLocator(new osgVolume::Locator(*matrix));
@ -1431,23 +1455,23 @@ int main( int argc, char **argv )
layer->addProperty(new osgVolume::AlphaFuncProperty(alphaFunc)); layer->addProperty(new osgVolume::AlphaFuncProperty(alphaFunc));
tile->setVolumeTechnique(new osgVolume::FixedFunctionTechnique); tile->setVolumeTechnique(new osgVolume::FixedFunctionTechnique);
} }
if (!outputFile.empty()) if (!outputFile.empty())
{ {
std::string ext = osgDB::getFileExtension(outputFile); std::string ext = osgDB::getFileExtension(outputFile);
std::string name_no_ext = osgDB::getNameLessExtension(outputFile); std::string name_no_ext = osgDB::getNameLessExtension(outputFile);
if (ext=="osg") if (ext=="osg")
{ {
if (image_3d.valid()) if (image_3d.valid())
{ {
image_3d->setFileName(name_no_ext + ".dds"); image_3d->setFileName(name_no_ext + ".dds");
osgDB::writeImageFile(*image_3d, image_3d->getFileName()); osgDB::writeImageFile(*image_3d, image_3d->getFileName());
} }
osgDB::writeNodeFile(*volume, outputFile); osgDB::writeNodeFile(*volume, outputFile);
} }
else if (ext=="ive") else if (ext=="ive")
{ {
osgDB::writeNodeFile(*volume, outputFile); osgDB::writeNodeFile(*volume, outputFile);
} }
else if (ext=="dds") else if (ext=="dds")
{ {
@ -1457,11 +1481,11 @@ int main( int argc, char **argv )
{ {
std::cout<<"Extension not support for file output, not file written."<<std::endl; std::cout<<"Extension not support for file output, not file written."<<std::endl;
} }
return 0; return 0;
} }
if (volume.valid()) if (volume.valid())
{ {
osg::ref_ptr<osg::Node> loadedModel = volume.get(); osg::ref_ptr<osg::Node> loadedModel = volume.get();
@ -1494,11 +1518,11 @@ int main( int argc, char **argv )
// set the scene to render // set the scene to render
viewer.setSceneData(loadedModel.get()); viewer.setSceneData(loadedModel.get());
// the the viewers main frame loop // the the viewers main frame loop
viewer.run(); viewer.run();
} }
return 0; return 0;
} }

View File

@ -22,6 +22,37 @@
namespace osgVolume { namespace osgVolume {
/** Data strucutre for passing details about the loading imagery on to osgVolume for use when setting up dimensions etc.*/
class OSGVOLUME_EXPORT ImageDetails : public osg::Object
{
public:
ImageDetails();
/** Copy constructor using CopyOp to manage deep vs shallow copy.*/
ImageDetails(const ImageDetails&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
META_Object(osgVolume, ImageDetails);
void setRescaleIntercept(double intercept) { _rescaleIntercept = intercept; }
double getRescaleIntercept() const { return _rescaleIntercept; }
void setRescaleSlope(double slope) { _rescaleSlope = slope; }
double getRescaleSlope() const { return _rescaleSlope; }
void setMatrix(osg::RefMatrix* matrix) { _matrix = matrix; }
osg::RefMatrix* getMatrix() { return _matrix.get(); }
const osg::RefMatrix* getMatrix() const { return _matrix.get(); }
protected:
double _rescaleIntercept;
double _rescaleSlope;
osg::ref_ptr<osg::RefMatrix> _matrix;
};
/** Base class for representing a single layer of volume data.*/
class OSGVOLUME_EXPORT Layer : public osg::Object class OSGVOLUME_EXPORT Layer : public osg::Object
{ {
public: public:
@ -30,9 +61,9 @@ class OSGVOLUME_EXPORT Layer : public osg::Object
/** Copy constructor using CopyOp to manage deep vs shallow copy.*/ /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
Layer(const Layer&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); Layer(const Layer&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
META_Object(osgVolume, Layer); META_Object(osgVolume, Layer);
/** Set the file name of the data associated with this layer. */ /** Set the file name of the data associated with this layer. */
virtual void setFileName(const std::string& filename) { _filename = filename; } virtual void setFileName(const std::string& filename) { _filename = filename; }
@ -42,7 +73,7 @@ class OSGVOLUME_EXPORT Layer : public osg::Object
void setLocator(Locator* locator) { _locator = locator; } void setLocator(Locator* locator) { _locator = locator; }
Locator* getLocator() { return _locator.get(); } Locator* getLocator() { return _locator.get(); }
const Locator* getLocator() const { return _locator.get(); } const Locator* getLocator() const { return _locator.get(); }
void setDefaultValue(const osg::Vec4& value) { _defaultValue = value; } void setDefaultValue(const osg::Vec4& value) { _defaultValue = value; }
const osg::Vec4& getDefaultValue() const { return _defaultValue; } const osg::Vec4& getDefaultValue() const { return _defaultValue; }
@ -58,10 +89,10 @@ class OSGVOLUME_EXPORT Layer : public osg::Object
/** Get the magnification texture filter to use when do texture associated with this layer.*/ /** Get the magnification texture filter to use when do texture associated with this layer.*/
osg::Texture::FilterMode getMagFilter() const { return _magFilter; } osg::Texture::FilterMode getMagFilter() const { return _magFilter; }
/** Return image associated with layer if supported. */ /** Return image associated with layer if supported. */
virtual osg::Image* getImage() { return 0; } virtual osg::Image* getImage() { return 0; }
/** Return const image associated with layer if supported. */ /** Return const image associated with layer if supported. */
virtual const osg::Image* getImage() const { return 0; } virtual const osg::Image* getImage() const { return 0; }
@ -82,7 +113,7 @@ class OSGVOLUME_EXPORT Layer : public osg::Object
virtual bool requiresUpdateTraversal() const { return false; } virtual bool requiresUpdateTraversal() const { return false; }
/** Call update on the Layer.*/ /** Call update on the Layer.*/
virtual void update(osg::NodeVisitor& /*nv*/) {} virtual void update(osg::NodeVisitor& /*nv*/) {}
/** increment the modified count."*/ /** increment the modified count."*/
virtual void dirty() {}; virtual void dirty() {};
@ -104,7 +135,7 @@ class OSGVOLUME_EXPORT Layer : public osg::Object
osg::Vec4 _defaultValue; osg::Vec4 _defaultValue;
osg::Texture::FilterMode _minFilter; osg::Texture::FilterMode _minFilter;
osg::Texture::FilterMode _magFilter; osg::Texture::FilterMode _magFilter;
osg::ref_ptr<Property> _property; osg::ref_ptr<Property> _property;
}; };
@ -117,7 +148,7 @@ class OSGVOLUME_EXPORT ImageLayer : public Layer
/** Copy constructor using CopyOp to manage deep vs shallow copy.*/ /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
ImageLayer(const ImageLayer& imageLayer,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); ImageLayer(const ImageLayer& imageLayer,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
META_Object(osgVolume, ImageLayer); META_Object(osgVolume, ImageLayer);
void setFileName(const std::string& filename) { _filename = filename; if (_image.valid()) _image->setFileName(filename); } void setFileName(const std::string& filename) { _filename = filename; if (_image.valid()) _image->setFileName(filename); }
@ -125,21 +156,29 @@ class OSGVOLUME_EXPORT ImageLayer : public Layer
void setImage(osg::Image* image); void setImage(osg::Image* image);
/** Return image associated with layer. */ /** Return image associated with layer. */
virtual osg::Image* getImage() { return _image.get(); } virtual osg::Image* getImage() { return _image.get(); }
/** Return const image associated with layer. */ /** Return const image associated with layer. */
virtual const osg::Image* getImage() const { return _image.get(); } virtual const osg::Image* getImage() const { return _image.get(); }
void setRescaleIntercept(double intercept) { _rescaleIntercept = intercept; }
double getRescaleIntercept() const { return _rescaleIntercept; }
void setRescaleSlope(double slope) { _rescaleSlope = slope; }
double setRescaleSlope() const { return _rescaleSlope; }
/** Compute the min and max pixel colors.*/ /** Compute the min and max pixel colors.*/
bool computeMinMax(osg::Vec4& min, osg::Vec4& max); bool computeMinMax(osg::Vec4& min, osg::Vec4& max);
/** Apply color transformation to pixels using c' = offset + c * scale .*/ /** Apply color transformation to pixels using c' = offset + c * scale .*/
void offsetAndScaleImage(const osg::Vec4& offset, const osg::Vec4& scale); void offsetAndScaleImage(const osg::Vec4& offset, const osg::Vec4& scale);
/** Compute the min max range of the image, and then remap this to a 0 to 1 range.*/ /** Compute the min max range of the image, and then remap this to a 0 to 1 range.*/
void rescaleToZeroToOneRange(); void rescaleToZeroToOneRange();
/** Compute the min color component of the image and then translate and pixels by this offset to make the new min component 0.*/ /** Compute the min color component of the image and then translate and pixels by this offset to make the new min component 0.*/
void translateMinToZero(); void translateMinToZero();
@ -155,6 +194,8 @@ class OSGVOLUME_EXPORT ImageLayer : public Layer
virtual ~ImageLayer() {} virtual ~ImageLayer() {}
double _rescaleIntercept;
double _rescaleSlope;
osg::ref_ptr<osg::Image> _image; osg::ref_ptr<osg::Image> _image;
}; };
@ -167,7 +208,7 @@ class OSGVOLUME_EXPORT CompositeLayer : public Layer
/** Copy constructor using CopyOp to manage deep vs shallow copy.*/ /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
CompositeLayer(const CompositeLayer& compositeLayer,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); CompositeLayer(const CompositeLayer& compositeLayer,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
META_Object(osgVolume, CompositeLayer); META_Object(osgVolume, CompositeLayer);
void clear(); void clear();
@ -182,11 +223,11 @@ class OSGVOLUME_EXPORT CompositeLayer : public Layer
void addLayer(Layer* layer) { _layers.push_back(NameLayer(layer->getFileName(),layer)); } void addLayer(Layer* layer) { _layers.push_back(NameLayer(layer->getFileName(),layer)); }
void removeLayer(unsigned int i) { _layers.erase(_layers.begin()+i); } void removeLayer(unsigned int i) { _layers.erase(_layers.begin()+i); }
unsigned int getNumLayers() const { return _layers.size(); } unsigned int getNumLayers() const { return _layers.size(); }
bool requiresUpdateTraversal() const; bool requiresUpdateTraversal() const;
virtual void update(osg::NodeVisitor& /*nv*/); virtual void update(osg::NodeVisitor& /*nv*/);
protected: protected:
@ -196,7 +237,7 @@ class OSGVOLUME_EXPORT CompositeLayer : public Layer
struct NameLayer struct NameLayer
{ {
NameLayer() {} NameLayer() {}
NameLayer(const NameLayer& cnl): NameLayer(const NameLayer& cnl):
filename(cnl.filename), filename(cnl.filename),
layer(cnl.layer) {} layer(cnl.layer) {}
@ -208,7 +249,7 @@ class OSGVOLUME_EXPORT CompositeLayer : public Layer
NameLayer& operator = (const NameLayer& cnl) NameLayer& operator = (const NameLayer& cnl)
{ {
if (&cnl==this) return *this; if (&cnl==this) return *this;
filename = cnl.filename; filename = cnl.filename;
layer = cnl.layer; layer = cnl.layer;
return *this; return *this;
@ -217,9 +258,9 @@ class OSGVOLUME_EXPORT CompositeLayer : public Layer
std::string filename; std::string filename;
osg::ref_ptr<Layer> layer; osg::ref_ptr<Layer> layer;
}; };
typedef std::vector< NameLayer > Layers; typedef std::vector< NameLayer > Layers;
Layers _layers; Layers _layers;
}; };

View File

@ -23,9 +23,10 @@
#define HAVE_CONFIG_H #define HAVE_CONFIG_H
#endif #endif
#include <dcmtk/config/osconfig.h> #include <dcmtk/config/osconfig.h>
#include <dcmtk/dcmdata/dcfilefo.h> #include <dcmtk/dcmdata/dcfilefo.h>
#include <dcmtk/dcmdata/dcdeftag.h> #include <dcmtk/dcmdata/dcdeftag.h>
#include <dcmtk/dcmdata/dcuid.h>
#include <dcmtk/dcmimgle/dcmimage.h> #include <dcmtk/dcmimgle/dcmimage.h>
#endif #endif
@ -48,7 +49,7 @@
class ReaderWriterDICOM : public osgDB::ReaderWriter class ReaderWriterDICOM : public osgDB::ReaderWriter
{ {
public: public:
ReaderWriterDICOM() ReaderWriterDICOM()
{ {
supportsExtension("mag","dicom image format"); supportsExtension("mag","dicom image format");
@ -63,18 +64,18 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
std::ostream& warning() const { return osg::notify(osg::WARN); } std::ostream& warning() const { return osg::notify(osg::WARN); }
std::ostream& notice() const { return osg::notify(osg::NOTICE); } std::ostream& notice() const { return osg::notify(osg::NOTICE); }
std::ostream& info() const { return osg::notify(osg::INFO); } std::ostream& info() const { return osg::notify(osg::INFO); }
template<typename T> template<typename T>
T* readData(std::istream& fin, unsigned int length, unsigned int& numComponents) const T* readData(std::istream& fin, unsigned int length, unsigned int& numComponents) const
{ {
numComponents = length/sizeof(T); numComponents = length/sizeof(T);
T* data = new T[numComponents]; T* data = new T[numComponents];
fin.read((char*)data, numComponents*sizeof(T)); fin.read((char*)data, numComponents*sizeof(T));
// read over any padding // read over any padding
length -= numComponents*sizeof(T); length -= numComponents*sizeof(T);
while(fin && length>0) { fin.get(); --length; } while(fin && length>0) { fin.get(); --length; }
return data; return data;
} }
@ -89,8 +90,8 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
else out<<"."; else out<<".";
} }
} }
else else
{ {
for(unsigned int i=0; i<numComponents; ++i) for(unsigned int i=0; i<numComponents; ++i)
{ {
if (i==0) out<<data[i]; if (i==0) out<<data[i];
@ -98,9 +99,9 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
} }
} }
} }
virtual const char* className() const { return "DICOM Image Reader/Writer"; } virtual const char* className() const { return "DICOM Image Reader/Writer"; }
typedef std::vector<std::string> Files; typedef std::vector<std::string> Files;
bool getDicomFilesInDirectory(const std::string& path, Files& files) const bool getDicomFilesInDirectory(const std::string& path, Files& files) const
{ {
@ -143,16 +144,16 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
{ {
ReadResult result = readImage(file, options); ReadResult result = readImage(file, options);
if (!result.validImage()) return result; if (!result.validImage()) return result;
osg::ref_ptr<osgVolume::VolumeTile> tile = new osgVolume::VolumeTile; osg::ref_ptr<osgVolume::VolumeTile> tile = new osgVolume::VolumeTile;
tile->setVolumeTechnique(new osgVolume::RayTracedTechnique()); tile->setVolumeTechnique(new osgVolume::RayTracedTechnique());
osg::ref_ptr<osgVolume::ImageLayer> layer= new osgVolume::ImageLayer(result.getImage()); osg::ref_ptr<osgVolume::ImageLayer> layer= new osgVolume::ImageLayer(result.getImage());
layer->rescaleToZeroToOneRange(); layer->rescaleToZeroToOneRange();
osgVolume::SwitchProperty* sp = new osgVolume::SwitchProperty; osgVolume::SwitchProperty* sp = new osgVolume::SwitchProperty;
sp->setActiveProperty(0); sp->setActiveProperty(0);
float alphaFunc = 0.1f; float alphaFunc = 0.1f;
osgVolume::AlphaFuncProperty* ap = new osgVolume::AlphaFuncProperty(alphaFunc); osgVolume::AlphaFuncProperty* ap = new osgVolume::AlphaFuncProperty(alphaFunc);
@ -206,24 +207,31 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
tile->setLayer(layer.get()); tile->setLayer(layer.get());
// get matrix providing size of texels (in mm) // get matrix providing size of texels (in mm)
osg::RefMatrix* matrix = dynamic_cast<osg::RefMatrix*>(result.getImage()->getUserData()); osgVolume::ImageDetails* details = dynamic_cast<osgVolume::ImageDetails*>(result.getImage()->getUserData());
osg::RefMatrix* matrix = details ? details->getMatrix() : 0;
if (details)
{
layer->setRescaleIntercept(details->getRescaleIntercept());
layer->setRescaleSlope(details->getRescaleSlope());
}
if (matrix) if (matrix)
{ {
osgVolume::Locator* locator = new osgVolume::Locator(*matrix); osgVolume::Locator* locator = new osgVolume::Locator(*matrix);
tile->setLocator(locator); tile->setLocator(locator);
layer->setLocator(locator); layer->setLocator(locator);
// result.getImage()->setUserData(0); // result.getImage()->setUserData(0);
info()<<"Locator "<<*matrix<<std::endl; info()<<"Locator "<<*matrix<<std::endl;
} }
else else
{ {
info()<<"No Locator found on osg::Image"<<std::endl; info()<<"No Locator found on osg::Image"<<std::endl;
} }
return tile.release(); return tile.release();
} }
@ -298,7 +306,8 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
++itr) ++itr)
{ {
osg::Image* image = itr->get(); osg::Image* image = itr->get();
osg::RefMatrix* matrix = dynamic_cast<osg::RefMatrix*>(image->getUserData()); osgVolume::ImageDetails* details = dynamic_cast<osgVolume::ImageDetails*>(result.getImage()->getUserData());
osg::RefMatrix* matrix = details ? details->getMatrix() : 0;
if (matrix) if (matrix)
{ {
osg::Vec3 p0 = osg::Vec3(0.0, 0.0, 0.0) * (*matrix); osg::Vec3 p0 = osg::Vec3(0.0, 0.0, 0.0) * (*matrix);
@ -340,18 +349,19 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
{ {
osg::Image* image = itr->second.get(); osg::Image* image = itr->second.get();
osg::copyImage(image, 0,0,0, image->s(), image->t(), image->r(), osg::copyImage(image, 0,0,0, image->s(), image->t(), image->r(),
image3D.get(), 0, 0, r, image3D.get(), 0, 0, r,
false); false);
r += image->r(); r += image->r();
} }
osg::Image* firstImage = dim.begin()->second.get(); osg::Image* firstImage = dim.begin()->second.get();
osg::RefMatrix* matrix = dynamic_cast<osg::RefMatrix*>(firstImage->getUserData()); osgVolume::ImageDetails* details = dynamic_cast<osgVolume::ImageDetails*>(result.getImage()->getUserData());
osg::RefMatrix* matrix = details ? details->getMatrix() : 0;
if (matrix) if (matrix)
{ {
image3D->setUserData( osgVolume::ImageDetails* details3D = new osgVolume::ImageDetails(*details);
new osg::RefMatrix(osg::Matrix::scale(1.0,1.0,totalThickness) * (*matrix)) details3D->getMatrix()->preMult(osg::Matrix::scale(1.0,1.0,totalThickness));
); image3D->setUserData(details3D);
} }
return image3D.get(); return image3D.get();
@ -384,36 +394,36 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
std::cerr << e.GetLocation() << std::endl; std::cerr << e.GetLocation() << std::endl;
return ReadResult::ERROR_IN_READING_FILE; return ReadResult::ERROR_IN_READING_FILE;
} }
ImageType::Pointer inputImage = reader->GetOutput(); ImageType::Pointer inputImage = reader->GetOutput();
ImageType::RegionType region = inputImage->GetBufferedRegion(); ImageType::RegionType region = inputImage->GetBufferedRegion();
ImageType::SizeType size = region.GetSize(); ImageType::SizeType size = region.GetSize();
ImageType::IndexType start = region.GetIndex(); ImageType::IndexType start = region.GetIndex();
//inputImage->GetSpacing(); //inputImage->GetSpacing();
//inputImage->GetOrigin(); //inputImage->GetOrigin();
unsigned int width = size[0]; unsigned int width = size[0];
unsigned int height = size[1]; unsigned int height = size[1];
unsigned int depth = size[2]; unsigned int depth = size[2];
osg::RefMatrix* matrix = new osg::RefMatrix; osg::RefMatrix* matrix = new osg::RefMatrix;
info()<<"width = "<<width<<" height = "<<height<<" depth = "<<depth<<std::endl; info()<<"width = "<<width<<" height = "<<height<<" depth = "<<depth<<std::endl;
for(unsigned int i=0; i<Dimension; ++i) for(unsigned int i=0; i<Dimension; ++i)
{ {
(*matrix)(i,i) = inputImage->GetSpacing()[i]; (*matrix)(i,i) = inputImage->GetSpacing()[i];
(*matrix)(3,i) = inputImage->GetOrigin()[i]; (*matrix)(3,i) = inputImage->GetOrigin()[i];
} }
osg::Image* image = new osg::Image; osg::Image* image = new osg::Image;
image->allocateImage(width, height, depth, GL_LUMINANCE, GL_UNSIGNED_BYTE, 1); image->allocateImage(width, height, depth, GL_LUMINANCE, GL_UNSIGNED_BYTE, 1);
unsigned char* data = image->data(); unsigned char* data = image->data();
typedef itk::ImageRegionConstIterator< ImageType > IteratorType; typedef itk::ImageRegionConstIterator< ImageType > IteratorType;
IteratorType it(inputImage, region); IteratorType it(inputImage, region);
it.GoToBegin(); it.GoToBegin();
while (!it.IsAtEnd()) while (!it.IsAtEnd())
{ {
@ -421,9 +431,12 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
++data; ++data;
++it; ++it;
} }
image->setUserData(matrix); osgVolume::ImageDetails* details = new osgVolume::ImageDetails;
details->setMatrix(matrix);
image->setUserData(details);
matrix->preMult(osg::Matrix::scale(double(image->s()), double(image->t()), double(image->r()))); matrix->preMult(osg::Matrix::scale(double(image->s()), double(image->t()), double(image->r())));
return image; return image;
@ -432,9 +445,9 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
#ifdef USE_DCMTK #ifdef USE_DCMTK
void convertPixelTypes(const DiPixel* pixelData, void convertPixelTypes(const DiPixel* pixelData,
EP_Representation& pixelRep, int& numPlanes, EP_Representation& pixelRep, int& numPlanes,
GLenum& dataType, GLenum& pixelFormat, unsigned int& pixelSize) const GLenum& dataType, GLenum& pixelFormat, unsigned int& pixelSize) const
{ {
dataType = GL_UNSIGNED_BYTE; dataType = GL_UNSIGNED_BYTE;
pixelRep = pixelData->getRepresentation(); pixelRep = pixelData->getRepresentation();
@ -490,7 +503,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
break; break;
} }
} }
@ -500,7 +513,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
std::string ext = osgDB::getLowerCaseFileExtension(file); std::string ext = osgDB::getLowerCaseFileExtension(file);
if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
std::string fileName = file; std::string fileName = file;
if (ext=="dicom") if (ext=="dicom")
{ {
@ -511,7 +524,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND; if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
Files files; Files files;
osgDB::FileType fileType = osgDB::fileType(fileName); osgDB::FileType fileType = osgDB::fileType(fileName);
if (fileType==osgDB::DIRECTORY) if (fileType==osgDB::DIRECTORY)
{ {
@ -521,12 +534,12 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
{ {
#if 1 #if 1
files.push_back(fileName); files.push_back(fileName);
#else #else
if (!getDicomFilesInDirectory(osgDB::getFilePath(fileName), files)) if (!getDicomFilesInDirectory(osgDB::getFilePath(fileName), files))
{ {
files.push_back(fileName); files.push_back(fileName);
} }
#endif #endif
} }
if (files.empty()) if (files.empty())
@ -534,22 +547,25 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
return ReadResult::FILE_NOT_FOUND; return ReadResult::FILE_NOT_FOUND;
} }
osg::ref_ptr<osg::RefMatrix> matrix = new osg::RefMatrix; osg::ref_ptr<osgVolume::ImageDetails> details = new osgVolume::ImageDetails;
details->setMatrix(new osg::RefMatrix);
osg::ref_ptr<osg::Image> image; osg::ref_ptr<osg::Image> image;
unsigned int imageNum = 0; unsigned int imageNum = 0;
EP_Representation pixelRep = EPR_Uint8; EP_Representation pixelRep = EPR_Uint8;
int numPlanes = 0; int numPlanes = 0;
GLenum pixelFormat = 0; GLenum pixelFormat = 0;
GLenum dataType = 0; GLenum dataType = 0;
unsigned int pixelSize = 0; unsigned int pixelSize = 0;
typedef std::list<FileInfo> FileInfoList; typedef std::list<FileInfo> FileInfoList;
FileInfoList fileInfoList; FileInfoList fileInfoList;
typedef std::map<double, FileInfo> DistanceFileInfoMap; typedef std::map<double, FileInfo> DistanceFileInfoMap;
typedef std::map<osg::Vec3d, DistanceFileInfoMap> OrientationFileInfoMap; typedef std::map<osg::Vec3d, DistanceFileInfoMap> OrientationFileInfoMap;
OrientationFileInfoMap orientationFileInfoMap; OrientationFileInfoMap orientationFileInfoMap;
unsigned int totalNumSlices = 0; unsigned int totalNumSlices = 0;
for(Files::iterator itr = files.begin(); for(Files::iterator itr = files.begin();
@ -559,7 +575,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
DcmFileFormat fileformat; DcmFileFormat fileformat;
OFCondition status = fileformat.loadFile((*itr).c_str()); OFCondition status = fileformat.loadFile((*itr).c_str());
if(!status.good()) return ReadResult::ERROR_IN_READING_FILE; if(!status.good()) return ReadResult::ERROR_IN_READING_FILE;
FileInfo fileInfo; FileInfo fileInfo;
fileInfo.filename = *itr; fileInfo.filename = *itr;
@ -569,7 +585,33 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
double imagePositionPatient[3] = {0, 0, 0}; double imagePositionPatient[3] = {0, 0, 0};
double imageOrientationPatient[6] = {1.0, 0.0, 0.0, 0.0, 1.0, 0.0 }; double imageOrientationPatient[6] = {1.0, 0.0, 0.0, 0.0, 1.0, 0.0 };
Uint16 numOfSlices = 1; Uint16 numOfSlices = 1;
// code for reading the intercept and scale that is required to convert to Hounsfield units.
bool rescaling = false;
double rescaleIntercept = 0.0;
double rescaleSlope = 1.0;
const char *classUID = NULL;
if (fileformat.getDataset()->findAndGetString(DCM_SOPClassUID, classUID).good())
{
osg::notify(osg::NOTICE)<<" classUID = "<<classUID<<std::endl;
if (0 == strcmp(classUID, UID_CTImageStorage))
{
osg::notify(osg::NOTICE)<<" is a UID_CTImageStorage "<<std::endl;
}
}
rescaling = fileformat.getDataset()->findAndGetFloat64(DCM_RescaleIntercept, rescaleIntercept).good();
rescaling &= fileformat.getDataset()->findAndGetFloat64(DCM_RescaleSlope, rescaleSlope).good();
if (rescaling)
{
fileInfo.rescaleIntercept = rescaleIntercept;
fileInfo.rescaleSlope = rescaleSlope;
osg::notify(osg::NOTICE)<<" rescaleIntercept = "<<rescaleIntercept<<std::endl;
osg::notify(osg::NOTICE)<<" rescaleSlope = "<<rescaleSlope<<std::endl;
}
double value = 0.0; double value = 0.0;
if (fileformat.getDataset()->findAndGetFloat64(DCM_PixelSpacing, value,0).good()) if (fileformat.getDataset()->findAndGetFloat64(DCM_PixelSpacing, value,0).good())
{ {
@ -590,7 +632,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
info()<<"sliceThickness = "<<sliceThickness<<std::endl; info()<<"sliceThickness = "<<sliceThickness<<std::endl;
fileInfo.sliceThickness = sliceThickness; fileInfo.sliceThickness = sliceThickness;
} }
info()<<"tagExistsWithValue(DCM_NumberOfFrames)="<<fileformat.getDataset()->tagExistsWithValue(DCM_NumberOfFrames)<<std::endl; info()<<"tagExistsWithValue(DCM_NumberOfFrames)="<<fileformat.getDataset()->tagExistsWithValue(DCM_NumberOfFrames)<<std::endl;
info()<<"tagExistsWithValue(DCM_NumberOfSlices)="<<fileformat.getDataset()->tagExistsWithValue(DCM_NumberOfSlices)<<std::endl; info()<<"tagExistsWithValue(DCM_NumberOfSlices)="<<fileformat.getDataset()->tagExistsWithValue(DCM_NumberOfSlices)<<std::endl;
@ -601,7 +643,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
info()<<"Read number of frames = "<<numFrames<<std::endl; info()<<"Read number of frames = "<<numFrames<<std::endl;
} }
OFString numFramesStr; OFString numFramesStr;
if (fileformat.getDataset()->findAndGetOFString(DCM_NumberOfFrames, numFramesStr).good()) if (fileformat.getDataset()->findAndGetOFString(DCM_NumberOfFrames, numFramesStr).good())
{ {
@ -614,7 +656,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
fileInfo.numSlices = numOfSlices; fileInfo.numSlices = numOfSlices;
info()<<"Read number of frames = "<<numOfSlices<<std::endl; info()<<"Read number of frames = "<<numOfSlices<<std::endl;
} }
if (fileformat.getDataset()->findAndGetUint16(DCM_NumberOfSlices, numOfSlices).good()) if (fileformat.getDataset()->findAndGetUint16(DCM_NumberOfSlices, numOfSlices).good())
{ {
fileInfo.numSlices = numOfSlices; fileInfo.numSlices = numOfSlices;
@ -636,7 +678,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
} }
} }
//info()<<"imagePositionPatient[2]="<<imagePositionPatient[2]<<std::endl; //info()<<"imagePositionPatient[2]="<<imagePositionPatient[2]<<std::endl;
fileInfo.matrix.setTrans(imagePositionPatient[0],imagePositionPatient[1],imagePositionPatient[2]); fileInfo.matrix.setTrans(imagePositionPatient[0],imagePositionPatient[1],imagePositionPatient[2]);
for(int i=0; i<6; ++i) for(int i=0; i<6; ++i)
@ -657,22 +699,22 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
osg::Vec3d dirY(imageOrientationPatient[3],imageOrientationPatient[4],imageOrientationPatient[5]); osg::Vec3d dirY(imageOrientationPatient[3],imageOrientationPatient[4],imageOrientationPatient[5]);
osg::Vec3d dirZ = dirX ^ dirY; osg::Vec3d dirZ = dirX ^ dirY;
dirZ.normalize(); dirZ.normalize();
dirX *= pixelSize_x; dirX *= pixelSize_x;
dirY *= pixelSize_y; dirY *= pixelSize_y;
fileInfo.matrix(0,0) = dirX[0]; fileInfo.matrix(0,0) = dirX[0];
fileInfo.matrix(1,0) = dirX[1]; fileInfo.matrix(1,0) = dirX[1];
fileInfo.matrix(2,0) = dirX[2]; fileInfo.matrix(2,0) = dirX[2];
fileInfo.matrix(0,1) = dirY[0]; fileInfo.matrix(0,1) = dirY[0];
fileInfo.matrix(1,1) = dirY[1]; fileInfo.matrix(1,1) = dirY[1];
fileInfo.matrix(2,1) = dirY[2]; fileInfo.matrix(2,1) = dirY[2];
fileInfo.matrix(0,2) = dirZ[0]; fileInfo.matrix(0,2) = dirZ[0];
fileInfo.matrix(1,2) = dirZ[1]; fileInfo.matrix(1,2) = dirZ[1];
fileInfo.matrix(2,2) = dirZ[2]; fileInfo.matrix(2,2) = dirZ[2];
fileInfo.distance = dirZ * (osg::Vec3d(0.0,0.0,0.0)*fileInfo.matrix); fileInfo.distance = dirZ * (osg::Vec3d(0.0,0.0,0.0)*fileInfo.matrix);
info()<<"dirX = "<<dirX<<std::endl; info()<<"dirX = "<<dirX<<std::endl;
@ -690,7 +732,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
} }
if (orientationFileInfoMap.empty()) return 0; if (orientationFileInfoMap.empty()) return 0;
typedef std::map<double, FileInfo> DistanceFileInfoMap; typedef std::map<double, FileInfo> DistanceFileInfoMap;
typedef std::map<osg::Vec3d, DistanceFileInfoMap> OrientationFileInfoMap; typedef std::map<osg::Vec3d, DistanceFileInfoMap> OrientationFileInfoMap;
for(OrientationFileInfoMap::iterator itr = orientationFileInfoMap.begin(); for(OrientationFileInfoMap::iterator itr = orientationFileInfoMap.begin();
@ -707,7 +749,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
info()<<" d = "<<fileInfo.distance<<" "<<fileInfo.filename<<std::endl; info()<<" d = "<<fileInfo.distance<<" "<<fileInfo.filename<<std::endl;
} }
} }
DistanceFileInfoMap& dfim = orientationFileInfoMap.begin()->second; DistanceFileInfoMap& dfim = orientationFileInfoMap.begin()->second;
if (dfim.empty()) return 0; if (dfim.empty()) return 0;
@ -721,11 +763,11 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
{ {
totalDistance = dfim.begin()->second.sliceThickness * double(dfim.begin()->second.numSlices); totalDistance = dfim.begin()->second.sliceThickness * double(dfim.begin()->second.numSlices);
} }
info()<<"Total Distance including ends "<<totalDistance<<std::endl; info()<<"Total Distance including ends "<<totalDistance<<std::endl;
double averageThickness = totalNumSlices<=1 ? 1.0 : totalDistance / double(totalNumSlices-1); double averageThickness = totalNumSlices<=1 ? 1.0 : totalDistance / double(totalNumSlices-1);
info()<<"Average thickness "<<averageThickness<<std::endl; info()<<"Average thickness "<<averageThickness<<std::endl;
for(DistanceFileInfoMap::iterator ditr = dfim.begin(); for(DistanceFileInfoMap::iterator ditr = dfim.begin();
@ -733,7 +775,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
++ditr) ++ditr)
{ {
FileInfo& fileInfo = ditr->second; FileInfo& fileInfo = ditr->second;
std::auto_ptr<DicomImage> dcmImage(new DicomImage(fileInfo.filename.c_str())); std::auto_ptr<DicomImage> dcmImage(new DicomImage(fileInfo.filename.c_str()));
if (dcmImage.get()) if (dcmImage.get())
{ {
@ -742,14 +784,14 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
// get the pixel data // get the pixel data
const DiPixel* pixelData = dcmImage->getInterData(); const DiPixel* pixelData = dcmImage->getInterData();
if(!pixelData) if(!pixelData)
{ {
warning()<<"Error: no data in DicomImage object."<<std::endl; warning()<<"Error: no data in DicomImage object."<<std::endl;
return ReadResult::ERROR_IN_READING_FILE; return ReadResult::ERROR_IN_READING_FILE;
} }
osg::ref_ptr<osg::Image> imageAdapter = new osg::Image; osg::ref_ptr<osg::Image> imageAdapter = new osg::Image;
EP_Representation curr_pixelRep; EP_Representation curr_pixelRep;
int curr_numPlanes; int curr_numPlanes;
GLenum curr_pixelFormat; GLenum curr_pixelFormat;
@ -758,15 +800,15 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
// create the new image // create the new image
convertPixelTypes(pixelData, convertPixelTypes(pixelData,
curr_pixelRep, curr_numPlanes, curr_pixelRep, curr_numPlanes,
curr_dataType, curr_pixelFormat, curr_pixelSize); curr_dataType, curr_pixelFormat, curr_pixelSize);
imageAdapter->setImage(dcmImage->getWidth(), dcmImage->getHeight(), dcmImage->getFrameCount(), imageAdapter->setImage(dcmImage->getWidth(), dcmImage->getHeight(), dcmImage->getFrameCount(),
curr_pixelFormat, curr_pixelFormat,
curr_pixelFormat, curr_pixelFormat,
curr_dataType, curr_dataType,
(unsigned char*)(pixelData->getData()), (unsigned char*)(pixelData->getData()),
osg::Image::NO_DELETE); osg::Image::NO_DELETE);
if (!image) if (!image)
{ {
pixelRep = curr_pixelRep; pixelRep = curr_pixelRep;
@ -775,6 +817,8 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
pixelFormat = curr_pixelFormat; pixelFormat = curr_pixelFormat;
pixelSize = curr_pixelSize; pixelSize = curr_pixelSize;
osg::RefMatrix* matrix = details->getMatrix();
(*matrix)(0,0) = fileInfo.matrix(0,0); (*matrix)(0,0) = fileInfo.matrix(0,0);
(*matrix)(1,0) = fileInfo.matrix(1,0); (*matrix)(1,0) = fileInfo.matrix(1,0);
(*matrix)(2,0) = fileInfo.matrix(2,0); (*matrix)(2,0) = fileInfo.matrix(2,0);
@ -784,49 +828,50 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
(*matrix)(0,2) = fileInfo.matrix(0,2) * averageThickness; (*matrix)(0,2) = fileInfo.matrix(0,2) * averageThickness;
(*matrix)(1,2) = fileInfo.matrix(1,2) * averageThickness; (*matrix)(1,2) = fileInfo.matrix(1,2) * averageThickness;
(*matrix)(2,2) = fileInfo.matrix(2,2) * averageThickness; (*matrix)(2,2) = fileInfo.matrix(2,2) * averageThickness;
details->setRescaleIntercept(fileInfo.rescaleIntercept);
details->setRescaleSlope(fileInfo.rescaleSlope);
image = new osg::Image; image = new osg::Image;
image->setUserData(matrix.get()); image->setUserData(details.get());
image->setFileName(fileName.c_str()); image->setFileName(fileName.c_str());
image->allocateImage(dcmImage->getWidth(), dcmImage->getHeight(), totalNumSlices, image->allocateImage(dcmImage->getWidth(), dcmImage->getHeight(), totalNumSlices,
pixelFormat, dataType); pixelFormat, dataType);
matrix->preMult(osg::Matrix::scale(double(image->s()), double(image->t()), double(image->r()))); matrix->preMult(osg::Matrix::scale(double(image->s()), double(image->t()), double(image->r())));
info()<<"Image dimensions = "<<image->s()<<", "<<image->t()<<", "<<image->r()<<" pixelFormat=0x"<<std::hex<<pixelFormat<<" dataType=0x"<<std::hex<<dataType<<std::dec<<std::endl; info()<<"Image dimensions = "<<image->s()<<", "<<image->t()<<", "<<image->r()<<" pixelFormat=0x"<<std::hex<<pixelFormat<<" dataType=0x"<<std::hex<<dataType<<std::dec<<std::endl;
} }
else if (pixelData->getPlanes()>numPlanes || else if (pixelData->getPlanes()>numPlanes ||
pixelData->getRepresentation()>pixelRep) pixelData->getRepresentation()>pixelRep)
{ {
info()<<"Need to reallocated "<<image->s()<<", "<<image->t()<<", "<<image->r()<<std::endl; info()<<"Need to reallocated "<<image->s()<<", "<<image->t()<<", "<<image->r()<<std::endl;
// record the previous image settings to use when we copy back the content. // record the previous image settings to use when we copy back the content.
osg::ref_ptr<osg::Image> previous_image = image; osg::ref_ptr<osg::Image> previous_image = image;
// create the new image // create the new image
convertPixelTypes(pixelData, convertPixelTypes(pixelData,
pixelRep, numPlanes, pixelRep, numPlanes,
dataType, pixelFormat, pixelSize); dataType, pixelFormat, pixelSize);
image = new osg::Image; image = new osg::Image;
image->setUserData(previous_image->getUserData()); image->setUserData(previous_image->getUserData());
image->setFileName(fileName.c_str()); image->setFileName(fileName.c_str());
image->allocateImage(dcmImage->getWidth(), dcmImage->getHeight(), totalNumSlices, image->allocateImage(dcmImage->getWidth(), dcmImage->getHeight(), totalNumSlices,
pixelFormat, dataType); pixelFormat, dataType);
osg::copyImage(previous_image.get(), 0,0,0, previous_image->s(), previous_image->t(), imageNum, osg::copyImage(previous_image.get(), 0,0,0, previous_image->s(), previous_image->t(), imageNum,
image.get(), 0, 0, 0, image.get(), 0, 0, 0,
false); false);
} }
osg::copyImage(imageAdapter.get(), 0,0,0, imageAdapter->s(), imageAdapter->t(), imageAdapter->r(), osg::copyImage(imageAdapter.get(), 0,0,0, imageAdapter->s(), imageAdapter->t(), imageAdapter->r(),
image.get(), 0, 0, imageNum, image.get(), 0, 0, imageNum,
false); false);
imageNum += dcmImage->getFrameCount(); imageNum += dcmImage->getFrameCount();
} }
else else
@ -835,14 +880,14 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
} }
} }
} }
if (!image) if (!image)
{ {
return ReadResult::ERROR_IN_READING_FILE; return ReadResult::ERROR_IN_READING_FILE;
} }
info()<<"Spacing = "<<*matrix<<std::endl; info()<<"Spacing = "<<*(details->getMatrix())<<std::endl;
return image.get(); return image.get();
} }
#endif #endif
@ -850,6 +895,8 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
struct FileInfo struct FileInfo
{ {
FileInfo(): FileInfo():
rescaleIntercept(0.0),
rescaleSlope(1.0),
numX(0), numX(0),
numY(0), numY(0),
numSlices(1), numSlices(1),
@ -859,6 +906,8 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
FileInfo(const FileInfo& rhs): FileInfo(const FileInfo& rhs):
filename(rhs.filename), filename(rhs.filename),
matrix(rhs.matrix), matrix(rhs.matrix),
rescaleIntercept(rhs.rescaleIntercept),
rescaleSlope(rhs.rescaleSlope),
numX(rhs.numX), numX(rhs.numX),
numY(rhs.numY), numY(rhs.numY),
numSlices(rhs.numSlices), numSlices(rhs.numSlices),
@ -868,20 +917,24 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
FileInfo& operator = (const FileInfo& rhs) FileInfo& operator = (const FileInfo& rhs)
{ {
if (&rhs == this) return *this; if (&rhs == this) return *this;
filename = rhs.filename; filename = rhs.filename;
matrix = rhs.matrix; matrix = rhs.matrix;
rescaleIntercept = rhs.rescaleIntercept;
rescaleSlope = rhs.rescaleSlope;
numX = rhs.numX; numX = rhs.numX;
numY = rhs.numY; numY = rhs.numY;
sliceThickness = rhs.sliceThickness; sliceThickness = rhs.sliceThickness;
numSlices = rhs.numSlices; numSlices = rhs.numSlices;
distance = rhs.distance; distance = rhs.distance;
return *this; return *this;
} }
std::string filename; std::string filename;
osg::Matrixd matrix; osg::Matrixd matrix;
double rescaleIntercept;
double rescaleSlope;
unsigned int numX; unsigned int numX;
unsigned int numY; unsigned int numY;
unsigned int numSlices; unsigned int numSlices;

View File

@ -1,14 +1,14 @@
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield
* *
* This library is open source and may be redistributed and/or modified under * This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file * (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website. * included with this distribution, and on the openscenegraph.org website.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details. * OpenSceneGraph Public License for more details.
*/ */
#include <osgVolume/Layer> #include <osgVolume/Layer>
@ -21,6 +21,19 @@
using namespace osgVolume; using namespace osgVolume;
ImageDetails::ImageDetails():
_rescaleIntercept(0.0),
_rescaleSlope(1.0)
{
}
ImageDetails::ImageDetails(const ImageDetails& rhs,const osg::CopyOp& copyop):
_rescaleIntercept(rhs._rescaleIntercept),
_rescaleSlope(rhs._rescaleSlope),
_matrix(rhs._matrix)
{
}
Layer::Layer(): Layer::Layer():
_minFilter(osg::Texture::LINEAR), _minFilter(osg::Texture::LINEAR),
_magFilter(osg::Texture::LINEAR) _magFilter(osg::Texture::LINEAR)
@ -42,10 +55,10 @@ Layer::~Layer()
osg::BoundingSphere Layer::computeBound() const osg::BoundingSphere Layer::computeBound() const
{ {
if (!getLocator()) return osg::BoundingSphere(); if (!getLocator()) return osg::BoundingSphere();
osg::Vec3d left, right; osg::Vec3d left, right;
getLocator()->computeLocalBounds(left, right); getLocator()->computeLocalBounds(left, right);
//osg::notify(osg::NOTICE)<<"left = "<<left<<std::endl; //osg::notify(osg::NOTICE)<<"left = "<<left<<std::endl;
//osg::notify(osg::NOTICE)<<"right = "<<right<<std::endl; //osg::notify(osg::NOTICE)<<"right = "<<right<<std::endl;
@ -57,12 +70,12 @@ void Layer::addProperty(Property* property)
{ {
if (!property) return; if (!property) return;
if (!_property) if (!_property)
{ {
_property = property; _property = property;
return; return;
} }
CompositeProperty* cp = dynamic_cast<CompositeProperty*>(_property.get()); CompositeProperty* cp = dynamic_cast<CompositeProperty*>(_property.get());
if (cp) if (cp)
{ {
@ -82,12 +95,16 @@ void Layer::addProperty(Property* property)
// ImageLayer // ImageLayer
// //
ImageLayer::ImageLayer(osg::Image* image): ImageLayer::ImageLayer(osg::Image* image):
_rescaleIntercept(0.0),
_rescaleSlope(1.0),
_image(image) _image(image)
{ {
} }
ImageLayer::ImageLayer(const ImageLayer& imageLayer,const osg::CopyOp& copyop): ImageLayer::ImageLayer(const ImageLayer& imageLayer,const osg::CopyOp& copyop):
Layer(imageLayer, copyop), Layer(imageLayer, copyop),
_rescaleIntercept(imageLayer._rescaleIntercept),
_rescaleSlope(imageLayer._rescaleSlope),
_image(imageLayer._image) _image(imageLayer._image)
{ {
} }
@ -123,12 +140,16 @@ bool ImageLayer::computeMinMax(osg::Vec4& minValue, osg::Vec4& maxValue)
void ImageLayer::offsetAndScaleImage(const osg::Vec4& offset, const osg::Vec4& scale) void ImageLayer::offsetAndScaleImage(const osg::Vec4& offset, const osg::Vec4& scale)
{ {
if (!_image) return; if (!_image) return;
osg::offsetAndScaleImage(_image.get(), offset, scale); osg::offsetAndScaleImage(_image.get(), offset, scale);
} }
void ImageLayer::rescaleToZeroToOneRange() void ImageLayer::rescaleToZeroToOneRange()
{ {
osg::notify(osg::NOTICE)<<"ImageLayer::rescaleToZeroToOneRange()"<<std::endl;
osg::notify(osg::NOTICE)<<" _rescaleIntercept "<<_rescaleIntercept<<std::endl;
osg::notify(osg::NOTICE)<<" _rescaleSlope "<<_rescaleSlope<<std::endl;
osg::Vec4 minValue, maxValue; osg::Vec4 minValue, maxValue;
if (computeMinMax(minValue, maxValue)) if (computeMinMax(minValue, maxValue))
{ {
@ -141,10 +162,13 @@ void ImageLayer::rescaleToZeroToOneRange()
maxComponent = osg::maximum(maxComponent,maxValue[1]); maxComponent = osg::maximum(maxComponent,maxValue[1]);
maxComponent = osg::maximum(maxComponent,maxValue[2]); maxComponent = osg::maximum(maxComponent,maxValue[2]);
maxComponent = osg::maximum(maxComponent,maxValue[3]); maxComponent = osg::maximum(maxComponent,maxValue[3]);
float scale = 0.99f/(maxComponent-minComponent); float scale = 0.99f/(maxComponent-minComponent);
float offset = -minComponent * scale; float offset = -minComponent * scale;
osg::notify(osg::NOTICE)<<" scale "<<scale<<std::endl;
osg::notify(osg::NOTICE)<<" offset "<<offset<<std::endl;
offsetAndScaleImage(osg::Vec4(offset, offset, offset, offset), offsetAndScaleImage(osg::Vec4(offset, offset, offset, offset),
osg::Vec4(scale, scale, scale, scale)); osg::Vec4(scale, scale, scale, scale));
} }
@ -204,7 +228,7 @@ bool CompositeLayer::requiresUpdateTraversal() const
{ {
if (itr->layer->requiresUpdateTraversal()) return true; if (itr->layer->requiresUpdateTraversal()) return true;
} }
return false; return false;
} }
@ -216,7 +240,7 @@ void CompositeLayer::update(osg::NodeVisitor& nv)
{ {
itr->layer->update(nv); itr->layer->update(nv);
} }
} }
@ -231,7 +255,7 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d)
GLenum dataType = image_3d->getDataType(); GLenum dataType = image_3d->getDataType();
unsigned int sourcePixelIncrement = 1; unsigned int sourcePixelIncrement = 1;
unsigned int alphaOffset = 0; unsigned int alphaOffset = 0;
switch(image_3d->getPixelFormat()) switch(image_3d->getPixelFormat())
{ {
case(GL_ALPHA): case(GL_ALPHA):
@ -269,7 +293,7 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d)
{ {
if (dataType==GL_UNSIGNED_BYTE) if (dataType==GL_UNSIGNED_BYTE)
{ {
unsigned char* ptr = image_3d->data(1,t,r)+alphaOffset; unsigned char* ptr = image_3d->data(1,t,r)+alphaOffset;
unsigned char* left = image_3d->data(0,t,r)+alphaOffset; unsigned char* left = image_3d->data(0,t,r)+alphaOffset;
unsigned char* right = image_3d->data(2,t,r)+alphaOffset; unsigned char* right = image_3d->data(2,t,r)+alphaOffset;
@ -284,8 +308,8 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d)
{ {
osg::Vec3 grad((float)(*left)-(float)(*right), osg::Vec3 grad((float)(*left)-(float)(*right),
(float)(*below)-(float)(*above), (float)(*below)-(float)(*above),
(float)(*out) -(float)(*in)); (float)(*out) -(float)(*in));
grad.normalize(); grad.normalize();
@ -331,8 +355,8 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d)
{ {
osg::Vec3 grad((float)(*left)-(float)(*right), osg::Vec3 grad((float)(*left)-(float)(*right),
(float)(*below)-(float)(*above), (float)(*below)-(float)(*above),
(float)(*out) -(float)(*in)); (float)(*out) -(float)(*in));
grad.normalize(); grad.normalize();
@ -348,7 +372,7 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d)
grad.y() = osg::clampBetween((grad.y()+1.0f)*128.0f,0.0f,255.0f); grad.y() = osg::clampBetween((grad.y()+1.0f)*128.0f,0.0f,255.0f);
grad.z() = osg::clampBetween((grad.z()+1.0f)*128.0f,0.0f,255.0f); grad.z() = osg::clampBetween((grad.z()+1.0f)*128.0f,0.0f,255.0f);
} }
*(destination++) = (unsigned char)(grad.x()); // scale and bias X. *(destination++) = (unsigned char)(grad.x()); // scale and bias X.
*(destination++) = (unsigned char)(grad.y()); // scale and bias Y. *(destination++) = (unsigned char)(grad.y()); // scale and bias Y.
@ -381,8 +405,8 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d)
{ {
osg::Vec3 grad((float)(*left)-(float)(*right), osg::Vec3 grad((float)(*left)-(float)(*right),
(float)(*below)-(float)(*above), (float)(*below)-(float)(*above),
(float)(*out) -(float)(*in)); (float)(*out) -(float)(*in));
grad.normalize(); grad.normalize();
@ -414,10 +438,10 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d)
} }
} }
} }
osg::notify(osg::INFO)<<"Created NormalMapTexture"<<std::endl; osg::notify(osg::INFO)<<"Created NormalMapTexture"<<std::endl;
return normalmap_3d.release(); return normalmap_3d.release();
} }
@ -430,7 +454,7 @@ struct ApplyTransferFunctionOperator
ApplyTransferFunctionOperator(osg::TransferFunction1D* tf, unsigned char* data): ApplyTransferFunctionOperator(osg::TransferFunction1D* tf, unsigned char* data):
_tf(tf), _tf(tf),
_data(data) {} _data(data) {}
inline void luminance(float l) const inline void luminance(float l) const
{ {
osg::Vec4 c = _tf->getColor(l); osg::Vec4 c = _tf->getColor(l);
@ -440,27 +464,27 @@ struct ApplyTransferFunctionOperator
*(_data++) = (unsigned char)(c[2]*255.0f + 0.5f); *(_data++) = (unsigned char)(c[2]*255.0f + 0.5f);
*(_data++) = (unsigned char)(c[3]*255.0f + 0.5f); *(_data++) = (unsigned char)(c[3]*255.0f + 0.5f);
} }
inline void alpha(float a) const inline void alpha(float a) const
{ {
luminance(a); luminance(a);
} }
inline void luminance_alpha(float l,float a) const inline void luminance_alpha(float l,float a) const
{ {
luminance(l); luminance(l);
} }
inline void rgb(float r,float g,float b) const inline void rgb(float r,float g,float b) const
{ {
luminance((r+g+b)*0.3333333); luminance((r+g+b)*0.3333333);
} }
inline void rgba(float r,float g,float b,float a) const inline void rgba(float r,float g,float b,float a) const
{ {
luminance(a); luminance(a);
} }
mutable osg::ref_ptr<osg::TransferFunction1D> _tf; mutable osg::ref_ptr<osg::TransferFunction1D> _tf;
mutable unsigned char* _data; mutable unsigned char* _data;
}; };
@ -468,12 +492,12 @@ struct ApplyTransferFunctionOperator
osg::Image* osgVolume::applyTransferFunction(osg::Image* image, osg::TransferFunction1D* transferFunction) osg::Image* osgVolume::applyTransferFunction(osg::Image* image, osg::TransferFunction1D* transferFunction)
{ {
osg::notify(osg::INFO)<<"Applying transfer function"<<std::endl; osg::notify(osg::INFO)<<"Applying transfer function"<<std::endl;
osg::Image* output_image = new osg::Image; osg::Image* output_image = new osg::Image;
output_image->allocateImage(image->s(),image->t(), image->r(), GL_RGBA, GL_UNSIGNED_BYTE); output_image->allocateImage(image->s(),image->t(), image->r(), GL_RGBA, GL_UNSIGNED_BYTE);
ApplyTransferFunctionOperator op(transferFunction, output_image->data()); ApplyTransferFunctionOperator op(transferFunction, output_image->data());
osg::readImage(image,op); osg::readImage(image,op);
return output_image; return output_image;
} }