OpenSceneGraph实现的NeHe OpenGL教程 - 第二十九课

  • 简介

这节课NeHe课程教我们如何读取一张raw格式的图片,并且对两张raw格式图片进行处理生成了一张纹理图片。整个过程并不是十分复杂,文中大部分内容涉及到图片数据的操作。

  • 实现

首先我们创建需要显示的立方体:

[cpp]  view plain  copy
  1. osg::Geode* createCubeGeode(osg::Image *image)  
  2. {  
  3.     osg::Geometry *quadGeometry = new osg::Geometry;  
  4.     osg::Vec3Array *quadVertexArray = new osg::Vec3Array;  
  5.     for (unsigned i = 0; i < sizeof(QuadVertices); ++i)  
  6.     {  
  7.         quadVertexArray->push_back(osg::Vec3(QuadVertices[i][0], QuadVertices[i][1], QuadVertices[i][2]));  
  8.     }  
  9.     quadGeometry->setVertexArray(quadVertexArray);  
  10.  ......  
  11. }  
接着我们需要创建纹理所需要的image,这里的raw格式图片实际上并不是一种通用的格式,在osg中也并不支持。我们需要将raw格式中的字节数据读取出来并赋值给osg::Image用来作为我们的纹理图片。

首先我们使用NeHe中用到的函数读取图片:(函数代码并不完整,完整代码查看后面的附录中源码)

[cpp]  view plain  copy
  1. osg::Image*  ReadTextureData ( char *filename, unsigned int width, unsigned int height, unsigned int pixelPerBytes)  
  2. {  
  3.     //NeHe中使用256x256大小的图片,并且每个像素的字节数是4  
  4.     //因此这里在分配内存是使用RGBA都是8位的方式(1个字节)  
  5.     //正好是4个字节  
  6.     osg::Image *buffer = new osg::Image;  
  7.     buffer->allocateImage(width, height, 1, GL_RGBA, GL_UNSIGNED_BYTE);  
  8.     int bytesPerPixel = buffer->getPixelSizeInBits() / 8;  
  9.   
  10.     FILE *f;  
  11.     int i,j,k,done=0;  
  12.     int stride = buffer->s() * buffer->getPixelSizeInBits() / 8;              // Size Of A Row (Width * Bytes Per Pixel)  
  13.     unsigned char *p = NULL;  
  14. ......  
  15. }  
图片加载之后,我们使用Blit函数来对两张图片中的数据进行一些处理,具体代码参考Blit函数

最后生成我们的256x256的大小的纹理,图片的每个像素占用4个字节:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. osg::Image* createTextureImage()  
  2. {  
  3.     osg::Image *src = ReadTextureData("Data/GL.raw",  256, 256, 32);  
  4.     osg::Image *dst = ReadTextureData("Data/Monitor.raw", 256, 256, 32);  
  5.       
  6.     Blit(src,dst,127,127,128,128,64,64,1,127);  
  7.     return dst;  
  8. }  

将图片设置给立方体纹理,场景中为了简便用AnimationPathCallback来进行旋转:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. osg::AnimationPathCallback *quadAnimationCallbackX =   
  2.     new osg::AnimationPathCallback(osg::Vec3d(0, 0, 0), osg::Vec3(1, 0, 0), 2.5);  
  3.   
  4. osg::AnimationPathCallback *quadAnimationCallbackY =   
  5.     new osg::AnimationPathCallback(osg::Vec3d(0, 0, 0), osg::Vec3(0, 1, 0), 1.5);  
  6.   
  7. osg::AnimationPathCallback *quadAnimationCallbackZ =   
  8.     new osg::AnimationPathCallback(osg::Vec3d(0, 0, 0), osg::Vec3(0, 0, 1), 0.5);  
  9.   
  10. osg::MatrixTransform *quadXRotMT = new osg::MatrixTransform;  
  11. quadXRotMT->setUpdateCallback(quadAnimationCallbackX);  
  12.   
  13. osg::MatrixTransform *quadYRotMT = new osg::MatrixTransform;  
  14. quadYRotMT->setUpdateCallback(quadAnimationCallbackY);  
  15.   
  16. osg::MatrixTransform *quadZRotMT = new osg::MatrixTransform;  
  17. quadZRotMT->setUpdateCallback(quadAnimationCallbackZ);  
  18.   
  19. quadMT->addChild(quadXRotMT);  
  20. quadXRotMT->addChild(quadYRotMT);  
  21. quadYRotMT->addChild(quadZRotMT);  
  22.   
  23. osg::Image *image = createTextureImage();  
  24. quadZRotMT->addChild(createCubeGeode(image));  
