ぬの部屋(仮)
nu-no-he-ya
  • 1234567
    891011121314
    15161718192021
    22232425262728
    2930     
           
        123
    45678910
    11121314151617
    18192021222324
    25262728293031
           
     123456
    78910111213
    14151617181920
    21222324252627
    28293031   
           
          1
    2345678
    9101112131415
    16171819202122
    23242526272829
    30      
       1234
    567891011
    12131415161718
    19202122232425
    262728293031 
           
     123456
    78910111213
    14151617181920
    21222324252627
    282930    
           
         12
    3456789
    10111213141516
    17181920212223
    24252627282930
    31      
         12
    3456789
    10111213141516
    17181920212223
    2425262728  
           
      12345
    6789101112
    13141516171819
    20212223242526
    2728293031  
           
          1
    2345678
    9101112131415
    16171819202122
    23242526272829
    3031     
        123
    45678910
    11121314151617
    18192021222324
    252627282930 
           
     123456
    78910111213
    14151617181920
    21222324252627
    28293031   
           
          1
    2345678
    9101112131415
    16171819202122
    23242526272829
    30      
       1234
    567891011
    12131415161718
    19202122232425
    262728293031 
           
    1234567
    891011121314
    15161718192021
    22232425262728
    293031    
           
         12
    3456789
    10111213141516
    17181920212223
    24252627282930
           
      12345
    6789101112
    13141516171819
    20212223242526
    2728293031  
           
    1234567
    891011121314
    15161718192021
    22232425262728
    2930     
           
        123
    45678910
    11121314151617
    18192021222324
    25262728293031
           
       1234
    567891011
    12131415161718
    19202122232425
    26272829   
           
    1234567
    891011121314
    15161718192021
    22232425262728
    293031    
           
        123
    45678910
    11121314151617
    18192021222324
    25262728293031
           
      12345
    6789101112
    13141516171819
    20212223242526
    27282930   
           
          1
    2345678
    9101112131415
    16171819202122
    23242526272829
    3031     
        123
    45678910
    11121314151617
    18192021222324
    252627282930 
           
     123456
    78910111213
    14151617181920
    21222324252627
    28293031   
           
         12
    3456789
    10111213141516
    17181920212223
    24252627282930
    31      
       1234
    567891011
    12131415161718
    19202122232425
    2627282930  
           
    1234567
    891011121314
    15161718192021
    22232425262728
    293031    
           
         12
    3456789
    10111213141516
    17181920212223
    24252627282930
           
      12345
    6789101112
    13141516171819
    20212223242526
    2728293031  
           
      12345
    6789101112
    13141516171819
    20212223242526
    2728     
           
          1
    2345678
    9101112131415
    16171819202122
    23242526272829
    3031     
       1234
    567891011
    12131415161718
    19202122232425
    262728293031 
           
     123456
    78910111213
    14151617181920
    21222324252627
    282930    
           
         12
    3456789
    10111213141516
    17181920212223
    24252627282930
    31      
       1234
    567891011
    12131415161718
    19202122232425
    2627282930  
           
    1234567
    891011121314
    15161718192021
    22232425262728
    293031    
           
        123
    45678910
    11121314151617
    18192021222324
    25262728293031
           
      12345
    6789101112
    13141516171819
    20212223242526
    27282930   
           
          1
    2345678
    9101112131415
    16171819202122
    23242526272829
    3031     
        123
    45678910
    11121314151617
    18192021222324
    252627282930 
           
     123456
    78910111213
    14151617181920
    21222324252627
    28293031   
           
     123456
    78910111213
    14151617181920
    21222324252627
    28      
           
         12
    3456789
    10111213141516
    17181920212223
    24252627282930
    31      
      12345
    6789101112
    13141516171819
    20212223242526
    2728293031  
           
    1234567
    891011121314
    15161718192021
    22232425262728
    2930     
           
        123
    45678910
    11121314151617
    18192021222324
    25262728293031
           
      12345
    6789101112
    13141516171819
    20212223242526
    27282930   
           
          1
    2345678
    9101112131415
    16171819202122
    23242526272829
    3031     
       1234
    567891011
    12131415161718
    19202122232425
    262728293031 
           
     123456
    78910111213
    14151617181920
    21222324252627
    282930    
           
         12
    3456789
    10111213141516
    17181920212223
    24252627282930
    31      
       1234
    567891011
    12131415161718
    19202122232425
    2627282930  
           
    1234567
    891011121314
    15161718192021
    22232425262728
    293031    
           
    1234567
    891011121314
    15161718192021
    22232425262728
           
           
        123
    45678910
    11121314151617
    18192021222324
    25262728293031
           
     123456
    78910111213
    14151617181920
    21222324252627
    28293031   
           
          1
    2345678
    9101112131415
    16171819202122
    23242526272829
    30      
       1234
    567891011
    12131415161718
    19202122232425
    262728293031 
           
     123456
    78910111213
    14151617181920
    21222324252627
    282930    
           
         12
    3456789
    10111213141516
    17181920212223
    24252627282930
    31      
      12345
    6789101112
    13141516171819
    20212223242526
    2728293031  
           
    1234567
    891011121314
    15161718192021
    22232425262728
    2930     
           
        123
    45678910
    11121314151617
    18192021222324
    25262728293031
           
      12345
    6789101112
    13141516171819
    20212223242526
    27282930   
           
          1
    2345678
    9101112131415
    16171819202122
    23242526272829
    3031     
         12
    3456789
    10111213141516
    17181920212223
    242526272829 
           
      12345
    6789101112
    13141516171819
    20212223242526
    2728293031  
           
          1
    2345678
    9101112131415
    16171819202122
    23242526272829
    3031     
        123
    45678910
    11121314151617
    18192021222324
    252627282930 
           
     123456
    78910111213
    14151617181920
    21222324252627
    28293031   
           
          1
    2345678
    9101112131415
    16171819202122
    23242526272829
    30      
       1234
    567891011
    12131415161718
    19202122232425
    262728293031 
           
    1234567
    891011121314
    15161718192021
    22232425262728
    293031    
           
         12
    3456789
    10111213141516
    17181920212223
    24252627282930
           
      12345
    6789101112
    13141516171819
    20212223242526
    2728293031  
           
    1234567
    891011121314
    15161718192021
    22232425262728
    2930     
           
        123
    45678910
    11121314151617
    18192021222324
    25262728293031
           
        123
    45678910
    11121314151617
    18192021222324
    25262728   
           
     123456
    78910111213
    14151617181920
    21222324252627
    28293031   
           
         12
    3456789
    10111213141516
    17181920212223
    24252627282930
    31      
       1234
    567891011
    12131415161718
    19202122232425
    2627282930  
           
    1234567
    15161718192021
    293031    
           
         12
    3456789
    10111213141516
           
      12345
    6789101112
    13141516171819
    20212223242526
    2728293031  
           
          1
    2345678
    9101112131415
    16171819202122
    23242526272829
    3031     
        123
    45678910
    11121314151617
    18192021222324
    252627282930 
           
     123456
    78910111213
    14151617181920
    21222324252627
    28293031   
           
          1
    2345678
    9101112131415
    16171819202122
    23242526272829
    30      
       1234
    567891011
    12131415161718
    19202122232425
    262728293031 
           
    1234567
    891011121314
    15161718192021
    22232425262728
    293031    
           
        123
    45678910
    11121314151617
    18192021222324
    25262728293031
           
      12345
    6789101112
    13141516171819
    20212223242526
    27282930   
           
        123
    45678910
    11121314151617
    18192021222324
    252627282930 
           
     123456
    78910111213
    14151617181920
    21222324252627
    28293031   
           
       1234
    567891011
    12131415161718
    19202122232425
    2627282930  
           
    1234567
    891011121314
    15161718192021
    22232425262728
    293031    
           
         12
    3456789
    10111213141516
    17181920212223
    24252627282930
           
      12345
    6789101112
    13141516171819
    20212223242526
    2728293031  
           
      12345
    6789101112
    13141516171819
    20212223242526
    2728     
           
          1
    2345678
    9101112131415
    16171819202122
    23242526272829
    3031     
     123456
    78910111213
    14151617181920
    21222324252627
    282930    
           
         12
    3456789
    10111213141516
    17181920212223
    24252627282930
    31      
    1234567
    891011121314
    15161718192021
    22232425262728
    293031    
           
        123
    45678910
    11121314151617
    18192021222324
    252627282930 
           
     123456
    78910111213
    14151617181920
    21222324252627
    28293031   
           
     123456
    78910111213
    14151617181920
    21222324252627
    28293031   
           
       1234
    567891011
    12131415161718
    19202122232425
    262728293031 
           
     123456
    78910111213
    14151617181920
    21222324252627
    282930    
           
         12
    3456789
    10111213141516
    17181920212223
    24252627282930
    31      
      12345
    6789101112
    13141516171819
    20212223242526
    2728293031  
           
    1234567
    891011121314
    15161718192021
    22232425262728
    2930     
           
        123
    45678910
    11121314151617
    18192021222324
    25262728293031
           
      12345
    6789101112
    13141516171819
    20212223242526
    27282930   
           
          1
    2345678
    9101112131415
    16171819202122
    23242526272829
    3031     
          1
    2345678
    9101112131415
    16171819202122
    232425262728 
           
       1234
    567891011
    12131415161718
    19202122232425
    262728293031 
           
    1234567
    891011121314
    15161718192021
    22232425262728
    293031    
           
         12
    3456789
    10111213141516
    17181920212223
    24252627282930
           
      12345
    6789101112
    13141516171819
    20212223242526
    2728293031  
           
    1234567
    891011121314
    15161718192021
    22232425262728
    2930     
           
        123
    45678910
    11121314151617
    18192021222324
    25262728293031
           
  • glPolygonModeでワイヤーフレーム表示

    #include <iostream>
    
    #include <Windows.h>
    #include <gl/GL.h>
    #include <gl/GLU.h>
    #include <gl/freeglut.h>
    
    //ウィンドウの幅と高さ
    int width, height;
    
    
    
    void draw() {
    
      double v = 0.7;
    
      glBegin(GL_QUADS);
      glColor3d(0, 0, 1);
      glVertex2d(-v, -v);
      glColor3d(1, 0, 1);
      glVertex2d(v, -v);
      glColor3d(1, 1, 1);
      glVertex2d(v, v);
      glColor3d(0, 1, 1);
      glVertex2d(-v, v);
    
      glEnd();
    
    }
    //描画関数
    void disp(void) {
    
      glViewport(0, 0, width, height);
    
      glClearColor(0.2, 0.2, 0.2, 1);
      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
      glPolygonMode(GL_FRONT, GL_LINE);//ワイヤーフレーム描画に設定
      draw();
      glPolygonMode(GL_FRONT, GL_FILL);//塗りつぶし描画に戻す
    
      glFlush();
    }
    //ウィンドウサイズの変化時に呼び出される
    void reshape(int w, int h) {
      width = w; height = h;
    
      disp();
    }
    
    //エントリポイント
    int main(int argc, char** argv)
    {
      glutInit(&argc, argv);
      glutInitWindowPosition(100, 50);
      glutInitWindowSize(500, 500);
      glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
    
      glutCreateWindow("sample");
      glutDisplayFunc(disp);
      glutReshapeFunc(reshape);
      glutMainLoop();
    
      return 0;
    }
    

    Particle Systems Are DEAD のチュートリアルを試す(2)

    Shroomにマテリアルを追加し、Emissionを設定する。

    ShroomにParticleを設定する。

    Shroomのマテリアルをもう一度いじる

    結果(APNG)

    Particle Systems Are DEAD のチュートリアルを試す(1)

    Particle Systems Are DEAD

    Shroomは、円を元に適当に作成する。

    また、上記中Emptyは[Shift+A]→[Empty]→[Sphere]で導入する

    Suzanneに対してGeometry Node Editorを開く。NewするとGroup InputとGroup Outputがあるので、この間にノードを追加していく。

    ノードを追加していく

    ここまでの結果

    BlenderのGeometry nodeについてPoint Distributeを例に調べたこと

    Geometry Nodeの使い方が全くと言っていいほどわからなかったので調べた。

    0.前提

    Geometry Node Editor からオブジェクトに対してジオメトリノードツリーを作成するとノードベースのモデリングが可能。

    1.Point Distributeを使ってみる

    まずCubeに対してPoint Distributeを使ってみる。とりあえずGroup InputとGroup Outputの間にPoint Distributeを挟んでみると、形状の表面に点が散布される。しかしこのままレンダリングしても何も表示されない。Point Instanceを繋げば表示されるが今はその前にこの散布された点について確認しておきたい。

    2.Attribute (=属性)について

    Attributeは属性のことで、つまり「それ」がどんな性質を持っているかという事で、別の表現をするならパラメータとかになると思う。Point Distributeで生成された点はそれぞれにAttribute(=属性)を持っている。どんな属性を持っているかというと「Built-In Attributes」と呼ばれている属性一覧がある。

    以下、Blender 3.0 Manual Attributes

    https://docs.blender.org/manual/en/dev/modeling/geometry_nodes/attributes_reference.html

    Name

    Type

    Domain

    Notes

    position

    Vector

    Point

    モディファイヤオブジェクトの変換空間で、頂点またはポイントの位置を記述する組み込み属性。ポイントの位置を変更するノードは、TransformノードPoint Translateノードのように、この属性を調整します

    radius

    Float

    Point

    Point Distributeノードによって作成されたポイントクラウドデータの組み込み属性ビューポート内のポイントのサイズを設定するために使用されます。

    material_index

    Integer

    Face

    メッシュ内のすべての面のマテリアルスロットを指定するために使用されます。

    crease

    Float

    Edge

    サブディビジョンサーフェスノードとモディファイヤによって使用されるエッジ属性。値は0から1の範囲に制限されています。

    normal

    Vector

    Face

    faceの法線。これは、変更できないという点で他の組み込み属性とは少し異なります。メッシュから自動的に派生します。この属性が非点ドメインでアクセスされる場合、隣接する面の法線から補間されるため、正規化されない可能性があります。

    shade_smooth

    Boolean

    Face

    faceでスムーズシェーディングを有効にするかどうかを決定する属性。

    Point Distributeにはradiusがあるらしいので、これを変更してみる。値を変更するにはAttribute Mathなどを使えばいい。

    3.Point Instance

    Point Distributeで生成されるのは点である。点はAttributeを持ってはいるが形状を持っていないのでそのままでは表示できない。Point Instanceを使えば点のpositionにObjectを配置できる。ただしこうするとradiusでサイズ指定ができない(次項)。

    4.Naming Conventions(命名規則)

    ノードによってNaming Conventionsを使用できる。Point Instanceノードではscaleを使用できる。

    Name

    Type

    Notes

    rotation

    Vector

    インスタンス化されたオブジェクトまたはコレクションの回転を制御するために、Point Instance Nodeで使用されます。Point Rotate NodeAlignRotation to VectorNodeによって調整されます。

    scale

    Vector

    インスタンスのスケールを制御するためにPoint Distribute Node使用されます。Point Scale Nodeまたは他の属性ノードによって調整されます。

    id

    Integer

    入力メッシュの形状が変化したときに安定性を提供するためにPoint Distribute Nodeによって作成されます。値は大きく、順序はありません。属性値は、Attribute Randomize Nodeなど、ランダム性を生成するノードによって使用されます

    radiusをscaleに変換すれば、サイズの変更ができる。

    scaleを変えるだけなら、scaleを直接いじったほうがいいかもしれない。

    glReadPixelsでOpenGLの表示内容を保存

    saveGLtoPPM.hpp

    #pragma once
    
    #include <Windows.h>
    #include <gl/GL.h>
    #include <vector>
    #include <cstdio>
    
    #pragma warning(disable:4996)
    
    
    
    //画像の上下を反転する
    void reverse_Y(const int width, const int height, unsigned char* p) {
    
      int WidthByte = width * 3;
    
      size_t HalfHEIGHT = height / 2;
      for (int ha = 0; ha < HalfHEIGHT; ha++) {
    
        int hb = (height - ha) - 1;
    
        unsigned char* pha = p + ha * WidthByte;
        unsigned char* phb = p + hb * WidthByte;
    
        if (ha != hb) {
          for (size_t i = 0; i < WidthByte; i++) {
            std::swap(pha[i], phb[i]);
          }
        }
    
      }
    
    }
    //! @brief PPM(RGB各1byte,カラー,テキスト)を書き込む
    //! @param [in] fname ファイル名
    //! @param [in] vmax 全てのRGBの中の最大値
    //! @param [in] width 画像の幅
    //! @param [in] height 画像の高さ
    //! @param [in] p 画像のメモリへのアドレス
    //! @details RGBRGBRGB....のメモリを渡すと、RGBテキストでファイル名fnameで書き込む
    void pnmP3_Write(const char* const fname, const int vmax, const int width, const int height, const unsigned char* const p) { // PPM ASCII
    
    
      FILE* fp = fopen(fname, "w");
    
      fprintf(fp, "P3\n%d %d\n%d\n", width, height, vmax);
    
      size_t k = 0;
      for (size_t i = 0; i < (size_t)height; i++) {
        for (size_t j = 0; j < (size_t)width; j++) {
          fprintf(fp, "%d %d %d ", p[k * 3 + 0], p[k * 3 + 1], p[k * 3 + 2]);
          k++;
        }
        fprintf(fp, "\n");
      }
    
      fclose(fp);
    
    
    }
    
    
    //! @brief OpenGLの画面を画像に保存 
    //! @param [in] width 画像幅ピクセル数
    //! @param [in] height 画像高さピクセル数
    //! @param [in] pathname ファイル名
    void saveGLtoPPM(const int width, const int height, const char* pathname) {
    
      //メモリ確保
      std::vector<GLubyte> buffer;
      buffer.resize(width*height * 3);
    
      //画像取得
      glReadBuffer(GL_FRONT);
      glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer.data());
    
      //上下反転
      reverse_Y(width, height, buffer.data());
    
      pnmP3_Write(
        pathname,
        255,
        width,
        height,
        buffer.data()); // PPM ASCII
    
    }
    

    使用方法

    #include <iostream>
    
    #include <Windows.h>
    #include "prepare_shader.hpp"
    #include <gl/GL.h>
    #include <gl/GLU.h>
    #include <gl/freeglut.h>
    
    #include <fstream>
    
    #include "saveGLtoPPM.hpp"
    
    
    #pragma comment(lib,"glew32.lib")
    
    
    //ウィンドウの幅と高さ
    int Width, Height;
    
    GLuint buf_points;
    GLuint buf_colors;
    
    GLfloat mproj[16];
    GLfloat mmodel[16];
    GLuint programID;
    
    
    // シェーダとデータの設定
    void init() {
    
      std::vector<GLfloat> colors;
      std::vector<GLfloat> points;
    
      GLfloat v = 0.8;
    
      push_3(colors, 0, 0, 1);//色 RGB
      push_3(points, 0, 0, 0);//座標 XYZ
    
      push_3(colors, 0, 1, 0);
      push_3(points, 0, v, 0);
    
      push_3(colors, 1, 0, 0);
      push_3(points, v, 0, 0);
    
      prepare_buffer(&buf_points, points.data(), points.size() * sizeof(GLfloat), GL_STATIC_DRAW);
      prepare_buffer(&buf_colors, colors.data(), colors.size() * sizeof(GLfloat), GL_STATIC_DRAW);
    
      GLuint vtxShader;
      GLuint flagShader;
    
      const char* vtxfile = "default.vert";
      const char* fragfile = "default.frag";
    
      std::string verr;
      std::string ferr;
      prepare_shader_byfile(&vtxShader, GL_VERTEX_SHADER, vtxfile, &verr);
      prepare_shader_byfile(&flagShader, GL_FRAGMENT_SHADER, fragfile, &ferr);
    
      std::cout << verr << std::endl;
      std::cout << ferr << std::endl;
    
      std::string linkerr;
      link_program(&programID, { vtxShader ,flagShader }, nullptr, &linkerr);
    
      loadidentity44(mproj);
      loadidentity44(mmodel);
    }
    
    //描画関数
    void disp(void) {
    
      glViewport(0, 0, Width, Height);
    
      glClearColor(0.2, 0.2, 0.2, 1);
      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
      glUseProgram(programID);
      GLuint loc_ModelViewMatrix = glGetUniformLocation(programID, "ModelViewMatrix");
      GLuint loc_ProjectionMatrix = glGetUniformLocation(programID, "ProjectionMatrix");
    
    
      glUniformMatrix4fv(loc_ModelViewMatrix, 1, GL_FALSE, mmodel);
      glUniformMatrix4fv(loc_ProjectionMatrix, 1, GL_FALSE, mproj);
    
      {
    
        auto bindbufP = EnableAndBindFArrayBuffer(0, buf_points, 3, GL_FLOAT);
        auto bindbufC = EnableAndBindFArrayBuffer(1, buf_colors, 3, GL_FLOAT);
    
        glDrawArrays(GL_TRIANGLES, 0, 3);
    
      }
      glFlush();
    
    }
    
    
    //ウィンドウサイズの変化時に呼び出される
    void reshape(int w, int h) {
      Width = w;
      Height = h;
    
      disp();
    }
    
    // クリックでファイルに保存
    void mouse(int button, int state, int x, int y) {
      saveGLtoPPM(
        Width, 
        Height, 
        R"(C:\test\a.ppm)");
    }
    
    //エントリポイント
    int main(int argc, char** argv)
    {
      glutInit(&argc, argv);
      glutInitWindowPosition(100, 50);
      glutInitWindowSize(500, 500);
      glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
    
    
      glutCreateWindow("sample");
      glutDisplayFunc(disp);
      glutReshapeFunc(reshape);
      glutMouseFunc(mouse);
    
      glewInit();
    
      init();
    
    
      glutMainLoop();
    
      return 0;
    }
    

    GLSLでマルチテクスチャ

    #include <iostream>
    
    #include <Windows.h>
    #include "prepare_shader.hpp"
    #include <gl/GL.h>
    #include <gl/GLU.h>
    #include <gl/freeglut.h>
    
    #pragma comment(lib,"glew32.lib")
    
    //ウィンドウの幅と高さ
    int width, height;
    
    GLuint buf_points;
    GLuint buf_tcoord;
    GLuint textureID22;
    GLuint textureID44;
    
    GLfloat mproj[16];
    GLfloat mmodel[16];
    
    GLuint programID;
    
    
    void texture_setting(GLuint* texid, std::vector < GLubyte >& texdata, int TEXWIDTH, int TEXHEIGHT) {
      glGenTextures(1, texid);
      glBindTexture(GL_TEXTURE_2D, *texid);
    
      glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    
      // テクスチャの割り当て
      glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, TEXWIDTH, TEXHEIGHT, 0,
        GL_RGB, GL_UNSIGNED_BYTE, texdata.data());
    
      // テクスチャを拡大・縮小する方法の指定
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    
    }
    
    // テクスチャ作成
    
    void create_texture_22() {
    std::vector < GLubyte > texdata;
     push_3(texdata, 255, 0, 0); push_3(texdata, 0, 255, 0); push_3(texdata, 255, 255, 255); push_3(texdata, 0, 255, 255); texture_setting(&textureID22, texdata, 2, 2); texdata.clear(); } void create_texture_44() { std::vector < GLubyte > texdata;
    push_3(texdata, 255, 0, 0); push_3(texdata, 0, 0, 0); push_3(texdata, 255, 0, 0); push_3(texdata, 0, 0, 0); push_3(texdata, 0, 0, 0); push_3(texdata, 255, 0, 0); push_3(texdata, 0, 0, 0); push_3(texdata, 255, 0, 0); push_3(texdata, 255, 0, 0); push_3(texdata, 0, 0, 0); push_3(texdata, 255, 0, 0); push_3(texdata, 0, 0, 0); push_3(texdata, 0, 0, 0); push_3(texdata, 255, 0, 0); push_3(texdata, 0, 0, 0); push_3(texdata, 255, 0, 0); texture_setting(&textureID44, texdata, 4, 4); texdata.clear(); }
    // シェーダとデータの設定
    void init() {
    
      /////////////////////////////////////////////
      std::vector<GLfloat> points;
      GLfloat v = 0.8;
      push_3(points, -v , -v , 0);
      push_3(points,  v , -v , 0);
      push_3(points, -v ,  v , 0);
      push_3(points,  v ,  v , 0);
      prepare_buffer(&buf_points, points.data(), points.size() * sizeof(GLfloat), GL_STATIC_DRAW);
    
      /////////////////////////////////////////////
      // テクスチャ座標
      std::vector<GLfloat> texcoord;
      push_2(texcoord, 0, 0);
      push_2(texcoord, 1, 0);
      push_2(texcoord, 0, 1);
      push_2(texcoord, 1, 1);
      prepare_buffer(&buf_tcoord, texcoord.data(), texcoord.size() * sizeof(GLfloat), GL_STATIC_DRAW);
      /////////////////////////////////////////////
    
      //テクスチャ(画像)作成
    
      create_texture_22();
    
      create_texture_44();
    
      /////////////////////////////////////////////
    
      GLuint vtxShader;
      GLuint flagShaderR;
      const char* vtxfile = "default.vert";
      const char* fragfileR = "default.frag";
    
      std::string verr;
      std::string ferr;
      prepare_shader_byfile(&vtxShader, GL_VERTEX_SHADER, vtxfile, &verr);
      prepare_shader_byfile(&flagShaderR, GL_FRAGMENT_SHADER, fragfileR, &ferr);
    
      std::cout << verr << std::endl;
      std::cout << ferr << std::endl;
    
      std::string linkerr;
      link_program(&programID, { vtxShader ,flagShaderR }, nullptr, &linkerr);
    
      loadidentity44(mproj);
      loadidentity44(mmodel);
    }
    
    
    //描画関数
    void disp(void) {
    
      glViewport(0, 0, width, height);
    
      glClearColor(0.2, 0.2, 0.2, 1);
      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
      glUseProgram(programID);
      GLuint loc_ModelViewMatrix = glGetUniformLocation(programID, "ModelViewMatrix");
      GLuint loc_ProjectionMatrix = glGetUniformLocation(programID, "ProjectionMatrix");
      glUniformMatrix4fv(loc_ModelViewMatrix, 1, GL_FALSE, mmodel);
      glUniformMatrix4fv(loc_ProjectionMatrix, 1, GL_FALSE, mproj);
    
    
      GLint loc_tex22 = glGetUniformLocation(programID, "Tex22");
      glUniform1i(loc_tex22, 0);// Texture unit 0
      glActiveTexture(GL_TEXTURE0 + 0); // Texture unit 0
      glBindTexture(GL_TEXTURE_2D, textureID22);
    
      GLint loc_tex44 = glGetUniformLocation(programID, "Tex44");
      glUniform1i(loc_tex44, 1);// Texture unit 1
      glActiveTexture(GL_TEXTURE0 + 1); // Texture unit 1
      glBindTexture(GL_TEXTURE_2D, textureID44);

    { auto bind_points = EnableAndBindFArrayBuffer(0, buf_points, 3, GL_FLOAT); auto bind_tcoord = EnableAndBindFArrayBuffer(1, buf_tcoord, 2, GL_FLOAT); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } glUseProgram(0); glFlush(); }
    //ウィンドウサイズの変化時に呼び出される
    void reshape(int w, int h) {
      width = w; height = h;
    
      disp();
    }
    
    //エントリポイント
    int main(int argc, char** argv)
    {
      glutInit(&argc, argv);
      glutInitWindowPosition(100, 50);
      glutInitWindowSize(500, 500);
      glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
    
      glutCreateWindow("sample");
      glutDisplayFunc(disp);
      glutReshapeFunc(reshape);
    
      glewInit();
    
      init();
    
      glutMainLoop();
    
      return 0;
    }
    

    シェーダ

    default.vert

    #version 460 core
    
    layout (location = 0) in vec3 aPos;//ポリゴンの頂点座標
    layout (location = 1) in vec2 texcd;//座標に対応するテクスチャ座標
    
    out vec2 vTexCoord;//テクスチャ座標の出力先
    
    uniform mat4 gl_ModelViewMatrix;
    uniform mat4 gl_ProjectionMatrix;
    
    void main()
    {
      gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * vec4(aPos, 1.0);
      vTexCoord = texcd;//フラグメントシェーダへテクスチャ座標を渡す
    }
    

    default.frag

    #version 460 core
    
    out vec4 FragColor;//色の出力先
    
    uniform sampler2D Tex22;
    uniform sampler2D Tex44;
      
    in vec2 vTexCoord;//頂点シェーダから渡されたテクスチャ座標
    
    void main()
    {
    
      //テクスチャデータとテクスチャ座標から色を決定
      vec4 c22 = texture(Tex22,vTexCoord);
      vec4 c44 = texture(Tex44,vTexCoord);
    
      //合成したテクスチャの色を作成
      vec4 crr;
      crr.x = c44.x * c22.x;
      crr.y = c44.x * c22.y;
      crr.z = c44.x * c22.z;
      
      FragColor = crr;
    } 
    

    GLSLのUniform Buffer Object (UBO) をとりあえず試す

    GLSLのUBO。普通のUniform変数はlinkしたプログラムごとに設定するが、UBOは全てのプログラムで共通の変数を使うことができる。

    今回はとりあえず動かすことに成功したのでひとまずコードを張っておきたい。

    なおシェーダの準備などは作り置きの関数を使用。

    GLSLのシェーダ関係の処理を関数化(C++)

    ソースコード(C++)

    #include <iostream>
    
    #include <Windows.h>
    #include "prepare_shader.hpp"
    #include <gl/GL.h>
    #include <gl/GLU.h>
    #include <gl/freeglut.h>
    #include <cassert>
    
    #pragma comment(lib,"glew32.lib")
    
    //ウィンドウの幅と高さ
    int width, height;
    
    GLuint buf_points1;
    GLuint buf_points2;
    
    
    GLuint programIDR;
    GLuint programIDG;
    
    GLuint uniformBufferID;
    struct CMatrices {
      GLfloat mproj[16];
      GLfloat mmodel[16];
    } _matrices;
    
    void GetZRotate(GLfloat* m, GLfloat rad);
    
    
    // シェーダとデータの設定
    void init() {
    
      std::vector<GLfloat> points;
    
      GLfloat s=0.0;
      GLfloat v = 0.8;
    
      push_3(points, 0 + s, 0,   0);//座標 XYZ
      push_3(points, 0 + s, v,   0);
      push_3(points, v + s, 0,   0);
      prepare_buffer(&buf_points1, points.data(), points.size() * sizeof(GLfloat), GL_STATIC_DRAW);
    
      s = 0.1;
      points.clear();
      push_3(points, 0 + s, 0, 0);//座標 XYZ
      push_3(points, 0 + s, v, 0);
      push_3(points, v + s, 0, 0);
      prepare_buffer(&buf_points2, points.data(), points.size() * sizeof(GLfloat), GL_STATIC_DRAW);
    
    
      GLuint vtxShader;
      GLuint flagShaderR;
      GLuint flagShaderG;
      const char* vtxfile = "default.vert";
      const char* fragfileR = "default-R.frag";
      const char* fragfileG = "default-G.frag";
    
      std::string verr;
      std::string ferr;
      prepare_shader_byfile(&vtxShader, GL_VERTEX_SHADER, vtxfile, &verr);
      prepare_shader_byfile(&flagShaderR, GL_FRAGMENT_SHADER, fragfileR, &ferr);
      prepare_shader_byfile(&flagShaderG, GL_FRAGMENT_SHADER, fragfileG, &ferr);
    
      std::cout << verr << std::endl;
      std::cout << ferr << std::endl;
    
      std::string linkerr;
      link_program(&programIDR, { vtxShader ,flagShaderR }, nullptr, &linkerr);
      link_program(&programIDG, { vtxShader ,flagShaderG }, nullptr, &linkerr);
    
      loadidentity44(_matrices.mproj);
      loadidentity44(_matrices.mmodel);
    
      // UBOを作成
      glGenBuffers(1, &uniformBufferID);
      glBindBuffer(GL_UNIFORM_BUFFER, uniformBufferID);
      glBufferData(GL_UNIFORM_BUFFER, sizeof(CMatrices), &_matrices, GL_DYNAMIC_DRAW); //UBOの内容を書き込み
      glBindBuffer(GL_UNIFORM_BUFFER, 0);
    
    }
    //描画関数
    void disp(void) {
    
      glViewport(0, 0, width, height);
    
      glClearColor(0.2, 0.2, 0.2, 1);
      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
      static int angle = 0;
      GetZRotate(_matrices.mmodel, angle++ * (3.14159 / 180.0));
    
      glBindBuffer(GL_UNIFORM_BUFFER, uniformBufferID);
      glBufferData(GL_UNIFORM_BUFFER, sizeof(CMatrices), &_matrices, GL_DYNAMIC_DRAW);
      glBindBuffer(GL_UNIFORM_BUFFER, 0);
    
      GLuint block_index_r = glGetUniformBlockIndex(programIDR, "Matrices");
     GLuint block_index_g = glGetUniformBlockIndex(programIDG, "Matrices");
    GLuint index = 0; //この数字はGL_MAX_UNIFORM_BUFFER_BINDINGS未満ならなんでもいい assert(index < GL_MAX_UNIFORM_BUFFER_BINDINGS);
      glUseProgram(programIDR);//使用するプログラムを変更
      glBindBufferBase(GL_UNIFORM_BUFFER, index, uniformBufferID);
      glUniformBlockBinding(programIDR, block_index_r, index);
      {
        auto bindbufP = EnableAndBindFArrayBuffer(0, buf_points1, 3, GL_FLOAT);//prepare_shader.hpp
        glDrawArrays(GL_TRIANGLES, 0, 3);
      }
    
    

    glUseProgram(programIDG);//使用するプログラムを変更 glBindBufferBase(GL_UNIFORM_BUFFER, index, uniformBufferID); glUniformBlockBinding(programIDG, block_index_g, index); { auto bindbufP = EnableAndBindFArrayBuffer(0, buf_points2, 3, GL_FLOAT);//prepare_shader.hpp glDrawArrays(GL_TRIANGLES, 0, 3); }

    glUseProgram(0); glFlush(); }
    //ウィンドウサイズの変化時に呼び出される
    void reshape(int w, int h) {
      width = w; height = h;
    
      disp();
    }
    
    void timer(int value) {
      glutPostRedisplay();
      glutTimerFunc(50, timer, 0);
    }
    
    //エントリポイント
    int main(int argc, char** argv)
    {
      glutInit(&argc, argv);
      glutInitWindowPosition(100, 50);
      glutInitWindowSize(500, 500);
      glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
    
      glutCreateWindow("sample");
      glutDisplayFunc(disp);
      glutReshapeFunc(reshape);
    
      glutTimerFunc(10, timer, 0);
    
      glewInit();
    
      init();
    
      glutMainLoop();
    
      return 0;
    }
    
    
    //! @brief X軸回転行列を作成する
    //! @param [out] m 結果を格納する要素数16の配列
    //! @param [in] rad 回転角(ラジアン)
    //! @return なし
    void GetZRotate(GLfloat* m, GLfloat rad) {
      m[0] = cos(rad);
      m[1] = sin(rad);
      m[2] = 0;
      m[3] = 0;
    
      m[4] = -sin(rad);
      m[5] = cos(rad);
      m[6] = 0;
      m[7] = 0;
    
      m[8] = 0;
      m[9] = 0;
      m[10] = 1;
      m[11] = 0;
    
      m[12] = 0;
      m[13] = 0;
      m[14] = 0;
      m[15] = 1;
    
    }
    

    シェーダプログラム

    default.vert

    #version 460 core
    
    layout (location = 0) in vec3 coord;
    
    out vec4 vColor;
    
    //Uniformブロック std140はメモリ配置方法
    layout (std140) uniform Matrices {
      mat4 ProjectionMatrix;
      mat4 ModelViewMatrix;
    };
    
    void main()
    {
      gl_Position = ProjectionMatrix * ModelViewMatrix * vec4(coord, 1.0);
    }
    

    default-g.frag

    #version 460 core
    
    in vec4 vColor;
    
    out vec4 FragColor;
    
    void main()
    {
      FragColor[0] = 0.0;
      FragColor[1] = 1.0;
      FragColor[2] = 0.0;
      FragColor[3] = 1.0;
    } 
    

    default-r.frag

    #version 460 core
    
    in vec4 vColor;
    
    out vec4 FragColor;
    
    void main()
    {
      FragColor[0] = 1.0;
      FragColor[1] = 0.0;
      FragColor[2] = 0.0;
      FragColor[3] = 1.0;
    } 
    

    コンソールアプリケーションでデバッグ用のウィンドウを表示-3-RGB,RGBA対応

    RGB画像だけではなく、RGBAにも対応する。

    まずはウィンドウの本体のクラスを書く。これはデータのポインタを受け取ったら背景画像とブレンドして表示用画像を作成する。

    CImageViewWindow.hpp

    #pragma once
    
    
    #include "gwindbg.hpp"
    #include <mutex>
     
    //! @brief DIBを扱う
    struct DIBData {
      BITMAPINFO m_bmpInfo;   //!< CreateDIBSectionに渡す構造体
      LPDWORD m_lpPixel;      //!< 画素へのポインタ
      HBITMAP m_hBitmap;      //!< 作成したMDCのビットマップハンドル
      HDC m_hMemDC;           //!< 作成したMDCのハンドル
    
      int m_imagesizemax;     //!< 合計画素数(width*height)
      int m_width;            //!< 画像の幅(ピクセル,自然数)
      int m_height;           //!< 画像の高さ(ピクセル,自然数)
    
      int m_bitcount;
      DIBData() {
        DeleteDC(m_hMemDC);
        DeleteObject(m_hBitmap);
      }
      ~DIBData() {
        m_hBitmap = nullptr;
        m_hMemDC = nullptr;
        m_lpPixel = nullptr;
        m_width = 0;
        m_height = 0;
        m_bitcount = 0;
      }
      void create(int width, int height, int bitcount) {
        if (width != m_width || height != m_height) {
          if (m_hBitmap) {
            DeleteObject(m_hBitmap);
            m_hBitmap = nullptr;
          }
          if (m_hMemDC) {
            DeleteDC(m_hMemDC);
            m_hMemDC = nullptr;
          }
          //DIBの情報を設定する
          m_bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
          m_bmpInfo.bmiHeader.biWidth = width;
          m_bmpInfo.bmiHeader.biHeight = -height; //-を指定しないと上下逆になる
          m_bmpInfo.bmiHeader.biPlanes = 1;
          m_bmpInfo.bmiHeader.biBitCount = bitcount;
          m_bmpInfo.bmiHeader.biCompression = BI_RGB;
    
          HDC hdc = GetDC(nullptr);
          m_hBitmap = CreateDIBSection(hdc, &m_bmpInfo, DIB_RGB_COLORS, (void**)&m_lpPixel, nullptr, 0);
          m_hMemDC = CreateCompatibleDC(hdc);
          SelectObject(m_hMemDC, m_hBitmap);
          ReleaseDC(nullptr, hdc);
    
          m_width = width;
          m_height = height;
          m_bitcount = bitcount;
        }
      }
    };
    //! @brief 画素の値を透明度でブレンドする
    //! @param [in] back 背景画像の色のr,g,bのいずれかの値
    //! @param [in] data 塗りたい色のr,g,bのいずれかの値
    //! @param [in] dataalpha 塗りたい色の透明度
    //データの色の割合

    unsigned
    char pixel_alpha_blend( unsigned char back, unsigned char data, unsigned char dataalpha ) { float weight_data = dataalpha / 255.0f;//データの色の割合 float weight_bkc = 1.0 - weight_data;//背景色の割合 int ret = data * weight_data + back * weight_bkc; if (data > 255)data = 255; return ret; }
    //! @brief RGB,RGBAの画像を表示するウィンドウのクラス。
    class CImageViewWindow : public GraphicDebugWindow {
    
      DIBData dibdata_background; //!< 背景画像
      DIBData dibdata_result;     //!< 表示画像
    
      int m_magnification;    //!< 表示倍率
      unsigned char* m_img_p; //!< 画像データへのポインタ
      int m_img_width;        //!< 画像データの幅
      int m_img_height;       //!< 画像データの高さ
      int m_pixelbyte;        //!< 画像データのピクセルのバイト数。RGBなら3,RGBAなら4
    
      std::mutex m_mainmuitex;
    
    public:
      CImageViewWindow() {}
    
    
      //! @brief 背景(透明を表現するチェスボードのような画像)を作成する
      void create_background_image() {
    
        const int blocksize = 10;
    
        if (get_hwnd() == nullptr)
          return;
        RECT rect;
        GetClientRect(get_hwnd(), &rect);
    
        //現在の背景画像が、画面サイズより小さかったら作り直す。
        //画面サイズより大きな背景画像が既に作成済みならそのまま使用する
        if (dibdata_background.m_width < rect.right || dibdata_background.m_height < rect.bottom) {
    
          dibdata_background.create(rect.right, rect.bottom, 32);
          int bkwidth = dibdata_background.m_width;
          int bkheight = dibdata_background.m_height;
    
          //背景画像の作成(チェスボードのような画像)
          for (int x = 0; x < bkwidth; x++) {
            for (int y = 0; y < bkheight; y++) {
    
              int pos = y * bkwidth + x;
    
              bool xb = (bool)((x / blocksize) % 2);
              bool yb = (bool)((y / blocksize) % 2);
    
              if (xb == yb) {
                dibdata_background.m_lpPixel[pos] = RGB(100, 100, 100);
              }
              else {
                dibdata_background.m_lpPixel[pos] = RGB(200, 200, 200);
              }
    
            }
          }
        }
    
      }
      //! @brief ウィンドウのサイズが変更されたときの関数
      void change_client_size() {
        create_background_image();
    
        //結果画像のサイズ変更(クライアント領域に合わせる)
        RECT rect;
        HWND hwnd = get_hwnd();
        if (hwnd == nullptr)
          return;
        GetClientRect(hwnd, &rect);
        dibdata_result.create(rect.right, rect.bottom, 32);
    
        //画像書き込み
        m_mainmuitex.lock();
    
        //背景を結果にコピー
        BitBlt(
          dibdata_result.m_hMemDC, 0, 0, dibdata_background.m_width, dibdata_background.m_height,
          dibdata_background.m_hMemDC, 0, 0, SRCCOPY);
    
        if (m_img_p) {
          for (int x = 0; x < m_img_width; x++) {
            for (int y = 0; y < m_img_height; y++) {
              int pos_src_pix = (y * m_img_width + x);// 元画像の画素の座標(ピクセル単位)
    
              {
                // 元画像の画素の色を取得
                unsigned int sr = m_img_p[pos_src_pix*m_pixelbyte + 0];
                unsigned int sg = m_img_p[pos_src_pix*m_pixelbyte + 1];
                unsigned int sb = m_img_p[pos_src_pix*m_pixelbyte + 2];
                unsigned int sa = m_img_p[pos_src_pix*m_pixelbyte + 3];
    
                // 書き込み先のピクセル座標の開始地点x,y
                int pos_dst_x_offset = x * m_magnification;
                int pos_dst_y_offset = y * m_magnification;
                if (pos_dst_x_offset >= dibdata_result.m_width)continue;
                if (pos_dst_y_offset >= dibdata_result.m_height)continue;
    
                int resultwidth = dibdata_result.m_width;
                unsigned char dr, dg, db;//表示ピクセル色
                for (int xblock = 0; xblock < m_magnification; xblock++) {
                  for (int yblock = 0; yblock < m_magnification; yblock++) {
                    int dx = pos_dst_x_offset + xblock;
                    int dy = pos_dst_y_offset + yblock;
                    if (dx >= dibdata_result.m_width)continue;
                    if (dy >= dibdata_result.m_height)continue;
    
                    int pos_dst_pix = (dy * resultwidth + dx);
                    int pos_bk_pix = (dy * dibdata_background.m_width + dx);
    
                    //透明度付きの場合だけ、背景色との混合を行う
                    if (m_pixelbyte == 4) {
                      COLORREF bkcolor = dibdata_background.m_lpPixel[pos_bk_pix];//下地の色を取得
                      dr = pixel_alpha_blend(GetRValue(bkcolor), sr, sa);
                      dg = pixel_alpha_blend(GetGValue(bkcolor), sg, sa);
                      db = pixel_alpha_blend(GetBValue(bkcolor), sb, sa);
                    }
                    else {
                      dr = sr;
                      dg = sg;
                      db = sb;
                    }
                    dibdata_result.m_lpPixel[pos_dst_pix] = RGB(dr, dg, db);
                  }
                }
              }
            }
          }
        }
    
        m_mainmuitex.unlock();
    
      }
      //! @brief 画面に画像を設定
      //! @param [in] width 画像幅
      //! @param [in] height 画像高さ
      //! @param [in] magnification 表示倍率。小さすぎる画像を大きく表示できる
      //! @param [in] p 画像データ。RGBRGBRGB...
      //! @param [in] pixelbyte 1ピクセルのバイト数 3か4
      //! @return なし
      void display(int width, int height, int magnification, unsigned char* p, int pixelbyte) {
    
        m_img_width = width;
        m_img_height = height;
        m_img_p = p;
        m_magnification = magnification;
        m_pixelbyte = pixelbyte;
    
        change_client_size();
    
        HWND hwnd = get_hwnd();
        if (hwnd == nullptr)
          return;
        InvalidateRect(hwnd, nullptr, TRUE);
    
    
      }
      virtual LRESULT WndProc(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp)override
      {
        PAINTSTRUCT ps;
        HDC hdc;
        switch (msg)
        {
        case WM_SIZE:
          change_client_size();
          InvalidateRect(hWnd, nullptr, TRUE);
          break;
        case WM_SIZING:
          change_client_size();
          InvalidateRect(hWnd, nullptr, TRUE);
          break;
        case WM_PAINT:
          hdc = BeginPaint(hWnd, &ps);
    
          m_mainmuitex.lock();
          //DIBの内容をウィンドウに表示
          if (dibdata_background.m_hMemDC) {
            RECT rect;
            GetClientRect(hWnd, &rect);
    
            BitBlt(
              hdc, 0, 0,
              rect.right, rect.bottom,
              dibdata_result.m_hMemDC, 0, 0, SRCCOPY);
          }
          m_mainmuitex.unlock();
          EndPaint(hWnd, &ps);
          break;
        case WM_DESTROY:
          PostQuitMessage(0);
          return 0;
        }
        return DefWindowProc(hWnd, msg, wp, lp);
      }
    
    };
    

    gwindbg.hpp

    GraphicDebugWindowはほとんど変わらないが以下のように変更する。

    open関数はウィンドウ生成をスレッドに投げてしまうため、open関数終了時点でウィンドウ生成が完了していない可能性がある。このためopen関数呼び出し元で、「ウィンドウがまだないのに画像を設定する」という構図になる可能性がある。それを防ぐために、スレッド側でCreateWindowが完了するまではopen関数内で待機したい。このために、m_hwndがnullptrの間ループするのだが、空ループと同じようなもののため、最適化で消えてしまう可能性がある。そこでm_hwndにvolatileを付けて最適化を抑止する。さらにUpdateWindowはちゃんと描画が行われるまで待機する。

    #pragma once
    
    #include <Windows.h>
    #include <thread>
    
    class GraphicDebugWindow {
    
      //! @brief WNDCLASSに設定するウィンドウプロシージャ
      static LRESULT CALLBACK StaticWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
      {
        //CreateWindowの最後の引数で渡したthisポインタを取得
        GraphicDebugWindow* This = (GraphicDebugWindow*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
        if (!This) {//取得できなかった(ウィンドウ生成中)場合
          if (message == WM_CREATE) {
            This = (GraphicDebugWindow*)((LPCREATESTRUCT)lParam)->lpCreateParams;
            if (This) {
              SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)This);
              return This->WndProc(hWnd, message, wParam, lParam);
            }
          }
        }
        else {//取得できた場合(ウィンドウ生成後)
          return This->WndProc(hWnd, message, wParam, lParam);
        }
        return DefWindowProc(hWnd, message, wParam, lParam);
      }
    
      //メインループのスレッド
      std::unique_ptr<std::thread> m_mainloop;
    
      HINSTANCE hInstance;
      
      //ウィンドウができるまでループしたいが、m_hwndがnullptrである間ループするだけだと
    //
    最適化で消えてしまう可能性があるので、volatileを付けておく
    volatile HWND m_hwnd;
    protected:
    
    public:
    
      GraphicDebugWindow() {}
    
      bool registerWindowClass() {
        //インスタンスハンドルの取得
        hInstance = GetModuleHandle(0);
    
        WNDCLASS winc;
    
        winc.style = CS_HREDRAW | CS_VREDRAW;
        winc.lpfnWndProc = StaticWndProc;
        winc.cbClsExtra = winc.cbWndExtra = 0;
        winc.hInstance = hInstance;
        winc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
        winc.hCursor = LoadCursor(NULL, IDC_ARROW);
        winc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
        winc.lpszMenuName = NULL;
        winc.lpszClassName = TEXT("SZL_TEST_GUI_WINDOW");
    
        if (!RegisterClass(&winc))
          return false;
    
        return true;
      }
    
      //! @brief スレッドの内容
      int MainLoop(const TCHAR* title, int posx, int posy, int width, int height) {
    
        //メッセージループはウィンドウを生成したスレッドに属していなければいけないので
        //CreateWindowの時点でスレッドに入っていなければならないのでここに書く
        m_hwnd = CreateWindow(
          TEXT("SZL_TEST_GUI_WINDOW"), title,
          WS_OVERLAPPEDWINDOW | WS_VISIBLE,
          posx, posy, width, height, NULL, NULL,
          hInstance, this
        );
    
        if (m_hwnd == NULL) {
          return 0;
        }
    
        MSG msg;
        while (GetMessage(&msg, NULL, 0, 0)) {
          TranslateMessage(&msg);
          DispatchMessage(&msg);
        }
    
        //スレッドから抜けるときはウィンドウハンドルをnullptrにする
        m_hwnd = nullptr;
    
        return msg.wParam;
    
      }
    
      //! @brief ウィンドウ作成
      bool open(const TCHAR* title, int posx, int posy, int width, int height) {
    
        if (registerWindowClass() == false)
          return false;
    
        m_mainloop.reset(//! @brief スレッド作成
          new std::thread(
            &GraphicDebugWindow::MainLoop,
            this,
            title,
            posx,
            posy,
            width,
            height
          ));
    
    
        // 窓が生成されるまで待つ
        while (m_hwnd == nullptr);
        UpdateWindow(m_hwnd);

    return true; } //! @brief ウィンドウを閉じたいときに呼び出す void close() { if (m_hwnd) { SendMessage(m_hwnd, WM_DESTROY, 0, 0); } if (m_mainloop) { if (m_mainloop->joinable()) { m_mainloop->join(); } m_mainloop.reset(); } } void join() { if (m_mainloop) { if (m_mainloop->joinable()) { m_mainloop->join(); } m_mainloop.reset(); } } //! @brief 外にウィンドウハンドルを公開 HWND get_hwnd() { return m_hwnd; } virtual ~GraphicDebugWindow() { close(); } //! @brief メンバ関数版ウィンドウプロシージャ virtual LRESULT WndProc(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp) { PAINTSTRUCT ps; HDC hdc; switch (msg) { case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, msg, wp, lp); } };

    使用例

    #include <iostream>
    #include<vector>
    
    #include "CImageViewWindow.hpp"
    
    #pragma warning(disable:4996)
    
    
    int main()
    {
      CImageViewWindow gw;
    
    #if 0
      gw.open(TEXT("2×3×RGB画像を表示"), 100, 100, 300, 300);
    
      typedef unsigned char rgb_t[3];
    
      rgb_t texdata[2*3];
      texdata[0][0] = 0;
      texdata[0][1] = 255;
      texdata[0][2] = 0;
    
      texdata[1][0] = 255;
      texdata[1][1] = 0;
      texdata[1][2] = 0;
    
      texdata[2][0] = 255;
      texdata[2][1] = 0;
      texdata[2][2] = 0;
    
      texdata[3][0] = 0;
      texdata[3][1] = 255;
      texdata[3][2] = 0;
    
      texdata[4][0] = 0;
      texdata[4][1] = 255;
      texdata[4][2] = 0;
    
      texdata[5][0] = 255;
      texdata[5][1] = 0;
      texdata[5][2] = 0;
    
      gw.display(2, 3, 57, &texdata[0][0], 3);
    
    #else
      gw.open(TEXT("2×3×RGBA画像を表示"), 100, 100, 300, 300);
    
      typedef unsigned char rgba_t[4];
    
      rgba_t texdata[2 * 3];
      texdata[0][0] = 0;
      texdata[0][1] = 255;
      texdata[0][2] = 0;
      texdata[0][3] = 0;
    
      texdata[1][0] = 255;
      texdata[1][1] = 0;
      texdata[1][2] = 0;
      texdata[1][3] = 50;
    
      texdata[2][0] = 255;
      texdata[2][1] = 0;
      texdata[2][2] = 0;
      texdata[2][3] = 100;
    
      texdata[3][0] = 0;
      texdata[3][1] = 255;
      texdata[3][2] = 0;
      texdata[3][3] = 150;
    
      texdata[4][0] = 0;
      texdata[4][1] = 255;
      texdata[4][2] = 0;
      texdata[4][3] = 200;
    
      texdata[5][0] = 255;
      texdata[5][1] = 0;
      texdata[5][2] = 0;
      texdata[5][3] = 255;
    
      gw.display(2, 3, 57, &texdata[0][0], 4);
    
    #endif
    
    
      gw.join();
    }
    

    実行結果

    コンソールアプリケーションでデバッグ用のウィンドウを表示-2-画像表示

    CG関係のプログラミングをやってるとコードから画像を作成して内容を確認したいといった時がある。PPMで出力して確認していたが何かと面倒だし、だからといってOpenGLでテクスチャに表示するのはさらに面倒なので確認用のウィンドウを作成したい。前回作ったウィンドウ表示用のクラスに、画像表示機能を付ける

    CRGBViewWindow.hpp

    #pragma once
    
    #include "gwindbg.hpp"
    #include <mutex>
    
    
    //! @brief DIBを扱う
    struct DIBData {
      BITMAPINFO m_bmpInfo;   //!< CreateDIBSectionに渡す構造体
      LPDWORD m_lpPixel;      //!< 画素へのポインタ
      HBITMAP m_hBitmap;      //!< 作成したMDCのビットマップハンドル
      HDC m_hMemDC;           //!< 作成したMDCのハンドル
    
      int m_imagesizemax;     //!< 合計画素数(width*height)
      int m_width;            //!< 画像の幅(ピクセル,自然数)
      int m_height;           //!< 画像の高さ(ピクセル,自然数)
    
      int m_bitcount;
      DIBData() {
        DeleteDC(m_hMemDC);
        DeleteObject(m_hBitmap);
      }
      ~DIBData() {
        m_hBitmap = nullptr;
        m_hMemDC = nullptr;
        m_lpPixel = nullptr;
        m_width = 0;
        m_height = 0;
        m_bitcount = 0;
      }
      void create(int width, int height, int bitcount) {
        if (width != m_width || height != m_height) {
          if (m_hBitmap) {
            DeleteObject(m_hBitmap);
            m_hBitmap = nullptr;
          }
          if (m_hMemDC) {
            DeleteDC(m_hMemDC);
            m_hMemDC = nullptr;
          }
          //DIBの情報を設定する
          m_bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
          m_bmpInfo.bmiHeader.biWidth = width;
          m_bmpInfo.bmiHeader.biHeight = -height; //-を指定しないと上下逆になる
          m_bmpInfo.bmiHeader.biPlanes = 1;
          m_bmpInfo.bmiHeader.biBitCount = bitcount;
          m_bmpInfo.bmiHeader.biCompression = BI_RGB;
    
          HDC hdc = GetDC(nullptr);
          m_hBitmap = CreateDIBSection(hdc, &m_bmpInfo, DIB_RGB_COLORS, (void**)&m_lpPixel, nullptr, 0);
          m_hMemDC = CreateCompatibleDC(hdc);
          SelectObject(m_hMemDC, m_hBitmap);
          ReleaseDC(nullptr, hdc);
    
          m_width = width;
          m_height = height;
          m_bitcount = bitcount;
        }
      }
    };
    class CRGBViewWindow : public GraphicDebugWindow {
    
      DIBData dibdata;
    
      //! @brief 表示倍率
      int m_magnification;
    
      std::mutex m_mainmuitex;
    
    public:
      CRGBViewWindow() {
      }
    
    
      //! @brief 画像表示関数
      //! @param [in] width 画像幅
      //! @param [in] height 画像高さ
      //! @param [in] magnification 表示倍率。小さすぎる画像を大きく表示できる
      //! @param [in] p 画像データ。RGBRGBRGB...
      //! @return なし
      void display(int width, int height, int magnification, unsigned char* p) {
    
        m_magnification = magnification;
    
        int pixelcount = 3;
    
        m_mainmuitex.lock();
    
        dibdata.create(width, height, 24);
    
        if (p) {// 画像を仮想スクリーンへコピー
          for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
              int pos = (y * width + x)*pixelcount;
              SetPixel(dibdata.m_hMemDC, x, y, RGB(p[pos + 0], p[pos + 1], p[pos + 2]));
            }
          }
        }
    
        m_mainmuitex.unlock();
    
      }
    
    
      virtual LRESULT WndProc(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp)override
      {
        PAINTSTRUCT ps;
        HDC hdc;
        switch (msg)
        {
        case WM_SIZING:
          InvalidateRect(hWnd, nullptr, TRUE);
          break;
        case WM_PAINT:
          hdc = BeginPaint(hWnd, &ps);
          m_mainmuitex.lock();
    
    //DIBの内容をウィンドウに表示
    if (dibdata.m_hMemDC) { StretchBlt( hdc, 0, 0, dibdata.m_width * m_magnification, dibdata.m_height * m_magnification, dibdata.m_hMemDC, 0, 0, dibdata.m_width, dibdata.m_height, SRCCOPY); }

    m_mainmuitex.unlock(); EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, msg, wp, lp); }
    };
    

    使用例

    #include <iostream>
    #include<vector>
    
    #include "CRGBViewWindow.hpp"
    
    #pragma warning(disable:4996)
    
    
    int main()
    {
      CRGBViewWindow gw;
      gw.open(TEXT("2×2×RGB画像を表示"), 100, 100, 300, 300);
    
      typedef unsigned char rgb_t[3];
    
      rgb_t texdata[2*3];
      texdata[0][0] = 0;
      texdata[0][1] = 255;
      texdata[0][2] = 0;
    
      texdata[1][0] = 255;
      texdata[1][1] = 0;
      texdata[1][2] = 0;
    
      texdata[2][0] = 255;
      texdata[2][1] = 0;
      texdata[2][2] = 0;
    
      texdata[3][0] = 0;
      texdata[3][1] = 255;
      texdata[3][2] = 0;
    
      texdata[4][0] = 0;
      texdata[4][1] = 255;
      texdata[4][2] = 0;
    
      texdata[5][0] = 255;
      texdata[5][1] = 0;
      texdata[5][2] = 0;
    
      gw.display(2, 3, 50, &texdata[0][0]);
    
      gw.join();
    }
    

    コンソールアプリケーションでデバッグ用のウィンドウを表示-1

    プログラムはコンソールで良いが画像での確認もしたい時にウィンドウが欲しくなるので、コンソールアプリから開けるウィンドウを作成する。

    gwindbg.hpp

    #pragma once
    
    #include <Windows.h>
    #include <thread>
    
    class GraphicDebugWindow {
    
      //! @brief WNDCLASSに設定するウィンドウプロシージャ
      static LRESULT CALLBACK StaticWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
      {
        //CreateWindowの最後の引数で渡したthisポインタを取得
        GraphicDebugWindow* This = (GraphicDebugWindow*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
        if (!This) {//取得できなかった(ウィンドウ生成中)場合
          if (message == WM_CREATE) {
            This = (GraphicDebugWindow*)((LPCREATESTRUCT)lParam)->lpCreateParams;
            if (This) {
              SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)This);
              return This->WndProc(hWnd, message, wParam, lParam);
            }
          }
        }
        else {//取得できた場合(ウィンドウ生成後)
          return This->WndProc(hWnd, message, wParam, lParam);
        }
        return DefWindowProc(hWnd, message, wParam, lParam);
      }
    
    
      //メインループのスレッド
      std::unique_ptr<std::thread> m_mainloop;
    
      HINSTANCE hInstance;
      HWND m_hwnd;
    public:
    
      GraphicDebugWindow() {}
    
    
      bool registerWindowClass() {
        //インスタンスハンドルの取得
        hInstance = GetModuleHandle(0);
    
        WNDCLASS winc;
    
        winc.style = CS_HREDRAW | CS_VREDRAW;
        winc.lpfnWndProc = StaticWndProc;
        winc.cbClsExtra = winc.cbWndExtra = 0;
        winc.hInstance = hInstance;
        winc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
        winc.hCursor = LoadCursor(NULL, IDC_ARROW);
        winc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
        winc.lpszMenuName = NULL;
        winc.lpszClassName = TEXT("SZL_TEST_GUI_WINDOW");
    
        if (!RegisterClass(&winc))
          return false;
    
        return true;
      }
    
      //! @brief スレッドの内容
      int MainLoop(const TCHAR* title,int posx,int posy,int width,int height) {
    
        //メッセージループはウィンドウを生成したスレッドに属していなければいけないので
        //CreateWindowの時点でスレッドに入っていなければならないのでここに書く
        m_hwnd = CreateWindow(
          TEXT("SZL_TEST_GUI_WINDOW"), title,
          WS_OVERLAPPEDWINDOW | WS_VISIBLE,
          posx, posy, width, height, NULL, NULL,
          hInstance, this
        );
    
        if (m_hwnd == NULL)
          return 0;
    
        MSG msg;
        while (GetMessage(&msg, NULL, 0, 0)) {
          TranslateMessage(&msg);
          DispatchMessage(&msg);
        }
    
        //スレッドから抜けるときはウィンドウハンドルをnullptrにする
        m_hwnd = nullptr;
    
        return msg.wParam;
    
      }
    
    
      //! @brief ウィンドウ作成
      bool open(const TCHAR* title, int posx, int posy, int width, int height) {
    
        if (registerWindowClass() == false)
          return false;
    
        m_mainloop.reset(//! @brief スレッド作成
          new std::thread(
            &GraphicDebugWindow::MainLoop,
            this, 
            title, 
            posx, 
            posy, 
            width, 
            height
          ));
    
        return true;
      }
    
    
      //! @brief ウィンドウを閉じたいときに呼び出す
      void close() {
        if (m_hwnd ) {
          SendMessage(m_hwnd, WM_DESTROY, 0, 0);
        }
        if (m_mainloop) {
          if (m_mainloop->joinable()) {
            m_mainloop->join();
          }
          m_mainloop.reset();
        }
      }

      void join() {
        if (m_mainloop) {
          if (m_mainloop->joinable()) {
            m_mainloop->join();
          }
          m_mainloop.reset();
        }
      } 
      //! @brief 外にウィンドウハンドルを公開
      HWND get_hwnd() {return m_hwnd;}
    
    
      virtual ~GraphicDebugWindow() {
        close();
      }
    
    
      //! @brief メンバ関数版ウィンドウプロシージャ
      virtual LRESULT WndProc(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp)
      {
        PAINTSTRUCT ps;
        HDC hdc;
        switch (msg)
        {
        case WM_DESTROY:
          PostQuitMessage(0);
          return 0;
        }
        return DefWindowProc(hWnd, msg, wp, lp);
      }
    };
    

    使用例

    コンソールにアルファベットを入力すると、ウィンドウに表示される。

    'c'または'z'で抜ける。

    #include <iostream>
    
    #include "gwindbg.hpp"
    
    #pragma warning(disable:4996)
    
    int main()
    {
      GraphicDebugWindow gw;
      gw.open(TEXT("入力したキー表示(zで終了)"), 100, 100, 300, 300);
    
      char a = 'a';
      while (a != 'z') {
        std::cin >> a;
    
        char text[10];
        sprintf(text, "%c", a);
    
        //ウィンドウが消されていたらループを抜ける
        if (gw.get_hwnd() == nullptr)
          break;
    
        // ウィンドウを消す
        if (a == 'c')
          gw.close();
    
        //ウィンドウの方に入力した文字を表示
        HDC dc = GetDC(gw.get_hwnd());
        TextOutA(dc, 0, 0, "  ", 2);
        TextOutA(dc, 0, 0, text, 1);
        ReleaseDC(gw.get_hwnd(), dc);
    
      }
      gw.close();
      std::cin >> a;
    }