glm (1125871)

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

Текст из файла

Manual

Version 0.9.4

22 February 2013

Christophe Riccio

glm@g-truc.net

Copyright © 2005–2013, G-Truc Creation

Copyright (c) 2005 - 2013 G-Truc Creation (www.g-truc.net)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.



Contents

Introduction 5

1. Getting started 6

1.1. Setup 6

1.2. Use sample of GLM core 6

1.3. Dependencies 6

1.4. GLM Extensions 6

1.5. OpenGL interoperability 7

1.6. GLM for CUDA 7

2. Advanced usages 8

2.1. Swizzle operators 8

2.2. Notification system 10

2.3. Force inline 10

2.4. SIMD support 11

2.5. Compatibility 11

2.6. Default precision 11

2.7. Force use of radians 12

3. Deprecated function replacements 13

3.1. OpenGL functions (Section 2.11.2 Matrices, OpenGL 2.1 specification) 13

3.2. GLU functions (Chapter 4: Matrix Manipulation, GLU 1.3 specification) 14

4. Extensions 17

4.1. GLM_GTC_constants 17

4.2. GLM_GTC_epsilon 17

4.3. GLM_GTC_half_float 17

4.4. GLM_GTC_matrix_access 17

4.5. GLM_GTC_matrix_integer 17

4.6. GLM_GTC_matrix_inverse 17

4.7. GLM_GTC_matrix_transform 17

4.8. GLM_GTC_noise 18

4.9. GLM_GTC_quaternion 21

4.10. GLM_GTC_random 21

4.11. GLM_GTC_reciprocal 23

4.12. GLM_GTC_swizzle 23

4.13. GLM_GTC_type_precision 23

4.14. GLM_GTC_type_ptr 24

4.15. GLM_GTC_ulp 24

5. Known issues 25

5.1. not function 25

5.2. half based types and component accesses 25

6. FAQ 26

6.1 Why GLM follows GLSL specification and conventions? 26

6.2. Does GLM run GLSL program? 26

6.3. Does a GLSL compiler build GLM codes? 26

6.4. Should I use ‘GTX’ extensions? 26

6.5. Where can I ask my questions? 26

6.6. Where can I find the documentation of extensions? 26

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

6.8. Is GLM fast? 26

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

7. Code samples 28

7.1. Compute a triangle normal 28

7.2. Matrix transform 28

7.3. Vector types 29

7.4. Lighting 29

8. References 31

8.1. GLM development 31

8.2. OpenGL specifications 31

8.3. External links 31

8.4. Projects using GLM 31

8.5. OpenGL tutorials using GLM 33

8.6. Alternatives to GLM 33

8.7. Acknowledgements 33

8.8. Quotes from the web 33



Introduction

OpenGL Mathematics (GLM) is a C++ mathematics library for graphics software based on the OpenGL Shading Language (GLSL) specification.

GLM provides classes and functions designed and implemented with the same naming conventions and functionalities than GLSL so that when a programmer knows GLSL, he knows GLM as well which makes it really easy to use.

This project isn't limited by GLSL features. An extension system, based on the GLSL extension conventions, provides extended capabilities: matrix transformations, quaternions, half-based types, random numbers, etc...

This library works perfectly with OpenGL but it also ensures interoperability with other third party libraries and SDK. It is a good candidate for software rendering (Raytracing / Rasterisation), image processing, physic simulations and any context that requires a simple and convenient mathematics library.

GLM is written in C++98 but can take advantage of C++11 when supported by the compiler. It is a platform independent library with no dependence and officially supports 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 compiler

The source code and the documentation, including this manual, are licensed under the MIT license.

Thanks for contributing to the project by submitting tickets for bug reports and feature requests. Any feedback is welcome at glm@g-truc.net.

1. Getting started

1.1. Setup

GLM is a header only library; there is nothing to build to use it which increases its cross 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 design may significantly increase the compile time for files that use GLM. Precompiled headers 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. Dependencies

When <glm/glm.hpp> is included, GLM provides all the GLSL features it implements in 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> is included, Boost static assert will be used all over GLM code to provide compiled time errors unless GLM is built with a C++ 11 compiler in which case static_assert.

