glm (1125161), страница 3

Файл №1125161 glm (Task 3 часть 1) 3 страницаglm (1125161) страница 32019-05-11СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 3)

Figure 4.8.9: glm::perlin(glm::vec4(x / 16.f, y / 16.f, glm::vec2(0.5f)), glm::vec4(2.0f));

4.9. GLM_GTC_quaternion

Defines a templated quaternion type and several quaternion operations.

<glm/gtc/quaternion.hpp> need to be included to use these features.

4.10. GLM_GTC_random

Generate random number from various distribution methods.

<glm/gtc/random.hpp> need to be included to use these features.

Figure 4.10.1: glm::vec4(glm::linearRand(glm::vec2(-1), glm::vec2(1)), 0, 1);

Figure 4.10.2: glm::vec4(glm::circularRand(1.0f), 0, 1);


Figure 4.10.3: glm::vec4(glm::sphericalRand(1.0f), 1);

Figure 4.10.4: glm::vec4(glm::diskRand(1.0f), 0, 1);

Figure 4.10.5: glm::vec4(glm::ballRand(1.0f), 1);

Figure 4.10.6: glm::vec4(glm::gaussRand(glm::vec3(0), glm::vec3(1)), 1);

4.11. GLM_GTC_reciprocal

Provides hyperbolic functions: secant, cosecant, cotangent, etc.

<glm/gtc/reciprocal.hpp> need to be included to use these functionalities.

4.12. GLM_GTC_swizzle

Provide functions to emulate GLSL swizzle operator features but with a different syntax that feats C++ boundaries.

<glm/gtc/swizzle.hpp> need to be included to use these functionalities.

4.13. GLM_GTC_type_precision

Vector and matrix types with defined precisions. Eg, i8vec4: vector of 4 signed integer of 8 bits.

<glm/gtc/type_precision.hpp> need to be included to use these functionalities.

4.14. GLM_GTC_type_ptr

Handles the interaction between pointers and vector, matrix types.

This extension defines an overloaded function, glm::value_ptr, which takes any of the core template types (vec3, mat4, etc.). It returns a pointer to the memory layout of the object. Matrix types store their values in column-major order.

This is useful for uploading data to matrices or copying data to buffer objects.

Example:

#include <glm/glm.hpp>

#include <glm/gtc/type_ptr.hpp>

glm::vec3 aVector(3);

glm::mat4 someMatrix(1.0);

glUniform3fv(uniformLoc, 1, glm::value_ptr(aVector));

glUniformMatrix4fv(uniformMatrixLoc,

1, GL_FALSE, glm::value_ptr(someMatrix));

<glm/gtc/type_ptr.hpp> need to be included to use these features.

4.15. GLM_GTC_ulp

Allow the measurement of the accuracy of a function against a reference implementation. This extension works on floating-point data and provides results in ULP.

<glm/gtc/ulp.hpp> need to be included to use these features.

5. Known issues

5.1. not function

The GLSL keyword not is also a keyword in C++. To prevent name collisions, ensure cross compiler support and a high API consistency, the GLSL not function has been implemented with the name not_.

5.2. half based types and component accesses

GLM supports half float number types through the extension GLM_GTC_half_float. This extension provides the types half, hvec*, hmat*x* and hquat*.

Unfortunately, C++98 specification doesn’t support anonymous unions which limits hvec* vector components access to x, y, z and w.

However, Visual C++ does support anonymous unions if the language extensions are enabled (/Za to disable them). In this case GLM will automatically enables the support of all component names (x,y,z,w ; r,g,b,a ; s,t,p,q).

To uniformalize the component access across types, GLM provides the define GLM_FORCE_ONLY_XYZW which will generates errors if component accesses are done using r,g,b,a or s,t,p,q.

#define GLM_FORCE_ONLY_XYZW

#include <glm/glm.hpp>

6. FAQ

6.1 Why GLM follows GLSL specification and conventions?

Following GLSL conventions is a really strict policy of GLM. It has been designed following the idea that everyone does its own math library with his own conventions. The idea is that brilliant developers (the OpenGL ARB) worked together and agreed to make GLSL. Following GLSL conventions is a way to find consensus. Moreover, basically when a developer knows GLSL, he knows GLM.

