glm (1124588), страница 4

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

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

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_ulpAllow the measurement of the accuracy of a function against a referenceimplementation. This extension works on floating-point data and provides results inULP.<glm/gtc/ulp.hpp>need to be included to use these features.5. Known issues5.1. not functionThe GLSL keyword not is also a keyword in C++.

To prevent name collisions, ensurecross compiler support and a high API consistency, the GLSL not function has beenimplemented with the name not_.5.2. half based types and component accessesGLM 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 limitshvec* vector components access to x, y, z and w.However, Visual C++ does support anonymous unions if the language extensions areenabled (/Za to disable them).

In this case GLM will automatically enables thesupport 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 defineGLM_FORCE_ONLY_XYZW which will generates errors if component accesses aredone using r,g,b,a or s,t,p,q.#define GLM_FORCE_ONLY_XYZW#include <glm/glm.hpp>6. FAQ6.1 Why GLM follows GLSL specification and conventions?Following GLSL conventions is a really strict policy of GLM.

It has been designedfollowing 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 agreedto 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 thatthese extensions might change from version to version without any restriction. Inpractice, it doesn’t really change except time to time. GTC extensions are stabled,tested and perfectly reliable in time. Many GTX extensions extend GTC extensionsand provide a way to explore features and implementations and APIs and then arepromoted 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.org6.6. Where can I find the documentation of extensions?The Doxygen generated documentation includes a complete list of all extensionsavailable. Explore this API documentation to get a complete view of all GLMcapabilities!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 fortypes and functions.

Avoiding ‘using namespace glm;’ will a higher compatibility withthird party library and SDKs.6.8. Is GLM fast?First, GLM is mainly designed to be convenient and that's why it is written againstGLSL specification. Following the 20-80 rules where 20% of the code grad 80% of theperformances, GLM perfectly operates on the 80% of the code that consumes 20% ofthe performances. This said, on performance critical code section, the developerswill probably have to write to specific code based on a specific design to reach peakperformances but GLM can provides some descent performances alternatives basedon approximations or SIMD instructions.6.9. When I build with Visual C++ with /W4 warning level, I havewarnings...You should not have any warnings even in /W4 mode.

However, if you expect suchlevel for you code, then you should ask for the same level to the compiler by at leastdisabling the Visual C++ language extensions (/Za) which generates warnings whenused. If these extensions are enabled, then GLM will take advantage of them and thecompiler will generate warnings.7. Code samplesThis series of samples only shows various GLM features without consideration of anysort.7.1.

Compute a triangle normal#include <glm/glm.hpp> // vec3 normalize crossglm::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> // fastNormalizeglm::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, i32vec2std::size_t const VertexCount = 4;// Float quad geometrystd::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 geometrystd::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 geometrystd::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 geometrystd::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 vec3glm::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.

References8.1. GLM development- GLM website- GLM HEAD snapshot- GLM bug report and feature request- G-Truc Creation’s page8.2. OpenGL specifications- OpenGL 4.3 core specification- GLSL 4.30 specification- GLU 1.3 specification8.3. External links- The OpenGL Toolkits forum to ask questions about GLM8.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 resolutionusing fractal algorithms.- opencloth:A collection of source codes implementing cloth simulation algorithms in OpenGL.- OpenGL 4.0 Shading Language Cookbook:A full set of recipes demonstrating simpleand advanced techniques for producinghigh-quality, real-time 3D graphics usingGLSL 4.0.How to use the OpenGL Shading Languageto implement lighting and shadingtechniques.Use the new features of GLSL 4.0including tessellation and geometryshaders.How to use textures in GLSL as part of awide variety of techniques from basictexture mapping to deferred shading.Simple, easy-to-follow examples withGLSL source code, as well as a basicdescription of the theory behind eachtechnique.- Are you using GLM in a project?8.5.

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

Тип файла
PDF-файл
Размер
976,21 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
Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
7027
Авторов
на СтудИзбе
260
Средний доход
с одного платного файла
Обучение Подробнее