ぬの部屋(仮)
nu-no-he-ya
  •      12
    3456789
    10111213141516
    17181920212223
    24252627282930
           
      12345
    6789101112
    13141516171819
    20212223242526
    2728293031  
           
    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
           
  • レイキャストを実装してみる(4) 三角形との交差

    球の代わりに三角形を使ってみる。

    raycast.hpp

    #pragma once
    
    #include "Grid.hpp"
    
    #include <array>
    
    //////////////////////////////////////////////
    //////////////////////////////////////////////
    // 球オブジェクト
    class object_sphere {
      glm::vec3 _center;
      glm::vec3 _color;
      float _r;
    public:
      object_sphere(glm::vec3 center_, glm::vec3 color_,float radius_) :
        _center(center_), _color(color_),_r(radius_) {}
      object_sphere() {}
    
      //! @brief レイと球の交点を求める
      //! @param [out] pos_ 交点の座標
      //! @param [out] color_ 球オブジェクトの色
      //! @param [out] normal_ 交点の面の法線
      //! @param [in] ray_ レイ
      //! @retval true 交差している
      //! @retval false 交差していない
      bool intersect(
        glm::vec3* pos_, 
        glm::vec3* color_,
        glm::vec3* normal_,
        const std::array<glm::vec3, 2>& ray_)const;
    
      const glm::vec3& color()const { return _color; }
      glm::vec3& color() { return _color; }
    
    };
    
    
    //////////////////////////////////////////////
    //////////////////////////////////////////////
    // 三角形オブジェクト
    class object_triangle {
      std::array<glm::vec3, 3> _points;
      glm::vec3 _color;
    public:
      object_triangle(
        std::array<glm::vec3, 3> points_, glm::vec3 color_) :
        _points(points_), _color(color_) {}
      object_triangle() {}
    
      bool intersect(
        glm::vec3* pos_,
        glm::vec3* color_,
        glm::vec3* normal_,
        const std::array<glm::vec3, 2>& ray_)const;
    
      const glm::vec3& color()const { return _color; }
      glm::vec3& color() { return _color; }
    
    };
    
          
    //////////////////////////////////////////////
    //////////////////////////////////////////////
    // ポイントライト
    class light_point {
      glm::vec3 _position;
      glm::vec3 _diffuse_color;
      glm::vec3 _ambient_color;
      glm::vec3 _specular_color;
    public:
    
      light_point(
        const glm::vec3& position_, 
        const glm::vec3& diffuse_color_,
        const glm::vec3& ambient_color_,
        const glm::vec3& specular_color_
      ) :
        _position(position_), 
        _diffuse_color(diffuse_color_),
        _ambient_color(ambient_color_),
        _specular_color(specular_color_)
      {}
      light_point() {}
    
      glm::vec3 calc_vector_point_to_light(const glm::vec3& point_)const {
        // from -> _position
        return glm::normalize(_position - point_);
      }
    
      const glm::vec3& position()const {return _position;}
      glm::vec3& position() { return _position; }
    
      const glm::vec3& diffuse_color()const {return _diffuse_color;}
      glm::vec3& diffuse_color() { return _diffuse_color; }
    
      const glm::vec3& ambient_color()const { return _ambient_color; }
      glm::vec3& ambient_color() { return _ambient_color; }
    
      const glm::vec3& specular_color()const { return _specular_color; }
      glm::vec3& specular_color() { return _specular_color; }
    
    };
    
    struct hit_pixel_t {
      glm::vec3 _position;
      glm::vec3 _color;
      hit_pixel_t(const glm::vec3& position_, const glm::vec3& color_) :
        _position(position_), _color(color_) {}
    
    };
    
    
    // レイキャスト用のクラス
    class my_raycast {
      grid g[2];
      float _startZ;
      float _endZ;
      int _pxwidth;
      int _pxheight;
    public:
    
      //! @brief 視点を取得
      //! @details 普通は視点、near , farからレイを作成すると思うが、今回は
      //! グリッドを二枚作ることでnear,farを決定しているので、視点を計算で求める必要がある。
      //! 視点はspecular計算の時に必要となる。
      glm::vec3 get_eye_position()const {
        float a = g[0].ywidth() / 2.0;
        float b = g[1].ywidth() / 2.0;
        float d = glm::length(g[1].center() - g[0].center());
        float c = a * d / (b - a);
    
    
        // 始点 → 終点
        glm::vec3 veceye = g[1].center() - g[0].center();
        veceye = glm::normalize(veceye);
        return g[0].center()  - veceye * c;
      }
    
      my_raycast() {}
    
      //! @brief 結果のピクセル数(幅)を取得
      int width()const { return _pxwidth; }
      //! @brief 結果のピクセル数(高さ)を取得
      int height()const { return _pxheight; }
    
      //! @brief レイの開始点となるグリッド、終点となるグリッドを作成する
      //! @param [in] startZ_   始点のグリッドのZ座標
      //! @param [in] endZ_   終点のグリッドのZ座標
      //! @param [in] pxwidth_  ピクセル数 X
      //! @param [in] pxheight_ ピクセル数 Y
      void set(const float startZ_, const float endZ_, const int pxwidth_, const int pxheight_);
    
      //グリッド取得
      const grid& get_grid(const size_t index)const {
        return g[index];
      }
    
      //グリッドから作成するレイの数を取得
      int ray_count() {
        return g[0].cellCount();
      }
    
      //グリッドから作成するレイを取得
      std::array<glm::vec3, 2> get_ray(const size_t index)const;
    
      //始点グリッド、終点グリッドの中間の位置を取得(表示用)
      float lookatZ()const {
        return (_startZ + _endZ) / 2.f;
      }
    
    
      //////////////////////////////////////////////
      //////////////////////////////////////////////
    
    private:
      // object_sphere _obj;
      object_triangle _obj;
    
      std::vector< hit_pixel_t > _hits;
    public:
      void raycast();
      std::vector< hit_pixel_t >& get_intersects() {return _hits;}
    
      //void set_object(const object_sphere& obj_);
      void set_object(const object_triangle& obj_);
    
      //////////////////////////////
    private:
      light_point _light;
    public:
      void set_light(const light_point& light_);
    
      const light_point& get_light()const { return _light; }
    };
    
    //! @brief diffuse計算
    //! @param [in] lightDiffuse ライトの色
    //! @param [in] materialDiffuse オブジェクトの色
    //! @param [in] lightIncidence ライトの入射ベクトル
    //! @param [in] objectNormal 面法線
    //! @return diffuse色
    inline glm::vec3 calc_diffuse(
      const glm::vec3& lightDiffuse, 
      const glm::vec3& materialDiffuse,
      const glm::vec3& lightIncidence,
      const glm::vec3& objectNormal) 
    {
      // 拡散反射は「そのポイント→光源」と面法線の内積を取る
    
      float sDotN = glm::max(glm::dot(-lightIncidence, objectNormal), 0.f);
    
      return lightDiffuse * materialDiffuse *sDotN;
    }
    
    //! @brief ambient計算
    //! @param [in] lightAmbient ライトの色
    //! @param [in] materialAmbient オブジェクトの色
    //! @return ambient色
    inline glm::vec3 calc_ambient(
      const glm::vec3& lightAmbient, 
      const glm::vec3& materialAmbient) 
    {
      return lightAmbient * materialAmbient;
    }
    
    //! @brief specular計算
    //! @param [in] eyePosition 視点の座標
    //! @param [in] lightSpecularColor ライトの色
    //! @param [in] materialSpecularColor オブジェクトの色
    //! @param [in] lightIncidence ライトの入射ベクトル
    //! @param [in] materialShininess 光沢度
    //! @param [in] objectNormal レイがヒットした位置の面法線
    //! @param [in] objectPosition レイがヒットした座標
    //! @return specular色
    inline glm::vec3 calc_specular(
      const glm::vec3& eyePosition,
      const glm::vec3& lightSpecularColor,
      const glm::vec3& materialSpecularColor,
      const glm::vec3& lightIncidence, // 入射
      const float materialShininess,
      const glm::vec3& objectNormal,
      const glm::vec3& objectPosition
    )
    {
    
      // 参考文献:
      // https://araramistudio.jimdo.com/2017/10/02/%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0-directx-11%E3%81%A7%E9%8F%A1%E9%9D%A2%E5%8F%8D%E5%B0%84-specular-reflection/
      // https://amengol.github.io/game_physics/using-glm-reflect-to-react/
      // https://learnopengl.com/Lighting/Basic-Lighting
    
      // レイとの交点→カメラ位置 のベクトル
      glm::vec3 VertexToEyeVec = glm::normalize(eyePosition - objectPosition);
    
      // ライトの入射に対する反射ベクトル
      glm::vec3 LightReflect = glm::normalize(glm::reflect(lightIncidence, objectNormal));
    
      float SpecularFactor = glm::pow(glm::max(glm::dot(VertexToEyeVec, LightReflect),0.f), materialShininess);
    
      glm::vec3 SpecularColor(0, 0, 0);
      SpecularColor = SpecularFactor * lightSpecularColor * materialSpecularColor;
    
      return SpecularColor;
    
    }
    

    raycast.cpp

    #include "raycast.hpp"
    
    #include <glm/gtx/intersect.hpp>
    
    
    #include <glm/gtx/normal.hpp>
    
    bool object_sphere::intersect(
      glm::vec3* pos_, 
      glm::vec3* color_,
      glm::vec3* normal_,
      const std::array<glm::vec3, 2>& ray_) const{
    
      // レイから正規化ベクトルを作成
      glm::vec3 nray = glm::normalize(ray_[1] - ray_[0]);
    
      // レイの始点から交点までの距離
      float distance;
      bool valid = glm::intersectRaySphere(ray_[0], nray, _center, _r*_r, distance);
    
      //レイが衝突した点の座標
      *pos_ = ray_[0] + nray * distance;
    
      //色の設定
      *color_ = _color;
    
    
      //面法線
      // 球中心 → 衝突点
      *normal_ = glm::normalize(*pos_ - _center);
    
      // 交差していればtrue
      return valid;
    }
    
    
    /////////////////////////////////
    // 三角形とレイの交差
    bool object_triangle::intersect(
      glm::vec3* pos_,
      glm::vec3* color_,
      glm::vec3* normal_,
      const std::array<glm::vec3, 2>& ray_)const {
    
      glm::vec3 nray = glm::normalize(ray_[1] - ray_[0]);
    
      float distance;
    
      glm::vec2 bary;
    
      bool valid = glm::intersectRayTriangle(
        ray_[0],
        nray,
        _points[0],
        _points[1],
        _points[2],
        bary,
        distance
      );
    
      //レイが衝突した点の座標
      *pos_ = ray_[0] + nray * distance;
    
    
      //色の設定
      *color_ = _color;
    
      //面法線
      *normal_ = glm::triangleNormal(
        _points[0],
        _points[1],
        _points[2]
      ); // normalize済
    
      return valid;
    
    }
    void my_raycast::set(const float startZ_, const float endZ_, const int pxwidth_, const int pxheight_) {
      _startZ = startZ_;
      _endZ = endZ_;
    
      _pxwidth = pxwidth_;
      _pxheight = pxheight_;
    
      glm::vec3 vecx(1, 0, 0);
      glm::vec3 vecy(0, 1, 0);
    
      g[0] = grid(
        vecx,
        vecy,
        glm::vec3(0, 0, _startZ),
        1.f, 1.f,
        pxwidth_, pxheight_
      );
      g[1] = grid(
        vecx,
        vecy,
        glm::vec3(0, 0, _endZ),
        2.f, 2.f,
        pxwidth_, pxheight_
      );
    
    }
    
    //! @brief レイの取得
    //! @param [in] index レイの番号 最大 pxwidth_ × pxheight_
    std::array<glm::vec3, 2> my_raycast::get_ray(const size_t index)const {
      return
        std::array<glm::vec3, 2>{
        g[0][index].center(),
          g[1][index].center()
      };
    
    }
    
    //void my_raycast::set_object(const object_sphere& obj_) {
    //  _obj = obj_;
    //}
    void my_raycast::set_object(const object_triangle& obj_) {
      _obj = obj_;
    }
    
    void my_raycast::set_light(const light_point& light_) {
      _light = light_;
    }
    
    void my_raycast::raycast() {
    
      float inf = std::numeric_limits<float>::infinity();
      // 結果の初期化
      _hits.clear();
      _hits.resize(
        _pxwidth * _pxheight,
        hit_pixel_t(
          glm::vec3(inf, inf, inf),
          glm::vec3(0, 0, 0)
        )
      );
    
      // 
      for (size_t y = 0; y < _pxheight; y++) {
        for (size_t x = 0; x < _pxwidth; x++) {
          size_t index = y * _pxwidth + x;
          auto ray = get_ray(index);
    
          glm::vec3 p; // レイがヒットした座標
          glm::vec3 c; // レイがヒットした位置の色
          glm::vec3 n; // レイがヒットした位置の法線
          if (_obj.intersect(&p, &c,&n, ray) == true) {
    
            _hits[index]._position = p;
            
            // ライトの入射ベクトル
            glm::vec3 lightIncidence = -_light.calc_vector_point_to_light(p);
    
            // diffuse色の計算
            glm::vec3 diffuse = calc_diffuse(_light.diffuse_color(),c, lightIncidence, n);
    
            // ambient色の計算
            glm::vec3 ambient = calc_ambient(
              _light.ambient_color(), c
            );
    
            // specular色の計算
            glm::vec3 specular = calc_specular(
              get_eye_position(),
              _light.specular_color(), 
              c,
              lightIncidence,
              80, n, p);
    
    
            _hits[index]._color = ambient + diffuse + specular;
    
          }
    
        }
      }
    }
    

    main.cpp

    #include <iostream>
    #include <array>
    
    #include<GL/freeglut.h>
    #include<gl/GL.h>
    
    #include "raycast.hpp"
    
    #include<glm/gtc/type_ptr.hpp>
    
    #include<glm/gtc/matrix_transform.hpp>
    
    my_raycast mydata;
    
    
    //! @brief グリッドを表示
    //! @param [in] g グリッドオブジェクト
    //! @param [in] dispcenter セルの中央を表示するか
    void drawGrid(const grid& g, const bool dispcenter) {
    
      glLineWidth(1);
      glColor3d(1, 1, 1);
      for (size_t i = 0; i < g.cellCount(); i++) {
        glBegin(GL_LINE_LOOP);
        glVertex3fv(glm::value_ptr(g.p0(i)));
        glVertex3fv(glm::value_ptr(g.p1(i)));
        glVertex3fv(glm::value_ptr(g.p2(i)));
        glVertex3fv(glm::value_ptr(g.p3(i)));
    
        glEnd();
      }
    
      if (dispcenter) {
        glPointSize(1);
        glColor3d(1, 1, 1);
        glBegin(GL_POINTS);
        for (size_t i = 0; i < g.cellCount(); i++) {
          glVertex3fv(
            glm::value_ptr(g[i].center()));
        }
        glEnd();
      }
    }
    
    
    
    void drawXYZ() {
      glLineWidth(3);
      glBegin(GL_LINES);
      glColor3f(1, 0, 0);
      glVertex3f(0, 0, 0);
      glVertex3f(1, 0, 0);
    
      glColor3f(0, 1, 0);
      glVertex3f(0, 0, 0);
      glVertex3f(0, 1, 0);
    
      glColor3f(0, 0, 1);
      glVertex3f(0, 0, 0);
      glVertex3f(0, 0, 1);
      glEnd();
      glLineWidth(1);
    }
    
    void drawRays() {
      glBegin(GL_LINES);
      for (size_t i = 0; i < mydata.ray_count(); i++) {
        auto ray = mydata.get_ray(i);
        glColor3f(1.0, 1.0, 1.0);
        glVertex3fv(glm::value_ptr(ray[0]));
        glColor3f(0.0, 0.0, 1.0);
        glVertex3fv(glm::value_ptr(ray[1]));
      }
      glEnd();
    }
    
    
    
    //ウィンドウの幅と高さ
    int width, height;
    
    //描画関数
    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);
    
      glMatrixMode(GL_PROJECTION);
      glLoadIdentity();
      glm::mat4 proj = glm::perspectiveFov(glm::radians(45.f), (float)width, (float)height, 0.1f, 50.f);
      glLoadMatrixf(glm::value_ptr(proj));
    
      glMatrixMode(GL_MODELVIEW);
      glLoadIdentity();
    
      //////////////////////////////////////////
      //////////////////////////////////////////
      // カメラの設定
      float z = mydata.lookatZ();
      glm::mat4 look = glm::lookAt(
        glm::vec3(5, 4, z-5 ),// eye
        glm::vec3(0, 0, z ), // lookat
        glm::vec3(0,1, 0)   // up
      );
      glLoadMatrixf(glm::value_ptr(look));
      //////////////////////////////////////////
      // グリッドを表示
      drawGrid(mydata.get_grid(0), false);//from
      drawGrid(mydata.get_grid(1), false);//to
      //////////////////////////////////////////
      // 作成したレイを表示
      //drawRays();
      //////////////////////////////////////////
      // レイと球の衝突位置を三次元空間に可視化
      glPointSize(5);
      glBegin(GL_POINTS);
      for (size_t i = 0; i < mydata.get_intersects().size(); i++) {
        glColor3fv(
          glm::value_ptr(mydata.get_intersects()[i]._color)
        );
        glVertex3fv(
          glm::value_ptr(mydata.get_intersects()[i]._position)
        );
      }
      glEnd();
      glPointSize(1);
    
      drawXYZ();
    
      // レイと球の衝突位置を二次元に可視化
      glPointSize(5);
      glBegin(GL_POINTS);
      for (size_t i = 0; i < mydata.get_intersects().size(); i++) {
    
        if (isinf(mydata.get_intersects()[i]._position.x) == false) {
          glColor3fv(
            glm::value_ptr(mydata.get_intersects()[i]._color)
          );
          glVertex3fv(
            glm::value_ptr(mydata.get_grid(0)[i].center())
          );
        }
      }
      glEnd();
      glPointSize(1);
    
      //ライトの位置表示
      glColor3d(1, 1, 0);
      glPointSize(10);
      glBegin(GL_POINTS);
      glVertex3fv(glm::value_ptr(mydata.get_light().position()));
      glEnd();
      glPointSize(1);
      glColor3d(1, 0, 0);
    
      //視点表示
      glColor3d(0, 0, 1);
      glPointSize(35);
      glBegin(GL_POINTS);
      glm::vec3 eyepos = mydata.get_eye_position();
      glVertex3fv(glm::value_ptr(eyepos));
      glEnd();
      glPointSize(1);
    
    
    
      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);
    
    
      mydata.set(0.f, 3.f,100,100);
      ///////////////////////////////////
      //球の設定
      /*
      mydata.set_object(
        object_sphere(
          glm::vec3(0.0, 0.0, 2.0), // 球の中心
          glm::vec3(1.0, 0.0, 0.0),   // 球の色
          0.5
        )
      );
      */
      //////////////////////////////////
    //三角形の設定 mydata.set_object( object_triangle( std::array< glm::vec3, 3>{ glm::vec3(0.916876, -0.440909, 1.58713),//第一頂点 glm::vec3(-0.633301, -0.622765, 0.585358),//第二頂点 glm::vec3(-0.513684, 0.853145, 1.330333)//第三頂点 }, glm::vec3(1, 1, 0) ) ); /////////////////////////////////// mydata.set_light( light_point( glm::vec3(1.0, 1.0, 0.5), // ライトの位置 glm::vec3(0.5, 0.5, 0.5), // diffuse色 glm::vec3(0.2, 0.2, 0.2), // ambient色 glm::vec3(1.0, 1.0, 1.0) // specular色 ) ); mydata.raycast(); glutCreateWindow("sample"); glutDisplayFunc(disp); glutReshapeFunc(reshape); glutMainLoop(); return 0; }

    レイキャストを実装してみる(3) ADSシェーダを実装

    光源を追加し、Ambient,Diffuse,Specularを計算する

    raycast.hpp

    #pragma once
    
    #include "Grid.hpp"
    
    #include <array>
    
    //////////////////////////////////////////////
    //////////////////////////////////////////////
    // 球オブジェクト
    class object_sphere {
      glm::vec3 _center;
      glm::vec3 _color;
      float _r;
    public:
      object_sphere(glm::vec3 center_, glm::vec3 color_,float radius_) :
        _center(center_), _color(color_),_r(radius_) {}
      object_sphere() {}
    
      //! @brief レイと球の交点を求める
      //! @param [out] pos_ 交点の座標
      //! @param [out] color_ 球オブジェクトの色
      //! @param [out] normal_ 交点の面の法線
      //! @param [in] ray_ レイ
      //! @retval true 交差している
      //! @retval false 交差していない
      bool intersect(
        glm::vec3* pos_, 
        glm::vec3* color_,
        glm::vec3* normal_,
        const std::array<glm::vec3, 2>& ray_)const;
    
      const glm::vec3& color()const { return _color; }
      glm::vec3& color() { return _color; }
    
    };
     
    //////////////////////////////////////////////
    //////////////////////////////////////////////
    // ポイントライト
    class light_point {
      glm::vec3 _position;
      glm::vec3 _diffuse_color;
      glm::vec3 _ambient_color;
      glm::vec3 _specular_color;
    public:
    
      light_point(
        const glm::vec3& position_, 
        const glm::vec3& diffuse_color_,
        const glm::vec3& ambient_color_,
        const glm::vec3& specular_color_
      ) :
        _position(position_), 
        _diffuse_color(diffuse_color_),
        _ambient_color(ambient_color_),
        _specular_color(specular_color_)
      {}
      light_point() {}
    
      glm::vec3 calc_vector_point_to_light(const glm::vec3& point_)const {
        // from -> _position
        return glm::normalize(_position - point_);
      }
    
      const glm::vec3& position()const {return _position;}
      glm::vec3& position() { return _position; }
    
      const glm::vec3& diffuse_color()const {return _diffuse_color;}
      glm::vec3& diffuse_color() { return _diffuse_color; }
    
      const glm::vec3& ambient_color()const { return _ambient_color; }
      glm::vec3& ambient_color() { return _ambient_color; }
    
      const glm::vec3& specular_color()const { return _specular_color; }
      glm::vec3& specular_color() { return _specular_color; }
    
    };

    struct
    hit_pixel_t { glm::vec3 _position; glm::vec3 _color; hit_pixel_t(const glm::vec3& position_, const glm::vec3& color_) : _position(position_), _color(color_) {} }; // レイキャスト用のクラス class my_raycast { grid g[2]; float _startZ; float _endZ; int _pxwidth; int _pxheight; public: //! @brief 視点を取得 //! @details 普通は視点、near , farからレイを作成すると思うが、今回は //! グリッドを二枚作ることでnear,farを決定しているので、視点を計算で求める必要がある。 //! 視点はspecular計算の時に必要となる。 glm::vec3 get_eye_position()const { float a = g[0].ywidth() / 2.0; float b = g[1].ywidth() / 2.0; float d = glm::length(g[1].center() - g[0].center()); float c = a * d / (b - a); // 始点 → 終点 glm::vec3 veceye = g[1].center() - g[0].center(); veceye = glm::normalize(veceye); return g[0].center() - veceye * c; } my_raycast() {} //! @brief 結果のピクセル数(幅)を取得 int width()const { return _pxwidth; } //! @brief 結果のピクセル数(高さ)を取得 int height()const { return _pxheight; } //! @brief レイの開始点となるグリッド、終点となるグリッドを作成する //! @param [in] startZ_ 始点のグリッドのZ座標 //! @param [in] endZ_ 終点のグリッドのZ座標 //! @param [in] pxwidth_ ピクセル数 X //! @param [in] pxheight_ ピクセル数 Y void set(const float startZ_, const float endZ_, const int pxwidth_, const int pxheight_); //グリッド取得 const grid& get_grid(const size_t index)const { return g[index]; } //グリッドから作成するレイの数を取得 int ray_count() { return g[0].cellCount(); } //グリッドから作成するレイを取得 std::array<glm::vec3, 2> get_ray(const size_t index)const; //始点グリッド、終点グリッドの中間の位置を取得(表示用) float lookatZ()const { return (_startZ + _endZ) / 2.f; } ////////////////////////////////////////////// ////////////////////////////////////////////// private: object_sphere _obj; std::vector< hit_pixel_t > _hits; public: void raycast(); std::vector< hit_pixel_t >& get_intersects() {return _hits;} void set_object(const object_sphere& obj_);
      //////////////////////////////
    private:
      light_point _light;
    public:
      void set_light(const light_point& light_);
    
      const light_point& get_light()const { return _light; }
    };
    
    
    //! @brief diffuse計算
    //! @param [in] lightDiffuse ライトの色
    //! @param [in] materialDiffuse オブジェクトの色
    //! @param [in] lightIncidence ライトの入射ベクトル
    //! @param [in] objectNormal 面法線
    //! @return diffuse色
    inline glm::vec3 calc_diffuse(
      const glm::vec3& lightDiffuse, 
      const glm::vec3& materialDiffuse,
      const glm::vec3& lightIncidence,
      const glm::vec3& objectNormal) 
    {
      // 拡散反射は「そのポイント→光源」と面法線の内積を取る
    
      float sDotN = glm::max(glm::dot(-lightIncidence, objectNormal), 0.f);
    
      return lightDiffuse * materialDiffuse *sDotN;
    }
          
    //! @brief ambient計算
    //! @param [in] lightAmbient ライトの色
    //! @param [in] materialAmbient オブジェクトの色
    //! @return ambient色
    inline glm::vec3 calc_ambient(
      const glm::vec3& lightAmbient, 
      const glm::vec3& materialAmbient) 
    {
      return lightAmbient * materialAmbient;
    }

    //! @brief specular計算
    //! @param [in] eyePosition 視点の座標
    //! @param [in] lightSpecularColor ライトの色
    //! @param [in] materialSpecularColor オブジェクトの色
    //! @param [in] lightIncidence ライトの入射ベクトル
    //! @param [in] materialShininess 光沢度
    //! @param [in] objectNormal レイがヒットした位置の面法線
    //! @param [in] objectPosition レイがヒットした座標
    //! @return specular色
    inline glm::vec3 calc_specular(
      const glm::vec3& eyePosition,
      const glm::vec3& lightSpecularColor,
      const glm::vec3& materialSpecularColor,
      const glm::vec3& lightIncidence, // 入射
      const float materialShininess,
      const glm::vec3& objectNormal,
      const glm::vec3& objectPosition
    )
    {
    
      // 参考文献:
      // https://araramistudio.jimdo.com/2017/10/02/%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0-directx-11%E3%81%A7%E9%8F%A1%E9%9D%A2%E5%8F%8D%E5%B0%84-specular-reflection/
      // https://amengol.github.io/game_physics/using-glm-reflect-to-react/
      // https://learnopengl.com/Lighting/Basic-Lighting
    
      // レイとの交点→カメラ位置 のベクトル
      glm::vec3 VertexToEyeVec = glm::normalize(eyePosition - objectPosition);
    
      // ライトの入射に対する反射ベクトル
      glm::vec3 LightReflect = glm::normalize(glm::reflect(lightIncidence, objectNormal));
    
      float SpecularFactor = glm::pow(glm::max(glm::dot(VertexToEyeVec, LightReflect),0.f), materialShininess);
    
      glm::vec3 SpecularColor(0, 0, 0);
      SpecularColor = SpecularFactor * lightSpecularColor * materialSpecularColor;
    
      return SpecularColor;
    
    }
    

    raycast.cpp

    #include "raycast.hpp"
    
    #include <glm/gtx/intersect.hpp>
    
    bool object_sphere::intersect(
      glm::vec3* pos_, 
      glm::vec3* color_,
      glm::vec3* normal_,
      const std::array<glm::vec3, 2>& ray_) const{
    
      // レイから正規化ベクトルを作成
      glm::vec3 nray = glm::normalize(ray_[1] - ray_[0]);
    
      // レイの始点から交点までの距離
      float distance;
      bool valid = glm::intersectRaySphere(ray_[0], nray, _center, _r*_r, distance);
    
      //レイが衝突した点の座標
      *pos_ = ray_[0] + nray * distance;
    
      //色の設定
      *color_ = _color;
    
    
      //面法線
      // 球中心 → 衝突点
      *normal_ = glm::normalize(*pos_ - _center);
    
      // 交差していればtrue
      return valid;
    }
    
    
    void my_raycast::set(const float startZ_, const float endZ_, const int pxwidth_, const int pxheight_) {
      _startZ = startZ_;
      _endZ = endZ_;
    
      _pxwidth = pxwidth_;
      _pxheight = pxheight_;
    
      glm::vec3 vecx(1, 0, 0);
      glm::vec3 vecy(0, 1, 0);
    
      g[0] = grid(
        vecx,
        vecy,
        glm::vec3(0, 0, _startZ),
        1.f, 1.f,
        pxwidth_, pxheight_
      );
      g[1] = grid(
        vecx,
        vecy,
        glm::vec3(0, 0, _endZ),
        2.f, 2.f,
        pxwidth_, pxheight_
      );
    
    }
    
    //! @brief レイの取得
    //! @param [in] index レイの番号 最大 pxwidth_ × pxheight_
    std::array<glm::vec3, 2> my_raycast::get_ray(const size_t index)const {
      return
        std::array<glm::vec3, 2>{
        g[0][index].center(),
          g[1][index].center()
      };
    
    }
    
    void my_raycast::set_object(const object_sphere& obj_) {
      _obj = obj_;
    }
    
    void my_raycast::set_light(const light_point& light_) {
      _light = light_;
    }
    
    
    void my_raycast::raycast() {
    
      float inf = std::numeric_limits<float>::infinity();
      // 結果の初期化
      _hits.clear();
      _hits.resize(
        _pxwidth * _pxheight,
        hit_pixel_t(
          glm::vec3(inf, inf, inf),
          glm::vec3(0, 0, 0)
        )
      );
    
      // 
      for (size_t y = 0; y < _pxheight; y++) {
        for (size_t x = 0; x < _pxwidth; x++) {
          size_t index = y * _pxwidth + x;
          auto ray = get_ray(index);
    
          glm::vec3 p; // レイがヒットした座標
          glm::vec3 c; // レイがヒットした位置の色
          glm::vec3 n; // レイがヒットした位置の法線
          if (_obj.intersect(&p, &c,&n, ray) == true) {
    
            _hits[index]._position = p;
            
            // ライトの入射ベクトル
            glm::vec3 lightIncidence = -_light.calc_vector_point_to_light(p);
    
            // diffuse色の計算
            glm::vec3 diffuse = calc_diffuse(_light.diffuse_color(),c, lightIncidence, n);
    
            // ambient色の計算
            glm::vec3 ambient = calc_ambient(_light.ambient_color(), c);
    
            // specular色の計算
            glm::vec3 specular = calc_specular(
              get_eye_position(),
              _light.specular_color(), 
              c,
              lightIncidence,
              80, n, p);
    
    
            _hits[index]._color = ambient + diffuse + specular;// 最終的な結果
    
          }
    
        }
      }
    }
    

    呼び出し

    #include <iostream>
    #include <array>
    
    #include<GL/freeglut.h>
    #include<gl/GL.h>
    
    #include "raycast.hpp"
    
    #include<glm/gtc/type_ptr.hpp>
    
    #include<glm/gtc/matrix_transform.hpp>
    
    my_raycast mydata;
    
    
    //! @brief グリッドを表示
    //! @param [in] g グリッドオブジェクト
    //! @param [in] dispcenter セルの中央を表示するか
    void drawGrid(const grid& g, const bool dispcenter) {
    
      glLineWidth(1);
      glColor3d(1, 1, 1);
      for (size_t i = 0; i < g.cellCount(); i++) {
        glBegin(GL_LINE_LOOP);
        glVertex3fv(glm::value_ptr(g.p0(i)));
        glVertex3fv(glm::value_ptr(g.p1(i)));
        glVertex3fv(glm::value_ptr(g.p2(i)));
        glVertex3fv(glm::value_ptr(g.p3(i)));
    
        glEnd();
      }
    
      if (dispcenter) {
        glPointSize(1);
        glColor3d(1, 1, 1);
        glBegin(GL_POINTS);
        for (size_t i = 0; i < g.cellCount(); i++) {
          glVertex3fv(
            glm::value_ptr(g[i].center()));
        }
        glEnd();
      }
    }
    
    
    
    void drawXYZ() {
      glLineWidth(3);
      glBegin(GL_LINES);
      glColor3f(1, 0, 0);
      glVertex3f(0, 0, 0);
      glVertex3f(1, 0, 0);
    
      glColor3f(0, 1, 0);
      glVertex3f(0, 0, 0);
      glVertex3f(0, 1, 0);
    
      glColor3f(0, 0, 1);
      glVertex3f(0, 0, 0);
      glVertex3f(0, 0, 1);
      glEnd();
      glLineWidth(1);
    }
    
    void drawRays() {
      glBegin(GL_LINES);
      for (size_t i = 0; i < mydata.ray_count(); i++) {
        auto ray = mydata.get_ray(i);
        glColor3f(1.0, 1.0, 1.0);
        glVertex3fv(glm::value_ptr(ray[0]));
        glColor3f(0.0, 0.0, 1.0);
        glVertex3fv(glm::value_ptr(ray[1]));
      }
      glEnd();
    }
    
    
    
    //ウィンドウの幅と高さ
    int width, height;
    
    //描画関数
    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);
    
      glMatrixMode(GL_PROJECTION);
      glLoadIdentity();
      glm::mat4 proj = glm::perspectiveFov(glm::radians(45.f), (float)width, (float)height, 0.1f, 50.f);
      glLoadMatrixf(glm::value_ptr(proj));
    
      glMatrixMode(GL_MODELVIEW);
      glLoadIdentity();
    
      //////////////////////////////////////////
      //////////////////////////////////////////
      // カメラの設定
      float z = mydata.lookatZ();
      glm::mat4 look = glm::lookAt(
        glm::vec3(5, 4, z-5 ),// eye
        glm::vec3(0, 0, z ), // lookat
        glm::vec3(0,1, 0)   // up
      );
      glLoadMatrixf(glm::value_ptr(look));
      //////////////////////////////////////////
      // グリッドを表示
      drawGrid(mydata.get_grid(0), false);//from
      drawGrid(mydata.get_grid(1), false);//to
      //////////////////////////////////////////
      // 作成したレイを表示
      //drawRays();
      //////////////////////////////////////////
      // レイと球の衝突位置を三次元空間に可視化
      glPointSize(5);
      glBegin(GL_POINTS);
      for (size_t i = 0; i < mydata.get_intersects().size(); i++) {
        glColor3fv(
          glm::value_ptr(mydata.get_intersects()[i]._color)
        );
        glVertex3fv(
          glm::value_ptr(mydata.get_intersects()[i]._position)
        );
      }
      glEnd();
      glPointSize(1);
    
      drawXYZ();
    
      // レイと球の衝突位置を二次元に可視化
      glPointSize(5);
      glBegin(GL_POINTS);
      for (size_t i = 0; i < mydata.get_intersects().size(); i++) {
    
        if (isinf(mydata.get_intersects()[i]._position.x) == false) {
          glColor3fv(
            glm::value_ptr(mydata.get_intersects()[i]._color)
          );
          glVertex3fv(
            glm::value_ptr(mydata.get_grid(0)[i].center())
          );
        }
      }
      glEnd();
      glPointSize(1);
    
      //ライトの位置表示
      glColor3d(1, 1, 0);
      glPointSize(10);
      glBegin(GL_POINTS);
      glVertex3fv(glm::value_ptr(mydata.get_light().position()));
      glEnd();
      glPointSize(1);
      glColor3d(1, 0, 0);
    
      //視点表示
      glColor3d(0, 0, 1);
      glPointSize(35);
      glBegin(GL_POINTS);
      glm::vec3 eyepos = mydata.get_eye_position();
      glVertex3fv(glm::value_ptr(eyepos));
      glEnd();
      glPointSize(1);
    
    
    
      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);
    
    
      mydata.set(0.f, 3.f,100,100);
      ///////////////////////////////////
      mydata.set_object(
        object_sphere(
          glm::vec3(0.0, 0.0, 2.0), // 球の中心
          glm::vec3(1.0, 0.0, 0.0), // 球の色
          0.5
        )
      );
      mydata.set_light(
        light_point(
          glm::vec3(1.0, 1.0, 0.5), // ライトの位置
          glm::vec3(0.5, 0.5, 0.5), // diffuse色
          glm::vec3(0.2, 0.2, 0.2), // ambient色
          glm::vec3(1.0, 1.0, 1.0)  // specular色
        )
      );
      mydata.raycast();
    
    
      glutCreateWindow("sample");
      glutDisplayFunc(disp);
      glutReshapeFunc(reshape);
      glutMainLoop();
    
      return 0;
    }
    

    レイキャストを実装してみる(2) レイと球の交差

    前回作成したレイと球を交差させて、その状態を可視化する。

    raycast.hpp

    #pragma once
    
    #include "Grid.hpp"
    
    #include <array>
    
    
    //////////////////////////////////////////////
    //////////////////////////////////////////////
    // 球オブジェクト
    class object_sphere {
      glm::vec3 _center;
      glm::vec3 _color;
      float _r;
    public:
      object_sphere(glm::vec3 center_, glm::vec3 color_, float radius_) :
        _center(center_), _color(color_), _r(radius_) {}
      object_sphere() {}
    
      bool intersect(glm::vec3* pos_, glm::vec3* color_, const std::array<glm::vec3, 2>& ray_)const;
    };
    
          
    //////////////////////////////////////////////
    //////////////////////////////////////////////
    // 画像として塗りつぶすピクセル
    struct hit_pixel_t {
      glm::vec3 _position; // 交点の座標
      glm::vec3 _color;  // 交点の色
      hit_pixel_t(const glm::vec3& position_, const glm::vec3& color_) :
        _position(position_), _color(color_) {}
    
    };
    
          
    // レイキャスト用のクラス
    class my_raycast {
      grid g[2];
      float _startZ;
      float _endZ;
      int _pxwidth;
      int _pxheight;
    public:
      my_raycast() {}
    
      int width()const { return _pxwidth; }
      int height()const { return _pxheight; }
    
      // レイの開始点となるグリッド、終点となるグリッドを作成する
      void set(const float startZ_, const float endZ_, const int pxwidth_, const int pxheight_);
    
      //グリッド取得
      const grid& get_grid(const size_t index)const {
        return g[index];
      }
    
      //グリッドから作成するレイの数を取得
      int ray_count() {
        return g[0].cellCount();
      }
    
      //グリッドから作成するレイを取得
      std::array<glm::vec3, 2> get_ray(const size_t index)const;
    
      //始点グリッド、終点グリッドの中間の位置を取得(表示用)
      float lookatZ()const {
        return (_startZ + _endZ) / 2.f;
      }
    
    
    
    
    
    
      //////////////////////////////////////////////
      //////////////////////////////////////////////
    
    private:
      object_sphere _obj;//球オブジェクト
      std::vector< hit_pixel_t > _hits;//レイキャストの結果
    public:
      void raycast();//レイキャスト
      std::vector< hit_pixel_t >& get_intersects() {return _hits;}
      void set_object(const object_sphere& obj_);
    };
    

    raycast.cpp

    レイキャストの部分はglm::intersectRaySphereを使う。

    #include "raycast.hpp"
    
    #include <glm/gtx/intersect.hpp>
    
    
    bool object_sphere::intersect(glm::vec3* pos_, glm::vec3* color_, const std::array<glm::vec3, 2>& ray_) const {
    
      glm::vec3 nray = glm::normalize(ray_[1] - ray_[0]);
    
      float distance;
    
      bool valid = glm::intersectRaySphere(ray_[0], nray, _center, _r * _r, distance);
    
      *pos_ = ray_[0] + nray * distance;
    
      *color_ = _color;
      return valid;
    }
    
          
    void my_raycast::set(const float startZ_, const float endZ_, const int pxwidth_, const int pxheight_) {
      _startZ = startZ_;
      _endZ = endZ_;
    
      _pxwidth = pxwidth_;
      _pxheight = pxheight_;
    
      glm::vec3 vecx(1, 0, 0);
      glm::vec3 vecy(0, 1, 0);
    
      g[0] = grid(
        vecx,
        vecy,
        glm::vec3(0, 0, _startZ),
        1.f, 1.f,
        pxwidth_, pxheight_
      );
      g[1] = grid(
        vecx,
        vecy,
        glm::vec3(0, 0, _endZ),
        2.f, 2.f,
        pxwidth_, pxheight_
      );
    
    }
    
    
    std::array<glm::vec3, 2> my_raycast::get_ray(const size_t index)const {
      return
        std::array<glm::vec3, 2>{
        g[0][index].center(),
          g[1][index].center()
      };
    
    }
    
    void my_raycast::set_object(const object_sphere& obj_) {
      _obj = obj_;
    }
    
    
    void my_raycast::raycast() {

    //結果の初期化
     float inf = std::numeric_limits<float>::infinity(); _hits.resize(_pxheight * _pxwidth, hit_pixel_t( glm::vec3(inf, inf, inf),//球とレイの交点を無効な値に設定 glm::vec3(0, 0, 0)//色を黒に ) ); for (size_t y = 0; y < _pxheight; y++) { for (size_t x = 0; x < _pxwidth; x++) { size_t index = y * _pxwidth + x; auto ray = get_ray(index);//レイ取得 glm::vec3 p; glm::vec3 c; if (_obj.intersect(&p,&c, ray) == true) {//球との交点を算出 _hits[index]._position = p;//交差していたらその座標を保存 _hits[index]._color = c; } } } }

    main.cpp

    #include <iostream>
    #include <array>
    
    #include<GL/freeglut.h>
    #include<gl/GL.h>
    
    #include "raycast.hpp"
    
    #include<glm/gtc/type_ptr.hpp>
    
    #include<glm/gtc/matrix_transform.hpp>
    
    my_raycast mydata;
    
    
    //! @brief グリッドを表示
    //! @param [in] g グリッドオブジェクト
    //! @param [in] dispcenter セルの中央を表示するか
    void drawGrid(const grid& g, const bool dispcenter) {
    
      glLineWidth(1);
      glColor3d(1, 1, 1);
      for (size_t i = 0; i < g.cellCount(); i++) {
        glBegin(GL_LINE_LOOP);
        glVertex3fv(glm::value_ptr(g.p0(i)));
        glVertex3fv(glm::value_ptr(g.p1(i)));
        glVertex3fv(glm::value_ptr(g.p2(i)));
        glVertex3fv(glm::value_ptr(g.p3(i)));
    
        glEnd();
      }
    
      if (dispcenter) {
        glPointSize(1);
        glColor3d(1, 1, 1);
        glBegin(GL_POINTS);
        for (size_t i = 0; i < g.cellCount(); i++) {
          glVertex3fv(
            glm::value_ptr(g[i].center()));
        }
        glEnd();
      }
    }
    
    
    
    void drawXYZ() {
      glLineWidth(3);
      glBegin(GL_LINES);
      glColor3f(1, 0, 0);
      glVertex3f(0, 0, 0);
      glVertex3f(1, 0, 0);
    
      glColor3f(0, 1, 0);
      glVertex3f(0, 0, 0);
      glVertex3f(0, 1, 0);
    
      glColor3f(0, 0, 1);
      glVertex3f(0, 0, 0);
      glVertex3f(0, 0, 1);
      glEnd();
      glLineWidth(1);
    }
    
    void drawRays() {
      glBegin(GL_LINES);
      for (size_t i = 0; i < mydata.ray_count(); i++) {
        auto ray = mydata.get_ray(i);
        glColor3f(1.0, 1.0, 1.0);
        glVertex3fv(glm::value_ptr(ray[0]));
        glColor3f(0.0, 0.0, 1.0);
        glVertex3fv(glm::value_ptr(ray[1]));
      }
      glEnd();
    }
    
    
    
    //ウィンドウの幅と高さ
    int width, height;
    
    //描画関数
    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);
    
      glMatrixMode(GL_PROJECTION);
      glLoadIdentity();
      glm::mat4 proj = glm::perspectiveFov(glm::radians(45.f), (float)width, (float)height, 0.1f, 50.f);
      glLoadMatrixf(glm::value_ptr(proj));
    
      glMatrixMode(GL_MODELVIEW);
      glLoadIdentity();
    
      //////////////////////////////////////////
      //////////////////////////////////////////
      // カメラの設定
      float z = mydata.lookatZ();
      glm::mat4 look = glm::lookAt(
        glm::vec3(3, 2, z ),// eye
        glm::vec3(0, 0, z ), // lookat
        glm::vec3(0,1, 0)   // up
      );
      glLoadMatrixf(glm::value_ptr(look));
      //////////////////////////////////////////
      // グリッドを表示
      drawGrid(mydata.get_grid(0), false);//from
      drawGrid(mydata.get_grid(1), false);//to
      //////////////////////////////////////////
      // 作成したレイを表示
      //drawRays();
      //////////////////////////////////////////
      // 始点から衝突した点までの線分を表示
    #if 0
      glLineWidth(1);
      glBegin(GL_LINES);
      for (size_t i = 0; i < mydata.get_intersects().size(); i++) {
        //for (size_t x = 0; x < mydata.get_intersects()[y].size(); x++) {
          glVertex3fv(
            glm::value_ptr(
              mydata.get_grid(0)[i].center()
            )
          );
          glVertex3fv(
            glm::value_ptr(
              mydata.get_intersects()[i]._position
            )
          );
        //}
      }
      glEnd();
    
    #endif
    
      /////////////////////////////////////////////
      // 三次元上にレイと球の交差点表示
      glPointSize(3);
      glBegin(GL_POINTS);
      for (size_t i = 0; i < mydata.get_intersects().size(); i++) {
    
        glColor3fv(
          glm::value_ptr(
            mydata.get_intersects()[i]._color
          )
        );
        glVertex3fv(
          glm::value_ptr(
            mydata.get_intersects()[i]._position
          )
        );
      }
      glEnd();
      glPointSize(1);
      drawXYZ();
    
    
      // グリッドの上にレイと球の交差点表示
      glColor3d(1, 1, 1);
      glBegin(GL_POINTS);
      for (size_t i = 0; i < mydata.get_intersects().size(); i++) {
        if (isinf(mydata.get_intersects()[i]._position.x) == false) {
          glColor3fv(
            glm::value_ptr(
              mydata.get_intersects()[i]._color
            )
          );
          glVertex3fv(
            glm::value_ptr(
              mydata.get_grid(0)[i].center()
            )
          );
        }
      }
      glEnd();
      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);
    
    
      mydata.set(
    0.f,//始点のZ座標
     3.f,//終点のZ座標
    100,//X方向の解像度
    100 //Y方向の解像度
    );
    /////////////////////////////////// mydata.set_object(
    object_sphere(
    glm::vec3(
    0.5, 0, 2),//球の中心座標
    glm::vec3(1, 0, 0),//球の
     0.5//球の半径
    )
    );
    mydata.raycast();//レイキャスト glutCreateWindow("sample"); glutDisplayFunc(disp); glutReshapeFunc(reshape); glutMainLoop(); return 0; }

    レイキャストを実装してみる(1) レイの生成

    自分でレイキャストを実装してみる。なおレイキャストは視点からレイを飛ばし、オブジェクトに衝突した時点の色でピクセルを塗る方法で、オブジェクトに衝突したらそこから反射したレイをさらに飛ばすを繰り返すのはレイトレーシングという。

    レイの生成

    レイの生成は真面目にやると数式ばかりになって初学者にとってはつまらないだけなので、グリッドを使って直感的な方法で実現してみる。

    1.Grid.hpp

    OpenGLでグリッドを描く

    #pragma once
    
    #include<glm/glm.hpp>
    #include<glm/gtc/type_ptr.hpp>
    
    #include<vector>
    
    // グリッド一つ分
    class cell {
      glm::vec3 _min;  //始点
      glm::vec3 _vecx; //方向1
      glm::vec3 _vecy; //方向2
    
    public:
      cell(glm::vec3 _min_, glm::vec3 _vec_x, glm::vec3 _vec_y) {
        _min = _min_;
        _vecx = _vec_x;
        _vecy = _vec_y;
      }
      const glm::vec3& cmin()const {
        return _min;
      }
      const glm::vec3& cvecx()const {
        return _vecx;
      }
      const glm::vec3& cvecy()const {
        return _vecy;
      }
    
      // セルの中心
      glm::vec3 center()const {
        return _min + _vecx / 2.f + _vecy / 2.f;
      }
    };
    
    
    class grid {
      std::vector<cell> _cells;
      int _xcount;
      int _ycount;
      float _xwidth;
      float _ywidth;
      glm::vec3 _center;
    
    public:
    
      float xwidth()const { return _xwidth; }
      float ywidth()const { return _ywidth; }
      const glm::vec3& center()const { return _center; }
    
      size_t cellCount()const {
        return _cells.size();
      }
      cell& operator[](const size_t index) {
        return _cells[index];
      }
      const cell& operator[](const size_t index)const {
        return _cells[index];
      }
      grid() {}
    
      grid(const grid& g) {
        _cells = g._cells;
        _xcount = g._xcount;
        _ycount = g._ycount;
        _xwidth = g._xwidth;
        _ywidth = g._ywidth;
        _center = g._center;
      }
      grid& operator=(const grid& g) {
        _cells = g._cells;
        _xcount = g._xcount;
        _ycount = g._ycount;
        _xwidth = g._xwidth;
        _ywidth = g._ywidth;
        _center = g._center;
      }
      grid& operator=(grid&& g) {
        _cells = std::move(g._cells);
        _xcount = g._xcount;
        _ycount = g._ycount;
        _xwidth = g._xwidth;
        _ywidth = g._ywidth;
        _center = g._center;
        return *this;
      }
    
      // 平面一つ分。xcount × ycountのcellからなる
      grid(
        const glm::vec3 vecX,
        const glm::vec3 vecY,
        const glm::vec3 center,
        const float width,
        const float height,
        const int xcount,
        const int ycount) {
    
        _xcount = xcount;
        _ycount = ycount;
        _xwidth = width;
        _ywidth = height;
    
        _center = center;
    
        glm::vec3 NVecX = glm::normalize(vecX);
        glm::vec3 NVecY = glm::normalize(vecY);
    
        ////////////////////
        _cells.clear();
    
        // セル一個の縦方向、横方向のベクトル。長さはセル一個分
        const glm::vec3 CellVX = NVecX * (_xwidth / xcount);
        const glm::vec3 CellVY = NVecY * (_ywidth / ycount);
    
        // 面の始点
        const glm::vec3 Start = _center - NVecX * _xwidth / 2.f - NVecY * _ywidth / 2.f;
    
        for (size_t y = 0; y < ycount; y++) {
          for (size_t x = 0; x < xcount; x++) {
    
            // 各セルの始点
            glm::vec3 from =
              Start +
              CellVX * (float)x + CellVY * (float)y;
    
            // セルを記録
            _cells.push_back(
              cell(
                from,
                CellVX,
                CellVY
              )
            );
    
          }
        }
    
      }
    
    
      /*
      p0        p3
      +---------+
      |         |
      |         |
      |         |
      |         |
      +---------+
      p1        p2
      */
      glm::vec3 p0(const size_t index)const {
        return _cells[index].cmin();
      }
      glm::vec3 p1(const size_t index)const {
    
        return
          _cells[index].cmin() +
          _cells[index].cvecx();
      }
      glm::vec3 p2(const size_t index) const {
        return
          _cells[index].cmin() +
          _cells[index].cvecx() +
          _cells[index].cvecy();
      }
      glm::vec3 p3(const size_t index) const {
        return
          _cells[index].cmin() +
          _cells[index].cvecy();
      }
    
    };
    

    2.my_raycast.hpp

    #pragma once
    
    #include "Grid.hpp"
    
    #include <array>
    
    // レイキャスト用のクラス
    class my_raycast {
      grid g[2];
      float _startZ;
      float _endZ;
      int _pxwidth;
      int _pxheight;
    public:
      my_raycast() {}
    
      int width()const { return _pxwidth; }
      int height()const { return _pxheight; }
    
      // レイの開始点となるグリッド、終点となるグリッドを作成する
      void set(const float startZ_, const float endZ_, const int pxwidth_, const int pxheight_);
    
      //グリッド取得
      const grid& get_grid(const size_t index)const {
        return g[index];
      }
    
      //グリッドから作成するレイの数を取得
      int ray_count() {
        return g[0].cellCount();
      }
    
      //グリッドから作成するレイを取得
      std::array<glm::vec3, 2> get_ray(const size_t index)const;
    
      //始点グリッド、終点グリッドの中間の位置を取得(表示用)
      float lookatZ()const {
        return (_startZ + _endZ) / 2.f;
      }
    
    };
    

    3.my_raycast.cpp

    #include "raycast.hpp"
    
    void my_raycast::set(const float startZ_, const float endZ_, const int pxwidth_, const int pxheight_) {
      _startZ = startZ_;
      _endZ = endZ_;
    
      _pxwidth = pxwidth_;
      _pxheight = pxheight_;
    
      glm::vec3 vecx(1, 0, 0);
      glm::vec3 vecy(0, 1, 0);
    
      g[0] = grid(
        vecx,
        vecy,
        glm::vec3(0, 0, _startZ),
        1.f, 1.f,
        pxwidth_, pxheight_
      );
      g[1] = grid(
        vecx,
        vecy,
        glm::vec3(0, 0, _endZ),
        2.f, 2.f,
        pxwidth_, pxheight_
      );
    
    }
    
    
    std::array<glm::vec3, 2> my_raycast::get_ray(const size_t index)const {
      return
        std::array<glm::vec3, 2>{
        g[0][index].center(),
          g[1][index].center()
      };
    
    }
    

    表示

    #include <iostream>
    #include <array>
    
    #include<GL/freeglut.h>
    #include<gl/GL.h>
    
    #include "raycast.hpp"
    
    #include<glm/gtc/type_ptr.hpp>
    
    #include<glm/gtc/matrix_transform.hpp>
    
    //! @brief グリッドの可視化
    //! @param [in] g グリッドオブジェクト
    //! @param [in] dispcenter セルの中央を表示するか
    void drawGrid(const grid& g, const bool dispcenter) {
    
      glLineWidth(1);
      glColor3d(1, 1, 1);
      for (size_t i = 0; i < g.cellCount(); i++) {
        glBegin(GL_LINE_LOOP);
        glVertex3fv(glm::value_ptr(g.p0(i)));
        glVertex3fv(glm::value_ptr(g.p1(i)));
        glVertex3fv(glm::value_ptr(g.p2(i)));
        glVertex3fv(glm::value_ptr(g.p3(i)));
    
        glEnd();
      }
    
      if (dispcenter) {
        glPointSize(1);
        glColor3d(1, 1, 1);
        glBegin(GL_POINTS);
        for (size_t i = 0; i < g.cellCount(); i++) {
          glVertex3fv(
            glm::value_ptr(g[i].center()));
        }
        glEnd();
      }
    }
    
    
    
    void drawXYZ() {
      glLineWidth(3);
      glBegin(GL_LINES);
      glColor3f(1, 0, 0);
      glVertex3f(0, 0, 0);
      glVertex3f(1, 0, 0);
    
      glColor3f(0, 1, 0);
      glVertex3f(0, 0, 0);
      glVertex3f(0, 1, 0);
    
      glColor3f(0, 0, 1);
      glVertex3f(0, 0, 0);
      glVertex3f(0, 0, 1);
      glEnd();
      glLineWidth(1);
    }
    
    //レイキャストオブジェクトの定義 my_raycast mydata; //ウィンドウの幅と高さ int width, height; //描画関数 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); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glm::mat4 proj = glm::perspectiveFov(glm::radians(45.f), (float)width, (float)height, 0.1f, 50.f); glLoadMatrixf(glm::value_ptr(proj)); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); ////////////////////////////////////////// ////////////////////////////////////////// // カメラの設定 レイとグリッドの状態を可視化するための表示用 float z = mydata.lookatZ(); glm::mat4 look = glm::lookAt( glm::vec3(3, 2, z-2 ),// eye glm::vec3(0, 0, z ), // lookat glm::vec3(0,1, 0) // up ); glLoadMatrixf(glm::value_ptr(look)); ////////////////////////////////////////// // グリッドを表示 OpenGLでグリッドを可視化 drawGrid(mydata.get_grid(0), false);//from drawGrid(mydata.get_grid(1), false);//to ////////////////////////////////////////// // 作成したレイを表示 OpenGLでレイを可視化
    // 第0グリッドの各セルの中央から、台グリッドの各セルの中央へ線分を引く
      glBegin(GL_LINES); for (size_t i = 0; i < mydata.ray_count(); i++) { auto ray = mydata.get_ray(i); glColor3f(1.0, 1.0, 1.0); glVertex3fv(glm::value_ptr(ray[0])); glColor3f(0.0, 0.0, 1.0); glVertex3fv(glm::value_ptr(ray[1])); } glEnd(); drawXYZ(); 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); //レイキャスト用クラスにレイの始点・終点を設定 mydata.set(
    0.f,//始点のZ座標
     3.f,//終点のZ座標
     
    10, //X方向の解像度
     
    10 //Y方向の解像度
    ); glutCreateWindow("sample"); glutDisplayFunc(disp); glutReshapeFunc(reshape); glutMainLoop(); return 0; }

    Unreal Engine 5のBlankにマネキン(Mannequin)を導入する

    Blankでプロジェクトを作るとマネキンがないので入れたい場合。

    マネキンの入れ方

    1.コンテンツブラウザ → 機能またはコンテンツパックを追加

    2.プロジェクトにコンテンツを追加 → サードパーソン を選択しプロジェクトに追加

    マネキンが入る。

    デフォルトで歩行の設定が入っている

    Blankのインプットにもともと軸マッピングがされており、マネキンにAdd Movement Input等が設定されているため、ワールドセッティング→Game Mode→Default Pawn Classにマネキンを設定するだけで歩くようになる。

    Unreal Engine 5で固定カメラ設置して動く自キャラを眺める

    Blankで一切ブループリントがないところから、自キャラをADSWで動かしたり、それを俯瞰したりするカメラを設定するのに必要な手順の基本を確認する。

    まずBlankで作ったときに初期配置されているテーブルや椅子を全て削除する。

    コンテンツブラウザを右クリックしてブループリントクラスを追加。

    Character , Player Controller ,  Game Mode Base を追加し、名前をそれぞれMyCharacter , MyController , MyGameModeへ変更する。

    再びブループリントを追加。今度は全てのクラスからCameraActorを追加し、名前をMyCameraへ変更。

    ワールドセッティングでGameModeにMyGameModeを設定し、Default Pawn Class→MyCharacter , Player Controller Class → MyController を設定する。

    MyCameraを画面内にドラッグして設置し、舞台が見える位置に配置する。

    レベルブループリントを開き、視点がMyCameraからになるように設定する。

    なおGet Player Controllerは複数候補があるのだが、Player Index [0] になっているものでないとコンパイルが通らない。

    プロジェクト設定→インプット→軸マッピングから、キーを押したときの移動量を設定する。

    下図では[W]を押したときに+1.0移動、[S]を押したときに-1.0移動する。

    今回は簡略化のため前進・後退で一般的に使われるW,Sだけを設定する。大抵は左右移動も使うのでA,Dも追加することになる。

    この設定名をMyMappingMoveForwardとしておく。

    自キャラのモデルを用意するのが面倒なので、最初から用意されているConeを自キャラに設定する。

    MyCharacterをダブルクリックして開き、ビューポートへコーンをドラッグする。

    W,Sを押したときにどの方向へ動くかを設定する。

    MyCharacterのブループリントを開き、Input AxisのMyMappingMoveForwardを追加。

    Axis Valueには、Wが押されたときは1.0、Sが押されたときは-1.0が来るように上で設定したはずなので、その値にWorld Directionの(1,0,0)をかけることで前進・後退をさせる。

    コンパイルして実行してみるとキャラを動かせる。

    psycopg2でPythonからPostgreSQLを操作

    Pythonから使おうとしている。当然だが pg_ctl start しておかなければいけない。

    セットアップ

    conda install psycopg2

    サンプルコード

    import psycopg2
    
    dsn = "user=postgres password=password"
    
    conn = psycopg2.connect(dsn)
    cur = conn.cursor()
    
    cur.execute('SELECT * FROM pg_tables')
    
    for row in cur:
        print(row)
    
    cur.close()
    conn.close()
    
    > python test.py
    ('pg_catalog', 'pg_statistic', 'postgres', None, True, False, False, False)
    ('pg_catalog', 'pg_type', 'postgres', None, True, False, False, False)
    ('pg_catalog', 'pg_foreign_table', 'postgres', None, True, False, False, False)
    ('pg_catalog', 'pg_authid', 'postgres', 'pg_global', True, False, False, False)
    ('pg_catalog', 'pg_statistic_ext_data', 'postgres', None, True, False, False, False)
    ('pg_catalog', 'pg_user_mapping', 'postgres', None, True, False, False, False)
    ('pg_catalog', 'pg_subscription', 'postgres', 'pg_global', True, False, False, False)
    ('pg_catalog', 'pg_attribute', 'postgres', None, True, False, False, False)
    ('pg_catalog', 'pg_proc', 'postgres', None, True, False, False, False)
    ('pg_catalog', 'pg_class', 'postgres', None, True, False, False, False)

    PostgreSQLをC言語から呼び出す(2) select文

    #include <iostream>
    
    #include <libpq-fe.h>
    
    #pragma comment(lib,"libpq.lib")
    
    
    int main()
    {
    
      // データベースへ接続する
      // ユーザー名:postgres
      // パスワード:password
      PGconn* conn;
      conn = PQconnectdb("user=postgres password=password");
      if (PQstatus(conn) != CONNECTION_OK)
      {
        printf("%s", PQerrorMessage(conn));
        exit(1);
      }
    
      PGresult* pgres;
      try {
     
    
          
        pgres = PQexec(conn, "select schemaname, tablename, tableowner  from pg_tables");
    
    
        if (PQresultStatus(pgres) != PGRES_TUPLES_OK) {
          throw -1;
        }
    
        int row = PQntuples(pgres); // 行数取得
        int col = PQnfields(pgres); // 列数取得
    
        // 列名ループ
        for (int c = 0; c < col; c++) {
    
          //列名取得
          char* name = PQfname(pgres, c);
          printf("%-25s | ", name);
    
        }
        printf("\n-----------------------------------------------------------------------------------\n");
        // 行番号ループ
        for (int r = 0; r < row; r++) {
          // 列ループ
          for (int c = 0; c < col; c++) {
    
            // 値取得
            char* val = PQgetvalue(pgres, r, c);
            printf("%-25s | ", val);
          }
          puts("");
        }
    
    
        PQclear(pgres);
    
    
          
      }
      catch (...) {
        printf("%s", PQerrorMessage(conn));
        PQclear(pgres);
      }
    
      PQfinish(conn);
    
    
    }
    
    

    PostgreSQLをC言語から呼び出す(1)

    pg_ctl start しておく必要がある。

    includeディレクトリ: C:\PostgreSQL\include

    ライブラリディレクトリ:C:\PostgreSQL\lib

    必要なDLLは:C:\PostgreSQL\bin

    ・libcrypto-3-x64.dll

    ・libiconv-2.dll

    ・libintl-9.dll

    ・libpq.dll

    ・libssl-3-x64.dll

    ・libwinpthread-1.dll

    #include <iostream>
    
    #include <libpq-fe.h>
    
    #pragma comment(lib,"libpq.lib")
    
    int main()
    {
    
    // データベースへ接続する
    // ユーザー名:postgres // パスワード:password PGconn* conn; conn = PQconnectdb("user=postgres password=password"); if (PQstatus(conn) != CONNECTION_OK) { printf("%s", PQerrorMessage(conn)); exit(1); } PGresult* pgres; #if 1 // ユーザー名 cuser , cpassword でユーザー作成 pgres = PQexec(conn, "CREATE USER cuser WITH PASSWORD 'cpassword'"); if (PQresultStatus(pgres) != PGRES_COMMAND_OK) { // 確認方法:postgres=# SELECT usename FROM pg_user; printf("%s", PQerrorMessage(conn));
     PQclear(pgres); exit(1); }
    PQclear(pgres);  
    // データベース名 cdatabase , 使用者 cuser でユーザー作成 pgres = PQexec(conn, "CREATE DATABASE cdatabase OWNER cuser"); if (PQresultStatus(pgres) != PGRES_COMMAND_OK) { // 確認方法:\l printf("%s", PQerrorMessage(conn));
     PQclear(pgres);
    exit(1); }
     PQclear(pgres); #else // ユーザやデータベースを削除する場合:
    pgres = PQexec(conn, "DROP DATABASE cdatabase"); if (PQresultStatus(pgres) != PGRES_COMMAND_OK) { printf("%s", PQerrorMessage(conn));
     PQclear(pgres); exit(1); }
     PQclear(pgres);


    pgres = PQexec(conn, "DROP USER cuser"); if (PQresultStatus(pgres) != PGRES_COMMAND_OK) { printf("%s", PQerrorMessage(conn));
     PQclear(pgres); exit(1); }  PQclear(pgres);
    #endif

    PQfinish(conn);
    }

    PostgreSQLでサーバを起動してユーザ・データベース・テーブルを作るまで

    データベースを使いたくなったのでBSD LicenseのPostgreSQLを使ってみる。

    インストール

    以下のサイトを参考にzipからインストールする。(これ以上うまくまとめられないのでリンク先に一任)。

    https://www.flyenginer.com/low/low_db/zip%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%A7postgresql12%E3%82%92%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB%E3%81%99%E3%82%8B.html

    なお、環境変数PGDATAを設定しないと、pg_ctl startやpg_clt stopの度に -D My-DataDirectory の指定をしなければならず面倒なことになるので設定したほうがいい。

    サーバー起動・停止

    サーバー起動は以下:

    pg_ctl start -l C:\PostgreSQL\My-LogDirectory\postgresql.log

    サーバー停止は以下:

    pg_ctl stop

    サーバーを停止せずにプロンプトを切ってしまった場合など、pg_ctl startが聞かなくなることがある。そういう時はrestartする。

    restartは以下:

    pg_ctl -D "C:\PostgreSQL\My-DataDirectory" restart

    上記、My-DataDirectoryは環境変数PGDATAに指定したものと同じ。

     

    データベースを使えるようにするまで

    postgresユーザで接続

    >psql -U postgres

    psqlコマンドを使って「postgres」ユーザーで接続する。

    なお接続を切るには

    \q

     

    データベースのユーザをパスワード付きで作成

    postgres=# CREATE USER myuser WITH PASSWORD 'secret';

    ユーザが作成できたかどうか確認するためにユーザ一覧を表示するには

    postgres=# SELECT usename FROM pg_user;

    なおユーザー削除は

    postgres=# DROP USER myuser;

    データベースをユーザを指定して作成

    postgres=# CREATE DATABASE mydatabase OWNER myuser;

    なおパスワードはユーザーに指定するもので、データベースには指定しない(戸惑った)

    データベースが作成できたかどうか確認するためデータベース一覧を表示するには

    postgres=# \l

    なおデータベースを削除するには

    postgres=# DROP DATABASE mydatabase;

    データベースのテーブルへアクセス権を付与

    まずpostgresユーザーでの接続を切り、

    postgres=# \q

    ユーザー「myuser」でデータベース「mydatabase」へ接続

     >psql -U myuser -d mydatabase

    GRANT で「ALL PRIVILEGES」をすべてのテーブルへ付加

    mydatabase=> GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO myuser;

    データベースへテーブルを作成

    mydatabase=>CREATE TABLE mytable(
    ID integer,
    TITLE text,
    AUTHOR text
    );

    使用例

    mydatabase=> select * from mytable;