6.2. Does GLM run GLSL program?

No, GLM is a C++ implementation of a subset of GLSL.

6.3. Does a GLSL compiler build GLM codes?

No, this is not what GLM attends to do!

6.4. Should I use ‘GTX’ extensions?

GTX extensions are qualified to be experimental extensions. In GLM this means that these extensions might change from version to version without any restriction. In practice, it doesn’t really change except time to time. GTC extensions are stabled, tested and perfectly reliable in time. Many GTX extensions extend GTC extensions and provide a way to explore features and implementations and APIs and then are promoted to GTC extensions. This is fairly the way OpenGL features are developed; through extensions.

6.5. Where can I ask my questions?

A good place is the OpenGL Toolkits forum on OpenGL.org

6.6. Where can I find the documentation of extensions?

The Doxygen generated documentation includes a complete list of all extensions available. Explore this API documentation to get a complete view of all GLM capabilities!

6.7. Should I use ‘using namespace glm;’?

NO! Chances are that if ‘using namespace glm;’ is called, especially in a header file, name collisions will happen as GLM is based on GLSL which uses common tokens for types and functions. Avoiding ‘using namespace glm;’ will a higher compatibility with third party library and SDKs.

6.8. Is GLM fast?

First, GLM is mainly designed to be convenient and that's why it is written against GLSL specification. Following the 20-80 rules where 20% of the code grad 80% of the performances, GLM perfectly operates on the 80% of the code that consumes 20% of the performances. This said, on performance critical code section, the developers will probably have to write to specific code based on a specific design to reach peak performances but GLM can provides some descent performances alternatives based on approximations or SIMD instructions.

6.9. When I build with Visual C++ with /W4 warning level, I have warnings...

You should not have any warnings even in /W4 mode. However, if you expect such level for you code, then you should ask for the same level to the compiler by at least disabling the Visual C++ language extensions (/Za) which generates warnings when used. If these extensions are enabled, then GLM will take advantage of them and the compiler will generate warnings.



7. Code samples

This series of samples only shows various GLM features without consideration of any sort.

7.1. Compute a triangle normal

#include <glm/glm.hpp> // vec3 normalize cross

glm::vec3 computeNormal

(

glm::vec3 const & a,

glm::vec3 const & b,

glm::vec3 const & c

)

{

return glm::normalize(glm::cross(c - a, b - a));

}

// A much faster but less accurate alternative:

#include <glm/glm.hpp> // vec3 cross

#include <glm/gtx/fast_square_root.hpp> // fastNormalize

glm::vec3 computeNormal

(

glm::vec3 const & a,

glm::vec3 const & b,

glm::vec3 const & c

)

{

return glm::fastNormalize(glm::cross(c - a, b - a));

}

7.2. Matrix transform

// vec3, vec4, ivec4, mat4

#include <glm/glm.hpp>

// translate, rotate, scale, perspective

#include <glm/gtc/matrix_transform.hpp>

// value_ptr

#include <glm/gtc/type_ptr.hpp>

void setUniformMVP

(

GLuint Location,

glm::vec3 const & Translate,

glm::vec3 const & Rotate

)

{

glm::mat4 Projection =

glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.f);

glm::mat4 ViewTranslate = glm::translate(

glm::mat4(1.0f),

Translate);

glm::mat4 ViewRotateX = glm::rotate(

ViewTranslate,

Rotate.y, glm::vec3(-1.0f, 0.0f, 0.0f));

glm::mat4 View = glm::rotate(

ViewRotateX,

Rotate.x, glm::vec3(0.0f, 1.0f, 0.0f));

glm::mat4 Model = glm::scale(

glm::mat4(1.0f),

glm::vec3(0.5f));

glm::mat4 MVP = Projection * View * Model;

glUniformMatrix4fv(Location, 1, GL_FALSE, glm::value_ptr(MVP));

}

7.3. Vector types

#include <glm/glm.hpp> //vec2

#include <glm/gtc/type_precision.hpp> //hvec2, i8vec2, i32vec2

std::size_t const VertexCount = 4;

// Float quad geometry

std::size_t const PositionSizeF32 = VertexCount * sizeof(glm::vec2);

