├── .gitignore ├── README.md ├── cp ├── ch02.md └── ch07.md ├── cpp_concurrency_in_action ├── CMakeLists.txt ├── README.md ├── condition_variable_example.h ├── hierarchical_mutex.h ├── main.cc ├── parallel_accumulate.h ├── threadsafe_map.h ├── threadsafe_queue.h ├── threadsafe_stack.h └── threadsafe_swap.h ├── js ├── index.html └── object.js ├── learningOpenCV ├── 01-Exercises.md ├── 01-Overview.md ├── 02-Introduction-to-OpenCV.md ├── 03-Getting-to-Know-OpenCV-Data-Types.md └── Preface.md ├── open.gl ├── .gitignore ├── Exercise │ ├── 11 │ │ ├── 11.vcxproj │ │ ├── 11.vcxproj.filters │ │ └── main.cpp │ ├── 12 │ │ ├── 12.vcxproj │ │ ├── 12.vcxproj.filters │ │ └── main.cpp │ ├── 13 │ │ ├── 13.vcxproj │ │ ├── 13.vcxproj.filters │ │ └── main.cpp │ ├── 21 │ │ ├── 21.vcxproj │ │ ├── 21.vcxproj.filters │ │ └── main.cpp │ ├── 22 │ │ ├── 22.vcxproj │ │ ├── 22.vcxproj.filters │ │ └── main.cpp │ ├── 51 │ │ ├── 51.vcxproj │ │ ├── 51.vcxproj.filters │ │ └── main.cpp │ ├── 01 │ │ ├── 01.vcxproj │ │ ├── 01.vcxproj.filters │ │ └── main.cpp │ ├── 02 │ │ ├── 02.vcxproj │ │ ├── 02.vcxproj.filters │ │ └── main.cpp │ ├── 03 │ │ ├── 03.vcxproj │ │ ├── 03.vcxproj.filters │ │ └── main.cpp │ ├── Exercise.sln │ ├── debug.cpp │ └── image │ │ ├── sample.png │ │ └── sample2.png └── README.md └── tdd_py ├── note.md └── superlists ├── functional_tests.py ├── lists ├── admin.py ├── apps.py ├── models.py ├── tests.py └── views.py ├── manage.py └── superlists ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | .DS_Store 3 | *.log 4 | __pycache__/ 5 | db.sqlite3 6 | __init__.py 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Reading Notes 2 | 3 | ## Reading 4 | 5 | - [ ] [C++ Primer 5th](http://book.douban.com/subject/24089577/) 6 | - [x] Chapter 1. Getting Started 7 | - [x] Chapter 2. Variables and Basic Types 8 | - [x] Chapter 3. Strings, Vectors, and Arrays 9 | - [x] Chapter 4. Expressions 10 | - [x] Chapter 5. Statements 11 | - [x] Chapter 6. Functions 12 | - [x] Chapter 7. Classes 13 | - [x] Chapter 8. The IO Library 14 | - [x] Chapter 9. Sequential Containers 15 | - [x] Chapter 10. Generic Algorithms 16 | - [x] Chapter 11. Associative Containers 17 | - [x] Chapter 12. Dynamic Memory 18 | - [x] Chapter 13. Copy Control 19 | - [x] Chapter 14. Overloaded Operations and Conversions 20 | - [x] Chapter 15. Object-Oriented Programming 21 | - [x] Chapter 16. Templates and Generic Programming 22 | - [ ] Chapter 17. Specialized Library Facilities 23 | - [ ] Chapter 18. Tools for Large Programs 24 | - [ ] Chapter 19. Specialized Tools and Techniques 25 | 26 | - [ ] [Learning OpenCV 3](http://shop.oreilly.com/product/0636920044765.do) 27 | - [x] Chapter 1 Overview 28 | - [x] Chapter 2 Introduction to OpenCV 29 | - [ ] Chapter 3 Getting to Know OpenCV Data Types 30 | - [ ] Chapter 4 Images and Large Array Types 31 | - [ ] Chapter 5 Array Operations 32 | - [ ] Chapter 6 Drawing and Annotating 33 | - [ ] Chapter 7 Functors in OpenCV 34 | - [ ] Chapter 8 Image, Video, and Data Files 35 | - [ ] Chapter 9 Cross-Platform and Native Windows 36 | - [ ] Chapter 10 Filters and Convolution 37 | - [ ] Chapter 11 General Image Transforms 38 | - [ ] Chapter 12 Image Analysis 39 | - [ ] Chapter 13 Histograms and Templates 40 | - [ ] Chapter 14 Contours 41 | - [ ] Chapter 15 Background Subtraction 42 | - [ ] Chapter 16 Keypoints and Descriptors 43 | - [ ] Chapter 17 Tracking 44 | - [ ] Chapter 18 Camera Models and Calibration 45 | - [ ] Chapter 19 Projection and Three-Dimensional Vision 46 | - [ ] Chapter 20 The Basics of Machine Learning in OpenCV 47 | - [ ] Chapter 21 StatModel: The Standard Model for Learning in OpenCV 48 | - [ ] Chapter 22 Object Detection 49 | - [ ] Chapter 23 Future of OpenCV 50 | 51 | ------ 52 | 53 | ## Todo 54 | 55 | - [MIT 算法导论](http://open.163.com/special/opencourse/algorithms.html) 56 | - [6.042J Mathematics for Computer Science](http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-042j-mathematics-for-computer-science-fall-2010/) 57 | - 研究并总结深度优先搜索与广度优先搜索(从树和图的角度全面的去看) 58 | - [6.837 Computer Graphics](http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-837-computer-graphics-fall-2012/index.htm) 59 | - [6.006 Introduction to Algorithms](http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/) 60 | 61 | ------ 62 | 63 | ## Cache 64 | 65 | - Rust 66 | - 67 | - 68 | - 69 | - 70 | - 71 | 72 | - C/C++ 73 | - 74 | 75 | - Graphics 76 | - 77 | - [SDL Tutorials](http://lazyfoo.net/tutorials/SDL/index.php) 78 | 79 | - Math 80 | - [Calculus II(GIR)](http://ocw.mit.edu/courses/mathematics/18-02-multivariable-calculus-fall-2007/) 81 | - [Linear Algebra](http://ocw.mit.edu/courses/mathematics/18-06-linear-algebra-spring-2010/index.htm) 82 | - [线性代数中文版](http://v.163.com/special/opencourse/daishu.html) 83 | 84 | - DataBase 85 | - [Database System Implementation](http://web.stanford.edu/class/cs346/) 86 | 87 | - Data Structure 88 | - [Open Data Structures](http://opendatastructures.org/) 89 | 90 | - JavaScript 91 | - [Head First JavaScript](http://book.douban.com/subject/2372267/) 92 | - [JavaScript: The Definitive Guide, 5th](http://book.douban.com/subject/1775608/) 93 | - [Secrets of the JavaScript Ninja](http://book.douban.com/subject/3176860/) 94 | 95 | - Python 96 | - [人人都懂的编程课 python](https://www.coursera.org/course/pythonlearn) 97 | 98 | - OS 99 | - [Berkeley CS162: Operating Systems and Systems Programming](http://cs162.eecs.berkeley.edu/) 100 | -------------------------------------------------------------------------------- /cp/ch02.md: -------------------------------------------------------------------------------- 1 | # Chapter 2. Variables and Basic Types 2 | 3 | ## 名不正言不顺 4 | 5 | 曾在 Stackoverflow 上 po 过[一个问题](http://stackoverflow.com/questions/26711536/initializing-a-stdvector-from-a-count-and-an-element-value-with-copies),引起了一些争论。也引起了我对于一些叫法的注意。 6 | 7 | 2.2.1. Variable Definitions 里面有一小节提了这个问题: 8 | > Terminology: What is an Object? 9 | > 10 | > C++ programmers tend to be cavalier in their use of the term object. Most generally, an object is a region of memory that can contain data and has a type. 11 | > 12 | > Some use the term object only to refer to variables or values of class types. Others distinguish between named and unnamed objects, using the term variable to refer to named objects. Still others distinguish between objects and values, using the term object for data that can be changed by the program and the term value for data that are read-only. 13 | > 14 | > In this book, we’ll follow the more general usage that an object is a region of memory that has a type. We will freely use the term object regardless of whether the object has built-in or class type, is named or unnamed, or can be read or written. 15 | 16 | **对象**:一段内存,type + data; 17 | 18 | - 习惯一:管**类**的变量或值才叫对象。(这也是我们通常所理解的) 19 | - 习惯二:区分**有名对象**与**无名对象**,管前者叫变量(variable)。 20 | - 习惯三:区分**对象**与**值**,前者是程序里可以改变的数据,后者是只读数据(也就是**字面量**)。 21 | 22 | 遵从上述叫法习惯,更利于沟通。 23 | 24 | ## 靡不有初 25 | 26 | **初始化**的事情其实也算是CP5的一条隐线了。这一章节仅仅涉及POD的初始化,在下一章节会涉及string与vector. 后续又有别的容器,但都大同小异了。到16章,会更深入的讨论。 27 | 28 | 在这里,我们仅需知道四种基本形态: 29 | 30 | ```cpp 31 | int i = 0; 32 | int i = {0}; 33 | int i{0}; 34 | int i(0); 35 | ``` 36 | 37 | 前两种有=,是典型assignment,后两种才可以称为是initialization。 38 | 39 | ()与{}:{}是C++11出来的东西。它的一大好处在于:**帮你检查类型** 40 | 41 | ```cpp 42 | double d = 3.14; 43 | int i{d}, j = {d}; // error: narrowing conversion required 44 | ``` 45 | 46 | ----- 47 | 48 | 另外,值得一提的是,**字面量与类型**的对应关系: 49 | 50 | - 1,2,3,4... ----> int(默认的整型都是int) 51 | - 0.1,0.2,3.14 --> double(默认的浮点都是double) 52 | 53 | ----- 54 | 55 | 默认初始化,由两个东西决定:**类型与位置**,也就是**是谁与在哪**的问题。 56 | 57 | |type|outside function body|inside function body| 58 | |----|---------------------|--------------------| 59 | |built-in type|intiailzed to 0|uninitialized and value is undefined| 60 | |class type|value defined by class|value defined by class| 61 | 62 | >Note 63 | > 64 | >Uninitialized objects of built-in type defined inside a function body have undefined value. Objects of class type that we do not explicitly initialize have a value that is defined by the class. 65 | -------------------------------------------------------------------------------- /cp/ch07.md: -------------------------------------------------------------------------------- 1 | # Chapter 7. Classes 2 | 3 | 说到 Class, 就不得不提两个概念:**抽象(data abstraction)**和**封装(encapsulation)**。 4 | 5 | 何谓**抽象**?就是程序语言中一种**将接口(interface)与实现(implementation)相分离**的技术。何谓**封装**?就是对上述技术的一种具体实践。所以我们可以说,是封装实践了抽象。抽象是一种思想,封装是一种手段。 6 | 7 | 经过封装,我们可以定义出一种抽象的数据结构,用户不必关心其内部实现,只需要考虑用它做什么。从而抽身繁琐的细节实现中,将注意力集中在具体需求上。 8 | 9 | ----- 10 | 11 | 更深一步思考,抽象这个思想是怎么来的?这和人类的大脑结构有关,即使是聪明绝顶的人,也无法做到事无巨细的考虑某个复杂的问题。面对复杂的问题,我们首先想到的应该是如何将其细分,用术语来说,就是**分治法**。这是最核心的一种算法思想,我们都知道算法的定义,本质是一套步骤,第一步干什么,第二步干什么,一个清单一样的东西,而这些步骤,其实就是**分而治之**的一种体现。这与军事上讲的“各个击破”,政治上讲的“连横”都是一个道理。然而,能否真正的化简复杂问题,核心在于“如何细分”,即细分的依据。 12 | 13 | 一个普遍的常识是,分清**主次、轻重、缓急**,能够有效的处理复杂的事务。具体到计算机领域,对于一个丰富经验的程序员来说,具体实现就是次、轻、缓,而理解需求,并将需求转化为领域模型、层次架构、算法结构,才是主、重、急。在学校老师常常说,写具体代码的都是流水的兵,做设计与架构的才是核心人员。这也从侧面反映了上述的主次轻重与缓急之分。 14 | 15 | 那么,领域模型考虑的是什么?说白了就是贴近业务用例的语言。下过象棋的人都知道有一个横冲直闯的“车”,这个“车”,有哪些特点?可以用它做什么?这些就是领域模型规定的事情。如,我们可以写出: 16 | 17 | 车,属性:当前位置;操作:横移,纵移,顶替在移动过程中遇到障碍物的位置。 18 | 19 | 我们描述象棋里面“车”这个东西,就要像类似上面这样,说清楚它必须具备什么属性,可以进行什么必备的操作。到这个层次就可以了。根据这个信息,系统设计人员,就可以画出总体类图了。 20 | 21 | 属性,操作,这都是面向对象中的词汇。在Java/C++里,我们一般说数据,成员(data, member)和接口(interface)、方法(function)。可统称为 interface. 22 | 23 | 那么,属性用什么数据结构记录,操作采用什么方式实现,如何与其他的棋子交互(吃与被吃),这些就是具体实现的范畴。可称为 implementation. 24 | 25 | 架构师的领域模型,直接对应着 interface 这一层,implementation 这一层却无法对应上,所以,分开他们很有必要。 26 | 27 | 综上所述,抽象是一种看全局、抓重点的思想;封装是对 interface 与 implementation 的一种分离。 28 | 29 | ----- 30 | 31 | ## 构造函数 32 | 33 | > Because we have provided a constructor, the compiler will not automatically generate a default constructor for us. 34 | 35 | 要注意,如果为一个类提供了有参的构造函数,却不标明无参的构造函数,系统**并不会为你生成一个默认的**。所以比较好的习惯是,如果有多个构造函数,最好加上下面这句: 36 | 37 | my_class() = default; 38 | 39 | ----- 40 | 41 | ```cpp 42 | class Screen { 43 | public: 44 | typedef std::string::size_type pos; 45 | private: 46 | pos cursor = 0; 47 | pos height = 0, width = 0; 48 | std::string contents; 49 | } 50 | ``` 51 | 52 | > By defining `pos` as a **public member**, we can **hide this detail of how Screen is implemented** 53 | 54 | 这一点比较有意思,合理的使用type alias,能够让封装更加的严密。还要注意它在class中的位置: 55 | 56 | > type members usually appear at the **beginning** of the class. 57 | 58 | ----- 59 | 60 | ## 拷贝、赋值与析构 61 | 62 | > Moreover, the synthesized versions for copy, assignment, and destruction work correctly for classes that have vector or string members. 63 | 64 | 如果你的类简单到成员只包含`std::string`或`std::vector`的话,这些事情就无需你操心了。 65 | 66 | ----- 67 | 68 | ## 内敛函数 69 | 70 | > inline member functions should be defined in the same header as the corresponding class definition 71 | 72 | 我觉得可以总结一个比较合适的经验:如果函数的实现仅有一行,完全可以将实现直接放到class body中,它将自动的被标记为内敛。如果超过一行,为保证可读性,应当在class body中加上inline关键字,然后在同一个头文件,class body外面,实现该函数(实现的时候最好也加上inline关键字)。 73 | 74 | ----- 75 | 76 | ## 类成员 77 | 78 | ### mutable Data Members 79 | 80 | > A `mutable` data member is never `const`, even when it is a member of a `const` object. A `mutable` member can be changed inside a `const function`. 81 | 82 | 只要被`mutable`标记的成员,永远和`const`无缘了,它竟可以不受`const`的限制。非常适合计数。 83 | 84 | ----- 85 | 86 | ### 在类定义中初始化 87 | 88 | > As we’ve seen, **in-class initializers** must use either the `=` form of initialization (which we used when we initialized the the data members of Screen) or the direct form of initialization using **curly braces** (as we do for screens) 89 | 90 | 这个行为,是C++11中才被允许的,非常的方便。两种方式,要么用 `=`,要么用 `{}`。 91 | 92 | ```cpp 93 | class Window_mgr { 94 | private: 95 | std::vector screens{Screen(24, 80, ' ') }; 96 | ``` 97 | 98 | ----- 99 | 100 | ## 不完整类型 101 | 102 | incomplete type , 表示的是**有声明但没有定义**的类型。 103 | 104 | > We can use an incomplete type in only limited ways: We can define **pointers** or **references** to such types, and we can **declare (but not define) functions** that use an incomplete type as a **parameter** or **return** type. 105 | 106 | 可以看到这种不完整类型的应用还是相当广泛的。可以定义指针,引用,可以声明函数,将其作为返回值或参数。 107 | 108 | 注:不完整类型的存在,加速了咱们的编译速度,好的实践习惯是,头文件中尽量少的include 头文件,而是多用类型声明。[**前置声明**] 109 | 110 | ## 友元 111 | 112 | > It is important to understand that friendship is not transitive 113 | 114 | 友元不具备可传递性,意味着,A 是 B 的友元, C 是 A 的友元;并不能得出 C 是 B 的友元的结论。和现实生活一致,你朋友的朋友,不一定是你的朋友。 115 | 116 | > Even if we define the function inside the class, we must still provide a declaration outside of the class itself to make that function visible 117 | 118 | 可以考虑将友元函数直接定义在 class body 里面。但是在 class 外面,还要在声明一下,才可以用。(大部分编译器可以不用这样做了) 119 | 120 | 这意味着:将友元函数直接定义在类里面,未尝不是件好事。参考: [Is it a good practice to put non member function inside a class?](http://stackoverflow.com/questions/26523892/is-it-a-good-practise-to-put-non-member-function-inside-a-class) 121 | -------------------------------------------------------------------------------- /cpp_concurrency_in_action/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required (VERSION 2.6) 2 | project (learn_cpp_concurrency) 3 | 4 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") 5 | 6 | # boost thread 7 | set(Boost_USE_STATIC_LIBS ON) 8 | set(Boost_USE_MULTITHREADED ON) 9 | set(Boost_USE_STATIC_RUNTIME OFF) 10 | find_package(Boost COMPONENTS thread) 11 | 12 | file (GLOB HEADERS ${CMAKE_CURRENT_SOURCE_DIR}/*.h) 13 | # add the executable 14 | add_executable(${PROJECT_NAME} main.cc ${HEADERS}) 15 | 16 | if (Boost_FOUND) 17 | include_directories(${Boost_INCLUDE_DIRS}) 18 | target_link_libraries(${PROJECT_NAME} ${Boost_LIBRARIES}) 19 | endif() -------------------------------------------------------------------------------- /cpp_concurrency_in_action/README.md: -------------------------------------------------------------------------------- 1 | # Notes 2 | 3 | ## About the `std::thread` object. 4 | 5 | Once you've started your thread, you need to explicitly decide whether to 6 | wait for it to finish (by **join**ing with it) or leave it to run on its own 7 | (by **detach**ing it). If you don't decide before the `std::thread` object is 8 | destoryed, then your program is terminated. 9 | 10 | > the `std::thread` destructor calls `std::terminate()`. 11 | 12 | Calling `detach()` on a `std::thread` object leaves the thread to run in the 13 | backgroud, with no direct means of communicating with it. 14 | 15 | Detached threads are often called `daemon threads` after the UNIX concept of 16 | a daemon process that runs in the backgroud without any explicit user interface. 17 | 18 | you detach a thread by calling the `detach()`, after the call completes, the 19 | `std::thread` object is no longer associated with the actual thread of execution 20 | and is therefore no longer joinable. 21 | 22 | Rather than just passing the name of the function, you can also pass in the 23 | parameter. 24 | 25 | ## About the `thread_guard` class 26 | 27 | The destructor of `thread_guard` first tests to see if the `std::thread` object 28 | is `joinable()` before calling `join()`. This is important, because `join()` 29 | can be called only once for a given thread of execution, so it would therefore 30 | be a mistake to do so if the thread had already been joined. 31 | 32 | ## Passing arguments to a thread function 33 | 34 | By default, the arguments are **copied** into internal storage, where they can 35 | be accessed by the newly created thread of execution, even if the corresponding 36 | parameter in the function is expecting a reference. 37 | 38 | Thus, consider using `std::ref` and `std::move`. 39 | 40 | The instances of `std::thread` are **movable**, even though they aren't 41 | copyable. 42 | 43 | ## Structuring code for protecting shared data 44 | 45 | > Don't pass pointers and references to protected data outside the scope of 46 | the lock, whether by returning them from a function, storing them in externally 47 | visible memory, or passing them as arguments to user-supplied functions. 48 | 49 | > In general, a lock should be held for only the minimum possible time needed to 50 | perform the required operations. 51 | 52 | `std::unique_lock` 53 | 54 | 1. move the mutex; 55 | 2. unlock at an appropriate granularity. -------------------------------------------------------------------------------- /cpp_concurrency_in_action/condition_variable_example.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | struct DataChunk { 7 | int value_ = 0; 8 | bool is_last_chunk_ = false; 9 | }; 10 | 11 | namespace Example { 12 | std::mutex mut; 13 | std::queue data_queue; 14 | std::condition_variable data_cond; 15 | 16 | void DataPrepare() { 17 | for (int i = 0; i != 20; ++i) { 18 | DataChunk data; 19 | data.value_ = i; 20 | data.is_last_chunk_ = i == 19; 21 | std::lock_guard lk(mut); 22 | data_queue.push(data); 23 | data_cond.notify_one(); 24 | } 25 | } 26 | 27 | void DataProcess() { 28 | while (true) { 29 | std::unique_lock lk(mut); 30 | data_cond.wait(lk, []{ return !data_queue.empty(); }); 31 | DataChunk data = data_queue.front(); 32 | data_queue.pop(); 33 | lk.unlock(); 34 | std::cout << "process " << data.value_ << "...\n"; 35 | if (data.is_last_chunk_) break; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /cpp_concurrency_in_action/hierarchical_mutex.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | class HierarchicalMutex { 6 | public: 7 | explicit HierarchicalMutex(unsigned long value) : hierarchy_value_(value){} 8 | void lock() { 9 | CheckForHierarchyViolation(); 10 | internal_mutex_.lock(); 11 | UpdateHierarchyValue(); 12 | } 13 | void unlock() { 14 | this_thread_hiearchy_value_ = previous_hierarchy_value_; 15 | internal_mutex_.unlock(); 16 | } 17 | bool try_lock() { 18 | CheckForHierarchyViolation(); 19 | if (!internal_mutex_.try_lock()) 20 | return false; 21 | UpdateHierarchyValue(); 22 | return true; 23 | } 24 | private: 25 | std::mutex internal_mutex_; 26 | const unsigned long hierarchy_value_; 27 | unsigned long previous_hierarchy_value_ = 0; 28 | static thread_local unsigned long this_thread_hiearchy_value_; 29 | 30 | void CheckForHierarchyViolation() { 31 | if (this_thread_hiearchy_value_ <= hierarchy_value_) { 32 | throw std::logic_error("mutex hierarchy violated"); 33 | } 34 | } 35 | void UpdateHierarchyValue() { 36 | previous_hierarchy_value_ = this_thread_hiearchy_value_; 37 | this_thread_hiearchy_value_ = hierarchy_value_; 38 | } 39 | }; 40 | 41 | thread_local unsigned long HierarchicalMutex::this_thread_hiearchy_value_(ULONG_MAX); -------------------------------------------------------------------------------- /cpp_concurrency_in_action/main.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #include "parallel_accumulate.h" 7 | #include "threadsafe_stack.h" 8 | #include "threadsafe_swap.h" 9 | #include "hierarchical_mutex.h" 10 | #include "threadsafe_map.h" 11 | #include "condition_variable_example.h" 12 | #include "threadsafe_queue.h" 13 | 14 | #define TEST_THREADSAFE_QUEUE 1 15 | 16 | template 17 | void Print(const C& c) { 18 | for (auto&& i : c) std::cout << i << " "; 19 | std::cout << std::endl; 20 | } 21 | 22 | void hello() { 23 | std::cout << "Hello Concurrent World\n"; 24 | } 25 | 26 | void simple_example() { 27 | // For the initial thread in an applicaiton, this is `main()`, 28 | // but for every other thread it's specified in the constructor of 29 | // a `std::thread` object. 30 | std::thread t(hello); 31 | 32 | // now, the thread count is two. 33 | // After the new thread has been launched, 34 | // the initial thread continues execution. 35 | // If it didn't wait for the new thread to finish, 36 | // it would merrily continue to the end of `main()` and thus end the program. 37 | // possibly before the new thread had had a chance to run. 38 | 39 | t.join(); 40 | // `join()` causes the calling thread(in main()) to wait for 41 | // the thread associated withe the `t`. 42 | } 43 | 44 | class background_task { 45 | public: 46 | void operator()() const { 47 | std::cout << "do something\n"; 48 | std::cout << "do something else\n"; 49 | } 50 | }; 51 | 52 | void callable_example() { 53 | // background_task bt; 54 | 55 | // the supplied function object is **copied** into the storage belonging 56 | // to the newly created thread of execution and invoked from there. 57 | 58 | // ```cpp 59 | // std::thread my_thread(background_task()); 60 | // ``` 61 | // declares a function `my_thread` that takes a single parameter, 62 | // and returns a std::thread object, rather than launching a new thread. 63 | 64 | // you can avoid this by nameing your function object as shown previously: 65 | std::thread my_thread{ background_task() }; 66 | // or std::thread my_thread((background_task())); 67 | // of course, you can use lambda. 68 | 69 | std::thread my_thread2([](int i) { 70 | std::cout << i << "from lambda\n"; 71 | std::cout << "else from lambda too\n"; 72 | }, 3); 73 | 74 | my_thread.join(); 75 | my_thread2.join(); 76 | } 77 | 78 | struct func { 79 | double& d_; 80 | //double d_; 81 | func(double& d) : d_(d) {} 82 | //func(double d) : d_(d) {} 83 | 84 | void operator()() { 85 | for (unsigned i = 0; i < 1000000; ++i) { 86 | std::cout << "do something (d = " << d_ << ")\n"; 87 | } 88 | } 89 | }; 90 | 91 | void do_something_in_current_thread() { 92 | std::this_thread::sleep_for(std::chrono::milliseconds(2)); 93 | throw; 94 | } 95 | 96 | void oops() { 97 | double some_local_state = 3.0; 98 | func my_func(some_local_state); 99 | std::thread t(my_func); 100 | //t.detach(); // don't wait for thread to finish. 101 | 102 | try { 103 | do_something_in_current_thread(); 104 | } 105 | catch (...) { 106 | t.join(); 107 | throw; 108 | } 109 | t.join(); 110 | } // new thread might still be running. 111 | 112 | // How to fix it? 113 | // One common way to handle this scenario is to make the thread 114 | // function self-contained and copy the data into the thread rather 115 | // than sharing the data. 116 | 117 | // Using RAII to wait for a thread to complete 118 | 119 | class thread_guard { 120 | std::thread& t_; 121 | public: 122 | explicit thread_guard(std::thread& t) : t_(t) {} 123 | ~thread_guard() { 124 | if (t_.joinable()) 125 | t_.join(); 126 | } 127 | 128 | thread_guard(const thread_guard&) = delete; 129 | thread_guard& operator=(const thread_guard&) = delete; 130 | }; 131 | 132 | void no_oops() { 133 | double some_local_state = 2.0; 134 | func my_func(some_local_state); 135 | std::thread t(my_func); 136 | thread_guard g(t); 137 | do_something_in_current_thread(); 138 | } 139 | 140 | class scoped_thread { 141 | public: 142 | explicit scoped_thread(std::thread t) : t_(std::move(t)) { 143 | if (!t_.joinable()) 144 | throw std::logic_error("No thread"); 145 | } 146 | ~scoped_thread() { 147 | t_.join(); 148 | } 149 | 150 | scoped_thread(const scoped_thread&) = delete; 151 | scoped_thread& operator=(const scoped_thread&) = delete; 152 | 153 | private: 154 | std::thread t_; 155 | }; 156 | 157 | int main() 158 | { 159 | #ifdef TEST_CALLABLE 160 | callable_example(); 161 | #endif 162 | 163 | #ifdef TEST_PARALLEL_ACCUMULATE 164 | unsigned int n = std::thread::hardware_concurrency(); 165 | std::cout << n << " concurrent threads are supported.\n"; 166 | 167 | std::vector vec{1,3,4,5,6,80,7,8,4,3,2,4,5,64,23,4,5,4,32,53,2323,23,2,23,89,67,7878,9}; 168 | auto sum = parallel_accumulate(vec.begin(), vec.end(), 0); 169 | std::cout << sum << std::endl; 170 | 171 | std::cout << std::this_thread::get_id() << std::endl; 172 | std::this_thread::sleep_for(std::chrono::milliseconds(10)); 173 | #endif 174 | 175 | #ifdef TEST_THREADSAFE_STACK 176 | ThreadSafeStack stack; 177 | 178 | std::thread productor([](ThreadSafeStack &s){ 179 | int n = 10; 180 | while (n --> 0) { 181 | s.Push(n); 182 | std::this_thread::sleep_for(std::chrono::milliseconds(2)); 183 | } 184 | }, std::ref(stack)); 185 | 186 | std::thread customer([](ThreadSafeStack &s){ 187 | while (true) { 188 | if (!s.Empty()) 189 | std::cout << *s.Pop() << std::endl; 190 | std::this_thread::sleep_for(std::chrono::milliseconds(5)); 191 | } 192 | }, std::ref(stack)); 193 | 194 | productor.join(); 195 | customer.join(); 196 | #endif 197 | 198 | #ifdef TEST_THREADSAFE_SWAP 199 | X safe_big_a(BigObject{3, 5, 7, 8, 0, 2}); 200 | X safe_big_b(BigObject{4, 6, 8, 9, 2, 1}); 201 | 202 | std::thread swap_thread([](X& lhs, X& rhs){ 203 | std::swap(lhs, rhs); 204 | }, std::ref(safe_big_a), std::ref(safe_big_b)); 205 | 206 | swap_thread.join(); 207 | 208 | Print(safe_big_a.big_object()); 209 | Print(safe_big_b.big_object()); 210 | #endif 211 | 212 | #ifdef TEST_HIERARCHICAL_MUTEX 213 | HierarchicalMutex high_level_mutex(10000); 214 | HierarchicalMutex low_level_mutex(5000); 215 | 216 | auto LowLevelFunc = [&](){ 217 | std::lock_guard lk(low_level_mutex); 218 | std::cout << "do some low level stuff..." << std::endl; 219 | }; 220 | 221 | auto HighLevelFunc = [&](){ 222 | std::lock_guard lk(high_level_mutex); 223 | std::cout << "do some low level stuff...\ndo some high level stuff..." << std::endl; 224 | }; 225 | 226 | HierarchicalMutex other_mutex(100); 227 | auto OtherStuff = [&](){ 228 | HighLevelFunc(); 229 | std::cout << "do other stuff..." << std::endl; 230 | }; 231 | 232 | std::thread thread_a([&](){ 233 | HighLevelFunc(); 234 | }); 235 | 236 | std::thread thread_b([&](){ 237 | std::lock_guard lk(other_mutex); 238 | try { 239 | OtherStuff(); 240 | } catch (std::logic_error e) { 241 | // HighLevelFunc tries to acquire the high_level_mutex, which has a value 242 | // 10000, considerably more than the current hierarchy value of 100. 243 | // The HierarchicalMutex will therefore report an error. 244 | std::cout << e.what() << std::endl; 245 | } 246 | }); 247 | 248 | thread_a.join(); 249 | thread_b.join(); 250 | #endif 251 | 252 | #ifdef TEST_THREADSAFE_MAP 253 | DnsCache cache; 254 | std::thread writer([&cache](){ 255 | cache.UpdateOrAddEntry("www.baidu.com", DnsEntry("220.181.112.244")); 256 | std::this_thread::sleep_for(std::chrono::milliseconds(2)); 257 | cache.UpdateOrAddEntry("www.sina.com", DnsEntry("66.102.251.33")); 258 | std::this_thread::sleep_for(std::chrono::milliseconds(2)); 259 | cache.UpdateOrAddEntry("www.google.com", DnsEntry("69.171.248.112")); 260 | std::this_thread::sleep_for(std::chrono::milliseconds(2)); 261 | cache.UpdateOrAddEntry("www.zhihu.com", DnsEntry("118.89.204.100")); 262 | std::this_thread::sleep_for(std::chrono::milliseconds(2)); 263 | cache.UpdateOrAddEntry("www.douban.com", DnsEntry("154.8.131.171")); 264 | std::this_thread::sleep_for(std::chrono::milliseconds(2)); 265 | }); 266 | 267 | auto view_web = [&cache](const std::string& domain) { 268 | for (int i = 0; i != 4; ++i) { 269 | const auto& entry = cache.FindEntry(domain); 270 | std::cout << (entry.ip_.empty() ? "cannot find..." : entry.ip_) << std::endl; 271 | std::this_thread::sleep_for(std::chrono::milliseconds(5)); 272 | } 273 | }; 274 | 275 | std::thread reader_douban(view_web, "www.douban.com"); 276 | std::thread reader_zhihu(view_web, "www.zhihu.com"); 277 | std::thread reader_baidu(view_web, "www.baidu.com"); 278 | 279 | writer.join(); 280 | reader_douban.join(); 281 | reader_zhihu.join(); 282 | reader_baidu.join(); 283 | #endif 284 | 285 | #ifdef TEST_CONDITION_VARIABLE_EXAMPLE 286 | std::thread data_preparetion(Example::DataPrepare); 287 | std::thread data_processing(Example::DataProcess); 288 | data_preparetion.join(); 289 | data_processing.join(); 290 | #endif 291 | 292 | #ifdef TEST_THREADSAFE_QUEUE 293 | ThreadSafeQueue data_queue; 294 | std::thread data_preparetion([&]{ 295 | for (int i = 0; i != 20; ++i) { 296 | DataChunk data; 297 | data.value_ = i; 298 | data.is_last_chunk_ = i == 19; 299 | data_queue.Push(data); 300 | } 301 | }); 302 | std::thread data_processing([&]{ 303 | while (true) { 304 | DataChunk data; 305 | data_queue.WaitAndPop(data); 306 | std::cout << "process " << data.value_ << "...\n"; 307 | if (data.is_last_chunk_) break; 308 | } 309 | }); 310 | data_preparetion.join(); 311 | data_processing.join(); 312 | #endif 313 | } 314 | -------------------------------------------------------------------------------- /cpp_concurrency_in_action/parallel_accumulate.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | template 4 | struct accumulate_block { 5 | void operator()(Iterator first, Iterator last, T& result) { 6 | result = std::accumulate(first, last, result); 7 | } 8 | }; 9 | 10 | template 11 | T parallel_accumulate(Iterator first, Iterator last, T init) { 12 | const unsigned long length = std::distance(first, last); 13 | if (!length) return init; 14 | 15 | const unsigned long min_per_thread = 25; 16 | const unsigned long max_threads = (length + min_per_thread - 1) / min_per_thread; 17 | const unsigned long hardware_threads = std::thread::hardware_concurrency(); 18 | const unsigned long num_threads = std::min(hardware_threads ? hardware_threads : 2, max_threads); 19 | const unsigned long block_size = length / num_threads; 20 | 21 | std::vector results(num_threads); 22 | std::vector threads(num_threads - 1); 23 | 24 | Iterator block_start = first; 25 | for (unsigned long i = 0; i < num_threads - 1; ++i) { 26 | Iterator block_end = block_start; 27 | std::advance(block_end, block_size); 28 | threads[i] = std::thread(accumulate_block(), block_start, block_end, std::ref(results[i])); 29 | block_start = block_end; 30 | } 31 | 32 | accumulate_block()(block_start, last, results[num_threads - 1]); 33 | std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join)); 34 | return std::accumulate(results.begin(), results.end(), init); 35 | } -------------------------------------------------------------------------------- /cpp_concurrency_in_action/threadsafe_map.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include "boost/thread.hpp" 6 | 7 | struct DnsEntry { 8 | DnsEntry() = default; 9 | DnsEntry(std::string&& ip) : ip_(std::forward(ip)) {} 10 | std::string ip_; 11 | }; 12 | 13 | class DnsCache { 14 | public: 15 | DnsEntry FindEntry(const std::string& domain) const { 16 | boost::shared_lock lk(entry_mutex_); 17 | const auto iter = entries_.find(domain); 18 | return (iter == entries_.end()) ? DnsEntry() : iter->second; 19 | } 20 | void UpdateOrAddEntry(const std::string& domain, const DnsEntry& dns_detail) { 21 | std::lock_guard lk(entry_mutex_); 22 | entries_[domain] = dns_detail; 23 | } 24 | private: 25 | std::unordered_map entries_; 26 | mutable boost::shared_mutex entry_mutex_; 27 | }; -------------------------------------------------------------------------------- /cpp_concurrency_in_action/threadsafe_queue.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | template 7 | class ThreadSafeQueue { 8 | public: 9 | ThreadSafeQueue() = default; 10 | ThreadSafeQueue(const ThreadSafeQueue& other) { 11 | std::lock_guard lk(other.mut_); 12 | data_queue_ = other.data_queue_; 13 | } 14 | void Push(T new_value) { 15 | std::lock_guard lk(mut_); 16 | data_queue_.push(new_value); 17 | data_cond_.notify_one(); 18 | } 19 | void WaitAndPop(T& value) { 20 | std::unique_lock lk(mut_); 21 | data_cond_.wait(lk, [this] { return !data_queue_.empty(); }); 22 | value = data_queue_.front(); 23 | data_queue_.pop(); 24 | } 25 | std::shared_ptr WaitAndPop() { 26 | std::unique_lock lk(mut_); 27 | data_cond_.wait(lk, [this] { return !data_queue_.empty(); }); 28 | std::shared_ptr res(std::make_shared(data_queue_.front())); 29 | data_queue_.pop(); 30 | return res; 31 | } 32 | bool try_pop(T& value) { 33 | std::lock_guard lk(mut_); 34 | if (data_queue_.empty()) return false; 35 | value = data_queue_.front(); 36 | data_queue_.pop(); 37 | return true; 38 | } 39 | std::shared_ptr try_pop() { 40 | std::lock_guard lk(mut_); 41 | if (data_queue_.empty()) return std::shared_ptr(); 42 | std::shared_ptr res(std::make_shared(data_queue_.front())); 43 | data_queue_.pop(); 44 | return res; 45 | } 46 | bool empty() const { 47 | std::lock_guard lk(mut_); 48 | return data_queue_.empty(); 49 | } 50 | 51 | private: 52 | mutable std::mutex mut_; 53 | std::queue data_queue_; 54 | std::condition_variable data_cond_; 55 | }; 56 | -------------------------------------------------------------------------------- /cpp_concurrency_in_action/threadsafe_stack.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | struct EmptyStack : std::exception { 7 | const char* what() const throw() { 8 | return "empty stack"; 9 | } 10 | }; 11 | 12 | template 13 | class ThreadSafeStack { 14 | public: 15 | ThreadSafeStack(){} 16 | ThreadSafeStack(const ThreadSafeStack& other) { 17 | std::lock_guard lock(other.m_); 18 | data_ = other.data_; 19 | } 20 | ThreadSafeStack& operator=(const ThreadSafeStack&) = delete; 21 | 22 | void Push(T new_value){ 23 | std::lock_guard lock(m_); 24 | data_.push(new_value); 25 | } 26 | std::shared_ptr Pop(){ 27 | std::lock_guard lock(m_); 28 | if (data_.empty()) throw EmptyStack(); 29 | const std::shared_ptr res(std::make_shared(data_.top())); 30 | data_.pop(); 31 | return res; 32 | } 33 | void Pop(T& value){ 34 | std::lock_guard lock(m_); 35 | if (data_.empty()) throw EmptyStack(); 36 | value = data_.top(); 37 | data_.pop(); 38 | } 39 | bool Empty() const { 40 | std::lock_guard lock(m_); 41 | return data_.empty(); 42 | } 43 | 44 | private: 45 | std::stack data_; 46 | mutable std::mutex m_; 47 | }; -------------------------------------------------------------------------------- /cpp_concurrency_in_action/threadsafe_swap.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef std::vector BigObject; 4 | 5 | class X { 6 | public: 7 | X() = default; 8 | X(const X& other) : big_object_(other.big_object_) {} 9 | X& operator=(X x) { 10 | swap(*this, x); 11 | return *this; 12 | } 13 | X(const BigObject& b) : big_object_(b) {} 14 | friend void swap(X& lhs, X& rhs) { 15 | if (&lhs == &rhs) 16 | return; 17 | // attempting to acquire a lock on a `std::mutex` when you already hold it 18 | // **is undefined behavior**. 19 | std::lock(lhs.m_, rhs.m_); 20 | // `std::lock` can lock a series of calls to lock. 21 | std::lock_guard lock_a(lhs.m_, std::adopt_lock); 22 | std::lock_guard lock_b(rhs.m_, std::adopt_lock); 23 | // or using `std::unique_lock` 24 | // std::unique_lock lock_a(lhs.m_, std::defer_lock); 25 | // std::unique_lock lock_b(lhs.m_, std::defer_lock); 26 | // std::lock(lock_a, lock_b); 27 | // `std::adopt_lock` indicates to the `std::lock_guard` objects that the 28 | // mutexes are already locked. 29 | swap(lhs.big_object_, rhs.big_object_); 30 | } 31 | 32 | const BigObject& big_object() const { 33 | return big_object_; 34 | } 35 | private: 36 | BigObject big_object_; 37 | std::mutex m_; 38 | }; 39 | 40 | class Y { 41 | public: 42 | Y(int sd) : some_detail_(sd) {} 43 | friend bool operator==(const Y& lhs, const Y& rhs) { 44 | if (&lhs == &rhs) 45 | return true; 46 | const int lhs_value = lhs.get_detail(); 47 | const int rhs_value = rhs.get_detail(); 48 | return lhs_value == rhs_value; 49 | } 50 | 51 | private: 52 | int get_detail() const { 53 | std::lock_guard lk(m_); 54 | return some_detail_; 55 | } 56 | 57 | int some_detail_; 58 | mutable std::mutex m_; 59 | }; -------------------------------------------------------------------------------- /js/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Test JavaScript 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /js/object.js: -------------------------------------------------------------------------------- 1 | var person = new Object; 2 | person.name = "pezy"; 3 | 4 | function test() { 5 | alert(person.name); 6 | } -------------------------------------------------------------------------------- /learningOpenCV/01-Exercises.md: -------------------------------------------------------------------------------- 1 | # Exercises 2 | 3 | ## Download and install the latest release of OpenCV. Compile it in debug and release mode 4 | 5 | Download from , then same as using Git. 6 | 7 | ## Download and build the latest trunk version of OpenCV using Git 8 | 9 | In Windows: 10 | 11 | ```sh 12 | cd c: 13 | mkdir opencv && cd opencv 14 | git clone git@github.com:opencv/opencv.git source 15 | ``` 16 | 17 | 1. open CMake(cmake-gui). 18 | 1. drag the CMakeLists.txt(in source) to it. 19 | 1. set build path, `C:/opencv/build` for me. 20 | 1. check Advanced, then Configure. 21 | 1. choose `Visual Studio 14 2015 Win64` for me. 22 | 1. chonfigure again, and check the configuration. 23 | 1. generate. 24 | 1. open `C:\opencv\build\OpenCV.sln`. 25 | 1. build `ALL_BUILD`. 26 | 1. set `Install` as active project, then build. 27 | 1. the `C:\opencv\build\install` directory would be generated. 28 | 1. set System Enviroments: `OPENCV_DIR`: `C:\opencv\build\install` 29 | 30 | Note: 31 | 32 | 1. In CMake configure, you can check `BUILD_opencv_world`, then you will get only one lib and dll. 33 | 1. You can check `BUILD_EXAMPLES`, that will let you more easy to start. 34 | 1. If you want to add more GUI feature, and the Qt is already installed, then you can check `WITH_QT`. 35 | 36 | When you check `WITH_QT`, the compiler may complain an error: `window_QT.obj : error LNK2001`, `31 linkage errors while building OpenCV_world dll` 37 | 38 | I find the solution in 39 | 40 | But we don't want to always `moc` the header in every compilation. You can do that to avoid: 41 | 42 | 1. find `Microsoft.Cpp.x64.user` in Property Manager>, then double-click it. 43 | 1. `User Macros` -> `Add Macro` -> Name: `QTDIR`, Value: `{your Qt path}`, such as `C:\Qt\Qt5.7.0\5.7\msvc2015_64`. 44 | 1. find the `window_QT.h` in Solution Explorer.(in the `modules` -> `opencv_world` -> `Src`) 45 | 1. right-click `window_QT.h` -> `properties` -> `General` -> change the `Item Type` to `Custom Build Tool`, then click the `Apply`. 46 | 1. the `Custom Build Tool` would show after apply: 47 | 1. Command Line: `"$(QTDIR)\bin\moc.exe" "%(FullPath)" -o ".\GeneratedFiles\$(ConfigurationName)\moc_%(Filename).cpp" -DUNICODE -DWIN32 -DQT_DLL -DQT_CORE_LIB -DQT_GUI_LIB -DQT_WIDGETS_LIB "-I.\GeneratedFiles" "-I." "-I$(QTDIR)\include" "-I.\GeneratedFiles\$(ConfigurationName)\." "-I$(QTDIR)\include\QtCore" "-I$(QTDIR)\include\QtGui" "-I$(QTDIR)\include\QtWidgets"` 48 | 1. Description: `Moc%27ing window_QT.h...` 49 | 1. Outputs: `.\GeneratedFiles\$(ConfigurationName)\moc_%(Filename).cpp` 50 | 1. Additional Dependencies: `$(QTDIR)\bin\moc.exe;%(FullPath)` 51 | 1. find the `Include` in Solution Explorer.(in the `modules` -> `opencv_world`) 52 | 1. right-click `Include`, and `Add` -> `New Filter`, change name to `GeneratedFiles`. then added `Debug` and `Release` filter in the `GenerateFiles`. 53 | 1. added the generated files `moc_window_QT.cpp` in `C:\opencv\build\modules\world\GeneratedFiles` to respective filter(Debug or Release). 54 | 55 | then, build again, it would be passed. 56 | 57 | When you new a project with OpenCV: 58 | 59 | 1. `Properties` -> `C/C++` -> `Additional Include Directories` -> `$(OPENCV_DIR)\include` 60 | 1. `Properties` -> `Linker` -> `Additional Library Directories` -> `$(OPENCV_DIR)\x64\vc14\lib` 61 | 1. `Properties` -> `Linker` -> `Input` -> `Additional Dependencies` -> `opencv_world330d.lib` or `opencv_world330.lib`(debug or release mode) 62 | 1. `Properties` -> `Debugging` -> `Enviroment` -> `PATH=$(OPENCV_DIR)\x64\vc14\bin%3b$(PATH)` (or `PATH=$(OPENCV_DIR)\x64\vc14\bin%3b$(QTDIR)\bin%3b$(PATH)` if with QT) 63 | 64 | ## Describe at least three ambiguous aspects of converting 3D inputs into a 2D representation. How would you overcome these ambiguities 65 | 66 | 1. variations in the world (weather, lighting, reflections, movements) 67 | 1. imperfections in the lens and mechanical setup 68 | 1. finite integration time on the sensor (motion blur) 69 | 1. electrical noise in the sensor or other electronics 70 | 1. compression artifacts after image capture 71 | -------------------------------------------------------------------------------- /learningOpenCV/01-Overview.md: -------------------------------------------------------------------------------- 1 | # 概览 2 | 3 | ## 关于 OpenCV 4 | 5 | 如果在 Intel 架构下需要进一步自动优化, 可以购买 Intel's Integrated Performance Primitives (IPP). 在 OpenCV 3.0 以后, Intel 授权给 OpenCV 团队与社区一份免费的 IPP 子集 (IPPICV), 已默认内置于 OpenCV, 为 OpenCV 提速。 6 | 7 | ## 使用 OpenCV 8 | 9 | OpenCV 的开源协议, 允许你在商业产品中使用, 并无需开源该产品或是公开实现. 当然, 如果你能那样做更好. 10 | 11 | ## 什么是计算机视觉 12 | 13 | 计算机视觉是一种数据转换, 它根据静态图片或视频, 来做出结论, 或采用一种更新的方式呈现. 所有这些转换, 都是为了某种特定的目的. 输入数据可能包含一些上下文信息, 诸如"车里安装了相机"或"激光测距仪表明一米远处有一个物体". 做出的结论可能是"场景里有一个人"或是"载玻片上有14个肿瘤细胞". 一种更新的呈现方式, 可以是将有颜色的图片, 转为灰度图, 也可以是从图像序列中移除相机运动. 14 | 15 | ## OpenCV 的一些资料 16 | 17 | - [Reference](http://docs.opencv.org/master/) 18 | - [Tutorials](http://docs.opencv.org/master/d9/df8/tutorial_root.html) 19 | - [Wiki](https://github.com/opencv/opencv/wiki) 20 | - [Q&A](http://answers.opencv.org/questions/) 21 | 22 | ## OpenCV 的主要模块 23 | 24 | - core: 基本对象类型与操作 25 | - imgproc: 基本的图像转换, 包括滤波器与近似卷积运算. 26 | - highgui: 轻量级 GUI 工具, 在 OpenCV3 中细分为 imgcodec, vidioio 和 highgui. 27 | - video: 读写视频流 28 | - calib3d: 单个相机与立体或相机组的校准算法实现 29 | - features2d: 特征点的检测, 描述与匹配算法 30 | - objdetect: 特定对象的检测, 如人脸与行人. 也可以训练探测器用来检测其他物体. 31 | - ml: 机器学习库本身就是一个独立的库, 包含一个广泛的机器学习算法, 以及兼容 OpenCV 的数据结构. 32 | - flann: 即“快速最邻近搜索库”. 33 | - gpu: 在 OpenCV3 中被拆分为多组 cuda* 模块, 包含针对 CUDA GPU 操作的优化. 有时需要提供更优秀的结果, 需要足够高的计算资源. 但在非 GPU 硬件上实用性将大大减弱. 34 | - photo: 这是一个比较新的模块, 用于可计算的摄影控制. 35 | - stitching: 该模块实现了一个复杂的图像拼接管道. 和 photo 模块一样, 这也是一个较新的模块, 有待增长. 36 | - nonfree: 在 OpenCV3 中移至 opencv_contrib/xfeatures2d 中. 包含了一些特殊的算法实现, 要么受制于专利, 要么有使用限制(如 SIFT 算法). 这些算法被隔离在各自模块中, 如果要在商业产品中使用它们, 你或许得做一些额外的工作. 37 | - contrib: 在 OpenCV3 中, 部分已融入 opencv_contrib 模块中. 38 | - legacy: 在 OpenCV3 中废弃. 39 | - ocl: 在 OpenCV3 中废弃, 用 T-API 技术替代. 这也是与 GPU 模块类似的技术, 但它实现了用于开放并行编程的 OpenCL 标准. 虽然此刻其特性不如 GPU 模块, 但其目标在于可以在任何 GPU 或 Khronos 兼容的并行设备上运行. (而 GPU 模块明确运用了 Nvidia 的 CUDA 工具包, 专注于 Nvidia 设备) 40 | 41 | ## OpenCV Contribution Repository 42 | 43 | 从 OpenCV3.0 开始, 以前的单库分为了两个部分: 44 | 45 | 1. 成熟的 OpenCV 46 | 1. 当前状态下拥有更多功能的 opencv_contrib 47 | 48 | 前者由 OpenCV 核心团队维护, 涵盖大多数稳定代码. 后者不太成熟, 由社区开发力量来维护, 且部分不受 OpenCV license 的管控, 可能涵盖一些专利算法. 49 | 50 | 以下是其主要模块: 51 | 52 | - Dnn: 深度神经网络 53 | - face: 人脸识别 54 | - text: 文本检测与识别, 可能选择性的使用开源 OCR Tesseract 为后端. 55 | - rgbd: 处理 RGB+ 深度图, 配合 Kinect 和 其他深度传感器(或简单与立体图像对应算法配合计算) 56 | - bioinspired: 仿生视觉 57 | - ximgproc, xphoto: 先进的图像处理和计算摄影学算法 58 | - tracking: 现代的物体追踪算法 -------------------------------------------------------------------------------- /learningOpenCV/02-Introduction-to-OpenCV.md: -------------------------------------------------------------------------------- 1 | # 介绍 OpenCV 2 | 3 | ## Include 文件 4 | 5 | 通常需要引用的头文件一般是: `../include/opencv2/opencv.hpp`, 它又会调用以下头文件: 6 | 7 | ```cpp 8 | #include "opencv2/core/core_c.h" // 传统 C 接口,以及通用计算方法 9 | #include "opencv2/core/core.hpp" // C++ 数据结构,以及通用计算方法 10 | #include "opencv2/flann/miniflann.hpp" // 近似最近邻匹配方法 11 | #include "opencv2/imgproc/imgproc_c.h" // 传统 C 图像处理方法 12 | #include "opencv2/imgproc/imgproc.hpp" // C++ 图像处理方法 13 | #include "opencv2/video/photo.hpp" // 针对照片处理与恢复的算法 14 | #include "opencv2/video/video.hpp" // 影像追踪与通用背景分割方法 15 | #include "opencv2/features2d/features2d.hpp" // 二维特征追踪 16 | #include "opencv2/objdetect/objdetect.hpp" // 人脸识别, 最新支持向量机, 方向梯度直方图, 平面贴片检测 17 | #include "opencv2/calib3d/calib3d.hpp" // 校准与立体 18 | #include "opencv2/ml/ml.hpp" // 机器学习: 集群与模式识别 19 | #include "opencv2/highgui/highgui_c.h" // 传统 C 图像展示, 滑块, 鼠标交互, I/O 20 | #include "opencv2/highgui/highgui.hpp" // C++ 图像展示, 滑块, 按钮, 鼠标, I/O 21 | #include "opencv2/contrib/contrib.hpp" // 用户贡献代码, 前沿检测, 模糊平移追踪, 图像旋转, 自相似特征 22 | ``` 23 | 24 | 你完全可以包含一个 "opencv.hpp" 来调用绝大部分 OpenCV 的函数, 但这样会降低编译速度. 如果你只用到图像处理功能, 那么你只引入 "opencv2/imgproc/imgproc.hpp" 会快很多. 类似的, 函数的实现会在它们各自的 `src` 目录下. 例如, `imgproc` 模块的 `cv::Canny()` 实现位于 `../modules/improc/src/canny.cpp`. 25 | 26 | ## 习题要求编译文档与示例代码 27 | 28 | 在 CMake 里勾选 `BUILD_DOCS`, 并指定 DOXYGEN 相关路径. 这就要求你安装以下两个工具: 29 | 30 | 1. [doxygen](http://www.stack.nl/~dimitri/doxygen/index.html) 31 | 1. [graphviz](http://www.graphviz.org/) 32 | 33 | 然后分别指定 doxygen.exe 的位置与 dot.exe 的位置即可. 34 | 35 | 在 build/doc 下会产生一个 `opencv_docs.sln`, 双击进入, 然后 build `ALL_BUILD` 和 `install_docs` 即可, 最后可以在 doc/doxygen/html/index.html 进入文档. 36 | 37 | ---- 38 | 39 | 关于示例代码, 在 CMake 里勾选 `BUILD_EXAMPLES` 即可. 40 | -------------------------------------------------------------------------------- /learningOpenCV/03-Getting-to-Know-OpenCV-Data-Types.md: -------------------------------------------------------------------------------- 1 | # 开始了解 OpenCV 的数据类型 2 | 3 | ## 基本类型 4 | 5 | 最直接的基本数据类型是模板类 `cv::Vec<>`, 一个原始类型的容器类, 我们称之为**定长向量类**. 为什么不直接用 STL 的类呢? 最关键的不同在于: 定长向量类, 注意力放在那些在编译期就知道维度的小 vectors 上. 6 | 这就使得处理一些小型公共操作, 会很高效. "小"的意思在于, 如果你用的元素个数比较多了, 那么这个类可能就不适合你.(事实上, 在 2.2 版, 超过 9 就完蛋了) 在下一章, 我们将关注 `cv::Mat` 类, 那才是对任意维度的大数组的正确处理方式. 现在, 我们仅考虑定长向量类对于小数据集合的方便与高效. 7 | 8 | 类似的, 还有 `cv::Matx<>`. 用作矩阵运算. `cv::Point<>` 作为坐标. 9 | 10 | `cv::Scalar` 本质上是一个四维的 Point. 但与 Point 不同的是, 它只支持下标访问, 就像 `cv::Vec<>` 一样, 更准确的说, 是 `cv::Vec` 的实例化. 11 | 12 | `cv::Size` 和 `cv::Rect` 就更好理解了, 前者有两个成员: width, height; 后者有四个, 除了长宽, 还有起始点的 x, y. 13 | 14 | `cv::RotatedRect` 与 `cv::Rect` 的最大区别是: 前者以中心点为第一参数, 而后者以左上角为第一参数. 15 | 16 | 定长矩阵类的效率很高, 因为在编译期就确定了尺寸. 因此其数据所有内存都分配在栈上, 可以被快速的分配与清理. 定长矩阵类其实是一个模板, 但单个矩阵通常会用别名, 别名的形式如下: `cv::Matx{1,2,...}{1,2,...}`, 其中的数字范围是 1~6. 如果你要表示的范围非常大, 这个必然不合适. 可以考虑后续介绍的 `cv::Mat`. 17 | 18 | 定长 `vector` 派生自定长矩阵类. `cv::Vec<>` is a `cv::Matx<>`, 但维度为 1. 用的时候也会借助别名, 和固定矩阵类的形式类似. 19 | 20 | OpenCV 中的复数类与 STL 中的兼容, 最显著的一点区别在于, STL 中读取实部与虚部, 需要借助 `real()` 和 `imag()` 接口. 21 | 22 | ## 辅助对象 23 | 24 | `cv::TermCriteria` 是一个终止条件变量. 关键参数: `type`, `maxCount`, `epsilon`. 25 | 26 | `cv::Range` 类用来指定一段 int 型的连续区间. 关键参数: `start`, `end`. 与 STL 的习惯一样, end 是一个标志位, 不在范围区间中. 如 `rng(0,4)` 包含的值是 0, 1, 2, 3. 关键方法: `size`, `empty`, `all`. 27 | 28 | `cv::Ptr` 模板与垃圾回收 101 : 与 C++11 之后的 `std::shared_ptr` 机制类似. 同样借助引用计数来回收. 并且专门提示, 说是线程安全的. 29 | 30 | `cv::Exception` 派生自 `std::exception`. 其成员有 `code`, `err`, `func`, `file` 和 `line`, 代表着错误代码, 错误描述信息, 错误发生所在函数名, 错误发生所在文件名及在文件中的行数. 31 | 32 | 几个比较有用的宏: 33 | 34 | ```cpp 35 | CV_Error( errorcode, description ); // 生成并抛出异常, 并给出相应描述 36 | CV_Error_( errorcode, printf_fmt_str, [printf-args] ); // 这个就是允许描述信息按照 printf-like 的形式组织 37 | CV_Assert( condition ); // 相当于 assert(); 38 | CV_DbgAssert( condition ); // 这个与上面的作用类似, 但仅在 debug 条件下工作. 39 | ``` 40 | 41 | `cv::DataType<>` 模板, OpenCV 中具体数据类型, 多自此特例化而来. 这有点类似 C++ 的特征萃取技术(types traits). 针对基本类型(float), 复杂类型(Rect)分别举例说明. 42 | 43 | `cv::InputArray` 和 `cv::OutputArray` 统一了输入输出接口. It is const. 44 | 45 | 这一大截东西略感无聊, 感觉介绍的干巴巴的. 46 | -------------------------------------------------------------------------------- /learningOpenCV/Preface.md: -------------------------------------------------------------------------------- 1 | # 最佳食用方法 2 | 3 | ## 抓包 4 | 5 | 通读 1-5 章, 然后则按需选读, 本书并不遵循某种特定顺序. 18,19 章除外, 涉及相机校准(camera calibration)与立体成像(stereo imaging), 还有 20~22 章, 也是例外, 涉及机器学习(machine learning). 有项目在身的企业人员或学生可以考虑采用这种方式. 6 | 7 | ## 循序渐进 8 | 9 | 以每周两章的速度, 在 11 周内读完前 22 章(23章可迅速扫完). 接下来最好能针对某特定领域, 开始着手一个项目, 深入细节. 最好同时能辅以额外资料与论文. 10 | 11 | ## 百米冲刺 12 | 13 | 在你的理解能力可以承受的范围内, 快速扫读 1-23 章, 然后开始针对特定领域开展项目, 并辅以额外资料与论文. 这种方式最适合专业人士, 也适合一些高阶计算机图像课程. 14 | -------------------------------------------------------------------------------- /open.gl/.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.sln.docstates 8 | 9 | # Build results 10 | [Dd]ebug/ 11 | [Dd]ebugPublic/ 12 | [Rr]elease/ 13 | [Rr]eleases/ 14 | x64/ 15 | x86/ 16 | build/ 17 | bld/ 18 | [Bb]in/ 19 | [Oo]bj/ 20 | 21 | # Roslyn cache directories 22 | *.ide/ 23 | 24 | # MSTest test Results 25 | [Tt]est[Rr]esult*/ 26 | [Bb]uild[Ll]og.* 27 | 28 | #NUNIT 29 | *.VisualState.xml 30 | TestResult.xml 31 | 32 | # Build Results of an ATL Project 33 | [Dd]ebugPS/ 34 | [Rr]eleasePS/ 35 | dlldata.c 36 | 37 | *_i.c 38 | *_p.c 39 | *_i.h 40 | *.ilk 41 | *.meta 42 | *.obj 43 | *.pch 44 | *.pdb 45 | *.pgc 46 | *.pgd 47 | *.rsp 48 | *.sbr 49 | *.tlb 50 | *.tli 51 | *.tlh 52 | *.tmp 53 | *.tmp_proj 54 | *.log 55 | *.vspscc 56 | *.vssscc 57 | .builds 58 | *.pidb 59 | *.svclog 60 | *.scc 61 | 62 | # Chutzpah Test files 63 | _Chutzpah* 64 | 65 | # Visual C++ cache files 66 | ipch/ 67 | *.aps 68 | *.ncb 69 | *.opensdf 70 | *.sdf 71 | *.cachefile 72 | 73 | # Visual Studio profiler 74 | *.psess 75 | *.vsp 76 | *.vspx 77 | 78 | # TFS 2012 Local Workspace 79 | $tf/ 80 | 81 | # Guidance Automation Toolkit 82 | *.gpState 83 | 84 | # ReSharper is a .NET coding add-in 85 | _ReSharper*/ 86 | *.[Rr]e[Ss]harper 87 | *.DotSettings.user 88 | 89 | # JustCode is a .NET coding addin-in 90 | .JustCode 91 | 92 | # TeamCity is a build add-in 93 | _TeamCity* 94 | 95 | # DotCover is a Code Coverage Tool 96 | *.dotCover 97 | 98 | # NCrunch 99 | _NCrunch_* 100 | .*crunch*.local.xml 101 | 102 | # MightyMoose 103 | *.mm.* 104 | AutoTest.Net/ 105 | 106 | # Web workbench (sass) 107 | .sass-cache/ 108 | 109 | # Installshield output folder 110 | [Ee]xpress/ 111 | 112 | # DocProject is a documentation generator add-in 113 | DocProject/buildhelp/ 114 | DocProject/Help/*.HxT 115 | DocProject/Help/*.HxC 116 | DocProject/Help/*.hhc 117 | DocProject/Help/*.hhk 118 | DocProject/Help/*.hhp 119 | DocProject/Help/Html2 120 | DocProject/Help/html 121 | 122 | # Click-Once directory 123 | publish/ 124 | 125 | # Publish Web Output 126 | *.[Pp]ublish.xml 127 | *.azurePubxml 128 | # TODO: Comment the next line if you want to checkin your web deploy settings 129 | # but database connection strings (with potential passwords) will be unencrypted 130 | *.pubxml 131 | *.publishproj 132 | 133 | # NuGet Packages 134 | *.nupkg 135 | # The packages folder can be ignored because of Package Restore 136 | **/packages/* 137 | # except build/, which is used as an MSBuild target. 138 | !**/packages/build/ 139 | # If using the old MSBuild-Integrated Package Restore, uncomment this: 140 | #!**/packages/repositories.config 141 | 142 | # Windows Azure Build Output 143 | csx/ 144 | *.build.csdef 145 | 146 | # Windows Store app package directory 147 | AppPackages/ 148 | 149 | # Others 150 | sql/ 151 | *.Cache 152 | ClientBin/ 153 | [Ss]tyle[Cc]op.* 154 | ~$* 155 | *~ 156 | *.dbmdl 157 | *.dbproj.schemaview 158 | *.pfx 159 | *.publishsettings 160 | node_modules/ 161 | 162 | # RIA/Silverlight projects 163 | Generated_Code/ 164 | 165 | # Backup & report files from converting an old project file 166 | # to a newer Visual Studio version. Backup files are not needed, 167 | # because we have git ;-) 168 | _UpgradeReport_Files/ 169 | Backup*/ 170 | UpgradeLog*.XML 171 | UpgradeLog*.htm 172 | 173 | # SQL Server files 174 | *.mdf 175 | *.ldf 176 | 177 | # Business Intelligence projects 178 | *.rdl.data 179 | *.bim.layout 180 | *.bim_*.settings 181 | 182 | # Microsoft Fakes 183 | FakesAssemblies/ 184 | -------------------------------------------------------------------------------- /open.gl/Exercise/01/01.vcxproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Debug 10 | x64 11 | 12 | 13 | Release 14 | Win32 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | {A0C1300E-DBEA-409A-B9C8-EDD5F2B3D048} 23 | Win32Proj 24 | My01 25 | 26 | 27 | 28 | Application 29 | true 30 | Unicode 31 | 32 | 33 | Application 34 | true 35 | Unicode 36 | 37 | 38 | Application 39 | false 40 | true 41 | Unicode 42 | 43 | 44 | Application 45 | false 46 | true 47 | Unicode 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | true 67 | 68 | 69 | true 70 | 71 | 72 | false 73 | 74 | 75 | false 76 | 77 | 78 | 79 | 80 | 81 | Level3 82 | Disabled 83 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 84 | D:\OpenGL\SDL2-2.0.3\include;D:\OpenGL\glew-1.11.0\include;%(AdditionalIncludeDirectories) 85 | 86 | 87 | Console 88 | true 89 | D:\OpenGL\SDL2-2.0.3\lib\x64;D:\OpenGL\glew-1.11.0\lib\Release\x64;%(AdditionalLibraryDirectories) 90 | opengl32.lib;SDL2.lib;SDL2main.lib;glew32s.lib;%(AdditionalDependencies) 91 | 92 | 93 | 94 | 95 | 96 | 97 | Level3 98 | Disabled 99 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 100 | D:\OpenGL\SDL2-2.0.3\include;D:\OpenGL\glew-1.11.0\include;%(AdditionalIncludeDirectories) 101 | 102 | 103 | Console 104 | true 105 | D:\OpenGL\SDL2-2.0.3\lib\x64;D:\OpenGL\glew-1.11.0\lib\Release\x64;%(AdditionalLibraryDirectories) 106 | opengl32.lib;SDL2.lib;SDL2main.lib;glew32s.lib;%(AdditionalDependencies) 107 | 108 | 109 | 110 | 111 | Level3 112 | 113 | 114 | MaxSpeed 115 | true 116 | true 117 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 118 | 119 | 120 | Console 121 | true 122 | true 123 | true 124 | 125 | 126 | 127 | 128 | Level3 129 | 130 | 131 | MaxSpeed 132 | true 133 | true 134 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 135 | 136 | 137 | Console 138 | true 139 | true 140 | true 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /open.gl/Exercise/01/01.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /open.gl/Exercise/01/main.cpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////// 2 | // Alter the vertex shader so that the triangle is upside down. 3 | 4 | #include 5 | 6 | #define GLEW_STATIC 7 | #include 8 | 9 | #include 10 | #include 11 | 12 | const GLchar* vertexSource = 13 | "#version 330\n" 14 | "in vec2 position;" 15 | "void main()" 16 | "{" 17 | " gl_Position = vec4(-position, 0.0, 1.0);" 18 | "}"; 19 | 20 | const GLchar* fragmentSource = 21 | "#version 330\n" 22 | "void main()" 23 | "{" 24 | " gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);" 25 | "}"; 26 | 27 | int main(int argc, char *argv[]) 28 | { 29 | SDL_Init(SDL_INIT_VIDEO); 30 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); 31 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); 32 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); 33 | 34 | SDL_Window* window = SDL_CreateWindow("OpenGL", 100, 100, 800, 600, SDL_WINDOW_OPENGL); 35 | SDL_GLContext context = SDL_GL_CreateContext(window); 36 | 37 | glewExperimental = GL_TRUE; // force GLEW to use a modern OpenGL method for checking if a function is available. 38 | glewInit(); 39 | 40 | GLuint vao; 41 | glGenVertexArrays(1, &vao); 42 | glBindVertexArray(vao); 43 | 44 | float vertices[] = { 45 | 0.0f, 0.5f, // Vertex 1 (X, Y) 46 | 0.5f, -0.5f, // Vertex 2 (X, Y) 47 | -0.5f, -0.5f // Vertex 3 (X, Y) 48 | }; 49 | 50 | GLuint vbo; 51 | glGenBuffers(1, &vbo); // Generate 1 buffer 52 | glBindBuffer(GL_ARRAY_BUFFER, vbo); 53 | glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); 54 | 55 | GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); 56 | glShaderSource(vertexShader, 1, &vertexSource, NULL); 57 | glCompileShader(vertexShader); 58 | 59 | GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); 60 | glShaderSource(fragmentShader, 1, &fragmentSource, NULL); 61 | glCompileShader(fragmentShader); 62 | 63 | GLuint shaderProgram = glCreateProgram(); 64 | glAttachShader(shaderProgram, vertexShader); 65 | glAttachShader(shaderProgram, fragmentShader); 66 | glLinkProgram(shaderProgram); 67 | glUseProgram(shaderProgram); 68 | 69 | GLint posAttrib = glGetAttribLocation(shaderProgram, "position"); 70 | glEnableVertexAttribArray(posAttrib); 71 | glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0); // last two param: stride and offset. 72 | 73 | SDL_Event windowEvent; 74 | while (true) 75 | { 76 | if (SDL_PollEvent(&windowEvent)) 77 | { 78 | if (windowEvent.type == SDL_QUIT) break; 79 | else if (windowEvent.type == SDL_KEYUP && 80 | windowEvent.key.keysym.sym == SDLK_ESCAPE) break; 81 | } 82 | 83 | // Clear the screen to black 84 | glClearColor(0.0f, 0.0f, 0.0f, 1.0f); 85 | glClear(GL_COLOR_BUFFER_BIT); 86 | 87 | glDrawArrays(GL_TRIANGLES, 0, 3); 88 | 89 | SDL_GL_SwapWindow(window); 90 | } 91 | SDL_GL_DeleteContext(context); 92 | 93 | glDeleteProgram(shaderProgram); 94 | glDeleteShader(fragmentShader); 95 | glDeleteShader(vertexShader); 96 | glDeleteBuffers(1, &vbo); 97 | glDeleteVertexArrays(1, &vao); 98 | 99 | SDL_Quit(); 100 | return 0; 101 | } -------------------------------------------------------------------------------- /open.gl/Exercise/02/02.vcxproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Debug 10 | x64 11 | 12 | 13 | Release 14 | Win32 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | {1A37077A-5A18-4104-94EE-D21523B70DCB} 23 | Win32Proj 24 | My01 25 | 26 | 27 | 28 | Application 29 | true 30 | Unicode 31 | 32 | 33 | Application 34 | true 35 | Unicode 36 | 37 | 38 | Application 39 | false 40 | true 41 | Unicode 42 | 43 | 44 | Application 45 | false 46 | true 47 | Unicode 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | true 67 | 68 | 69 | true 70 | 71 | 72 | false 73 | 74 | 75 | false 76 | 77 | 78 | 79 | 80 | 81 | Level3 82 | Disabled 83 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 84 | D:\OpenGL\SDL2-2.0.3\include;D:\OpenGL\glew-1.11.0\include;%(AdditionalIncludeDirectories) 85 | 86 | 87 | Console 88 | true 89 | D:\OpenGL\SDL2-2.0.3\lib\x64;D:\OpenGL\glew-1.11.0\lib\Release\x64;%(AdditionalLibraryDirectories) 90 | opengl32.lib;SDL2.lib;SDL2main.lib;glew32s.lib;%(AdditionalDependencies) 91 | 92 | 93 | 94 | 95 | 96 | 97 | Level3 98 | Disabled 99 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 100 | D:\OpenGL\SDL2-2.0.3\include;D:\OpenGL\glew-1.11.0\include;%(AdditionalIncludeDirectories) 101 | 102 | 103 | Console 104 | true 105 | D:\OpenGL\SDL2-2.0.3\lib\x64;D:\OpenGL\glew-1.11.0\lib\Release\x64;%(AdditionalLibraryDirectories) 106 | opengl32.lib;SDL2.lib;SDL2main.lib;glew32s.lib;%(AdditionalDependencies) 107 | 108 | 109 | 110 | 111 | Level3 112 | 113 | 114 | MaxSpeed 115 | true 116 | true 117 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 118 | 119 | 120 | Console 121 | true 122 | true 123 | true 124 | 125 | 126 | 127 | 128 | Level3 129 | 130 | 131 | MaxSpeed 132 | true 133 | true 134 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 135 | 136 | 137 | Console 138 | true 139 | true 140 | true 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /open.gl/Exercise/02/02.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /open.gl/Exercise/02/main.cpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////// 2 | // Invert the colors of the triangle by altering the fragment shader. 3 | 4 | #include 5 | 6 | #define GLEW_STATIC 7 | #include 8 | 9 | #include 10 | #include 11 | 12 | const GLchar* vertexSource = 13 | "#version 330\n" 14 | "in vec2 position;" 15 | "in vec3 color;" 16 | "out vec3 Color;" 17 | "void main()" 18 | "{" 19 | " Color = color;" 20 | " gl_Position = vec4(position, 0.0, 1.0);" 21 | "}"; 22 | 23 | const GLchar* fragmentSource = 24 | "#version 330\n" 25 | "in vec3 Color;" 26 | "void main()" 27 | "{" 28 | " gl_FragColor = vec4(1.0-Color, 1.0);" 29 | "}"; 30 | 31 | int main(int argc, char *argv[]) 32 | { 33 | SDL_Init(SDL_INIT_VIDEO); 34 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); 35 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); 36 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); 37 | 38 | SDL_Window* window = SDL_CreateWindow("OpenGL", 100, 100, 800, 600, SDL_WINDOW_OPENGL); 39 | SDL_GLContext context = SDL_GL_CreateContext(window); 40 | 41 | glewExperimental = GL_TRUE; // force GLEW to use a modern OpenGL method for checking if a function is available. 42 | glewInit(); 43 | 44 | GLuint vao; 45 | glGenVertexArrays(1, &vao); 46 | glBindVertexArray(vao); 47 | 48 | float vertices[] = { 49 | 0.0f, 0.5f, 1.0f, 0.0f, 0.0f, // Vertex 1 (X, Y) Red 50 | 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, // Vertex 2 (X, Y) Green 51 | -0.5f, -0.5f, 0.0f, 0.0f, 1.0f // Vertex 3 (X, Y) Blue 52 | }; 53 | 54 | GLuint vbo; 55 | glGenBuffers(1, &vbo); // Generate 1 buffer 56 | glBindBuffer(GL_ARRAY_BUFFER, vbo); 57 | glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); 58 | 59 | GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); 60 | glShaderSource(vertexShader, 1, &vertexSource, NULL); 61 | glCompileShader(vertexShader); 62 | 63 | GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); 64 | glShaderSource(fragmentShader, 1, &fragmentSource, NULL); 65 | glCompileShader(fragmentShader); 66 | 67 | GLuint shaderProgram = glCreateProgram(); 68 | glAttachShader(shaderProgram, vertexShader); 69 | glAttachShader(shaderProgram, fragmentShader); 70 | glLinkProgram(shaderProgram); 71 | glUseProgram(shaderProgram); 72 | 73 | GLint posAttrib = glGetAttribLocation(shaderProgram, "position"); 74 | glEnableVertexAttribArray(posAttrib); 75 | glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 5*sizeof(float), 0); // last two param: stride and offset. 76 | 77 | GLint colorAttrib = glGetAttribLocation(shaderProgram, "color"); 78 | glEnableVertexAttribArray(colorAttrib); 79 | glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, 5*sizeof(float), (void*)(2*sizeof(float))); 80 | 81 | SDL_Event windowEvent; 82 | while (true) 83 | { 84 | if (SDL_PollEvent(&windowEvent)) 85 | { 86 | if (windowEvent.type == SDL_QUIT) break; 87 | else if (windowEvent.type == SDL_KEYUP && 88 | windowEvent.key.keysym.sym == SDLK_ESCAPE) break; 89 | } 90 | 91 | // Clear the screen to black 92 | glClearColor(0.0f, 0.0f, 0.0f, 1.0f); 93 | glClear(GL_COLOR_BUFFER_BIT); 94 | 95 | glDrawArrays(GL_TRIANGLES, 0, 3); 96 | 97 | SDL_GL_SwapWindow(window); 98 | } 99 | SDL_GL_DeleteContext(context); 100 | 101 | glDeleteProgram(shaderProgram); 102 | glDeleteShader(fragmentShader); 103 | glDeleteShader(vertexShader); 104 | glDeleteBuffers(1, &vbo); 105 | glDeleteVertexArrays(1, &vao); 106 | 107 | SDL_Quit(); 108 | return 0; 109 | } -------------------------------------------------------------------------------- /open.gl/Exercise/03/03.vcxproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Debug 10 | x64 11 | 12 | 13 | Release 14 | Win32 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | {FBA5880C-FC70-4A1D-97AE-532EA10387B4} 23 | Win32Proj 24 | My01 25 | 26 | 27 | 28 | Application 29 | true 30 | Unicode 31 | 32 | 33 | Application 34 | true 35 | Unicode 36 | 37 | 38 | Application 39 | false 40 | true 41 | Unicode 42 | 43 | 44 | Application 45 | false 46 | true 47 | Unicode 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | true 67 | 68 | 69 | true 70 | 71 | 72 | false 73 | 74 | 75 | false 76 | 77 | 78 | 79 | 80 | 81 | Level3 82 | Disabled 83 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 84 | D:\OpenGL\SDL2-2.0.3\include;D:\OpenGL\glew-1.11.0\include;%(AdditionalIncludeDirectories) 85 | 86 | 87 | Console 88 | true 89 | D:\OpenGL\SDL2-2.0.3\lib\x64;D:\OpenGL\glew-1.11.0\lib\Release\x64;%(AdditionalLibraryDirectories) 90 | opengl32.lib;SDL2.lib;SDL2main.lib;glew32s.lib;%(AdditionalDependencies) 91 | 92 | 93 | 94 | 95 | 96 | 97 | Level3 98 | Disabled 99 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 100 | D:\OpenGL\SDL2-2.0.3\include;D:\OpenGL\glew-1.11.0\include;%(AdditionalIncludeDirectories) 101 | 102 | 103 | Console 104 | true 105 | D:\OpenGL\SDL2-2.0.3\lib\x64;D:\OpenGL\glew-1.11.0\lib\Release\x64;%(AdditionalLibraryDirectories) 106 | opengl32.lib;SDL2.lib;SDL2main.lib;glew32s.lib;%(AdditionalDependencies) 107 | 108 | 109 | 110 | 111 | Level3 112 | 113 | 114 | MaxSpeed 115 | true 116 | true 117 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 118 | 119 | 120 | Console 121 | true 122 | true 123 | true 124 | 125 | 126 | 127 | 128 | Level3 129 | 130 | 131 | MaxSpeed 132 | true 133 | true 134 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 135 | 136 | 137 | Console 138 | true 139 | true 140 | true 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /open.gl/Exercise/03/03.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /open.gl/Exercise/03/main.cpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////// 2 | // Change the program so that each vertex has only one color value, determining the shade of gray 3 | 4 | #include 5 | 6 | #define GLEW_STATIC 7 | #include 8 | 9 | #include 10 | #include 11 | 12 | const GLchar* vertexSource = 13 | "#version 330\n" 14 | "in vec2 position;" 15 | "in float color;" 16 | "out float Color;" 17 | "void main()" 18 | "{" 19 | " Color = color;" 20 | " gl_Position = vec4(position, 0.0, 1.0);" 21 | "}"; 22 | 23 | const GLchar* fragmentSource = 24 | "#version 330\n" 25 | "in float Color;" 26 | "void main()" 27 | "{" 28 | " gl_FragColor = vec4(Color, Color, Color, 1.0);" 29 | "}"; 30 | 31 | int main(int argc, char *argv[]) 32 | { 33 | SDL_Init(SDL_INIT_VIDEO); 34 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); 35 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); 36 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); 37 | 38 | SDL_Window* window = SDL_CreateWindow("OpenGL", 100, 100, 800, 600, SDL_WINDOW_OPENGL); 39 | SDL_GLContext context = SDL_GL_CreateContext(window); 40 | 41 | glewExperimental = GL_TRUE; // force GLEW to use a modern OpenGL method for checking if a function is available. 42 | glewInit(); 43 | 44 | GLuint vao; 45 | glGenVertexArrays(1, &vao); 46 | glBindVertexArray(vao); 47 | 48 | float vertices[] = { 49 | 0.0f, 0.5f, 0.0f, // Vertex 1 (X, Y) White 50 | 0.5f, -0.5f, 0.5f, // Vertex 2 (X, Y) Gray 51 | -0.5f, -0.5f, 1.0f // Vertex 3 (X, Y) Black 52 | }; 53 | 54 | GLuint vbo; 55 | glGenBuffers(1, &vbo); // Generate 1 buffer 56 | glBindBuffer(GL_ARRAY_BUFFER, vbo); 57 | glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); 58 | 59 | GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); 60 | glShaderSource(vertexShader, 1, &vertexSource, NULL); 61 | glCompileShader(vertexShader); 62 | 63 | GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); 64 | glShaderSource(fragmentShader, 1, &fragmentSource, NULL); 65 | glCompileShader(fragmentShader); 66 | 67 | GLuint shaderProgram = glCreateProgram(); 68 | glAttachShader(shaderProgram, vertexShader); 69 | glAttachShader(shaderProgram, fragmentShader); 70 | glLinkProgram(shaderProgram); 71 | glUseProgram(shaderProgram); 72 | 73 | GLint posAttrib = glGetAttribLocation(shaderProgram, "position"); 74 | glEnableVertexAttribArray(posAttrib); 75 | glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 3*sizeof(float), 0); // last two param: stride and offset. 76 | 77 | GLint colorAttrib = glGetAttribLocation(shaderProgram, "color"); 78 | glEnableVertexAttribArray(colorAttrib); 79 | glVertexAttribPointer(colorAttrib, 1, GL_FLOAT, GL_FALSE, 3*sizeof(float), (void*)(2*sizeof(float))); 80 | 81 | SDL_Event windowEvent; 82 | while (true) 83 | { 84 | if (SDL_PollEvent(&windowEvent)) 85 | { 86 | if (windowEvent.type == SDL_QUIT) break; 87 | else if (windowEvent.type == SDL_KEYUP && 88 | windowEvent.key.keysym.sym == SDLK_ESCAPE) break; 89 | } 90 | 91 | // Clear the screen to black 92 | glClearColor(0.0f, 0.0f, 0.0f, 1.0f); 93 | glClear(GL_COLOR_BUFFER_BIT); 94 | 95 | glDrawArrays(GL_TRIANGLES, 0, 3); 96 | 97 | SDL_GL_SwapWindow(window); 98 | } 99 | SDL_GL_DeleteContext(context); 100 | 101 | glDeleteProgram(shaderProgram); 102 | glDeleteShader(fragmentShader); 103 | glDeleteShader(vertexShader); 104 | glDeleteBuffers(1, &vbo); 105 | glDeleteVertexArrays(1, &vao); 106 | 107 | SDL_Quit(); 108 | return 0; 109 | } -------------------------------------------------------------------------------- /open.gl/Exercise/11/11.vcxproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Debug 10 | x64 11 | 12 | 13 | Release 14 | Win32 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | {F948423A-1891-473F-9E11-49D1CD7C7239} 23 | Win32Proj 24 | My01 25 | 26 | 27 | 28 | Application 29 | true 30 | Unicode 31 | 32 | 33 | Application 34 | true 35 | Unicode 36 | 37 | 38 | Application 39 | false 40 | true 41 | Unicode 42 | 43 | 44 | Application 45 | false 46 | true 47 | Unicode 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | true 67 | 68 | 69 | true 70 | 71 | 72 | false 73 | 74 | 75 | false 76 | 77 | 78 | 79 | 80 | 81 | Level3 82 | Disabled 83 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 84 | D:\OpenGL\SDL2-2.0.3\include;D:\OpenGL\glew-1.11.0\include;%(AdditionalIncludeDirectories) 85 | 86 | 87 | Console 88 | true 89 | D:\OpenGL\SDL2-2.0.3\lib\x64;D:\OpenGL\glew-1.11.0\lib\Release\x64;%(AdditionalLibraryDirectories) 90 | opengl32.lib;SDL2.lib;SDL2main.lib;glew32s.lib;%(AdditionalDependencies) 91 | 92 | 93 | 94 | 95 | 96 | 97 | Level3 98 | Disabled 99 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 100 | D:\OpenGL\SDL2-2.0.3\include;D:\OpenGL\glew-1.11.0\include;D:\OpenGL\Simple OpenGL Image Library\src;%(AdditionalIncludeDirectories) 101 | 102 | 103 | Console 104 | true 105 | D:\OpenGL\SDL2-2.0.3\lib\x64;D:\OpenGL\glew-1.11.0\lib\Release\x64;D:\OpenGL\Simple OpenGL Image Library\lib;%(AdditionalLibraryDirectories) 106 | opengl32.lib;SDL2.lib;SDL2main.lib;glew32s.lib;SOIL.lib;%(AdditionalDependencies) 107 | 108 | 109 | 110 | 111 | Level3 112 | 113 | 114 | MaxSpeed 115 | true 116 | true 117 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 118 | 119 | 120 | Console 121 | true 122 | true 123 | true 124 | 125 | 126 | 127 | 128 | Level3 129 | 130 | 131 | MaxSpeed 132 | true 133 | true 134 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 135 | 136 | 137 | Console 138 | true 139 | true 140 | true 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /open.gl/Exercise/11/11.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /open.gl/Exercise/11/main.cpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////// 2 | // Animate the blending between the textures by adding a time uniform. 3 | 4 | #include 5 | #include 6 | 7 | #define GLEW_STATIC 8 | #include 9 | 10 | #include 11 | #include 12 | 13 | #include 14 | 15 | const GLchar* vertexSource = 16 | "#version 150\n" 17 | "in vec2 position;" 18 | "in vec3 color;" 19 | "in vec2 texcoord;" 20 | "out vec3 Color;" 21 | "out vec2 Texcoord;" 22 | "void main()" 23 | "{" 24 | " Texcoord = texcoord;" 25 | " Color = color;" 26 | " gl_Position = vec4(position, 0.0, 1.0);" 27 | "}"; 28 | 29 | const GLchar* fragmentSource = 30 | "#version 150\n" 31 | "in vec3 Color;" 32 | "in vec2 Texcoord;" 33 | "out vec4 outColor;" 34 | "uniform sampler2D texKitten;" 35 | "uniform sampler2D texPuppy;" 36 | "uniform float time;" 37 | "void main()" 38 | "{" 39 | " float factor = (sin(time * 3.0) + 1.0) / 2.0;" 40 | " vec4 colKitten = texture(texKitten, Texcoord);" 41 | " vec4 colPuppy = texture(texPuppy, Texcoord);" 42 | " outColor = mix(colKitten, colPuppy, factor);" 43 | "}"; 44 | 45 | int main(int argc, char *argv[]) 46 | { 47 | SDL_Init(SDL_INIT_VIDEO); 48 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); 49 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); 50 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); 51 | 52 | SDL_Window* window = SDL_CreateWindow("OpenGL", 100, 100, 800, 600, SDL_WINDOW_OPENGL); 53 | SDL_GLContext context = SDL_GL_CreateContext(window); 54 | 55 | glewExperimental = GL_TRUE; // force GLEW to use a modern OpenGL method for checking if a function is available. 56 | glewInit(); 57 | 58 | GLuint vao; 59 | glGenVertexArrays(1, &vao); 60 | glBindVertexArray(vao); 61 | 62 | float vertices[] = { 63 | // Position Color Texture 64 | -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // Top-left 65 | 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // Top-right 66 | 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // Bottom-right 67 | -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f // Bottom-left 68 | }; 69 | 70 | GLuint elements[] = { 71 | 0, 1, 2, 72 | 2, 3, 0 73 | }; 74 | 75 | GLuint vbo; 76 | glGenBuffers(1, &vbo); // Generate 1 buffer 77 | glBindBuffer(GL_ARRAY_BUFFER, vbo); 78 | glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); 79 | 80 | GLuint ebo; 81 | glGenBuffers(1, &ebo); 82 | glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); 83 | glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW); 84 | 85 | GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); 86 | glShaderSource(vertexShader, 1, &vertexSource, NULL); 87 | glCompileShader(vertexShader); 88 | 89 | GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); 90 | glShaderSource(fragmentShader, 1, &fragmentSource, NULL); 91 | glCompileShader(fragmentShader); 92 | 93 | GLuint shaderProgram = glCreateProgram(); 94 | glAttachShader(shaderProgram, vertexShader); 95 | glAttachShader(shaderProgram, fragmentShader); 96 | glLinkProgram(shaderProgram); 97 | glUseProgram(shaderProgram); 98 | 99 | GLint posAttrib = glGetAttribLocation(shaderProgram, "position"); 100 | glEnableVertexAttribArray(posAttrib); 101 | glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 7*sizeof(float), 0); // last two param: stride and offset. 102 | 103 | GLint colorAttrib = glGetAttribLocation(shaderProgram, "color"); 104 | glEnableVertexAttribArray(colorAttrib); 105 | glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, 7*sizeof(float), (void*)(2*sizeof(float))); 106 | 107 | GLint texAttrib = glGetAttribLocation(shaderProgram, "texcoord"); 108 | glEnableVertexAttribArray(texAttrib); 109 | glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 7*sizeof(float), (void*)(5*sizeof(float))); 110 | 111 | GLuint textures[2]; 112 | glGenTextures(2, textures); 113 | 114 | int width, height; 115 | unsigned char* image; 116 | 117 | glActiveTexture(GL_TEXTURE0); 118 | glBindTexture(GL_TEXTURE_2D, textures[0]); 119 | image = SOIL_load_image("../image/sample.png", &width, &height, 0, SOIL_LOAD_RGB); 120 | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); 121 | SOIL_free_image_data(image); 122 | glUniform1i(glGetUniformLocation(shaderProgram, "texKitten"), 0); 123 | 124 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 125 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 126 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 127 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 128 | 129 | glActiveTexture(GL_TEXTURE1); 130 | glBindTexture(GL_TEXTURE_2D, textures[1]); 131 | image = SOIL_load_image("../image/sample2.png", &width, &height, 0, SOIL_LOAD_RGB); 132 | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); 133 | SOIL_free_image_data(image); 134 | glUniform1i(glGetUniformLocation(shaderProgram, "texPuppy"), 1); 135 | 136 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 137 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 138 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 139 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 140 | 141 | GLint uniTime = glGetUniformLocation(shaderProgram, "time"); 142 | 143 | SDL_Event windowEvent; 144 | while (true) 145 | { 146 | if (SDL_PollEvent(&windowEvent)) 147 | { 148 | if (windowEvent.type == SDL_QUIT) break; 149 | else if (windowEvent.type == SDL_KEYUP && 150 | windowEvent.key.keysym.sym == SDLK_ESCAPE) break; 151 | } 152 | 153 | // Clear the screen to black 154 | glClearColor(0.0f, 0.0f, 0.0f, 1.0f); 155 | glClear(GL_COLOR_BUFFER_BIT); 156 | 157 | // set the time uniform 158 | glUniform1f(uniTime, (GLfloat)clock() / (GLfloat)CLOCKS_PER_SEC); 159 | 160 | glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); 161 | 162 | SDL_GL_SwapWindow(window); 163 | } 164 | SDL_GL_DeleteContext(context); 165 | 166 | glDeleteTextures(2, textures); 167 | 168 | glDeleteProgram(shaderProgram); 169 | glDeleteShader(fragmentShader); 170 | glDeleteShader(vertexShader); 171 | glDeleteBuffers(1, &vbo); 172 | glDeleteVertexArrays(1, &vao); 173 | 174 | SDL_Quit(); 175 | return 0; 176 | } -------------------------------------------------------------------------------- /open.gl/Exercise/12/12.vcxproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Debug 10 | x64 11 | 12 | 13 | Release 14 | Win32 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | {05438FD4-F4E8-4491-B969-AF56A01C85BD} 23 | Win32Proj 24 | My01 25 | 26 | 27 | 28 | Application 29 | true 30 | Unicode 31 | 32 | 33 | Application 34 | true 35 | Unicode 36 | 37 | 38 | Application 39 | false 40 | true 41 | Unicode 42 | 43 | 44 | Application 45 | false 46 | true 47 | Unicode 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | true 67 | 68 | 69 | true 70 | 71 | 72 | false 73 | 74 | 75 | false 76 | 77 | 78 | 79 | 80 | 81 | Level3 82 | Disabled 83 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 84 | D:\OpenGL\SDL2-2.0.3\include;D:\OpenGL\glew-1.11.0\include;%(AdditionalIncludeDirectories) 85 | 86 | 87 | Console 88 | true 89 | D:\OpenGL\SDL2-2.0.3\lib\x64;D:\OpenGL\glew-1.11.0\lib\Release\x64;%(AdditionalLibraryDirectories) 90 | opengl32.lib;SDL2.lib;SDL2main.lib;glew32s.lib;%(AdditionalDependencies) 91 | 92 | 93 | 94 | 95 | 96 | 97 | Level3 98 | Disabled 99 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 100 | D:\OpenGL\SDL2-2.0.3\include;D:\OpenGL\glew-1.11.0\include;D:\OpenGL\Simple OpenGL Image Library\src;%(AdditionalIncludeDirectories) 101 | 102 | 103 | Console 104 | true 105 | D:\OpenGL\SDL2-2.0.3\lib\x64;D:\OpenGL\glew-1.11.0\lib\Release\x64;D:\OpenGL\Simple OpenGL Image Library\lib;%(AdditionalLibraryDirectories) 106 | opengl32.lib;SDL2.lib;SDL2main.lib;glew32s.lib;SOIL.lib;%(AdditionalDependencies) 107 | 108 | 109 | 110 | 111 | Level3 112 | 113 | 114 | MaxSpeed 115 | true 116 | true 117 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 118 | 119 | 120 | Console 121 | true 122 | true 123 | true 124 | 125 | 126 | 127 | 128 | Level3 129 | 130 | 131 | MaxSpeed 132 | true 133 | true 134 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 135 | 136 | 137 | Console 138 | true 139 | true 140 | true 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /open.gl/Exercise/12/12.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /open.gl/Exercise/12/main.cpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////// 2 | // Draw a reflection of the kitten in the lower half of the rectangle. 3 | 4 | #include 5 | #include 6 | 7 | #define GLEW_STATIC 8 | #include 9 | 10 | #include 11 | #include 12 | 13 | #include 14 | 15 | const GLchar* vertexSource = 16 | "#version 150\n" 17 | "in vec2 position;" 18 | "in vec3 color;" 19 | "in vec2 texcoord;" 20 | "out vec3 Color;" 21 | "out vec2 Texcoord;" 22 | "void main()" 23 | "{" 24 | " Texcoord = texcoord;" 25 | " Color = color;" 26 | " gl_Position = vec4(position, 0.0, 1.0);" 27 | "}"; 28 | 29 | const GLchar* fragmentSource = 30 | "#version 150\n" 31 | "in vec3 Color;" 32 | "in vec2 Texcoord;" 33 | "out vec4 outColor;" 34 | "uniform sampler2D tex;" 35 | "void main()" 36 | "{" 37 | " if (Texcoord.y < 0.5)" 38 | " outColor = texture(tex, Texcoord);" 39 | " else" 40 | " outColor = texture(tex, vec2(Texcoord.x, 1.0 - Texcoord.y));" 41 | "}"; 42 | 43 | int main(int argc, char *argv[]) 44 | { 45 | SDL_Init(SDL_INIT_VIDEO); 46 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); 47 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); 48 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); 49 | 50 | SDL_Window* window = SDL_CreateWindow("OpenGL", 100, 100, 800, 600, SDL_WINDOW_OPENGL); 51 | SDL_GLContext context = SDL_GL_CreateContext(window); 52 | 53 | glewExperimental = GL_TRUE; // force GLEW to use a modern OpenGL method for checking if a function is available. 54 | glewInit(); 55 | 56 | GLuint vao; 57 | glGenVertexArrays(1, &vao); 58 | glBindVertexArray(vao); 59 | 60 | float vertices[] = { 61 | // Position Color Texture 62 | -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // Top-left 63 | 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // Top-right 64 | 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // Bottom-right 65 | -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f // Bottom-left 66 | }; 67 | 68 | GLuint elements[] = { 69 | 0, 1, 2, 70 | 2, 3, 0 71 | }; 72 | 73 | GLuint vbo; 74 | glGenBuffers(1, &vbo); // Generate 1 buffer 75 | glBindBuffer(GL_ARRAY_BUFFER, vbo); 76 | glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); 77 | 78 | GLuint ebo; 79 | glGenBuffers(1, &ebo); 80 | glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); 81 | glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW); 82 | 83 | GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); 84 | glShaderSource(vertexShader, 1, &vertexSource, NULL); 85 | glCompileShader(vertexShader); 86 | 87 | GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); 88 | glShaderSource(fragmentShader, 1, &fragmentSource, NULL); 89 | glCompileShader(fragmentShader); 90 | 91 | GLuint shaderProgram = glCreateProgram(); 92 | glAttachShader(shaderProgram, vertexShader); 93 | glAttachShader(shaderProgram, fragmentShader); 94 | glLinkProgram(shaderProgram); 95 | glUseProgram(shaderProgram); 96 | 97 | GLint posAttrib = glGetAttribLocation(shaderProgram, "position"); 98 | glEnableVertexAttribArray(posAttrib); 99 | glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 7*sizeof(float), 0); // last two param: stride and offset. 100 | 101 | GLint colorAttrib = glGetAttribLocation(shaderProgram, "color"); 102 | glEnableVertexAttribArray(colorAttrib); 103 | glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, 7*sizeof(float), (void*)(2*sizeof(float))); 104 | 105 | GLint texAttrib = glGetAttribLocation(shaderProgram, "texcoord"); 106 | glEnableVertexAttribArray(texAttrib); 107 | glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 7*sizeof(float), (void*)(5*sizeof(float))); 108 | 109 | GLuint tex; 110 | glGenTextures(1, &tex); 111 | glBindTexture(GL_TEXTURE_2D, tex); 112 | 113 | int width, height; 114 | unsigned char* image = SOIL_load_image("../image/sample.png", &width, &height, 0, SOIL_LOAD_RGB); 115 | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); 116 | SOIL_free_image_data(image); 117 | 118 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 119 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 120 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 121 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 122 | 123 | SDL_Event windowEvent; 124 | while (true) 125 | { 126 | if (SDL_PollEvent(&windowEvent)) 127 | { 128 | if (windowEvent.type == SDL_QUIT) break; 129 | else if (windowEvent.type == SDL_KEYUP && 130 | windowEvent.key.keysym.sym == SDLK_ESCAPE) break; 131 | } 132 | 133 | // Clear the screen to black 134 | glClearColor(0.0f, 0.0f, 0.0f, 1.0f); 135 | glClear(GL_COLOR_BUFFER_BIT); 136 | 137 | glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); 138 | 139 | SDL_GL_SwapWindow(window); 140 | } 141 | SDL_GL_DeleteContext(context); 142 | 143 | glDeleteTextures(1, &tex); 144 | glDeleteProgram(shaderProgram); 145 | glDeleteShader(fragmentShader); 146 | glDeleteShader(vertexShader); 147 | glDeleteBuffers(1, &vbo); 148 | glDeleteVertexArrays(1, &vao); 149 | 150 | SDL_Quit(); 151 | return 0; 152 | } -------------------------------------------------------------------------------- /open.gl/Exercise/13/13.vcxproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Debug 10 | x64 11 | 12 | 13 | Release 14 | Win32 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | {880DC02D-6FA6-44DF-A9F1-BBE1C557BADF} 23 | Win32Proj 24 | My01 25 | 26 | 27 | 28 | Application 29 | true 30 | Unicode 31 | 32 | 33 | Application 34 | true 35 | Unicode 36 | 37 | 38 | Application 39 | false 40 | true 41 | Unicode 42 | 43 | 44 | Application 45 | false 46 | true 47 | Unicode 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | true 67 | 68 | 69 | true 70 | 71 | 72 | false 73 | 74 | 75 | false 76 | 77 | 78 | 79 | 80 | 81 | Level3 82 | Disabled 83 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 84 | D:\OpenGL\SDL2-2.0.3\include;D:\OpenGL\glew-1.11.0\include;%(AdditionalIncludeDirectories) 85 | 86 | 87 | Console 88 | true 89 | D:\OpenGL\SDL2-2.0.3\lib\x64;D:\OpenGL\glew-1.11.0\lib\Release\x64;%(AdditionalLibraryDirectories) 90 | opengl32.lib;SDL2.lib;SDL2main.lib;glew32s.lib;%(AdditionalDependencies) 91 | 92 | 93 | 94 | 95 | 96 | 97 | Level3 98 | Disabled 99 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 100 | D:\OpenGL\SDL2-2.0.3\include;D:\OpenGL\glew-1.11.0\include;D:\OpenGL\Simple OpenGL Image Library\src;%(AdditionalIncludeDirectories) 101 | 102 | 103 | Console 104 | true 105 | D:\OpenGL\SDL2-2.0.3\lib\x64;D:\OpenGL\glew-1.11.0\lib\Release\x64;D:\OpenGL\Simple OpenGL Image Library\lib;%(AdditionalLibraryDirectories) 106 | opengl32.lib;SDL2.lib;SDL2main.lib;glew32s.lib;SOIL.lib;%(AdditionalDependencies) 107 | 108 | 109 | 110 | 111 | Level3 112 | 113 | 114 | MaxSpeed 115 | true 116 | true 117 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 118 | 119 | 120 | Console 121 | true 122 | true 123 | true 124 | 125 | 126 | 127 | 128 | Level3 129 | 130 | 131 | MaxSpeed 132 | true 133 | true 134 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 135 | 136 | 137 | Console 138 | true 139 | true 140 | true 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /open.gl/Exercise/13/13.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /open.gl/Exercise/13/main.cpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////// 2 | // Now try adding distortion with sin and the time variable to simulate water. 3 | 4 | #include 5 | #include 6 | 7 | #define GLEW_STATIC 8 | #include 9 | 10 | #include 11 | #include 12 | 13 | #include 14 | 15 | const GLchar* vertexSource = 16 | "#version 150\n" 17 | "in vec2 position;" 18 | "in vec3 color;" 19 | "in vec2 texcoord;" 20 | "out vec3 Color;" 21 | "out vec2 Texcoord;" 22 | "void main()" 23 | "{" 24 | " Texcoord = texcoord;" 25 | " Color = color;" 26 | " gl_Position = vec4(position, 0.0, 1.0);" 27 | "}"; 28 | 29 | const GLchar* fragmentSource = 30 | "#version 150\n" 31 | "in vec3 Color;" 32 | "in vec2 Texcoord;" 33 | "out vec4 outColor;" 34 | "uniform sampler2D tex;" 35 | "uniform float time;" 36 | "void main()" 37 | "{" 38 | " float factor = sin(Texcoord.y * 60.0 + time * 2.0) / 30.0;" 39 | " if (Texcoord.y < 0.5)" 40 | " outColor = texture(tex, Texcoord);" 41 | " else" 42 | " outColor = texture(tex, vec2(Texcoord.x + factor, 1.0 - Texcoord.y)) * vec4(0.7, 0.7, 1.0, 1.0);" 43 | "}"; 44 | 45 | int main(int argc, char *argv[]) 46 | { 47 | SDL_Init(SDL_INIT_VIDEO); 48 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); 49 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); 50 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); 51 | 52 | SDL_Window* window = SDL_CreateWindow("OpenGL", 100, 100, 800, 600, SDL_WINDOW_OPENGL); 53 | SDL_GLContext context = SDL_GL_CreateContext(window); 54 | 55 | glewExperimental = GL_TRUE; // force GLEW to use a modern OpenGL method for checking if a function is available. 56 | glewInit(); 57 | 58 | GLuint vao; 59 | glGenVertexArrays(1, &vao); 60 | glBindVertexArray(vao); 61 | 62 | float vertices[] = { 63 | // Position Color Texture 64 | -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // Top-left 65 | 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // Top-right 66 | 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // Bottom-right 67 | -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f // Bottom-left 68 | }; 69 | 70 | GLuint elements[] = { 71 | 0, 1, 2, 72 | 2, 3, 0 73 | }; 74 | 75 | GLuint vbo; 76 | glGenBuffers(1, &vbo); // Generate 1 buffer 77 | glBindBuffer(GL_ARRAY_BUFFER, vbo); 78 | glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); 79 | 80 | GLuint ebo; 81 | glGenBuffers(1, &ebo); 82 | glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); 83 | glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW); 84 | 85 | GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); 86 | glShaderSource(vertexShader, 1, &vertexSource, NULL); 87 | glCompileShader(vertexShader); 88 | 89 | GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); 90 | glShaderSource(fragmentShader, 1, &fragmentSource, NULL); 91 | glCompileShader(fragmentShader); 92 | 93 | GLuint shaderProgram = glCreateProgram(); 94 | glAttachShader(shaderProgram, vertexShader); 95 | glAttachShader(shaderProgram, fragmentShader); 96 | glLinkProgram(shaderProgram); 97 | glUseProgram(shaderProgram); 98 | 99 | GLint posAttrib = glGetAttribLocation(shaderProgram, "position"); 100 | glEnableVertexAttribArray(posAttrib); 101 | glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 7*sizeof(float), 0); // last two param: stride and offset. 102 | 103 | GLint colorAttrib = glGetAttribLocation(shaderProgram, "color"); 104 | glEnableVertexAttribArray(colorAttrib); 105 | glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, 7*sizeof(float), (void*)(2*sizeof(float))); 106 | 107 | GLint texAttrib = glGetAttribLocation(shaderProgram, "texcoord"); 108 | glEnableVertexAttribArray(texAttrib); 109 | glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 7*sizeof(float), (void*)(5*sizeof(float))); 110 | 111 | GLuint tex; 112 | glGenTextures(1, &tex); 113 | glBindTexture(GL_TEXTURE_2D, tex); 114 | 115 | int width, height; 116 | unsigned char* image = SOIL_load_image("../image/sample.png", &width, &height, 0, SOIL_LOAD_RGB); 117 | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); 118 | SOIL_free_image_data(image); 119 | 120 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 121 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 122 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 123 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 124 | 125 | GLint uniTime = glGetUniformLocation(shaderProgram, "time"); 126 | 127 | SDL_Event windowEvent; 128 | while (true) 129 | { 130 | if (SDL_PollEvent(&windowEvent)) 131 | { 132 | if (windowEvent.type == SDL_QUIT) break; 133 | else if (windowEvent.type == SDL_KEYUP && 134 | windowEvent.key.keysym.sym == SDLK_ESCAPE) break; 135 | } 136 | 137 | // Clear the screen to black 138 | glClearColor(0.0f, 0.0f, 0.0f, 1.0f); 139 | glClear(GL_COLOR_BUFFER_BIT); 140 | 141 | glUniform1f(uniTime, (GLfloat)clock() / (GLfloat)CLOCKS_PER_SEC); 142 | 143 | glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); 144 | 145 | SDL_GL_SwapWindow(window); 146 | } 147 | SDL_GL_DeleteContext(context); 148 | 149 | glDeleteTextures(1, &tex); 150 | glDeleteProgram(shaderProgram); 151 | glDeleteShader(fragmentShader); 152 | glDeleteShader(vertexShader); 153 | glDeleteBuffers(1, &vbo); 154 | glDeleteVertexArrays(1, &vao); 155 | 156 | SDL_Quit(); 157 | return 0; 158 | } -------------------------------------------------------------------------------- /open.gl/Exercise/21/21.vcxproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Debug 10 | x64 11 | 12 | 13 | Release 14 | Win32 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | {1FB80404-C836-4EAE-9842-88D343A190A3} 23 | Win32Proj 24 | My01 25 | 26 | 27 | 28 | Application 29 | true 30 | Unicode 31 | 32 | 33 | Application 34 | true 35 | Unicode 36 | 37 | 38 | Application 39 | false 40 | true 41 | Unicode 42 | 43 | 44 | Application 45 | false 46 | true 47 | Unicode 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | true 67 | 68 | 69 | true 70 | 71 | 72 | false 73 | 74 | 75 | false 76 | 77 | 78 | 79 | 80 | 81 | Level3 82 | Disabled 83 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 84 | D:\OpenGL\SDL2-2.0.3\include;D:\OpenGL\glew-1.11.0\include;%(AdditionalIncludeDirectories) 85 | 86 | 87 | Console 88 | true 89 | D:\OpenGL\SDL2-2.0.3\lib\x64;D:\OpenGL\glew-1.11.0\lib\Release\x64;%(AdditionalLibraryDirectories) 90 | opengl32.lib;SDL2.lib;SDL2main.lib;glew32s.lib;%(AdditionalDependencies) 91 | 92 | 93 | 94 | 95 | 96 | 97 | Level3 98 | Disabled 99 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 100 | D:\OpenGL\SDL2-2.0.3\include;D:\OpenGL\glew-1.11.0\include;D:\OpenGL\Simple OpenGL Image Library\src;D:\OpenGL\glm-0.9.5.4;%(AdditionalIncludeDirectories) 101 | 102 | 103 | Console 104 | true 105 | D:\OpenGL\SDL2-2.0.3\lib\x64;D:\OpenGL\glew-1.11.0\lib\Release\x64;D:\OpenGL\Simple OpenGL Image Library\lib;%(AdditionalLibraryDirectories) 106 | opengl32.lib;SDL2.lib;SDL2main.lib;glew32s.lib;SOIL.lib;%(AdditionalDependencies) 107 | 108 | 109 | 110 | 111 | Level3 112 | 113 | 114 | MaxSpeed 115 | true 116 | true 117 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 118 | 119 | 120 | Console 121 | true 122 | true 123 | true 124 | 125 | 126 | 127 | 128 | Level3 129 | 130 | 131 | MaxSpeed 132 | true 133 | true 134 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 135 | 136 | 137 | Console 138 | true 139 | true 140 | true 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /open.gl/Exercise/21/21.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /open.gl/Exercise/21/main.cpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////// 2 | // Make the rectangle with the blended image grow bigger and smaller with sin. 3 | 4 | #include 5 | #include 6 | 7 | #define GLEW_STATIC 8 | #include 9 | 10 | #include 11 | #include 12 | 13 | #include 14 | 15 | #include 16 | #include 17 | #include 18 | 19 | const GLchar* vertexSource = 20 | "#version 150\n" 21 | "in vec2 position;" 22 | "in vec3 color;" 23 | "in vec2 texcoord;" 24 | "out vec3 Color;" 25 | "out vec2 Texcoord;" 26 | "uniform mat4 model;" 27 | "uniform mat4 view;" 28 | "uniform mat4 proj;" 29 | "void main()" 30 | "{" 31 | " Texcoord = texcoord;" 32 | " Color = color;" 33 | " gl_Position = proj * view * model * vec4(position, 0.0, 1.0);" 34 | "}"; 35 | 36 | const GLchar* fragmentSource = 37 | "#version 150\n" 38 | "in vec3 Color;" 39 | "in vec2 Texcoord;" 40 | "out vec4 outColor;" 41 | "uniform sampler2D texKitten;" 42 | "uniform sampler2D texPuppy;" 43 | "void main()" 44 | "{" 45 | " vec4 colKitten = texture(texKitten, Texcoord);" 46 | " vec4 colPuppy = texture(texPuppy, Texcoord);" 47 | " outColor = mix(colKitten, colPuppy, 0.5);" 48 | "}"; 49 | 50 | int main(int argc, char *argv[]) 51 | { 52 | SDL_Init(SDL_INIT_VIDEO); 53 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); 54 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); 55 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); 56 | 57 | SDL_Window* window = SDL_CreateWindow("OpenGL", 100, 100, 800, 600, SDL_WINDOW_OPENGL); 58 | SDL_GLContext context = SDL_GL_CreateContext(window); 59 | 60 | glewExperimental = GL_TRUE; // force GLEW to use a modern OpenGL method for checking if a function is available. 61 | glewInit(); 62 | 63 | GLuint vao; 64 | glGenVertexArrays(1, &vao); 65 | glBindVertexArray(vao); 66 | 67 | float vertices[] = { 68 | // Position Color Texture 69 | -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // Top-left 70 | 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // Top-right 71 | 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // Bottom-right 72 | -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f // Bottom-left 73 | }; 74 | 75 | GLuint elements[] = { 76 | 0, 1, 2, 77 | 2, 3, 0 78 | }; 79 | 80 | GLuint vbo; 81 | glGenBuffers(1, &vbo); // Generate 1 buffer 82 | glBindBuffer(GL_ARRAY_BUFFER, vbo); 83 | glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); 84 | 85 | GLuint ebo; 86 | glGenBuffers(1, &ebo); 87 | glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); 88 | glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW); 89 | 90 | GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); 91 | glShaderSource(vertexShader, 1, &vertexSource, NULL); 92 | glCompileShader(vertexShader); 93 | 94 | GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); 95 | glShaderSource(fragmentShader, 1, &fragmentSource, NULL); 96 | glCompileShader(fragmentShader); 97 | 98 | GLuint shaderProgram = glCreateProgram(); 99 | glAttachShader(shaderProgram, vertexShader); 100 | glAttachShader(shaderProgram, fragmentShader); 101 | glLinkProgram(shaderProgram); 102 | glUseProgram(shaderProgram); 103 | 104 | GLint posAttrib = glGetAttribLocation(shaderProgram, "position"); 105 | glEnableVertexAttribArray(posAttrib); 106 | glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 7*sizeof(float), 0); // last two param: stride and offset. 107 | 108 | GLint colorAttrib = glGetAttribLocation(shaderProgram, "color"); 109 | glEnableVertexAttribArray(colorAttrib); 110 | glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, 7*sizeof(float), (void*)(2*sizeof(float))); 111 | 112 | GLint texAttrib = glGetAttribLocation(shaderProgram, "texcoord"); 113 | glEnableVertexAttribArray(texAttrib); 114 | glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 7*sizeof(float), (void*)(5*sizeof(float))); 115 | 116 | GLuint textures[2]; 117 | glGenTextures(2, textures); 118 | 119 | int width, height; 120 | unsigned char* image; 121 | 122 | glActiveTexture(GL_TEXTURE0); 123 | glBindTexture(GL_TEXTURE_2D, textures[0]); 124 | image = SOIL_load_image("../image/sample.png", &width, &height, 0, SOIL_LOAD_RGB); 125 | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); 126 | SOIL_free_image_data(image); 127 | glUniform1i(glGetUniformLocation(shaderProgram, "texKitten"), 0); 128 | 129 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 130 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 131 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 132 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 133 | 134 | glActiveTexture(GL_TEXTURE1); 135 | glBindTexture(GL_TEXTURE_2D, textures[1]); 136 | image = SOIL_load_image("../image/sample2.png", &width, &height, 0, SOIL_LOAD_RGB); 137 | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); 138 | SOIL_free_image_data(image); 139 | glUniform1i(glGetUniformLocation(shaderProgram, "texPuppy"), 1); 140 | 141 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 142 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 143 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 144 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 145 | 146 | glm::mat4 view = glm::lookAt( 147 | glm::vec3(1.2f, 1.2f, 1.2f), 148 | glm::vec3(0.0f, 0.0f, 0.0f), 149 | glm::vec3(0.0f, 0.0f, 1.0f) 150 | ); 151 | glm::mat4 proj = glm::perspective(45.0f, 800.0f / 600.0f, 1.0f, 10.0f); 152 | 153 | //GLint uniTime = glGetUniformLocation(shaderProgram, "time"); 154 | GLint uniTrans = glGetUniformLocation(shaderProgram, "model"); 155 | GLint uniView = glGetUniformLocation(shaderProgram, "view"); 156 | GLint uniProj = glGetUniformLocation(shaderProgram, "proj"); 157 | 158 | glUniformMatrix4fv(uniView, 1, GL_FALSE, glm::value_ptr(view)); 159 | glUniformMatrix4fv(uniProj, 1, GL_FALSE, glm::value_ptr(proj)); 160 | 161 | SDL_Event windowEvent; 162 | while (true) 163 | { 164 | if (SDL_PollEvent(&windowEvent)) 165 | { 166 | if (windowEvent.type == SDL_QUIT) break; 167 | else if (windowEvent.type == SDL_KEYUP && 168 | windowEvent.key.keysym.sym == SDLK_ESCAPE) break; 169 | } 170 | 171 | // Clear the screen to black 172 | glClearColor(0.0f, 0.0f, 0.0f, 1.0f); 173 | glClear(GL_COLOR_BUFFER_BIT); 174 | 175 | // set the time uniform 176 | //glUniform1f(uniTime, (GLfloat)clock() / (GLfloat)CLOCKS_PER_SEC); 177 | 178 | // Calculate transformation 179 | glm::mat4 model; 180 | model = glm::rotate( 181 | model, 182 | (float)clock() / (float)CLOCKS_PER_SEC * 180.0f, 183 | glm::vec3(0.0f, 0.0f, 1.0f) 184 | ); 185 | 186 | GLfloat s = sin((GLfloat)clock() / (GLfloat)CLOCKS_PER_SEC * 5.0f) * 0.25f + 0.75f; 187 | model = glm::scale(model, glm::vec3(s, s, s)); 188 | 189 | glUniformMatrix4fv(uniTrans, 1, GL_FALSE, glm::value_ptr(model)); 190 | 191 | // Draw a rectangle from the 2 triangles using 6 indices 192 | glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); 193 | 194 | SDL_GL_SwapWindow(window); 195 | } 196 | SDL_GL_DeleteContext(context); 197 | 198 | glDeleteTextures(2, textures); 199 | 200 | glDeleteProgram(shaderProgram); 201 | glDeleteShader(fragmentShader); 202 | glDeleteShader(vertexShader); 203 | glDeleteBuffers(1, &vbo); 204 | glDeleteVertexArrays(1, &vao); 205 | 206 | SDL_Quit(); 207 | return 0; 208 | } -------------------------------------------------------------------------------- /open.gl/Exercise/22/22.vcxproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Debug 10 | x64 11 | 12 | 13 | Release 14 | Win32 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | {88AE46DE-5CD8-49F1-948F-E86A7CBF092F} 23 | Win32Proj 24 | My01 25 | 26 | 27 | 28 | Application 29 | true 30 | Unicode 31 | 32 | 33 | Application 34 | true 35 | Unicode 36 | 37 | 38 | Application 39 | false 40 | true 41 | Unicode 42 | 43 | 44 | Application 45 | false 46 | true 47 | Unicode 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | true 67 | 68 | 69 | true 70 | 71 | 72 | false 73 | 74 | 75 | false 76 | 77 | 78 | 79 | 80 | 81 | Level3 82 | Disabled 83 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 84 | D:\OpenGL\SDL2-2.0.3\include;D:\OpenGL\glew-1.11.0\include;%(AdditionalIncludeDirectories) 85 | 86 | 87 | Console 88 | true 89 | D:\OpenGL\SDL2-2.0.3\lib\x64;D:\OpenGL\glew-1.11.0\lib\Release\x64;%(AdditionalLibraryDirectories) 90 | opengl32.lib;SDL2.lib;SDL2main.lib;glew32s.lib;%(AdditionalDependencies) 91 | 92 | 93 | 94 | 95 | 96 | 97 | Level3 98 | Disabled 99 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 100 | D:\OpenGL\SDL2-2.0.3\include;D:\OpenGL\glew-1.11.0\include;D:\OpenGL\Simple OpenGL Image Library\src;D:\OpenGL\glm-0.9.5.4;%(AdditionalIncludeDirectories) 101 | 102 | 103 | Console 104 | true 105 | D:\OpenGL\SDL2-2.0.3\lib\x64;D:\OpenGL\glew-1.11.0\lib\Release\x64;D:\OpenGL\Simple OpenGL Image Library\lib;%(AdditionalLibraryDirectories) 106 | opengl32.lib;SDL2.lib;SDL2main.lib;glew32s.lib;SOIL.lib;%(AdditionalDependencies) 107 | 108 | 109 | 110 | 111 | Level3 112 | 113 | 114 | MaxSpeed 115 | true 116 | true 117 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 118 | 119 | 120 | Console 121 | true 122 | true 123 | true 124 | 125 | 126 | 127 | 128 | Level3 129 | 130 | 131 | MaxSpeed 132 | true 133 | true 134 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 135 | 136 | 137 | Console 138 | true 139 | true 140 | true 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /open.gl/Exercise/22/22.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /open.gl/Exercise/22/main.cpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////// 2 | // Make the rectangle flip around the X axis after pressing the space bar and slowly stop again. 3 | 4 | #include 5 | #include 6 | 7 | #define GLEW_STATIC 8 | #include 9 | 10 | #include 11 | #include 12 | 13 | #include 14 | 15 | #include 16 | #include 17 | #include 18 | 19 | const GLchar* vertexSource = 20 | "#version 150\n" 21 | "in vec2 position;" 22 | "in vec3 color;" 23 | "in vec2 texcoord;" 24 | "out vec3 Color;" 25 | "out vec2 Texcoord;" 26 | "uniform mat4 model;" 27 | "uniform mat4 view;" 28 | "uniform mat4 proj;" 29 | "void main()" 30 | "{" 31 | " Texcoord = texcoord;" 32 | " Color = color;" 33 | " gl_Position = proj * view * model * vec4(position, 0.0, 1.0);" 34 | "}"; 35 | 36 | const GLchar* fragmentSource = 37 | "#version 150\n" 38 | "in vec3 Color;" 39 | "in vec2 Texcoord;" 40 | "out vec4 outColor;" 41 | "uniform sampler2D texKitten;" 42 | "uniform sampler2D texPuppy;" 43 | "void main()" 44 | "{" 45 | " vec4 colKitten = texture(texKitten, Texcoord);" 46 | " vec4 colPuppy = texture(texPuppy, Texcoord);" 47 | " outColor = mix(colKitten, colPuppy, 0.5);" 48 | "}"; 49 | 50 | int main(int argc, char *argv[]) 51 | { 52 | SDL_Init(SDL_INIT_VIDEO); 53 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); 54 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); 55 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); 56 | 57 | SDL_Window* window = SDL_CreateWindow("OpenGL", 100, 100, 800, 600, SDL_WINDOW_OPENGL); 58 | SDL_GLContext context = SDL_GL_CreateContext(window); 59 | 60 | glewExperimental = GL_TRUE; // force GLEW to use a modern OpenGL method for checking if a function is available. 61 | glewInit(); 62 | 63 | GLuint vao; 64 | glGenVertexArrays(1, &vao); 65 | glBindVertexArray(vao); 66 | 67 | float vertices[] = { 68 | // Position Color Texture 69 | -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // Top-left 70 | 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // Top-right 71 | 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // Bottom-right 72 | -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f // Bottom-left 73 | }; 74 | 75 | GLuint elements[] = { 76 | 0, 1, 2, 77 | 2, 3, 0 78 | }; 79 | 80 | GLuint vbo; 81 | glGenBuffers(1, &vbo); // Generate 1 buffer 82 | glBindBuffer(GL_ARRAY_BUFFER, vbo); 83 | glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); 84 | 85 | GLuint ebo; 86 | glGenBuffers(1, &ebo); 87 | glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); 88 | glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW); 89 | 90 | GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); 91 | glShaderSource(vertexShader, 1, &vertexSource, NULL); 92 | glCompileShader(vertexShader); 93 | 94 | GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); 95 | glShaderSource(fragmentShader, 1, &fragmentSource, NULL); 96 | glCompileShader(fragmentShader); 97 | 98 | GLuint shaderProgram = glCreateProgram(); 99 | glAttachShader(shaderProgram, vertexShader); 100 | glAttachShader(shaderProgram, fragmentShader); 101 | glLinkProgram(shaderProgram); 102 | glUseProgram(shaderProgram); 103 | 104 | GLint posAttrib = glGetAttribLocation(shaderProgram, "position"); 105 | glEnableVertexAttribArray(posAttrib); 106 | glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 7*sizeof(float), 0); // last two param: stride and offset. 107 | 108 | GLint colorAttrib = glGetAttribLocation(shaderProgram, "color"); 109 | glEnableVertexAttribArray(colorAttrib); 110 | glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, 7*sizeof(float), (void*)(2*sizeof(float))); 111 | 112 | GLint texAttrib = glGetAttribLocation(shaderProgram, "texcoord"); 113 | glEnableVertexAttribArray(texAttrib); 114 | glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 7*sizeof(float), (void*)(5*sizeof(float))); 115 | 116 | GLuint textures[2]; 117 | glGenTextures(2, textures); 118 | 119 | int width, height; 120 | unsigned char* image; 121 | 122 | glActiveTexture(GL_TEXTURE0); 123 | glBindTexture(GL_TEXTURE_2D, textures[0]); 124 | image = SOIL_load_image("../image/sample.png", &width, &height, 0, SOIL_LOAD_RGB); 125 | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); 126 | SOIL_free_image_data(image); 127 | glUniform1i(glGetUniformLocation(shaderProgram, "texKitten"), 0); 128 | 129 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 130 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 131 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 132 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 133 | 134 | glActiveTexture(GL_TEXTURE1); 135 | glBindTexture(GL_TEXTURE_2D, textures[1]); 136 | image = SOIL_load_image("../image/sample2.png", &width, &height, 0, SOIL_LOAD_RGB); 137 | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); 138 | SOIL_free_image_data(image); 139 | glUniform1i(glGetUniformLocation(shaderProgram, "texPuppy"), 1); 140 | 141 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 142 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 143 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 144 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 145 | 146 | glm::mat4 view = glm::lookAt( 147 | glm::vec3(1.2f, 1.2f, 1.2f), 148 | glm::vec3(0.0f, 0.0f, 0.0f), 149 | glm::vec3(0.0f, 0.0f, 1.0f) 150 | ); 151 | glm::mat4 proj = glm::perspective(45.0f, 800.0f / 600.0f, 1.0f, 10.0f); 152 | 153 | //GLint uniTime = glGetUniformLocation(shaderProgram, "time"); 154 | GLint uniModel = glGetUniformLocation(shaderProgram, "model"); 155 | GLint uniView = glGetUniformLocation(shaderProgram, "view"); 156 | GLint uniProj = glGetUniformLocation(shaderProgram, "proj"); 157 | 158 | glUniformMatrix4fv(uniView, 1, GL_FALSE, glm::value_ptr(view)); 159 | glUniformMatrix4fv(uniProj, 1, GL_FALSE, glm::value_ptr(proj)); 160 | 161 | GLfloat angle = -45.0f; 162 | GLfloat speed = 0.0f; 163 | 164 | SDL_Event windowEvent; 165 | while (true) 166 | { 167 | if (SDL_PollEvent(&windowEvent)) 168 | { 169 | if (windowEvent.type == SDL_QUIT) break; 170 | else if (windowEvent.type == SDL_KEYUP && 171 | windowEvent.key.keysym.sym == SDLK_ESCAPE) break; 172 | else if (windowEvent.key.keysym.sym == SDLK_SPACE) { // start 173 | speed = 180.0f; 174 | } 175 | else if (windowEvent.key.keysym.sym == SDLK_s) { // stop 176 | speed = 0.0f; 177 | } 178 | } 179 | 180 | // Clear the screen to black 181 | glClearColor(0.0f, 0.0f, 0.0f, 1.0f); 182 | glClear(GL_COLOR_BUFFER_BIT); 183 | 184 | // set the time uniform 185 | //glUniform1f(uniTime, (GLfloat)clock() / (GLfloat)CLOCKS_PER_SEC); 186 | 187 | // Calculate transformation 188 | glm::mat4 model; 189 | model = glm::rotate( 190 | model, 191 | angle, 192 | glm::vec3(1.0f, 0.0f, 0.0f) 193 | ); 194 | 195 | angle += speed / (GLfloat)CLOCKS_PER_SEC; 196 | speed /= 1.0f + 0.2f / (GLfloat)CLOCKS_PER_SEC; 197 | 198 | glUniformMatrix4fv(uniModel, 1, GL_FALSE, glm::value_ptr(model)); 199 | 200 | // Draw a rectangle from the 2 triangles using 6 indices 201 | glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); 202 | 203 | SDL_GL_SwapWindow(window); 204 | } 205 | SDL_GL_DeleteContext(context); 206 | 207 | glDeleteTextures(2, textures); 208 | 209 | glDeleteProgram(shaderProgram); 210 | glDeleteShader(fragmentShader); 211 | glDeleteShader(vertexShader); 212 | glDeleteBuffers(1, &vbo); 213 | glDeleteVertexArrays(1, &vao); 214 | 215 | SDL_Quit(); 216 | return 0; 217 | } -------------------------------------------------------------------------------- /open.gl/Exercise/51/51.vcxproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Debug 10 | x64 11 | 12 | 13 | Release 14 | Win32 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | {03AF960F-61CD-470A-B0E1-7D142690DC30} 23 | Win32Proj 24 | My01 25 | 26 | 27 | 28 | Application 29 | true 30 | Unicode 31 | 32 | 33 | Application 34 | true 35 | Unicode 36 | 37 | 38 | Application 39 | false 40 | true 41 | Unicode 42 | 43 | 44 | Application 45 | false 46 | true 47 | Unicode 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | true 67 | 68 | 69 | true 70 | 71 | 72 | false 73 | 74 | 75 | false 76 | 77 | 78 | 79 | 80 | 81 | Level3 82 | Disabled 83 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 84 | D:\OpenGL\SDL2-2.0.3\include;D:\OpenGL\glew-1.11.0\include;%(AdditionalIncludeDirectories) 85 | 86 | 87 | Console 88 | true 89 | D:\OpenGL\SDL2-2.0.3\lib\x64;D:\OpenGL\glew-1.11.0\lib\Release\x64;%(AdditionalLibraryDirectories) 90 | opengl32.lib;SDL2.lib;SDL2main.lib;glew32s.lib;%(AdditionalDependencies) 91 | 92 | 93 | 94 | 95 | 96 | 97 | Level3 98 | Disabled 99 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 100 | D:\OpenGL\SDL2-2.0.3\include;D:\OpenGL\glew-1.11.0\include;D:\OpenGL\Simple OpenGL Image Library\src;D:\OpenGL\glm-0.9.5.4;%(AdditionalIncludeDirectories) 101 | 102 | 103 | Console 104 | true 105 | D:\OpenGL\SDL2-2.0.3\lib\x64;D:\OpenGL\glew-1.11.0\lib\Release\x64;D:\OpenGL\Simple OpenGL Image Library\lib;%(AdditionalLibraryDirectories) 106 | opengl32.lib;SDL2.lib;SDL2main.lib;glew32s.lib;SOIL.lib;%(AdditionalDependencies) 107 | 108 | 109 | 110 | 111 | Level3 112 | 113 | 114 | MaxSpeed 115 | true 116 | true 117 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 118 | 119 | 120 | Console 121 | true 122 | true 123 | true 124 | 125 | 126 | 127 | 128 | Level3 129 | 130 | 131 | MaxSpeed 132 | true 133 | true 134 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 135 | 136 | 137 | Console 138 | true 139 | true 140 | true 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /open.gl/Exercise/51/51.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /open.gl/Exercise/51/main.cpp: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////// 2 | // Try using a geometry shader in a 3D scenario to create more complex meshes like cubes from points. 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #define GLEW_STATIC 9 | #include 10 | 11 | #include 12 | #include 13 | 14 | #include 15 | 16 | #include 17 | #include 18 | #include 19 | 20 | #define GLSL(src) "#version 150 core\n" #src 21 | 22 | // Vertex shader 23 | const char* vertexShaderSrc = GLSL( 24 | in vec3 pos; 25 | in vec3 color; 26 | 27 | out vec3 vColor; 28 | 29 | void main() { 30 | gl_Position = vec4(pos, 1.0); 31 | vColor = color; 32 | } 33 | ); 34 | 35 | // Geometry shader 36 | const char* geometryShaderSrc = GLSL( 37 | layout(points) in; 38 | layout(triangle_strip, max_vertices = 8) out; 39 | 40 | in vec3 vColor[]; 41 | out vec3 fColor; 42 | 43 | void main() { 44 | fColor = vColor[0]; 45 | 46 | gl_Position = gl_in[0].gl_Position + vec4(-0.1, 0.1,-0.1, 0.0); 47 | EmitVertex(); 48 | 49 | gl_Position = gl_in[0].gl_Position + vec4( 0.1, 0.1,-0.1, 0.0); 50 | EmitVertex(); 51 | 52 | gl_Position = gl_in[0].gl_Position + vec4(-0.1, 0.1, 0.1, 0.0); 53 | EmitVertex(); 54 | 55 | gl_Position = gl_in[0].gl_Position + vec4( 0.1, 0.1, 0.1, 0.0); 56 | EmitVertex(); 57 | 58 | gl_Position = gl_in[0].gl_Position + vec4(-0.1,-0.1, 0.1, 0.0); 59 | EmitVertex(); 60 | 61 | gl_Position = gl_in[0].gl_Position + vec4( 0.1,-0.1, 0.1, 0.0); 62 | EmitVertex(); 63 | 64 | gl_Position = gl_in[0].gl_Position + vec4(-0.1,-0.1,-0.1, 0.0); 65 | EmitVertex(); 66 | 67 | gl_Position = gl_in[0].gl_Position + vec4( 0.1,-0.1,-0.1, 0.0); 68 | EmitVertex(); 69 | 70 | EndPrimitive(); 71 | } 72 | ); 73 | 74 | // Fragment shader 75 | const char* fragmentShaderSrc = GLSL( 76 | in vec3 fColor; 77 | out vec4 outColor; 78 | void main() { 79 | outColor = vec4(fColor, 1.0); 80 | } 81 | ); 82 | 83 | GLuint createShader(GLenum type, const GLchar* src) { 84 | GLuint shader = glCreateShader(type); 85 | glShaderSource(shader, 1, &src, nullptr); 86 | glCompileShader(shader); 87 | 88 | GLint status; 89 | glGetShaderiv(shader, GL_COMPILE_STATUS, &status); 90 | if (status != GL_TRUE) 91 | { 92 | char buffer[512]; 93 | glGetShaderInfoLog(shader, 512, NULL, buffer); 94 | printf("\n%s\n", buffer); 95 | } 96 | 97 | return shader; 98 | } 99 | 100 | int main(int argc, char *argv[]) 101 | { 102 | SDL_Init(SDL_INIT_VIDEO); 103 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); 104 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); 105 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); 106 | 107 | SDL_Window* window = SDL_CreateWindow("OpenGL", 100, 100, 800, 600, SDL_WINDOW_OPENGL); 108 | SDL_GLContext context = SDL_GL_CreateContext(window); 109 | 110 | glewExperimental = GL_TRUE; // force GLEW to use a modern OpenGL method for checking if a function is available. 111 | glewInit(); 112 | 113 | GLuint vertexShader = createShader(GL_VERTEX_SHADER, vertexShaderSrc); 114 | GLuint geometryShader = createShader(GL_GEOMETRY_SHADER, geometryShaderSrc); 115 | GLuint fragmentShader = createShader(GL_FRAGMENT_SHADER, fragmentShaderSrc); 116 | 117 | GLuint shaderProgram = glCreateProgram(); 118 | glAttachShader(shaderProgram, vertexShader); 119 | glAttachShader(shaderProgram, geometryShader); 120 | glAttachShader(shaderProgram, fragmentShader); 121 | glLinkProgram(shaderProgram); 122 | glUseProgram(shaderProgram); 123 | 124 | // Create VBO with point coordinates 125 | GLuint vbo; 126 | glGenBuffers(1, &vbo); 127 | 128 | float points[] = { 129 | // Coordinates Color 130 | -0.45f, 0.45f, 0.0f, 1.0f, 0.0f, 0.0f, 131 | 0.45f, 0.45f, 0.0f, 0.0f, 1.0f, 0.0f, 132 | 0.45f, -0.45f, 0.0f, 0.0f, 0.0f, 1.0f, 133 | -0.45f, -0.45f, 0.0f, 1.0f, 1.0f, 0.0f 134 | }; 135 | 136 | glBindBuffer(GL_ARRAY_BUFFER, vbo); 137 | glBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW); 138 | 139 | // Create VAO 140 | GLuint vao; 141 | glGenVertexArrays(1, &vao); 142 | glBindVertexArray(vao); 143 | 144 | // Specify layout of point data 145 | GLint posAttrib = glGetAttribLocation(shaderProgram, "pos"); 146 | glEnableVertexAttribArray(posAttrib); 147 | glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), 0); 148 | 149 | GLint colAttrib = glGetAttribLocation(shaderProgram, "color"); 150 | glEnableVertexAttribArray(colAttrib); 151 | glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float))); 152 | 153 | SDL_Event windowEvent; 154 | while (true) 155 | { 156 | if (SDL_PollEvent(&windowEvent)) 157 | { 158 | if (windowEvent.type == SDL_QUIT) break; 159 | else if (windowEvent.type == SDL_KEYUP && 160 | windowEvent.key.keysym.sym == SDLK_ESCAPE) break; 161 | } 162 | 163 | glClearColor(0.0f, 0.0f, 0.0f, 1.0f); 164 | glClear(GL_COLOR_BUFFER_BIT); 165 | 166 | glDrawArrays(GL_POINTS, 0, 4); 167 | 168 | SDL_GL_SwapWindow(window); 169 | } 170 | SDL_GL_DeleteContext(context); 171 | 172 | glDeleteProgram(shaderProgram); 173 | glDeleteShader(vertexShader); 174 | glDeleteShader(geometryShader); 175 | glDeleteShader(fragmentShader); 176 | 177 | glDeleteBuffers(1, &vbo); 178 | glDeleteVertexArrays(1, &vao); 179 | 180 | SDL_Quit(); 181 | return 0; 182 | } -------------------------------------------------------------------------------- /open.gl/Exercise/Exercise.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 11.00 3 | # Visual Studio 2010 4 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "01", "01\01.vcxproj", "{A0C1300E-DBEA-409A-B9C8-EDD5F2B3D048}" 5 | EndProject 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "02", "02\02.vcxproj", "{1A37077A-5A18-4104-94EE-D21523B70DCB}" 7 | EndProject 8 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "03", "03\03.vcxproj", "{FBA5880C-FC70-4A1D-97AE-532EA10387B4}" 9 | EndProject 10 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "11", "11\11.vcxproj", "{F948423A-1891-473F-9E11-49D1CD7C7239}" 11 | EndProject 12 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "12", "12\12.vcxproj", "{05438FD4-F4E8-4491-B969-AF56A01C85BD}" 13 | EndProject 14 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "13", "13\13.vcxproj", "{880DC02D-6FA6-44DF-A9F1-BBE1C557BADF}" 15 | EndProject 16 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "21", "21\21.vcxproj", "{1FB80404-C836-4EAE-9842-88D343A190A3}" 17 | EndProject 18 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "22", "22\22.vcxproj", "{88AE46DE-5CD8-49F1-948F-E86A7CBF092F}" 19 | EndProject 20 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "51", "51\51.vcxproj", "{03AF960F-61CD-470A-B0E1-7D142690DC30}" 21 | EndProject 22 | Global 23 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 24 | Debug|Win32 = Debug|Win32 25 | Debug|x64 = Debug|x64 26 | Release|Win32 = Release|Win32 27 | Release|x64 = Release|x64 28 | EndGlobalSection 29 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 30 | {A0C1300E-DBEA-409A-B9C8-EDD5F2B3D048}.Debug|Win32.ActiveCfg = Debug|Win32 31 | {A0C1300E-DBEA-409A-B9C8-EDD5F2B3D048}.Debug|Win32.Build.0 = Debug|Win32 32 | {A0C1300E-DBEA-409A-B9C8-EDD5F2B3D048}.Debug|x64.ActiveCfg = Debug|x64 33 | {A0C1300E-DBEA-409A-B9C8-EDD5F2B3D048}.Debug|x64.Build.0 = Debug|x64 34 | {A0C1300E-DBEA-409A-B9C8-EDD5F2B3D048}.Release|Win32.ActiveCfg = Release|Win32 35 | {A0C1300E-DBEA-409A-B9C8-EDD5F2B3D048}.Release|Win32.Build.0 = Release|Win32 36 | {A0C1300E-DBEA-409A-B9C8-EDD5F2B3D048}.Release|x64.ActiveCfg = Release|x64 37 | {A0C1300E-DBEA-409A-B9C8-EDD5F2B3D048}.Release|x64.Build.0 = Release|x64 38 | {1A37077A-5A18-4104-94EE-D21523B70DCB}.Debug|Win32.ActiveCfg = Debug|Win32 39 | {1A37077A-5A18-4104-94EE-D21523B70DCB}.Debug|Win32.Build.0 = Debug|Win32 40 | {1A37077A-5A18-4104-94EE-D21523B70DCB}.Debug|x64.ActiveCfg = Debug|x64 41 | {1A37077A-5A18-4104-94EE-D21523B70DCB}.Debug|x64.Build.0 = Debug|x64 42 | {1A37077A-5A18-4104-94EE-D21523B70DCB}.Release|Win32.ActiveCfg = Release|Win32 43 | {1A37077A-5A18-4104-94EE-D21523B70DCB}.Release|Win32.Build.0 = Release|Win32 44 | {1A37077A-5A18-4104-94EE-D21523B70DCB}.Release|x64.ActiveCfg = Release|x64 45 | {1A37077A-5A18-4104-94EE-D21523B70DCB}.Release|x64.Build.0 = Release|x64 46 | {FBA5880C-FC70-4A1D-97AE-532EA10387B4}.Debug|Win32.ActiveCfg = Debug|Win32 47 | {FBA5880C-FC70-4A1D-97AE-532EA10387B4}.Debug|Win32.Build.0 = Debug|Win32 48 | {FBA5880C-FC70-4A1D-97AE-532EA10387B4}.Debug|x64.ActiveCfg = Debug|x64 49 | {FBA5880C-FC70-4A1D-97AE-532EA10387B4}.Debug|x64.Build.0 = Debug|x64 50 | {FBA5880C-FC70-4A1D-97AE-532EA10387B4}.Release|Win32.ActiveCfg = Release|Win32 51 | {FBA5880C-FC70-4A1D-97AE-532EA10387B4}.Release|Win32.Build.0 = Release|Win32 52 | {FBA5880C-FC70-4A1D-97AE-532EA10387B4}.Release|x64.ActiveCfg = Release|x64 53 | {FBA5880C-FC70-4A1D-97AE-532EA10387B4}.Release|x64.Build.0 = Release|x64 54 | {F948423A-1891-473F-9E11-49D1CD7C7239}.Debug|Win32.ActiveCfg = Debug|Win32 55 | {F948423A-1891-473F-9E11-49D1CD7C7239}.Debug|Win32.Build.0 = Debug|Win32 56 | {F948423A-1891-473F-9E11-49D1CD7C7239}.Debug|x64.ActiveCfg = Debug|x64 57 | {F948423A-1891-473F-9E11-49D1CD7C7239}.Debug|x64.Build.0 = Debug|x64 58 | {F948423A-1891-473F-9E11-49D1CD7C7239}.Release|Win32.ActiveCfg = Release|Win32 59 | {F948423A-1891-473F-9E11-49D1CD7C7239}.Release|Win32.Build.0 = Release|Win32 60 | {F948423A-1891-473F-9E11-49D1CD7C7239}.Release|x64.ActiveCfg = Release|x64 61 | {F948423A-1891-473F-9E11-49D1CD7C7239}.Release|x64.Build.0 = Release|x64 62 | {05438FD4-F4E8-4491-B969-AF56A01C85BD}.Debug|Win32.ActiveCfg = Debug|Win32 63 | {05438FD4-F4E8-4491-B969-AF56A01C85BD}.Debug|Win32.Build.0 = Debug|Win32 64 | {05438FD4-F4E8-4491-B969-AF56A01C85BD}.Debug|x64.ActiveCfg = Debug|x64 65 | {05438FD4-F4E8-4491-B969-AF56A01C85BD}.Debug|x64.Build.0 = Debug|x64 66 | {05438FD4-F4E8-4491-B969-AF56A01C85BD}.Release|Win32.ActiveCfg = Release|Win32 67 | {05438FD4-F4E8-4491-B969-AF56A01C85BD}.Release|Win32.Build.0 = Release|Win32 68 | {05438FD4-F4E8-4491-B969-AF56A01C85BD}.Release|x64.ActiveCfg = Release|x64 69 | {05438FD4-F4E8-4491-B969-AF56A01C85BD}.Release|x64.Build.0 = Release|x64 70 | {880DC02D-6FA6-44DF-A9F1-BBE1C557BADF}.Debug|Win32.ActiveCfg = Debug|Win32 71 | {880DC02D-6FA6-44DF-A9F1-BBE1C557BADF}.Debug|Win32.Build.0 = Debug|Win32 72 | {880DC02D-6FA6-44DF-A9F1-BBE1C557BADF}.Debug|x64.ActiveCfg = Debug|x64 73 | {880DC02D-6FA6-44DF-A9F1-BBE1C557BADF}.Debug|x64.Build.0 = Debug|x64 74 | {880DC02D-6FA6-44DF-A9F1-BBE1C557BADF}.Release|Win32.ActiveCfg = Release|Win32 75 | {880DC02D-6FA6-44DF-A9F1-BBE1C557BADF}.Release|Win32.Build.0 = Release|Win32 76 | {880DC02D-6FA6-44DF-A9F1-BBE1C557BADF}.Release|x64.ActiveCfg = Release|x64 77 | {880DC02D-6FA6-44DF-A9F1-BBE1C557BADF}.Release|x64.Build.0 = Release|x64 78 | {1FB80404-C836-4EAE-9842-88D343A190A3}.Debug|Win32.ActiveCfg = Debug|Win32 79 | {1FB80404-C836-4EAE-9842-88D343A190A3}.Debug|Win32.Build.0 = Debug|Win32 80 | {1FB80404-C836-4EAE-9842-88D343A190A3}.Debug|x64.ActiveCfg = Debug|x64 81 | {1FB80404-C836-4EAE-9842-88D343A190A3}.Debug|x64.Build.0 = Debug|x64 82 | {1FB80404-C836-4EAE-9842-88D343A190A3}.Release|Win32.ActiveCfg = Release|Win32 83 | {1FB80404-C836-4EAE-9842-88D343A190A3}.Release|Win32.Build.0 = Release|Win32 84 | {1FB80404-C836-4EAE-9842-88D343A190A3}.Release|x64.ActiveCfg = Release|x64 85 | {1FB80404-C836-4EAE-9842-88D343A190A3}.Release|x64.Build.0 = Release|x64 86 | {88AE46DE-5CD8-49F1-948F-E86A7CBF092F}.Debug|Win32.ActiveCfg = Debug|Win32 87 | {88AE46DE-5CD8-49F1-948F-E86A7CBF092F}.Debug|Win32.Build.0 = Debug|Win32 88 | {88AE46DE-5CD8-49F1-948F-E86A7CBF092F}.Debug|x64.ActiveCfg = Debug|x64 89 | {88AE46DE-5CD8-49F1-948F-E86A7CBF092F}.Debug|x64.Build.0 = Debug|x64 90 | {88AE46DE-5CD8-49F1-948F-E86A7CBF092F}.Release|Win32.ActiveCfg = Release|Win32 91 | {88AE46DE-5CD8-49F1-948F-E86A7CBF092F}.Release|Win32.Build.0 = Release|Win32 92 | {88AE46DE-5CD8-49F1-948F-E86A7CBF092F}.Release|x64.ActiveCfg = Release|x64 93 | {88AE46DE-5CD8-49F1-948F-E86A7CBF092F}.Release|x64.Build.0 = Release|x64 94 | {03AF960F-61CD-470A-B0E1-7D142690DC30}.Debug|Win32.ActiveCfg = Debug|Win32 95 | {03AF960F-61CD-470A-B0E1-7D142690DC30}.Debug|Win32.Build.0 = Debug|Win32 96 | {03AF960F-61CD-470A-B0E1-7D142690DC30}.Debug|x64.ActiveCfg = Debug|x64 97 | {03AF960F-61CD-470A-B0E1-7D142690DC30}.Debug|x64.Build.0 = Debug|x64 98 | {03AF960F-61CD-470A-B0E1-7D142690DC30}.Release|Win32.ActiveCfg = Release|Win32 99 | {03AF960F-61CD-470A-B0E1-7D142690DC30}.Release|Win32.Build.0 = Release|Win32 100 | {03AF960F-61CD-470A-B0E1-7D142690DC30}.Release|x64.ActiveCfg = Release|x64 101 | {03AF960F-61CD-470A-B0E1-7D142690DC30}.Release|x64.Build.0 = Release|x64 102 | EndGlobalSection 103 | GlobalSection(SolutionProperties) = preSolution 104 | HideSolutionNode = FALSE 105 | EndGlobalSection 106 | EndGlobal 107 | -------------------------------------------------------------------------------- /open.gl/Exercise/debug.cpp: -------------------------------------------------------------------------------- 1 | // check the compile 2 | GLint vertex_status; 3 | glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &vertex_status); 4 | if (vertex_status != GL_TRUE) 5 | { 6 | char vertex_buffer[512]; 7 | glGetShaderInfoLog(vertexShader, 512, NULL, vertex_buffer); 8 | printf("\n%s\n", vertex_buffer); 9 | } 10 | 11 | // check the compile 12 | GLint fragment_status; 13 | glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &fragment_status); 14 | if (fragment_status != GL_TRUE) 15 | { 16 | char fragment_buffer[512]; 17 | glGetShaderInfoLog(fragmentShader, 512, NULL, fragment_buffer); 18 | printf("\n%s\n", fragment_buffer); 19 | } 20 | -------------------------------------------------------------------------------- /open.gl/Exercise/image/sample.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pezy/ReadingNotes/37b2b4757ec6a6baf6b8fd9b19a06e7ff7fc49f3/open.gl/Exercise/image/sample.png -------------------------------------------------------------------------------- /open.gl/Exercise/image/sample2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pezy/ReadingNotes/37b2b4757ec6a6baf6b8fd9b19a06e7ff7fc49f3/open.gl/Exercise/image/sample2.png -------------------------------------------------------------------------------- /open.gl/README.md: -------------------------------------------------------------------------------- 1 | # Notes 2 | 3 | ## Introduction 4 | 5 | This guide just introduce `shader` (new parts of the OpenGL specification). 6 | 7 | Prerequisites: 8 | 9 | - creating the context and handling input: [SDL](https://www.libsdl.org/), [GLFW](https://github.com/glfw/glfw) 10 | - use newer OpenGL functions: [GLEW](https://github.com/nigels-com/glew) 11 | - vectors and matrices: [GLM](https://github.com/g-truc/glm) 12 | 13 | ## context 14 | 15 | SDL: 16 | 17 | - include 18 | - lib: SDL2 and SDL2main 19 | - dll: SDL2.dll, SDL2.so 20 | 21 | GLEW: 22 | 23 | - include 24 | - lib (static): glew32s.lib (`GLEW_STATIC`) 25 | 26 | Code: 27 | 28 | ```cpp 29 | #include "stdio.h" 30 | 31 | #define GLEW_STATIC 32 | #include 33 | 34 | #include 35 | #include 36 | 37 | int main(int argc, char *argv[]) 38 | { 39 | SDL_Init(SDL_INIT_VIDEO); 40 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); 41 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); 42 | SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); 43 | 44 | SDL_Window* window = SDL_CreateWindow("OpenGL", 100, 100, 800, 600, SDL_WINDOW_OPENGL); 45 | SDL_GLContext context = SDL_GL_CreateContext(window); 46 | 47 | glewExperimental = GL_TRUE; 48 | glewInit(); 49 | GLuint vertexBuffer; 50 | glGenBuffers(1, &vertexBuffer); 51 | 52 | printf("%u\n", vertexBuffer); 53 | 54 | SDL_Event windowEvent; 55 | while (true) 56 | { 57 | if (SDL_PollEvent(&windowEvent)) 58 | { 59 | if (windowEvent.type == SDL_QUIT) break; 60 | else if (windowEvent.type == SDL_KEYUP && 61 | windowEvent.key.keysym.sym == SDLK_ESCAPE) break; 62 | } 63 | 64 | SDL_GL_SwapWindow(window); 65 | } 66 | SDL_GL_DeleteContext(context); 67 | 68 | SDL_Quit(); 69 | return 0; 70 | } 71 | ``` 72 | 73 | ## The graphics pipeline 74 | 75 | ![](https://open.gl/media/img/c2_pipeline.png) 76 | 77 | ----- 78 | 79 | 数据是如何变成三维图形的? 80 | 81 | 一切都要从 vertices 说起,我们给出的数据是一个三角形的三个顶点。存放在 vertices 数组中。它将要经历以下几段程序: 82 | 83 | - [***vertex shader***] 84 | 85 | 这货藏在显卡上,就是它将咱们的数据(那三个点)加载到显卡上的,我们给出的数据,可能是三维的,但我们的屏幕却是二维的,这货负责从三维到二维的转换(perspective transformation),同时它还负责某些重要属性(如颜色和纹理坐标等)传输到pipeline中。 86 | 87 | - [***primitives***] 88 | 89 | 这货叫图元,就是基本的几何体,上面不是把顶点坐标传到显卡了吗?接下来它们就要被组装成一个一个基本图元,点、线、三角、四边形等等。还包括一些比较聪明的图元:triangle strip 和 line strips。这俩东西说白了就是偷懒偷出来的,啥意思呢?譬如两个三角形挨着,那么他们一定共用着一条线,我们想办法让这条线只画一次。于是就有了这些 strips. 90 | 91 | - [***geometry shader***] 92 | 93 | 这一步是可选的,这货也刚出世不久。和上面那些搬运工、装配工相比,它可不一般,它接收到 primitives 后,会对其进行存储、优化、修正等等一系列事情,然后可能产生更加全面的数据。咱都知道,GPU 和 CPU 之间传输效率是个瓶颈,但这货可以帮你权衡到底哪些才是 GPU 真正需要的。 94 | 95 | - [***rasterizer***] 96 | 97 | 当上述一系列图形都准备好,光栅器出场了,这家伙曾在[知乎](http://www.zhihu.com/question/24786878)上引出几位图形学大牛热烈的探讨,实现一个 rasterizer 应该算是图形学真正入门的标志。这货会将可视化的图形转换为像素片段(pixel-sized *fragments*),如上面那张图画的那样,就连原本平滑变化的颜色也要计算插值,然后分布在各个片段上。 98 | 99 | - [***fragment shader***] 100 | 101 | 这货主要就是干插值的,将各种属性(诸如颜色、纹理,乃至光照与阴影),分配到各个像素片段上。它还能删减一些片段,让其看起来是透明效果。 102 | 103 | - [***blending and tests***] 104 | 105 | 最后就是混合调配,加上深度模板测试(depth and stencil testing)等等。譬如一个三角形被另一个三角形挡住,那么应该让上面那个显示在屏幕上。 106 | 107 | 就这样,我们输入的一个个数据,变成了三维图形。 108 | 109 | ----- 110 | 111 | ### Vertices 112 | 113 | glBufferData 最后一个参数: 114 | 115 | - `GL_STATIC_DRAW`: The vertex data will be uploaded once and drawn many times (e.g. the world). 116 | - `GL_DYNAMIC_DRAW`: The vertex data will be changed from time to time, but drawn many times more than that. 117 | - `GL_STREAM_DRAW`: The vertex data will change almost every time it's drawn (e.g. user interface). 118 | 119 | ----- 120 | 121 | 两种绘制方式:Vertices and Uniforms 122 | 123 | Uniforms 高级的地方在于,它可以提取 program 中定义为 uniform 类型的值(譬如颜色),然后可以做到在循环渲染中不断改变,使图形呈现动态的效果。 124 | 125 | ```cpp 126 | glGetUniformLocation // 取值 127 | glUniform3f // 设值 128 | ``` 129 | 130 | ----- 131 | 132 | Vertices shader 和 fragment shader 可以用 in 和 out 同名参数来进行连接。 133 | 134 | ----- 135 | 136 | ### Element buffers 137 | 138 | 这种方式有点像咱们在OSG里面的DrawElementsUInt,可以把你要绘制的所有点,都先放到 vertices 中,然后根据按照某种顺序连接部分点。这样就实现了点的**复用**。而这个顺序,就存在 elements 数组中。 139 | 140 | ```cpp 141 | GLuint ebo; 142 | glGenBuffers(1, &ebo); 143 | glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); 144 | glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW); 145 | ``` 146 | 147 | ### vao, vbo, ebo 148 | 149 | 我们总结一下,vao(Vertex Array Objects) 出现在程序的开始,作为顶点数组的缓存。vbo(Vertex Buffer Object) 和 ebo 类似,都是基于特定类型数组的绑定,是我们数据的来源。 150 | 151 | ----- 152 | 153 | Exercise [01](Exercise/01/main.cpp) | [02](Exercise/02/main.cpp) | [03](Exercise/03/main.cpp) 154 | 155 | ----- 156 | 157 | ## Textures objects and parameters 158 | 159 | >texture coordinates 160 | 161 | ```cpp 162 | _ _ _ (1,1) 163 | | | 164 | | | 165 | |_ _ _| 166 | (0,0) 167 | ``` 168 | 169 | (0, 0) -> (1, 1) 分别代表左下角和右上角 170 | 171 | >sampling 172 | 173 | 取样, 根据纹理坐标检索像素颜色信息。 174 | 175 | ### (x, y, z) ---> (s, t, r) 176 | 177 | ----- 178 | 179 | >While linear interpolation gives a smoother result, it isn't always the most ideal option. Nearest neighbour interpolation is more suited in games that want to mimic 8 bit graphics, because of the pixelated look. 180 | 181 | linear 更平滑,但 Nearest 更加适合游戏,因其像素化的展示。 182 | 183 | 更常用的是 mipmaps , 其处理结果不仅高质量,而且高效率。 184 | 185 | ```cpp 186 | glGenerateMipmap(GL_TEXTURE_2D); 187 | ``` 188 | 189 | - `GL_NEAREST_MIPMAP_NEAREST` : 一个滤镜,近邻插值,更加贴近像素大小 190 | - `GL_LINEAR_MIPMAP_NEAREST` : 一个滤镜,线性插值 191 | - `GL_NEAREST_MIPMAP_LINEAR` : 两个滤镜,贴近像素大小,且线性插值 192 | - `GL_LINEAR_MIPMAP_LINEAR` : 两个滤镜,线性插值 193 | 194 | ----- 195 | 196 | ### Loading texture images 197 | 198 | ```cpp 199 | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_FLOAT, pixels); 200 | ^ ^ ^ ^(0) v v ^ 201 | LOD | width&height |_______|________| 202 | internal pixel format format type array 203 | ``` 204 | 205 | ## Transformations in OpenGL 206 | 207 | 物体坐标系 -----> 世界坐标系 -----> 相机坐标系 -----> 投影坐标系 208 | ^ ^ ^ 209 | model matrix view matrix projection matrix 210 | 211 | ----- 212 | 213 | ### Field-of-view 214 | 215 | ![FOV](https://open.gl/media/img/c4_fov.png) 216 | 217 | ## Depth buffer 218 | 219 | > *Z-buffering* is a way of keeping track of the depth of every pixel on the screen. 220 | 221 | ** depth testing ** 222 | 223 | 深度测试是啥意思? 224 | 225 | 比较两个 fragment 的深度值,谁更贴近表面(离用户视角更近),它就应该覆盖另一个,另一个甚至可以被舍弃。 226 | 227 | 而 OpenGL 用来存储这些深度值的 buffer,就叫 depth buffer. depth testing 默认是不开启的,因为它对性能会有很大的影响,要开启它,需要调用: 228 | 229 | glEnable(GL_DEPTH_TEST); 230 | 231 | 并且应该在循环中时刻清空 depth buffer, 确保默认值 1.0f. 232 | 233 | glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 234 | 235 | ## Stencil buffer 236 | 237 | 这个 buffer 决定了哪些该画,哪些不该画。它是依赖 depth buffer 的,如果 depth test fails, 它也不会继续决定了。 238 | 239 | ## Basic geometry shader 240 | 241 | ### Input type 242 | 243 | - points - GL_POINTS(1 vertex) 244 | - lines - GL_LINES, GL_LINE_STRIP, GL_LINE_LIST (2 vertices) 245 | - lines_adjacency - GL_LINES_ADJACENCY, GL_LINE_STRIP_ADJACENCY (4 vertices) 246 | - triangles - GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN (3 vertices) 247 | - triangles_adjacency - GL_TRIANGLES_ADJACENCY, GL_TRIANGLE_STRIP_ADJACENCY (6 vertices) 248 | 249 | ### Output type 250 | 251 | - points 252 | - line_strip 253 | - triangle_strip 254 | -------------------------------------------------------------------------------- /tdd_py/note.md: -------------------------------------------------------------------------------- 1 | # Note 2 | 3 | ## 功能测试与单元测试 4 | 5 | 功能测试是从用户的角度出发,描述应用的新功能,而单元测试是从程序员角度出发,描述希望代码实现的效果。应先写功能测试,并写代码让其顺利通过;然后再写单元测试,保证每一行应用代码都编写一个单元测试,然后用少量代码让单元测试通过。如此往复。 6 | 7 | 功能测试站在高层驱动开发;单元测试站在低层驱动开发。 8 | 9 | -------------------------------------------------------------------------------- /tdd_py/superlists/functional_tests.py: -------------------------------------------------------------------------------- 1 | from selenium import webdriver 2 | import unittest 3 | 4 | class NewVisitorTest(unittest.TestCase): 5 | def setUp(self): 6 | self.browser = webdriver.Firefox() 7 | def tearDown(self): 8 | self.browser.quit() 9 | def test_can_start_a_list_and_retrieve_it_later(self): 10 | self.browser.get("http://localhost:8000") 11 | self.assertIn('To-Do', self.browser.title) 12 | 13 | if __name__ == '__main__': 14 | unittest.main() 15 | -------------------------------------------------------------------------------- /tdd_py/superlists/lists/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /tdd_py/superlists/lists/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ListsConfig(AppConfig): 5 | name = 'lists' 6 | -------------------------------------------------------------------------------- /tdd_py/superlists/lists/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /tdd_py/superlists/lists/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | from django.urls import resolve 3 | from django.http import HttpRequest 4 | from lists.views import home_page 5 | 6 | class HomePageTest(TestCase): 7 | def test_root_url_resolves_to_home_page_view(self): 8 | found = resolve('/') 9 | self.assertEqual(found.func, home_page) 10 | def test_home_page_returns_correct_html(self): 11 | request = HttpRequest() 12 | response = home_page(request) 13 | html = response.content.decode('utf8') 14 | self.assertTrue(html.startswith('')) 15 | self.assertIn('To-Do lists', html) 16 | self.assertTrue(html.endswith('')) 17 | -------------------------------------------------------------------------------- /tdd_py/superlists/lists/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from django.http import HttpResponse 3 | 4 | def home_page(request): 5 | return HttpResponse('To-Do lists') 6 | -------------------------------------------------------------------------------- /tdd_py/superlists/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "superlists.settings") 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError: 10 | # The above import may fail for some other reason. Ensure that the 11 | # issue is really that Django is missing to avoid masking other 12 | # exceptions on Python 2. 13 | try: 14 | import django 15 | except ImportError: 16 | raise ImportError( 17 | "Couldn't import Django. Are you sure it's installed and " 18 | "available on your PYTHONPATH environment variable? Did you " 19 | "forget to activate a virtual environment?" 20 | ) 21 | raise 22 | execute_from_command_line(sys.argv) 23 | -------------------------------------------------------------------------------- /tdd_py/superlists/superlists/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pezy/ReadingNotes/37b2b4757ec6a6baf6b8fd9b19a06e7ff7fc49f3/tdd_py/superlists/superlists/__init__.py -------------------------------------------------------------------------------- /tdd_py/superlists/superlists/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for superlists project. 3 | 4 | Generated by 'django-admin startproject' using Django 1.11.15. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.11/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/1.11/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = '%c+8p5@j4()h^!ds71cmp#zetc#!$0oh5aum%g4237z-zi6u=-' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | ] 41 | 42 | MIDDLEWARE = [ 43 | 'django.middleware.security.SecurityMiddleware', 44 | 'django.contrib.sessions.middleware.SessionMiddleware', 45 | 'django.middleware.common.CommonMiddleware', 46 | 'django.middleware.csrf.CsrfViewMiddleware', 47 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 48 | 'django.contrib.messages.middleware.MessageMiddleware', 49 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 50 | ] 51 | 52 | ROOT_URLCONF = 'superlists.urls' 53 | 54 | TEMPLATES = [ 55 | { 56 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 57 | 'DIRS': [], 58 | 'APP_DIRS': True, 59 | 'OPTIONS': { 60 | 'context_processors': [ 61 | 'django.template.context_processors.debug', 62 | 'django.template.context_processors.request', 63 | 'django.contrib.auth.context_processors.auth', 64 | 'django.contrib.messages.context_processors.messages', 65 | ], 66 | }, 67 | }, 68 | ] 69 | 70 | WSGI_APPLICATION = 'superlists.wsgi.application' 71 | 72 | 73 | # Database 74 | # https://docs.djangoproject.com/en/1.11/ref/settings/#databases 75 | 76 | DATABASES = { 77 | 'default': { 78 | 'ENGINE': 'django.db.backends.sqlite3', 79 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 80 | } 81 | } 82 | 83 | 84 | # Password validation 85 | # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators 86 | 87 | AUTH_PASSWORD_VALIDATORS = [ 88 | { 89 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 90 | }, 91 | { 92 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 93 | }, 94 | { 95 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 96 | }, 97 | { 98 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 99 | }, 100 | ] 101 | 102 | 103 | # Internationalization 104 | # https://docs.djangoproject.com/en/1.11/topics/i18n/ 105 | 106 | LANGUAGE_CODE = 'en-us' 107 | 108 | TIME_ZONE = 'UTC' 109 | 110 | USE_I18N = True 111 | 112 | USE_L10N = True 113 | 114 | USE_TZ = True 115 | 116 | 117 | # Static files (CSS, JavaScript, Images) 118 | # https://docs.djangoproject.com/en/1.11/howto/static-files/ 119 | 120 | STATIC_URL = '/static/' 121 | -------------------------------------------------------------------------------- /tdd_py/superlists/superlists/urls.py: -------------------------------------------------------------------------------- 1 | """superlists URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/1.11/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.conf.urls import url, include 14 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 15 | """ 16 | from django.conf.urls import url 17 | from lists import views 18 | 19 | urlpatterns = [ 20 | url(r'^$', views.home_page, name='home'), 21 | ] 22 | -------------------------------------------------------------------------------- /tdd_py/superlists/superlists/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for superlists project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "superlists.settings") 15 | 16 | application = get_wsgi_application() 17 | --------------------------------------------------------------------------------