1.4. GLM Extensions

GLM 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. Once included, 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 interoperability

It could be possible to implement glVertex3fv(glm::vec3(0)) in C++ with the appropriate cast operator. It would result as a transparent cast in this example; however cast operator may result of programs running with unexpected behaviours without 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 CUDA

GLM 0.9.2 introduces CUDA compiler support allowing programmer to use GLM inside a CUDA Kernel. This support is automatic when a GLM header is included inside a CUDA kernel. If necessary, a user can decided to force this support by defining 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 if used in a CUDA kernel.

2. Advanced usages

2.1. Swizzle operators

A common feature of shader languages like GLSL is components swizzling. This involves being able to select which components of a vector are used and in what order. For example, “variable.x”, “variable.xxy”, “variable.zxyy” are examples of swizzling.

vec4 A;

vec2 B;

...

B.yx = A.wy;

B = A.xx;

This functionality turns out to be really complicated, not to say impossible, to implement in C++ using the exact GLSL conventions. GLM provides three implementations for this feature.

C++98 implementation

The C++98 implementation exposes the swizzle operator as member functions of vector 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++98 implementation is compatible with the C++11 implementation so that building code using 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 and glm::vec4) when the swizzle operators are used as r-values. Instead, the swizzle functions return reference types (glm::ref2, glm::ref3 and glm::ref4). Hence, when the reference type objects are generated, these objects can’t be used directly with 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::vec4

glm::vec4 Clamped = glm::clamp(

glm::vec4(ColorRGBA.bgra() = ColorRGBA), 0.f, 1.f);

}

C++11 implementation

The C++11 implementation follows the GLSL conventions accurately but it is disabled by default. To enable this implementation, GLM_SWIZZLE has to be defined before any 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-value

ColorRGBA.bgra = ColorRGBA.rgba;

}

Note: Swizzle functions doesn’t return vector types (glm::vec2, glm::vec3 and glm::vec4) when the swizzle operators are used as r-values. Instead, the swizzle functions return reference types (glm::ref2, glm::ref3 and glm::ref4). Hence, when the reference type objects are generated, these objects can’t be used directly with 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::vec4

glm::vec4 ClampedA = glm::clamp(

glm::vec4(ColorRGBA.bgra = ColorRGBA), 0.f, 1.f);

// Need to cast the swizzle operator into glm::vec4 (alternative method)

glm::vec4 ClampedB = glm::clamp(

(ColorRGBA.bgra = ColorRGBA)(), 0.f, 1.f);

// Need to cast the swizzle operator into glm::vec4

glm::vec4 ClampedC = glm::clamp(ColorRGBA.bgra(), 0.f, 1.f);

}

Extension implementation

A safer way to do swizzling is to use the extension GLM_GTC_swizzle. In term of features, this extension is at the same level than GLSL expect that GLM support both static and dynamic swizzling where GLSL only support static swizzling.

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

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

Тип файла документ

Документы такого типа открываются такими программами, как Microsoft Office Word на компьютерах Windows, Apple Pages на компьютерах Mac, Open Office - бесплатная альтернатива на различных платформах, в том числе Linux. Наиболее простым и современным решением будут Google документы, так как открываются онлайн без скачивания прямо в браузере на любой платформе. Существуют российские качественные аналоги, например от Яндекса.

Будьте внимательны на мобильных устройствах, так как там используются упрощённый функционал даже в официальном приложении от Microsoft, поэтому для просмотра скачивайте PDF-версию. А если нужно редактировать файл, то используйте оригинальный файл.

Файлы такого типа обычно разбиты на страницы, а текст может быть форматированным (жирный, курсив, выбор шрифта, таблицы и т.п.), а также в него можно добавлять изображения. Формат идеально подходит для рефератов, докладов и РПЗ курсовых проектов, которые необходимо распечатать. Кстати перед печатью также сохраняйте файл в PDF, так как принтер может начудить со шрифтами.

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

решение
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
Средний доход
с одного платного файла
Обучение Подробнее