一般来说,纹理操作很少使用这种方式进行,大部分都是通过加载多重纹理的方式来实现贴多张纹理,并设置其中纹理的作用方式。这种方式相当于先将多张纹理处理成一张再贴到物体上。编译运行程序:


附:本课源码(源码中可能存在错误和不足,仅供参考)

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include "../osgNeHe.h"  
  2.   
  3. #include <QtCore/QTimer>  
  4. #include <QtGui/QApplication>  
  5. #include <QtGui/QVBoxLayout>  
  6.   
  7. #include <osgViewer/Viewer>  
  8. #include <osgDB/ReadFile>  
  9. #include <osgQt/GraphicsWindowQt>  
  10.   
  11. #include <osg/MatrixTransform>  
  12. #include <osg/Texture2D>  
  13.   
  14. #include <osg/AnimationPath>  
  15.   
  16.   
  17.   
  18. float textureVertices[][2] = {  
  19.     //Front Face  
  20.     {0.0f, 0.0f},  
  21.     {1.0f, 0.0f},  
  22.     {1.0f, 1.0f},  
  23.     {0.0f, 1.0f},  
  24.     // Back Face  
  25.     {1.0f, 0.0f},  
  26.     {1.0f, 1.0f},  
  27.     {0.0f, 1.0f},  
  28.     {0.0f, 0.0f},  
  29.     // Top Face  
  30.     {0.0f, 1.0f},  
  31.     {0.0f, 0.0f},  
  32.     {1.0f, 0.0f},  
  33.     {1.0f, 1.0f},  
  34.     // Bottom Face  
  35.     {1.0f, 1.0f},  
  36.     {0.0f, 1.0f},  
  37.     {0.0f, 0.0f},  
  38.     {1.0f, 0.0f},  
  39.     // Right face  
  40.     {1.0f, 0.0f},  
  41.     {1.0f, 1.0f},  
  42.     {0.0f, 1.0f},  
  43.     {0.0f, 0.0f},  
  44.     // Left Face  
  45.     {0.0f, 0.0f},  
  46.     {1.0f, 0.0f},  
  47.     {1.0f, 1.0f},  
  48.     {0.0f, 1.0f}  
  49. };  
  50.   
  51. float QuadVertices[][3] = {  
  52.   
  53.     {-1.0f, -1.0f,  1.0f},  
  54.     { 1.0f, -1.0f,  1.0f},  
  55.     { 1.0f,  1.0f,  1.0f},  
  56.     {-1.0f,  1.0f,  1.0f},  
  57.   
  58.     {-1.0f, -1.0f, -1.0f},  
  59.     {-1.0f,  1.0f, -1.0f},  
  60.     { 1.0f,  1.0f, -1.0f},  
  61.     { 1.0f, -1.0f, -1.0f},  
  62.   
  63.     {-1.0f,  1.0f, -1.0f},  
  64.     {-1.0f,  1.0f,  1.0f},  
  65.     { 1.0f,  1.0f,  1.0f},  
  66.     { 1.0f,  1.0f, -1.0f},  
  67.   
  68.     {-1.0f, -1.0f, -1.0f},  
  69.     { 1.0f, -1.0f, -1.0f},  
  70.     { 1.0f, -1.0f,  1.0f},  
  71.     {-1.0f, -1.0f,  1.0f},  
  72.   
  73.     { 1.0f, -1.0f, -1.0f},  
  74.     { 1.0f,  1.0f, -1.0f},  
  75.     { 1.0f,  1.0f,  1.0f},  
  76.     { 1.0f, -1.0f,  1.0f},  
  77.   
  78.     {-1.0f, -1.0f, -1.0f},  
  79.     {-1.0f, -1.0f,  1.0f},  
  80.     {-1.0f,  1.0f,  1.0f},  
  81.     {-1.0f,  1.0f, -1.0f}  
  82.   
  83. };  
  84.   
  85.   
  86. float normalsArray[][3] = {  
  87.     {0.0f, 0.0f, 1.0f},  
  88.     {0.0f, 0.0f,-1.0f},  
  89.     {0.0f, 1.0f, 0.0f},  
  90.     {0.0f,-1.0f, 0.0f},  
  91.     {1.0f, 0.0f, 0.0f},  
  92.     {-1.0f, 0.0f, 0.0f}  
  93. };  
  94.   
  95.   
  96. //  
  97. osg::Geode* createCubeGeode(osg::Image *image)  
  98. {  
  99.     osg::Geometry *quadGeometry = new osg::Geometry;  
  100.     osg::Vec3Array *quadVertexArray = new osg::Vec3Array;  
  101.     for (unsigned i = 0; i < sizeof(QuadVertices); ++i)  
  102.     {  
  103.         quadVertexArray->push_back(osg::Vec3(QuadVertices[i][0], QuadVertices[i][1], QuadVertices[i][2]));  
  104.     }  
  105.     quadGeometry->setVertexArray(quadVertexArray);  
  106.   
  107.     osg::Vec2Array* texcoords = new osg::Vec2Array;  
  108.     for (unsigned i = 0; i < sizeof(textureVertices); ++i)  
  109.     {  
  110.         texcoords->push_back(osg::Vec2(textureVertices[i][0], textureVertices[i][1]));  
  111.     }  
  112.     quadGeometry->setTexCoordArray(0,texcoords);  
  113.   
  114.     osg::Vec3Array *normals = new osg::Vec3Array;  
  115.     for (unsigned i = 0; i < sizeof(normals); ++i)  
  116.     {  
  117.         for (int j = 0; j < 4; ++j)  
  118.         {  
  119.             normals->push_back(osg::Vec3(normalsArray[i][0], normalsArray[i][1], normalsArray[i][2]));  
  120.         }  
  121.     }  
  122.     quadGeometry->setNormalArray(normals, osg::Array::BIND_PER_VERTEX);  
  123.     int first = 0;  
  124.     for (unsigned i = 0; i < 6; ++i)  
  125.     {  
  126.         osg::DrawArrays *vertexIndices = new osg::DrawArrays(osg::PrimitiveSet::QUADS, first, 4);  
  127.         first += 4;  
  128.         quadGeometry->addPrimitiveSet(vertexIndices);  
  129.     }  
  130.   
  131.     osg::Texture2D *texture2D = new osg::Texture2D;  
  132.     texture2D->setImage(image);  
  133.     texture2D->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);  
  134.     texture2D->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);  
  135.   
  136.     quadGeometry->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture2D);  
  137.     quadGeometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);  
  138.   
  139.     osg::Geode *quadGeode = new osg::Geode;  
  140.     quadGeode->addDrawable(quadGeometry);  
  141.   
  142.     return quadGeode;  
  143. }  
  144.   
  145. //  
  146. //  
  147. //操作Raw纹理  
  148.   
  149. osg::Image*  ReadTextureData ( char *filename, unsigned int width, unsigned int height, unsigned int pixelPerBytes)  
  150. {  
  151.     //NeHe中使用256x256大小的图片,并且每个像素的字节数是4  
  152.     //因此这里在分配内存是使用RGBA都是8位的方式(1个字节)  
  153.     //正好是4个字节  
  154.     osg::Image *buffer = new osg::Image;  
  155.     buffer->allocateImage(width, height, 1, GL_RGBA, GL_UNSIGNED_BYTE);  
  156.     int bytesPerPixel = buffer->getPixelSizeInBits() / 8;  
  157.   
  158.     FILE *f;  
  159.     int i,j,k,done=0;  
  160.     int stride = buffer->s() * buffer->getPixelSizeInBits() / 8;              // Size Of A Row (Width * Bytes Per Pixel)  
  161.     unsigned char *p = NULL;  
  162.   
  163.     f = fopen(filename, "rb");                                  // Open "filename" For Reading Bytes  
  164.     if( f != NULL )                                             // If File Exists  
  165.     {  
  166.         for( i = buffer->t()-1; i >= 0 ; i-- )                // Loop Through Height (Bottoms Up - Flip Image)  
  167.         {  
  168.             p = buffer->data() + (i * stride );                  //   
  169.             for ( j = 0; j < buffer->s() ; j++ )              // Loop Through Width  
  170.             {  
  171.                 for ( k = 0 ; k < buffer->getPixelSizeInBits() / 8-1 ; k++, p++, done++ )  
  172.                 {  
  173.                     *p = fgetc(f);                              // Read Value From File And Store In Memory  
  174.                 }  
  175.                 *p = 255; p++;                                  // Store 255 In Alpha Channel And Increase Pointer  
  176.             }  
  177.         }  
  178.         fclose(f);                                              // Close The File  
  179.     }  
  180.     return buffer;                                              // Returns Number Of Bytes Read In  
  181. }  
  182.   
  183.   
  184. void Blit( osg::Image *src, osg::Image *dst,   
  185.           int src_xstart, int src_ystart, int src_width, int src_height,  
  186.           int dst_xstart, int dst_ystart, int blend, int alpha)  
  187. {  
  188.     int i,j,k;  
  189.     unsigned char *s, *d;  
  190.   
  191.     // Clamp Alpha If Value Is Out Of Range  
  192.     if( alpha > 255 ) alpha = 255;  
  193.     if( alpha < 0 ) alpha = 0;  
  194.   
  195.     // Check For Incorrect Blend Flag Values  
  196.     if( blend < 0 ) blend = 0;  
  197.     if( blend > 1 ) blend = 1;  
  198.   
  199.     d = dst->data() + (dst_ystart * dst->s() * dst->getPixelSizeInBits() / 8);    // Start Row - dst (Row * Width In Pixels * Bytes Per Pixel)  
  200.     s = src->data() + (src_ystart * src->s() * src->getPixelSizeInBits() / 8);    // Start Row - src (Row * Width In Pixels * Bytes Per Pixel)  
  201.   
  202.     for (i = 0 ; i < src_height ; i++ )                          // Height Loop  
  203.     {  
  204.         s = s + (src_xstart * src->getPixelSizeInBits() / 8);                        // Move Through Src Data By Bytes Per Pixel  
  205.         d = d + (dst_xstart * dst->getPixelSizeInBits() / 8);                        // Move Through Dst Data By Bytes Per Pixel  
  206.         for (j = 0 ; j < src_width ; j++ )                       // Width Loop  
  207.         {  
  208.             for( k = 0 ; k < src->getPixelSizeInBits()/8 ; k++, d++, s++)     // "n" Bytes At A Time  
  209.             {  
  210.                 if (blend)                                      // If Blending Is On  
  211.                     *d = ( (*s * alpha) + (*d * (255-alpha)) ) >> 8; // Multiply Src Data*alpha Add Dst Data*(255-alpha)  
  212.                 else                                            // Keep in 0-255 Range With >> 8  
  213.                     *d = *s;                                    // No Blending Just Do A Straight Copy  
  214.             }  
  215.         }  
  216.         d = d + (dst->s() - (src_width + dst_xstart))*dst->getPixelSizeInBits()/8;    // Add End Of Row */  
  217.         s = s + (src->s() - (src_width + src_xstart))*src->getPixelSizeInBits()/8;    // Add End Of Row */  
  218.     }  
  219. }  
  220.   
  221.   
  222. osg::Image* createTextureImage()  
  223. {  
  224.     osg::Image *src = ReadTextureData("Data/GL.raw",  256, 256, 32);  
  225.     osg::Image *dst = ReadTextureData("Data/Monitor.raw", 256, 256, 32);  
  226.       
  227.     Blit(src,dst,127,127,128,128,64,64,1,127);  
  228.     return dst;  
  229. }  
  230.   
  231.   
  232. //  
  233. //  
  234.   
  235.   
  236.   
  237. class ViewerWidget : public QWidget, public osgViewer::Viewer  
  238. {  
  239. public:  
  240.     ViewerWidget(osg::Node *scene = NULL)  
  241.     {  
  242.         QWidget* renderWidget = getRenderWidget( createGraphicsWindow(0,0,100,100), scene);  
  243.   
  244.         QVBoxLayout* layout = new QVBoxLayout;  
  245.         layout->addWidget(renderWidget);  
  246.         layout->setContentsMargins(0, 0, 0, 1);  
  247.         setLayout( layout );  
  248.   
  249.         connect( &_timer, SIGNAL(timeout()), this, SLOT(update()) );  
  250.         _timer.start( 10 );  
  251.     }  
  252.   
  253.     QWidget* getRenderWidget( osgQt::GraphicsWindowQt* gw, osg::Node* scene )  
  254.     {  
  255.         osg::Camera* camera = this->getCamera();  
  256.         camera->setGraphicsContext( gw );  
  257.   
  258.         const osg::GraphicsContext::Traits* traits = gw->getTraits();  
  259.   
  260.         camera->setClearColor( osg::Vec4(0.0, 0.0, 0.0, 1.0) );  
  261.         camera->setViewport( new osg::Viewport(0, 0, traits->width, traits->height) );  
  262.         camera->setProjectionMatrixAsPerspective(45.0f, static_cast<double>(traits->width)/static_cast<double>(traits->height), 0.1f, 100.0f );  
  263.         camera->setViewMatrixAsLookAt(osg::Vec3d(0, 0, 1), osg::Vec3d(0, 0, 0), osg::Vec3d(0, 1, 0));  
  264.   
  265.         this->setSceneData( scene );  
  266.   
  267.         return gw->getGLWidget();  
  268.     }  
  269.   
  270.     osgQt::GraphicsWindowQt* createGraphicsWindow( int x, int y, int w, int h, const std::string& name=""bool windowDecoration=false )  
  271.     {  
  272.         osg::DisplaySettings* ds = osg::DisplaySettings::instance().get();  
  273.         osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;  
  274.         traits->windowName = name;  
  275.         traits->windowDecoration = windowDecoration;  
  276.         traits->x = x;  
  277.         traits->y = y;  
  278.         traits->width = w;  
  279.         traits->height = h;  
  280.         traits->doubleBuffer = true;  
  281.         traits->alpha = ds->getMinimumNumAlphaBits();  
  282.         traits->stencil = ds->getMinimumNumStencilBits();  
  283.         traits->sampleBuffers = ds->getMultiSamples();  
  284.         traits->samples = ds->getNumMultiSamples();  
  285.   
  286.         return new osgQt::GraphicsWindowQt(traits.get());  
  287.     }  
  288.   
  289.     virtual void paintEvent( QPaintEvent* event )  
  290.     {   
  291.         frame();   
  292.     }  
  293.   
  294. protected:  
  295.   
  296.     QTimer _timer;  
  297. };  
  298.   
  299.   
  300.   
  301. osg::Node*  buildScene()  
  302. {  
  303.     osg::Group *root = new osg::Group;  
  304.   
  305.     osg::MatrixTransform *quadMT = new osg::MatrixTransform;  
  306.     quadMT->setMatrix(osg::Matrix::translate(0.0, 0.0, -5.0));  
  307.   
  308.     osg::AnimationPathCallback *quadAnimationCallbackX =   
  309.         new osg::AnimationPathCallback(osg::Vec3d(0, 0, 0), osg::Vec3(1, 0, 0), 2.5);  
  310.   
  311.     osg::AnimationPathCallback *quadAnimationCallbackY =   
  312.         new osg::AnimationPathCallback(osg::Vec3d(0, 0, 0), osg::Vec3(0, 1, 0), 1.5);  
  313.   
  314.     osg::AnimationPathCallback *quadAnimationCallbackZ =   
  315.         new osg::AnimationPathCallback(osg::Vec3d(0, 0, 0), osg::Vec3(0, 0, 1), 0.5);  
  316.   
  317.     osg::MatrixTransform *quadXRotMT = new osg::MatrixTransform;  
  318.     quadXRotMT->setUpdateCallback(quadAnimationCallbackX);  
  319.   
  320.     osg::MatrixTransform *quadYRotMT = new osg::MatrixTransform;  
  321.     quadYRotMT->setUpdateCallback(quadAnimationCallbackY);  
  322.   
  323.     osg::MatrixTransform *quadZRotMT = new osg::MatrixTransform;  
  324.     quadZRotMT->setUpdateCallback(quadAnimationCallbackZ);  
  325.   
  326.     quadMT->addChild(quadXRotMT);  
  327.     quadXRotMT->addChild(quadYRotMT);  
  328.     quadYRotMT->addChild(quadZRotMT);  
  329.   
  330.     osg::Image *image = createTextureImage();  
  331.     quadZRotMT->addChild(createCubeGeode(image));  
  332.   
  333.     root->addChild(quadMT);  
  334.     return root;  
  335. }  
  336.   
  337.   
  338. int main( int argc, char** argv )  
  339. {  
  340.     QApplication app(argc, argv);  
  341.     ViewerWidget* viewWidget = new ViewerWidget(buildScene());  
  342.     viewWidget->setGeometry( 100, 100, 640, 480 );  
  343.     viewWidget->show();  
  344.     return app.exec();  
  345. }  
