link : http://www.opengl-tutorial.org/kr/intermediate-tutorials/billboards-particles/particles-instancing/
Wow 마지막 튜토리얼이다. 꾸준히 달려온 나에게 칭찬을 보낸다.
하지만 튜토리얼을 진행해오면서 이해가 덜된 부분이 많기 때문에 복습을 다시 할 것이다.
복습 후에는 가볍게 게임을 하나 만들어봐야지! 화이팅!
Particles / Instancing
particle은 3D billboards와 매우 유사하다. 두 가지 차이점이 있다 :
1) 많은 것들이 합쳐져있고, 움직인다
2) 나타나고 죽고, 그들은 반투명하다
이 두 가지 차이는 모두 문제가 있다. 이 튜토리얼에서는 문제를 해결할 수 있는 방법을 제시한다.
Particles, lots of them !
많은 입자를 그리는 첫 번째 아이디어는 이전 튜토리얼의 코드를 사용하고,
각 입자에 대해 glDrawArrays를 한 번 호출하는 것이다.
반짝이는 GTX의 512+ 멀티프로세서는 모두 하나의 쿼드를 그리기 위해 사용된다.
(분명히 하나만 사용되므로 99%의 효율 손실이 발생함)
그런 다음 두 번째 광고판을 그릴 것이다.
분명히, 우리는 동시에 모든 입자를 그리는 방법이 필요하다.
이를 수행할 수 있는 많은 방법이 있다. 여기에 세가지가 있다 :
1) 모든 입자가 들어있는 단일 VBO를 생성해라. 쉽고 효과적이며 모든 플랫폼에서 작동한다.
2) 기하학 쉐이더를 사용해라. 이 튜토리얼의 범위를 벗어나서 컴퓨터의 50%가 이 기능을 지원하지 않기 때문이다.
3) 인스턴싱을 사용해라. 모든 컴퓨터에서 사용할 수 있는 것은 아니지만, 대다수의 컴퓨터에서 가능하다.
이 튜토리얼에서는 퍼포먼스와 가용성의 균형이 잘 잡혀 있기 때문에 세 번째 옵션을 사용한다.
이 옵션을 사용하면 첫 번째 메소드에 대한 지원을 쉽게 추가할 수 있다.
Instancing
"instancing"은 우리가 기본 메시를 가지고 있지만, 이 쿼드에는 많은 인스턴스가 있다는 것이다.
기술적으로 이것은 여러 버퍼를 통해 수행된다 :
1) 그들 중 일부는 기본 메쉬를 설명한다.
2) 그 중 일부는 기본 메쉬의 각 인스턴스의 특수성을 설명한다.
각 버퍼에 넣을 항목에는 많은 옵션이 있다. 단순한 경우에 우리는 :
1) 메시의 꼭지점을 위한 하나의 버퍼. index 버퍼가 없으므로 이것은 2개의 삼각형을 만들어 1쿼드가 되는 6 vec3이다.
2) 입자 중심을 위한 하나의 버퍼.
3) particle의 색상을 위한 하나의 버퍼.
이들은 매우 표준적인 버퍼이다. 그들은 다음과 같은 방법으로 만들어진다.
// The VBO containing the 4 vertices of the particles.
// Thanks to instancing, they will be shared by all particles.
static const GLfloat g_vertex_buffer_data[] = {
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
-0.5f, 0.5f, 0.0f,
0.5f, 0.5f, 0.0f,
};
GLuint billboard_vertex_buffer;
glGenBuffers(1, &billboard_vertex_buffer);
glBindBuffer(GL_ARRAY_BUFFER, billboard_vertex_buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
// The VBO containing the positions and sizes of the particles
GLuint particles_position_buffer;
glGenBuffers(1, &particles_position_buffer);
glBindBuffer(GL_ARRAY_BUFFER, particles_position_buffer);
// Initialize with empty (NULL) buffer : it will be updated later, each frame.
glBufferData(GL_ARRAY_BUFFER, MaxParticles * 4 * sizeof(GLfloat), NULL, GL_STREAM_DRAW);
// The VBO containing the colors of the particles
GLuint particles_color_buffer;
glGenBuffers(1, &particles_color_buffer);
glBindBuffer(GL_ARRAY_BUFFER, particles_color_buffer);
// Initialize with empty (NULL) buffer : it will be updated later, each frame.
glBufferData(GL_ARRAY_BUFFER, MaxParticles * 4 * sizeof(GLubyte), NULL, GL_STREAM_DRAW);
, which is as usual. They are updated this way :
// Update the buffers that OpenGL uses for rendering.
// There are much more sophisticated means to stream data from the CPU to the GPU,
// but this is outside the scope of this tutorial.
// http://www.opengl.org/wiki/Buffer_Object_Streaming
glBindBuffer(GL_ARRAY_BUFFER, particles_position_buffer);
glBufferData(GL_ARRAY_BUFFER, MaxParticles * 4 * sizeof(GLfloat), NULL, GL_STREAM_DRAW); // Buffer orphaning, a common way to improve streaming perf. See above link for details.
glBufferSubData(GL_ARRAY_BUFFER, 0, ParticlesCount * sizeof(GLfloat) * 4, g_particule_position_size_data);
glBindBuffer(GL_ARRAY_BUFFER, particles_color_buffer);
glBufferData(GL_ARRAY_BUFFER, MaxParticles * 4 * sizeof(GLubyte), NULL, GL_STREAM_DRAW); // Buffer orphaning, a common way to improve streaming perf. See above link for details.
glBufferSubData(GL_ARRAY_BUFFER, 0, ParticlesCount * sizeof(GLubyte) * 4, g_particule_color_data);
, which is as usual. Before render, they are bound this way :
// 1rst attribute buffer : vertices
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, billboard_vertex_buffer);
glVertexAttribPointer(
0, // attribute. No particular reason for 0, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// 2nd attribute buffer : positions of particles' centers
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, particles_position_buffer);
glVertexAttribPointer(
1, // attribute. No particular reason for 1, but must match the layout in the shader.
4, // size : x + y + z + size => 4
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// 3rd attribute buffer : particles' colors
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, particles_color_buffer);
glVertexAttribPointer(
2, // attribute. No particular reason for 1, but must match the layout in the shader.
4, // size : r + g + b + a => 4
GL_UNSIGNED_BYTE, // type
GL_TRUE, // normalized? *** YES, this means that the unsigned char[4] will be accessible with a vec4 (floats) in the shader ***
0, // stride
(void*)0 // array buffer offset
);
그것은 평소와 같고, 렌더링할 때 차이가 생긴다. glDrawArrays 대신 glDrawArrays를 N번 호출하는 것과 동일한
glDrawArraysInstanced / glDrawElementsInstanced를 사용한다.
glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, ParticlesCount);
여기에는 무언가가 빠져있다. OpenGL에게 기본 메시용 버퍼와 다른 인스턴스용 버퍼를 말하지 않았다.
이 작업은 glVertexAttribDivisor를 사용해 수행된다. 전체 주석 처리된 코드는 다음과 같다.
// These functions are specific to glDrawArrays*Instanced*.
// The first parameter is the attribute buffer we're talking about.
// The second parameter is the "rate at which generic vertex attributes advance when rendering multiple instances"
// http://www.opengl.org/sdk/docs/man/xhtml/glVertexAttribDivisor.xml
glVertexAttribDivisor(0, 0); // particles vertices : always reuse the same 4 vertices -> 0
glVertexAttribDivisor(1, 1); // positions : one per quad (its center) -> 1
glVertexAttribDivisor(2, 1); // color : one per quad -> 1
// Draw the particules !
// This draws many times a small triangle_strip (which looks like a quad).
// This is equivalent to :
// for(i in ParticlesCount) : glDrawArrays(GL_TRIANGLE_STRIP, 0, 4),
// but faster.
glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, ParticlesCount);
AttribDivisor로 정수를 전달할 수 있으므로 인스턴스화는 매우 다양하다.
예를 들어, glVertexAttribDivisor (2,10)를 사용하면 10개의 후속 인스턴스가 같은 색상을 갖게 된다.
What's the point ?
요점은 이제 우리는 거대한 메시가 아닌 각 프레임(the center of particles)의 작은ㅇ 버퍼를 업데이트해야한다는 것이다.
이것은 x4 대역폭 이득이다.
Life and death
장면의 대부분 다른 물체와는 달리, particle은 매우 높은 속도로 죽고 태어난다. 우리는 새로운 particle을 얻고 버리는
아주 빠른 방법이 필요하다. 이것은 "new Particle()"보다 낫다.
Creating new particles
For this, we will have a big particles container :
// CPU representation of a particle
struct Particle{
glm::vec3 pos, speed;
unsigned char r,g,b,a; // Color
float size, angle, weight;
float life; // Remaining life of the particle. if < 0 : dead and unused.
};
const int MaxParticles = 100000;
Particle ParticlesContainer[MaxParticles];
이제 우리는 새로운 것을 창조할 방법이 필요하다. 이 함수는 ParticlesContainer에서 선형으로 검색한다.
마지막 알려진 위치에서 시작한다는 점만 제외하면 끔찍한 생각이다. 따라서 이 함수는 일반적으로 즉시 반환된다.
int LastUsedParticle = 0;
// Finds a Particle in ParticlesContainer which isn't used yet.
// (i.e. life < 0);
int FindUnusedParticle(){
for(int i=LastUsedParticle; i<MaxParticles; i++){
if (ParticlesContainer[i].life < 0){
LastUsedParticle = i;
return i;
}
}
for(int i=0; i<LastUsedParticle; i++){
if (ParticlesContainer[i].life < 0){
LastUsedParticle = i;
return i;
}
}
return 0; // All particles are taken, override the first one
}
"life", "color", "speed" 및 "position" 값을 ParticlesContainer [particleIndex]에 채울 수 있습니다. 자세한 내용은 코드를 참조해라.
그러나 여기에서는 거의 모든 것을 할 수 있습니다. 유일한 재미있는 점은 각 프레임을 생성하기 위해 얼마나 많은 입자가
있어야 하는가이다. 이것은 대개 응용 프로그램에 따라 다르기 때문에 초당 10000개의 새 입자를 가정해보자.
int newparticles = (int)(deltaTime*10000.0);
except that you should probably clamp this to a fixed number :
// Generate 10 new particule each millisecond,
// but limit this to 16 ms (60 fps), or if you have 1 long frame (1sec),
// newparticles will be huge and the next frame even longer.
int newparticles = (int)(deltaTime*10000.0);
if (newparticles > (int)(0.016f*10000.0))
newparticles = (int)(0.016f*10000.0);
The main simulation loop
ParticlesContainer에는 활성 particle과 "dead" particle 모두 들어있지만, GPU로 보내는 버퍼에는 살아있는 입자만 있어야한다.
따라서 우리는 각 입자에 대해 반복해 그것이 살아있는지, 죽어있는지, 모든 것이 올바르면 중력을 추가하고 마지막으로
GPU 전용 버퍼에 복사한다.
// Simulate all particles
int ParticlesCount = 0;
for(int i=0; i<MaxParticles; i++){
Particle& p = ParticlesContainer[i]; // shortcut
if(p.life > 0.0f){
// Decrease life
p.life -= delta;
if (p.life > 0.0f){
// Simulate simple physics : gravity only, no collisions
p.speed += glm::vec3(0.0f,-9.81f, 0.0f) * (float)delta * 0.5f;
p.pos += p.speed * (float)delta;
p.cameradistance = glm::length2( p.pos - CameraPosition );
//ParticlesContainer[i].pos += glm::vec3(0.0f,10.0f, 0.0f) * (float)delta;
// Fill the GPU buffer
g_particule_position_size_data[4*ParticlesCount+0] = p.pos.x;
g_particule_position_size_data[4*ParticlesCount+1] = p.pos.y;
g_particule_position_size_data[4*ParticlesCount+2] = p.pos.z;
g_particule_position_size_data[4*ParticlesCount+3] = p.size;
g_particule_color_data[4*ParticlesCount+0] = p.r;
g_particule_color_data[4*ParticlesCount+1] = p.g;
g_particule_color_data[4*ParticlesCount+2] = p.b;
g_particule_color_data[4*ParticlesCount+3] = p.a;
}else{
// Particles that just died will be put at the end of the buffer in SortParticles();
p.cameradistance = -1.0f;
}
ParticlesCount++;
}
}
이것이 얻은 것이다. 하지만 문제가 있다.
Sorting
튜토리얼 10에서 설명했듯이 블렌딩이 올바르도록 반투명 개겣를 뒤에서 앞으로 정렬해야한다.
void SortParticles(){
std::sort(&ParticlesContainer[0], &ParticlesContainer[MaxParticles]);
}
이제는 std::sort에는 컨테이너에 있는 다른 입자 앞이라 뒤에 입자가 있어야하는지 여부를 알 수 있는 함수가 필요하다.
이것은 Particle::operator<:로 할 수 있다.
// CPU representation of a particle
struct Particle{
...
bool operator<(Particle& that){
// Sort in reverse order : far particles drawn first.
return this->cameradistance > that.cameradistance;
}
};
그러면 ParticleContainer가 정렬되고 파티클이 올바르게 표시된다.
Going further
Animated particles
텍스처 아트라스로 입자의 텍스처에 애니메이션을 적용할 수 있다. 각 파티클의 age와 position을 함께 보내고,
쉐이더에서 2D font 튜토리얼과 같이 UV를 계산한다. 텍스처 atlas는 다음과 같이 보인다.
Handling several particle systems
둘 이상의 파티클 시스템이 필요한 경우 두 가지 옵션이 있다. 하나의 ParticleContainer를 사용하거나 시스템 당 하나를 사용한다.
모든 particle에 대해 하나의 컨테이너가 있다면 완벽하게 정렬할 수 있다. 가장 큰 단점은 모든 입자에 대해 동일한 질감을
사용해야한다는 점이다. 이는 큰 문제이다. 이것은 texture atlas를 사용해 해결할 수 있지만, 편집하고 사용하는 것은 쉽지 않다.
반면에 particle system당 하나의 컨테이너가 있는 경우 particle은 이 컨테이너 내부에서만 정렬된다.
두 개의 입자 시스템이 겹치면 인공물이 나타난다. 응용 프로그램에 따라 문제가 되지 않을 수도 있다.
물론, (작고 다루기 쉬운) atlas가 있는 여러가지 입자 시스템이 있는 일종의 하이브리드 시스템을 사용할수도 있다.
Smooth particles
조만간 common artifact를 볼 수 있을 것이다 : particle이 일부 geometry와 교차할 때 한계가 매우 눈에 띄고 추악해 질 것이다.
이것을 해결하는 일반적인 기법은 현재 그려진 조각이 Z-Buffer 근처에 있는지 테스트하는 것이다.
만약 그렇다면 조각이 사라진다.
그러나 "normal" Z-Buffer로는 불가능한 Z-Buffer를 샘플링해야한다. 렌더링 대상에서 장면을 렌더링해야한다.
또는, glBlitFramebuffer를 사용해 Z 버퍼를 한 프레임 버퍼에서 다른 버퍼로 복사할 수 있다.
Improving fillrate
현대 GPU에서 가장 제한적인 요소 중 하나는 채우기 속도이다 : 16.6ms에 쓸 수 있는 조각(pixel)의 양은 60FPS를 얻을 수 있다.
이것은 문제이다. 왜냐하면 입자가 일반적으로 많은 양의 채우기를 필요로 하기 때문이다.
매번 다른 입자로 동일한 조각을 10번 다시 그릴 수 있기 때문이다. 당신이 그렇게 하지 않으면 인공물을 얻게될 수도 있다.
쓰여진 모든 fragments 중에서 많은 것은 쓸모가 없다 :
1) 이것들은 국경(border)에 있다.
2) particle texture는 종종 가장자리에서 완전히 투명하지만 입자의 메시가 여전히 그릴 것이며,
3) 이전과 완전히 같은 값으로 색상 버퍼를 업데이트한다.
이 작은 유틸리티는 텍스처에 꼭 맞는 메시(glDrawArraysInstanced()로 그릴 메시)를 계산한다.
후... 다했다! particle이 생각보다 매우 예쁘게 나왔다. 유니티에서는 공부할 때 실험만 해보고 실제 게임에는 써보지 않았었는데
이렇게 직접 코딩으로 만들어보니 신기하고, 더 예뻐보였다.
1) Particle.fragmentshader
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #version 330 core // 정점 쉐이더로부터 보간된 값 in vec2 UV; in vec4 particlecolor; // Ouput data out vec4 color; uniform sampler2D myTextureSampler; void main(){ // Output color = color of the texture at the specified UV color = texture( myTextureSampler, UV ) * particlecolor; } | cs |
2) Particle.vertexshader
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #version 330 core // Input vertex data, different for all executions of this shader. layout(location = 0) in vec3 squareVertices; layout(location = 1) in vec4 xyzs; // Position of the center of the particule and size of the square layout(location = 2) in vec4 color; // Position of the center of the particule and size of the square // Output data ; will be interpolated for each fragment. out vec2 UV; out vec4 particlecolor; // Values that stay constant for the whole mesh. uniform vec3 CameraRight_worldspace; uniform vec3 CameraUp_worldspace; uniform mat4 VP; // Model-View-Projection matrix, but without the Model (the position is in BillboardPos; the orientation depends on the camera) void main() { float particleSize = xyzs.w; // because we encoded it this way. vec3 particleCenter_wordspace = xyzs.xyz; vec3 vertexPosition_worldspace = particleCenter_wordspace + CameraRight_worldspace * squareVertices.x * particleSize + CameraUp_worldspace * squareVertices.y * particleSize; // Output position of the vertex gl_Position = VP * vec4(vertexPosition_worldspace, 1.0f); // UV of the vertex. No special space for this one. UV = squareVertices.xy + vec2(0.5, 0.5); particlecolor = color; } | cs |
3) source.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 | #include <stdio.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <algorithm> #include <map> #include <GL/glew.h> #include <glfw3.h> #include <GL/glew.h> GLFWwindow* window; //로테이션 #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/quaternion.hpp> #include <glm/gtx/quaternion.hpp> #include <glm/gtx/euler_angles.hpp> #include <glm/gtx/norm.hpp> #include <glm/gtc/quaternion.hpp> #include <glm/gtx/quaternion.hpp> #include <glm/gtx/euler_angles.hpp> #include <glm/gtx/norm.hpp> #include <AntTweakBar.h> #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> using namespace glm; #define FOURCC_DXT1 0x31545844 // Equivalent to "DXT1" in ASCII #define FOURCC_DXT3 0x33545844 // Equivalent to "DXT3" in ASCII #define FOURCC_DXT5 0x35545844 // Equivalent to "DXT5" in ASCII #define DRAW_CUBE GLuint LoadShaders(const char *, const char *); GLuint loadBMP_custom(const char *); GLuint loadDDS(const char *); bool loadOBJ( const char *, std::vector<glm::vec3> &, std::vector<glm::vec2> &, std::vector<glm::vec3> &); void indexVBO( std::vector<glm::vec3> &, std::vector<glm::vec2> &, std::vector<glm::vec3> &, std::vector<unsigned short> &, std::vector<glm::vec3> &, std::vector<glm::vec2> &, std::vector<glm::vec3> & ); void indexVBO_TBN( std::vector<glm::vec3> &, std::vector<glm::vec2> &, std::vector<glm::vec3> &, std::vector<glm::vec3> &, std::vector<glm::vec3> &, std::vector<unsigned short> &, std::vector<glm::vec3> &, std::vector<glm::vec2> &, std::vector<glm::vec3> &, std::vector<glm::vec3> &, std::vector<glm::vec3> & ); //mouse-keyboard input void computeMatricesFromInputs(); glm::mat4 getViewMatrix(); glm::mat4 getProjectionMatrix(); glm::mat4 ViewMatrix; glm::mat4 ProjectionMatrix; glm::mat4 getViewMatrix() { return ViewMatrix; } glm::mat4 getProjectionMatrix() { return ProjectionMatrix; } struct PackedVertex { glm::vec3 position; glm::vec2 uv; glm::vec3 normal; bool operator<(const PackedVertex that) const { return memcmp((void*)this, (void*)&that, sizeof(PackedVertex)) > 0; }; }; bool is_near(float v1, float v2) { return fabs(v1 - v2) < 0.01f; } bool getSimilarVertexIndex_fast( PackedVertex & packed, std::map<PackedVertex, unsigned short> & VertexToOutIndex, unsigned short & result ) { std::map<PackedVertex, unsigned short>::iterator it = VertexToOutIndex.find(packed); if (it == VertexToOutIndex.end()) { return false; } else { result = it->second; return true; } } bool getSimilarVertexIndex( glm::vec3 & in_vertex, glm::vec2 & in_uv, glm::vec3 & in_normal, std::vector<glm::vec3> & out_vertices, std::vector<glm::vec2> & out_uvs, std::vector<glm::vec3> & out_normals, unsigned short & result ) { // Lame linear search for (unsigned int i = 0; i < out_vertices.size(); i++) { if ( is_near(in_vertex.x, out_vertices[i].x) && is_near(in_vertex.y, out_vertices[i].y) && is_near(in_vertex.z, out_vertices[i].z) && is_near(in_uv.x, out_uvs[i].x) && is_near(in_uv.y, out_uvs[i].y) && is_near(in_normal.x, out_normals[i].x) && is_near(in_normal.y, out_normals[i].y) && is_near(in_normal.z, out_normals[i].z) ) { result = i; return true; } } // No other vertex could be used instead. // Looks like we'll have to add it to the VBO. return false; } void computeTangentBasis( //inputs std::vector<glm::vec3> &, std::vector<glm::vec2> &, std::vector<glm::vec3> &, //outputs std::vector<glm::vec3> &, std::vector<glm::vec3> & ); //text2D unsigned int Text2DTextureID; unsigned int Text2DVertexBufferID; unsigned int Text2DUVBufferID; unsigned int Text2DShaderID; unsigned int Text2DUniformID; void initText2D(const char *); void printText2D(const char *, int, int, int); void cleanupText2D(); //포지션 초기화 glm::vec3 position = glm::vec3(0, 0, 5); float horizontalAngle = 3.14f; float verticalAngle = 0.0f; float initialFoV = 45.0f; float speed = 3.0f; float mouseSpeed = 0.005f; void APIENTRY DebugOutputCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { printf("OpenGL Debug Output message : "); if (source == GL_DEBUG_SOURCE_API_ARB) printf("Source : API; "); else if (source == GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB) printf("Source : WINDOW_SYSTEM; "); else if (source == GL_DEBUG_SOURCE_SHADER_COMPILER_ARB) printf("Source : SHADER_COMPILER; "); else if (source == GL_DEBUG_SOURCE_THIRD_PARTY_ARB) printf("Source : THIRD_PARTY; "); else if (source == GL_DEBUG_SOURCE_APPLICATION_ARB) printf("Source : APPLICATION; "); else if (source == GL_DEBUG_SOURCE_OTHER_ARB) printf("Source : OTHER; "); if (type == GL_DEBUG_TYPE_ERROR_ARB) printf("Type : ERROR; "); else if (type == GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB) printf("Type : DEPRECATED_BEHAVIOR; "); else if (type == GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB) printf("Type : UNDEFINED_BEHAVIOR; "); else if (type == GL_DEBUG_TYPE_PORTABILITY_ARB) printf("Type : PORTABILITY; "); else if (type == GL_DEBUG_TYPE_PERFORMANCE_ARB) printf("Type : PERFORMANCE; "); else if (type == GL_DEBUG_TYPE_OTHER_ARB) printf("Type : OTHER; "); if (severity == GL_DEBUG_SEVERITY_HIGH_ARB) printf("Severity : HIGH; "); else if (severity == GL_DEBUG_SEVERITY_MEDIUM_ARB) printf("Severity : MEDIUM; "); else if (severity == GL_DEBUG_SEVERITY_LOW_ARB) printf("Severity : LOW; "); //break point를 여기에 설정해라, 당신의 디버거는 프로그램을 멈출 것이다 //callstack은 바로 너에게 offending call을 보여줄 것이다 printf("Mesage : %s\n", message); } //로테이션 vec3 gPosition1(-1.5f, 0.0f, 0.0f); vec3 gOrientation1; vec3 gPosition2(1.5f, 0.05f, 0.0f); quat gOrientation2; bool gLookAtOther = true; //quaternion such that q*start = dest 리턴 quat RotationBetweenVectors(vec3, vec3); //"direction"을 바라보는 개체를 만드는 쿼터니언을 반환한다. //RotationBetweenVectors와 유사하지만 수직 방향을 제어한다. //이것은 정지 상태에서 객체가 +Z를 향하고 있다고 가정한다. //첫번째 매개 변수는 목표 지점이 아닌 방향이다. quat LookAt(vec3, vec3); //SLERP와 비슷하지만 maxAngle보다 큰 회전을 금지한다 (라디안 단위). //LookAt과 함께 문자를 만들 수 있다. quat RotateTowards(quat, quat, float); //Particle 코드 struct Particle { glm::vec3 pos, speed; unsigned char r, g, b, a; float size, angle, weight; float life; //if < 0 : dead and unused float cameradistance; //if dead : -1.0f bool operator<(const Particle& that) const { return this->cameradistance > that.cameradistance; } }; const int MaxParticles = 100000; Particle ParticlesContainer[MaxParticles]; int LastUsedParticle = 0; // ParticlesContainer에 있는 아직 사용되지 않은 Particle을 찾는다 // (i.e. life < 0); int FindUnusedParticle() { for (int i = LastUsedParticle; i < MaxParticles; i++) { if (ParticlesContainer[i].life < 0) { LastUsedParticle = i; return i; } } for (int i = 0; i < LastUsedParticle; i++) { if (ParticlesContainer[i].life < 0) { LastUsedParticle = i; return i; } } return 0; // 모든 파티클이 사용됐다, 첫번째를 override한다. } void SortParticles() { std::sort(&ParticlesContainer[0], &ParticlesContainer[MaxParticles]); } int main() { // Initialise GLFW if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); getchar(); return -1; } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Open a window and create its OpenGL context window = glfwCreateWindow(1024, 768, "QBOT_opengl", NULL, NULL); if (window == NULL) { fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n"); getchar(); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); // Initialize GLEW glewExperimental = true; if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); getchar(); glfwTerminate(); return -1; } glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // Set the mouse at the center of the screen glfwPollEvents(); glfwSetCursorPos(window, 1024 / 2, 768 / 2); // Dark blue background glClearColor(0.0f, 0.0f, 0.4f, 0.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); GLuint VertexArrayID; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); GLuint programID = LoadShaders("Particle.vertexshader", "Particle.fragmentshader"); GLuint CameraRight_worldspace_ID = glGetUniformLocation(programID, "CameraRight_worldspace"); GLuint CameraUp_worldspace_ID = glGetUniformLocation(programID, "CameraUp_worldspace"); GLuint ViewProjMatrixID = glGetUniformLocation(programID, "VP"); GLuint TextureID = glGetUniformLocation(programID, "myTextureSampler"); static GLfloat* g_particule_position_size_data = new GLfloat[MaxParticles * 4]; static GLubyte* g_particule_color_data = new GLubyte[MaxParticles * 4]; for (int i = 0; i < MaxParticles; i++) { ParticlesContainer[i].life = -1.0f; ParticlesContainer[i].cameradistance = -1.0f; } GLuint Texture = loadDDS("particle.DDS"); // 파티클의 4 정점을 포함하는 VBO static const GLfloat g_vertex_buffer_data[] = { -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, -0.5f, 0.5f, 0.0f, 0.5f, 0.5f, 0.0f, }; GLuint billboard_vertex_buffer; glGenBuffers(1, &billboard_vertex_buffer); glBindBuffer(GL_ARRAY_BUFFER, billboard_vertex_buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_DYNAMIC_DRAW); // The VBO containing the positions and sizes of the particles GLuint particles_position_buffer; glGenBuffers(1, &particles_position_buffer); glBindBuffer(GL_ARRAY_BUFFER, particles_position_buffer); // Initialize with empty (NULL) buffer : it will be updated later, each frame. glBufferData(GL_ARRAY_BUFFER, MaxParticles * 4 * sizeof(GLfloat), NULL, GL_STREAM_DRAW); // The VBO containing the colors of the particles GLuint particles_color_buffer; glGenBuffers(1, &particles_color_buffer); glBindBuffer(GL_ARRAY_BUFFER, particles_color_buffer); // Initialize with empty (NULL) buffer : it will be updated later, each frame. glBufferData(GL_ARRAY_BUFFER, MaxParticles * 4 * sizeof(GLubyte), NULL, GL_STREAM_DRAW); double lastTime = glfwGetTime(); do { //Clear the Screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); double currentTime = glfwGetTime(); double deltaTime = currentTime - lastTime; lastTime = currentTime; computeMatricesFromInputs(); glm::mat4 ProjectionMatrix = getProjectionMatrix(); glm::mat4 ViewMatrix = getViewMatrix(); //입자를 정렬하려면 카메라의 위치가 필요하다 //카메라의 거리 w.r.t glm::vec3 CameraPosition(glm::inverse(ViewMatrix)[3]); glm::mat4 ViewProjectionMatrix = ProjectionMatrix * ViewMatrix; // 밀리 세컨드당 10개의 새로운 파티클 생성 // 16ms (60fps)로 제한하거나 1개의 긴 프레임이 있는경우 // new particle은 거대하고 다음 프레임은 더 길어진다 int newparticles = (int)(deltaTime*10000.0); if (newparticles > (int)(0.016f*10000.0)) newparticles = (int)(0.016f*10000.0); for (int i = 0; i < newparticles; i++) { int particleIndex = FindUnusedParticle(); ParticlesContainer[particleIndex].life = 5.0f; ParticlesContainer[particleIndex].pos = glm::vec3(0, 0, -20.0f); float spread = 1.5f; glm::vec3 maindir = glm::vec3(0.0f, 10.0f, 0.0f); glm::vec3 randomdir = glm::vec3( (rand() % 2000 - 1000.0f) / 1000.0f, (rand() % 2000 - 1000.0f) / 1000.0f, (rand() % 2000 - 1000.0f) / 1000.0f ); ParticlesContainer[particleIndex].speed = maindir + randomdir*spread; // 랜덤 컬러를 생성하는 매우 좋지 않은 방법 ParticlesContainer[particleIndex].r = rand() % 256; ParticlesContainer[particleIndex].g = rand() % 256; ParticlesContainer[particleIndex].b = rand() % 256; ParticlesContainer[particleIndex].a = (rand() % 256) / 3; ParticlesContainer[particleIndex].size = (rand() % 1000) / 2000.0f + 0.1f; }; // 모든 particle 시뮬레이트 int ParticlesCount = 0; for (int i = 0; i < MaxParticles; i++) { Particle& p = ParticlesContainer[i]; if (p.life > 0.0f) { // life를 줄인다 p.life -= deltaTime; if (p.life > 0.0f) { // 간단한 물리를 시뮬레이트 : 충돌x, 오로지 중력만! p.speed += glm::vec3(0.0f, -9.81f, 0.0f) * (float)deltaTime * 0.5f; p.pos += p.speed * (float)deltaTime; p.cameradistance = glm::length2(p.pos - CameraPosition); // GPU buffer를 채운다 g_particule_position_size_data[4 * ParticlesCount + 0] = p.pos.x; g_particule_position_size_data[4 * ParticlesCount + 1] = p.pos.y; g_particule_position_size_data[4 * ParticlesCount + 2] = p.pos.z; g_particule_position_size_data[4 * ParticlesCount + 3] = p.size; g_particule_color_data[4 * ParticlesCount + 0] = p.r; g_particule_color_data[4 * ParticlesCount + 1] = p.g; g_particule_color_data[4 * ParticlesCount + 2] = p.b; g_particule_color_data[4 * ParticlesCount + 3] = p.a; } else { // 곧 죽을 particle들은 SortParticles()의 마지막 버퍼에 넣어진다. p.cameradistance = -1.0f; } ParticlesCount++; } } SortParticles(); glBindBuffer(GL_ARRAY_BUFFER, particles_position_buffer); glBufferData(GL_ARRAY_BUFFER, MaxParticles * 4 * sizeof(GLfloat), NULL, GL_STREAM_DRAW); // Buffer orphaning, a common way to improve streaming perf. See above link for details. glBufferSubData(GL_ARRAY_BUFFER, 0, ParticlesCount * sizeof(GLfloat) * 4, g_particule_position_size_data); glBindBuffer(GL_ARRAY_BUFFER, particles_color_buffer); glBufferData(GL_ARRAY_BUFFER, MaxParticles * 4 * sizeof(GLubyte), NULL, GL_STREAM_DRAW); // Buffer orphaning, a common way to improve streaming perf. See above link for details. glBufferSubData(GL_ARRAY_BUFFER, 0, ParticlesCount * sizeof(GLubyte) * 4, g_particule_color_data); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glUseProgram(programID); // Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Texture); // Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(TextureID, 0); // 튜토리얼의 흥미로운 부분이다. // 이것은 inverse (ViewMatrix)에 의한 mlutiplying (1,0,0)과 (0,1,0)과 같습니다. // ViewMatrix는 직각 (이 방법으로 만들었습니다)입니다. // 그래서 그것의 역함수 역시 그것의 전치이고, // 행렬을 조 변경하는 것이 "자유"입니다 (반전은 느림) glUniform3f(CameraRight_worldspace_ID, ViewMatrix[0][0], ViewMatrix[1][0], ViewMatrix[2][0]); glUniform3f(CameraUp_worldspace_ID, ViewMatrix[0][1], ViewMatrix[1][1], ViewMatrix[2][1]); glUniformMatrix4fv(ViewProjMatrixID, 1, GL_FALSE, &ViewProjectionMatrix[0][0]); // 1rst attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, billboard_vertex_buffer); glVertexAttribPointer( 0, // attribute. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // 2nd attribute buffer : positions of particles' centers glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, particles_position_buffer); glVertexAttribPointer( 1, // attribute. No particular reason for 1, but must match the layout in the shader. 4, // size : x + y + z + size => 4 GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // 3rd attribute buffer : particles' colors glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, particles_color_buffer); glVertexAttribPointer( 2, // attribute. No particular reason for 1, but must match the layout in the shader. 4, // size : r + g + b + a => 4 GL_UNSIGNED_BYTE, // type GL_TRUE, // normalized? *** YES, this means that the unsigned char[4] will be accessible with a vec4 (floats) in the shader *** 0, // stride (void*)0 // array buffer offset ); glVertexAttribDivisor(0, 0); // particles vertices : always reuse the same 4 vertices -> 0 glVertexAttribDivisor(1, 1); // positions : one per quad (its center) -> 1 glVertexAttribDivisor(2, 1); // color : one per quad -> 1 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, ParticlesCount); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); glfwSwapBuffers(window); glfwPollEvents(); } // Check if the ESC key was pressed or the window was closed while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0); delete[] g_particule_position_size_data; // Cleanup VBO and shader glDeleteBuffers(1, &particles_color_buffer); glDeleteBuffers(1, &particles_position_buffer); glDeleteBuffers(1, &billboard_vertex_buffer); glDeleteProgram(programID); glDeleteTextures(1, &TextureID); glDeleteVertexArrays(1, &VertexArrayID); // Close OpenGL window and terminate GLFW glfwTerminate(); return 0; } GLuint LoadShaders(const char * vertex_file_path, const char * fragment_file_path) { //쉐이더 생성 GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER); GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); //버텍스 쉐이더 코드를 파일에서 읽기 std::string VertexShaderCode; std::ifstream VertexShaderStream(vertex_file_path, std::ios::in); if (VertexShaderStream.is_open()) { std::stringstream sstr; sstr << VertexShaderStream.rdbuf(); VertexShaderCode = sstr.str(); VertexShaderStream.close(); } else { printf("파일 %s를 읽을 수 없음. 정확한 디렉토리를 사용 중입니까?\n", vertex_file_path); getchar(); return 0; } //프래그먼트 쉐이더 코드를 파일에서 읽기 std::string FragmentShaderCode; std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in); if (FragmentShaderStream.is_open()) { std::stringstream sstr; sstr << FragmentShaderStream.rdbuf(); FragmentShaderCode = sstr.str(); FragmentShaderStream.close(); } GLint Result = GL_FALSE; int InfoLogLength; //버텍스 쉐이더를 컴파일 printf("Compiling shader : %s\n", vertex_file_path); char const * VertexSourcePointer = VertexShaderCode.c_str(); glShaderSource(VertexShaderID, 1, &VertexSourcePointer, NULL); glCompileShader(VertexShaderID); //버텍스 쉐이더를 검사 glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { std::vector<char> VertexShaderErrorMessage(InfoLogLength + 1); glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]); printf("%s\n", &VertexShaderErrorMessage[0]); } //프래그먼트 쉐이더를 컴파일 printf("Compiling shader : %s", fragment_file_path); char const * FragmentSourcePointer = FragmentShaderCode.c_str(); glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer, NULL); glCompileShader(FragmentShaderID); //프래그먼트 쉐이더를 검사 glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { std::vector<char> FragmentShaderErrorMessage(InfoLogLength + 1); glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]); printf("%s\n", &FragmentShaderErrorMessage[0]); } //프로그램에 링크 printf("Linking program\n"); GLuint ProgramID = glCreateProgram(); glAttachShader(ProgramID, VertexShaderID); glAttachShader(ProgramID, FragmentShaderID); glLinkProgram(ProgramID); //프로그램 검사 glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result); glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { std::vector<char> ProgramErrorMessage(InfoLogLength + 1); glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]); printf("%s\n", &ProgramErrorMessage[0]); } glDetachShader(ProgramID, VertexShaderID); glDetachShader(ProgramID, FragmentShaderID); glDeleteShader(VertexShaderID); glDeleteShader(FragmentShaderID); return ProgramID; } GLuint loadBMP_custom(const char * imagepath) { printf("Reading image %s\n", imagepath); //BMP파일의 헤더에서 데이터를 읽는다 unsigned char header[54]; unsigned int dataPos; unsigned int imageSize; unsigned int width, height; //실제 RGB 데이터 unsigned char * data; //파일을 연다 FILE * file = fopen(imagepath, "rb"); if (!file) { printf("%s는 열수 없다. 경로가 맞는지 확인해라.\n", imagepath); getchar(); return 0; } //헤더를 읽는다, i.e. the 54 first bytes //만약 54 bytes보다 적게 읽혔으면 문제 발생 if (fread(header, 1, 54, file) != 54) { printf("BMP 파일이 아니다\n"); return 0; } //A BMP 파일은 항상 "BM"으로 시작한다. if (header[0] != 'B' || header[1] != 'M') { printf("BMP 파일이 아니다\n"); return 0; } //24pp file임을 확인한다. if (*(int*)&(header[0x1e]) != 0 || *(int*)&(header[0x1C]) != 24) { printf("BMP 파일이 아니다\n"); return 0; } //이미지에 대한 정보를 읽는다. dataPos = *(int*)&(header[0x0A]); imageSize = *(int*)&(header[0x22]); width = *(int*)&(header[0x12]); height = *(int*)&(header[0x16]); //몇몇 BMP 파일들은 포맷이 놓쳐졌다, 놓쳐진 정보를 추측해라 if (imageSize == 0) imageSize = width*height * 3; // 3 : one byte for each Red-Green-Blue component if (dataPos == 0) dataPos = 54; //BMP 헤더는 항상 이 형식 //버퍼를 생성한다 data = new unsigned char[imageSize]; //파일의 버퍼에 있는 실제 데이터를 읽는다 fread(data, 1, imageSize, file); //모든 것은 현재 메모리에 있다, 파일을 닫는다 fclose(file); //openGL 텍스처를 만든다 GLuint textureID; glGenTextures(1, &textureID); //새로이 만들어진 텍스처를 바인딩한다. glBindTexture(GL_TEXTURE_2D, textureID); //이미지를 OpenGL에게 넘긴다 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data); delete[] data; // trilinear(삼선형) 필터링 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glGenerateMipmap(GL_TEXTURE_2D); return textureID; } GLuint loadDDS(const char * imagepath) { unsigned char header[124]; FILE *fp; //파일을 연다 fp = fopen(imagepath, "rb"); if (fp == NULL) { printf("%s는 열 수 없다. 경로를 확인해라\n", imagepath); getchar(); return 0; } //파일의 타입을 확인한다 char filecode[4]; fread(filecode, 1, 4, fp); if (strncmp(filecode, "DDS ", 4) != 0) { fclose(fp); return 0; } //surface desc를 얻는다 fread(&header, 124, 1, fp); unsigned int height = *(unsigned int*)&(header[8]); unsigned int width = *(unsigned int*)&(header[12]); unsigned int linearSize = *(unsigned int*)&(header[16]); unsigned int mipMapCount = *(unsigned int*)&(header[24]); unsigned int fourCC = *(unsigned int*)&(header[80]); unsigned char * buffer; unsigned int bufsize; bufsize = mipMapCount > 1 ? linearSize * 2 : linearSize; buffer = (unsigned char*)malloc(bufsize * sizeof(unsigned char)); fread(buffer, 1, bufsize, fp); fclose(fp); unsigned int components = (fourCC == FOURCC_DXT1) ? 3 : 4; unsigned int format; switch (fourCC) { case FOURCC_DXT1: format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; break; case FOURCC_DXT3: format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; break; case FOURCC_DXT5: format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; break; default: free(buffer); return 0; } //하나의 OpenGL 텍스처를 생성한다 GLuint textureID; glGenTextures(1, &textureID); //새로이 만들어진 텍스처를 바인딩한다 glBindTexture(GL_TEXTURE_2D, textureID); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); unsigned int blockSize = (format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) ? 8 : 16; unsigned int offset = 0; //밉맵을 불러온다 for (unsigned int level = 0; level < mipMapCount && (width || height); ++level) { unsigned int size = ((width + 3) / 4)*((height + 3) / 4)*blockSize; glCompressedTexImage2D(GL_TEXTURE_2D, level, format, width, height, 0, size, buffer + offset); offset += size; width /= 2; height /= 2; //Non-Power-Of-Two 텍스처를 사용합니다. //이 코드는 혼란을 줄이기 위해 웹 페이지에는 포함되어 있지 않습니다. if (width < 1)width = 1; if (height < 1) height = 1; } free(buffer); return textureID; } bool loadOBJ( const char * path, std::vector<glm::vec3> & out_vertices, std::vector<glm::vec2> & out_uvs, std::vector<glm::vec3> & out_normals ) { printf("OBJ 파일 로딩중 %s...\n", path); std::vector<unsigned int> vertexIndices, uvIndices, normalIndices; std::vector<glm::vec3> temp_vertices; std::vector <glm::vec2> temp_uvs; std::vector<glm::vec3> temp_normals; FILE * file = fopen(path, "r"); if (file == NULL) { printf("파일 경로를 확인하세요!\n"); getchar(); return false; } while (1) { char lineHeader[128]; //첫번째 라인의 첫번째 단어를 읽는다 int res = fscanf(file, "%s", lineHeader); if (res == EOF) break; //else : 라인의 헤더를 parse if (strcmp(lineHeader, "v") == 0) { glm::vec3 vertex; fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z); temp_vertices.push_back(vertex); } else if (strcmp(lineHeader, "vt") == 0) { glm::vec2 uv; fscanf(file, "%f %f\n", &uv.x, &uv.y); uv.y = -uv.y; //우리가 DDS texture만을 이용할 것이므로 V의 좌표를 반대로 바꾸어준다. 만약 TGA or BMP 로더를 사용하면 이 것을 제거해라. temp_uvs.push_back(uv); } else if (strcmp(lineHeader, "vn") == 0) { glm::vec3 normal; fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z); temp_normals.push_back(normal); } else if (strcmp(lineHeader, "f") == 0) { std::string vertex1, vertex2, vertex3; unsigned int vertexIndex[3], uvIndex[3], normalIndex[3]; int matches = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2]); if (matches != 9) { printf("파일을 읽을수없다."); return false; } vertexIndices.push_back(vertexIndex[0]); vertexIndices.push_back(vertexIndex[1]); vertexIndices.push_back(vertexIndex[2]); uvIndices.push_back(uvIndex[0]); uvIndices.push_back(uvIndex[1]); uvIndices.push_back(uvIndex[2]); normalIndices.push_back(normalIndex[0]); normalIndices.push_back(normalIndex[1]); normalIndices.push_back(normalIndex[2]); } else { //나머지 라인을 먹는다. char stupidBuffer[1000]; fgets(stupidBuffer, 1000, file); } } //각 삼각형의 각 꼭지점 for (unsigned int i = 0; i < vertexIndices.size(); i++) { //속성의 인덱스를 가져온다 unsigned int vertexIndex = vertexIndices[i]; unsigned int uvIndex = uvIndices[i]; unsigned int normalIndex = normalIndices[i]; //인덱스에서 속성을 가져온다 glm::vec3 vertex = temp_vertices[vertexIndex - 1]; glm::vec2 uv = temp_uvs[uvIndex - 1]; glm::vec3 normal = temp_normals[normalIndex - 1]; //버퍼에 속성을 넣는다 out_vertices.push_back(vertex); out_uvs.push_back(uv); out_normals.push_back(normal); } return true; } void indexVBO( std::vector<glm::vec3> & in_vertices, std::vector<glm::vec2> & in_uvs, std::vector<glm::vec3> & in_normals, std::vector<unsigned short> & out_indices, std::vector<glm::vec3> & out_vertices, std::vector<glm::vec2> & out_uvs, std::vector<glm::vec3> & out_normals ) { std::map<PackedVertex, unsigned short> VertexToOutIndex; //각 input vertex를 위해 for (unsigned int i = 0; i < in_vertices.size(); i++) { PackedVertex packed = { in_vertices[i], in_uvs[i], in_normals[i] }; //out_XXXX에서 비슷한 vertex를 찾는다 unsigned short index; bool found = getSimilarVertexIndex_fast(packed, VertexToOutIndex, index); if (found) { //비슷한 vertex가 VBO에 이미 있다면 대신 사용한다 out_indices.push_back(index); } else { //아니라면 이것은 아웃풋 데이터 추가가 필요하다 out_vertices.push_back(in_vertices[i]); out_uvs.push_back(in_uvs[i]); out_normals.push_back(in_normals[i]); unsigned short newindex = (unsigned short)out_vertices.size() - 1; out_indices.push_back(newindex); VertexToOutIndex[packed] = newindex; } } } void indexVBO_TBN( std::vector<glm::vec3> & in_vertices, std::vector<glm::vec2> & in_uvs, std::vector<glm::vec3> & in_normals, std::vector<glm::vec3> & in_tangents, std::vector<glm::vec3> & in_bitangents, std::vector<unsigned short> & out_indices, std::vector<glm::vec3> & out_vertices, std::vector<glm::vec2> & out_uvs, std::vector<glm::vec3> & out_normals, std::vector<glm::vec3> & out_tangents, std::vector<glm::vec3> & out_bitangents ) { //각 input vertex를 위해 for (unsigned int i = 0; i < in_vertices.size(); i++) { //out_XXXX 에서 비슷한 vertex를 찾는다 unsigned short index; bool found = getSimilarVertexIndex(in_vertices[i], in_uvs[i], in_normals[i], out_vertices, out_uvs, out_normals, index); if (found) { //비슷한 vertex가 이미 VBO에 있으면, 이것을 대신 사용 out_indices.push_back(index); //tangents와 bitangents의 평균을 한다 out_tangents[index] += in_tangents[i]; out_bitangents[index] += in_bitangents[i]; } else { // 만약 아니라면, output data에서 추가한다 out_vertices.push_back(in_vertices[i]); out_uvs.push_back(in_uvs[i]); out_normals.push_back(in_normals[i]); out_tangents.push_back(in_tangents[i]); out_bitangents.push_back(in_bitangents[i]); out_indices.push_back((unsigned short)out_vertices.size() - 1); } } } void computeMatricesFromInputs() { //glfwGetTime은 한번만 호출된다. static double lastTime = glfwGetTime(); //현재와 마지막 프레임의 시간 차를 계산한다. double currentTime = glfwGetTime(); float deltaTime = float(currentTime - lastTime); //마우스의 위치를 얻는다. double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); //다음 프레임의 마우스 위치를 리셋한다. glfwSetCursorPos(window, 1024 / 2, 768 / 2); horizontalAngle += mouseSpeed * float(1024 / 2 - xpos); verticalAngle += mouseSpeed * float(768 / 2 - ypos); //Direction : Spherical 좌표 to Cartesian 좌표 변환 glm::vec3 direction( cos(verticalAngle)*sin(horizontalAngle), sin(verticalAngle), cos(verticalAngle)*cos(horizontalAngle) ); //Right vector glm::vec3 right = glm::vec3( sin(horizontalAngle - 3.14f / 2.0f), 0, cos(horizontalAngle - 3.14f / 2.0f) ); //Up vector glm::vec3 up = glm::cross(right, direction); //앞으로 이동 if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) { position += direction*deltaTime*speed; } //뒤로 이동 if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) { position -= direction*deltaTime*speed; } //오른쪽로 Strafe if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) { position += right*deltaTime*speed; } //왼쪽으로 Strafe if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) { position -= right*deltaTime*speed; } float FoV = initialFoV; ProjectionMatrix = glm::perspective(FoV, 4.0f / 3.0f, 0.1f, 100.0f); ViewMatrix = glm::lookAt( position, //camera here position + direction, //and looks here up // Head is up ); //다음 프레임을 위해 lastTime = currentTime; } void computeTangentBasis( //inputs std::vector<glm::vec3> & vertices, std::vector<glm::vec2> & uvs, std::vector<glm::vec3> & normals, //outputs std::vector<glm::vec3> & tangents, std::vector<glm::vec3> & bitangents ) { for (unsigned int i = 0; i < vertices.size(); i += 3) { //shortcuts for vertices glm::vec3 & v0 = vertices[i + 0]; glm::vec3 & v1 = vertices[i + 1]; glm::vec3 & v2 = vertices[i + 2]; //shortcuts for UVs glm::vec2 & uv0 = uvs[i + 0]; glm::vec2 & uv1 = uvs[i + 1]; glm::vec2 & uv2 = uvs[i + 2]; //edges of the triangle : position delta glm::vec3 deltaPos1 = v1 - v0; glm::vec3 deltaPos2 = v2 - v0; //UV delta glm::vec2 deltaUV1 = uv1 - uv0; glm::vec2 deltaUV2 = uv2 - uv0; float r = 1.0f / (deltaUV1.x * deltaUV2.y - deltaUV1.y * deltaUV2.x); glm::vec3 tangent = (deltaPos1 * deltaUV2.y - deltaPos2 * deltaUV1.y)*r; glm::vec3 bitangent = (deltaPos2 * deltaUV1.x - deltaPos1*deltaUV2.x)*r; //삼각형의 모든 세개의 정점을 위해 같은 tangent를 세팅한다. //그것들은 곧 병합될겉이다 tangents.push_back(tangent); tangents.push_back(tangent); tangents.push_back(tangent); //binormals를 위한 같은 것 bitangents.push_back(bitangent); bitangents.push_back(bitangent); bitangents.push_back(bitangent); } // "Going Further" 봐라 for (unsigned int i = 0; i < vertices.size(); i += 1) { glm::vec3 & n = normals[i]; glm::vec3 & t = tangents[i]; glm::vec3 & b = bitangents[i]; //Gram-Schmidt orthogonalize t = glm::normalize(t - n*glm::dot(n, t)); //handedness 계산 if (glm::dot(glm::cross(n, t), b) < 0.0f) { t = t*-1.0f; } } } void initText2D(const char * texturePath) { //텍스쳐 초기화 Text2DTextureID = loadDDS(texturePath); //VBO 초기화 glGenBuffers(1, &Text2DVertexBufferID); glGenBuffers(1, &Text2DUVBufferID); //Shader 초기화 Text2DShaderID = LoadShaders("TextVertexShader.vertexshader", "TextVertexShader.fragmentshader"); //uniforms' IDs 초기화 Text2DUniformID = glGetUniformLocation(Text2DShaderID, "myTextureSampler"); } void printText2D(const char * text, int x, int y, int size) { unsigned int length = strlen(text); //buffer 채우기 std::vector<glm::vec2> vertices; std::vector<glm::vec2> UVs; for (unsigned int i = 0; i < length; i++) { glm::vec2 vertex_up_left = glm::vec2(x + i*size, y + size); glm::vec2 vertex_up_right = glm::vec2(x + i*size + size, y + size); glm::vec2 vertex_down_right = glm::vec2(x + i*size + size, y); glm::vec2 vertex_down_left = glm::vec2(x + i*size, y); vertices.push_back(vertex_up_left); vertices.push_back(vertex_down_left); vertices.push_back(vertex_up_right); vertices.push_back(vertex_down_right); vertices.push_back(vertex_up_right); vertices.push_back(vertex_down_left); char character = text[i]; float uv_x = (character % 16) / 16.0f; float uv_y = (character / 16) / 16.0f; glm::vec2 uv_up_left = glm::vec2(uv_x, uv_y); glm::vec2 uv_up_right = glm::vec2(uv_x + 1.0f / 16.0f, uv_y); glm::vec2 uv_down_right = glm::vec2(uv_x + 1.0f / 16.0f, (uv_y + 1.0f / 16.0f)); glm::vec2 uv_down_left = glm::vec2(uv_x, (uv_y + 1.0f / 16.0f)); UVs.push_back(uv_up_left); UVs.push_back(uv_down_left); UVs.push_back(uv_up_right); UVs.push_back(uv_down_right); UVs.push_back(uv_up_right); UVs.push_back(uv_down_left); glBindBuffer(GL_ARRAY_BUFFER, Text2DVertexBufferID); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec2), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, Text2DUVBufferID); glBufferData(GL_ARRAY_BUFFER, UVs.size() * sizeof(glm::vec2), &UVs[0], GL_STATIC_DRAW); // Bind shader glUseProgram(Text2DShaderID); // Bind texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Text2DTextureID); // Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(Text2DUniformID, 0); // 1rst attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, Text2DVertexBufferID); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0); // 2nd attribute buffer : UVs glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, Text2DUVBufferID); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (void*)0); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Draw call glDrawArrays(GL_TRIANGLES, 0, vertices.size()); glDisable(GL_BLEND); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); } } void cleanupText2D() { // Delete buffers glDeleteBuffers(1, &Text2DVertexBufferID); glDeleteBuffers(1, &Text2DUVBufferID); // Delete texture glDeleteTextures(1, &Text2DTextureID); // Delete shader glDeleteProgram(Text2DShaderID); } quat RotationBetweenVectors(vec3 start, vec3 dest) { start = normalize(start); dest = normalize(dest); float cosTheta = dot(start, dest); vec3 rotationAxis; if (cosTheta < -1 + 0.001f) { //반대 방향의 벡터인 특별한 경우 : //"ideal" rotation 축이 없다 //그래서 추축해라; 어떤 것도 그것이 시작에 수직일 때만 할 것이다 //이 구현은 up축을 중심으로 한 회전을 선호하지만 rotationAxis = cross(vec3(0.0f, 0.0f, 1.0f), start); if (length2(rotationAxis) < 0.01) //운이 나빠서 평행일때 다시해라! rotationAxis = cross(vec3(1.0f, 0.0f, 0.0f), start); rotationAxis = normalize(rotationAxis); return angleAxis(180.0f, rotationAxis); } // Stan Melax의 게임 프로그래밍 Gems 1 구현 rotationAxis = cross(start, dest); float s = sqrt((1 + cosTheta) * 2); float invs = 1 / s; return quat( s*0.5f, rotationAxis.x * invs, rotationAxis.y * invs, rotationAxis.z * invs ); } quat LookAt(vec3 direction, vec3 desiredUp) { if (length2(direction) < 0.0001f) return quat(); // 방향에 수직이 되도록 desiredUp을 재계산한다 // 원하는 부분을 실제로 강제 실행하려면 해당 부분을 건너 뛸 수 있다 vec3 right = cross(direction, desiredUp); desiredUp = cross(right, direction); // 객체의 앞면(+Z쪽으로 가정하는 회전)을 찾는다 // 그러나 이것은 당신의 모델에 달려있다, 그리고 원하는 방향 quat rot1 = RotationBetweenVectors(vec3(0.0f, 0.0f, 1.0f), direction); // 1회전 때문에, 위로 올랐을 때 아마 완전히 엉망이 되었다 // 회전된 객체의 "up"과 원하는 객체 사이의 회전을 찾는다 vec3 newUp = rot1*vec3(0.0f, 1.0f, 0.0f); quat rot2 = RotationBetweenVectors(newUp, desiredUp); // 적용한다 return rot2*rot1; } quat RotateTowards(quat q1, quat q2, float maxAngle) { if (maxAngle < 0.001f) { // 회전은 허용되지 않는다. 나중에 0으로 나누는 것을 방지해라 return q1; } float cosTheta = dot(q1, q2); // q1과 q2는 이미 동일하다 // q2는 옳다 if (cosTheta > 0.9999f) { return q2; } // sphere 주변의 긴 경로를 방지해라 if (cosTheta < 0) { q1 = q1*-1.0f; cosTheta *= -1.0f; } float angle = acos(cosTheta); // 차이가 2개인 경우 5가 허용될까? if (angle < maxAngle) { return q2; } // 이것은 slerp()와 같지만 사용자 정의 t와 함께 한다 float t = maxAngle / angle; angle = maxAngle; quat res = (sin((1.0f - t)*angle) * q1 + sin(t*angle)*q2) / sin(angle); res = normalize(res); return res; } | cs |
'Game > Graphics' 카테고리의 다른 글
Learn OpenGL - Getting started : Creating a Window (0) | 2018.08.01 |
---|---|
Learn OpenGL (0) | 2018.08.01 |
OpenGL-Tutorial 18 : Billboards (0) | 2018.07.04 |
OpenGL-Tutorial 17 : Rotations (2) | 2018.07.03 |
OpenGL-Tutorial 16 : Shadow mapping (2) | 2018.07.02 |