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

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

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

It is a good candidate for software rendering(Raytracing / Rasterisation), image processing, physic simulations and any contextthat requires a simple and convenient mathematics library.GLM is written in C++98 but can take advantage of C++11 when supported by thecompiler. It is a platform independent library with no dependence and officiallysupports the following compilers:● Clang 2.6 and higher● CUDA 3.0 and higher● GCC 3.4 and higher● Intel C++ Composer XE 2013 and higher● LLVM 2.3 through GCC 4.2 front-end and higher● Visual Studio 2005 and higher● Any conform C++98 or C++11 compilerThe source code and the documentation, including this manual, are licensed underthe MIT license.Thanks for contributing to the project by submitting tickets for bug reports andfeature requests.

Any feedback is welcome at glm@g-truc.net.1. Getting started1.1. SetupGLM is a header only library; there is nothing to build to use it which increases itscross platform capabilities. To use GLM, a programmer only has to include<glm/glm.hpp>. This provides all the GLSL features implemented by GLM.GLM is a header only library that makes heavy usages of C++ templates. This designmay significantly increase the compile time for files that use GLM. Precompiledheaders are recommended to avoid this issue.1.2. Use sample of GLM core#include <glm/glm.hpp>int foo(){glm::vec4 Position = glm::vec4(glm::vec3(0.0), 1.0);glm::mat4 Model = glm::mat4(1.0);Model[3] = glm::vec4(1.0, 1.0, 0.0, 1.0);glm::vec4 Transformed = Model * Position;return 0;}1.3.

DependenciesWhen <glm/glm.hpp> is included, GLM provides all the GLSL features it implementsin C++.When an extension is included, all the dependent extensions will be included as well.All the extensions depend on GLM core. (<glm/glm.hpp>)There is no dependence with external libraries or external headers like gl.h,glcorearb.h, gl3.h, glu.h or windows.h. However, if <boost/static_assert.hpp> isincluded, Boost static assert will be used all over GLM code to provide compiled timeerrors unless GLM is built with a C++ 11 compiler in which case static_assert.1.4.

GLM ExtensionsGLM extends the core GLSL feature set with extensions. These extensions include:quaternion, transformation, spline, matrix inverse, color spaces, etc.To include an extension, we only need to include the dedicated header file. Onceincluded, the features are added to the GLM namespace.#include <glm/glm.hpp>#include <glm/gtc/matrix_transform.hpp>int foo(){glm::vec4 Position = glm::vec4(glm:: vec3(0.0f), 1.0f);glm::mat4 Model = glm::translate(glm::mat4(1.0f), glm::vec3(1.0f));glm::vec4 Transformed = Model * Position;…return 0;}1.5.

OpenGL interoperabilityIt could be possible to implement glVertex3fv(glm::vec3(0)) in C++ with theappropriate cast operator. It would result as a transparent cast in this example;however cast operator may result of programs running with unexpected behaviourswithout build error or any notification.GLM_GTC_type_ptr extension provides a safe solution:#include <glm/glm.hpp>#include <glm/gtc/type_ptr.hpp>void foo(){glm::vec4 v(0.0f);glm::mat4 m(1.0f);...glVertex3fv(glm::value_ptr(v))glLoadMatrixfv(glm::value_ptr(m));}Another solution inspired by STL:#include <glm/glm.hpp>void foo(){glm::vec4 v(0.0f);glm::mat4 m(1.0f);...glVertex3fv(&v[0]);glLoadMatrixfv(&m[0][0]);}1.6. GLM for CUDAGLM 0.9.2 introduces CUDA compiler support allowing programmer to use GLMinside a CUDA Kernel.

This support is automatic when a GLM header is includedinside a CUDA kernel. If necessary, a user can decided to force this support bydefining GLM_FORCE_CUDA before any inclusion of <glm/glm.hpp>.#define GLM_FORCE_CUDA#include <glm/glm.hpp>Some GLM functionalities might not be available and will return an error message ifused in a CUDA kernel.2. Advanced usages2.1. Swizzle operatorsA common feature of shader languages like GLSL is components swizzling. Thisinvolves being able to select which components of a vector are used and in whatorder. For example, “variable.x”, “variable.xxy”, “variable.zxyy” are examples ofswizzling.vec4 A;vec2 B;...B.yx = A.wy;B = A.xx;This functionality turns out to be really complicated, not to say impossible, toimplement in C++ using the exact GLSL conventions.

GLM provides threeimplementations for this feature.C++98 implementationThe C++98 implementation exposes the swizzle operator as member functions ofvector types but it remains disabled by default. To enable this implementation,GLM_SWIZZLE has to be defined before any inclusion of <glm/glm.hpp>. The C++98implementation is compatible with the C++11 implementation so that building codeusing this implementation wrong break on a C++11 compiler.#define GLM_SWIZZLE#include <glm/glm.hpp>void foo(){glm::vec4 ColorRGBA(1.0f, 0.5f, 0.0f, 1.0f);glm::vec4 ColorBGRA = ColorRGBA.bgra();…ColorRGBA.bgra() = ColorRGBA;ColorRGBA.bgra() = ColorRGBA.rgba();…}Note: Swizzle functions doesn’t return vector types (glm::vec2, glm::vec3 andglm::vec4) when the swizzle operators are used as r-values.

