├── .github └── workflows │ └── ccpp.yml ├── .gitignore ├── .gitmodules ├── .travis.yml ├── .travis ├── installLinux.sh ├── prepareCmake.sh └── prepareCmakeRelease.sh ├── CMakeLists.txt ├── LICENSE ├── Manuel_utilisation.md ├── README.md ├── README.pdf ├── TODOList.md ├── data ├── default_imgui.ini ├── fonts │ ├── BreeSerif-Regular.ttf │ ├── NotoSerif-Black.ttf │ └── OFL.txt ├── models │ ├── icosa.off │ ├── icosphere.obj │ ├── octahedron.off │ ├── quad.off │ ├── sphere.obj │ ├── sphere.off │ ├── sphereVoxelized.mtl │ ├── sphereVoxelized.obj │ ├── spot.obj │ └── suzanne.off ├── shaders │ ├── debugNormal.frag │ ├── debugNormal.vert │ ├── displayBoundingBox.frag │ ├── displayBoundingBox.vert │ ├── lambertian.frag │ ├── lambertian.vert │ ├── postProcess.frag │ ├── postProcess.vert │ ├── simple.frag │ ├── simple.vert │ ├── texture.frag │ └── texture.vert └── textures │ ├── pattern.jpg │ ├── test.png │ └── water_texture.jpg ├── documentation.pdf ├── imgui.ini ├── ressources ├── TP_graphe_scene.md ├── TP_simplify.md ├── composants.png ├── demo.gif ├── documentation.md ├── documentation.pdf ├── gameloop.png ├── minecraft.jpg ├── planPresentation.md ├── screen2.PNG ├── screen3.PNG ├── screenGreenEngine.PNG ├── screen_editor.PNG ├── screen_game.PNG ├── structure.png ├── terrain_1.png ├── terrain_2.png ├── terrain_2_wire.png ├── terrain_3.png ├── terrain_3_wire.png ├── terrain_deep.png ├── terrain_large.png ├── travis.PNG └── voxel-engine.png ├── src ├── components │ ├── axisRenderer.cpp │ ├── axisRenderer.h │ ├── cameraControllerFirstPerson.cpp │ ├── cameraControllerFirstPerson.h │ ├── cameraFollow.cpp │ ├── cameraFollow.h │ ├── cameraProjective.cpp │ ├── cameraProjective.h │ ├── cameraRenderer.cpp │ ├── cameraRenderer.h │ ├── colliders │ │ ├── collider.cpp │ │ └── collider.h │ ├── component.cpp │ ├── component.h │ ├── debug │ │ ├── debugTransform.cpp │ │ └── debugTransform.h │ ├── fireProjectiles.cpp │ ├── fireProjectiles.h │ ├── groundFollow.cpp │ ├── groundFollow.h │ ├── meshRenderer.cpp │ ├── meshRenderer.h │ ├── playerController.cpp │ ├── playerController.h │ ├── projectile.cpp │ ├── projectile.h │ ├── renderer.h │ ├── rigidbody.cpp │ ├── rigidbody.h │ ├── terrainModificator.cpp │ ├── terrainModificator.h │ ├── thirdPersonController.cpp │ └── thirdPersonController.h ├── engineClass │ ├── InputManager.cpp │ ├── InputManager.h │ ├── UI.cpp │ ├── UI.h │ ├── gameObject.cpp │ ├── gameObject.h │ ├── gameObject.inl │ ├── mainRenderer.cpp │ ├── mainRenderer.h │ ├── scene.cpp │ └── scene.h ├── main.cpp ├── material │ ├── lambertian.cpp │ ├── lambertian.h │ ├── material.cpp │ ├── material.h │ ├── shader.cpp │ ├── shader.h │ ├── simpleMat.cpp │ ├── simpleMat.h │ ├── textureMaterial.cpp │ └── textureMaterial.h ├── models │ ├── mesh │ │ ├── mesh.cpp │ │ ├── mesh.h │ │ ├── meshCube.cpp │ │ └── meshCube.h │ ├── transform.cpp │ └── transform.h ├── terrain │ ├── cubicArray.h │ ├── cubicArray.inl │ ├── simplexNoise.cpp │ ├── simplexNoise.h │ ├── terrainChunk.cpp │ ├── terrainChunk.h │ ├── terrainManager.cpp │ ├── terrainManager.h │ └── voxel.h └── tools │ └── lights │ ├── directionnalLight.cpp │ ├── directionnalLight.h │ └── light.h └── thirdparty ├── CMakeLists.txt ├── imgui ├── CMakeLists.txt ├── imconfig.h ├── imgui.cpp ├── imgui.h ├── imgui_demo.cpp ├── imgui_draw.cpp ├── imgui_impl_glfw.cpp ├── imgui_impl_glfw.h ├── imgui_impl_opengl3.cpp ├── imgui_impl_opengl3.h ├── imgui_internal.h ├── imgui_widgets.cpp ├── imstb_rectpack.h ├── imstb_textedit.h └── imstb_truetype.h ├── stb_image ├── stb_image.h ├── stb_image_resize.h └── stb_image_write.h └── utilities ├── catch.hpp ├── drawDebug.h ├── glmCout.h └── glm_display.h /.github/workflows/ccpp.yml: -------------------------------------------------------------------------------- 1 | name: C/C++ CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v2 12 | - name: Checkout submodules 13 | shell: bash 14 | run: | 15 | auth_header="$(git config --local --get http.https://github.com/.extraheader)" 16 | git submodule sync --recursive 17 | git -c "http.extraheader=$auth_header" -c protocol.version=2 submodule update --init --force --recursive --depth=1 18 | - name: install dependancies 19 | run: sudo apt-get update -qq && sudo apt-get install -y build-essential cmake xorg-dev libgl1-mesa-dev libfreetype6-dev 20 | - name: configure cmake 21 | run: mkdir build && cd build && cmake .. 22 | - name: compile 23 | run: cd build && cmake --build . 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | .vscode -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "thirdparty/glfw"] 2 | path = thirdparty/glfw 3 | url = https://github.com/glfw/glfw.git 4 | [submodule "thirdparty/glad"] 5 | path = thirdparty/glad 6 | url = https://github.com/Dav1dde/glad.git 7 | [submodule "thirdparty/glm"] 8 | path = thirdparty/glm 9 | url = https://github.com/TheSpyGeek/glm_without_test 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | os: linux 2 | language: cpp 3 | 4 | # safelist 5 | branches: 6 | only: 7 | - master 8 | - stable 9 | - develop 10 | 11 | stage: 12 | - build 13 | - build Release 14 | - tests 15 | - deploy 16 | 17 | jobs: 18 | include: 19 | - stage: build 20 | name: "Linux Build Debug" 21 | os: linux 22 | install: 23 | - bash .travis/installLinux.sh 24 | - bash .travis/prepareCmake.sh 25 | script: 26 | - cd build && make -j 27 | 28 | - stage: build 29 | name: "MacOS Build Debug" 30 | os: osx 31 | install: 32 | - bash .travis/prepareCmake.sh 33 | script: 34 | - cd build && make -j 35 | - stage: build 36 | name: "Windows MVS 2017 Build Debug" 37 | os: windows 38 | install: 39 | - mkdir build && cd build 40 | - cmake -G "Visual Studio 15 2017" .. 41 | script: 42 | - cmake --build . 43 | - stage: build 44 | name: "Windows MinGW Build Debug" 45 | os: windows 46 | addons: 47 | apt: 48 | packages: 49 | - mingw-w64 50 | - mingw-w64-tools 51 | - mingw-w64-x86-64-dev 52 | - mingw-w64-x86-64-gcc 53 | - mingw-w64-x86-64-gcc-libgfortran 54 | - mingw-w64-x86-64-gcc-fortran 55 | - mingw-w64-x86-64-headers 56 | - cmake 57 | install: 58 | - mkdir build && cd build 59 | - cmake -G "MinGW Makefiles" -DCMAKE_SH="CMAKE_SH-NOTFOUND" .. 60 | script: 61 | - cmake --build . 62 | 63 | - stage: build Release 64 | name: "Linux Build Release" 65 | os: linux 66 | install: 67 | - bash .travis/installLinux.sh 68 | - bash .travis/prepareCmakeRelease.sh 69 | script: 70 | - cd build && make -j 71 | 72 | - stage: build Release 73 | name: "MacOS Build Release" 74 | os: osx 75 | install: 76 | - bash .travis/prepareCmakeRelease.sh 77 | script: 78 | - cd build && make -j 79 | - stage: build Release 80 | name: "Windows MVS 2017 Build Release" 81 | os: windows 82 | install: 83 | - mkdir build && cd build 84 | - cmake -G "Visual Studio 15 2017" -DCMAKE_BUILD_TYPE=Release .. 85 | script: 86 | - cmake --build . 87 | - stage: build Release 88 | name: "Windows MinGW Build Release" 89 | os: windows 90 | addons: 91 | apt: 92 | packages: 93 | - mingw-w64 94 | - mingw-w64-tools 95 | - mingw-w64-x86-64-dev 96 | - mingw-w64-x86-64-gcc 97 | - mingw-w64-x86-64-gcc-libgfortran 98 | - mingw-w64-x86-64-gcc-fortran 99 | - mingw-w64-x86-64-headers 100 | - cmake 101 | install: 102 | - mkdir build && cd build 103 | - cmake -G "MinGW Makefiles" -DCMAKE_SH="CMAKE_SH-NOTFOUND" -DCMAKE_BUILD_TYPE=Release .. 104 | script: 105 | - cmake --build . 106 | -------------------------------------------------------------------------------- /.travis/installLinux.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | sudo apt-get update -qq 4 | sudo apt-get install -y build-essential cmake xorg-dev libgl1-mesa-dev libfreetype6-dev 5 | -------------------------------------------------------------------------------- /.travis/prepareCmake.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | mkdir build && cd build && cmake -DCMAKE_BUILD_TYPE=Debug .. -------------------------------------------------------------------------------- /.travis/prepareCmakeRelease.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | mkdir build && cd build && cmake -DCMAKE_BUILD_TYPE=Release .. -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(PROJECT_NAME voxel-engine) 2 | 3 | cmake_minimum_required(VERSION 2.8) 4 | 5 | 6 | project(${PROJECT_NAME}) 7 | 8 | 9 | 10 | ###### BUILD THIRDPARTY ####### 11 | 12 | # affectation des variables pour les includes 13 | set(GLM_INCLUDE_DIR thirdparty/glm) 14 | set(GLFW_INCLUDE_DIR thirdparty/glfw/include) 15 | set(IMGUI_INCLUDE_DIR thirdparty/imgui) 16 | set(GLAD_INCLUDE_DIR thirdparty/glad/include) 17 | set(STB_IMAGE_DIR thirdparty/stb_image) 18 | set(UTILITIES_DIR thirdparty/utilities) 19 | 20 | 21 | # 3rd party libraries 22 | add_subdirectory(thirdparty) 23 | 24 | #find_package(glm) 25 | #find_package(glfw) 26 | #find_package(imgui) 27 | 28 | # pour ajouter le fichier par défaut de ImGui 29 | configure_file(data/default_imgui.ini imgui.ini COPYONLY) 30 | 31 | 32 | ###### BUILD OPTION ####### 33 | 34 | # BUILD TYPE = Debug | Release 35 | if( NOT CMAKE_BUILD_TYPE ) 36 | set(CMAKE_BUILD_TYPE Debug) 37 | message("BUILD TYPE = Debug | Release") 38 | endif() 39 | 40 | if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") 41 | message("DEBUG MODE ACTIVATED") 42 | endif() 43 | 44 | if("${CMAKE_BUILD_TYPE}" STREQUAL "Release") 45 | message("RELEASE MODE ACTIVATED") 46 | endif() 47 | 48 | add_definitions(-pthread ) 49 | add_definitions(-DIMGUI_IMPL_OPENGL_LOADER_GLAD) 50 | add_definitions(-DGLFW_INCLUDE_NONE) 51 | 52 | 53 | if("${CMAKE_BUILD_TYPE}" STREQUAL "Release") 54 | add_definitions(-O3 -DNDEBUG) 55 | endif() 56 | 57 | # si le compilateur est Visual Studio 58 | if (CMAKE_GENERATOR MATCHES "Visual Studio") 59 | # Do Visual Studio specific stuff 60 | else() 61 | if (CMAKE_GENERATOR MATCHES "MinGW") 62 | else() 63 | add_definitions(-std=c++11) 64 | if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") 65 | add_definitions(-g) 66 | add_definitions(-Wformat -Wall -Wdelete-non-virtual-dtor -Wshadow -Wextra) 67 | # add_definitions(-pedantic -fsanitize=address -fno-omit-frame-pointer) 68 | # set(CMAKE_EXE_LINKER_FLAGS -fsanitize=address) 69 | endif() 70 | endif() 71 | 72 | endif() 73 | 74 | message("Generator : ${CMAKE_GENERATOR}") 75 | 76 | 77 | 78 | 79 | 80 | #### SET SOURCES #### 81 | 82 | 83 | # SRCS prends la valeur des sources 84 | file(GLOB_RECURSE SRCS 85 | src/*.c 86 | src/*.cpp 87 | ) 88 | 89 | # SRCS prends la valeur des headers 90 | file(GLOB_RECURSE HEADERS 91 | src/*.h 92 | src/*.hpp 93 | ) 94 | 95 | 96 | 97 | 98 | add_executable(${PROJECT_NAME} ${HEADERS} ${SRCS}) 99 | 100 | # ajout des includes directory 101 | include_directories( 102 | ${GLM_INCLUDE_DIR} 103 | ${GLFW_INCLUDE_DIR} 104 | ${GLAD_INCLUDE_DIR} 105 | ${IMGUI_INCLUDE_DIR} 106 | ${OPENGL_INCLUDE_DIR} 107 | ${STB_IMAGE_DIR} 108 | ${UTILITIES_DIR} 109 | ) 110 | 111 | target_link_libraries(${PROJECT_NAME} glfw glm glad imgui ${CMAKE_DL_LIBS}) 112 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 maximeI 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Manuel_utilisation.md: -------------------------------------------------------------------------------- 1 | # Manuel d'utilisation 2 | 3 | ## Controles 4 | 5 | On lancement du jeu, vous controlez le personnage, vous pouvez : 6 | * vous déplacer avec ZQSD 7 | * tourner la caméra avec la souris 8 | 9 | Si vous faites ```CTRL + U``` vous passez en mode "editeur" vous pouvez maintenant : 10 | * Orienter la camera en appuyant sur le clic gauche de la souris et en déplaçant la souris 11 | * Bouger la caméra sur les cotés en appuyant sur le clic droit de la souris 12 | * ```CTRL + H``` pour afficher/cacher l'interface 13 | * vous pouvez toujours déplacer le personnage et voir le terrain se charger 14 | 15 | 16 | 17 | ## Compiler le code 18 | 19 | ##### Sur Linux 20 | 21 | Dependencies : 22 | 23 | ```sudo apt-get install -y build-essential cmake xorg-dev libgl1-mesa-dev libfreetype6-dev``` 24 | 25 | Pour compiler : 26 | 27 | ```cd build && cmake .. && make``` 28 | 29 | ##### Sur Windows 30 | 31 | Dependencies : 32 | 33 | * mingw64 ou mingw32 34 | * cmake 35 | 36 | Pour compiler : 37 | 38 | * Lancer ```Cmake``` 39 | * Configurer avec les ```Mingw Makefile``` pour compiler dans le dossier ```build``` 40 | * Lancer ```mingw64``` 41 | * Aller dans le dossier ```build``` 42 | * Compiler avec ```mingw32-make``` 43 | 44 | Pour lancer le programme : 45 | 46 | ```./green-engine``` 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Voxel-Engine 2 | 3 | [![Build Status](https://travis-ci.com/TheSpyGeek/VoxelEngine.svg?branch=master)](https://travis-ci.com/TheSpyGeek/VoxelEngine) 4 | 5 | Voxel-Engine is a WIP game engine specialized for voxel rendering. It is made by 2 students to learn the process of creating a game engine. 6 | 7 | ![terrain_1](ressources/terrain_1.png) 8 | 9 | ![terrain_deep](ressources/terrain_deep.png) 10 | 11 | ![terrain_large](ressources/terrain_large.png) 12 | 13 | #### Features 14 | 15 | ###### Jeu 16 | 17 | * you can shoot projectile by pushing F 18 | 19 | ###### Change transform 20 | 21 | * Change position 22 | * Change orientation 23 | * Change scale 24 | * Animate orientation 25 | 26 | ###### Change tools position 27 | 28 | * Change camera position, fov, orientation 29 | * Change light position 30 | 31 | ###### Display 32 | 33 | * Activate/Deactivate display in wire frame 34 | 35 | ###### Components 36 | 37 | The components are in the folder ```src/components/``` 38 | 39 | * Camera Follow : follow the objet attached to 40 | * Axis Renderer : display axis in the camera Editor 41 | * Camera Controller First Person : allow to move and rotate the camera with left and right click 42 | * Camera Projective : functions needed to make a projective camera 43 | * Camera Renderer : WIP, display the camera in the editor 44 | * Chunk Renderer : display a terrain composed of chunks with OpenGL 45 | * Controller : allow to interactively strafe and go forward and backward 46 | * Mesh Renderer : display in the screen with OpenGL the mesh 47 | * Third Person Controller : allow to move the camera around an objet like in a third person game 48 | 49 | #### How to clone 50 | 51 | ```git clone --recursive https://github.com/TheSpyGeek/VoxelEngine.git``` 52 | 53 | #### Build 54 | 55 | ##### On Linux 56 | 57 | Dependencies : 58 | 59 | ```sudo apt-get install -y build-essential cmake xorg-dev libgl1-mesa-dev libfreetype6-dev``` 60 | 61 | To build : 62 | 63 | ```mkdir build && cd build && cmake .. && make``` 64 | 65 | ##### On Windows 66 | 67 | Dependencies : 68 | 69 | * [Mingw](https://sourceforge.net/projects/mingw-w64/) 70 | * [Cmake](https://cmake.org/download/) 71 | 72 | To build : 73 | 74 | * Create a directory ```build``` 75 | * Run ```Cmake``` 76 | * Configure with ```Mingw Makefile``` 77 | * Run ```mingw64``` 78 | * Go to ```build``` directory 79 | * Compile with ```mingw32-make``` 80 | 81 | ##### On MAC OSX 82 | 83 | Should work 84 | 85 | #### Resources 86 | 87 | * https://sonarlearning.co.uk/coursepage.php?topic=game&course=ext-bb-3d-ged 88 | * https://www.3dgep.com/courses/ 89 | * https://github.com/nothings/stb 90 | * https://jheer.github.io/barnes-hut/ 91 | * https://www.youtube.com/watch?v=BP6NxVxDQIs 92 | * Let's make a voxel engine : https://sites.google.com/site/letsmakeavoxelengine/home/ 93 | * https://community.khronos.org/t/how-to-draw-one-line-on-top-of-another-in-opengl-without-z-fighting/68922 94 | * Free look camera : https://gamedev.stackexchange.com/questions/60266/create-a-fly-camera-with-lookat 95 | * Third person camera : https://www.youtube.com/watch?v=PoxDDZmctnU&list=PLRIWtICgwaX0u7Rf9zkZhLoLuZVfUksDP&index=19 96 | * Voxelizer sur blender : https://www.youtube.com/watch?v=ntVhi8SlOzA 97 | * Voxelizer algorithm : https://github.com/davidstutz/mesh-voxelization 98 | * Travis Windows build : https://github.com/open-license-manager/open-license-manager/blob/dfddf5294677407c3a01b3a13c8348f02fe993ee/.travis.yml 99 | * FBX loader : https://github.com/nem0/OpenFBX/blob/master/demo/main.cpp#L203 100 | * Procedural generation : https://www.youtube.com/watch?v=wbpMiKiSKm8 101 | * Multi-threading : https://www.randygaul.net/wp-content/uploads/2014/09/MultiThread.pdf 102 | * Intersection : https://noonat.github.io/intersect/ 103 | 104 | -------------------------------------------------------------------------------- /README.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/README.pdf -------------------------------------------------------------------------------- /TODOList.md: -------------------------------------------------------------------------------- 1 | # TODOLIST 2 | 3 | * Object importer (.obj) 4 | * pouvoir afficher les uv, normal, position, courbure dans un fenêtre séparé 5 | * custom shader 6 | * faire deux fbo afin de switch pendant qu'un affiche l'autre calcul 7 | * VAO list pour éviter de charger plusieurs fois les maillages 8 | * Pouvoir changer le nom des objets 9 | * fixed FPS (almost done) 10 | * mouse wheel control view 11 | * put the object in the center 12 | * Sphere - Manual Mesh 13 | * implem orthographic camera 14 | * Subdivision curves 15 | * shadows 16 | * rotator 17 | * customable pipeline 18 | * sortie de message sur une console 19 | * imgui.ini par défaut 20 | * Les objets avec un maillage doivent hériter de "MeshObject" 21 | -------------------------------------------------------------------------------- /data/default_imgui.ini: -------------------------------------------------------------------------------- 1 | [Window][Debug##Default] 2 | Pos=60,60 3 | Size=400,400 4 | Collapsed=0 5 | 6 | [Window][Scene Manager] 7 | Pos=1335,230 8 | Size=557,569 9 | Collapsed=0 10 | 11 | [Window][Debug] 12 | Pos=13,13 13 | Size=348,53 14 | Collapsed=0 15 | 16 | [Window][Settings] 17 | Pos=41,560 18 | Size=289,142 19 | Collapsed=0 20 | 21 | [Window][Renderer Setting] 22 | Pos=12,664 23 | Size=303,194 24 | Collapsed=1 25 | 26 | [Window][Game] 27 | Pos=30,232 28 | Size=442,275 29 | Collapsed=0 30 | 31 | [Window][Game View] 32 | Pos=14,360 33 | Size=442,275 34 | Collapsed=0 35 | 36 | [Window][Execution time] 37 | Pos=1626,15 38 | Size=276,157 39 | Collapsed=0 40 | 41 | [Window][Pause Menu] 42 | Pos=792,215 43 | Size=200,92 44 | Collapsed=0 45 | 46 | [Window][MainRenderer Setting] 47 | Pos=5,773 48 | Size=376,223 49 | Collapsed=0 50 | 51 | [Window][Engine mode] 52 | Pos=10,14 53 | Size=129,48 54 | Collapsed=0 55 | 56 | [Window][Controls] 57 | Pos=5,69 58 | Size=274,121 59 | Collapsed=0 60 | 61 | [Window][Play Mode Controls] 62 | Pos=9,200 63 | Size=393,101 64 | Collapsed=0 65 | 66 | [Window][Mode Controls] 67 | Pos=9,195 68 | Size=381,103 69 | Collapsed=0 70 | 71 | -------------------------------------------------------------------------------- /data/fonts/BreeSerif-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/data/fonts/BreeSerif-Regular.ttf -------------------------------------------------------------------------------- /data/fonts/NotoSerif-Black.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/data/fonts/NotoSerif-Black.ttf -------------------------------------------------------------------------------- /data/fonts/OFL.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2011, TypeTogether (www.type-together.com), 2 | with Reserved Font Names "Bree" and "Bree Serif" 3 | 4 | This Font Software is licensed under the SIL Open Font License, Version 1.1. 5 | This license is copied below, and is also available with a FAQ at: 6 | http://scripts.sil.org/OFL 7 | 8 | 9 | ----------------------------------------------------------- 10 | SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 11 | ----------------------------------------------------------- 12 | 13 | PREAMBLE 14 | The goals of the Open Font License (OFL) are to stimulate worldwide 15 | development of collaborative font projects, to support the font creation 16 | efforts of academic and linguistic communities, and to provide a free and 17 | open framework in which fonts may be shared and improved in partnership 18 | with others. 19 | 20 | The OFL allows the licensed fonts to be used, studied, modified and 21 | redistributed freely as long as they are not sold by themselves. The 22 | fonts, including any derivative works, can be bundled, embedded, 23 | redistributed and/or sold with any software provided that any reserved 24 | names are not used by derivative works. The fonts and derivatives, 25 | however, cannot be released under any other type of license. The 26 | requirement for fonts to remain under this license does not apply 27 | to any document created using the fonts or their derivatives. 28 | 29 | DEFINITIONS 30 | "Font Software" refers to the set of files released by the Copyright 31 | Holder(s) under this license and clearly marked as such. This may 32 | include source files, build scripts and documentation. 33 | 34 | "Reserved Font Name" refers to any names specified as such after the 35 | copyright statement(s). 36 | 37 | "Original Version" refers to the collection of Font Software components as 38 | distributed by the Copyright Holder(s). 39 | 40 | "Modified Version" refers to any derivative made by adding to, deleting, 41 | or substituting -- in part or in whole -- any of the components of the 42 | Original Version, by changing formats or by porting the Font Software to a 43 | new environment. 44 | 45 | "Author" refers to any designer, engineer, programmer, technical 46 | writer or other person who contributed to the Font Software. 47 | 48 | PERMISSION & CONDITIONS 49 | Permission is hereby granted, free of charge, to any person obtaining 50 | a copy of the Font Software, to use, study, copy, merge, embed, modify, 51 | redistribute, and sell modified and unmodified copies of the Font 52 | Software, subject to the following conditions: 53 | 54 | 1) Neither the Font Software nor any of its individual components, 55 | in Original or Modified Versions, may be sold by itself. 56 | 57 | 2) Original or Modified Versions of the Font Software may be bundled, 58 | redistributed and/or sold with any software, provided that each copy 59 | contains the above copyright notice and this license. These can be 60 | included either as stand-alone text files, human-readable headers or 61 | in the appropriate machine-readable metadata fields within text or 62 | binary files as long as those fields can be easily viewed by the user. 63 | 64 | 3) No Modified Version of the Font Software may use the Reserved Font 65 | Name(s) unless explicit written permission is granted by the corresponding 66 | Copyright Holder. This restriction only applies to the primary font name as 67 | presented to the users. 68 | 69 | 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font 70 | Software shall not be used to promote, endorse or advertise any 71 | Modified Version, except to acknowledge the contribution(s) of the 72 | Copyright Holder(s) and the Author(s) or with their explicit written 73 | permission. 74 | 75 | 5) The Font Software, modified or unmodified, in part or in whole, 76 | must be distributed entirely under this license, and must not be 77 | distributed under any other license. The requirement for fonts to 78 | remain under this license does not apply to any document created 79 | using the Font Software. 80 | 81 | TERMINATION 82 | This license becomes null and void if any of the above conditions are 83 | not met. 84 | 85 | DISCLAIMER 86 | THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 87 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF 88 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT 89 | OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE 90 | COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 91 | INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL 92 | DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 93 | FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM 94 | OTHER DEALINGS IN THE FONT SOFTWARE. 95 | -------------------------------------------------------------------------------- /data/models/icosa.off: -------------------------------------------------------------------------------- 1 | OFF 2 | 12 20 30 3 | 0.0 0.0 2.0 4 | 1.788854 0.000000 0.894427 5 | 0.552786 1.701302 0.894427 6 | -1.447214 1.051462 0.894427 7 | -1.447214 -1.051462 0.894427 8 | 0.552786 -1.701302 0.894427 9 | 1.447214 1.051462 -0.894427 10 | -0.552786 1.701302 -0.894427 11 | -1.788854 0.000000 -0.894427 12 | -0.552786 -1.701302 -0.894427 13 | 1.447214 -1.051462 -0.894427 14 | 0.0 0.0 -2.0 15 | 3 2 0 1 16 | 3 3 0 2 17 | 3 4 0 3 18 | 3 5 0 4 19 | 3 1 0 5 20 | 3 2 1 6 21 | 3 7 2 6 22 | 3 3 2 7 23 | 3 8 3 7 24 | 3 4 3 8 25 | 3 9 4 8 26 | 3 5 4 9 27 | 3 10 5 9 28 | 3 6 1 10 29 | 3 1 5 10 30 | 3 6 11 7 31 | 3 7 11 8 32 | 3 8 11 9 33 | 3 9 11 10 34 | 3 10 11 6 35 | -------------------------------------------------------------------------------- /data/models/icosphere.obj: -------------------------------------------------------------------------------- 1 | # Blender v2.66 (sub 1) OBJ File: '' 2 | # www.blender.org 3 | o Icosphere_Icosphere.001 4 | v 0.000000 -1.000000 0.000000 5 | v 0.723600 -0.447215 0.525720 6 | v -0.276385 -0.447215 0.850640 7 | v -0.894425 -0.447215 0.000000 8 | v -0.276385 -0.447215 -0.850640 9 | v 0.723600 -0.447215 -0.525720 10 | v 0.276385 0.447215 0.850640 11 | v -0.723600 0.447215 0.525720 12 | v -0.723600 0.447215 -0.525720 13 | v 0.276385 0.447215 -0.850640 14 | v 0.894425 0.447215 0.000000 15 | v 0.000000 1.000000 0.000000 16 | s off 17 | f 1 2 3 18 | f 2 1 6 19 | f 1 3 4 20 | f 1 4 5 21 | f 1 5 6 22 | f 2 6 11 23 | f 3 2 7 24 | f 4 3 8 25 | f 5 4 9 26 | f 6 5 10 27 | f 2 11 7 28 | f 3 7 8 29 | f 4 8 9 30 | f 5 9 10 31 | f 6 10 11 32 | f 7 11 12 33 | f 8 7 12 34 | f 9 8 12 35 | f 10 9 12 36 | f 11 10 12 37 | -------------------------------------------------------------------------------- /data/models/octahedron.off: -------------------------------------------------------------------------------- 1 | OFF 2 | 6 8 12 3 | 0.0 0.0 1.0 4 | 1.0 0.0 0.0 5 | 0.0 1.0 0.0 6 | -1.0 0.0 0.0 7 | 0.0 -1.0 0.0 8 | 0.0 0.0 -1.0 9 | 3 1 0 4 10 | 3 4 0 3 11 | 3 3 0 2 12 | 3 2 0 1 13 | 3 1 5 2 14 | 3 2 5 3 15 | 3 3 5 4 16 | 3 4 5 1 17 | -------------------------------------------------------------------------------- /data/models/quad.off: -------------------------------------------------------------------------------- 1 | OFF 2 | 4 2 4 3 | -1.0 1.0 0.0 4 | 1.0 1.0 0.0 5 | -1.0 -1.0 0.0 6 | 1.0 -1.0 0.0 7 | 3 0 1 2 8 | 3 2 1 3 9 | -------------------------------------------------------------------------------- /data/models/sphereVoxelized.mtl: -------------------------------------------------------------------------------- 1 | # Blender MTL File: 'None' 2 | # Material Count: 1 3 | 4 | newmtl None 5 | Ns 500 6 | Ka 0.8 0.8 0.8 7 | Kd 0.8 0.8 0.8 8 | Ks 0.8 0.8 0.8 9 | d 1 10 | illum 2 11 | -------------------------------------------------------------------------------- /data/shaders/debugNormal.frag: -------------------------------------------------------------------------------- 1 | #version 330 2 | 3 | out vec4 bufferColor; 4 | 5 | in vec3 normal; 6 | 7 | 8 | 9 | void main(){ 10 | 11 | bufferColor = vec4(normal, 1.0); 12 | } 13 | -------------------------------------------------------------------------------- /data/shaders/debugNormal.vert: -------------------------------------------------------------------------------- 1 | #version 330 2 | 3 | // input attributes 4 | layout(location = 0) in vec3 position; 5 | layout(location = 1) in vec3 vertNormal; 6 | 7 | 8 | uniform mat4 modelMat; 9 | uniform mat4 projMat; 10 | uniform mat4 viewMat; 11 | 12 | out vec3 normal; 13 | 14 | void main() { 15 | gl_Position = projMat*viewMat*modelMat*vec4(position, 1.0); 16 | 17 | normal = vertNormal; 18 | } 19 | -------------------------------------------------------------------------------- /data/shaders/displayBoundingBox.frag: -------------------------------------------------------------------------------- 1 | #version 330 2 | 3 | out vec4 bufferColor; 4 | 5 | 6 | void main(){ 7 | bufferColor = vec4(1,0,0,1); 8 | } 9 | -------------------------------------------------------------------------------- /data/shaders/displayBoundingBox.vert: -------------------------------------------------------------------------------- 1 | #version 330 2 | 3 | layout(location = 0) in vec3 position; 4 | 5 | uniform mat4 modelMat; 6 | uniform mat4 projMat; 7 | uniform mat4 viewMat; 8 | 9 | 10 | void main() { 11 | 12 | gl_Position = projMat*viewMat * modelMat*vec4(position, 1.0); 13 | 14 | // gl_Position = vec4(position, 1.0); 15 | 16 | } 17 | -------------------------------------------------------------------------------- /data/shaders/lambertian.frag: -------------------------------------------------------------------------------- 1 | #version 330 2 | 3 | out vec4 bufferColor; 4 | 5 | 6 | uniform float m_specularDegree; 7 | uniform vec4 ambientColor; 8 | uniform vec4 specularColor; 9 | uniform vec4 diffuseColor; 10 | 11 | uniform int boolUseDiffuse; 12 | 13 | in vec4 lightVec; 14 | in vec4 normal; 15 | in vec4 normalView; 16 | in vec4 eyeView; 17 | in vec4 vertex; 18 | in vec2 uv; 19 | in vec3 color; 20 | 21 | 22 | vec4 phong(vec3 l, vec3 n, vec3 e, vec4 colorDif) { 23 | vec4 renderedColor; 24 | vec3 r = normalize(-reflect(l,n)); 25 | float d = clamp(max(dot(l,n),0.),0.0,1.0); 26 | 27 | renderedColor = ambientColor; 28 | 29 | // if the light comes from the back 30 | if(dot(l,n) > 0.0){ 31 | float s = pow(max(dot(r,e),0.),m_specularDegree); 32 | renderedColor += specularColor*s + colorDif*d; 33 | //renderedColor = vec4(1.0, 0, 0, 1); 34 | } 35 | else{ 36 | //renderedColor= vec4(0, 0, 1.0, 1); 37 | } 38 | 39 | return renderedColor; 40 | } 41 | 42 | 43 | void main(){ 44 | 45 | vec4 usedColor; 46 | if(boolUseDiffuse == 1){ 47 | usedColor = diffuseColor; 48 | } else { 49 | usedColor = vec4(color,1); 50 | } 51 | 52 | 53 | vec3 light = normalize(lightVec.xyz - vertex.xyz); 54 | if(light != vec3(0,0,0)){ 55 | // normal, view and light directions (in camera space) 56 | vec3 n = normalize(normalView.xyz); 57 | vec3 e = normalize(-eyeView.xyz); 58 | vec3 l = light; 59 | 60 | 61 | bufferColor = phong(l, n, e, usedColor); 62 | //bufferColor = vec4(l.xyz, 1); 63 | 64 | } else { 65 | bufferColor = vec4(color,1); 66 | } 67 | 68 | } 69 | 70 | -------------------------------------------------------------------------------- /data/shaders/lambertian.vert: -------------------------------------------------------------------------------- 1 | #version 330 2 | 3 | // input attributes 4 | layout(location = 0) in vec3 position; 5 | layout(location = 1) in vec3 vertNormal; 6 | layout(location = 2) in vec2 textureCoordinate; 7 | layout(location = 3) in vec3 vertColor; 8 | 9 | 10 | uniform mat4 normalMatrix; 11 | 12 | 13 | uniform mat4 modelMat; 14 | uniform mat4 projMat; 15 | uniform mat4 viewMat; 16 | 17 | uniform vec4 light; 18 | 19 | out vec4 normal; 20 | out vec4 normalView; 21 | out vec4 eyeView; 22 | out vec4 vertex; 23 | out vec2 uv; 24 | out vec3 color; 25 | 26 | out vec4 lightVec; 27 | 28 | void main() { 29 | vertex = vec4(position, 1.0); 30 | 31 | mat4 mv = viewMat * modelMat; 32 | 33 | gl_Position = projMat*mv*vec4(position, 1.0); 34 | 35 | normal = vec4(vertNormal,1.0); 36 | normalView = normalize(normalMatrix*normal); 37 | eyeView = (mv*vec4(position,1.0)); 38 | 39 | lightVec = viewMat * vec4(light.xyz, 0.0); 40 | 41 | uv = textureCoordinate; 42 | color = vertColor; 43 | } 44 | -------------------------------------------------------------------------------- /data/shaders/postProcess.frag: -------------------------------------------------------------------------------- 1 | #version 330 2 | 3 | uniform sampler2D sceneRendered; 4 | 5 | in vec2 texcoord; 6 | 7 | out vec4 bufferColor; 8 | 9 | void main(){ 10 | 11 | bufferColor = texture(sceneRendered, texcoord); 12 | 13 | // bufferColor = vec4(texcoord.x,texcoord.y,0.0,1.0); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /data/shaders/postProcess.vert: -------------------------------------------------------------------------------- 1 | #version 330 2 | 3 | // input attributes 4 | layout(location = 0) in vec3 position;// position of the vertex in world space 5 | 6 | out vec2 texcoord; 7 | 8 | void main() { 9 | texcoord = position.xy*0.5+0.5; 10 | gl_Position = vec4(position,1.0); 11 | } 12 | -------------------------------------------------------------------------------- /data/shaders/simple.frag: -------------------------------------------------------------------------------- 1 | #version 330 2 | 3 | out vec4 bufferColor; 4 | 5 | 6 | uniform vec4 color; 7 | 8 | 9 | void main(){ 10 | 11 | bufferColor = color; 12 | // bufferColor = vec4(1,0,0,1); 13 | } 14 | -------------------------------------------------------------------------------- /data/shaders/simple.vert: -------------------------------------------------------------------------------- 1 | #version 330 2 | 3 | // input attributes 4 | layout(location = 0) in vec3 position; 5 | 6 | 7 | uniform mat4 modelMat; 8 | uniform mat4 projMat; 9 | uniform mat4 viewMat; 10 | 11 | 12 | void main() { 13 | gl_Position = projMat*viewMat*modelMat*vec4(position, 1.0); 14 | } 15 | -------------------------------------------------------------------------------- /data/shaders/texture.frag: -------------------------------------------------------------------------------- 1 | #version 330 2 | 3 | out vec4 bufferColor; 4 | 5 | uniform sampler2D tex; 6 | 7 | in vec2 uv; 8 | 9 | 10 | 11 | void main(){ 12 | 13 | bufferColor = vec4(uv.xy,0,1); 14 | bufferColor = texture(tex, uv); 15 | } 16 | -------------------------------------------------------------------------------- /data/shaders/texture.vert: -------------------------------------------------------------------------------- 1 | #version 330 2 | 3 | // input attributes 4 | layout(location = 0) in vec3 position; 5 | layout(location = 1) in vec3 vertNormal; 6 | layout(location = 2) in vec2 texCoord; 7 | 8 | 9 | uniform mat4 modelMat; 10 | uniform mat4 projMat; 11 | uniform mat4 viewMat; 12 | 13 | out vec2 uv; 14 | 15 | void main() { 16 | uv = texCoord; 17 | gl_Position = projMat*viewMat*modelMat*vec4(position, 1.0); 18 | } 19 | -------------------------------------------------------------------------------- /data/textures/pattern.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/data/textures/pattern.jpg -------------------------------------------------------------------------------- /data/textures/test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/data/textures/test.png -------------------------------------------------------------------------------- /data/textures/water_texture.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/data/textures/water_texture.jpg -------------------------------------------------------------------------------- /documentation.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/documentation.pdf -------------------------------------------------------------------------------- /imgui.ini: -------------------------------------------------------------------------------- 1 | [Window][Debug##Default] 2 | Pos=60,60 3 | Size=400,400 4 | Collapsed=0 5 | 6 | [Window][Debug] 7 | Pos=60,54 8 | Size=345,54 9 | Collapsed=0 10 | 11 | [Window][Scene Manager] 12 | Pos=192,193 13 | Size=415,264 14 | Collapsed=0 15 | 16 | [Window][Renderer Setting] 17 | Pos=60,60 18 | Size=32,39 19 | Collapsed=0 20 | 21 | [Window][Game] 22 | Pos=776,140 23 | Size=442,275 24 | Collapsed=0 25 | 26 | -------------------------------------------------------------------------------- /ressources/TP_graphe_scene.md: -------------------------------------------------------------------------------- 1 | # Moteur de jeu 2 | #### TP : Graphe de scene 3 | 4 | par Maxime Isnel 5 | 6 | lien du Git de [Green Engine](https://github.com/TheSpyGeek/Green-Engine) : https://github.com/TheSpyGeek/Green-Engine 7 | 8 | ## Compiler le code 9 | 10 | ##### Sur Linux 11 | 12 | Dependencies : 13 | 14 | ```sudo apt-get install -y build-essential cmake xorg-dev libgl1-mesa-dev libfreetype6-dev``` 15 | 16 | Pour compiler : 17 | 18 | ```cd build && cmake .. && make``` 19 | 20 | ##### Sur Windows 21 | 22 | Dependencies : 23 | 24 | * mingw64 ou mingw32 25 | * cmake 26 | 27 | Pour compiler : 28 | 29 | * Lancer ```Cmake``` 30 | * Configurer avec les ```Mingw Makefile``` pour compiler dans le dossier ```build``` 31 | * Lancer ```mingw64``` 32 | * Aller dans le dossier ```build``` 33 | * Compiler avec ```mingw32-make``` 34 | 35 | Pour lancer le programme : 36 | 37 | ```./green-engine``` 38 | 39 | ## Structure du code 40 | 41 | Les grandes classes du programme sont : 42 | * **MainRenderer** : il fait le rendu d'une scène dans une texture et puis l'affiche dans une texture 43 | * **InputManager** : gère les entrées clavier et les associent avec des fonctions du moteur 44 | * **UI** : gère tout l'affichage des widgets sur l'écran (hors rendu). Le méthode d'affichage de chaque composant d'un objet sont défini dans les objet eux mêmes 45 | * **Scene** : gère tous les objets du moteur (ajout, suppression, mise à jour). Elle possède une liste d'**ObjectEngine** 46 | * **ObjectEngine** : Est un objet géré par la scène. Il possède un **Transform** ce qui permet de le déplacer. Il possède une liste d'**ObjectEngine** qui sont ses fils et dont les positions et rotations vont dépendre de la matrice model du parent. 47 | * **MeshObject** : Il possède un maillage donc ils sont affichable. Il possède un **Material** qui va faire le shading et la couleur de l'affichage de cette objet. 48 | 49 | ### Graphe de scène 50 | 51 | Pour faire mon graphe de scène, j'ai d'abord créé une classe **Transform** qui me permet de controller la position, la rotation, le scale ce qui me donne la matrice model pour pouvoir afficher cette objet. Je peux aussi dissocié la matrice model qui me permet d'afficher l'objet et celle que je vais utiliser avec les objets enfants de cet objet. 52 | 53 | Pour dissocier ces deux matrices il faut aller sur l'interface => cliquer sur un objet dans le scène manager => "Model matrix to child" => Uncheck "Same matrix as parent". Vous pouvez donc controller la position, la rotation indépendement. 54 | 55 | Vous pouvez aussi animer la rotation de chaque objet dans la partie **Animation** (il y en une pour l'affichage de l'objet et une pour la matrice envoyée aux enfants). Vous pouvez cocher l'axe ou les axes que vous voulez faire tourner et à quelle vitesse. Vous pouvez "reset" l'animation en appuyant sur le bouton reset 56 | 57 | Pour vous assurer que la Terre tourne sur son axe et en étant incliné par rapport au soleil, vous pouvez activé les **WireFrame** (```View => Toggle wire frame```). 58 | 59 | **Transform classe** 60 | 61 | dans le fichier ```src/models/Transform.cpp``` 62 | 63 | Dans la classe Transform je stocke les vecteurs de position, rotation et scale, pour afficher l'objet mais aussi pour la matrice envoyée aux enfants. Il y a aussi`toute les variables nécéssaires à l'animation. 64 | 65 | ## Fonctionnalités 66 | 67 | Vous pouvez : 68 | 69 | * Vous pouvez redimensionner la fenêtre de l'application et la fenêtre du **scene manager** 70 | * Ouvrir un arbe dans le **scene manager** si l'objet à des fils en clique sur la flèche 71 | * Ajouter des objets avec maillage en faisant ```Edit => Add MeshObject```. Vous pouvez ensuite changer le maillage chargé en changeant le chemin du fichier .OFF et en appuyant sur le bouton "Recreate" 72 | * Afficher l'objet avec des ```WireFrame``` en faisant ```View => Toggle wire frame``` 73 | * Faire tourner les objets, les déplacer, ... 74 | * Avec ```CTRL + H``` vous pouvez cacher/montrer l'affichage des fenêtre. 75 | * Avec ```CTRL + P``` pause et play l'animation 76 | -------------------------------------------------------------------------------- /ressources/TP_simplify.md: -------------------------------------------------------------------------------- 1 | # Informatique graphique 2 | #### TP : Simplification de maillage 3 | 4 | par Maxime Isnel 5 | 6 | ## Compiler le code 7 | 8 | ##### Sur Linux 9 | 10 | Dependencies : 11 | 12 | ```sudo apt-get install -y build-essential cmake xorg-dev libgl1-mesa-dev libfreetype6-dev``` 13 | 14 | Pour compiler : 15 | 16 | ```cd build && cmake .. && make``` 17 | 18 | ##### Sur Windows 19 | 20 | Dependencies : 21 | 22 | * mingw64 ou mingw32 23 | * cmake 24 | 25 | Pour compiler : 26 | 27 | * Lancer ```Cmake``` 28 | * Configurer avec les ```Mingw Makefile``` pour compiler dans le dossier ```build``` 29 | * Lancer ```mingw64``` 30 | * Aller dans le dossier ```build``` 31 | * Compiler avec ```mingw32-make``` 32 | 33 | Pour lancer le programme : 34 | 35 | ```./green-engine``` 36 | 37 | ## Fonctionnalités 38 | 39 | Dans le programme, il y a une fenêtre qui gère la scène, qui contient (la lumière, la caméra, les objets de la scène). La fenêtre peut être redimensionnée. Quand vous cliquez sur un objet dans la liste d'objet vous voyez à droite toutes les informations concernant cet objet (position, mesh, orientation, ...). 40 | 41 | Vous pouvez : 42 | 43 | * Ajouter des objets avec maillage en faisant ```Edit => Add MeshObject```. Vous pouvez ensuite changer le maillage chargé en changeant le chemin du fichier .OFF et en appuyant sur le bouton "Recreate" 44 | * Faire tourner les objets, les déplacers, ... 45 | * Afficher l'objet avec des ```WireFrame``` en faisant ```View => Toggle wire frame``` 46 | * Simplifier le maillage en changeant la **résolution** après "vertices simplification" et en appuyant sur le bouton simplify. Cette résolution correspond à la grille qui permet de simplifier le maillage. 47 | * Avec ```CTRL + H``` vous pouvez cacher/montrer l'affichage des fenêtre. 48 | 49 | ## Structure du code 50 | 51 | La scène est composé d'un arbre de ```ObjectEngine```, chaque ```ObjectEngine``` a un Transform qui permet de le déplacer. Les objets affichables contiennent un maillage et un matériau. Le materiau permet d'afficher l'objet et de changer le shading. Le maillage contient les informations données à OpenGL pour afficher l'objet. Le fichier ```Mesh.cpp``` dans le dossier "models" contient toutes les fonctions liées au maillage comme l'algorithme pour la **simplification**. 52 | -------------------------------------------------------------------------------- /ressources/composants.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/composants.png -------------------------------------------------------------------------------- /ressources/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/demo.gif -------------------------------------------------------------------------------- /ressources/documentation.md: -------------------------------------------------------------------------------- 1 | # Compilation et Documentation 2 | 3 | Source du projet : https://github.com/TheSpyGeek/VoxelEngine 4 | 5 | **Attention** pour cloner utiliser l'option "recursive" de git : ```git clone --recursive https://github.com/TheSpyGeek/VoxelEngine.git``` 6 | 7 | ## Compilation 8 | 9 | Le projet utilise ```cmake``` pour le développement nous utilisons le flags type de compilation en mode ```Debug``` mais pour une utilisation est pour voir les performances il vaut mieux utiliser le mode ```Release```. Pour ce faire , lors de la préparation avec ```Cmake``` au lieu de juste faire ```cmake ..``` vous devez faire ```cmake -DCMAKE_BUILD_TYPE=Release ..```. 10 | 11 | Le projet peut être compilé sur Linux, Windows et normalement MacOSX. 12 | 13 | ##### Sur Linux 14 | 15 | Dépendances : 16 | 17 | ```sudo apt-get install -y build-essential cmake xorg-dev libgl1-mesa-dev libfreetype6-dev``` 18 | 19 | Pour compiler : 20 | 21 | ```mkdir build && cd build && cmake .. && make``` 22 | 23 | ##### Sur Windows 24 | 25 | Vous aurez besoin de [Cmake](https://cmake.org/download/) (lien téléchargement: https://cmake.org/download/) 26 | 27 | ###### Avec MinGW 28 | 29 | Vous devez avoir [Mingw](https://sourceforge.net/projects/mingw-w64/) (lien téléchargement : https://sourceforge.net/projects/mingw-w64/) 30 | 31 | Pour compiler vous devez faire: 32 | 33 | * Créer un dossier ```build``` dans le dossier du projet 34 | * Lancer ```Cmake``` 35 | * Configurer avec ```Mingw Makefile``` 36 | * Lancer le terminal ```mingw64``` 37 | * Aller dans le dossier ```build``` 38 | * Compiler avec la commande ```mingw32-make``` 39 | 40 | ###### Avec Microsoft Visual Studio 2017 41 | 42 | Pour compiler vous devez faire: 43 | 44 | * Créer un dossier ```build``` dans le dossier du projet 45 | * Lancer ```Cmake``` 46 | * Configurer avec ```Visual Studio 15 2017``` 47 | * Ouvrir le fichier ```ALL_BUILD.vcxproj``` 48 | * Dans Microsoft Visual Studio 2017 faire clic droit sur "ALL_BUILD" puis "Générer" 49 | * Cela va compiler le projet 50 | * Vous allez déplacer l'executable dans le dossier ```build``` que vous avez créer 51 | 52 | Vous pouvez lancer l'executable 53 | 54 | ## Documentation 55 | 56 | La game loop est présente dans le fichier ```main.cpp```. Elle appelle plusieurs classes qui votn s'occuper de la mise à jour des objets et du rendu. 57 | 58 | Classes importantes (la plupart présent dans le dossier ```engineClass```) : 59 | 60 | * **Scene** : gère tous les objets dans la scène. C'est cette classe qui va appeler le méthode de mise à jour des objets et des méthodes de dessins des objets. 61 | * **MainRenderer** : C'est lui qui s'occupe de la configuration d'```OpenGL```, qui met les bonnes options et qui décide quoi afficher. Selon si le moteur est en mode "Jeu" ou non il va afficher des choses différentes. C'est le mode "Editeur" et le mode "Jeu". On peut basculé de l'un à l'autre avec ```CTRL + U```. 62 | * **UI** : gère tout l'affichage des widgets sur l'écran (hors rendu). Le méthode d'affichage de chaque composant d'un objet sont défini dans les objet eux mêmes. Elle affiche l'arborescence de la scène à droite de l'écran, les menus déroulant, etc. 63 | * **InputManager** : cette classe gère les entrées clavier au niveau du moteur. Exemple: mettre en pause le jeu, passer en mode wireframe, etc. Les contrôles du joueur sont gérés à un autre endroit. 64 | * **Transform** : cette classe gère tout ce qui est position, rotation, scale d'un objet. Chaque objet en a un. 65 | * **Gameobject** : Cette objet du moteur qui est géré par la scène. Il possède une liste de ```Component``` qui vont venir changer le comportement de ce Gameobject. Il possède un nom et un ID. 66 | * **Component** : Ceux sont des classes qui vont modifier le comportement d'un ou plusieurs Gameobject. Ils ont plusieurs fonctions de mise àjour qui sont appelées à des moments différents (```update()```, ```inputUpdate()```, ```physicsUpdate()```). C'est inspiré de ce qui est fait dans **Unity** 67 | 68 | ##### Composants 69 | 70 | On va faire un vite tour des **Component** et de ce qu'ils font : (dans le dossier ```components``` et ```terrain```) 71 | 72 | * Les **Renderer** : (```AxisRenderer```, ```CameraRenderer```, ```MeshRenderer```) ils font tous les trois un rendu ```OpenGL```, le plus important des trois est le ```MeshRenderer``` qui fait le rendu d'un maillage avec les informations de normales, position, etc. 73 | * **Collider** : il défini un box collider de type AABB (Axis-aligned bounding boxes) il fait la detection de collision **mais pour l'instant qu'avec le terrain** 74 | * **Rigidbody** : il permet de faire les déplacements de l'objet dependant de la vitesse du ```Rigidbody```. 75 | * **CameraFollow** : defini le comportement d'une camera qui suit un objet à une certaine distance. 76 | * **GroundFollow** : permet à l'objet de rester toujours à la surface du terrain 77 | * **CameraControllerFirstPerson** : defini le comportement d'une caméra e vue à la première personne. Elle est utilisé pour la caméra de l'éditeur. 78 | * **CameraProjective** : permet d'avoir les informations de projection, c'est ce composant qui donne la matrice 4x4 Projection; 79 | * **ThirdPersonController** : permet de controller la caméra du mode "Jeu" avec la souris. La caméra va tourner autour du joueur. 80 | * **FireProjectiles** : permet de tirer des projectiles 81 | * **Projectile** : Défini le comportement d'un projectile. Dans notre cas, c'est un projectile qui va faire une explosion à l'impact 82 | * **TerrainModifier** : c'est lui va modifier le terrain quand il y a des explosions 83 | * **TerrainManager** : C'est lui qui est responsable de la génération et de l'affichage du terrain. C'est lui qui gère quels ```chunk``` doit être afficher et lequels modifier 84 | * **TerraiChunk** : C'est lui qui contient les informations utiles à un ```chunk```. Chaque ```chunk``` en ont un. 85 | -------------------------------------------------------------------------------- /ressources/documentation.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/documentation.pdf -------------------------------------------------------------------------------- /ressources/gameloop.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/gameloop.png -------------------------------------------------------------------------------- /ressources/minecraft.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/minecraft.jpg -------------------------------------------------------------------------------- /ressources/planPresentation.md: -------------------------------------------------------------------------------- 1 | * enjeu du projet 2 | * but du projet 3 | * presentation du moteur 4 | * cmake,imgui, glfw, glad, glm 5 | * travis 6 | * structure du moteur 7 | * classes principales 8 | * mode editeur / mode jeu 9 | * demonstration 10 | * composants 11 | * demonstration 12 | * game loop 13 | * inputUpdate 14 | * physics Update 15 | * update 16 | * rendu 17 | * affichage 18 | * voxel engine 19 | * génération procédurale 20 | * problématique 21 | * optimisations 22 | * creation d'un maillage 23 | * chargement des chunks 24 | * gameplay 25 | * camera 26 | * mouvement 27 | * explosions 28 | * améliorations 29 | * génération procédurale plus riche 30 | * implémenter un frustum culling 31 | * collision entre objet 32 | * meilleure gestion de la camera -------------------------------------------------------------------------------- /ressources/screen2.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/screen2.PNG -------------------------------------------------------------------------------- /ressources/screen3.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/screen3.PNG -------------------------------------------------------------------------------- /ressources/screenGreenEngine.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/screenGreenEngine.PNG -------------------------------------------------------------------------------- /ressources/screen_editor.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/screen_editor.PNG -------------------------------------------------------------------------------- /ressources/screen_game.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/screen_game.PNG -------------------------------------------------------------------------------- /ressources/structure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/structure.png -------------------------------------------------------------------------------- /ressources/terrain_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/terrain_1.png -------------------------------------------------------------------------------- /ressources/terrain_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/terrain_2.png -------------------------------------------------------------------------------- /ressources/terrain_2_wire.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/terrain_2_wire.png -------------------------------------------------------------------------------- /ressources/terrain_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/terrain_3.png -------------------------------------------------------------------------------- /ressources/terrain_3_wire.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/terrain_3_wire.png -------------------------------------------------------------------------------- /ressources/terrain_deep.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/terrain_deep.png -------------------------------------------------------------------------------- /ressources/terrain_large.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/terrain_large.png -------------------------------------------------------------------------------- /ressources/travis.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/travis.PNG -------------------------------------------------------------------------------- /ressources/voxel-engine.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lensimax/VoxelEngine/ef86291c4de5b040bad653adc08c81ba00c9288f/ressources/voxel-engine.png -------------------------------------------------------------------------------- /src/components/axisRenderer.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | #include 7 | #include 8 | 9 | #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) 10 | #include // Initialize with gl3wInit() 11 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) 12 | #include // Initialize with glewInit() 13 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) 14 | #include // Initialize with gladLoadGL() 15 | #else 16 | #include IMGUI_IMPL_OPENGL_LOADER_CUSTOM 17 | #endif 18 | 19 | #include "axisRenderer.h" 20 | 21 | #include "../models/mesh/meshCube.h" 22 | #include "../material/shader.h" 23 | 24 | #include 25 | 26 | AxisRenderer::AxisRenderer() : m_lineLength(0.2f), m_lineWidth(2.0f){ 27 | setName("Axis Renderer"); 28 | } 29 | 30 | void AxisRenderer::draw(glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projectionMat, Light *light){ 31 | 32 | glm::vec3 origin = glm::vec3(0, 0, 0); 33 | glm::vec3 forward = glm::vec3(0, 0, 1); 34 | glm::vec3 up = glm::vec3(0, 1, 0); 35 | glm::vec3 right = glm::vec3(1, 0, 0); 36 | 37 | 38 | std::vector arrayAxis; 39 | 40 | glLineWidth(m_lineWidth); 41 | 42 | Shader shader = Shader(); 43 | shader.load("../data/shaders/simple.vert","../data/shaders/simple.frag"); 44 | glUseProgram(shader.id()); 45 | glUniformMatrix4fv(glGetUniformLocation(shader.id(),"modelMat"),1,GL_FALSE,&(modelMat[0][0])); 46 | glUniformMatrix4fv(glGetUniformLocation(shader.id(),"viewMat"),1,GL_FALSE,&(viewMat[0][0])); 47 | glUniformMatrix4fv(glGetUniformLocation(shader.id(),"projMat"),1,GL_FALSE,&(projectionMat[0][0])); 48 | 49 | // Z axis 50 | glm::vec4 color = glm::vec4(0,0,1,1); 51 | glUniform4fv(glGetUniformLocation(shader.id(),"color"), 1, &color[0]); 52 | arrayAxis.resize(2); 53 | arrayAxis[0] = origin; arrayAxis[1] = forward*m_lineLength; 54 | DrawDebug::drawArrayPosition(arrayAxis.size(), (float*)&arrayAxis[0], GL_LINES); 55 | 56 | // Y axis 57 | color = glm::vec4(0,1,0,1); 58 | glUniform4fv(glGetUniformLocation(shader.id(),"color"), 1, &color[0]); 59 | arrayAxis.resize(2); 60 | arrayAxis[0] = origin; arrayAxis[1] = up*m_lineLength; 61 | DrawDebug::drawArrayPosition(arrayAxis.size(), (float*)&arrayAxis[0], GL_LINES); 62 | 63 | // X axis 64 | color = glm::vec4(1,0,0,1); 65 | glUniform4fv(glGetUniformLocation(shader.id(),"color"), 1, &color[0]); 66 | arrayAxis.resize(2); 67 | arrayAxis[0] = origin; arrayAxis[1] = right*m_lineLength; 68 | DrawDebug::drawArrayPosition(arrayAxis.size(), (float*)&arrayAxis[0], GL_LINES); 69 | 70 | glUseProgram(0); 71 | 72 | 73 | } 74 | 75 | void AxisRenderer::createUI(){ 76 | 77 | ImGui::Text("Line length : "); 78 | ImGui::DragFloat("##lineLength", &m_lineLength, 0.01f,0.01f, 1000.f); 79 | ImGui::Text("Line width : "); 80 | ImGui::DragFloat("##linewidth", &m_lineWidth,0.2f, 1.0f, 1000.0f); 81 | 82 | } -------------------------------------------------------------------------------- /src/components/axisRenderer.h: -------------------------------------------------------------------------------- 1 | #ifndef AXIS_RENDERER_H 2 | #define AXIS_RENDERER_H 3 | 4 | #include "renderer.h" 5 | 6 | 7 | class AxisRenderer : public Renderer { 8 | 9 | public: 10 | 11 | AxisRenderer(); 12 | 13 | void draw(glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projectionMat, Light *light) override; 14 | 15 | void createUI() override; 16 | 17 | private: 18 | 19 | float m_lineLength; 20 | float m_lineWidth; 21 | }; 22 | 23 | #endif -------------------------------------------------------------------------------- /src/components/cameraControllerFirstPerson.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "cameraControllerFirstPerson.h" 3 | #include "../engineClass/gameObject.h" 4 | 5 | 6 | 7 | CameraControllerFirstPerson::CameraControllerFirstPerson() : m_sensitivityRotateWorld(glm::vec2(0.5f)), m_scrollZoomSensitivity(1.f), m_stafeSensitivity(0.1f) { 8 | 9 | setName("Camera Controller"); 10 | 11 | } 12 | 13 | 14 | CameraControllerFirstPerson::~CameraControllerFirstPerson(){ 15 | 16 | } 17 | 18 | void CameraControllerFirstPerson::update(){ 19 | if(!m_active){ 20 | return; 21 | } 22 | 23 | ImGuiIO& io = ImGui::GetIO(); 24 | 25 | // CAMERA EDITOR CONTROL 26 | if(!io.WantCaptureMouse){ 27 | 28 | glm::vec3 position = m_gameobject->getTransform()->getPosition(); 29 | glm::vec3 rotation = m_gameobject->getTransform()->getRotation(); 30 | 31 | const mat4 inverted = glm::inverse(m_gameobject->getTransform()->getModelMat()); 32 | 33 | glm::vec3 move = glm::vec3(0,0,0); 34 | // mouse wheel 35 | if(io.MouseWheel != 0.0){ 36 | const vec3 forward = normalize(glm::vec3(inverted[2])); 37 | move -= io.MouseWheel*forward*m_scrollZoomSensitivity; 38 | 39 | } 40 | 41 | // right click 42 | if(ImGui::IsMouseDown(1)){ 43 | 44 | const vec3 left = normalize(glm::vec3(inverted[0])); 45 | const vec3 top = normalize(glm::vec3(inverted[1])); 46 | 47 | glm::vec2 vectorTranslate = glm::vec2(io.MouseDelta.x, io.MouseDelta.y); 48 | vectorTranslate.y *= -1.0f; 49 | move -= vectorTranslate.x * left * m_stafeSensitivity.x; 50 | move -= vectorTranslate.y * top * m_stafeSensitivity.y; 51 | } 52 | 53 | // Left click 54 | if(ImGui::IsMouseDown(0)){ 55 | 56 | // ROTATION OF the world 57 | glm::vec2 vectorMouse = glm::vec2(io.MouseDelta.x, io.MouseDelta.y); 58 | vectorMouse *= -1.0f; 59 | vectorMouse *= m_sensitivityRotateWorld*0.01f; 60 | 61 | 62 | rotation.x -= vectorMouse.y; 63 | rotation.y -= vectorMouse.x; 64 | 65 | } 66 | 67 | m_gameobject->getTransform()->setPosition(position + move); 68 | m_gameobject->getTransform()->setRotation(rotation); 69 | } 70 | 71 | } 72 | 73 | 74 | void CameraControllerFirstPerson::createUI(){ 75 | ImGui::Text("Rotation world sensitivity : (x0.01)"); 76 | ImGui::DragFloat2("##rotationsensitivity", &m_sensitivityRotateWorld[0], 0.01, 0.0, 100.); 77 | ImGui::Text("Scroll zoom sensitivity : "); 78 | ImGui::DragFloat("##m_scrollZoomSensitivity", &m_scrollZoomSensitivity, 0.01, 0.0, 100.); 79 | ImGui::Text("Strafe sensitivity : "); 80 | ImGui::DragFloat2("##strafesensitivity", &m_stafeSensitivity[0], 0.01, 0.0, 100.); 81 | 82 | /*const mat4 inverted = glm::inverse(m_gameobject->getTransform()->getModelMat()); 83 | const vec3 forward = -1.0f*normalize(glm::vec3(inverted[2])); 84 | const vec3 left = normalize(glm::vec3(inverted[0])); 85 | const vec3 top = normalize(glm::vec3(inverted[1])); 86 | 87 | ImGui::Separator(); 88 | ImGui::Text("Forward (%f, %f, %f)", forward.x, forward.y, forward.z); 89 | ImGui::Text("Left (%f, %f, %f)", left.x, left.y, left.z); 90 | ImGui::Text("Top (%f, %f, %f)", top.x, top.y, top.z);*/ 91 | 92 | 93 | } -------------------------------------------------------------------------------- /src/components/cameraControllerFirstPerson.h: -------------------------------------------------------------------------------- 1 | #ifndef CAMERACONTROLLERFIRSTPERSON_H 2 | #define CAMERACONTROLLERFIRSTPERSON_H 3 | 4 | #include "component.h" 5 | 6 | #ifndef GLM_H 7 | #define GLM_H 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #endif 14 | 15 | 16 | class CameraControllerFirstPerson : public Component { 17 | public: 18 | CameraControllerFirstPerson(); 19 | ~CameraControllerFirstPerson(); 20 | 21 | void update() override; 22 | 23 | void createUI() override; 24 | 25 | private: 26 | 27 | 28 | glm::vec2 m_sensitivityRotateWorld; 29 | float m_scrollZoomSensitivity; 30 | glm::vec2 m_stafeSensitivity; 31 | 32 | 33 | }; 34 | 35 | 36 | #endif -------------------------------------------------------------------------------- /src/components/cameraFollow.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #ifndef GLM_H 4 | #define GLM_H 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #endif 11 | 12 | #include "cameraFollow.h" 13 | 14 | 15 | #include "cameraProjective.h" 16 | 17 | 18 | CameraFollow::CameraFollow(float distance, float offsetAngle) : m_distanceFromPlayer(distance), m_angleOffset(offsetAngle){ 19 | setName("Camera Follow"); 20 | m_player = NULL; 21 | } 22 | 23 | 24 | CameraFollow::~CameraFollow(){ 25 | 26 | } 27 | 28 | void CameraFollow::update(){ 29 | if(m_player == NULL){ 30 | return; 31 | } 32 | 33 | updateCameraPositionFromPlayer(); 34 | 35 | 36 | } 37 | 38 | void CameraFollow::createUI(){ 39 | ImGui::Text("Distance from the player : "); 40 | ImGui::DragFloat("##distance", &m_distanceFromPlayer, 0.01f,0.01f, 1000.f); 41 | ImGui::Text("Offset angle : "); 42 | ImGui::DragFloat("##offsetangle", &m_angleOffset, 0.01f,-50.f, 50.f); 43 | } 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | float CameraFollow::getHorizontalDistance(){ 53 | return m_distanceFromPlayer * cos(m_gameobject->getTransform()->getRotation().x); 54 | } 55 | 56 | float CameraFollow::getVerticalDistance(){ 57 | return m_distanceFromPlayer * sin(m_gameobject->getTransform()->getRotation().x); 58 | } 59 | 60 | void CameraFollow::updateCameraPositionFromPlayer(){ 61 | if(m_player == NULL){ 62 | return; 63 | } 64 | 65 | float vertical = getVerticalDistance(); 66 | float horizontal = getHorizontalDistance(); 67 | float theta = m_player->getTransform()->getRotation().y + m_angleOffset; 68 | 69 | float offsetX = horizontal * sin(theta); 70 | float offsetZ = horizontal * cos(theta); 71 | 72 | glm::vec3 position = m_player->getTransform()->getPosition(); 73 | position.x -= offsetX; 74 | position.y += vertical; 75 | position.z -= offsetZ; 76 | 77 | m_gameobject->getTransform()->setPosition(position); 78 | glm::vec3 rotation = m_gameobject->getTransform()->getRotation(); 79 | rotation.y = 3.14159f - theta; 80 | m_gameobject->getTransform()->setRotation(rotation); 81 | } -------------------------------------------------------------------------------- /src/components/cameraFollow.h: -------------------------------------------------------------------------------- 1 | #ifndef CAMERAFOLLOW_H 2 | #define CAMERAFOLLOW_H 3 | 4 | 5 | #include "../engineClass/gameObject.h" 6 | #include "component.h" 7 | class CameraFollow : public Component { 8 | public: 9 | 10 | CameraFollow(float distance = 6.3f, float offsetAngle = 0.0f); 11 | ~CameraFollow(); 12 | 13 | void update() override; 14 | void createUI() override; 15 | 16 | void setPlayer(GameObject *player){m_player = player;} 17 | GameObject *getPlayer(){return m_player;} 18 | 19 | private: 20 | 21 | float getHorizontalDistance(); 22 | float getVerticalDistance(); 23 | void updateCameraPositionFromPlayer(); 24 | 25 | float m_distanceFromPlayer; 26 | float m_angleOffset; 27 | 28 | GameObject *m_player; 29 | 30 | 31 | 32 | }; 33 | 34 | #endif -------------------------------------------------------------------------------- /src/components/cameraProjective.cpp: -------------------------------------------------------------------------------- 1 | #include "cameraProjective.h" 2 | #include 3 | 4 | #include "../engineClass/gameObject.h" 5 | 6 | CameraProjective::CameraProjective(float fov, float near, float far) : m_fov(fov), m_near(near), m_far(far){ 7 | setName("Camera"); 8 | } 9 | 10 | 11 | glm::mat4 CameraProjective::getView(){ 12 | glm::mat4 viewMat = glm::mat4(1); 13 | 14 | glm::vec3 rotation = m_gameobject->getTransform()->getRotation(); 15 | 16 | viewMat = glm::rotate(viewMat, rotation.x, glm::vec3(1.0,0.0,0.0)); 17 | viewMat = glm::rotate(viewMat, rotation.y, glm::vec3(0.0,1.0,0.0)); 18 | viewMat = glm::translate(viewMat, m_gameobject->getTransform()->getPosition()*(-1.0f)); 19 | // on applique pas de roll 20 | //viewMat = glm::rotate(viewMat, rotation.z, glm::vec3(0.0,0.0,1.0)); 21 | 22 | return viewMat; 23 | } 24 | 25 | glm::mat4 CameraProjective::getProjection(float aspect){ 26 | return glm::perspective(m_fov, aspect, m_near, m_far); 27 | } 28 | 29 | void CameraProjective::createUI(){ 30 | const float min = 0.001f; 31 | const float max = 1000000.0f; 32 | 33 | ImGui::Text("Fov: "); ImGui::SameLine(); 34 | ImGui::DragFloat("##fov", &m_fov, 0.01f, min, max); 35 | ImGui::Text("Near: "); ImGui::SameLine(); 36 | ImGui::DragFloat("##near", &m_near, 0.01f, min, max); //ImGui::SameLine(); 37 | ImGui::Text("Far: "); ImGui::SameLine(); 38 | ImGui::DragFloat("##far", &m_far, 0.01f, min, max); 39 | } -------------------------------------------------------------------------------- /src/components/cameraProjective.h: -------------------------------------------------------------------------------- 1 | #ifndef CAMERAPROJECTIVE_H 2 | #define CAMERAPROJECTIVE_H 3 | 4 | #ifndef GLM_H 5 | #define GLM_H 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #endif 12 | 13 | #include "component.h" 14 | 15 | 16 | 17 | class CameraProjective : public Component { 18 | 19 | public: 20 | CameraProjective(float fov = 45.f, float near = 0.1f, float far = 1000.f); 21 | 22 | 23 | glm::mat4 getView(); 24 | 25 | glm::mat4 getProjection(float aspect = 16./9.); 26 | 27 | void createUI() override final; 28 | 29 | protected: 30 | 31 | float m_fov; 32 | float m_near; 33 | float m_far; 34 | 35 | 36 | }; 37 | 38 | #endif -------------------------------------------------------------------------------- /src/components/cameraRenderer.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #include 8 | #include 9 | 10 | #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) 11 | #include // Initialize with gl3wInit() 12 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) 13 | #include // Initialize with glewInit() 14 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) 15 | #include // Initialize with gladLoadGL() 16 | #else 17 | #include IMGUI_IMPL_OPENGL_LOADER_CUSTOM 18 | #endif 19 | 20 | #include "cameraRenderer.h" 21 | #include "cameraProjective.h" 22 | #include "../material/shader.h" 23 | 24 | CameraRenderer::CameraRenderer() : m_lineLength(0.2f), m_lineWidth(2.0f){ 25 | setName("Camera Renderer"); 26 | } 27 | 28 | 29 | CameraRenderer::~CameraRenderer(){ 30 | 31 | } 32 | 33 | 34 | 35 | void CameraRenderer::draw(glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projectionMat, Light *light){ 36 | 37 | if(!getActive()){ 38 | return; 39 | } 40 | 41 | CameraProjective * camera = m_gameobject->getComponent(); 42 | if(camera == NULL){ 43 | return; 44 | } 45 | 46 | 47 | // pour enlever la rotation sur la matrix model 48 | modelMat[0][0] = 1; modelMat[1][1] = 1; modelMat[2][2] = 1; 49 | modelMat[0][1] = 0; modelMat[0][2] = 0; 50 | modelMat[1][0] = 0; modelMat[1][2] = 0; 51 | modelMat[2][0] = 0; modelMat[2][1] = 0; 52 | 53 | std::vector arrayAxis; 54 | 55 | 56 | glLineWidth(0.5f); 57 | 58 | Shader shader = Shader(); 59 | shader.load("../data/shaders/simple.vert","../data/shaders/simple.frag"); 60 | glUseProgram(shader.id()); 61 | glUniformMatrix4fv(glGetUniformLocation(shader.id(),"modelMat"),1,GL_FALSE,&(modelMat[0][0])); 62 | glUniformMatrix4fv(glGetUniformLocation(shader.id(),"viewMat"),1,GL_FALSE,&(viewMat[0][0])); 63 | glUniformMatrix4fv(glGetUniformLocation(shader.id(),"projMat"),1,GL_FALSE,&(projectionMat[0][0])); 64 | 65 | // Z axis 66 | glm::vec4 color = glm::vec4(1,0,0,1); 67 | glUniform4fv(glGetUniformLocation(shader.id(),"color"), 1, &color[0]); 68 | 69 | const float size = 0.2f; 70 | 71 | // face dessus 72 | arrayAxis.push_back(glm::vec3(-size, size, size)); 73 | arrayAxis.push_back(glm::vec3(size, size, size)); 74 | arrayAxis.push_back(glm::vec3(size, size, size)); 75 | arrayAxis.push_back(glm::vec3(size, size, -size)); 76 | arrayAxis.push_back(glm::vec3(size, size, -size)); 77 | arrayAxis.push_back(glm::vec3(-size, size, -size)); 78 | arrayAxis.push_back(glm::vec3(-size, size, -size)); 79 | arrayAxis.push_back(glm::vec3(-size, size, size)); 80 | // face dessus 81 | arrayAxis.push_back(glm::vec3(-size, -size, size)); 82 | arrayAxis.push_back(glm::vec3(size, -size, size)); 83 | arrayAxis.push_back(glm::vec3(size, -size, size)); 84 | arrayAxis.push_back(glm::vec3(size, -size, -size)); 85 | arrayAxis.push_back(glm::vec3(size, -size, -size)); 86 | arrayAxis.push_back(glm::vec3(-size, -size, -size)); 87 | arrayAxis.push_back(glm::vec3(-size, -size, -size)); 88 | arrayAxis.push_back(glm::vec3(-size, -size, size)); 89 | 90 | arrayAxis.push_back(glm::vec3(-size, size, -size)); 91 | arrayAxis.push_back(glm::vec3(-size, -size, -size)); 92 | arrayAxis.push_back(glm::vec3(size, size, -size)); 93 | arrayAxis.push_back(glm::vec3(size, -size, -size)); 94 | arrayAxis.push_back(glm::vec3(-size, size, size)); 95 | arrayAxis.push_back(glm::vec3(-size, -size, size)); 96 | arrayAxis.push_back(glm::vec3(size, size, size)); 97 | arrayAxis.push_back(glm::vec3(size, -size, size)); 98 | 99 | 100 | DrawDebug::drawArrayPosition(arrayAxis.size(), (float*)&arrayAxis[0], GL_LINES); 101 | 102 | glUseProgram(0); 103 | } 104 | 105 | 106 | void CameraRenderer::createUI(){ 107 | ImGui::Text("Line length : "); 108 | ImGui::DragFloat("##lineLength", &m_lineLength, 0.01f,0.01f, 1000.f); 109 | ImGui::Text("Line width : "); 110 | ImGui::DragFloat("##linewidth", &m_lineWidth,0.2f, 1.0f, 1000.0f); 111 | } -------------------------------------------------------------------------------- /src/components/cameraRenderer.h: -------------------------------------------------------------------------------- 1 | #ifndef CAMERARENDERER_H 2 | #define CAMERARENDERER_H 3 | 4 | #include "renderer.h" 5 | 6 | class CameraRenderer : public Renderer { 7 | public: 8 | 9 | CameraRenderer(); 10 | ~CameraRenderer(); 11 | 12 | virtual void draw(glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projectionMat, Light *light); 13 | 14 | virtual void createUI() override; 15 | 16 | private: 17 | float m_lineLength; 18 | float m_lineWidth; 19 | 20 | const glm::vec4 m_colorLine = glm::vec4(0.8,0.8,0.8,1); 21 | }; 22 | 23 | 24 | #endif -------------------------------------------------------------------------------- /src/components/colliders/collider.h: -------------------------------------------------------------------------------- 1 | #ifndef COLLIDER_H 2 | #define COLLIDER_H 3 | #include "../rigidbody.h" 4 | 5 | #include "../component.h" 6 | #include "../../terrain/terrainManager.h" 7 | 8 | #include "../../terrain/terrainChunk.h" 9 | 10 | 11 | class Collider : public Renderer { 12 | public: 13 | Collider(glm::vec3 box = glm::vec3(0.6f)); 14 | ~Collider(); 15 | 16 | void start() override; 17 | void physicsUpdate() override; 18 | void createUI() override; 19 | 20 | void draw(glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projectionMat, Light *light) override; 21 | 22 | inline bool isGrounded(){return m_isGrounded;} 23 | inline void setTerrain(TerrainManager *terrain){m_terrain = terrain;} 24 | inline bool isInCollision(){return m_isGrounded || m_isInCollision;} 25 | private: 26 | void displayImGuiVoxel(Voxel voxel, const char message[]); 27 | bool intersect(glm::vec3 boxMin, glm::vec3 boxMax); 28 | bool intersect(glm::vec3 box1Min, glm::vec3 box1Max, glm::vec3 box2Min, glm::vec3 box2Max); 29 | bool intersectAccordingToMove(glm::vec3 boxMin, glm::vec3 boxMax); 30 | void updateCollidingBox(); 31 | void computeCollisionWithGround(); 32 | glm::vec3 computeCollision(); 33 | bool raycast(); 34 | 35 | void drawAABB(glm::vec3 min, glm::vec3 max, Shader shader, glm::vec4 color = glm::vec4(1,0,0,1)); 36 | 37 | TerrainManager *m_terrain = nullptr; 38 | 39 | glm::vec3 m_collidingBox; 40 | bool m_showCollidingBox, m_showCheckCollision; 41 | 42 | glm::vec3 m_boxMin, m_boxMax; 43 | 44 | Rigidbody *m_rb; 45 | 46 | glm::vec3 m_targetHitPoint; 47 | 48 | bool m_isGrounded, m_isInCollision; 49 | }; 50 | 51 | #endif -------------------------------------------------------------------------------- /src/components/component.cpp: -------------------------------------------------------------------------------- 1 | #include "component.h" 2 | 3 | 4 | -------------------------------------------------------------------------------- /src/components/component.h: -------------------------------------------------------------------------------- 1 | #ifndef COMPONENT_H 2 | #define COMPONENT_H 3 | 4 | #include 5 | #include 6 | 7 | class GameObject; 8 | 9 | 10 | class Component { 11 | public: 12 | virtual ~Component() = default; 13 | 14 | virtual void start(){} 15 | 16 | virtual void update(){} 17 | virtual void inputUpdate(){} 18 | virtual void physicsUpdate(){} 19 | 20 | virtual void createUI(){} 21 | 22 | 23 | bool getActive(){return m_active;} 24 | void setActive(bool active){m_active = active;} 25 | const char* getName(){return m_name;} 26 | void setName(const char* name){strncpy(m_name, name, 2048);}; 27 | 28 | 29 | void setGameObject(GameObject * obj){m_gameobject = obj;} 30 | GameObject* getGameObject(){return m_gameobject;} 31 | 32 | bool m_active = true; 33 | 34 | 35 | protected: 36 | 37 | GameObject *m_gameobject; 38 | char m_name[2048] = "Untitled Component"; 39 | 40 | 41 | }; 42 | 43 | #endif -------------------------------------------------------------------------------- /src/components/debug/debugTransform.cpp: -------------------------------------------------------------------------------- 1 | #include "debugTransform.h" 2 | 3 | #include "../../engineClass/gameObject.h" 4 | 5 | #include 6 | 7 | #ifndef GLM_H 8 | #define GLM_H 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #endif 15 | 16 | 17 | void DebugTransform::createUI(){ 18 | const glm::mat4 inverted = glm::inverse(m_gameobject->getTransform()->getModelMat()); 19 | const glm::vec3 forward = normalize(glm::vec3(inverted[2])); 20 | const glm::vec3 left = normalize(glm::vec3(inverted[0])); 21 | const glm::vec3 top = normalize(glm::vec3(inverted[1])); 22 | 23 | ImGui::Separator(); 24 | ImGui::Text("Forward (%f, %f, %f)", forward.x, forward.y, forward.z); 25 | ImGui::Text("Left (%f, %f, %f)", left.x, left.y, left.z); 26 | ImGui::Text("Top (%f, %f, %f)", top.x, top.y, top.z); 27 | } -------------------------------------------------------------------------------- /src/components/debug/debugTransform.h: -------------------------------------------------------------------------------- 1 | #ifndef DEBUGTRANSFORM_H 2 | #define DEBUGTRANSFORM_H 3 | 4 | #include "../component.h" 5 | 6 | class DebugTransform : public Component { 7 | public: 8 | 9 | DebugTransform(){setName("Debug Transform");} 10 | void createUI() override; 11 | 12 | private: 13 | 14 | }; 15 | 16 | #endif -------------------------------------------------------------------------------- /src/components/fireProjectiles.cpp: -------------------------------------------------------------------------------- 1 | #include "fireProjectiles.h" 2 | 3 | #include "meshRenderer.h" 4 | #include "../models/mesh/meshCube.h" 5 | #include "../material/lambertian.h" 6 | #include "projectile.h" 7 | #include "axisRenderer.h" 8 | #include "debug/debugTransform.h" 9 | #include "colliders/collider.h" 10 | #include "rigidbody.h" 11 | #include "terrainModificator.h" 12 | 13 | #include 14 | #include 15 | 16 | FireProjectiles::FireProjectiles() : m_projectileSpeed(0.2f), m_radiusExplosionProjectile(5){ 17 | setName("Fire Projectiles"); 18 | } 19 | 20 | 21 | FireProjectiles::~FireProjectiles(){ 22 | 23 | } 24 | 25 | void FireProjectiles::inputUpdate(){ 26 | if(!getActive()){ 27 | return; 28 | } 29 | if(ImGui::IsKeyPressed('F')){ 30 | createProjectile(); 31 | } 32 | } 33 | 34 | glm::vec3 FireProjectiles::computeForward(){ 35 | glm::vec3 input = glm::vec3(0,0,-1); 36 | glm::vec3 pos = m_gameobject->getTransform()->getPosition(); 37 | glm::vec3 rotation = m_gameobject->getTransform()->getRotation(); 38 | float dx = glm::cos(rotation.y); 39 | float dz = glm::sin(rotation.y); 40 | 41 | pos.z += input.z * dx; 42 | pos.x += input.z * dz; 43 | 44 | glm::vec3 vect = glm::normalize(m_gameobject->getTransform()->getPosition() - pos); 45 | 46 | return vect; 47 | } 48 | 49 | void FireProjectiles::createProjectile(){ 50 | 51 | 52 | 53 | Transform *transf = new Transform(); 54 | 55 | const vec3 forward = computeForward(); 56 | 57 | glm::vec3 pos = m_gameobject->getTransform()->getPosition(); 58 | pos += forward*0.5f; 59 | transf->setPosition(pos); 60 | transf->setRotation(m_gameobject->getTransform()->getRotation()); 61 | 62 | // Creation Rigidbody 63 | Rigidbody *rb = new Rigidbody(); 64 | rb->setUseGravity(false); 65 | rb->setMove(forward); 66 | rb->setSpeed(m_projectileSpeed); 67 | 68 | GameObject *projectile = new GameObject(m_scene->addNewId(), "Projectile", transf); 69 | projectile->addComponent(new MeshCube(0.2f)); 70 | projectile->addComponent(new Lambertian()); 71 | projectile->addComponent(rb); 72 | projectile->addComponent(new MeshRenderer()); 73 | projectile->getComponent()->toggleDisplayDiffuse(); 74 | projectile->addComponent(new Collider(glm::vec3(0.25f))); 75 | projectile->getComponent()->setTerrain(m_terrain); 76 | 77 | projectile->addComponent(new TerrainModificator()); 78 | projectile->getComponent()->setTerrain(m_terrain); 79 | 80 | Projectile *proj = new Projectile(m_radiusExplosionProjectile); 81 | proj->setScene(m_scene); 82 | proj->setPlayerTransform(m_gameobject->getTransform()); 83 | projectile->addComponent(proj); 84 | 85 | // debug 86 | 87 | m_scene->addGameObject(projectile); 88 | 89 | } 90 | 91 | 92 | 93 | void FireProjectiles::createUI() { 94 | ImGui::Text("Projectile Speed : "); 95 | ImGui::DragFloat("##speed", &m_projectileSpeed, 0.01f,0.01f, 200.f); 96 | ImGui::Text("Radius of explosion : "); 97 | ImGui::DragInt("##radius", &m_radiusExplosionProjectile, 1, 1, 100); 98 | } -------------------------------------------------------------------------------- /src/components/fireProjectiles.h: -------------------------------------------------------------------------------- 1 | #ifndef FIREPROJECTILES_H 2 | #define FIREPROJECTILES_H 3 | 4 | #include "component.h" 5 | #include "../engineClass/scene.h" 6 | #include "../terrain/terrainManager.h" 7 | 8 | class FireProjectiles : public Component { 9 | 10 | public: 11 | FireProjectiles(); 12 | ~FireProjectiles(); 13 | 14 | void inputUpdate() override; 15 | void createUI() override; 16 | 17 | void setScene(Scene *scene){m_scene = scene;} 18 | void setTerrain(TerrainManager *terrain){m_terrain = terrain;} 19 | private: 20 | glm::vec3 computeForward(); 21 | void createProjectile(); 22 | 23 | Scene *m_scene; 24 | float m_projectileSpeed; 25 | TerrainManager *m_terrain; 26 | int m_radiusExplosionProjectile; 27 | 28 | }; 29 | 30 | 31 | #endif -------------------------------------------------------------------------------- /src/components/groundFollow.cpp: -------------------------------------------------------------------------------- 1 | #include "groundFollow.h" 2 | 3 | #ifndef GLM_H 4 | #define GLM_H 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #endif 11 | 12 | GroundFollow::GroundFollow() : m_heightOffset(0.25f){ 13 | setName("Ground Follow"); 14 | } 15 | 16 | void GroundFollow::update(){ 17 | 18 | assert(m_terrain != nullptr); 19 | 20 | glm::vec3 position = m_gameobject->getTransform()->getPosition(); 21 | position.y -= m_heightOffset; 22 | 23 | glm::vec3 bottomVoxelOffset(0, 1, 0); 24 | 25 | Voxel v = m_terrain->getVoxelAt(round(position)); 26 | 27 | if (v == Voxel::Empty) { 28 | v = m_terrain->getVoxelAt(round(position - bottomVoxelOffset)); 29 | 30 | if (v == Voxel::Empty){ 31 | position.y = round(position.y - 1); 32 | } 33 | } 34 | else{ 35 | position.y = round(position.y + 1); 36 | } 37 | 38 | m_gameobject->getTransform()->setPosition(position + bottomVoxelOffset * m_heightOffset); 39 | } 40 | 41 | void GroundFollow::createUI(){ 42 | ImGui::Text("Height Offset : "); 43 | ImGui::DragFloat("##heightOffset", &m_heightOffset, 0.00f,0.01f, 1000.f); 44 | ImGui::Text("height: %f", m_terrain->getHeightAt(m_gameobject->getTransform()->getPosition().x, m_gameobject->getTransform()->getPosition().z)); 45 | } -------------------------------------------------------------------------------- /src/components/groundFollow.h: -------------------------------------------------------------------------------- 1 | #ifndef GROUNDFOLLOW_H 2 | #define GROUNDFOLLOW_H 3 | 4 | #include "component.h" 5 | #include "../terrain/terrainManager.h" 6 | 7 | class GroundFollow : public Component { 8 | public: 9 | 10 | GroundFollow(); 11 | 12 | void update() override; 13 | void createUI() override; 14 | 15 | void setTerrain(TerrainManager *terrain){m_terrain = terrain;} 16 | 17 | private: 18 | 19 | TerrainManager *m_terrain = nullptr; 20 | float m_heightOffset; 21 | 22 | }; 23 | 24 | 25 | #endif -------------------------------------------------------------------------------- /src/components/meshRenderer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "../models/mesh/mesh.h" 6 | 7 | #define POSITION_ATTRIB 0 8 | #define VERTEX_NORMAL_ATTRIB 1 9 | #define VERTEX_UV_ATTRIB 2 10 | 11 | 12 | #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) 13 | #include // Initialize with gl3wInit() 14 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) 15 | #include // Initialize with glewInit() 16 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) 17 | #include // Initialize with gladLoadGL() 18 | #else 19 | #include IMGUI_IMPL_OPENGL_LOADER_CUSTOM 20 | #endif 21 | 22 | #include 23 | 24 | #include 25 | 26 | #include "meshRenderer.h" 27 | 28 | MeshRenderer::MeshRenderer() : m_showBoundingBox(false) { 29 | setName("Mesh Renderer"); 30 | } 31 | 32 | void MeshRenderer::start() { 33 | mesh = m_gameobject->getComponent(); assert(mesh != nullptr); 34 | material = m_gameobject->getComponent(); assert(material != nullptr); 35 | } 36 | 37 | void MeshRenderer::draw(glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projectionMat, Light *light) { 38 | 39 | if(!material->getActive()) 40 | return; 41 | 42 | glUseProgram(material->getShaderID()); 43 | 44 | material->callUniform(modelMat, viewMat, projectionMat, light); 45 | 46 | if(mesh->getActive()) 47 | mesh->drawVAO(); 48 | 49 | glUseProgram(0); 50 | 51 | if(m_showBoundingBox) 52 | drawBoxWithMatrices(mesh->getMin()*1.1f, mesh->getMax()*1.1f, modelMat, viewMat, projectionMat); 53 | } 54 | 55 | void MeshRenderer::createUI(){ 56 | ImGui::Text("Show bounding box : "); ImGui::SameLine(); ImGui::Checkbox("##showbounding", &m_showBoundingBox); 57 | } 58 | 59 | // draw box that move with the object 60 | void MeshRenderer::drawBoxWithMatrices(glm::vec3 min, glm::vec3 max, glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projectionMat){ 61 | Shader shader = Shader(); 62 | shader.load("../data/shaders/displayBoundingBox.vert","../data/shaders/displayBoundingBox.frag"); 63 | 64 | glUseProgram(shader.id()); 65 | glUniformMatrix4fv(glGetUniformLocation(shader.id(),"modelMat"),1,GL_FALSE,&(modelMat[0][0])); 66 | glUniformMatrix4fv(glGetUniformLocation(shader.id(),"viewMat"),1,GL_FALSE,&(viewMat[0][0])); 67 | glUniformMatrix4fv(glGetUniformLocation(shader.id(),"projMat"),1,GL_FALSE,&(projectionMat[0][0])); 68 | 69 | std::vector array; 70 | array.reserve(36); 71 | 72 | array.push_back(glm::vec3(min.x,max.y,max.z)); array.push_back(glm::vec3(min.x,min.y,max.z)); array.push_back(glm::vec3(max.x,max.y,max.z)); 73 | array.push_back(glm::vec3(max.x,max.y,max.z)); array.push_back(glm::vec3(min.x,min.y,max.z)); array.push_back(glm::vec3(max.x,min.y,max.z)); 74 | 75 | array.push_back(glm::vec3(max.x,max.y,min.z)); array.push_back(glm::vec3(max.x,min.y,min.z)); array.push_back(glm::vec3(min.x,max.y,min.z)); 76 | array.push_back(glm::vec3(min.x,max.y,min.z)); array.push_back(glm::vec3(max.x,min.y,min.z)); array.push_back(glm::vec3(min.x,min.y,min.z)); 77 | 78 | array.push_back(glm::vec3(min.x,max.y,min.z)); array.push_back(glm::vec3(min.x,min.y,min.z)); array.push_back(glm::vec3(min.x,min.y,max.z)); 79 | array.push_back(glm::vec3(min.x,min.y,max.z)); array.push_back(glm::vec3(min.x,max.y,max.z)); array.push_back(glm::vec3(min.x,max.y,min.z)); 80 | 81 | array.push_back(glm::vec3(max.x,max.y,max.z)); array.push_back(glm::vec3(max.x,min.y,max.z)); array.push_back(glm::vec3(max.x,max.y,min.z)); 82 | array.push_back(glm::vec3(max.x,max.y,min.z)); array.push_back(glm::vec3(max.x,min.y,max.z)); array.push_back(glm::vec3(max.x,min.y,min.z)); 83 | 84 | array.push_back(glm::vec3(min.x,min.y,max.z)); array.push_back(glm::vec3(min.x,min.y,min.z)); array.push_back(glm::vec3(max.x,min.y,max.z)); 85 | array.push_back(glm::vec3(max.x,min.y,max.z)); array.push_back(glm::vec3(min.x,min.y,min.z)); array.push_back(glm::vec3(max.x,min.y,min.z)); 86 | 87 | array.push_back(glm::vec3(min.x,max.y,min.z)); array.push_back(glm::vec3(min.x,max.y,max.z)); array.push_back(glm::vec3(max.x,max.y,min.z)); 88 | array.push_back(glm::vec3(max.x,max.y,min.z)); array.push_back(glm::vec3(min.x,max.y,max.z)); array.push_back(glm::vec3(max.x,max.y,max.z)); 89 | 90 | 91 | glLineWidth(1); 92 | DrawDebug::drawArrayPosition(array.size(), (float*)&(array[0]), GL_TRIANGLES, GL_LINE); 93 | 94 | glUseProgram(0); 95 | } 96 | 97 | -------------------------------------------------------------------------------- /src/components/meshRenderer.h: -------------------------------------------------------------------------------- 1 | #ifndef MESHRENDERER_H 2 | #define MESHRENDERER_H 3 | 4 | #include "renderer.h" 5 | #include "../models/mesh/mesh.h" 6 | #include "../material/lambertian.h" 7 | 8 | class MeshRenderer : public Renderer { 9 | 10 | public: 11 | 12 | Mesh *mesh = nullptr; 13 | Material *material = nullptr; 14 | 15 | MeshRenderer(); 16 | 17 | void start() override; 18 | void draw(glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projectionMat, Light *light) override; 19 | void createUI() override; 20 | 21 | protected: 22 | 23 | void drawBoxWithMatrices(glm::vec3 min, glm::vec3 max, glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projectionMat); 24 | 25 | bool m_showBoundingBox; 26 | }; 27 | 28 | #endif -------------------------------------------------------------------------------- /src/components/playerController.cpp: -------------------------------------------------------------------------------- 1 | #include "playerController.h" 2 | 3 | #ifndef GLM_H 4 | #define GLM_H 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #endif 11 | 12 | #include 13 | #include "colliders/collider.h" 14 | #include "rigidbody.h" 15 | 16 | #ifndef M_PI 17 | #define M_PI 3.1415926 18 | #endif 19 | 20 | 21 | 22 | PlayerController::PlayerController() : m_jumpForce(1.3f) { 23 | setName("Player Controller"); 24 | } 25 | 26 | void PlayerController::inputUpdate() { 27 | Rigidbody *rb = m_gameobject->getComponent(); 28 | if(rb == nullptr){ 29 | return; 30 | } 31 | 32 | 33 | glm::vec3 input = glm::vec3(0.0f); 34 | 35 | if(ImGui::IsKeyPressed('W')){ 36 | input.z = 1.0f; 37 | } 38 | if(ImGui::IsKeyPressed('S')){ 39 | input.z = -1.0f; 40 | } 41 | if(ImGui::IsKeyPressed('A')){ 42 | input.x = -1.0f; 43 | } 44 | if(ImGui::IsKeyPressed('D')){ 45 | input.x = 1.0f; 46 | } 47 | if(ImGui::IsKeyPressed(' ')) { // barre espace 48 | Collider* collider = m_gameobject->getComponent(); 49 | if(collider != nullptr && collider->getActive()){ 50 | if(collider->isGrounded()){ 51 | input.y = 1.0f; 52 | } 53 | } 54 | } 55 | 56 | glm::vec3 pos = m_gameobject->getTransform()->getPosition(); 57 | glm::vec3 rotation = m_gameobject->getTransform()->getRotation(); 58 | float dx = glm::cos(rotation.y); 59 | float dz = glm::sin(rotation.y); 60 | 61 | float dxx = glm::cos(M_PI - rotation.y); 62 | float dzx = glm::sin(M_PI - rotation.y); 63 | 64 | pos.z += input.z * dx; 65 | pos.x += input.z * dz; 66 | pos.z += input.x * dzx; 67 | pos.x += input.x * dxx; 68 | 69 | glm::vec3 vectorMove = rb->getMove(); 70 | 71 | 72 | float yMove = vectorMove.y + input.y*m_jumpForce; 73 | 74 | 75 | vectorMove = pos - m_gameobject->getTransform()->getPosition(); 76 | vectorMove.y = yMove; 77 | 78 | rb->setMove(vectorMove); 79 | } 80 | 81 | 82 | void PlayerController::createUI(){ 83 | ImGui::Text("Jump Force : "); 84 | ImGui::DragFloat("##jump", &m_jumpForce, 0.01f,0.01f, 1000.f); 85 | } 86 | -------------------------------------------------------------------------------- /src/components/playerController.h: -------------------------------------------------------------------------------- 1 | #ifndef PLAYERCONTROLLER_H 2 | #define PLAYERCONTROLLER_H 3 | 4 | #include "component.h" 5 | 6 | class PlayerController : public Component { 7 | public: 8 | PlayerController(); 9 | void inputUpdate() override; 10 | void createUI() override; 11 | 12 | private: 13 | float m_jumpForce; 14 | 15 | }; 16 | 17 | #endif -------------------------------------------------------------------------------- /src/components/projectile.cpp: -------------------------------------------------------------------------------- 1 | #include "projectile.h" 2 | 3 | #ifndef M_PI 4 | #define M_PI 3.1415926 5 | #endif 6 | 7 | #ifndef GLM_H 8 | #define GLM_H 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #endif 15 | 16 | #include "../engineClass/gameObject.h" 17 | 18 | #include 19 | 20 | #include "colliders/collider.h" 21 | #include "terrainModificator.h" 22 | 23 | 24 | Projectile::Projectile(int radius) : m_radiusOfExplosion(radius){ 25 | setName("Projectile"); 26 | } 27 | 28 | 29 | Projectile::~Projectile(){ 30 | 31 | } 32 | 33 | void Projectile::update(){ 34 | Collider* collider = m_gameobject->getComponent(); 35 | TerrainModificator* terainModif = m_gameobject->getComponent(); 36 | if(collider == nullptr || terainModif == nullptr){ 37 | return; 38 | } 39 | 40 | if(collider->isInCollision()){ 41 | terainModif->destroy(m_radiusOfExplosion); 42 | assert(m_scene != nullptr); 43 | m_scene->addToDestroy(m_gameobject->getID()); 44 | } 45 | } 46 | 47 | void Projectile::createUI(){ 48 | Collider* collider = m_gameobject->getComponent(); 49 | if(collider != nullptr){ 50 | ImGui::Text("Is in collision : %s", collider->isInCollision() ? "true" : "false"); 51 | } 52 | ImGui::Text("Radius of explosion : "); 53 | ImGui::DragInt("##radius", &m_radiusOfExplosion, 1, 1, 100); 54 | } -------------------------------------------------------------------------------- /src/components/projectile.h: -------------------------------------------------------------------------------- 1 | #ifndef PROJECTILE_H 2 | #define PROJECTILE_H 3 | 4 | #include "component.h" 5 | #include "../engineClass/scene.h" 6 | 7 | class Projectile : public Component { 8 | public: 9 | Projectile(int radius = 5); 10 | ~Projectile(); 11 | 12 | void update() override; 13 | void createUI() override; 14 | void setScene(Scene *scene){m_scene = scene;} 15 | void setPlayerTransform(Transform *transform){ m_playerTransform = transform;} 16 | 17 | private: 18 | Transform *m_playerTransform; 19 | float m_speed; 20 | int m_radiusOfExplosion; 21 | Scene *m_scene; 22 | }; 23 | 24 | 25 | #endif -------------------------------------------------------------------------------- /src/components/renderer.h: -------------------------------------------------------------------------------- 1 | #ifndef RENDERER_H 2 | #define RENDERER_H 3 | 4 | #include "component.h" 5 | #include "../tools/lights/light.h" 6 | 7 | class Renderer : public Component { 8 | 9 | public: 10 | 11 | virtual void draw(glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projectionMat, Light *light) = 0; 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /src/components/rigidbody.cpp: -------------------------------------------------------------------------------- 1 | #include "rigidbody.h" 2 | #include "../engineClass/mainRenderer.h" 3 | 4 | #include 5 | 6 | #include "colliders/collider.h" 7 | 8 | #ifndef M_PI 9 | #define M_PI 3.1415926 10 | #endif 11 | 12 | 13 | Rigidbody::Rigidbody(float speed) : m_speed(speed), m_velocity(glm::vec3(0)), m_vectorMove(glm::vec3(0)), m_useGravity(false), m_mass(0.15f) { 14 | setName("Rigidbody"); 15 | } 16 | 17 | 18 | void Rigidbody::update() { 19 | extern float global_limitFramerate; 20 | 21 | 22 | glm::vec3 pos = m_gameobject->getTransform()->getPosition(); 23 | 24 | 25 | computeGravity(); 26 | 27 | glm::vec3 currentMove = m_vectorMove; 28 | 29 | currentMove.x *= m_speed; 30 | currentMove.z *= m_speed; 31 | 32 | 33 | 34 | 35 | assert(global_limitFramerate != 0.0f); 36 | float deltaTime = ImGui::GetIO().Framerate / global_limitFramerate; 37 | currentMove *= deltaTime; 38 | // printf("Delta Y: %f\n", deltaTime); 39 | 40 | 41 | 42 | m_gameobject->m_transform->setPosition(pos+currentMove); 43 | 44 | } 45 | 46 | void Rigidbody::createUI() { 47 | ImGui::Text("Speed : "); 48 | ImGui::DragFloat("##speed", &m_speed, 0.01f,0.01f, 1000.f); 49 | ImGui::Text("Mass : "); 50 | ImGui::DragFloat("##mass", &m_mass, 0.01f,0.01f, 1000.f); 51 | ImGui::Text("Use gravity: "); ImGui::SameLine(); 52 | ImGui::Checkbox("##useGravity", &m_useGravity); 53 | ImGui::Text("Vector move : (%4f, %4f, %4f)", m_vectorMove.x, m_vectorMove.y, m_vectorMove.z); 54 | } 55 | 56 | 57 | void Rigidbody::computeGravity() { 58 | if(m_useGravity){ 59 | 60 | m_vectorMove.y -= m_mass*m_gameobject->getTransform()->getScale().y; 61 | 62 | Collider* collider = m_gameobject->getComponent(); 63 | if(collider != nullptr && collider->getActive()){ 64 | if(collider->isGrounded() && m_vectorMove.y < 0){ 65 | m_vectorMove.y = 0.0f; 66 | } 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/components/rigidbody.h: -------------------------------------------------------------------------------- 1 | #ifndef RIGIDBODY_H 2 | #define RIGIDBODY_H 3 | 4 | #include "component.h" 5 | #include "../engineClass/gameObject.h" 6 | 7 | #ifndef GLM_H 8 | #define GLM_H 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #endif 15 | 16 | #include 17 | #include 18 | #include 19 | 20 | 21 | class Rigidbody : public Component { 22 | 23 | public: 24 | Rigidbody(float speed = 0.5f); 25 | 26 | void update() override; 27 | 28 | void createUI() override; 29 | 30 | float getSpeed(){return m_speed;} 31 | void setSpeed(float speed){m_speed = speed;} 32 | float getMass(){return m_mass;} 33 | glm::vec3 getMove(){return m_vectorMove;} 34 | void setMove(glm::vec3 move){m_vectorMove = move;} 35 | bool useGravity(){return m_useGravity;} 36 | void setUseGravity(bool use){m_useGravity = use;} 37 | 38 | private: 39 | void computeGravity(); 40 | 41 | float m_speed, m_mass; 42 | bool m_useGravity; 43 | 44 | glm::vec3 m_vectorMove; 45 | glm::vec3 m_velocity; 46 | 47 | }; 48 | 49 | #endif -------------------------------------------------------------------------------- /src/components/terrainModificator.cpp: -------------------------------------------------------------------------------- 1 | #include "terrainModificator.h" 2 | 3 | #ifndef GLM_H 4 | #define GLM_H 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #endif 11 | 12 | TerrainModificator::TerrainModificator(){ 13 | setName("Terrain Modificator"); 14 | } 15 | 16 | void TerrainModificator::destroy(size_t radius) 17 | { 18 | setSphere(m_gameobject->getTransform()->getPosition(), radius, Voxel::Empty); 19 | } 20 | 21 | void TerrainModificator::setSphere(glm::vec3 world_coord, size_t radius, Voxel v) { 22 | glm::vec3 min_coord = world_coord - glm::vec3(radius); 23 | 24 | for(size_t i = 0 ; i < m_terrain->getChunkSize() ; i++) { 25 | for(size_t j = 0 ; j < m_terrain->getChunkSize() ; j++) { 26 | for(size_t k = 0 ; k < m_terrain->getChunkSize() ; k++) { 27 | 28 | glm::vec3 current_coord = min_coord + glm::vec3(i, j, k); 29 | 30 | if (glm::distance(world_coord, current_coord) <= radius) 31 | m_terrain->setVoxelAt(min_coord + glm::vec3(i, j, k), v); 32 | } 33 | } 34 | } 35 | } 36 | 37 | void TerrainModificator::inputUpdate(){ 38 | 39 | glm::vec3 pos = m_gameobject->getTransform()->getPosition(); 40 | 41 | if(ImGui::IsKeyPressed('O')) 42 | setSphere(pos, 10, Voxel::Empty); 43 | else if (ImGui::IsKeyPressed('I')) 44 | setSphere(pos, 10, Voxel::Full); 45 | } 46 | 47 | void TerrainModificator::createUI(){ 48 | // ImGui::Text("Height Offset : "); 49 | glm::vec3 world_pos = m_gameobject->getTransform()->getPosition(); 50 | glm::ivec3 chunk_grid_pos = m_terrain->toChunkGridCoord(world_pos); 51 | glm::ivec3 voxel_coord = m_terrain->toVoxelCoord(world_pos); 52 | glm::ivec3 voxel_delete = m_terrain->toVoxelCoord(glm::vec3(world_pos.x, world_pos.y-1, world_pos.z)); 53 | 54 | ImGui::InputInt3("Player Chunk Pos : ", &chunk_grid_pos.x); 55 | ImGui::InputInt3("Player Voxel Pos : ", &voxel_coord.x); 56 | ImGui::InputInt3("Delete Voxel Pos : ", &voxel_delete.x); 57 | } -------------------------------------------------------------------------------- /src/components/terrainModificator.h: -------------------------------------------------------------------------------- 1 | #ifndef TERRAIN_MODIFICATOR_H 2 | #define TERRAIN_MODIFICATOR_H 3 | 4 | #include "component.h" 5 | #include "../terrain/terrainManager.h" 6 | 7 | class TerrainModificator : public Component { 8 | public: 9 | 10 | TerrainModificator(); 11 | 12 | void inputUpdate() override; 13 | void createUI() override; 14 | 15 | void destroy(size_t radius); 16 | void setSphere(glm::vec3 position, size_t radius, Voxel v); 17 | 18 | void setTerrain(TerrainManager *terrain){m_terrain = terrain;} 19 | 20 | private: 21 | 22 | TerrainManager *m_terrain = nullptr; 23 | }; 24 | 25 | 26 | #endif -------------------------------------------------------------------------------- /src/components/thirdPersonController.cpp: -------------------------------------------------------------------------------- 1 | #include "thirdPersonController.h" 2 | #include 3 | 4 | #include 5 | 6 | #ifndef GLM_H 7 | #define GLM_H 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #endif 14 | 15 | ThirdPersonController::ThirdPersonController() : m_sensitivity(glm::vec2(0.5f)){ 16 | setName("Third Person Controller"); 17 | } 18 | 19 | 20 | 21 | ThirdPersonController::~ThirdPersonController(){ 22 | 23 | } 24 | 25 | 26 | 27 | void ThirdPersonController::update(){ 28 | ImGuiIO& io = ImGui::GetIO(); 29 | if(io.KeyCtrl && ImGui::IsKeyPressed('G')){ 30 | m_active = !m_active; 31 | } 32 | if(!m_active){ 33 | return; 34 | } 35 | 36 | if(m_camera == NULL){ 37 | return; 38 | } 39 | 40 | 41 | // CAMERA EDITOR CONTROL 42 | if(!io.WantCaptureMouse){ 43 | 44 | glm::vec3 rotation = m_gameobject->getTransform()->getRotation(); 45 | glm::vec3 camrotation = m_camera->getTransform()->getRotation(); 46 | 47 | glm::vec2 vectorMouse = glm::vec2(io.MouseDelta.x, io.MouseDelta.y); 48 | vectorMouse *= -1.0f; 49 | vectorMouse *= m_sensitivity*0.01f; 50 | 51 | rotation.y += vectorMouse.x; 52 | camrotation.x -= vectorMouse.y; 53 | camrotation.x = glm::clamp(camrotation.x, 0.0f, 1.5f); 54 | 55 | m_gameobject->getTransform()->setRotation(rotation); 56 | m_camera->getTransform()->setRotation(camrotation); 57 | } 58 | 59 | } 60 | 61 | 62 | void ThirdPersonController::createUI(){ 63 | ImGui::Text("Sensitivity : (x0.01)"); 64 | ImGui::DragFloat2("##rotationsensitivity", &m_sensitivity[0], 0.01, 0.0, 100.); 65 | } -------------------------------------------------------------------------------- /src/components/thirdPersonController.h: -------------------------------------------------------------------------------- 1 | #ifndef THIRDPERSONCONTROLLER_H 2 | #define THIRDPERSONCONTROLLER_H 3 | 4 | #include "component.h" 5 | #include "cameraProjective.h" 6 | #include "../engineClass/gameObject.h" 7 | 8 | class ThirdPersonController : public Component { 9 | public: 10 | ThirdPersonController(); 11 | ~ThirdPersonController(); 12 | 13 | void update() override; 14 | void createUI() override; 15 | 16 | void setCamera(GameObject *camera){m_camera = camera;} 17 | 18 | 19 | private: 20 | 21 | GameObject *m_camera; 22 | glm::vec2 m_sensitivity; 23 | 24 | }; 25 | 26 | 27 | #endif -------------------------------------------------------------------------------- /src/engineClass/InputManager.cpp: -------------------------------------------------------------------------------- 1 | #include "InputManager.h" 2 | #include 3 | 4 | #include "UI.h" 5 | 6 | #include 7 | 8 | InputManager::InputManager(){ 9 | } 10 | 11 | InputManager::~InputManager(){ 12 | 13 | } 14 | 15 | void InputManager::setScene(Scene *sc){ 16 | m_scene = sc; 17 | } 18 | 19 | void InputManager::setUI(UI *u){ 20 | m_ui = u; 21 | } 22 | 23 | void InputManager::setRenderer(MainRenderer *r){ 24 | m_renderer = r; 25 | } 26 | 27 | void InputManager::createUI(){ 28 | 29 | if(m_ui == NULL){ 30 | return; 31 | } else { 32 | if(!m_ui->hasToDisplayed()){ return; } 33 | } 34 | 35 | ImGui::Begin("Settings"); 36 | 37 | ImGui::Text("Input Manager"); 38 | ImGui::Separator(); 39 | 40 | 41 | 42 | ImGui::End(); 43 | 44 | 45 | ImGuiIO& io = ImGui::GetIO(); 46 | ImGui::Begin("Debug"); 47 | ImGui::Separator(); 48 | 49 | if(ImGui::IsMouseDown(0) && !io.WantCaptureMouse){ 50 | ImGui::Text("Mouse click position : (%3f, %3f)", io.MousePos.x, io.MousePos.y); 51 | ImGui::Text("Vector mouse : (%2f, %2f)\n", io.MouseDelta.x, io.MouseDelta.y); 52 | 53 | } else { 54 | ImGui::Text("Mouse click position : \n"); 55 | ImGui::Text("Vector mouse : \n"); 56 | } 57 | 58 | ImGui::Text("Mouse wheel: %.1f", io.MouseWheel); 59 | 60 | ImGui::End(); 61 | } 62 | 63 | void InputManager::update(){ 64 | 65 | ImGuiIO& io = ImGui::GetIO(); 66 | 67 | if(m_scene != NULL && m_ui != NULL){ 68 | 69 | // suppr 70 | 71 | // if(ImGui::IsKeyPressed(ImGuiKey_Delete)){ 72 | if(ImGui::IsKeyPressed(261)){ // 0x105 73 | m_scene->deleteObject(m_ui->getSelected()); 74 | 75 | } 76 | 77 | if(io.KeyCtrl && ImGui::IsKeyPressed('T')){ 78 | m_scene->addGameObject(); 79 | } 80 | if(io.KeyCtrl && ImGui::IsKeyPressed('O')){ 81 | m_scene->addCube(); 82 | } 83 | } 84 | 85 | if(io.KeyCtrl){ 86 | if(ImGui::IsKeyPressed('P')){ 87 | if(m_scene != NULL){ 88 | m_scene->togglePause(); 89 | } 90 | } 91 | if(ImGui::IsKeyPressed('F')){ 92 | if(m_renderer != NULL){ 93 | m_renderer->toggleWire(); 94 | } 95 | } 96 | if(ImGui::IsKeyPressed('H')){ 97 | if(m_ui != NULL){ 98 | m_ui->toggleHasToBeDisplayed(); 99 | } 100 | } 101 | if(ImGui::IsKeyPressed('U')){ 102 | if(m_renderer != NULL){ 103 | m_renderer->togglePlayMode(); 104 | } 105 | } 106 | } 107 | 108 | 109 | } 110 | -------------------------------------------------------------------------------- /src/engineClass/InputManager.h: -------------------------------------------------------------------------------- 1 | #ifndef INPUTMANAGER_H 2 | #define INPUTMANAGER_H 3 | 4 | #include "scene.h" 5 | #include "mainRenderer.h" 6 | 7 | class UI; 8 | 9 | #ifndef GLM_H 10 | #define GLM_H 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #endif 17 | 18 | class InputManager { 19 | 20 | public: 21 | 22 | InputManager(); 23 | ~InputManager(); 24 | 25 | void setScene(Scene *sc); 26 | void setUI(UI *u); 27 | void setRenderer(MainRenderer *r); 28 | 29 | void createUI(); 30 | 31 | void update(); 32 | 33 | 34 | 35 | private: 36 | 37 | Scene *m_scene = NULL; 38 | UI *m_ui = NULL; 39 | MainRenderer *m_renderer = NULL; 40 | 41 | 42 | }; 43 | 44 | 45 | #endif 46 | -------------------------------------------------------------------------------- /src/engineClass/UI.h: -------------------------------------------------------------------------------- 1 | #ifndef UI_H 2 | #define UI_H 3 | 4 | #include 5 | 6 | #include "scene.h" 7 | #include "mainRenderer.h" 8 | #include "InputManager.h" 9 | 10 | #include 11 | 12 | 13 | #include 14 | #include 15 | #include 16 | 17 | 18 | class UI { 19 | public: 20 | UI(); 21 | ~UI(); 22 | 23 | void drawUI(); 24 | 25 | 26 | int getSelected(); 27 | 28 | void set(Scene *sc); 29 | void set(MainRenderer *main); 30 | void set(GLFWwindow *win); 31 | void set(InputManager *input){m_inputManager = input;}; 32 | 33 | inline bool hasToDisplayed(){ 34 | return m_hasToBeDisplayed; 35 | } 36 | inline void toggleHasToBeDisplayed(){ 37 | m_hasToBeDisplayed = !m_hasToBeDisplayed; 38 | } 39 | 40 | 41 | private: 42 | 43 | void createUISceneManager(Scene *scene); 44 | void DrawSplitter(int split_vertically, float thickness, float* size0, float* size1, float min_size0, float min_size1); 45 | void createInfoWindow(); 46 | void displayEngineNode(std::vector obj); 47 | GLuint loadTexture(unsigned char *pixels, int w, int h, int components); 48 | 49 | 50 | bool m_hasToBeDisplayed; 51 | int m_selectedID; 52 | 53 | Scene *m_scene; 54 | MainRenderer *m_mainRenderer; 55 | GLFWwindow* m_window; 56 | InputManager *m_inputManager; 57 | 58 | ImFont* m_pFont; 59 | 60 | }; 61 | 62 | #endif 63 | -------------------------------------------------------------------------------- /src/engineClass/gameObject.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "gameObject.h" 4 | #include "../components/meshRenderer.h" 5 | 6 | #include "../material/lambertian.h" 7 | #include "../models/mesh/meshCube.h" 8 | // #include "../components/chunkRenderer.h" 9 | #include "../components/axisRenderer.h" 10 | #include "../components/colliders/collider.h" 11 | #include "../components/rigidbody.h" 12 | #include "../components/playerController.h" 13 | 14 | #include 15 | #include 16 | 17 | 18 | GameObject::GameObject(int id, std::string n, Transform *t) : m_transform(t){ 19 | setID(id); 20 | setName(n); 21 | 22 | m_components = std::vector(); 23 | m_toRemove = std::vector(); 24 | } 25 | 26 | GameObject::~GameObject(){ 27 | delete m_transform; 28 | 29 | for(Component * comp : m_components){ 30 | delete comp; 31 | } 32 | 33 | for(unsigned int i=0; igetID() == id){ 72 | 73 | m_listOfChildren[i]->deleteAllChildren(); 74 | delete(m_listOfChildren[i]); 75 | m_listOfChildren.erase(m_listOfChildren.begin()+i); 76 | return; 77 | } 78 | } 79 | } 80 | 81 | 82 | // supprime tous les enfants de ce gameobject en récursif 83 | void GameObject::deleteAllChildren(){ 84 | for(int i=m_listOfChildren.size()-1; i >=0; i--){ 85 | if(m_listOfChildren[i]->m_listOfChildren.size() == 0){ // n'a pas d'enfant 86 | delete(m_listOfChildren[i]); 87 | m_listOfChildren.erase(m_listOfChildren.begin()+i); 88 | } else { 89 | m_listOfChildren[i]->deleteAllChildren(); 90 | delete(m_listOfChildren[i]); 91 | } 92 | } 93 | } 94 | 95 | 96 | void GameObject::createUI(char *ID){ 97 | ImGui::BeginChild(ID); 98 | ImGui::Text(m_name.c_str()); //ImGui::SameLine(); 99 | //ImGui::Text("id : %d", getID()); 100 | ImGui::Separator(); 101 | m_transform->createUI(); 102 | 103 | char label[2048]; 104 | unsigned int i=0; 105 | while(igetName()); 108 | if (ImGui::TreeNode(m_components[i]->getName())){ 109 | ImGui::SameLine(); ImGui::Checkbox("##active", &(m_components[i]->m_active)); 110 | ImGui::SameLine(); 111 | if(ImGui::Button("Delete Component")){ 112 | delete m_components[i]; 113 | m_components.erase(m_components.begin()+i); 114 | } else { 115 | m_components[i]->createUI(); 116 | i++; 117 | } 118 | ImGui::TreePop(); 119 | } else { 120 | i++; 121 | } 122 | } 123 | 124 | ImGui::Separator(); 125 | 126 | if(ImGui::BeginMenu("Add Component")){ 127 | if (ImGui::MenuItem("Add MeshCube")) { addComponent(new MeshCube()); } 128 | if (ImGui::MenuItem("Add Material")) { addComponent(new Lambertian()); } 129 | if (ImGui::MenuItem("Add MeshRenderer")) { addComponent(new MeshRenderer()); } 130 | if (ImGui::MenuItem("Add AxisRenderer")) { addComponent(new AxisRenderer()); } 131 | if (ImGui::MenuItem("Add Collider")) { addComponent(new Collider()); } 132 | if (ImGui::MenuItem("Add Rigidbody")) { addComponent(new Rigidbody()); } 133 | if (ImGui::MenuItem("Add Player Controller")) { addComponent(new PlayerController()); } 134 | ImGui::EndMenu(); 135 | } 136 | 137 | ImGui::EndChild(); 138 | } 139 | 140 | 141 | void GameObject::update(){ 142 | removeComponentToBeDestroyed(); 143 | m_transform->update(); 144 | 145 | for(unsigned int i=0; iupdate(); 147 | } 148 | } 149 | 150 | 151 | void GameObject::inputUpdate(){ 152 | for(unsigned int i=0; iinputUpdate(); 154 | } 155 | } 156 | 157 | void GameObject::physicsUpdate(){ 158 | for(unsigned int i=0; iphysicsUpdate(); 160 | } 161 | } 162 | 163 | 164 | void GameObject::removeComponentToBeDestroyed(){ 165 | for(int i=m_toRemove.size()-1; i>=0; i--){ 166 | delete m_toRemove[i]; 167 | m_toRemove.erase(m_toRemove.begin()+i); 168 | } 169 | } 170 | 171 | -------------------------------------------------------------------------------- /src/engineClass/gameObject.h: -------------------------------------------------------------------------------- 1 | #ifndef ENGINE_OBJECT_H 2 | #define ENGINE_OBJECT_H 3 | 4 | 5 | #include 6 | #include 7 | #include "../models/transform.h" 8 | 9 | #include "../components/component.h" 10 | 11 | 12 | 13 | class GameObject { 14 | 15 | 16 | public: 17 | GameObject(int id = -1, std::string n = "GameObject", Transform *t = new Transform()); 18 | virtual ~GameObject(); 19 | virtual void createUI(char *ID); 20 | 21 | void update(); 22 | void inputUpdate(); 23 | void physicsUpdate(); 24 | 25 | // ID + NAME 26 | void setName(std::string n); 27 | std::string getName(); 28 | int getID(); 29 | void setID(int i); 30 | 31 | /// GRAPHE SCENE 32 | void addChild(GameObject *obj); 33 | void removeChild(int id); 34 | void deleteAllChildren(); 35 | std::vector m_listOfChildren; 36 | 37 | // COMPONENT 38 | template< class ComponentType> ComponentType getComponent(); 39 | template< class ComponentType> std::vector getComponents(); 40 | template< class ComponentType> void addComponent(Component * component); 41 | template< class ComponentType> void addComponent(); 42 | template< class ComponentType > bool removeComponent(); 43 | 44 | 45 | std::vector m_toRemove; 46 | // TRANSFORM 47 | Transform *getTransform(); 48 | Transform *m_transform; 49 | 50 | protected: 51 | std::vector m_components; 52 | 53 | 54 | void removeComponentToBeDestroyed(); 55 | 56 | std::string m_name; 57 | int m_id; 58 | 59 | 60 | }; 61 | 62 | #include "gameObject.inl" 63 | 64 | #endif 65 | -------------------------------------------------------------------------------- /src/engineClass/gameObject.inl: -------------------------------------------------------------------------------- 1 | #ifndef ENGINE_OBJECT_INL 2 | #define ENGINE_OBJECT_INL 3 | 4 | // #include "gameObject.h" 5 | 6 | template< class ComponentType> ComponentType GameObject::getComponent(){ 7 | for ( Component * component : m_components ) { 8 | if ( ComponentType o = dynamic_cast(component) ){ 9 | return o; 10 | } 11 | } 12 | 13 | return nullptr; 14 | } 15 | 16 | template< class ComponentType> std::vector GameObject::getComponents(){ 17 | std::vector vec = std::vector(); 18 | for ( Component * component : m_components ) { 19 | if ( ComponentType o = dynamic_cast(component) ){ 20 | vec.push_back(o); 21 | } 22 | } 23 | 24 | return vec; 25 | } 26 | 27 | 28 | template< class ComponentType > bool GameObject::removeComponent() { 29 | for (unsigned int i=0; i(m_components[i]) ){ 32 | delete m_components[i]; 33 | m_components.erase(m_components.begin()+i); 34 | return true; 35 | } 36 | } 37 | 38 | return false; 39 | } 40 | 41 | template< class ComponentType > void GameObject::addComponent(Component * component) { 42 | if(!getComponent()){ 43 | m_components.push_back(component); 44 | component->setGameObject(this); 45 | component->start(); // Permet d'initialiser les données dynamiques du composant 46 | } 47 | } 48 | 49 | 50 | template< class ComponentType> void GameObject::addComponent(){ 51 | if(!getComponent()){ 52 | Component * comp = new ComponentType(); 53 | m_components.push_back(comp); 54 | comp->setGameObject(this); 55 | comp->start(); // Permet d'initialiser les données dynamiques du composant 56 | } 57 | } 58 | 59 | #endif -------------------------------------------------------------------------------- /src/engineClass/mainRenderer.h: -------------------------------------------------------------------------------- 1 | #ifndef MAINRENDERER_H 2 | #define MAINRENDERER_H 3 | 4 | #ifndef GLM_H 5 | #define GLM_H 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #endif 12 | 13 | 14 | #include "../tools/lights/light.h" 15 | #include "../tools/lights/directionnalLight.h" 16 | #include "../material/shader.h" 17 | 18 | #include "../components/cameraProjective.h" 19 | 20 | #include "scene.h" 21 | 22 | #include 23 | #include 24 | 25 | class MainRenderer { 26 | 27 | public: 28 | MainRenderer(); 29 | ~MainRenderer(); 30 | 31 | 32 | void paintGL(Scene *scene, int width, int height); 33 | void initializeGL(); 34 | void displaySceneOnTheScreen(int width, int height); 35 | 36 | 37 | 38 | 39 | void update(); 40 | void createUI(); 41 | 42 | 43 | 44 | inline void toggleWire(){m_wireActivated = !m_wireActivated;} 45 | inline void toggleCullface(){m_cullface = !m_cullface;} 46 | inline void toggleGrid(){m_gridActivated = !m_gridActivated;} 47 | inline void togglePlayMode(){m_playMode = !m_playMode;} 48 | GLuint getTextureID(){return m_renderedSceneTextureID;} 49 | inline unsigned int width(){return m_widthScreen;} 50 | inline unsigned int height(){return m_heightScreen;} 51 | inline GLuint getGameTextureID(){return m_renderedSceneTextureID;} 52 | inline GLuint getEditorTextureID(){return m_editorTextureID;} 53 | inline GameObject *getCamera(){return m_camera;} 54 | inline bool getPlayMode(){return m_playMode;} 55 | 56 | inline void setCamera(glm::vec3 position, glm::vec3 rotation){ 57 | m_camera->getTransform()->setPosition(position); 58 | m_camera->getTransform()->setRotation(rotation); 59 | } 60 | 61 | private: 62 | 63 | void renderTheScene(Scene *scene, int width, int height); 64 | void renderTheSceneEditor(Scene *scene, int width, int height); 65 | void drawRecursive(glm::mat4 modelMat, GameObject *obj, glm::mat4 viewMat, glm::mat4 projectionMat, Light *l, float screenAspectRatio); 66 | 67 | void drawEditorGrid(glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projectionMat); 68 | 69 | Light *getLight(); 70 | 71 | glm::mat4 m_viewMat; 72 | glm::mat4 m_projectionMat; 73 | 74 | // FBO 75 | 76 | GLuint m_fboRenderScene; 77 | GLuint m_renderedSceneTextureID; 78 | GLuint m_editorTextureID; 79 | GLuint m_renderedDepth; 80 | 81 | void createFBOSceneRender(); 82 | void initFBOSceneRender(int width, int height); 83 | void deleteFBOSceneRender(); 84 | 85 | 86 | 87 | 88 | /* final rendering */ 89 | void createVAOQuad(); 90 | void deleteVAOQuad(); 91 | void drawQuad(); 92 | 93 | Shader *m_postProcessShader; 94 | 95 | 96 | GLuint m_vaoQuad; 97 | GLuint m_quad; 98 | 99 | bool m_wireActivated; 100 | bool m_cullface; 101 | bool m_gridActivated; 102 | 103 | unsigned int m_widthScreen, m_heightScreen; 104 | 105 | GameObject *m_camera; 106 | CameraProjective *m_camProj; 107 | bool m_firstFramePassed; 108 | 109 | bool m_playMode; 110 | 111 | 112 | }; 113 | 114 | #endif 115 | -------------------------------------------------------------------------------- /src/engineClass/scene.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef SCENE_H 3 | #define SCENE_H 4 | 5 | 6 | 7 | #include 8 | #include 9 | 10 | #include "../tools/lights/light.h" 11 | 12 | #include "gameObject.h" 13 | 14 | #include "../components/cameraProjective.h" 15 | 16 | 17 | 18 | 19 | class Scene { 20 | 21 | public: 22 | Scene(); 23 | ~Scene(); 24 | 25 | void createUI(); 26 | CameraProjective* getCamera(); 27 | Light *getLight(); 28 | void createUIAtID(int indexItem, char *ID); 29 | void drawUIAtID(std::vector objs, int indexItem, char *ID); 30 | void getAllObjects(std::vector & names, std::vector & ids); 31 | 32 | void update(); 33 | void updateObj(GameObject *obj); 34 | void inputUpdate(); 35 | void inputUpdateObj(GameObject *obj); 36 | void physicsUpdate(); 37 | void physicsUpdateObj(GameObject *obj); 38 | 39 | 40 | void addGameObject(); 41 | void addGameObject(GameObject *obj); 42 | void addCube(); 43 | void deleteObject(int id); 44 | 45 | void loadDefaultScene(); 46 | void loadGameplayScene(); 47 | void loadExplorationScene(); 48 | void loadSampleScene(); 49 | 50 | void addToDestroy(int index){m_hasToBeDestroyed.push_back(index);} 51 | 52 | 53 | std::vector objectsEngine; 54 | int addNewId(); 55 | 56 | void togglePause(); 57 | 58 | 59 | void deleteScene(); 60 | bool getPause(){return m_pause;} 61 | 62 | void cleanDestroy(); 63 | 64 | // inline void setMainRenderer(MainRenderer *renderer){m_renderer = renderer;} 65 | 66 | private: 67 | 68 | CameraProjective* getCameraRecursive(GameObject *obj, glm::mat4 modelMat); 69 | Light *getLightRecursive(GameObject *obj); 70 | 71 | int m_idObject = 0; 72 | 73 | bool m_pause; 74 | std::vector m_hasToBeDestroyed; 75 | 76 | }; 77 | 78 | #endif 79 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | // dear imgui: standalone example application for GLFW + OpenGL 3, using programmable pipeline 2 | // If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. 3 | // (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | // About Desktop OpenGL function loaders: 12 | // Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers. 13 | // Helper libraries are often used for this purpose! Here we are supporting a few common ones (gl3w, glew, glad). 14 | // You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own. 15 | #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) 16 | #include // Initialize with gl3wInit() 17 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) 18 | #include // Initialize with glewInit() 19 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) 20 | #include // Initialize with gladLoadGL() 21 | #else 22 | #include IMGUI_IMPL_OPENGL_LOADER_CUSTOM 23 | #endif 24 | 25 | // Include glfw3.h after our OpenGL definitions 26 | #include 27 | 28 | #include "engineClass/scene.h" 29 | #include "engineClass/mainRenderer.h" 30 | #include "engineClass/UI.h" 31 | #include "engineClass/InputManager.h" 32 | // #include "engineClass/var_global.h" 33 | 34 | #include 35 | #include 36 | #include 37 | 38 | // [Win32] Our example includes a copy of glfw3.lib pre-compiled with VS2010 to maximize ease of testing and compatibility with old VS compilers. 39 | // To link with VS2010-era libraries, VS2015+ requires linking with legacy_stdio_definitions.lib, which we do using this pragma. 40 | // Your own project should not be affected, as you are likely to link with a newer binary of GLFW that is adequate for your version of Visual Studio. 41 | #if defined(_MSC_VER) && (_MSC_VER >= 1900) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) 42 | #pragma comment(lib, "legacy_stdio_definitions") 43 | #endif 44 | 45 | float global_limitFramerate; 46 | 47 | std::chrono::microseconds inputUpdateTime, updateTime, renderingTime, rendererUpdate, physicsUpdate; 48 | 49 | 50 | 51 | void display(int display_w, int display_h, MainRenderer *renderer, UI *ui){ 52 | ImGui_ImplOpenGL3_NewFrame(); 53 | ImGui_ImplGlfw_NewFrame(); 54 | ImGui::NewFrame(); 55 | 56 | // CREATE UI // 57 | ui->drawUI(); 58 | //ImGui::ShowDemoWindow(); 59 | if(ui->hasToDisplayed()){ 60 | ImGui::Begin("Execution time"); 61 | ImGui::Text("Application average %.3f ms/frame", 1000.0f / ImGui::GetIO().Framerate); 62 | ImGui::Text("(%.1f FPS)", ImGui::GetIO().Framerate); 63 | ImGui::Text("Input update : %u microseconds", inputUpdateTime); 64 | ImGui::Text("Physics update: %u microseconds", physicsUpdate); 65 | ImGui::Text("scene update : %u microseconds", updateTime); 66 | ImGui::Text("rendering : %u microseconds", renderingTime); 67 | ImGui::Text("renderer update : %u microseconds", rendererUpdate); 68 | ImGui::End(); 69 | } 70 | 71 | // Rendering 72 | ImGui::Render(); 73 | renderer->displaySceneOnTheScreen(display_w, display_h); 74 | // draw UI 75 | ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); 76 | } 77 | 78 | void rendering(int display_w, int display_h, MainRenderer *renderer, Scene *scene){ 79 | const ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); 80 | 81 | glViewport(0, 0, display_w, display_h); 82 | glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); 83 | glClear(GL_COLOR_BUFFER_BIT); 84 | renderer->paintGL(scene, display_w, display_h); 85 | } 86 | 87 | 88 | static void glfw_error_callback(int error, const char* description) 89 | { 90 | fprintf(stderr, "Glfw Error %d: %s\n", error, description); 91 | } 92 | 93 | 94 | int main(int, char**) 95 | { 96 | // Setup window 97 | glfwSetErrorCallback(glfw_error_callback); 98 | if (!glfwInit()) 99 | return 1; 100 | 101 | // Decide GL+GLSL versions 102 | #if __APPLE__ 103 | // GL 3.2 + GLSL 150 104 | const char* glsl_version = "#version 150"; 105 | glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); 106 | glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); 107 | glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // 3.2+ only 108 | glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Required on Mac 109 | #else 110 | // GL 3.0 + GLSL 130 111 | const char* glsl_version = "#version 130"; 112 | glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); 113 | glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); 114 | //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // 3.2+ only 115 | //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // 3.0+ only 116 | #endif 117 | 118 | // Create window with graphics context 119 | GLFWwindow* window = glfwCreateWindow(1920, 1080, "Voxel-Engine", NULL, NULL); 120 | if (window == NULL) 121 | return 1; 122 | glfwMakeContextCurrent(window); 123 | glfwSwapInterval(1); // Enable vsync 124 | 125 | // Initialize OpenGL loader 126 | #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) 127 | bool err = gl3wInit() != 0; 128 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) 129 | bool err = glewInit() != GLEW_OK; 130 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) 131 | bool err = gladLoadGL() == 0; 132 | #else 133 | bool err = false; // If you use IMGUI_IMPL_OPENGL_LOADER_CUSTOM, your loader is likely to requires some form of initialization. 134 | #endif 135 | if (err) 136 | { 137 | fprintf(stderr, "Failed to initialize OpenGL loader!\n"); 138 | return 1; 139 | } 140 | 141 | // Setup Dear ImGui context 142 | IMGUI_CHECKVERSION(); 143 | ImGui::CreateContext(); 144 | ImGuiIO& io = ImGui::GetIO(); (void)io; 145 | //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls 146 | //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls 147 | 148 | // Setup Dear ImGui style 149 | ImGui::StyleColorsDark(); 150 | 151 | // Setup Platform/Renderer bindings 152 | ImGui_ImplGlfw_InitForOpenGL(window, true); 153 | ImGui_ImplOpenGL3_Init(glsl_version); 154 | 155 | glfwSwapInterval(1); 156 | 157 | // glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); 158 | 159 | 160 | 161 | MainRenderer *renderer = new MainRenderer(); 162 | renderer->initializeGL(); 163 | 164 | Scene *scene = new Scene(); 165 | 166 | UI *ui = new UI(); 167 | InputManager inputManager; 168 | 169 | ui->set(scene); 170 | ui->set(renderer); 171 | ui->set(window); 172 | 173 | inputManager.setUI(ui); 174 | inputManager.setScene(scene); 175 | inputManager.setRenderer(renderer); 176 | 177 | 178 | 179 | int display_w, display_h; 180 | double lasttime = glfwGetTime(); 181 | global_limitFramerate = 60.f; 182 | 183 | // Main loop 184 | while (!glfwWindowShouldClose(window)){ 185 | 186 | 187 | glfwPollEvents(); 188 | glfwGetFramebufferSize(window, &display_w, &display_h); 189 | 190 | scene->cleanDestroy(); 191 | 192 | 193 | auto start = std::chrono::high_resolution_clock::now(); 194 | scene->inputUpdate(); 195 | auto stop = std::chrono::high_resolution_clock::now(); 196 | inputUpdateTime = std::chrono::duration_cast(stop - start); 197 | 198 | /// UPDATE 199 | inputManager.update(); 200 | 201 | start = std::chrono::high_resolution_clock::now(); 202 | scene->physicsUpdate(); 203 | stop = std::chrono::high_resolution_clock::now(); 204 | physicsUpdate = std::chrono::duration_cast(stop - start); 205 | 206 | start = std::chrono::high_resolution_clock::now(); 207 | scene->update(); 208 | stop = std::chrono::high_resolution_clock::now(); 209 | updateTime = std::chrono::duration_cast(stop - start); 210 | 211 | start = std::chrono::high_resolution_clock::now(); 212 | renderer->update(); 213 | stop = std::chrono::high_resolution_clock::now(); 214 | rendererUpdate = std::chrono::duration_cast(stop - start); 215 | 216 | // std::thread threadSceneUpdate(&Scene::update, scene); 217 | // std::thread threadRendererUpdate(&MainRenderer::update, renderer); 218 | // renderer->update(); 219 | 220 | //threadInput.join(); 221 | // threadSceneUpdate.join(); 222 | // threadRendererUpdate.join(); 223 | 224 | // RENDERING 225 | start = std::chrono::high_resolution_clock::now(); 226 | rendering(display_w, display_h, renderer, scene); 227 | stop = std::chrono::high_resolution_clock::now(); 228 | renderingTime = std::chrono::duration_cast(stop - start); 229 | 230 | // DISPLAY ON THE SCREEN 231 | display(display_w, display_h, renderer, ui); 232 | 233 | // wait for refresh rate 234 | while (glfwGetTime() < lasttime + 1.0/global_limitFramerate) { 235 | // sleep for x milliseconds 236 | std::this_thread::sleep_for(std::chrono::milliseconds(1)); 237 | } 238 | lasttime += 1.0/global_limitFramerate; 239 | 240 | glfwSwapBuffers(window); 241 | // glfwSetCursorPos(window, display_w/2,display_h/2); 242 | } 243 | 244 | delete(scene); 245 | delete(renderer); 246 | delete(ui); 247 | // delete(inputManager); 248 | 249 | // Cleanup 250 | ImGui_ImplOpenGL3_Shutdown(); 251 | ImGui_ImplGlfw_Shutdown(); 252 | ImGui::DestroyContext(); 253 | 254 | glfwDestroyWindow(window); 255 | glfwTerminate(); 256 | 257 | return 0; 258 | } 259 | -------------------------------------------------------------------------------- /src/material/lambertian.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | 8 | #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) 9 | #include // Initialize with gl3wInit() 10 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) 11 | #include // Initialize with glewInit() 12 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) 13 | #include // Initialize with gladLoadGL() 14 | #else 15 | #include IMGUI_IMPL_OPENGL_LOADER_CUSTOM 16 | #endif 17 | 18 | #include "lambertian.h" 19 | 20 | using namespace glm; 21 | 22 | Lambertian::Lambertian(glm::vec4 ambientColor, glm::vec4 specularColor, float specularDeg, glm::vec4 diffuseColor, bool activeDebugNormal) 23 | : m_activeDebugNormal(activeDebugNormal), m_specularDeg(specularDeg), m_ambientColor(ambientColor), m_diffuseColor(diffuseColor), m_specularColor(specularColor){ 24 | 25 | setName("Material"); 26 | 27 | createShader(); 28 | 29 | 30 | } 31 | 32 | Lambertian::~Lambertian(){ 33 | deleteShader(); 34 | } 35 | 36 | 37 | void Lambertian::callUniform(glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projMat, Light *light){ 38 | 39 | GLuint shaderID = getShaderID(); 40 | 41 | sendUniformMatrices(shaderID, modelMat, viewMat, projMat); 42 | 43 | 44 | 45 | // printf("y = %f\n", light[1]); 46 | 47 | if(!m_activeDebugNormal){ 48 | 49 | glm::vec4 lightVec; 50 | glm::vec3 vec = light->getLight(); 51 | lightVec.x = vec.x; 52 | lightVec.y = vec.y; 53 | lightVec.z = vec.z; 54 | lightVec.w = 1; 55 | 56 | glm::mat4 normalMatrix = viewMat * modelMat; 57 | normalMatrix = inverseTranspose(normalMatrix); 58 | 59 | glUniformMatrix4fv(glGetUniformLocation(shaderID,"normalMatrix"),1,GL_FALSE,&(normalMatrix[0][0])); 60 | 61 | glUniformMatrix4fv(glGetUniformLocation(shaderID,"lightMat4"),1,GL_FALSE,&(modelMat[0][0])); 62 | 63 | glUniform4fv(glGetUniformLocation(shaderID,"light"), 1, &(lightVec[0])); 64 | 65 | int boolUseDiffuse = m_displayDiffuse ? 1 : 0; 66 | glUniform1i(glGetUniformLocation(shaderID,"boolUseDiffuse"), boolUseDiffuse); 67 | glUniform4fv(glGetUniformLocation(shaderID,"ambientColor"),1,&(m_ambientColor[0])); 68 | glUniform4fv(glGetUniformLocation(shaderID,"diffuseColor"),1,&(m_diffuseColor[0])); 69 | glUniform4fv(glGetUniformLocation(shaderID,"specularColor"),1,&(m_specularColor[0])); 70 | 71 | glUniform1f(glGetUniformLocation(shaderID,"m_specularDegree"), m_specularDeg); 72 | 73 | } 74 | } 75 | 76 | 77 | void Lambertian::createUI(){ 78 | 79 | if (ImGui::Button("Refresh")){ 80 | reloadShaders(); 81 | } 82 | 83 | ImGui::Text("Display by diffuse color "); ImGui::SameLine(); 84 | ImGui::Checkbox("##diffuseBool",&m_displayDiffuse); 85 | if(m_displayDiffuse){ 86 | ImGui::Text("Diffuse Color: "); ImGui::SameLine(); 87 | ImGui::ColorEdit4("##diffuse-color", (float *)&m_diffuseColor); 88 | } 89 | ImGui::Text("Ambient Color: "); ImGui::SameLine(); 90 | ImGui::ColorEdit4("##ambient-color", (float *)&m_ambientColor); 91 | ImGui::Text("Specular Color: "); ImGui::SameLine(); 92 | ImGui::ColorEdit4("##spec-color", (float *)&m_specularColor); 93 | 94 | ImGui::Text("Specular degree"); ImGui::SameLine(); 95 | ImGui::DragFloat("##specdeg", &m_specularDeg, 0.01f, 0.001f, 10000, "%.3f"); 96 | 97 | ImGui::Text("debug Normal "); ImGui::SameLine(); 98 | ImGui::Checkbox("##debugNormal",&m_activeDebugNormal); 99 | 100 | 101 | } 102 | 103 | GLuint Lambertian::getShaderID(){ 104 | GLuint shaderID; 105 | if(m_activeDebugNormal){ 106 | shaderID = m_debugNormalShader->id(); 107 | } else { 108 | shaderID = m_shader->id(); 109 | } 110 | return shaderID; 111 | } 112 | 113 | 114 | void Lambertian::createShader(){ 115 | m_shader = new Shader(); 116 | m_shader->load(m_lambertianShaderVert,m_lambertianShaderFrag); 117 | m_debugNormalShader = new Shader(); 118 | m_debugNormalShader->load(m_debugShaderVert,m_debugShaderFrag); 119 | } 120 | void Lambertian::reloadShaders(){ 121 | m_shader->reload(m_lambertianShaderVert,m_lambertianShaderFrag); 122 | m_debugNormalShader->reload(m_debugShaderVert, m_debugShaderFrag); 123 | } 124 | 125 | void Lambertian::deleteShader(){ 126 | delete m_shader; m_shader = NULL; 127 | delete m_debugNormalShader; m_debugNormalShader = NULL; 128 | } 129 | -------------------------------------------------------------------------------- /src/material/lambertian.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef LAMBERTIAN_H 3 | #define LAMBERTIAN_H 4 | 5 | 6 | 7 | #ifndef GLM_H 8 | #define GLM_H 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #endif 15 | 16 | 17 | 18 | #include "material.h" 19 | 20 | class Lambertian : public Material { 21 | 22 | public: 23 | Lambertian(glm::vec4 ambientColor = glm::vec4(0.1,0.1,0.1,0.0), glm::vec4 specularColor = glm::vec4(64./255.,64./255.,64./255.,1.0), float specularDeg = 10, glm::vec4 diffuseColor = glm::vec4(255./255.,0./255.,0./255.,1.0), bool activeDebugNormal = false); 24 | ~Lambertian(); 25 | 26 | virtual void callUniform(glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projMat, Light *light); 27 | virtual void createUI(); 28 | virtual GLuint getShaderID(); 29 | virtual void reloadShaders(); 30 | 31 | void toggleDisplayDiffuse(){m_displayDiffuse = !m_displayDiffuse; } 32 | 33 | protected: 34 | 35 | void createShader(); 36 | void deleteShader(); 37 | 38 | Shader *m_debugNormalShader; 39 | 40 | bool m_activeDebugNormal; 41 | 42 | float m_specularDeg; 43 | glm::vec4 m_ambientColor, m_specularColor, m_diffuseColor; 44 | 45 | bool m_displayDiffuse = false; 46 | 47 | const char * m_lambertianShaderVert = "../data/shaders/lambertian.vert"; 48 | const char * m_lambertianShaderFrag = "../data/shaders/lambertian.frag"; 49 | const char * m_debugShaderVert = "../data/shaders/debugNormal.vert"; 50 | const char * m_debugShaderFrag = "../data/shaders/debugNormal.frag"; 51 | 52 | }; 53 | 54 | #endif 55 | -------------------------------------------------------------------------------- /src/material/material.cpp: -------------------------------------------------------------------------------- 1 | #include "material.h" 2 | 3 | 4 | 5 | 6 | 7 | void Material::sendUniformMatrices(GLuint shaderID, glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projMat){ 8 | glUniformMatrix4fv(glGetUniformLocation(shaderID,"modelMat"),1,GL_FALSE,&(modelMat[0][0])); 9 | glUniformMatrix4fv(glGetUniformLocation(shaderID,"viewMat"),1,GL_FALSE,&(viewMat[0][0])); 10 | glUniformMatrix4fv(glGetUniformLocation(shaderID,"projMat"),1,GL_FALSE,&(projMat[0][0])); 11 | } 12 | -------------------------------------------------------------------------------- /src/material/material.h: -------------------------------------------------------------------------------- 1 | #ifndef MATERIAL_H 2 | #define MATERIAL_H 3 | 4 | #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) 5 | #include // Initialize with gl3wInit() 6 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) 7 | #include // Initialize with glewInit() 8 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) 9 | #include // Initialize with gladLoadGL() 10 | #else 11 | #include IMGUI_IMPL_OPENGL_LOADER_CUSTOM 12 | #endif 13 | 14 | #ifndef GLM_H 15 | #define GLM_H 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #endif 22 | 23 | 24 | #include "shader.h" 25 | #include "../tools/lights/light.h" 26 | 27 | #include "../components/component.h" 28 | 29 | class Material : public Component { 30 | 31 | public: 32 | virtual ~Material() = default; 33 | 34 | virtual void callUniform(glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projMat, Light *light) = 0; 35 | virtual void createUI() = 0; 36 | virtual GLuint getShaderID() = 0; 37 | virtual void reloadShaders() = 0; 38 | protected: 39 | Shader *m_shader; 40 | 41 | void sendUniformMatrices(GLuint shaderID, glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projMat); 42 | 43 | }; 44 | 45 | #endif 46 | -------------------------------------------------------------------------------- /src/material/shader.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | 7 | #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) 8 | #include // Initialize with gl3wInit() 9 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) 10 | #include // Initialize with glewInit() 11 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) 12 | #include // Initialize with gladLoadGL() 13 | #else 14 | #include IMGUI_IMPL_OPENGL_LOADER_CUSTOM 15 | #endif 16 | 17 | 18 | #include "shader.h" 19 | 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | 29 | using namespace std; 30 | 31 | Shader::Shader() : m_programId(0) { 32 | 33 | } 34 | 35 | Shader::~Shader() { 36 | if(glIsProgram(m_programId)) { 37 | glDeleteProgram(m_programId); 38 | } 39 | } 40 | 41 | void Shader::load(const char *vertex_file_path, const char *fragment_file_path) { 42 | 43 | // create and compile vertex shader object 44 | std::string vertexCode = getCode(vertex_file_path); 45 | const char * vertexCodeC = vertexCode.c_str(); 46 | GLuint vertexId = glCreateShader(GL_VERTEX_SHADER); 47 | glShaderSource(vertexId,1,&(vertexCodeC),NULL); 48 | glCompileShader(vertexId); 49 | checkCompilation(vertexId); 50 | 51 | // create and compile fragment shader object 52 | std::string fragmentCode = getCode(fragment_file_path); 53 | const char * fragmentCodeC = fragmentCode.c_str(); 54 | GLuint fragmentId = glCreateShader(GL_FRAGMENT_SHADER); 55 | glShaderSource(fragmentId,1,&(fragmentCodeC),NULL); 56 | glCompileShader(fragmentId); 57 | checkCompilation(fragmentId); 58 | 59 | // create, attach and link program object 60 | m_programId = glCreateProgram(); 61 | glAttachShader(m_programId,vertexId); 62 | glAttachShader(m_programId,fragmentId); 63 | glLinkProgram(m_programId); 64 | checkLinks(m_programId); 65 | 66 | // delete vertex and fragment ids 67 | glDeleteShader(vertexId); 68 | glDeleteShader(fragmentId); 69 | } 70 | 71 | 72 | void Shader::reload(const char *vertex_file_path, const char *fragment_file_path) { 73 | 74 | // check if the program already contains a shader 75 | if(glIsProgram(m_programId)) { 76 | // delete it... 77 | glDeleteProgram(m_programId); 78 | } 79 | 80 | // ... and reload it 81 | load(vertex_file_path,fragment_file_path); 82 | } 83 | 84 | 85 | 86 | 87 | void Shader::checkCompilation(GLuint shaderId) { 88 | // check if the compilation was successfull (and display syntax errors) 89 | // call it after each shader compilation 90 | GLint result = GL_FALSE; 91 | int infoLogLength; 92 | 93 | glGetShaderiv(shaderId,GL_COMPILE_STATUS,&result); 94 | glGetShaderiv(shaderId,GL_INFO_LOG_LENGTH,&infoLogLength); 95 | 96 | if(infoLogLength>0) { 97 | std::vector message(infoLogLength+1); 98 | glGetShaderInfoLog(shaderId,infoLogLength,NULL,&message[0]); 99 | printf("%s\n", &message[0]); 100 | } 101 | } 102 | 103 | void Shader::checkLinks(GLuint programId) { 104 | // check if links were successfull (and display errors) 105 | // call it after linking the program 106 | GLint result = GL_FALSE; 107 | int infoLogLength; 108 | 109 | glGetProgramiv(programId,GL_LINK_STATUS,&result); 110 | glGetProgramiv(programId,GL_INFO_LOG_LENGTH,&infoLogLength); 111 | 112 | if(infoLogLength>0) { 113 | std::vector message(infoLogLength+1); 114 | glGetProgramInfoLog(programId,infoLogLength,NULL,&message[0]); 115 | printf("%s\n", &message[0]); 116 | } 117 | } 118 | 119 | std::string Shader::getCode(const char *file_path) { 120 | // return a string containing the source code of the input file 121 | std::string shaderCode; 122 | std::ifstream shaderStream(file_path,std::ios::in); 123 | 124 | if(!shaderStream.is_open()) { 125 | cout << "Unable to open " << file_path << endl; 126 | return ""; 127 | } 128 | 129 | std::string line = ""; 130 | while(getline(shaderStream,line)) 131 | shaderCode += "\n" + line; 132 | shaderStream.close(); 133 | 134 | return shaderCode; 135 | } 136 | -------------------------------------------------------------------------------- /src/material/shader.h: -------------------------------------------------------------------------------- 1 | #ifndef SHADER_H 2 | #define SHADER_H 3 | 4 | #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) 5 | #include // Initialize with gl3wInit() 6 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) 7 | #include // Initialize with glewInit() 8 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) 9 | #include // Initialize with gladLoadGL() 10 | #else 11 | #include IMGUI_IMPL_OPENGL_LOADER_CUSTOM 12 | #endif 13 | 14 | #include 15 | 16 | class Shader { 17 | public: 18 | 19 | Shader(); 20 | ~Shader(); 21 | 22 | void load(const char *vertex_file_path, const char *fragment_file_path); 23 | 24 | void reload(const char *vertex_file_path, const char *fragment_file_path); 25 | 26 | inline GLuint id() {return m_programId;} 27 | 28 | private: 29 | 30 | GLuint m_programId; 31 | 32 | // string containing the source code of the input file 33 | std::string getCode(const char *file_path); 34 | 35 | // call it after each shader compilation 36 | void checkCompilation(GLuint shaderId); 37 | 38 | // call it after linking the program 39 | void checkLinks(GLuint programId); 40 | }; 41 | 42 | #endif // SHADER_H 43 | -------------------------------------------------------------------------------- /src/material/simpleMat.cpp: -------------------------------------------------------------------------------- 1 | #include "simpleMat.h" 2 | 3 | 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | 10 | #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) 11 | #include // Initialize with gl3wInit() 12 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) 13 | #include // Initialize with glewInit() 14 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) 15 | #include // Initialize with gladLoadGL() 16 | #else 17 | #include IMGUI_IMPL_OPENGL_LOADER_CUSTOM 18 | #endif 19 | 20 | using namespace glm; 21 | 22 | SimpleMat::SimpleMat(glm::vec4 color) : m_color(color){ 23 | 24 | 25 | createShader(); 26 | 27 | 28 | } 29 | SimpleMat::~SimpleMat(){ 30 | deleteShader(); 31 | } 32 | 33 | 34 | void SimpleMat::callUniform(glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projMat, Light *light){ 35 | 36 | 37 | GLuint shaderID = m_shader->id(); 38 | 39 | sendUniformMatrices(shaderID, modelMat, viewMat, projMat); 40 | 41 | glUniform4fv(glGetUniformLocation(shaderID,"color"),1,&(m_color[0])); 42 | 43 | } 44 | 45 | 46 | void SimpleMat::createUI(){ 47 | // to hide label of the input 48 | 49 | if (ImGui::Button("Refresh")){ 50 | reloadShaders(); 51 | } 52 | ImGui::Text("Color: "); ImGui::SameLine(); 53 | ImGui::ColorEdit4("##color", (float *)&m_color); 54 | } 55 | 56 | 57 | GLuint SimpleMat::getShaderID(){ 58 | return m_shader->id(); 59 | } 60 | 61 | 62 | void SimpleMat::createShader(){ 63 | m_shader = new Shader(); 64 | m_shader->load(m_simpleShaderVert,m_simpleShaderFrag); 65 | } 66 | void SimpleMat::reloadShaders(){ 67 | m_shader->reload(m_simpleShaderVert,m_simpleShaderFrag); 68 | } 69 | 70 | void SimpleMat::deleteShader(){ 71 | delete m_shader; m_shader = NULL; 72 | } 73 | -------------------------------------------------------------------------------- /src/material/simpleMat.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef SIMPLEMAT_H 3 | #define SIMPLEMAT_H 4 | 5 | 6 | 7 | #ifndef GLM_H 8 | #define GLM_H 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #endif 15 | 16 | 17 | 18 | #include "material.h" 19 | 20 | class SimpleMat : public Material { 21 | 22 | public: 23 | SimpleMat(glm::vec4 color = glm::vec4(255./255.,255./255.,0./255.,1.0)); 24 | ~SimpleMat(); 25 | 26 | virtual void callUniform(glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projMat, Light *light); 27 | virtual void createUI(); 28 | virtual GLuint getShaderID(); 29 | virtual void reloadShaders(); 30 | 31 | protected: 32 | 33 | void createShader(); 34 | void deleteShader(); 35 | 36 | 37 | glm::vec4 m_color; 38 | 39 | const char * m_simpleShaderVert = "../data/shaders/simple.vert"; 40 | const char * m_simpleShaderFrag = "../data/shaders/simple.frag"; 41 | 42 | }; 43 | 44 | #endif 45 | -------------------------------------------------------------------------------- /src/material/textureMaterial.cpp: -------------------------------------------------------------------------------- 1 | #include "textureMaterial.h" 2 | 3 | #include 4 | #include 5 | 6 | #include 7 | 8 | #include 9 | 10 | #define STB_IMAGE_IMPLEMENTATION 11 | #include 12 | 13 | 14 | TextureMaterial::TextureMaterial(char file[2048]) : m_imageBuffer(nullptr), m_imageWidth(-1), m_imageHeight(-1){ 15 | 16 | createShader(); 17 | 18 | initTexture(); 19 | createTexture(file); 20 | 21 | 22 | } 23 | 24 | TextureMaterial::~TextureMaterial(){ 25 | deleteShader(); 26 | stbi_image_free(m_imageBuffer); 27 | glDeleteTextures(1,&m_textureFBO); 28 | } 29 | 30 | void TextureMaterial::initTexture(){ 31 | glGenTextures(1,&m_textureFBO); 32 | 33 | glBindTexture(GL_TEXTURE_2D,m_textureFBO); 34 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); 35 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); 36 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 37 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 38 | } 39 | 40 | void TextureMaterial::createTexture(char file[2048]){ 41 | 42 | sprintf(m_filename, "%s", file); 43 | FILE *f = fopen(m_filename, "r"); 44 | if(f){ 45 | createImageBuffer(f); 46 | m_errorMessage =""; 47 | fclose(f); 48 | } else { 49 | if(m_imageWidth < 0){ // we fill with a default texture 50 | f = fopen(m_defaultTexture, "r"); 51 | createImageBuffer(f); 52 | fclose(f); 53 | } 54 | m_errorMessage = "Couldn't find the texture file"; 55 | } 56 | 57 | } 58 | 59 | 60 | 61 | void TextureMaterial::deleteShader(){ 62 | delete m_shader; 63 | } 64 | 65 | 66 | void TextureMaterial::createImageBuffer(FILE *file){ 67 | 68 | // stbi_set_flip_vertically_on_load(true); 69 | 70 | m_imageBuffer = stbi_load_from_file(file, &m_imageWidth, &m_imageHeight, &m_channels, STBI_rgb_alpha); 71 | 72 | if(m_imageBuffer == nullptr){ 73 | m_errorMessage = "Couldn't load the texture from the file"; 74 | createTexture((char*)m_defaultTexture); 75 | } 76 | 77 | glBindTexture(GL_TEXTURE_2D, m_textureFBO); 78 | 79 | // fill texture 80 | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_imageWidth, m_imageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_imageBuffer); 81 | 82 | // generate mipmaps 83 | glGenerateMipmap(GL_TEXTURE_2D); 84 | 85 | glBindTexture(GL_TEXTURE_2D, 0); 86 | } 87 | 88 | void TextureMaterial::createUI(){ 89 | // to hide label of the input 90 | 91 | if (ImGui::Button("Refresh")){ 92 | reloadShaders(); 93 | createTexture(m_filename); 94 | } 95 | 96 | ImGui::Text("Texture: "); ImGui::SameLine(); 97 | ImGui::TextColored(ImVec4(1.0f,0.0f,0.0f,1.0f), m_errorMessage.c_str()); 98 | ImGui::InputText("##fileTexture", m_filename, IM_ARRAYSIZE(m_filename)); 99 | } 100 | 101 | void TextureMaterial::callUniform(glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projMat, Light *light){ 102 | 103 | GLuint shaderID = m_shader->id(); 104 | 105 | sendUniformMatrices(shaderID, modelMat, viewMat, projMat); 106 | 107 | 108 | glActiveTexture(GL_TEXTURE0); 109 | glBindTexture(GL_TEXTURE_2D, m_textureFBO); 110 | glUniform1i(glGetUniformLocation(shaderID,"tex"),0); 111 | 112 | 113 | } 114 | 115 | GLuint TextureMaterial::getShaderID(){ 116 | return m_shader->id(); 117 | } 118 | 119 | void TextureMaterial::createShader(){ 120 | m_shader = new Shader(); 121 | m_shader->load(m_textureShaderVert,m_textureShaderFrag); 122 | } 123 | void TextureMaterial::reloadShaders(){ 124 | m_shader->reload(m_textureShaderVert,m_textureShaderFrag); 125 | } 126 | -------------------------------------------------------------------------------- /src/material/textureMaterial.h: -------------------------------------------------------------------------------- 1 | #ifndef TEXTUREMATERIAL_H 2 | #define TEXTUREMATERIAL_H 3 | 4 | #ifndef GLM_H 5 | #define GLM_H 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #endif 12 | 13 | #include 14 | 15 | 16 | #include "material.h" 17 | 18 | class TextureMaterial : public Material { 19 | 20 | public: 21 | TextureMaterial(char file[2048]); 22 | ~TextureMaterial(); 23 | 24 | virtual void callUniform(glm::mat4 modelMat, glm::mat4 viewMat, glm::mat4 projMat, Light *light); 25 | virtual void createUI(); 26 | virtual GLuint getShaderID(); 27 | virtual void reloadShaders(); 28 | 29 | private: 30 | char m_filename[2048]; 31 | 32 | unsigned char *m_imageBuffer; 33 | 34 | void createShader(); 35 | void deleteShader(); 36 | void createTexture(char file[2048]); 37 | 38 | void createImageBuffer(FILE *file); 39 | void initTexture(); 40 | 41 | const char m_defaultTexture[2048] = "../data/textures/pattern.jpg"; 42 | 43 | const char * m_textureShaderVert = "../data/shaders/texture.vert"; 44 | const char * m_textureShaderFrag = "../data/shaders/texture.frag"; 45 | 46 | int m_imageWidth,m_imageHeight, m_channels; 47 | 48 | std::string m_errorMessage; 49 | 50 | 51 | 52 | GLuint m_textureFBO; 53 | 54 | }; 55 | 56 | 57 | #endif 58 | -------------------------------------------------------------------------------- /src/models/mesh/mesh.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | 5 | 6 | 7 | #define POSITION_ATTRIB 0 8 | #define VERTEX_NORMAL_ATTRIB 1 9 | #define VERTEX_UV_ATTRIB 2 10 | #define VERTEX_COLOR_ATTRIB 3 11 | 12 | #include "mesh.h" 13 | 14 | #include "../../material/shader.h" 15 | 16 | #include 17 | 18 | #include 19 | #include 20 | 21 | #ifndef M_PI 22 | #define M_PI 3.1415926 23 | #endif 24 | 25 | Mesh::Mesh() { 26 | setName("Mesh"); 27 | } 28 | 29 | Mesh::~Mesh() 30 | { 31 | deleteVAO(); 32 | } 33 | 34 | void Mesh::createUI(){ 35 | if (ImGui::TreeNode("Mesh")){ 36 | ImGui::Text("Number vertices: %d", getNBVertices()); 37 | ImGui::Text("Number faces: %d", getNBFaces()); 38 | 39 | ImGui::Separator(); 40 | if (ImGui::TreeNode("Vertices")){ 41 | 42 | ImGui::Columns(3, "Vertices"); // 4-ways, with border 43 | ImGui::Separator(); 44 | ImGui::Text("X"); ImGui::NextColumn(); 45 | ImGui::Text("Y"); ImGui::NextColumn(); 46 | ImGui::Text("Z"); ImGui::NextColumn(); 47 | ImGui::Separator(); 48 | for(unsigned int i=0; i 0); 75 | 76 | m_maxX = m_vertices[0].x; m_maxY = m_vertices[0].y; m_maxZ = m_vertices[0].z; 77 | m_minX = m_vertices[0].x; m_minY = m_vertices[0].y; m_minZ = m_vertices[0].z; 78 | 79 | for(unsigned int i=0; i m_maxX){ 81 | m_maxX = m_vertices[i].x; 82 | } else if(m_vertices[i].x < m_minX){ 83 | m_minX = m_vertices[i].x; 84 | } 85 | if(m_vertices[i].y > m_maxY){ 86 | m_maxY = m_vertices[i].y; 87 | } else if(m_vertices[i].y < m_minY){ 88 | m_minY = m_vertices[i].y; 89 | } 90 | if(m_vertices[i].z > m_maxZ){ 91 | m_maxZ = m_vertices[i].z; 92 | } else if(m_vertices[i].z < m_minZ){ 93 | m_minZ = m_vertices[i].z; 94 | } 95 | } 96 | } 97 | 98 | void Mesh::recreate(){ 99 | createVAO(); 100 | } 101 | 102 | void Mesh::inflateBoundingBox(){ 103 | const float percent = 0.1f; 104 | m_maxX += percent*m_radius; m_maxY += percent*m_radius; m_maxZ += percent*m_radius; 105 | m_minX -= percent*m_radius; m_minY -= percent*m_radius; m_minZ -= percent*m_radius; 106 | } 107 | 108 | 109 | glm::vec3 Mesh::getMin(){ 110 | return glm::vec3(m_minX, m_minY, m_minZ); 111 | } 112 | 113 | 114 | glm::vec3 Mesh::getMax(){ 115 | return glm::vec3(m_maxX, m_maxY, m_maxZ); 116 | } 117 | 118 | 119 | void Mesh::createVAO(){ 120 | 121 | glGenBuffers(m_buffers.size(), m_buffers.data()); 122 | glGenVertexArrays(1,&m_vertexArrayID); 123 | 124 | // create the VBO associated with the grid (the terrain) 125 | glBindVertexArray(m_vertexArrayID); 126 | 127 | glBindBuffer(GL_ARRAY_BUFFER,m_buffers[0]); // vertices 128 | glBufferData(GL_ARRAY_BUFFER,getNBVertices()*3*sizeof(float),getVertices(),GL_STATIC_DRAW); 129 | glEnableVertexAttribArray(POSITION_ATTRIB); 130 | glVertexAttribPointer(POSITION_ATTRIB,3,GL_FLOAT,GL_FALSE,0,(void *)0); 131 | 132 | 133 | // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,m_buffers[1]); // indices 134 | // glBufferData(GL_ELEMENT_ARRAY_BUFFER,mesh->getNBFaces()*3*sizeof(unsigned int),mesh->getFaces(),GL_STATIC_DRAW); 135 | 136 | // m_normals 137 | glEnableVertexAttribArray(VERTEX_NORMAL_ATTRIB); 138 | glBindBuffer(GL_ARRAY_BUFFER, m_buffers[1]); 139 | glBufferData(GL_ARRAY_BUFFER, getNBVertices()*3* sizeof(float), getNormals(), GL_STATIC_DRAW); //m_normals is std::vector 140 | glVertexAttribPointer(VERTEX_NORMAL_ATTRIB, 3, GL_FLOAT, GL_FALSE, 0, 0); 141 | 142 | // texture coordinates 143 | glEnableVertexAttribArray(VERTEX_UV_ATTRIB); 144 | glBindBuffer(GL_ARRAY_BUFFER, m_buffers[2]); 145 | glBufferData(GL_ARRAY_BUFFER, getNBVertices()*2* sizeof(float), getUVs(), GL_STATIC_DRAW); //m_normals is std::vector 146 | glVertexAttribPointer(VERTEX_UV_ATTRIB, 2, GL_FLOAT, GL_FALSE, 0, 0); 147 | 148 | // m_colors 149 | glEnableVertexAttribArray(VERTEX_COLOR_ATTRIB); 150 | glBindBuffer(GL_ARRAY_BUFFER, m_buffers[3]); 151 | glBufferData(GL_ARRAY_BUFFER, getNBVertices()*3* sizeof(float), getColors(), GL_STATIC_DRAW); //m_normals is std::vector 152 | glVertexAttribPointer(VERTEX_COLOR_ATTRIB, 3, GL_FLOAT, GL_FALSE, 0, 0); 153 | 154 | 155 | glBindVertexArray(0); 156 | } 157 | 158 | 159 | void Mesh::drawVAO(){ 160 | 161 | glBindVertexArray(m_vertexArrayID); 162 | glDrawArrays(GL_TRIANGLES,0,getNBVertices()); 163 | glBindVertexArray(0); 164 | 165 | } 166 | 167 | void Mesh::deleteVAO(){ 168 | if (m_vertexArrayID != 0){ 169 | glDeleteBuffers(m_buffers.size(), m_buffers.data()); 170 | glDeleteVertexArrays(1,&m_vertexArrayID); 171 | } 172 | } 173 | 174 | 175 | // -- Add Method -- 176 | 177 | void Mesh::addTriangle(const glm::vec3& v1, const glm::vec3& v2, const glm::vec3& v3, 178 | const glm::vec3& normal, const glm::vec3& color) { 179 | 180 | m_vertices.push_back(v1); 181 | m_vertices.push_back(v2); 182 | m_vertices.push_back(v3); 183 | 184 | m_normals.push_back(normal); 185 | m_normals.push_back(normal); 186 | m_normals.push_back(normal); 187 | 188 | m_colors.push_back(color); 189 | m_colors.push_back(color); 190 | m_colors.push_back(color); 191 | 192 | // Coord bidon pour ne pas faire bugger l'affichage 193 | 194 | m_coords.push_back(glm::vec3(0, 0, 0)); 195 | m_coords.push_back(glm::vec3(0, 0, 0)); 196 | m_coords.push_back(glm::vec3(0, 0, 0)); 197 | } 198 | 199 | void Mesh::addQuad (const glm::vec3& v1, const glm::vec3& v2, const glm::vec3& v3, const glm::vec3& v4, 200 | const glm::vec3& normal, const glm::vec3& color) { 201 | 202 | this->addTriangle(v1, v2, v3, normal, color); 203 | this->addTriangle(v2, v4, v3, normal, color); 204 | } 205 | 206 | void Mesh::clear() { 207 | 208 | m_vertices.clear(); 209 | m_normals.clear(); 210 | m_colors.clear(); 211 | 212 | m_coords.clear(); 213 | 214 | m_tangents.clear(); 215 | m_backupVertices.clear(); 216 | } 217 | -------------------------------------------------------------------------------- /src/models/mesh/mesh.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef MESH_H 3 | #define MESH_H 4 | 5 | #include 6 | #include 7 | #include 8 | #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) 9 | #include // Initialize with gl3wInit() 10 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) 11 | #include // Initialize with glewInit() 12 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) 13 | #include // Initialize with gladLoadGL() 14 | #else 15 | #include IMGUI_IMPL_OPENGL_LOADER_CUSTOM 16 | #endif 17 | 18 | #ifndef GLM_H 19 | #define GLM_H 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #endif 26 | 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | #include "../../components/component.h" 34 | 35 | 36 | class Mesh : public Component { 37 | 38 | public: 39 | 40 | Mesh(); 41 | virtual ~Mesh(); 42 | 43 | virtual void createUI(); 44 | virtual void recreate(); 45 | 46 | glm::vec3 getMin(); 47 | glm::vec3 getMax(); 48 | 49 | void createVAO(); 50 | 51 | void drawVAO(); 52 | 53 | void deleteVAO(); 54 | 55 | inline void *getVertices(){ return &(m_vertices[0]);} 56 | inline void *getNormals(){ return &(m_normals[0]);} 57 | inline void *getUVs(){ return &(m_coords[0]);} 58 | inline void *getColors(){ return &(m_colors[0]);} 59 | 60 | inline unsigned int getNBVertices(){ return m_vertices.size();} 61 | 62 | inline unsigned int getNBFaces(){ return getNBVertices()/3; } 63 | 64 | inline glm::vec3 get_vertex(unsigned int i) { return m_vertices[i];} 65 | inline glm::vec3 get_normal(unsigned int i) { return m_normals[i];} 66 | inline glm::vec3 get_color(unsigned int i) { return m_colors[i];} 67 | inline glm::vec2 get_coord(unsigned int i) { return m_coords[i];} 68 | 69 | inline glm::vec3 get_tangent(unsigned int i) { return m_tangents[i];} 70 | 71 | // -- Modificators -- 72 | 73 | void addTriangle(const glm::vec3& v1, const glm::vec3& v2, const glm::vec3& v3, 74 | const glm::vec3& normal, const glm::vec3& color); 75 | 76 | void addQuad (const glm::vec3& v1, const glm::vec3& v2, const glm::vec3& v3, const glm::vec3& v4, 77 | const glm::vec3& normal, const glm::vec3& color); 78 | 79 | void clear(); 80 | 81 | protected: 82 | 83 | float m_maxX, m_maxY, m_maxZ; 84 | float m_minX, m_minY, m_minZ; 85 | 86 | // data 87 | std::vector m_vertices; 88 | std::vector m_normals; 89 | std::vector m_colors; 90 | 91 | std::vector m_coords; // ne sert pas pour l'instant 92 | 93 | std::vector m_tangents; 94 | std::vector m_backupVertices; 95 | 96 | 97 | float m_radius; 98 | 99 | 100 | 101 | void computeBoundingBox(); 102 | void inflateBoundingBox(); 103 | 104 | GLuint m_vertexArrayID = 0; 105 | std::array m_buffers; 106 | 107 | 108 | }; 109 | 110 | 111 | 112 | #endif 113 | -------------------------------------------------------------------------------- /src/models/mesh/meshCube.cpp: -------------------------------------------------------------------------------- 1 | #include "meshCube.h" 2 | 3 | #include 4 | 5 | MeshCube::MeshCube(float w, bool center) : m_width(w), m_centered(center){ 6 | 7 | setName("Mesh Cube"); 8 | 9 | createMesh(m_width); 10 | createVAO(); 11 | } 12 | 13 | // MeshCube::~MeshCube() { 14 | // deleteVAO(); 15 | // } 16 | 17 | void MeshCube::recreate(){ 18 | createMesh(m_width); 19 | Mesh::recreate(); 20 | } 21 | 22 | void MeshCube::createUI(){ 23 | 24 | ImGui::Text("Number vertices: %d", getNBVertices()); 25 | ImGui::Text("Number faces: %d", getNBFaces()); 26 | 27 | ImGui::Text("Width : "); 28 | ImGui::DragFloat("##width", &m_width, 0.01f); 29 | 30 | ImGui::Text("Centered : "); ImGui::SameLine(); 31 | ImGui::Checkbox("##centered", &m_centered); 32 | 33 | ImGui::Text("min: %f, %f, %f", m_minX, m_minY, m_minZ); 34 | ImGui::Text("max: %f, %f, %f", m_maxX, m_maxY, m_maxZ); 35 | 36 | if(ImGui::Button("Recreate")){ 37 | recreate(); 38 | } 39 | } 40 | 41 | 42 | void MeshCube::createMesh(float w){ 43 | 44 | 45 | createPositions(w); 46 | createNormals(); 47 | createm_tangents(); 48 | createUVs(); 49 | createColors(); 50 | 51 | // createInfo(); 52 | 53 | computeBoundingBox(); 54 | inflateBoundingBox(); 55 | 56 | m_backupVertices = m_vertices; 57 | 58 | } 59 | 60 | ////// FACES 61 | /// 1 FRONT 62 | /// 2 BACK 63 | /// 3 LEFT 64 | /// 4 RIGHT 65 | /// 5 TOP 66 | /// 6 BOTTOM 67 | 68 | void MeshCube::createPositions(float w){ 69 | 70 | float min = 0; 71 | float max = w; 72 | 73 | if(m_centered){ 74 | min = -w/2.0f; 75 | max = w/2.0f; 76 | } 77 | 78 | const unsigned int nb_vertices = 36; 79 | 80 | m_vertices.resize(nb_vertices); 81 | 82 | // FRONT 83 | m_vertices[0] = glm::vec3(min, max, max); 84 | m_vertices[1] = glm::vec3(min,min, max); 85 | m_vertices[2] = glm::vec3(max,min, max); 86 | 87 | m_vertices[3] = glm::vec3(max, max, max); 88 | m_vertices[4] = glm::vec3(min, max, max); 89 | m_vertices[5] = glm::vec3(max,min, max); 90 | 91 | // BACK 92 | m_vertices[6] = glm::vec3(max, max,min); 93 | m_vertices[7] = glm::vec3(min,min,min); 94 | m_vertices[8] = glm::vec3(min, max,min); 95 | 96 | m_vertices[9] = glm::vec3(max, max,min); 97 | m_vertices[10] = glm::vec3(max,min,min); 98 | m_vertices[11] = glm::vec3(min,min,min); 99 | 100 | // LEFT 101 | m_vertices[12] = glm::vec3(min,min,min); 102 | m_vertices[13] = glm::vec3(min, max, max); 103 | m_vertices[14] = glm::vec3(min, max,min); 104 | 105 | m_vertices[15] = glm::vec3(min,min,min); 106 | m_vertices[16] = glm::vec3(min,min, max); 107 | m_vertices[17] = glm::vec3(min, max, max); 108 | 109 | // RIGHT 110 | m_vertices[18] = glm::vec3(max, max, max); 111 | m_vertices[19] = glm::vec3(max,min,min); 112 | m_vertices[20] = glm::vec3(max, max,min); 113 | 114 | m_vertices[21] = glm::vec3(max,min,min); 115 | m_vertices[22] = glm::vec3(max, max, max); 116 | m_vertices[23] = glm::vec3(max,min, max); 117 | 118 | // TOP 119 | m_vertices[24] = glm::vec3(max, max, max); 120 | m_vertices[25] = glm::vec3(max, max,min); 121 | m_vertices[26] = glm::vec3(min, max,min); 122 | 123 | m_vertices[27] = glm::vec3(max, max, max); 124 | m_vertices[28] = glm::vec3(min, max,min); 125 | m_vertices[29] = glm::vec3(min, max, max); 126 | 127 | // BOTTOM 128 | m_vertices[30] = glm::vec3(max,min, max); 129 | m_vertices[31] = glm::vec3(min,min,min); 130 | m_vertices[32] = glm::vec3(max,min,min); 131 | 132 | m_vertices[33] = glm::vec3(max,min, max); 133 | m_vertices[34] = glm::vec3(min,min, max); 134 | m_vertices[35] = glm::vec3(min,min,min); 135 | 136 | 137 | } 138 | 139 | void MeshCube::createNormals(){ 140 | unsigned int i; 141 | glm::vec3 normal; 142 | m_normals.resize(getNBVertices()); 143 | 144 | int index = 0; 145 | 146 | normal = glm::vec3(0,0,1); 147 | for(i=0; i<6; i++ ){ 148 | m_normals[index+i] = normal; 149 | } 150 | index+=6; 151 | 152 | normal = glm::vec3(0,0,-1); 153 | for(i=0; i<6; i++ ){ 154 | m_normals[index+i] = normal; 155 | } 156 | index+=6; 157 | 158 | normal = glm::vec3(-1,0,0); 159 | for(i=0; i<6; i++ ){ 160 | m_normals[index+i] = normal; 161 | } 162 | index+=6; 163 | 164 | normal = glm::vec3(1,0,0); 165 | for(i=0; i<6; i++ ){ 166 | m_normals[index+i] = normal; 167 | } 168 | index+=6; 169 | 170 | normal = glm::vec3(0,1,0); 171 | for(i=0; i<6; i++ ){ 172 | m_normals[index+i] = normal; 173 | } 174 | index+=6; 175 | 176 | normal = glm::vec3(0,-1,0); 177 | for(i=0; i<6; i++ ){ 178 | m_normals[index+i] = normal; 179 | } 180 | index+=6; 181 | 182 | 183 | } 184 | 185 | void MeshCube::createUVs(){ 186 | 187 | // TODO ajouter les vrai UV 188 | glm::vec2 uv = glm::vec2(0.5f,0); 189 | m_coords.resize(getNBVertices()); 190 | 191 | for(unsigned int i=0; i 7 | #include 8 | #include 9 | #include 10 | #include 11 | #endif 12 | 13 | #include "mesh.h" 14 | 15 | class MeshCube : public Mesh { 16 | 17 | public: 18 | 19 | MeshCube(float w = 1.0f, bool center = true); 20 | 21 | void recreate(); 22 | void createUI(); 23 | 24 | float getVoxelSize(){return m_width;} 25 | 26 | private: 27 | 28 | void createMesh(float w); 29 | void createPositions(float w); 30 | 31 | void createNormals(); 32 | void createm_tangents(); 33 | void createUVs(); 34 | void createColors(); 35 | 36 | float m_width; 37 | bool m_centered; 38 | 39 | }; 40 | 41 | 42 | #endif -------------------------------------------------------------------------------- /src/models/transform.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | #include "transform.h" 4 | 5 | 6 | #include 7 | 8 | #include 9 | 10 | 11 | Transform::Transform(vec3 position, vec3 rotation, vec3 scale) : m_position(position),m_scale(scale), m_rotation(rotation), m_center(glm::vec3(0)), m_translateAfter(glm::vec3(0)), 12 | m_positionToSend(position), m_scaleToSend(glm::vec3(1)), m_rotationToSend(glm::vec3(0)), m_samePosition(true), m_sameRotation(true), 13 | m_animRotSpeedX(m_defaultSpeed), m_animRotSpeedY(m_defaultSpeed), m_animRotSpeedZ(m_defaultSpeed), 14 | m_animChildRotSpeedX(m_defaultSpeed), m_animChildRotSpeedY(m_defaultSpeed), m_animChildRotSpeedZ(m_defaultSpeed), 15 | m_b_animRotX(false), m_b_animRotY(false), b_animRotZ(false), m_b_animChildRotX(false), m_b_animChildRotY(false), m_b_animChildRotZ(false){ 16 | 17 | 18 | reset(); 19 | 20 | } 21 | 22 | 23 | 24 | Transform::~Transform(){ 25 | 26 | } 27 | 28 | 29 | void Transform::reset(){ 30 | m_animRotX = 0, m_animRotY = 0; m_animRotZ = 0; 31 | m_animChildRotX = 0; m_animChildRotY = 0; m_animChildRotZ = 0; 32 | } 33 | 34 | void Transform::setPosition(vec3 position){ 35 | m_position = position; 36 | } 37 | void Transform::setRotation(vec3 axis){ 38 | m_rotation = axis; 39 | } 40 | 41 | void Transform::rotatefromScreen(vec2 v){ 42 | m_rotation.x += v.y; 43 | m_rotation.y += v.x; 44 | } 45 | 46 | void Transform::setCenter(vec3 center) { 47 | m_center = center; 48 | } 49 | 50 | void Transform::scale(vec3 scale){ 51 | m_scale = scale; 52 | } 53 | 54 | void Transform::addTranslation(vec3 t){ 55 | m_position += t; 56 | } 57 | 58 | void Transform::addTranslationAfter(vec3 t){ 59 | m_translateAfter += t; 60 | } 61 | 62 | 63 | 64 | mat4 Transform::getModelMat(mat4 modelMat){ 65 | modelMat = translate(modelMat, m_position); 66 | // modelMat = translate(modelMat, center); 67 | modelMat = glm::rotate(modelMat, m_rotation[0]+m_animRotX, vec3(1.0,0.0,0.0)); 68 | modelMat = glm::rotate(modelMat, m_rotation[1]+m_animRotY, vec3(0.0,1.0,0.0)); 69 | modelMat = glm::rotate(modelMat, m_rotation[2]+m_animRotZ, vec3(0.0,0.0,1.0)); 70 | modelMat = translate(modelMat, m_translateAfter); 71 | modelMat = glm::scale(modelMat, m_scale); 72 | 73 | m_test = modelMat; 74 | return modelMat; 75 | } 76 | 77 | mat4 Transform::getModelToChild(mat4 modelMat){ 78 | 79 | mat4 model = modelMat; 80 | 81 | 82 | 83 | if(!m_samePosition){ 84 | model = translate(model, m_positionToSend); 85 | } else { 86 | model = translate(model, m_position); 87 | } 88 | 89 | if(!m_sameRotation){ 90 | model = glm::rotate(model, m_rotationToSend[0]+m_animChildRotX, vec3(1.0,0.0,0.0)); 91 | model = glm::rotate(model, m_rotationToSend[1]+m_animChildRotY, vec3(0.0,1.0,0.0)); 92 | model = glm::rotate(model, m_rotationToSend[2]+m_animChildRotZ, vec3(0.0,0.0,1.0)); 93 | } else { 94 | model = glm::rotate(model, m_rotation[0]+m_animRotX, vec3(1.0,0.0,0.0)); 95 | model = glm::rotate(model, m_rotation[1]+m_animRotY, vec3(0.0,1.0,0.0)); 96 | model = glm::rotate(model, m_rotation[2]+m_animRotZ, vec3(0.0,0.0,1.0)); 97 | } 98 | 99 | model = translate(model, m_translateAfter); 100 | 101 | model = glm::scale(model, m_scaleToSend); 102 | 103 | return model; 104 | 105 | } 106 | 107 | void Transform::update(){ 108 | 109 | if(m_b_animRotX){ m_animRotX += m_animRotSpeedX; } 110 | if(m_b_animRotY){ m_animRotY += m_animRotSpeedY; } 111 | if(b_animRotZ){ m_animRotZ += m_animRotSpeedZ; } 112 | 113 | if(m_b_animChildRotX){ m_animChildRotX += m_animChildRotSpeedX; } 114 | if(m_b_animChildRotY){ m_animChildRotY += m_animChildRotSpeedY; } 115 | if(m_b_animChildRotZ){ m_animChildRotZ += m_animChildRotSpeedZ; } 116 | 117 | } 118 | 119 | 120 | 121 | void Transform::createUI(){ 122 | const float lowestValue = -1000.0f; 123 | const float highestValue = 1000.0f; 124 | int node_flags = 0; 125 | 126 | // format d'affichage 127 | const char *format = "%.3f"; 128 | 129 | // to hide label of the input 130 | ImGui::PushItemWidth(-1); 131 | 132 | ImGui::Text("Transform"); 133 | ImGui::Text("Position: "); ImGui::SameLine(); 134 | ImGui::DragFloat3("##position", &m_position[0], 0.01f, lowestValue, highestValue, format); 135 | ImGui::Text("Rotation: "); ImGui::SameLine(); 136 | ImGui::DragFloat3("##rotation", &m_rotation[0], 0.01f, lowestValue, highestValue, format); 137 | ImGui::Text("Scale: "); ImGui::SameLine(); 138 | ImGui::DragFloat3("##scale", &m_scale[0], 0.005f, 0.0f, highestValue, format); 139 | 140 | 141 | 142 | int node_flags_child = 0; 143 | bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)1, node_flags_child, "Model Matrix to child"); 144 | 145 | if (node_open) { 146 | 147 | ImGui::Text("Same position as parent"); 148 | ImGui::Checkbox("##Transformm_samePositionAsParent", &m_samePosition); 149 | if(!m_samePosition){ 150 | ImGui::SameLine(); ImGui::Text("Position: "); ImGui::SameLine(); 151 | ImGui::DragFloat3("##position", &m_positionToSend[0], 0.01f, lowestValue, highestValue, format); 152 | } 153 | 154 | ImGui::Text("Same rotation as parent"); 155 | ImGui::Checkbox("##Transformm_sameRotationAsParent", &m_sameRotation); 156 | if(!m_sameRotation){ 157 | ImGui::SameLine(); ImGui::Text("Rotation: "); ImGui::SameLine(); 158 | ImGui::DragFloat3("##rotation", &m_rotationToSend[0], 0.01f, lowestValue, highestValue, format); 159 | } 160 | 161 | 162 | 163 | 164 | ImGui::TreePop(); 165 | } 166 | 167 | /* 168 | ///// ANIMATION 169 | 170 | bool node_open_anim = ImGui::TreeNodeEx((void*)(intptr_t)0, node_flags, "Animation"); 171 | 172 | if (node_open_anim) { 173 | ImGui::Text("Rotation X : "); 174 | ImGui::SameLine(); ImGui::Checkbox("##RotX", &m_b_animRotX); 175 | ImGui::SameLine(); ImGui::Text("speed X: "); ImGui::SameLine(); 176 | ImGui::DragFloat("##speedX", &m_animRotSpeedX, 0.002f, lowestValue, highestValue, format); 177 | ImGui::Text("Rotation Y : "); 178 | ImGui::SameLine(); ImGui::Checkbox("##RotY", &m_b_animRotY); 179 | ImGui::SameLine(); ImGui::Text("speed Y: "); ImGui::SameLine(); 180 | ImGui::DragFloat("##speedY", &m_animRotSpeedY, 0.002f, lowestValue, highestValue, format); 181 | ImGui::Text("Rotation Z : "); 182 | ImGui::SameLine(); ImGui::Checkbox("##RotZ", &b_animRotZ); 183 | ImGui::SameLine(); ImGui::Text("speed Z: "); ImGui::SameLine(); 184 | ImGui::DragFloat("##speedZ", &m_animRotSpeedZ, 0.002f, lowestValue, highestValue, format); 185 | 186 | ImGui::TreePop(); 187 | } 188 | 189 | int anim_node_flags_child = 0; 190 | bool node_open_anim_child = ImGui::TreeNodeEx((void*)(intptr_t)2, anim_node_flags_child, "Animation Child"); 191 | 192 | if (node_open_anim_child) { 193 | ImGui::Text("Rotation X : "); 194 | ImGui::SameLine(); ImGui::Checkbox("##ChildRotX", &m_b_animChildRotX); 195 | ImGui::SameLine(); ImGui::Text("speed X: "); ImGui::SameLine(); 196 | ImGui::DragFloat("##speedChildX", &m_animChildRotSpeedX, 0.002f, lowestValue, highestValue, format); 197 | ImGui::Text("Rotation Y : "); 198 | ImGui::SameLine(); ImGui::Checkbox("##ChildRotY", &m_b_animChildRotY); 199 | ImGui::SameLine(); ImGui::Text("speed Y: "); ImGui::SameLine(); 200 | ImGui::DragFloat("##speedChildY", &m_animChildRotSpeedY, 0.002f, lowestValue, highestValue, format); 201 | ImGui::Text("Rotation Z : "); 202 | ImGui::SameLine(); ImGui::Checkbox("##ChildRotZ", &m_b_animChildRotZ); 203 | ImGui::SameLine(); ImGui::Text("speed Z: "); ImGui::SameLine(); 204 | ImGui::DragFloat("##speedChildZ", &m_animChildRotSpeedZ, 0.002f, lowestValue, highestValue, format); 205 | 206 | ImGui::TreePop(); 207 | } 208 | 209 | if(ImGui::Button("Reset Animation")){ 210 | reset(); 211 | }*/ 212 | 213 | // to hide label of the input 214 | ImGui::PopItemWidth(); 215 | } 216 | 217 | 218 | void Transform::setAnimation(bool b_X, bool b_Y, bool b_Z, float SpeedX, float SpeedY, float SpeedZ){ 219 | m_b_animRotX = b_X; m_b_animRotY = b_Y; b_animRotZ = b_Z; 220 | m_animRotSpeedX = SpeedX; m_animRotSpeedY = SpeedY; m_animRotSpeedZ = SpeedZ; 221 | } 222 | 223 | 224 | void Transform::setChildAnimation(bool b_X, bool b_Y, bool b_Z, float SpeedX, float SpeedY, float SpeedZ){ 225 | m_b_animChildRotX = b_X; m_b_animChildRotY = b_Y; m_b_animChildRotZ = b_Z; 226 | m_animChildRotSpeedX = SpeedX; m_animChildRotSpeedY = SpeedY; m_animChildRotSpeedZ = SpeedZ; 227 | } 228 | 229 | void Transform::setSameAsParent(bool position, bool rotation){ 230 | m_samePosition = position; 231 | m_sameRotation = rotation; 232 | } 233 | 234 | 235 | vec3 Transform::getPosition(){ 236 | return m_position; 237 | } 238 | 239 | vec3 Transform::getRotation(){ 240 | return m_rotation; 241 | } 242 | 243 | vec3 Transform::getScale(){ 244 | return m_scale; 245 | } 246 | 247 | void Transform::decompose(mat4 mat){ 248 | 249 | 250 | printf("(%f, %f, %f, %f)\n", mat[0][0],mat[0][1], mat[0][2], mat[0][3]); 251 | printf("(%f, %f, %f, %f)\n", mat[1][0],mat[1][1], mat[1][2], mat[1][3]); 252 | printf("(%f, %f, %f, %f)\n", mat[2][0],mat[2][1], mat[2][2], mat[2][3]); 253 | printf("(%f, %f, %f, %f)\n\n", mat[3][0],mat[3][1], mat[3][2], mat[3][3]); 254 | 255 | m_position = vec3(mat[0][3], mat[1][3], mat[2][3]); 256 | 257 | 258 | m_rotation = rotationMatrixToEulerAngles(mat); 259 | m_scale = glm::vec3(1,1,1); 260 | 261 | } 262 | 263 | vec3 Transform::rotationMatrixToEulerAngles(mat4 r){ 264 | 265 | float sy = sqrt(r[0][0] * r[0][0] + r[1][0] * r[1][0] ); 266 | 267 | bool singular = sy < 1e-6; // If 268 | 269 | float x, y, z; 270 | if (!singular) 271 | { 272 | x = atan2(r[2][1] , r[2][2]); 273 | y = atan2(-r[2][0], sy); 274 | z = atan2(r[1][0], r[0][0]); 275 | } 276 | else 277 | { 278 | x = atan2(-r[1][2], r[1][1]); 279 | y = atan2(-r[2][0], sy); 280 | z = 0; 281 | } 282 | return vec3(x, y, z); 283 | 284 | } -------------------------------------------------------------------------------- /src/models/transform.h: -------------------------------------------------------------------------------- 1 | #ifndef TRANSFORM_H 2 | #define TRANSFORM_H 3 | 4 | 5 | #ifndef GLM_H 6 | #define GLM_H 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #endif 13 | 14 | using namespace glm; 15 | 16 | class Transform { 17 | public: 18 | Transform(vec3 position = vec3(0.0,0.0,0.0), vec3 rotation = vec3(0.0,0.0,0.0), vec3 scale = vec3(1.0,1.0,1.0)); 19 | ~Transform(); 20 | 21 | void setPosition(vec3 position); 22 | void setRotation(vec3 angle); 23 | void rotatefromScreen(vec2 v); 24 | void scale(vec3 scale); 25 | void setCenter(vec3 center); 26 | 27 | void addTranslation(vec3 t); 28 | void addTranslationAfter(vec3 t); 29 | 30 | vec3 getPosition(); 31 | vec3 getRotation(); 32 | vec3 getScale(); 33 | 34 | void update(); 35 | 36 | mat4 getModelMat(mat4 modelMat = glm::mat4(1)); 37 | mat4 getModelToChild(mat4 modelMat); 38 | 39 | void createUI(); 40 | 41 | void setAnimation(bool b_X, bool b_Y, bool b_Z, float SpeedX = 0.01f, float SpeedY = 0.01f, float SpeedZ = 0.01f); 42 | void setChildAnimation(bool b_X, bool b_Y, bool b_Z, float SpeedX = 0.01f, float SpeedY = 0.01f, float SpeedZ = 0.01f); 43 | void setSameAsParent(bool position, bool rotation); 44 | 45 | 46 | void decompose(mat4 mat); 47 | 48 | protected: 49 | 50 | vec3 rotationMatrixToEulerAngles(mat4 r); 51 | 52 | void reset(); 53 | 54 | vec3 m_position, m_scale, m_rotation, m_center, m_translateAfter; 55 | 56 | bool m_samePosition, m_sameRotation; 57 | 58 | vec3 m_positionToSend, m_scaleToSend, m_rotationToSend; 59 | 60 | 61 | // To animate the transform 62 | float m_animRotX, m_animRotY, m_animRotZ; 63 | float m_animChildRotX, m_animChildRotY, m_animChildRotZ; 64 | 65 | float m_animRotSpeedX, m_animRotSpeedY, m_animRotSpeedZ; 66 | float m_animChildRotSpeedX, m_animChildRotSpeedY, m_animChildRotSpeedZ; 67 | 68 | bool m_b_animRotX = false, m_b_animRotY = false, b_animRotZ = false; 69 | bool m_b_animChildRotX, m_b_animChildRotY, m_b_animChildRotZ; 70 | 71 | const float m_defaultSpeed = 0.01; 72 | 73 | glm::mat4 m_test = glm::mat4(1); 74 | }; 75 | 76 | #endif 77 | -------------------------------------------------------------------------------- /src/terrain/cubicArray.h: -------------------------------------------------------------------------------- 1 | #ifndef _CUBIC_ARRAY_H_ 2 | #define _CUBIC_ARRAY_H_ 3 | 4 | #include 5 | 6 | // Permet d'accèder un std::vector comme un tableau à 3 dimensions 7 | // CubicArray arr(5) -> tableau de taille 5 * 5 * 5 8 | 9 | template 10 | class CubicArray : public std::vector { 11 | 12 | public: 13 | 14 | /// Constructors 15 | 16 | CubicArray(); 17 | CubicArray(size_t cubic_size, const T& value = {}); 18 | 19 | /// Memory 20 | 21 | void resize(size_t cubic_size); 22 | 23 | /// Accessors 24 | 25 | // Ces fonctions renvoient toute la taille cubic 26 | size_t cubic_size() const; 27 | size_t width() const; 28 | size_t height() const; 29 | size_t depth() const; 30 | 31 | // Les coordonnées n'ont pas le droit d'être négatives 32 | T& operator()(size_t x, size_t y, size_t z); 33 | const T& operator()(size_t x, size_t y, size_t z) const; 34 | 35 | private: 36 | 37 | size_t m_cubic_size; 38 | }; 39 | 40 | #include "cubicArray.inl" 41 | 42 | #endif 43 | -------------------------------------------------------------------------------- /src/terrain/cubicArray.inl: -------------------------------------------------------------------------------- 1 | #ifndef _CUBIC_ARRAY_INL_ 2 | #define _CUBIC_ARRAY_INL_ 3 | 4 | #include "cubicArray.h" 5 | 6 | ///////////////////////// CubicArray 7 | 8 | // Constructors 9 | 10 | template 11 | CubicArray::CubicArray() : std::vector(), m_cubic_size{0} {} 12 | 13 | template 14 | CubicArray::CubicArray(size_t cubic_size, const T& value) : std::vector(cubic_size * cubic_size * cubic_size, value), m_cubic_size{cubic_size} {} 15 | 16 | // Memory 17 | 18 | template 19 | void CubicArray::resize(size_t cubic_size) { 20 | std::vector::resize(cubic_size * cubic_size * cubic_size); 21 | m_cubic_size = cubic_size; 22 | } 23 | 24 | // Accessors 25 | 26 | template 27 | size_t CubicArray::cubic_size() const { 28 | return m_cubic_size;; 29 | } 30 | 31 | template 32 | size_t CubicArray::width() const { 33 | return this->cubic_size(); 34 | } 35 | 36 | template 37 | size_t CubicArray::height() const { 38 | return this->cubic_size(); 39 | } 40 | 41 | template 42 | size_t CubicArray::depth() const { 43 | return this->cubic_size(); 44 | } 45 | 46 | template 47 | T& CubicArray::operator()(size_t x, size_t y, size_t z) { 48 | return (*this)[ x + (y * this->width()) + (z * this->width() * this->height()) ]; 49 | } 50 | 51 | template 52 | const T& CubicArray::operator()(size_t x, size_t y, size_t z) const { 53 | return (*this)[ x + (y * this->width()) + (z * this->width() * this->height()) ]; 54 | } 55 | 56 | #endif -------------------------------------------------------------------------------- /src/terrain/simplexNoise.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file SimplexNoise.h 3 | * @brief A Perlin Simplex Noise C++ Implementation (1D, 2D, 3D). 4 | * 5 | * Copyright (c) 2014-2018 Sebastien Rombauts (sebastien.rombauts@gmail.com) 6 | * 7 | * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt 8 | * or copy at http://opensource.org/licenses/MIT) 9 | */ 10 | #pragma once 11 | 12 | #include // size_t 13 | 14 | /** 15 | * @brief A Perlin Simplex Noise C++ Implementation (1D, 2D, 3D, 4D). 16 | */ 17 | class SimplexNoise { 18 | public: 19 | // 1D Perlin simplex noise 20 | static float noise(float x); 21 | // 2D Perlin simplex noise 22 | static float noise(float x, float y); 23 | // 3D Perlin simplex noise 24 | static float noise(float x, float y, float z); 25 | 26 | // Fractal/Fractional Brownian Motion (fBm) noise summation 27 | float fractal(size_t octaves, float x) const; 28 | float fractal(size_t octaves, float x, float y) const; 29 | float fractal(size_t octaves, float x, float y, float z) const; 30 | 31 | /** 32 | * Constructor of to initialize a fractal noise summation 33 | * 34 | * @param[in] frequency Frequency ("width") of the first octave of noise (default to 1.0) 35 | * @param[in] amplitude Amplitude ("height") of the first octave of noise (default to 1.0) 36 | * @param[in] lacunarity Lacunarity specifies the frequency multiplier between successive octaves (default to 2.0). 37 | * @param[in] persistence Persistence is the loss of amplitude between successive octaves (usually 1/lacunarity) 38 | */ 39 | explicit SimplexNoise(float frequency = 1.0f, 40 | float amplitude = 1.0f, 41 | float lacunarity = 2.0f, 42 | float persistence = 0.5f) : 43 | mFrequency(frequency), 44 | mAmplitude(amplitude), 45 | mLacunarity(lacunarity), 46 | mPersistence(persistence) 47 | {} 48 | 49 | private: 50 | // Parameters of Fractional Brownian Motion (fBm) : sum of N "octaves" of noise 51 | float mFrequency; ///< Frequency ("width") of the first octave of noise (default to 1.0) 52 | float mAmplitude; ///< Amplitude ("height") of the first octave of noise (default to 1.0) 53 | float mLacunarity; ///< Lacunarity specifies the frequency multiplier between successive octaves (default to 2.0). 54 | float mPersistence; ///< Persistence is the loss of amplitude between successive octaves (usually 1/lacunarity) 55 | }; 56 | -------------------------------------------------------------------------------- /src/terrain/terrainChunk.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "terrainChunk.h" 4 | #include "simplexNoise.h" 5 | #include "terrainManager.h" 6 | 7 | ///////////////////////// Chunk 8 | 9 | //// Constructors 10 | 11 | // float TerrainChunk::m_frequency = 0.008f; 12 | // size_t TerrainChunk::nbOctaves = 4; 13 | float TerrainChunk::m_frequency = 0.01f; 14 | size_t TerrainChunk::nbOctaves = 3; 15 | 16 | 17 | TerrainChunk::TerrainChunk(size_t cubic_size) : voxels(cubic_size) { 18 | setName("TerrainChunk"); 19 | } 20 | 21 | void TerrainChunk::start() { 22 | assert(m_gameobject != nullptr); 23 | 24 | renderer = m_gameobject->getComponent(); 25 | 26 | assert(renderer != nullptr); 27 | 28 | generate(); 29 | 30 | // calculateMesh(); 31 | 32 | // renderer->mesh->createVAO(); 33 | } 34 | 35 | // TerrainChunk::TerrainChunk(size_t cubic_size, float x, float y, float z) : TerrainChunk(cubic_size, glm::vec3(x, y, z)) {} 36 | 37 | void TerrainChunk::generate() { 38 | glm::vec3 position = m_gameobject->getTransform()->getPosition(); 39 | // std::cerr << position.x << ','<< position.y << ',' << position.z << '\n'; 40 | 41 | if (position.y >= 0 && position.y < voxels.height()) // Affichage de la surface du terrain 42 | { 43 | for(size_t i = 0 ; i < voxels.width() ; ++i) { 44 | for(size_t k = 0 ; k < voxels.depth() ; ++k) { 45 | 46 | // perlin_value in [0, 1] 47 | // float perlin_value = (snoise.fractal(octaves, 48 | // position.x + i, 49 | // position.z + k) + 1.0) / 2.0; 50 | // 51 | // size_t max_y = std::round(perlin_value * voxels.cubic_size()); 52 | size_t max_y = getHeightAt(voxels.cubic_size(), position.x + i, position.z + k); 53 | // 54 | // voxels(i, max_y, k) = Voxel::Full; 55 | 56 | // if (max_y > 0) 57 | // voxels(i, max_y - 1, k) = Voxel::Full; 58 | 59 | for (size_t j = 0 ; j < max_y ; ++j) // => active les voxel de 0 à Y 60 | { 61 | voxels(i, j, k) = Voxel::Full; 62 | } 63 | } 64 | } 65 | } 66 | else if (position.y < 0) { // Affiche le sous-sol de la map 67 | for(size_t i = 0 ; i < voxels.width() ; ++i) { 68 | for (size_t j = 0 ; j < voxels.height() ; ++j) // => active les voxel de 0 à Y 69 | for(size_t k = 0 ; k < voxels.depth() ; ++k) { 70 | { 71 | voxels(i, j, k) = getGroundAt(voxels.cubic_size(), position.x + i, position.y + j, position.z + k); 72 | } 73 | } 74 | } 75 | } 76 | } 77 | 78 | 79 | std::array TerrainChunk::surrounding(size_t x, size_t y, size_t z) const { 80 | 81 | std::array activated_neighbors = {}; // Tout est faux 82 | glm::vec3 pos = m_gameobject->getTransform()->getPosition(); 83 | 84 | if ( (!(x == (voxels.width() - 1)) && (voxels(x + 1, y , z ) != Voxel::Empty)) || 85 | ((x == (voxels.width() - 1)) && (y < getHeightAt(voxels.cubic_size(), pos.x + x + 1, pos.z + z))) ) 86 | activated_neighbors[0] = true; 87 | 88 | if ( (!(x == 0) && (voxels(x - 1, y , z ) != Voxel::Empty)) || 89 | ((x == 0) && (y < getHeightAt(voxels.cubic_size(), pos.x + float(x) - 1, pos.z + z))) ) 90 | activated_neighbors[1] = true; 91 | 92 | if ( (!(y == (voxels.height() - 1)) && (voxels(x , y + 1, z ) != Voxel::Empty)) || 93 | ((y == (voxels.height() - 1)) && (float(y) + 1 < getHeightAt(voxels.cubic_size(), pos.x + x, pos.z + z))) ) 94 | activated_neighbors[2] = true; 95 | 96 | if ( (!(y == 0) && (voxels(x , y - 1, z ) != Voxel::Empty)) || 97 | ((y == 0) && (float(y) - 1 < getHeightAt(voxels.cubic_size(), pos.x + x, pos.z + z))) ) 98 | activated_neighbors[3] = true; 99 | 100 | if ( (!(z == (voxels.depth() - 1)) && (voxels(x , y , z + 1) != Voxel::Empty)) || 101 | ((z == (voxels.depth() - 1)) && (y < getHeightAt(voxels.cubic_size(), pos.x + x, pos.z + z + 1))) ) 102 | activated_neighbors[4] = true; 103 | 104 | if ( (!(z == 0) && (voxels(x , y , z - 1) != Voxel::Empty)) || 105 | ((z == 0) && (y < getHeightAt(voxels.cubic_size(), pos.x + x, pos.z + float(z) - 1))) ) 106 | activated_neighbors[5] = true; 107 | 108 | // if ( !(x == (voxels.width() - 1)) && (voxels(x + 1, y , z ) != Voxel::Empty) ) activated_neighbors[0] = true; 109 | // if ( !(x == 0) && (voxels(x - 1, y , z ) != Voxel::Empty) ) activated_neighbors[1] = true; 110 | // if ( !(y == (voxels.height()- 1)) && (voxels(x , y + 1, z ) != Voxel::Empty) ) activated_neighbors[2] = true; 111 | // if ( !(y == 0) && (voxels(x , y - 1, z ) != Voxel::Empty) ) activated_neighbors[3] = true; 112 | // if ( !(z == (voxels.depth() - 1)) && (voxels(x , y , z + 1) != Voxel::Empty) ) activated_neighbors[4] = true; 113 | // if ( !(z == 0) && (voxels(x , y , z - 1) != Voxel::Empty) ) activated_neighbors[5] = true; 114 | 115 | // assert(x != 0 && x != voxels.width() - 1); 116 | // assert(y != 0 && y != voxels.height() - 1); 117 | // assert(z != 0 && z != voxels.depth() - 1); 118 | 119 | // if (voxels(x + 1, y , z ) != Voxel::Empty) activated_neighbors[0] = true; 120 | // if (voxels(x - 1, y , z ) != Voxel::Empty) activated_neighbors[1] = true; 121 | // if (voxels(x , y + 1, z ) != Voxel::Empty) activated_neighbors[2] = true; 122 | // if (voxels(x , y - 1, z ) != Voxel::Empty) activated_neighbors[3] = true; 123 | // if (voxels(x , y , z + 1) != Voxel::Empty) activated_neighbors[4] = true; 124 | // if (voxels(x , y , z - 1) != Voxel::Empty) activated_neighbors[5] = true; 125 | 126 | return activated_neighbors; 127 | } 128 | 129 | 130 | void TerrainChunk::addCubeFaces(const std::array& surrounding, size_t x, size_t y, size_t z) const 131 | { 132 | 133 | float height_ratio = float(y) / voxels.cubic_size(); 134 | // std::cerr << "height_ratio : "<< height_ratio << '\n'; 135 | 136 | glm::vec3 color(1.0, 0.8, 0.1); 137 | 138 | // std::cerr << "(" << color.r << ", " << color.g << ", " << color.b << ")\n"; 139 | 140 | if(height_ratio > 0.25) 141 | color = glm::vec3(0.1, 1.0 - height_ratio, 0); 142 | 143 | // glm::vec3 normal(0, 0, 0); 144 | 145 | // XPlus 146 | if (!surrounding[0]) 147 | { 148 | glm::vec3 v1(x + 1, y , z); 149 | glm::vec3 v2(x + 1, y + 1, z); 150 | glm::vec3 v3(x + 1, y , z + 1); 151 | glm::vec3 v4(x + 1, y + 1, z + 1); 152 | 153 | // glm::vec3 normal = glm::cross((v2 - v1), (v3 - v1)); 154 | 155 | renderer->mesh->addQuad(v1, v2, v3, v4, glm::vec3(1, 0, 0), color); // multiply by voxel_size if != 1.0f 156 | } 157 | 158 | // XMinus 159 | if (!surrounding[1]) 160 | { 161 | glm::vec3 v1(x, y , z); 162 | glm::vec3 v2(x, y + 1, z); 163 | glm::vec3 v3(x, y , z + 1); 164 | glm::vec3 v4(x, y + 1, z + 1); 165 | 166 | // glm::vec3 normal = glm::cross((v3 - v1), (v2 - v1)); 167 | 168 | renderer->mesh->addQuad(v1, v3, v2, v4, glm::vec3(-1, 0, 0), color); // multiply by voxel_size if != 1.0f 169 | } 170 | 171 | // YPlus 172 | if (!surrounding[2]) 173 | { 174 | glm::vec3 v1(x , y + 1, z); 175 | glm::vec3 v2(x + 1, y + 1, z); 176 | glm::vec3 v3(x , y + 1, z + 1); 177 | glm::vec3 v4(x + 1, y + 1, z + 1); 178 | 179 | // glm::vec3 normal = glm::cross((v2 - v1), (v3 - v1)); 180 | 181 | renderer->mesh->addQuad(v1, v3, v2, v4, glm::vec3(0, 1, 0), color); // multiply by voxel_size if != 1.0f 182 | } 183 | 184 | // YMinus 185 | if (!surrounding[3]) 186 | { 187 | glm::vec3 v1(x , y, z); 188 | glm::vec3 v2(x + 1, y, z); 189 | glm::vec3 v3(x , y, z + 1); 190 | glm::vec3 v4(x + 1, y, z + 1); 191 | 192 | // glm::vec3 normal = glm::cross((v3 - v1), (v2 - v1)); 193 | 194 | renderer->mesh->addQuad(v1, v2, v3, v4, glm::vec3(0, -1, 0), color); // multiply by voxel_size if != 1.0f 195 | } 196 | 197 | // ZPlus 198 | if (!surrounding[4]) 199 | { 200 | glm::vec3 v1(x , y , z + 1); 201 | glm::vec3 v2(x + 1, y , z + 1); 202 | glm::vec3 v3(x , y + 1, z + 1); 203 | glm::vec3 v4(x + 1, y + 1, z + 1); 204 | 205 | // glm::vec3 normal = -glm::cross((v2 - v1), (v3 - v1)); 206 | 207 | renderer->mesh->addQuad(v1, v2, v3, v4, glm::vec3(0, 0, 1), color); // multiply by voxel_size if != 1.0f 208 | } 209 | 210 | // ZMinus 211 | if (!surrounding[5]) 212 | { 213 | glm::vec3 v1(x , y , z); 214 | glm::vec3 v2(x + 1, y , z); 215 | glm::vec3 v3(x , y + 1, z); 216 | glm::vec3 v4(x + 1, y + 1, z); 217 | 218 | // glm::vec3 normal = glm::cross((v3 - v1), (v2 - v1)); 219 | 220 | renderer->mesh->addQuad(v1, v3, v2, v4, glm::vec3(0, 0, -1), color); // multiply by voxel_size if != 1.0f 221 | } 222 | } 223 | 224 | void TerrainChunk::calculateMesh() 225 | { 226 | for(size_t i = 0 ; i< voxels.width(); i++) { 227 | for(size_t j = 0 ; j < voxels.height(); j++) { 228 | for(size_t k = 0 ; k < voxels.depth(); k++) { 229 | if (voxels(i, j, k) != Voxel::Empty) // si le voxel est activé 230 | { 231 | this->addCubeFaces(this->surrounding(i, j, k), i, j, k); 232 | } 233 | } 234 | } 235 | } 236 | } 237 | 238 | size_t TerrainChunk::getHeightAt(size_t chunk_size, float x, float z) { 239 | 240 | SimplexNoise snoise(m_frequency); 241 | 242 | float perlin_value = (snoise.fractal(nbOctaves, x, z) + 1.0) / 2.0; 243 | 244 | return std::round(perlin_value * chunk_size); 245 | } 246 | 247 | Voxel TerrainChunk::getGroundAt(size_t chunk_size, float x, float y, float z) { 248 | float scale = 50.f; 249 | size_t octaves = 3; 250 | 251 | SimplexNoise snoise(1.0f / scale); 252 | 253 | float perlin_value = (snoise.fractal(octaves, x, y, z) + 1.0) / 2.0; 254 | 255 | return perlin_value < 0.5 ? Voxel::Empty : Voxel::Full; 256 | } 257 | 258 | -------------------------------------------------------------------------------- /src/terrain/terrainChunk.h: -------------------------------------------------------------------------------- 1 | #ifndef _TERRAIN_CHUNK_H_ 2 | #define _TERRAIN_CHUNK_H_ 3 | 4 | #include 5 | 6 | #include "cubicArray.h" 7 | #include "voxel.h" 8 | #include "../models/mesh/mesh.h" 9 | #include "../components/component.h" 10 | #include "../components/meshRenderer.h" 11 | 12 | class TerrainManager; 13 | 14 | class TerrainChunk : public Component { 15 | 16 | public: 17 | 18 | /// Attributes 19 | 20 | CubicArray voxels; 21 | MeshRenderer* renderer = nullptr; 22 | bool needUpdate = true; 23 | 24 | /// Constructors 25 | 26 | TerrainChunk(size_t cubic_size); 27 | 28 | /// Overrides 29 | 30 | void start() override; 31 | // void update() override; 32 | // void createUI() override; 33 | 34 | /// Modificators 35 | 36 | void generate(); // initialize le chunk en fonction de sa position dans le monde 37 | void calculateMesh(); 38 | void addCubeFaces(const std::array& surrounding, size_t x, size_t y, size_t z) const; 39 | 40 | /// Accessors 41 | 42 | // Renvoie 6 booleen correspondant à la presence ou non des 6 voisins du voxel (x, y, z) 43 | std::array surrounding(size_t x, size_t y, size_t z) const; 44 | 45 | /// Statics 46 | 47 | static size_t getHeightAt(size_t chunk_size, float x, float z); 48 | static Voxel getGroundAt(size_t chunk_size, float x, float y, float z); 49 | // private: 50 | static float m_frequency; 51 | static size_t nbOctaves; 52 | 53 | // TerrainManager* m_terrain = nullptr; 54 | 55 | private: 56 | }; 57 | 58 | #endif -------------------------------------------------------------------------------- /src/terrain/terrainManager.h: -------------------------------------------------------------------------------- 1 | #ifndef _TERRAIN_MANAGER_H_ 2 | #define _TERRAIN_MANAGER_H_ 3 | 4 | #ifndef GLM_H 5 | #define GLM_H 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #endif 12 | 13 | #include 14 | #include 15 | 16 | #include "terrainChunk.h" 17 | #include "../engineClass/gameObject.h" 18 | 19 | 20 | class TerrainManager : public Component { 21 | 22 | public: 23 | 24 | /// Constructors 25 | 26 | TerrainManager(size_t chunk_size, size_t terrain_size, Transform* player_transform); // Initialise les valeurs du chunk à partir de sa position dans le monde 27 | 28 | /// Overrides 29 | 30 | void start() override; 31 | // void update() override; 32 | void inputUpdate() override; 33 | void update() override; 34 | 35 | void createUI() override; 36 | 37 | /// Factory 38 | 39 | // Alloue un nouveau chunk 40 | GameObject* createTerrainChunk(glm::vec3 position); 41 | 42 | /// Modificators 43 | 44 | void createChunksAround(glm::vec3 world_coord); 45 | void manageChunksAround(glm::vec3 world_coord); 46 | 47 | void updateChunkAt(glm::vec3 world_coord); 48 | 49 | /// Accessors 50 | 51 | glm::ivec3 toChunkGridCoord(glm::vec3 world_coord) const; 52 | glm::uvec3 toChunkCoord(glm::vec3 world_coord) const; 53 | glm::vec3 toVoxelCoordInChunk(glm::vec3 world_coord) const; 54 | glm::vec3 toVoxelWorldCoord(glm::vec3 world_coord) const; 55 | glm::vec3 toWorldGridCoord(glm::ivec3 chunk_grid_coord) const; 56 | glm::uvec3 toVoxelCoord(glm::vec3 world_coord) const; 57 | 58 | TerrainChunk* getPlayerChunk(); 59 | TerrainChunk* getChunkAt(glm::vec3 world_coord); 60 | 61 | Voxel getVoxelAt(glm::vec3 world_coord); 62 | void setVoxelAt(glm::vec3 world_coord, Voxel v); // change le voxel seulement si il est dans les terrains visibles 63 | 64 | glm::vec3 getPlayerCoord() const; 65 | 66 | size_t getHeightAt(float x, float z) const; 67 | size_t getChunkSize() const; 68 | size_t getTerrainSize() const; 69 | 70 | private: 71 | 72 | size_t m_chunk_size; 73 | size_t m_terrain_size; 74 | Transform* m_player_transform = nullptr; 75 | glm::ivec3 m_oldChunkGridCoord; 76 | 77 | int m_octaves; 78 | float m_frequency; 79 | bool m_recreate; 80 | 81 | std::map> m_grid_to_chunk_map; 82 | }; 83 | 84 | #endif -------------------------------------------------------------------------------- /src/terrain/voxel.h: -------------------------------------------------------------------------------- 1 | #ifndef _VOXEL_H_ 2 | #define _VOXEL_H_ 3 | 4 | enum class Voxel : unsigned char { 5 | Empty, 6 | Full 7 | }; 8 | 9 | #endif -------------------------------------------------------------------------------- /src/tools/lights/directionnalLight.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "directionnalLight.h" 4 | 5 | DirectionnalLight::DirectionnalLight(int id, std::string name, glm::vec3 l) : m_light(l){ 6 | setID(id); 7 | setName(name); 8 | m_intensity = 1.0; 9 | } 10 | 11 | 12 | 13 | glm::vec3 DirectionnalLight::getLight(){ 14 | return m_light; 15 | } 16 | 17 | void DirectionnalLight::createUI(char *ID){ 18 | const float lowestValue = -1000.0f; 19 | const float highestValue = 1000.0f; 20 | const char *format = "%.3f"; 21 | 22 | ImGui::BeginChild(ID); 23 | ImGui::Text(m_name.c_str()); 24 | ImGui::Separator(); 25 | 26 | 27 | ImGui::PushItemWidth(-1); 28 | 29 | ImGui::Text("Direction: "); ImGui::SameLine(); 30 | ImGui::DragFloat3("directionLight", &m_light[0], 0.01f, lowestValue, highestValue, format); 31 | 32 | ImGui::Text("Intensity: "); ImGui::SameLine(); 33 | ImGui::DragFloat("intensity", &m_intensity, 0.01f, 0.0, 2.0, "%.3f"); 34 | 35 | 36 | ImGui::PopItemWidth(); 37 | 38 | ImGui::EndChild(); 39 | } 40 | -------------------------------------------------------------------------------- /src/tools/lights/directionnalLight.h: -------------------------------------------------------------------------------- 1 | #ifndef DIRECTIONNAL_LIGHT_H 2 | #define DIRECTIONNAL_LIGHT_H 3 | 4 | #include "light.h" 5 | #include 6 | 7 | class DirectionnalLight : public Light { 8 | public: 9 | DirectionnalLight(int id, std::string name = "Directionnal Light", glm::vec3 l = glm::vec3(0.f,-1.0f,0.0f)); 10 | 11 | virtual glm::vec3 getLight(); 12 | 13 | void createUI(char *ID) override; 14 | 15 | private: 16 | glm::vec3 m_light; 17 | }; 18 | 19 | #endif 20 | -------------------------------------------------------------------------------- /src/tools/lights/light.h: -------------------------------------------------------------------------------- 1 | #ifndef LIGHT_H 2 | #define LIGHT_H 3 | 4 | #ifndef GLM_H 5 | #define GLM_H 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #endif 12 | 13 | #include "../../engineClass/gameObject.h" 14 | 15 | class Light : public GameObject { 16 | 17 | public: 18 | virtual glm::vec3 getLight() = 0; 19 | 20 | float m_intensity; 21 | 22 | }; 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /thirdparty/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_subdirectory(glm) 2 | add_subdirectory(glfw) 3 | 4 | file(GLOB GLAD_SOURCES glad/src/glad.c) 5 | file(GLOB GLAD_HEADERS glad/include/glad/glad.h) 6 | set(GLAD_INCLUDE glad/include) 7 | 8 | include_directories(${GLAD_INCLUDE}) 9 | 10 | add_library(glad STATIC ${GLAD_HEADERS} ${GLAD_SOURCES}) 11 | set_target_properties(glad PROPERTIES LINKER_LANGUAGE C) 12 | 13 | 14 | add_subdirectory(imgui) 15 | -------------------------------------------------------------------------------- /thirdparty/imgui/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | file(GLOB_RECURSE SRCS_IMGUI 4 | *.cpp 5 | *.c 6 | ) 7 | 8 | 9 | file(GLOB_RECURSE HEADERS_IMGUI 10 | *.h 11 | *.hpp 12 | ) 13 | 14 | include_directories( 15 | ${GLFW_INCLUDE_DIR} 16 | ${GLAD_INCLUDE_DIR} 17 | ${OPENGL_INCLUDE_DIR} 18 | ) 19 | 20 | 21 | add_definitions( -ldl ) 22 | add_definitions(-DIMGUI_IMPL_OPENGL_LOADER_GLAD) 23 | 24 | add_library(imgui STATIC ${SRCS_IMGUI} ${HEADERS_IMGUI} ) 25 | 26 | target_link_libraries (imgui glfw glad ${OPENGL_LIBRARIES}) 27 | 28 | set_target_properties(imgui PROPERTIES LINKER_LANGUAGE CXX) 29 | -------------------------------------------------------------------------------- /thirdparty/imgui/imconfig.h: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------------- 2 | // COMPILE-TIME OPTIONS FOR DEAR IMGUI 3 | // Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure. 4 | // You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions. 5 | //----------------------------------------------------------------------------- 6 | // A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/branch with your modifications to imconfig.h) 7 | // B) or add configuration directives in your own file and compile with #define IMGUI_USER_CONFIG "myfilename.h" 8 | // If you do so you need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include 9 | // the imgui*.cpp files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures. 10 | // Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts. 11 | // Call IMGUI_CHECKVERSION() from your .cpp files to verify that the data structures your files are using are matching the ones imgui.cpp is using. 12 | //----------------------------------------------------------------------------- 13 | 14 | #pragma once 15 | 16 | //---- Define assertion handler. Defaults to calling assert(). 17 | //#define IM_ASSERT(_EXPR) MyAssert(_EXPR) 18 | //#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts 19 | 20 | //---- Define attributes of all API symbols declarations, e.g. for DLL under Windows 21 | // Using dear imgui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility. 22 | //#define IMGUI_API __declspec( dllexport ) 23 | //#define IMGUI_API __declspec( dllimport ) 24 | 25 | //---- Don't define obsolete functions/enums names. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names. 26 | //#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS 27 | 28 | //---- Don't implement demo windows functionality (ShowDemoWindow()/ShowStyleEditor()/ShowUserGuide() methods will be empty) 29 | // It is very strongly recommended to NOT disable the demo windows during development. Please read the comments in imgui_demo.cpp. 30 | //#define IMGUI_DISABLE_DEMO_WINDOWS 31 | //#define IMGUI_DISABLE_METRICS_WINDOW 32 | 33 | //---- Don't implement some functions to reduce linkage requirements. 34 | //#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. 35 | //#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] Don't implement default IME handler. Won't use and link with ImmGetContext/ImmSetCompositionWindow. 36 | //#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, ime). 37 | //#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices'). 38 | //#define IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself if you don't want to link with vsnprintf. 39 | //#define IMGUI_DISABLE_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 wrapper so you can implement them yourself. Declare your prototypes in imconfig.h. 40 | //#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). 41 | 42 | //---- Include imgui_user.h at the end of imgui.h as a convenience 43 | //#define IMGUI_INCLUDE_IMGUI_USER_H 44 | 45 | //---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another) 46 | //#define IMGUI_USE_BGRA_PACKED_COLOR 47 | 48 | //---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version 49 | // By default the embedded implementations are declared static and not available outside of imgui cpp files. 50 | //#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" 51 | //#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" 52 | //#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION 53 | //#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION 54 | 55 | //---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4. 56 | // This will be inlined as part of ImVec2 and ImVec4 class declarations. 57 | /* 58 | #define IM_VEC2_CLASS_EXTRA \ 59 | ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \ 60 | operator MyVec2() const { return MyVec2(x,y); } 61 | 62 | #define IM_VEC4_CLASS_EXTRA \ 63 | ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \ 64 | operator MyVec4() const { return MyVec4(x,y,z,w); } 65 | */ 66 | 67 | //---- Using 32-bits vertex indices (default is 16-bits) is one way to allow large meshes with more than 64K vertices. 68 | // Your renderer back-end will need to support it (most example renderer back-ends support both 16/32-bits indices). 69 | // Another way to allow large meshes while keeping 16-bits indices is to handle ImDrawCmd::VtxOffset in your renderer. 70 | // Read about ImGuiBackendFlags_RendererHasVtxOffset for details. 71 | //#define ImDrawIdx unsigned int 72 | 73 | //---- Override ImDrawCallback signature (will need to modify renderer back-ends accordingly) 74 | //struct ImDrawList; 75 | //struct ImDrawCmd; 76 | //typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data); 77 | //#define ImDrawCallback MyImDrawCallback 78 | 79 | //---- Debug Tools 80 | // Use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging. 81 | //#define IM_DEBUG_BREAK IM_ASSERT(0) 82 | //#define IM_DEBUG_BREAK __debugbreak() 83 | // Have the Item Picker break in the ItemAdd() function instead of ItemHoverable() - which is earlier in the code, will catch a few extra items, allow picking items other than Hovered one. 84 | // This adds a small runtime cost which is why it is not enabled by default. 85 | //#define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX 86 | 87 | //---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. 88 | /* 89 | namespace ImGui 90 | { 91 | void MyFunction(const char* name, const MyMatrix44& v); 92 | } 93 | */ 94 | -------------------------------------------------------------------------------- /thirdparty/imgui/imgui_impl_glfw.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Platform Binding for GLFW 2 | // This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan..) 3 | // (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) 4 | 5 | // Implemented features: 6 | // [X] Platform: Clipboard support. 7 | // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. 8 | // [x] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: 3 cursors types are missing from GLFW. 9 | // [X] Platform: Keyboard arrays indexed using GLFW_KEY_* codes, e.g. ImGui::IsKeyPressed(GLFW_KEY_SPACE). 10 | 11 | // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. 12 | // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. 13 | // https://github.com/ocornut/imgui 14 | 15 | // About GLSL version: 16 | // The 'glsl_version' initialization parameter defaults to "#version 150" if NULL. 17 | // Only override if your GL version doesn't handle this GLSL version. Keep NULL if unsure! 18 | 19 | #pragma once 20 | 21 | struct GLFWwindow; 22 | 23 | IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks); 24 | IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks); 25 | IMGUI_IMPL_API void ImGui_ImplGlfw_Shutdown(); 26 | IMGUI_IMPL_API void ImGui_ImplGlfw_NewFrame(); 27 | 28 | // InitXXX function with 'install_callbacks=true': install GLFW callbacks. They will call user's previously installed callbacks, if any. 29 | // InitXXX function with 'install_callbacks=false': do not install GLFW callbacks. You will need to call them yourself from your own GLFW callbacks. 30 | IMGUI_IMPL_API void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods); 31 | IMGUI_IMPL_API void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset); 32 | IMGUI_IMPL_API void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); 33 | IMGUI_IMPL_API void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c); 34 | -------------------------------------------------------------------------------- /thirdparty/imgui/imgui_impl_opengl3.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Renderer for modern OpenGL with shaders / programmatic pipeline 2 | // - Desktop GL: 2.x 3.x 4.x 3 | // - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0) 4 | // This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..) 5 | 6 | // Implemented features: 7 | // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. 8 | // [x] Renderer: Desktop GL only: Support for large meshes (64k+ vertices) with 16-bits indices. 9 | 10 | // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. 11 | // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. 12 | // https://github.com/ocornut/imgui 13 | 14 | // About Desktop OpenGL function loaders: 15 | // Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers. 16 | // Helper libraries are often used for this purpose! Here we are supporting a few common ones (gl3w, glew, glad). 17 | // You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own. 18 | 19 | // About GLSL version: 20 | // The 'glsl_version' initialization parameter should be NULL (default) or a "#version XXX" string. 21 | // On computer platform the GLSL version default to "#version 130". On OpenGL ES 3 platform it defaults to "#version 300 es" 22 | // Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp. 23 | 24 | #pragma once 25 | 26 | // Backend API 27 | IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = NULL); 28 | IMGUI_IMPL_API void ImGui_ImplOpenGL3_Shutdown(); 29 | IMGUI_IMPL_API void ImGui_ImplOpenGL3_NewFrame(); 30 | IMGUI_IMPL_API void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data); 31 | 32 | // (Optional) Called by Init/NewFrame/Shutdown 33 | IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateFontsTexture(); 34 | IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyFontsTexture(); 35 | IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects(); 36 | IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects(); 37 | 38 | // Specific OpenGL versions 39 | //#define IMGUI_IMPL_OPENGL_ES2 // Auto-detected on Emscripten 40 | //#define IMGUI_IMPL_OPENGL_ES3 // Auto-detected on iOS/Android 41 | 42 | // Desktop OpenGL: attempt to detect default GL loader based on available header files. 43 | // If auto-detection fails or doesn't select the same GL loader file as used by your application, 44 | // you are likely to get a crash in ImGui_ImplOpenGL3_Init(). 45 | // You can explicitly select a loader by using '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line. 46 | #if !defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) \ 47 | && !defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) \ 48 | && !defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) \ 49 | && !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM) 50 | #if defined(__has_include) 51 | #if __has_include() 52 | #define IMGUI_IMPL_OPENGL_LOADER_GLEW 53 | #elif __has_include() 54 | #define IMGUI_IMPL_OPENGL_LOADER_GLAD 55 | #elif __has_include() 56 | #define IMGUI_IMPL_OPENGL_LOADER_GL3W 57 | #else 58 | #error "Cannot detect OpenGL loader!" 59 | #endif 60 | #else 61 | #define IMGUI_IMPL_OPENGL_LOADER_GL3W // Default to GL3W 62 | #endif 63 | #endif 64 | 65 | -------------------------------------------------------------------------------- /thirdparty/utilities/drawDebug.h: -------------------------------------------------------------------------------- 1 | #ifndef DRAWDEBUG_H 2 | #define DRAWDEBUG_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) 9 | #include // Initialize with gl3wInit() 10 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) 11 | #include // Initialize with glewInit() 12 | #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) 13 | #include // Initialize with gladLoadGL() 14 | #else 15 | #include IMGUI_IMPL_OPENGL_LOADER_CUSTOM 16 | #endif 17 | 18 | 19 | class DrawDebug { 20 | 21 | public: 22 | static inline void drawArrayPosition(unsigned int nbVertices, float *array, GLenum drawMode, GLenum primitiveDraw = GL_FILL){ 23 | //glPolygonMode(GL_FRONT_AND_BACK,primitiveDraw); 24 | GLuint buffer, vertexArray; 25 | 26 | glGenBuffers(1, &buffer); 27 | glGenVertexArrays(1,&vertexArray); 28 | 29 | // create the VBO associated with the grid (the terrain) 30 | glBindVertexArray(vertexArray); 31 | 32 | glBindBuffer(GL_ARRAY_BUFFER,buffer); // vertices 33 | glBufferData(GL_ARRAY_BUFFER,nbVertices*3*sizeof(float),array,GL_STATIC_DRAW); 34 | glEnableVertexAttribArray(0); 35 | glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,(void *)0); 36 | 37 | glDrawArrays(drawMode,0,nbVertices); 38 | 39 | glBindVertexArray(0); 40 | 41 | glDeleteBuffers(1,&buffer); 42 | glDeleteVertexArrays(1,&vertexArray); 43 | 44 | //glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); 45 | 46 | }; 47 | 48 | }; 49 | 50 | #endif 51 | -------------------------------------------------------------------------------- /thirdparty/utilities/glmCout.h: -------------------------------------------------------------------------------- 1 | #ifndef GLMCOUT_H 2 | #define GLMCOUT_H 3 | 4 | #ifndef GLM_H 5 | #define GLM_H 6 | #include 7 | #include 8 | #include 9 | #include 10 | #endif 11 | 12 | #include 13 | 14 | class GLMCOUT { 15 | public: 16 | static void printMat(glm::mat4 matrix){ 17 | for(unsigned int i=0; i<4; i++){ 18 | std::cout << "[" << matrix[i][0] << ", " << matrix[i][1] << ", " << matrix[i][2] << ", " << matrix[i][3] << "]\n"; 19 | } 20 | } 21 | 22 | static void printVec(glm::vec3 v){ 23 | std::cout << "{" << v.x << ", " << v.y << ", " << v.z << "}"; 24 | } 25 | 26 | static void printVec(glm::vec4 v){ 27 | std::cout << "{" << v.x << ", " << v.y << ", " << v.z << ", " << v.w << "}"; 28 | } 29 | }; 30 | 31 | #endif -------------------------------------------------------------------------------- /thirdparty/utilities/glm_display.h: -------------------------------------------------------------------------------- 1 | #ifndef VOXEL_ENGINE_GLM_DISPLAY_H 2 | #define VOXEL_ENGINE_GLM_DISPLAY_H 3 | 4 | 5 | #ifndef GLM_H 6 | #define GLM_H 7 | #include 8 | #include 9 | #include 10 | #include 11 | #endif 12 | 13 | #include 14 | 15 | 16 | std::ostream & operator<<(std::ostream & out, const glm::vec3& v){ 17 | out << "{" << v.x << ", " << v.y << ", " << v.z << "}"; 18 | return out; 19 | } 20 | 21 | std::ostream & operator<<(std::ostream & out, const glm::vec4& v){ 22 | out << "{" << v.x << ", " << v.y << ", " << v.z << ", " << v.w << "}"; 23 | return out; 24 | } 25 | 26 | std::ostream & operator<<(std::ostream & out, const glm::vec2& v){ 27 | out << "{" << v.x << ", " << v.y << "}"; 28 | return out; 29 | } 30 | 31 | 32 | std::ostream & operator<<(std::ostream & out, const glm::mat4& matrix){ 33 | 34 | for(unsigned int i=0; i<4; i++){ 35 | out << "[" << matrix[i][0] << ", " << matrix[i][1] << ", " << matrix[i][2] << ", " << matrix[i][3] << "]\n"; 36 | } 37 | 38 | return out; 39 | } 40 | 41 | 42 | std::ostream & operator<<(std::ostream & out, const glm::mat3& matrix){ 43 | 44 | for(unsigned int i=0; i<3; i++){ 45 | out << "[" << matrix[i][0] << ", " << matrix[i][1] << ", " << matrix[i][2] << "]\n"; 46 | } 47 | 48 | return out; 49 | } 50 | 51 | #endif --------------------------------------------------------------------------------