glm::vec2 const PositionDataF32[VertexCount] =

{

glm::vec2(-1.0f,-1.0f),

glm::vec2( 1.0f,-1.0f),

glm::vec2( 1.0f, 1.0f),

glm::vec2(-1.0f, 1.0f)

};

// Half-float quad geometry

std::size_t const PositionSizeF16 = VertexCount * sizeof(glm::hvec2);

glm::hvec2 const PositionDataF16[VertexCount] =

{

glm::hvec2(-1.0f, -1.0f),

glm::hvec2( 1.0f, -1.0f),

glm::hvec2( 1.0f, 1.0f),

glm::hvec2(-1.0f, 1.0f)

};

// 8 bits signed integer quad geometry

std::size_t const PositionSizeI8 = VertexCount * sizeof(glm::i8vec2);

glm::i8vec2 const PositionDataI8[VertexCount] =

{

glm::i8vec2(-1,-1),

glm::i8vec2( 1,-1),

glm::i8vec2( 1, 1),

glm::i8vec2(-1, 1)

};

// 32 bits signed integer quad geometry

std::size_t const PositionSizeI32 = VertexCount * sizeof(glm::i32vec2);

glm::i32vec2 const PositionDataI32[VertexCount] =

{

glm::i32vec2(-1,-1),

glm::i32vec2( 1,-1),

glm::i32vec2( 1, 1),

glm::i32vec2(-1, 1)

};

7.4. Lighting

#include <glm/glm.hpp> // vec3 normalize reflect dot pow

#include <glm/gtx/random.hpp> // vecRand3

// vecRand3, generate a random and equiprobable normalized vec3

glm::vec3 lighting

(

intersection const & Intersection,

material const & Material,

light const & Light,

glm::vec3 const & View

)

{

glm::vec3 Color = glm::vec3(0.0f);

glm::vec3 LightVertor = glm::normalize(

Light.position() - Intersection.globalPosition() +

glm::vecRand3(0.0f, Light.inaccuracy());

if(!shadow(

Intersection.globalPosition(),

Light.position(),

LightVertor))

{

float Diffuse = glm::dot(Intersection.normal(), LightVector);

if(Diffuse <= 0.0f)

return Color;

if(Material.isDiffuse())

Color += Light.color() * Material.diffuse() * Diffuse;

if(Material.isSpecular())

{

glm::vec3 Reflect = glm::reflect(

-LightVector,

Intersection.normal());

float Dot = glm::dot(Reflect, View);

float Base = Dot > 0.0f ? Dot : 0.0f;

float Specular = glm::pow(Base, Material.exponent());

Color += Material.specular() * Specular;

}

}

return Color;

}

8. References

8.1. GLM development

- GLM website

- GLM HEAD snapshot

- GLM bug report and feature request

- G-Truc Creation’s page

8.2. OpenGL specifications

- OpenGL 4.3 core specification

- GLSL 4.30 specification

- GLU 1.3 specification

8.3. External links

- The OpenGL Toolkits forum to ask questions about GLM

8.4. Projects using GLM

- Outerra:

3D planetary engine for seamless planet rendering from space down to the surface. Can use arbitrary resolution of elevation data, refining it to centimeter resolution using fractal algorithms.

Характеристики

Тип файла
Документ
Размер
748,38 Kb
Материал
Тип материала
Высшее учебное заведение

Список файлов лабораторной работы

решение
Mashgraph2013-3task
bin
Win32
Release
Fragment-orbit.frag.cpp
Fragment.frag.cpp
Triangles.exe
Triangles.pdb
Vertex-orbit.vert.cpp
Vertex.vert.cpp
controls(1).bin
controls(1).xml
controls(2).bin
controls(2).xml
controls(3).bin
controls(3).xml
freeglut.dll
glew32.dll
x64
Release
Fragment-orbit.frag.cpp
Fragment.frag.cpp
Triangles.exe
Triangles.pdb
Vertex-orbit.vert.cpp
Vertex.vert.cpp
controls(1).bin
controls(1).xml
controls(2).bin
controls(2).xml
Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
7028
Авторов
на СтудИзбе
260
Средний доход
с одного платного файла
Обучение Подробнее