Instead, the swizzlefunctions return reference types (glm::ref2, glm::ref3 and glm::ref4). Hence,when the reference type objects are generated, these objects can’t be used directlywith a GLM functions and need to be cast into vector types.#define GLM_SWIZZLE#include <glm/glm.hpp>void foo(){glm::vec4 Color(1.0f, 0.5f, 0.0f, 1.0f);…// Need to cast the swizzle operator into glm::vec4glm::vec4 Clamped = glm::clamp(glm::vec4(ColorRGBA.bgra() = ColorRGBA), 0.f, 1.f);…}C++11 implementationThe C++11 implementation follows the GLSL conventions accurately but it is disabledby default. To enable this implementation, GLM_SWIZZLE has to be defined beforeany inclusion of <glm/glm.hpp> and a C++11 compiler need to be used.#define GLM_SWIZZLE#include <glm/glm.hpp>void foo(){glm::vec4 ColorRGBA(1.0f, 0.5f, 0.0f, 1.0f);…// l-value:glm::vec4 ColorBGRA = ColorRGBA.bgra;// r-value:ColorRGBA.bgra = ColorRGBA;// Both l-value and r-valueColorRGBA.bgra = ColorRGBA.rgba;…}Note: Swizzle functions doesn’t return vector types (glm::vec2, glm::vec3 andglm::vec4) when the swizzle operators are used as r-values.

Instead, the swizzlefunctions return reference types (glm::ref2, glm::ref3 and glm::ref4). Hence,when the reference type objects are generated, these objects can’t be used directlywith a GLM functions and need to be cast into vector types.#define GLM_SWIZZLE#include <glm/glm.hpp>void foo(){glm::vec4 Color(1.0f, 0.5f, 0.0f, 1.0f);…// Need to cast the swizzle operator into glm::vec4glm::vec4 ClampedA = glm::clamp(glm::vec4(ColorRGBA.bgra = ColorRGBA), 0.f, 1.f);// Need to cast the swizzle operator into glm::vec4 (alternativemethod)glm::vec4 ClampedB = glm::clamp((ColorRGBA.bgra = ColorRGBA)(), 0.f, 1.f);// Need to cast the swizzle operator into glm::vec4glm::vec4 ClampedC = glm::clamp(ColorRGBA.bgra(), 0.f, 1.f);…}Extension implementationA safer way to do swizzling is to use the extension GLM_GTC_swizzle.

In term offeatures, this extension is at the same level than GLSL expect that GLM support bothstatic and dynamic swizzling where GLSL only support static swizzling.Static swizzling is an operation which is resolved at build time but dynamic swizzlingis revolved at runtime which is more flexible but slower especially when SSEoptimisations are used.#include <glm/glm.hpp>#include <glm/gtc/swizzle.hpp>void foo(){glm::vec4 ColorRGBA(1.0f, 0.5f, 0.0f, 1.0f);…// Dynamic swizzling (at run time, more flexible)// l-value:glm::vec4 ColorBGRA1 =glm::swizzle(ColorRGBA, glm::B, glm::G, glm::R, glm::A);// r-value:glm::swizzle(ColorRGBA, glm::B, glm::G, glm::R, glm::A) = ColorRGBA;// Static swizzling (at build time, faster)// l-value:glm::vec4 ColorBGRA2 =glm::swizzle<glm::B, glm::G, glm::R, glm::A>(ColorRGBA);// r-value:glm::swizzle<glm::B, glm::G, glm::R, glm::A>(ColorRGBA) = ColorRGBA;}2.2. Notification systemGLM includes a notification system which can display some information at buildtime:- Compiler- Build model: 32bits or 64 bits- C++ version- Architecture: x86, SSE, AVX, etc.- Included extensions- etc.This system is disabled by default.

To enable this system, define GLM_MESSAGES beforeany inclusion of <glm/glm.hpp>.#define GLM_MESSAGES#include <glm/glm.hpp>2.3. Force inlineTo push further the software performance, a programmer can defineGLM_FORCE_INLINE before any inclusion of <glm/glm.hpp> to force the compiler toinline GLM code.#define GLM_FORCE_INLINE#include <glm/glm.hpp>2.4. SIMD supportGLM provides some SIMD optimization based on compiler intrinsics. Theseoptimizations will be automatically utilized based on the build environment. Theseoptimizations are mainly available through extensions, GLM_GTX_simd_vec4 andGLM_GTX_simd_mat4.A programmer can restrict or force instruction sets used for these optimizationsusing GLM_FORCE_SSE2 or GLM_FORCE_AVX.A programmer can discard the use of intrinsics by defining GLM_FORCE_PURE beforeany inclusion of <glm/glm.hpp>.

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

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