ESP8266是一款常用的WiFi模块,它支持通过MQTT(Message Queuing Telemetry Transport,消息队列遥测传输协议)连接到物联网服务器,实现设备之间的通信。以下是基本步骤: 1. **安装库**: - 首先,你需要在Arduino IDE中安装`PubSubClient`库,这是一个用于ESP8266与MQTT服务器通信的常用库。 2. **配置WiFi连接**: - 设置ESP8266连接到你的Wi-Fi网络,包括SSID和密码。 3. **设置MQTT客户端**: ```cpp #include <ESP8266WiFi.h> #include < PubSubClient.h > WiFiClient client; PubSubClient mqttClient(client, "your_broker_address", "username", "password"); ``` 这里"your_broker_address"替换为你的MQTT服务器地址,"username"和"password"则是登录账号和密码。 4. **连接到MQTT服务器**: ```cpp void connectToMqtt() { mqttClient.setServer("your_broker_address", 1883); while (!client.connected()) { if (client.connect("ESP8266Client")) { Serial.println("Connected to MQTT broker"); mqttClient.subscribe("$SYS/#"); // 订阅所有主题 } else { delay(5000); // 尝试重连,延时5秒 Serial.print("Attempting to reconnect..."); } } } ``` 5. **发布和订阅主题**: - 发布数据到主题: ```cpp void publish(String topic, String message) { mqttClient.publish(topic, message); Serial.println("Published message to " + topic); } ``` - 订阅并处理接收的数据: ```cpp void loop() { if (mqttClient.connected()) { mqttClient.loop(); // 处理接收到的消息 } // ...其他代码... } ``` 6. **断开连接**: ```cpp void stopMqtt() { mqttClient.disconnect(); Serial.println("Disconnected from MQTT broker"); } ``` 记得根据实际情况调整代码,并在`loop()`函数中添加相应的数据处理逻辑。当你有新的消息要发送或需要监听来自服务器的信息时,只需调用上述相应方法即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值