├── .gitignore ├── CMakeLists.txt ├── LICENSE ├── README.md ├── bin ├── conf │ └── sim.conf ├── font │ └── font.ttf ├── img │ ├── border.png │ ├── creatureBody.png │ ├── creatureExtra.png │ ├── egg.png │ ├── food.png │ └── meat.png ├── plot │ └── img.p └── shader │ ├── frag.glsl │ ├── grid.glsl │ ├── gridvert.glsl │ ├── menu.glsl │ ├── menuVert.glsl │ ├── vert.glsl │ ├── vite.glsl │ └── viteVert.glsl ├── compile_commands.json ├── inc ├── Buffer.hpp ├── Creature.hpp ├── CreatureData.hpp ├── Egg.hpp ├── EnDex.hpp ├── Environment.hpp ├── Food.hpp ├── Meat.hpp ├── Menu.hpp ├── MenuBar.hpp ├── PhysicsObj.hpp ├── Serializer.hpp ├── Simulation.hpp ├── SimulationRules.hpp ├── ThreadPool.hpp ├── ViteSeg.hpp ├── macro.hpp └── other.hpp ├── lib ├── stb_image.h ├── stb_truetype.h ├── updateAGL.sh └── updateIN.sh ├── linecount.sh └── src ├── Buffer.cpp ├── Creature.cpp ├── CreatureData.cpp ├── Egg.cpp ├── Menu.cpp ├── Simulation.cpp ├── main.cpp └── other.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.pdb 32 | *.raddbg 33 | *.ilk 34 | *.out 35 | *.app 36 | 37 | # AGL library 38 | lib/AGL 39 | 40 | # cmake 41 | build/* 42 | 43 | #ext deps 44 | dependents/* 45 | 46 | *.xcf 47 | .cache 48 | debug 49 | release 50 | 51 | bin/plot/* 52 | !bin/plot/img.p 53 | bin/img/border.png.bak 54 | lib/PHY 55 | lib/IN 56 | simbeta6win32.zip 57 | .vs 58 | .vscode 59 | bin/EvolutionSimulator 60 | bin/READ.txt 61 | bin/creature (copy 1).vt 62 | bin/creature.vt 63 | 64 | lib/stb_image.h 65 | lib/stb_truetype.h 66 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.10) 2 | 3 | project(EvolutionSimulator) 4 | 5 | file(GLOB_RECURSE SRC ./src/*.cpp) 6 | file(GLOB_RECURSE AGL ./lib/AGL/src/*.cpp) 7 | file(GLOB_RECURSE PHY ./lib/PHY/src/*.cpp) 8 | file(GLOB_RECURSE IN ./lib/IN/src/*.cpp) 9 | 10 | set (CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin) 11 | set(CMAKE_EXPORT_COMPILE_COMMANDS ON) 12 | set (CMAKE_CXX_STANDARD 17) 13 | #set(CMAKE_CXX_COMPILER "g++") 14 | 15 | if(WIN32) 16 | find_package(GLEW REQUIRED) 17 | find_package(GLFW3 3.3 REQUIRED) 18 | endif() 19 | 20 | 21 | # set(CMAKE_BUILD_TYPE Debug) # default build 22 | 23 | message(STATUS "CMAKE_BUILD_TYPE = ${CMAKE_BUILD_TYPE}") 24 | 25 | if(CMAKE_BUILD_TYPE MATCHES Debug) 26 | set (CMAKE_CXX_FLAGS "-g -fsanitize=address") 27 | message(STATUS "Building with debug flags") 28 | elseif(CMAKE_BUILD_TYPE MATCHES Release) 29 | set (CMAKE_CXX_FLAGS "-Ofast -flto=auto") 30 | message(STATUS "Building with release flags") 31 | endif() 32 | 33 | add_executable(EvolutionSimulator ${SRC} ${AGL} ${PHY} ${IN}) 34 | 35 | if(LINUX) 36 | target_link_libraries(EvolutionSimulator -lX11 -lGL -lGLEW -lSOIL -lfreetype) 37 | target_include_directories(EvolutionSimulator PUBLIC "/usr/include/freetype2") 38 | include_directories("./lib") 39 | endif() 40 | 41 | if(WIN32) 42 | #target_link_libraries(EvolutionSimulator "C:\\soil\\lib\\libsoil.a" "C:\\freetype\\objs\\libfreetype.dll" opengl32) 43 | target_link_libraries(EvolutionSimulator opengl32) 44 | #include_directories("C:\\Users\\$ENV{USERNAME}\\Documents\\vcpkg\\installed\\x64-mingw-dynamic\\include") 45 | target_include_directories(EvolutionSimulator 46 | PUBLIC ${GLEW_INCLUDE_DIRS} 47 | PUBLIC "./lib") 48 | target_link_libraries(EvolutionSimulator glfw ) 49 | #target_link_libraries(EvolutionSimulator glew ) 50 | target_link_libraries(EvolutionSimulator ${GLEW_STATIC_LIBRARY} ) 51 | endif() 52 | 53 | #target_include_directories(EvolutionSimulator INTERFACE ) 54 | #link_libraries(${GLEW_LIBRARIES}) 55 | #target_include_directories(EvolutionSimulator ) 56 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EvolutionSimulator 1.2 2 | 3 | ## What is this 4 | This project was inspired by [Bibits](https://www.youtube.com/@TheBibitesDigitalLife) and [this video](https://www.youtube.com/watch?v=N3tRFayqVtk). It creates some creatures with simulated brains (with a NEAT like neural network) that live and die with the successfull ones (living long enough to reproduce) being able to pass down their genetic information to the next generation and so on. 5 | 6 | ## How to compile 7 | Run 8 | ```bash 9 | # download libraries - only needed to be done once 10 | cd lib 11 | ./updateAGL.sh 12 | ./updatePHY.sh 13 | ./updateIN.sh 14 | cd .. 15 | 16 | # compile 17 | cmake -S . -B build -DCMAKE_BUILD_TYPE=Release 18 | cmake --build build 19 | 20 | ``` 21 | 22 | ## Roadmap of stuff done 23 | 1.0 - Basics, Initial release
24 | 1.1 - Predation, digestion and tweaks
25 | 1.1.1 - Windows port, UI overhaul
26 | 1.1.2 - AI Overhaul (Policy Gradients)
27 | 1.1.3 - The Big Optimise/Optimize
28 | 1.2 - Body overhaul
29 | 30 | ## TODO 31 | - Add a tree diagram of how the creatures evolved 32 | - Evolving plants (probably make plants evolve into creatures) 33 | - Saving and loading 34 | - Add a help menu or something to make understanding the UI easier (tooltip on hover?) 35 | -------------------------------------------------------------------------------- /bin/conf/sim.conf: -------------------------------------------------------------------------------- 1 | imulationRules : 2 | size : 3 | x = 1920 4 | y = 1080 5 | gridResolution : 6 | x = 1 7 | y = 1 8 | startingCreatures = 1 9 | foodCap = 10 10 | energyCostMultiplier = 0.0003 11 | threads = 20 12 | learningRate = 0.1 13 | memory = 240 14 | brainMutation = 3 15 | bodyMutation = 50 16 | exploration = 0.5 17 | vaporize = 0.9 18 | startBody & 19 | [] : 20 | size : 21 | x = 24 22 | y = 24 23 | branch & 24 | [] : 25 | size : 26 | x = 10 27 | y = 18 28 | branch & 29 | [] : 30 | size : 31 | x = 4 32 | y = 18 33 | branch & 34 | startBrain & 35 | [] : 36 | startNode = 1 37 | endNode = 4 38 | weight = 1 39 | id = -1 40 | valid = 1 41 | exists = 1 42 | maxConnections = 7 43 | -------------------------------------------------------------------------------- /bin/font/font.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4t-2/EvolutionSimulator/fc6cf14f7629a9e0377a473f8768ab6347debef6/bin/font/font.ttf -------------------------------------------------------------------------------- /bin/img/border.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4t-2/EvolutionSimulator/fc6cf14f7629a9e0377a473f8768ab6347debef6/bin/img/border.png -------------------------------------------------------------------------------- /bin/img/creatureBody.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4t-2/EvolutionSimulator/fc6cf14f7629a9e0377a473f8768ab6347debef6/bin/img/creatureBody.png -------------------------------------------------------------------------------- /bin/img/creatureExtra.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4t-2/EvolutionSimulator/fc6cf14f7629a9e0377a473f8768ab6347debef6/bin/img/creatureExtra.png -------------------------------------------------------------------------------- /bin/img/egg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4t-2/EvolutionSimulator/fc6cf14f7629a9e0377a473f8768ab6347debef6/bin/img/egg.png -------------------------------------------------------------------------------- /bin/img/food.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4t-2/EvolutionSimulator/fc6cf14f7629a9e0377a473f8768ab6347debef6/bin/img/food.png -------------------------------------------------------------------------------- /bin/img/meat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4t-2/EvolutionSimulator/fc6cf14f7629a9e0377a473f8768ab6347debef6/bin/img/meat.png -------------------------------------------------------------------------------- /bin/plot/img.p: -------------------------------------------------------------------------------- 1 | sizex=1920 2 | sizey=1080/2 3 | 4 | set term png size sizex, sizey 5 | 6 | set output "plot.png" 7 | plot "neat.txt" with lines, "rl.txt" with lines, "both.txt" with lines 8 | -------------------------------------------------------------------------------- /bin/shader/frag.glsl: -------------------------------------------------------------------------------- 1 | #version 330 core 2 | 3 | in vec2 UVcoord; 4 | in vec4 fragColor; 5 | 6 | out vec4 color; 7 | 8 | uniform sampler2D textureSampler; 9 | 10 | void main() 11 | { 12 | color = texture(textureSampler, UVcoord) * fragColor; 13 | } 14 | -------------------------------------------------------------------------------- /bin/shader/grid.glsl: -------------------------------------------------------------------------------- 1 | #version 330 core 2 | 3 | in vec2 UVcoord; 4 | in vec4 fragColor; 5 | in vec4 fragPos; 6 | 7 | out vec4 color; 8 | 9 | uniform float scale; 10 | uniform sampler2D textureSampler; 11 | 12 | void main() 13 | { 14 | color = fragColor; 15 | 16 | const int gridSize = 100; 17 | 18 | if(mod(fragPos.x+(.5*scale), gridSize) < (1*scale) || mod(fragPos.y+(.5*scale), gridSize) < (1*scale)) 19 | { 20 | color = vec4(0, 0, 0, 1); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /bin/shader/gridvert.glsl: -------------------------------------------------------------------------------- 1 | #version 330 core 2 | 3 | layout(location = 0) in vec3 position; 4 | layout(location = 1) in vec2 vertexUV; 5 | 6 | uniform mat4 transform; 7 | uniform mat4 mvp; 8 | uniform vec3 shapeColor; 9 | uniform mat4 textureTransform; 10 | 11 | out vec2 UVcoord; 12 | out vec4 fragColor; 13 | out vec4 fragPos; 14 | 15 | void main() 16 | { 17 | UVcoord = vec2((textureTransform * vec4(vertexUV, 0, 1)).xy); 18 | 19 | fragColor = vec4(shapeColor, 1); 20 | 21 | fragPos = transform * vec4(position, 1); 22 | 23 | gl_Position = mvp * transform * vec4(position, 1); 24 | } 25 | 26 | 27 | -------------------------------------------------------------------------------- /bin/shader/menu.glsl: -------------------------------------------------------------------------------- 1 | #version 330 core 2 | #define PI 3.1415926535897932384626433832795 3 | 4 | in vec2 UVcoord; 5 | in vec4 fragPos; 6 | in vec2 scale; 7 | in vec4 fragColor; 8 | flat in int typeM; 9 | 10 | out vec4 color; 11 | 12 | uniform sampler2D textureSampler; 13 | 14 | void main() 15 | { 16 | if(typeM == 0) 17 | { 18 | if(fragPos.x <= 1 || fragPos.y <= 1) 19 | { 20 | color = vec4(1, 1, 1, 1); 21 | } else if(fragPos.x >= (scale.x - 1) || fragPos.y >= (scale.y - 1)) 22 | { 23 | color = vec4(128./255, 128./255, 128./255, 1); 24 | } else 25 | { 26 | color = vec4(192./255, 192./255, 192./255, 1); 27 | } 28 | } else if(typeM == 1) 29 | { 30 | if(fragPos.x >= (scale.x - 1) || fragPos.y >= (scale.y - 1)) 31 | { 32 | color = vec4(0, 0, 0, 1); 33 | } else if(fragPos.x <= 1 || fragPos.y <= 1) 34 | { 35 | color = vec4(1, 1, 1, 1); 36 | } else if(fragPos.x >= (scale.x - 2) || fragPos.y >= (scale.y - 2)) 37 | { 38 | color = vec4(128./255, 128./255, 128./255, 1); 39 | } else if(fragPos.x <= 2 || fragPos.y <= 2) 40 | { 41 | color = vec4(223./255, 223./255, 223./255, 1); 42 | } else 43 | { 44 | color = vec4(192./255, 192./255, 192./255, 1); 45 | } 46 | } else if(typeM == 2) 47 | { 48 | if(fragPos.x <= 1 || fragPos.y <= 1) 49 | { 50 | color = vec4(128./255, 128./255, 128./255, 1); 51 | } else if(fragPos.x >= (scale.x - 1) || fragPos.y >= (scale.y - 1)) 52 | { 53 | color = vec4(1, 1, 1, 1); 54 | } else 55 | { 56 | color = vec4(192./255, 192./255, 192./255, 1); 57 | } 58 | } else if(typeM == 3) 59 | { 60 | if(fragPos.x <= 1 || fragPos.y <= 1) 61 | { 62 | color = vec4(0, 0, 0, 1); 63 | } else if(fragPos.x >= (scale.x - 1) || fragPos.y >= (scale.y - 1)) 64 | { 65 | color = vec4(1, 1, 1, 1); 66 | } else if(fragPos.x <= 2 || fragPos.y <= 2) 67 | { 68 | color = vec4(128./255, 128./255, 128./255, 1); 69 | } else if(fragPos.x >= (scale.x - 2) || fragPos.y >= (scale.y - 2)) 70 | { 71 | color = vec4(223./255, 223./255, 223./255, 1); 72 | } else 73 | { 74 | color = vec4(192./255, 192./255, 192./255, 1); 75 | } 76 | } else if(typeM == 4) 77 | { 78 | if((fragPos.x >= (scale.x-1) && fragPos.y <= 1) || (fragPos.x <= 1 && fragPos.y >= (scale.y-1))) 79 | { 80 | color = vec4(0, 0, 0, 0); 81 | } else if(fragPos.x <= 1 || fragPos.y <= 1) 82 | { 83 | color = vec4(128./255, 128./255, 128./255, 1); 84 | } else if(fragPos.x >= (scale.x - 1) || fragPos.y >= (scale.y - 1)) 85 | { 86 | color = vec4(1, 1, 1, 1); 87 | } else if(fragPos.y <= 2) 88 | { 89 | color = vec4(192./255, 192./255, 192./255, 1); 90 | } else if(fragPos.y >= (scale.y - 2)) 91 | { 92 | color = vec4(192./255, 192./255, 192./255, 1); 93 | } else 94 | { 95 | color = vec4(1, 1, 1, 1); 96 | } 97 | } else if(typeM == 5) 98 | { 99 | if(fragPos.x <= 1 || fragPos.x >= (scale.x - 1) || fragPos.y <= 1 || fragPos.y >= (scale.y-1)) 100 | { 101 | color = vec4(0, 0, 0, 1); 102 | } else if(fragPos.x <= 2 || fragPos.x >= (scale.x - 2) || fragPos.y <= 2 || fragPos.y >= (scale.y-2)) 103 | { 104 | color = vec4(128./255, 128./255, 128./255, 1); 105 | } else 106 | { 107 | color = vec4(192./255, 192./255, 192./255, 1); 108 | } 109 | } 110 | 111 | color *= vec4(.25, .25, .25, 1); 112 | } 113 | -------------------------------------------------------------------------------- /bin/shader/menuVert.glsl: -------------------------------------------------------------------------------- 1 | #version 330 core 2 | 3 | layout(location = 0) in vec3 position; 4 | layout(location = 1) in vec2 vertexUV; 5 | 6 | uniform mat4 transform; 7 | uniform mat4 mvp; 8 | uniform vec3 shapeColor; 9 | uniform mat4 textureTransform; 10 | uniform float scaleX; 11 | uniform float scaleY; 12 | uniform int type; 13 | 14 | out vec2 UVcoord; 15 | out vec4 fragColor; 16 | out vec4 fragPos; 17 | out vec2 scale; 18 | flat out int typeM; 19 | 20 | void main() 21 | { 22 | UVcoord = vec2((textureTransform * vec4(vertexUV, 0, 1)).xy); 23 | 24 | fragPos = vec4(position, 1); 25 | fragPos.x *= scaleX; 26 | fragPos.y *= scaleY; 27 | 28 | scale = vec2(scaleX, scaleY); 29 | 30 | fragColor = vec4(shapeColor, 1); 31 | 32 | gl_Position = mvp * transform * vec4(position, 1); 33 | 34 | typeM = type; 35 | } 36 | 37 | 38 | -------------------------------------------------------------------------------- /bin/shader/vert.glsl: -------------------------------------------------------------------------------- 1 | #version 330 core 2 | 3 | layout(location = 0) in vec3 position; 4 | layout(location = 1) in vec2 vertexUV; 5 | 6 | uniform mat4 transform; 7 | uniform mat4 mvp; 8 | uniform vec3 shapeColor; 9 | uniform mat4 textureTransform; 10 | 11 | out vec2 UVcoord; 12 | out vec4 fragColor; 13 | 14 | void main() 15 | { 16 | UVcoord = vec2((textureTransform * vec4(vertexUV, 0, 1)).xy); 17 | 18 | fragColor = vec4(shapeColor, 1); 19 | 20 | gl_Position = mvp * transform * vec4(position, 1); 21 | } 22 | 23 | 24 | -------------------------------------------------------------------------------- /bin/shader/vite.glsl: -------------------------------------------------------------------------------- 1 | #version 330 core 2 | #define PI 3.1415926535897932384626433832795 3 | 4 | in vec2 UVcoord; 5 | in vec4 fragPos; 6 | in vec2 scale; 7 | in vec4 fragColor; 8 | 9 | out vec4 color; 10 | 11 | uniform sampler2D textureSampler; 12 | uniform float isJoint; 13 | uniform float time; 14 | 15 | void main() 16 | { 17 | vec2 pixSize = scale / 2; 18 | if(isJoint < .5) 19 | { 20 | if(fragPos.x <= 1 || fragPos.x >= (scale.x - 1) || fragPos.y <= 1 || fragPos.y >= (scale.y-1)) 21 | { 22 | color = vec4(192./255, 192./255, 192./255, 1) * fragColor; 23 | } else 24 | { 25 | float start = 130; 26 | float end = (100 * (sin(time / 30) / 2 + .5)) + 155; 27 | 28 | vec2 sin = sin((floor(UVcoord * pixSize) * pixSize/(pixSize-1)) / pixSize * PI); 29 | float val = sin.x < sin.y ? sin.x : sin.y; 30 | 31 | val = (val * (end - start) + start) / 255; 32 | 33 | color = vec4(fragColor.xyz * val, fragColor.w); 34 | } 35 | } else 36 | { 37 | color = vec4(192./255, 192./255, 192./255, 1) * fragColor; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /bin/shader/viteVert.glsl: -------------------------------------------------------------------------------- 1 | #version 330 core 2 | 3 | layout(location = 0) in vec3 position; 4 | layout(location = 1) in vec2 vertexUV; 5 | 6 | uniform mat4 transform; 7 | uniform mat4 mvp; 8 | uniform vec3 shapeColor; 9 | uniform mat4 textureTransform; 10 | uniform float scaleX; 11 | uniform float scaleY; 12 | 13 | uniform mat4 top; 14 | uniform mat4 bottom; 15 | 16 | out vec2 UVcoord; 17 | out vec4 fragColor; 18 | out vec4 fragPos; 19 | out vec2 scale; 20 | 21 | void main() 22 | { 23 | UVcoord = vec2((textureTransform * vec4(vertexUV, 0, 1)).xy); 24 | 25 | fragPos = vec4(position, 1); 26 | fragPos.x *= scaleX; 27 | fragPos.y *= scaleY; 28 | 29 | scale = vec2(scaleX, scaleY); 30 | 31 | fragColor = vec4(shapeColor, 1); 32 | 33 | vec4 pos = vec4(position, 1); 34 | pos = ((top * pos) * (1 - position.y) + (bottom * pos) * (position.y)); 35 | 36 | gl_Position = mvp * transform * pos; 37 | } 38 | 39 | 40 | -------------------------------------------------------------------------------- /compile_commands.json: -------------------------------------------------------------------------------- 1 | ./build/compile_commands.json -------------------------------------------------------------------------------- /inc/Buffer.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | class Buffer 6 | { 7 | public: 8 | unsigned char *data = nullptr; 9 | int size; 10 | 11 | Buffer(int size); 12 | Buffer(const Buffer &buffer); 13 | Buffer(); 14 | ~Buffer(); 15 | 16 | void operator=(Buffer &buffer); 17 | 18 | void printBits(); 19 | void mutate(int chance) 20 | { 21 | 22 | return; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /inc/Creature.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include "CreatureData.hpp" 5 | #include "Food.hpp" 6 | #include "Meat.hpp" 7 | #include "SimulationRules.hpp" 8 | #include "other.hpp" 9 | #include "macro.hpp" 10 | #include "Environment.hpp" 11 | #include "PhysicsObj.hpp" 12 | 13 | #define sizeToHealth(size) 100*size*size*size 14 | 15 | struct Memory 16 | { 17 | std::vector state; 18 | std::vector action; 19 | float reward; 20 | }; 21 | 22 | struct RelPos 23 | { 24 | float rotation = 0; 25 | float distance = 0; 26 | }; 27 | 28 | class Creature : public PhysicsObj 29 | { 30 | public: 31 | bool eating = false; 32 | bool layingEgg = false; 33 | 34 | bool incubating = 0; 35 | 36 | // sight + (speed^2)(size^3) 37 | float energy = 0; 38 | float health = 0; 39 | int life = 0; 40 | float maxEnergy = 0; 41 | float maxHealth = 0; 42 | int maxLife = 0; 43 | 44 | float maxBiomass = 0; 45 | float biomass = 0; 46 | float energyDensity = 0; 47 | 48 | float eggTotalCost = 0; 49 | float eggHealthCost = 0; 50 | float eggEnergyCost = 0; 51 | float eggDesposit = 0; 52 | 53 | CreatureData creatureData; 54 | 55 | std::vector segments; 56 | 57 | Creature(); 58 | ~Creature(); 59 | 60 | void clear(); 61 | 62 | void learnBrain(SimulationRules &simRules); 63 | void updateNetwork(); 64 | void updateActions(); 65 | }; 66 | -------------------------------------------------------------------------------- /inc/CreatureData.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Serializer.hpp" 4 | #include 5 | #include 6 | 7 | #undef e//; 8 | 9 | class SegmentData 10 | { 11 | public: 12 | agl::Vec size; 13 | std::vector branch; 14 | }; 15 | 16 | class CreatureData 17 | { 18 | public: 19 | in::NetworkStructure *netStr = nullptr; 20 | 21 | float sight; // 0 - 2 22 | int hue; // 0 - 359 23 | 24 | float startEnergy; 25 | float preference; // 1 = plant, -1 = meat 26 | float metabolism; 27 | 28 | bool useNEAT; 29 | bool usePG; 30 | 31 | std::vector sd; 32 | 33 | CreatureData(); 34 | CreatureData(float sight, int hue, std::vector &segs, std::vector &cons, int maxCon); 35 | CreatureData(const CreatureData &creatureData); 36 | ~CreatureData(); 37 | 38 | void operator=(CreatureData &creatureData); 39 | 40 | static int totalSegJoints(std::vector &segs); 41 | }; 42 | 43 | template void recurse(T processor, agl::Vec &v, std::string name = "null") 44 | { 45 | processor.process(name, v); 46 | 47 | RECSER(v.x); 48 | RECSER(v.y); 49 | } 50 | 51 | template void recurse(T processor, SegmentData &v, std::string name = "null") 52 | { 53 | processor.process(name, v); 54 | 55 | RECSER(v.size); 56 | RECSER(v.branch); 57 | } 58 | -------------------------------------------------------------------------------- /inc/Egg.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Creature.hpp" 4 | 5 | class Egg 6 | { 7 | public: 8 | agl::Vec position; 9 | bool exists; 10 | CreatureData creatureData; 11 | int timeleft = 0; 12 | 13 | Egg() 14 | { 15 | } 16 | 17 | void setup(CreatureData &creatureData); 18 | void update(); 19 | void clear(); 20 | }; 21 | -------------------------------------------------------------------------------- /inc/EnDex.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | template class TupleList 9 | { 10 | private: 11 | std::tuple...> tup; 12 | 13 | public: 14 | template std::list &getList() 15 | { 16 | return std::get>(tup); 17 | } 18 | }; 19 | 20 | template class EnDex 21 | { 22 | private: 23 | template void privateView(std::function &func) 24 | { 25 | if constexpr (std::is_base_of_v || std::is_same_v) 26 | { 27 | std::list &list = entityList.template getList(); 28 | 29 | for (auto it = list.begin(); it != list.end(); it++) 30 | { 31 | func(*(T *)&*it); 32 | } 33 | } 34 | 35 | if constexpr (sizeof...(Us) > 0) 36 | { 37 | privateView(func); 38 | } 39 | } 40 | 41 | template 42 | void loopThroughU(std::function &func) 43 | { 44 | if constexpr (std::is_base_of_v || std::is_same_v) 45 | { 46 | if constexpr (!std::is_same_v) 47 | { 48 | std::list &listV = entityList.template getList(); 49 | std::list &listR = entityList.template getList(); 50 | 51 | for (auto &v : listV) 52 | { 53 | for (auto &r : listR) 54 | { 55 | func(*(T *)&r, *(V *)&v); 56 | } 57 | } 58 | } 59 | else 60 | { 61 | std::list &list1 = entityList.template getList(); 62 | 63 | for (auto it1 = list1.begin(); it1 != list1.end(); it1++) 64 | { 65 | for (auto it2 = std::next(it1, 1); it2 != list1.end(); it2++) 66 | { 67 | func(*(V *)&*it1, *(V *)&*it2); 68 | } 69 | } 70 | } 71 | } 72 | 73 | if constexpr (sizeof...(Vs) > 0) 74 | { 75 | loopThroughU(func); 76 | } 77 | } 78 | 79 | template 80 | void privateInteract(std::function &func) 81 | { 82 | if constexpr (std::is_base_of_v || std::is_same_v) 83 | { 84 | loopThroughU(func); 85 | } 86 | 87 | if constexpr (sizeof...(Vs) > 0) 88 | { 89 | privateInteract(func); 90 | } 91 | } 92 | 93 | public: 94 | TupleList entityList; 95 | 96 | template T &addEntity() 97 | { 98 | entityList.template getList().emplace_back(); 99 | 100 | return entityList.template getList().back(); 101 | } 102 | 103 | template void view(std::function func) 104 | { 105 | privateView(func); 106 | } 107 | 108 | template void interact(std::function func) 109 | { 110 | privateInteract(func); 111 | } 112 | 113 | template void removeEntity(typename std::list::iterator it) 114 | { 115 | entityList.template getList().erase(it); 116 | } 117 | 118 | template void removeEntity(typename std::list::iterator it, std::function func) 119 | { 120 | func(*it); 121 | entityList.template getList().erase(it); 122 | } 123 | 124 | template std::list &getList() 125 | { 126 | return entityList.template getList(); 127 | } 128 | }; 129 | -------------------------------------------------------------------------------- /inc/Environment.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | /* 3 | #include "ThreadPool.hpp" 4 | #include "macro.hpp" 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | class BaseEntity 17 | { 18 | public: 19 | 20 | BaseEntity(bool &exists, agl::Vec &position) 21 | { 22 | } 23 | 24 | virtual ~BaseEntity() 25 | { 26 | } 27 | }; 28 | 29 | class DoNotUse : public BaseEntity 30 | { 31 | public: 32 | DoNotUse(bool &exists, agl::Vec &position) : BaseEntity(exists, position) 33 | { 34 | } 35 | }; 36 | 37 | template class Signature 38 | { 39 | }; 40 | 41 | template class Entity : public DoNotUse, public T... 42 | { 43 | private: 44 | public: 45 | Entity(bool &exists, agl::Vec &position) : DoNotUse(exists, position), T(exists, position)... 46 | { 47 | } 48 | 49 | virtual ~Entity() 50 | { 51 | } 52 | }; 53 | 54 | class Environment 55 | { 56 | private: 57 | template 58 | inline void execGridThing(agl::Vec &gridPosition, std::function &func, 59 | std::function &distFunc) 60 | { 61 | auto hashT = typeid(O).hash_code(); 62 | auto hashU = typeid(E).hash_code(); 63 | auto &listT = grid[gridPosition.x][gridPosition.y][hashT].list; 64 | for (auto it = listT.begin(); it != listT.end(); it++) 65 | { 66 | T *addressT = (O *)(DoNotUse *)*it; 67 | 68 | float distance = distFunc(*addressT); 69 | 70 | agl::Vec startGrid = 71 | toGridPosition({(*it)->position.x - distance, (*it)->position.y - distance}) - gridPosition; 72 | agl::Vec endGrid = 73 | toGridPosition({(*it)->position.x + distance, (*it)->position.y + distance}) - gridPosition; 74 | 75 | if constexpr (!oneWay) 76 | { 77 | for (int y = startGrid.y; y <= -1; y++) 78 | { 79 | for (int x = startGrid.x; x <= endGrid.x; x++) 80 | { 81 | grid[gridPosition.x + x][gridPosition.y + y][hashU].mtx.lock(); 82 | grid[gridPosition.x][gridPosition.y][hashT].mtx.lock(); 83 | gridUpdate(func, gridPosition, {x, y}, addressT, it); 84 | grid[gridPosition.x][gridPosition.y][hashT].mtx.unlock(); 85 | grid[gridPosition.x + x][gridPosition.y + y][hashU].mtx.unlock(); 86 | } 87 | } 88 | 89 | for (int x = startGrid.x; x <= -1; x++) 90 | { 91 | grid[gridPosition.x + x][gridPosition.y + 0][hashU].mtx.lock(); 92 | grid[gridPosition.x][gridPosition.y][hashT].mtx.lock(); 93 | gridUpdate(func, gridPosition, {x, 0}, addressT, it); 94 | grid[gridPosition.x][gridPosition.y][hashT].mtx.unlock(); 95 | grid[gridPosition.x + x][gridPosition.y + 0][hashU].mtx.unlock(); 96 | } 97 | } 98 | 99 | if (hashT > hashU) 100 | { 101 | grid[gridPosition.x][gridPosition.y][hashT].mtx.lock(); 102 | grid[gridPosition.x][gridPosition.y][hashU].mtx.lock(); 103 | } 104 | else if (hashT < hashU) 105 | { 106 | grid[gridPosition.x][gridPosition.y][hashU].mtx.lock(); 107 | grid[gridPosition.x][gridPosition.y][hashT].mtx.lock(); 108 | } 109 | else 110 | { 111 | grid[gridPosition.x][gridPosition.y][hashT].mtx.lock(); 112 | } 113 | if (hashT == hashU && oneWay) 114 | { 115 | gridUpdate(func, gridPosition, {0, 0}, addressT, it); 116 | } 117 | else 118 | { 119 | gridUpdate(func, gridPosition, {0, 0}, addressT, it); 120 | } 121 | 122 | if (hashT > hashU) 123 | { 124 | grid[gridPosition.x][gridPosition.y][hashT].mtx.unlock(); 125 | grid[gridPosition.x][gridPosition.y][hashU].mtx.unlock(); 126 | } 127 | else if (hashT < hashU) 128 | { 129 | grid[gridPosition.x][gridPosition.y][hashU].mtx.unlock(); 130 | grid[gridPosition.x][gridPosition.y][hashT].mtx.unlock(); 131 | } 132 | else 133 | { 134 | grid[gridPosition.x][gridPosition.y][hashT].mtx.unlock(); 135 | } 136 | 137 | for (int x = 1; x <= endGrid.x; x++) 138 | { 139 | grid[gridPosition.x][gridPosition.y][hashT].mtx.lock(); 140 | grid[gridPosition.x + x][gridPosition.y + 0][hashU].mtx.lock(); 141 | gridUpdate(func, gridPosition, {x, 0}, addressT, it); 142 | grid[gridPosition.x + x][gridPosition.y + 0][hashU].mtx.unlock(); 143 | grid[gridPosition.x][gridPosition.y][hashT].mtx.unlock(); 144 | } 145 | for (int y = 1; y <= endGrid.y; y++) 146 | { 147 | for (int x = startGrid.x; x <= endGrid.x; x++) 148 | { 149 | grid[gridPosition.x][gridPosition.y][hashT].mtx.lock(); 150 | grid[gridPosition.x + x][gridPosition.y + y][hashU].mtx.lock(); 151 | gridUpdate(func, gridPosition, {x, y}, addressT, it); 152 | grid[gridPosition.x + x][gridPosition.y + y][hashU].mtx.unlock(); 153 | grid[gridPosition.x][gridPosition.y][hashT].mtx.unlock(); 154 | } 155 | } 156 | } 157 | } 158 | 159 | // loops through entity 2 160 | template 162 | inline void threadFunc2(agl::Vec &pos, std::function &func, 163 | std::function &distFunc) 164 | { 165 | if constexpr (!skip) 166 | { 167 | if constexpr (flip) 168 | { 169 | if constexpr (std::is_base_of_v || std::is_same_v) 170 | { 171 | execGridThing(pos, func, distFunc); 172 | } 173 | } 174 | else 175 | { 176 | if constexpr (std::is_base_of_v || std::is_same_v) 177 | { 178 | execGridThing(pos, func, distFunc); 179 | } 180 | } 181 | } 182 | 183 | if constexpr (sizeof...(Es) > 0) 184 | { 185 | threadFunc2(pos, func, distFunc); 186 | } 187 | } 188 | 189 | // loops through entity 1 190 | template 191 | inline void threadFunc1(agl::Vec &pos, std::function func, 192 | std::function distFunc) 193 | { 194 | if constexpr (std::is_base_of_v || std::is_same_v) 195 | { 196 | threadFunc2(pos, func, distFunc); 197 | } 198 | if constexpr (std::is_base_of_v || std::is_same_v) 199 | { 200 | if constexpr (std::is_base_of_v || std::is_same_v) 201 | { 202 | threadFunc2(pos, func, distFunc); 203 | } 204 | else 205 | { 206 | threadFunc2(pos, func, distFunc); 207 | } 208 | } 209 | 210 | if constexpr (sizeof...(Es) > 0) 211 | { 212 | threadFunc1(pos, func, distFunc); 213 | } 214 | } 215 | 216 | template 217 | void digestTupleThreadFunc(std::tuple *e, std::function func, 218 | std::function dist, agl::Vec &pos) 219 | { 220 | threadFunc1(pos, func, dist); 221 | } 222 | 223 | template 224 | inline void threadFunc0(agl::Vec pos, Funcs funcs) 225 | { 226 | digestTupleThreadFunc((Entis *)nullptr, std::get(funcs), std::get(funcs), pos); 227 | 228 | if constexpr (i < (std::tuple_size::value - 2)) 229 | { 230 | threadFunc0(pos, funcs); 231 | } 232 | } 233 | 234 | template 236 | inline void gridUpdate(std::function func, agl::Vec gridPosition, 237 | agl::Vec gridOffset, T *addressT, std::list::iterator &it1) 238 | { 239 | auto &list2 = 240 | getListInGrid({gridOffset.x + gridPosition.x, gridOffset.y + gridPosition.y}, typeid(E).hash_code()); 241 | 242 | std::list::iterator it2 = sameGrid ? std::next(it1, 1) : list2.begin(); 243 | 244 | for (; *it2 != *list2.end(); it2++) 245 | { 246 | U *addressU = (E *)(DoNotUse *)*it2; 247 | 248 | if constexpr (!sameGrid && std::is_same()) 249 | { 250 | if ((void *)addressU == (void *)addressT) 251 | { 252 | continue; 253 | } 254 | } 255 | 256 | func(*addressT, *addressU); 257 | 258 | if constexpr (mirror) 259 | { 260 | func(*addressU, *addressT); 261 | } 262 | } 263 | } 264 | 265 | template constexpr static P testFunc(std::function) 266 | { 267 | return; 268 | } 269 | 270 | template static void loopThrougFuncs(T &entitiy, F func, Fs... funcs) 271 | { 272 | using functype = decltype(testFunc(std::function(func))); 273 | 274 | if constexpr (std::is_base_of_v || std::is_same_v) 275 | { 276 | func(entitiy); 277 | } 278 | 279 | if constexpr (sizeof...(Fs) > 0) 280 | { 281 | loopThrougFuncs(entitiy, funcs...); 282 | } 283 | } 284 | 285 | public: 286 | struct GridCell 287 | { 288 | std::list list; 289 | std::mutex mtx; 290 | }; 291 | 292 | std::map> entityList; 293 | agl::Vec size; 294 | agl::Vec gridResolution; 295 | std::vector>> grid; 296 | ThreadPool pool; 297 | agl::Vec *randomPosition; 298 | 299 | void *selected = nullptr; 300 | 301 | Environment() : pool(THREADS) 302 | { 303 | } 304 | 305 | void setThreads(int threads) 306 | { 307 | pool.ThreadPool::~ThreadPool(); 308 | new (&pool) ThreadPool(threads); 309 | } 310 | 311 | void setupGrid(agl::Vec size, agl::Vec gridResolution) 312 | { 313 | this->size = size; 314 | this->gridResolution = gridResolution; 315 | 316 | grid.resize(gridResolution.x); 317 | for (auto &vec : grid) 318 | { 319 | vec.resize(gridResolution.y); 320 | } 321 | 322 | randomPosition = new agl::Vec[gridResolution.x * gridResolution.y]; 323 | 324 | int index = 0; 325 | 326 | if (size.y > size.x) 327 | { 328 | for (int y = 0; y < gridResolution.y; y++) 329 | { 330 | for (int x = 0; x < gridResolution.x; x++) 331 | { 332 | randomPosition[index] = {x, y}; 333 | index++; 334 | } 335 | } 336 | } 337 | else 338 | { 339 | for (int x = 0; x < gridResolution.x; x++) 340 | { 341 | for (int y = 0; y < gridResolution.y; y++) 342 | { 343 | randomPosition[index] = {x, y}; 344 | index++; 345 | } 346 | } 347 | } 348 | } 349 | 350 | template T &addEntity() 351 | { 352 | std::size_t hash = typeid(T).hash_code(); 353 | 354 | T *t = new T(); 355 | 356 | t->exists = true; 357 | entityList[hash].emplace_back((BaseEntity *)(DoNotUse *)t); 358 | 359 | return *t; 360 | } 361 | 362 | template std::list &getList() 363 | { 364 | return entityList[typeid(T).hash_code()]; 365 | } 366 | 367 | template 368 | inline void view(std::function::iterator &)> func) 369 | { 370 | if constexpr (std::is_base_of_v || std::is_same_v) 371 | { 372 | std::size_t hashT = typeid(T).hash_code(); 373 | 374 | auto &list = entityList[hashT]; 375 | 376 | for (auto it = list.begin(); it != list.end(); it++) 377 | { 378 | Search *add = (T *)(DoNotUse *)*it; 379 | 380 | func(*add, it); 381 | } 382 | } 383 | 384 | if constexpr (sizeof...(Ts) > 0) 385 | { 386 | view(func); 387 | } 388 | } 389 | 390 | template 391 | inline void view(std::function::iterator &)> func, 392 | agl::Vec start, agl::Vec end) 393 | { 394 | if constexpr (std::is_base_of_v || std::is_same_v) 395 | { 396 | for (int x = start.x; x <= end.x; x++) 397 | { 398 | for (int y = start.y; y <= end.y; y++) 399 | { 400 | std::size_t hashT = typeid(T).hash_code(); 401 | 402 | auto &list = getListInGrid({x, y}, hashT); 403 | 404 | for (auto it = list.begin(); it != list.end(); it++) 405 | { 406 | Search *add = (T *)(DoNotUse *)*it; 407 | 408 | func(*add, it); 409 | } 410 | } 411 | } 412 | } 413 | 414 | if constexpr (sizeof...(Ts) > 0) 415 | { 416 | view(func, start, end); 417 | } 418 | } 419 | 420 | agl::Vec toGridPosition(agl::Vec position) 421 | { 422 | agl::Vec gridPosition; 423 | gridPosition.x = (position.x / size.x) * (gridResolution.x); 424 | gridPosition.y = (position.y / size.y) * (gridResolution.y); 425 | 426 | if (gridPosition.x < 0) 427 | { 428 | gridPosition.x = 0; 429 | } 430 | else if (gridPosition.x > (gridResolution.x - 1)) 431 | { 432 | gridPosition.x = (gridResolution.x - 1); 433 | } 434 | 435 | if (gridPosition.y < 0) 436 | { 437 | gridPosition.y = 0; 438 | } 439 | else if (gridPosition.y > (gridResolution.y - 1)) 440 | { 441 | gridPosition.y = (gridResolution.y - 1); 442 | } 443 | 444 | return gridPosition; 445 | } 446 | 447 | template void addToGrid(BaseEntity &entity) 448 | { 449 | agl::Vec gridPosition = toGridPosition(entity.position); 450 | auto &map = (grid[gridPosition.x][gridPosition.y])[typeid(T).hash_code()]; 451 | 452 | map.mtx.lock(); 453 | map.list.emplace_back(&entity); 454 | map.mtx.unlock(); 455 | } 456 | 457 | template 458 | void removeEntity( 459 | typename std::list::iterator it, std::function func = [](T &) {}) 460 | { 461 | func(*(T *)(DoNotUse *)(*it)); 462 | delete *it; 463 | 464 | agl::Vec gridPosition = toGridPosition((*it)->position); 465 | 466 | auto &list = grid.at(gridPosition.x).at(gridPosition.y)[typeid(T).hash_code()].list; 467 | 468 | auto i = list.begin(); 469 | 470 | for (; i != list.end(); i++) 471 | { 472 | if (*i == *it) 473 | { 474 | list.erase(i); 475 | 476 | break; 477 | } 478 | } 479 | 480 | entityList[typeid(T).hash_code()].erase(it); 481 | } 482 | 483 | template void getArea(std::function func, agl::Vec gridPosition) 484 | { 485 | agl::Vec startGridOffset = {0, 0}; 486 | agl::Vec endGridOffset = {1, 1}; 487 | 488 | for (int x = startGridOffset.x; x <= endGridOffset.x; x++) 489 | { 490 | if (gridPosition.x + x < 0 || gridPosition.x + x > (this->size.x - 1)) 491 | { 492 | continue; 493 | } 494 | 495 | for (int y = startGridOffset.y; y <= endGridOffset.y; y++) 496 | { 497 | if (gridPosition.y + y < 0 || gridPosition.y + y > (this->size.y - 1)) 498 | { 499 | continue; 500 | } 501 | 502 | for (auto &entity : grid.at(gridPosition.x).at(gridPosition.y)[typeid(T).hash_code()].list) 503 | { 504 | if (!entity->exists) 505 | { 506 | continue; 507 | } 508 | 509 | func(*(T *)(DoNotUse *)(entity)); 510 | } 511 | } 512 | } 513 | } 514 | 515 | std::list &getListInGrid(agl::Vec pos, std::size_t hash) 516 | { 517 | return grid.at(pos.x).at(pos.y)[hash].list; 518 | } 519 | // std::is_invocable 520 | template 521 | void update(Funcs... funcs) 522 | { 523 | auto threadedQueue = [&](int start, int end) { 524 | pool.queue([&, start = start, end = end, funcs = std::tuple(funcs...)]() { 525 | for (int i = start; i <= end; i++) 526 | { 527 | threadFunc0, 0, oneWay, mirror, Entis>(randomPosition[i], funcs); 528 | } 529 | }); 530 | }; 531 | 532 | int gridSize = gridResolution.x * gridResolution.y; 533 | int chunkSize = gridSize / pool.size; 534 | int i = 0; 535 | 536 | for (; i < pool.size - 1; i++) 537 | { 538 | threadedQueue(i * chunkSize, (i * chunkSize) + chunkSize - 1); 539 | } 540 | 541 | if (i * chunkSize < gridSize) 542 | { 543 | threadedQueue(i * chunkSize, gridSize - 1); 544 | } 545 | } 546 | 547 | void clearGrid() 548 | { 549 | for (auto &x : grid) 550 | { 551 | for (auto &y : x) 552 | { 553 | for (auto &[key, cell] : y) 554 | { 555 | cell.list.clear(); 556 | } 557 | } 558 | } 559 | } 560 | 561 | template void selfUpdate(Funcs... funcs) 562 | { 563 | typedef std::remove_reference_t())> EnTy; 564 | auto &list = entityList[typeid(EnTy).hash_code()]; 565 | 566 | for (auto it = list.begin(); it != list.end(); it++) 567 | { 568 | EnTy *en = (EnTy *)(DoNotUse *)*it; 569 | 570 | loopThrougFuncs(*en, funcs...); 571 | 572 | if (!en->exists || std::isnan(en->position.x)) 573 | { 574 | it--; 575 | list.erase(std::next(it, 1)); 576 | } 577 | else 578 | { 579 | addToGrid(*(BaseEntity *)(DoNotUse *)en); 580 | } 581 | } 582 | 583 | if constexpr (i < (std::tuple_size::value - 1)) 584 | { 585 | selfUpdate(funcs...); 586 | } 587 | } 588 | 589 | void destroy() 590 | { 591 | for (auto &[f, s] : entityList) 592 | { 593 | for (auto &entity : s) 594 | { 595 | delete entity; 596 | } 597 | } 598 | 599 | clearGrid(); 600 | entityList.clear(); 601 | 602 | while (pool.active()) 603 | { 604 | } 605 | } 606 | }; 607 | */ 608 | -------------------------------------------------------------------------------- /inc/Food.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Environment.hpp" 4 | #include "PhysicsObj.hpp" 5 | #include "macro.hpp" 6 | #include 7 | #include 8 | 9 | class Food : public PhysicsObj 10 | { 11 | public: 12 | Food() 13 | { 14 | setup({0, 0}, {10, 10}, 1); 15 | } 16 | 17 | int id; 18 | float energy; 19 | 20 | #ifdef ACTIVEFOOD 21 | agl::Vec nextPos; 22 | 23 | void nextRandPos(agl::Vec worldSize) 24 | { 25 | constexpr float range = ACTIVEFOOD; 26 | 27 | float xOffset = rand() / (float)RAND_MAX; 28 | xOffset -= .5; 29 | xOffset *= 2 * range; 30 | 31 | float yOffset = rand() / (float)RAND_MAX; 32 | yOffset -= .5; 33 | yOffset *= 2 * range; 34 | 35 | nextPos.x = std::max((float)0, std::min(worldSize.x, position.x + xOffset)); 36 | nextPos.y = std::max((float)0, std::min(worldSize.y, position.y + yOffset)); 37 | } 38 | #endif 39 | }; 40 | -------------------------------------------------------------------------------- /inc/Meat.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Food.hpp" 4 | #include 5 | 6 | class Meat : public PhysicsObj 7 | { 8 | public: 9 | Meat() 10 | { 11 | setup({0, 0}, {10, 10}, 1); 12 | } 13 | 14 | float lifetime = 0; 15 | float energyVol = 60; 16 | }; 17 | -------------------------------------------------------------------------------- /inc/Menu.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "macro.hpp" 4 | #include 5 | #include 6 | 7 | #undef e//; 8 | 9 | #include 10 | 11 | inline bool pointInArea(agl::Vec point, agl::Vec position, agl::Vec size) 12 | { 13 | if (point.x < position.x) 14 | { 15 | return false; 16 | } 17 | if (point.x > position.x + size.x) 18 | { 19 | return false; 20 | } 21 | if (point.y < position.y) 22 | { 23 | return false; 24 | } 25 | if (point.y > position.y + size.y) 26 | { 27 | return false; 28 | } 29 | 30 | return true; 31 | } 32 | 33 | class MenuShare 34 | { 35 | public: 36 | static agl::Event *event; 37 | static agl::Text *text; 38 | static agl::Text *smallText; 39 | static agl::Rectangle *rect; 40 | static agl::Circle *circ; 41 | static agl::Texture *border; 42 | static agl::Texture *blank; 43 | static void *focusedMenu; 44 | static bool *leftClick; 45 | static agl::Shader *menuShader; 46 | static agl::Shader *baseShader; 47 | static agl::Camera *camera; 48 | 49 | static void init(agl::Texture *blank, agl::Font *font, agl::Font *smallFont, agl::Event *event, bool *leftClick) 50 | { 51 | // left 52 | // right 53 | // up 54 | // down 55 | // tr 56 | // br 57 | // tl 58 | // bl 59 | 60 | border = new agl::Texture(); 61 | border->loadFromFile("img/border.png"); 62 | 63 | text = new agl::Text(); 64 | text->setFont(font); 65 | text->setColor(agl::Color::Black); 66 | text->setScale(1); 67 | 68 | smallText = new agl::Text(); 69 | smallText->setFont(smallFont); 70 | smallText->setColor(agl::Color::Black); 71 | smallText->setScale(1); 72 | 73 | rect = new agl::Rectangle(); 74 | rect->setTexture(blank); 75 | 76 | circ = new agl::Circle(30); 77 | circ->setTexture(blank); 78 | 79 | MenuShare::blank = blank; 80 | MenuShare::event = event; 81 | MenuShare::leftClick = leftClick; 82 | } 83 | 84 | static void destroy() 85 | { 86 | text->clearText(); 87 | smallText->clearText(); 88 | border->deleteTexture(); 89 | 90 | delete text; 91 | delete smallText; 92 | delete border; 93 | delete rect; 94 | delete circ; 95 | } 96 | }; 97 | 98 | class OuterArea : public agl::Drawable, public MenuShare 99 | { 100 | public: 101 | agl::Vec position; 102 | agl::Vec size; 103 | 104 | void drawFunction(agl::RenderWindow &window) override 105 | { 106 | window.getShaderUniforms(*menuShader); 107 | menuShader->use(); 108 | window.updateMvp(*camera); 109 | 110 | glUniform1f(menuShader->getUniformLocation("scaleX"), size.x); 111 | glUniform1f(menuShader->getUniformLocation("scaleY"), size.y); 112 | glUniform1i(menuShader->getUniformLocation("type"), 1); 113 | 114 | rect->setTexture(blank); 115 | rect->setColor(agl::Color::White); 116 | 117 | rect->setPosition(position); 118 | rect->setSize(size); 119 | window.drawShape(*rect); 120 | 121 | window.getShaderUniforms(*baseShader); 122 | baseShader->use(); 123 | window.updateMvp(*camera); 124 | } 125 | }; 126 | 127 | class ThinAreaOut : public agl::Drawable, public MenuShare 128 | { 129 | public: 130 | agl::Vec position; 131 | agl::Vec size; 132 | 133 | void drawFunction(agl::RenderWindow &window) override 134 | { 135 | window.getShaderUniforms(*menuShader); 136 | menuShader->use(); 137 | window.updateMvp(*camera); 138 | 139 | glUniform1f(menuShader->getUniformLocation("scaleX"), size.x); 140 | glUniform1f(menuShader->getUniformLocation("scaleY"), size.y); 141 | glUniform1i(menuShader->getUniformLocation("type"), 0); 142 | 143 | rect->setColor(agl::Color::White); 144 | rect->setPosition(position); 145 | rect->setSize(size); 146 | rect->setTextureScaling({1, 1, 1}); 147 | rect->setTextureTranslation({0, 0, 0}); 148 | window.drawShape(*rect); 149 | 150 | window.getShaderUniforms(*baseShader); 151 | baseShader->use(); 152 | window.updateMvp(*camera); 153 | } 154 | }; 155 | 156 | class ThinAreaIn : public agl::Drawable, public MenuShare 157 | { 158 | public: 159 | agl::Vec position; 160 | agl::Vec size; 161 | 162 | void drawFunction(agl::RenderWindow &window) override 163 | { 164 | window.getShaderUniforms(*menuShader); 165 | menuShader->use(); 166 | window.updateMvp(*camera); 167 | 168 | glUniform1f(menuShader->getUniformLocation("scaleX"), size.x); 169 | glUniform1f(menuShader->getUniformLocation("scaleY"), size.y); 170 | glUniform1i(menuShader->getUniformLocation("type"), 2); 171 | 172 | rect->setTexture(blank); 173 | 174 | rect->setColor(agl::Color::White); 175 | rect->setPosition(position); 176 | rect->setSize(size); 177 | rect->setTextureScaling({1, 1, 1}); 178 | rect->setTextureTranslation({0, 0, 0}); 179 | window.drawShape(*rect); 180 | 181 | window.getShaderUniforms(*baseShader); 182 | baseShader->use(); 183 | window.updateMvp(*camera); 184 | } 185 | }; 186 | 187 | class DipArea : public agl::Drawable, public MenuShare 188 | { 189 | public: 190 | agl::Vec position; 191 | agl::Vec size; 192 | 193 | void drawFunction(agl::RenderWindow &window) override 194 | { 195 | window.getShaderUniforms(*menuShader); 196 | menuShader->use(); 197 | window.updateMvp(*camera); 198 | 199 | glUniform1f(menuShader->getUniformLocation("scaleX"), size.x); 200 | glUniform1f(menuShader->getUniformLocation("scaleY"), size.y); 201 | glUniform1i(menuShader->getUniformLocation("type"), 3); 202 | 203 | rect->setTexture(blank); 204 | rect->setColor(agl::Color::White); 205 | 206 | rect->setColor({0, 0, 0}); 207 | rect->setPosition(position); 208 | rect->setSize(size); 209 | window.drawShape(*rect); 210 | 211 | window.getShaderUniforms(*baseShader); 212 | baseShader->use(); 213 | window.updateMvp(*camera); 214 | } 215 | }; 216 | 217 | class InnerArea : public agl::Drawable, public MenuShare 218 | { 219 | public: 220 | agl::Vec position; 221 | agl::Vec size; 222 | 223 | void drawFunction(agl::RenderWindow &window) override 224 | { 225 | window.getShaderUniforms(*menuShader); 226 | menuShader->use(); 227 | window.updateMvp(*camera); 228 | 229 | glUniform1f(menuShader->getUniformLocation("scaleX"), size.x); 230 | glUniform1f(menuShader->getUniformLocation("scaleY"), size.y); 231 | glUniform1i(menuShader->getUniformLocation("type"), 4); 232 | 233 | bool state = true; 234 | (void)state; 235 | // body 236 | rect->setRotation({0, 0, 0}); 237 | rect->setTexture(blank); 238 | rect->setSize(size); 239 | rect->setPosition(position); 240 | rect->setColor(agl::Color::White); 241 | window.drawShape(*rect); 242 | 243 | window.getShaderUniforms(*baseShader); 244 | baseShader->use(); 245 | window.updateMvp(*camera); 246 | } 247 | }; 248 | 249 | class PressedArea : public agl::Drawable, public MenuShare 250 | { 251 | public: 252 | agl::Vec position; 253 | agl::Vec size; 254 | 255 | void drawFunction(agl::RenderWindow &window) override 256 | { 257 | window.getShaderUniforms(*menuShader); 258 | menuShader->use(); 259 | window.updateMvp(*camera); 260 | 261 | glUniform1f(menuShader->getUniformLocation("scaleX"), size.x); 262 | glUniform1f(menuShader->getUniformLocation("scaleY"), size.y); 263 | glUniform1i(menuShader->getUniformLocation("type"), 5); 264 | 265 | bool state = true; 266 | 267 | // body 268 | rect->setRotation({0, 0, 0}); 269 | rect->setTexture(blank); 270 | rect->setSize(size); 271 | rect->setPosition(position); 272 | rect->setColor(agl::Color::White); 273 | window.drawShape(*rect); 274 | 275 | window.getShaderUniforms(*baseShader); 276 | baseShader->use(); 277 | window.updateMvp(*camera); 278 | } 279 | }; 280 | 281 | class MenuElement : public agl::Drawable, public MenuShare 282 | { 283 | public: 284 | agl::Vec position = {0, 0, 0}; 285 | agl::Vec size = {0, 0}; 286 | 287 | bool pointInElement(agl::Vec point) 288 | { 289 | return pointInArea(point, position, size); 290 | } 291 | 292 | virtual void init(float width) 293 | { 294 | if (size.y == 0) 295 | { 296 | size.y = text->getHeight() * text->getScale(); 297 | } 298 | 299 | size.x = width; 300 | } 301 | 302 | // void drawFunction(agl::RenderWindow &window); 303 | }; 304 | 305 | class TextElement : public MenuElement 306 | { 307 | public: 308 | std::string str = "null"; 309 | 310 | TextElement() 311 | { 312 | } 313 | 314 | TextElement(std::string str) 315 | { 316 | this->str = str; 317 | } 318 | 319 | void drawFunction(agl::RenderWindow &window) override 320 | { 321 | text->setPosition(position); 322 | text->clearText(); 323 | text->setText(str); 324 | 325 | window.drawText(*text); 326 | } 327 | }; 328 | 329 | template inline std::string toString(T value) 330 | { 331 | return std::to_string(value); 332 | } 333 | 334 | template <> inline std::string toString(std::string value) 335 | { 336 | return value; 337 | } 338 | 339 | template <> inline std::string toString(const char *value) 340 | { 341 | return value; 342 | } 343 | 344 | template class ValueElement : public MenuElement 345 | { 346 | public: 347 | std::string label = "null"; 348 | std::function valueFunc; 349 | 350 | ValueElement() 351 | { 352 | } 353 | 354 | ValueElement(std::string label, std::function valueFunc) 355 | { 356 | this->label = label; 357 | this->valueFunc = valueFunc; 358 | } 359 | 360 | void operator=(ValueElement valueElement) 361 | { 362 | this->label = valueElement.label; 363 | this->value = valueElement.value; 364 | } 365 | 366 | void drawFunction(agl::RenderWindow &window) override 367 | { 368 | text->setPosition(position); 369 | text->clearText(); 370 | text->setText(label + " - " + toString(*valueFunc())); 371 | 372 | window.drawText(*text); 373 | } 374 | }; 375 | 376 | class SpacerElement : public MenuElement 377 | { 378 | public: 379 | SpacerElement() 380 | { 381 | } 382 | 383 | SpacerElement(float height) 384 | { 385 | this->size.y = height; 386 | } 387 | 388 | void drawFunction(agl::RenderWindow &window) override 389 | { 390 | } 391 | }; 392 | 393 | enum ButtonType 394 | { 395 | Toggle, 396 | Hold, 397 | }; 398 | 399 | template class ButtonElement : public MenuElement 400 | { 401 | public: 402 | float mouseHeld = false; 403 | std::string label = "null"; 404 | bool state = false; 405 | 406 | ButtonElement() 407 | { 408 | } 409 | 410 | ButtonElement(std::string label) 411 | { 412 | this->label = label; 413 | } 414 | 415 | void init(float width) override 416 | { 417 | size.y = text->getHeight() * text->getScale() + 7; 418 | size.x = width; 419 | } 420 | 421 | void drawFunction(agl::RenderWindow &window) override 422 | { 423 | if constexpr (buttonType == ButtonType::Toggle) 424 | { 425 | if (*leftClick && this->pointInElement(event->getPointerWindowPosition())) 426 | { 427 | state = !state; 428 | } 429 | } 430 | else if constexpr (buttonType == ButtonType::Hold) 431 | { 432 | if (event->isPointerButtonPressed(agl::Button::Left) && 433 | this->pointInElement(event->getPointerWindowPosition())) 434 | { 435 | state = true; 436 | } 437 | else 438 | { 439 | state = false; 440 | } 441 | } 442 | 443 | if (state) 444 | { 445 | PressedArea pressedArea; 446 | pressedArea.size = size; 447 | pressedArea.position = position; 448 | 449 | window.draw(pressedArea); 450 | } 451 | else 452 | { 453 | OuterArea outerArea; 454 | outerArea.size = size; 455 | outerArea.position = position; 456 | 457 | window.draw(outerArea); 458 | } 459 | 460 | text->setPosition(position + agl::Vec{MENU_BORDEREDGE * 2, 0}); 461 | text->clearText(); 462 | text->setText(label); 463 | window.drawText(*text); 464 | text->clearText(); 465 | } 466 | }; 467 | 468 | class FocusableElement 469 | { 470 | public: 471 | virtual void unFocus() 472 | { 473 | } 474 | static FocusableElement *focusedField; 475 | }; 476 | 477 | template class FieldElement : public MenuElement, public FocusableElement 478 | { 479 | public: 480 | std::string label = "null"; 481 | T value; 482 | std::string liveValue = ""; 483 | 484 | float labelBuffer = 0; 485 | 486 | bool textFocus = false; 487 | bool valid = true; 488 | bool hovered = false; 489 | 490 | FieldElement() 491 | { 492 | } 493 | 494 | FieldElement(std::string label, T startValue) 495 | { 496 | this->label = label; 497 | this->value = startValue; 498 | this->liveValue = toString(this->value); 499 | } 500 | 501 | void init(float width) override 502 | { 503 | size.y = text->getHeight() + 7; 504 | size.x = width; 505 | labelBuffer = 80; 506 | } 507 | 508 | void unFocus() override 509 | { 510 | textFocus = false; 511 | 512 | try 513 | { 514 | if constexpr (std::is_same_v) 515 | { 516 | value = liveValue; 517 | } 518 | else if constexpr (std::is_same_v) 519 | { 520 | value = std::stoi(liveValue); 521 | } 522 | else if constexpr (std::is_same_v) 523 | { 524 | value = std::stof(liveValue); 525 | } 526 | 527 | valid = true; 528 | } 529 | catch (const std::invalid_argument &) 530 | { 531 | valid = false; 532 | } 533 | 534 | focusedField = nullptr; 535 | } 536 | 537 | void drawFunction(agl::RenderWindow &window) override 538 | { 539 | // bad fix, too lazy to add utf-8 fonts yet 540 | 541 | bool utf8 = false; 542 | 543 | for (const char &byte : event->keybuffer) 544 | { 545 | if (byte & (1 << 8)) 546 | { 547 | utf8 = true; 548 | break; 549 | } 550 | } 551 | 552 | if (this->pointInElement(event->getPointerWindowPosition())) 553 | { 554 | if (*leftClick) 555 | { 556 | textFocus = !textFocus; 557 | 558 | if (textFocus) 559 | { 560 | if (focusedField != nullptr) 561 | { 562 | focusedField->unFocus(); 563 | } 564 | 565 | focusedField = this; 566 | } 567 | else 568 | { 569 | this->unFocus(); 570 | } 571 | } 572 | 573 | if (hovered) // holding 574 | { 575 | window.setCursorShape(agl::CursorType::Beam); 576 | } 577 | else // first 578 | { 579 | window.setCursorShape(agl::CursorType::Beam); 580 | hovered = true; 581 | } 582 | } 583 | else if (hovered) // last 584 | { 585 | window.setCursorShape(agl::CursorType::Arrow); 586 | hovered = false; 587 | } 588 | 589 | if (event->keybuffer.find('\r') != std::string::npos && textFocus) 590 | { 591 | this->unFocus(); 592 | } 593 | 594 | if (textFocus && !utf8) 595 | { 596 | liveValue += event->keybuffer; 597 | 598 | while (liveValue[0] == 127 || liveValue[0] == 8) 599 | { 600 | liveValue.erase(0, 1); 601 | } 602 | 603 | for (int i = 1; i < liveValue.length(); i++) 604 | { 605 | if (liveValue[i] == 127 || liveValue[i] == 8) 606 | { 607 | liveValue.erase(i - 1, 2); 608 | i--; 609 | } 610 | } 611 | } 612 | 613 | text->setPosition(position + agl::Vec{0, 0}); 614 | text->clearText(); 615 | text->setText(label); 616 | 617 | window.drawText(*text); 618 | 619 | text->clearText(); 620 | 621 | InnerArea innerArea; 622 | innerArea.position = position + agl::Vec{labelBuffer, 0}; 623 | innerArea.size = {size.x - labelBuffer, size.y}; 624 | 625 | window.draw(innerArea); 626 | 627 | text->setPosition(position + agl::Vec{labelBuffer + 5, 0}); 628 | text->setText(liveValue); 629 | 630 | if (valid) 631 | { 632 | text->setColor(agl::Color::White); 633 | rect->setColor(agl::Color::White); 634 | } 635 | else 636 | { 637 | text->setColor(agl::Color::Red); 638 | rect->setColor(agl::Color::Red); 639 | } 640 | 641 | agl::Vec start = window.drawText(*text) + position + agl::Vec{labelBuffer + 5, 0}; 642 | 643 | if (textFocus) 644 | { 645 | rect->setPosition(start + agl::Vec{0, 2}); 646 | rect->setSize({1, (float)text->getHeight() - 1}); 647 | window.drawShape(*rect); 648 | } 649 | 650 | text->setColor(agl::Color::White); 651 | rect->setColor(agl::Color::White); 652 | 653 | text->clearText(); 654 | } 655 | }; 656 | 657 | class NetworkGraph : public MenuElement 658 | { 659 | public: 660 | int selectedID = 0; 661 | 662 | in::NeuralNetwork **network; 663 | 664 | std::function networkFunc; 665 | 666 | NetworkGraph() 667 | { 668 | } 669 | 670 | NetworkGraph(std::function networkFunc) : networkFunc(networkFunc) 671 | { 672 | } 673 | 674 | void init(float width) override 675 | { 676 | size = {300, 300}; 677 | } 678 | 679 | void drawFunction(agl::RenderWindow &window) override 680 | { 681 | circ->setTexture(blank); 682 | circ->setColor({15, 15, 15}); 683 | circ->setSize(agl::Vec{150, 150, 0}); 684 | circ->setPosition(position + agl::Vec{150, 150}); 685 | window.drawShape(*circ); 686 | 687 | // draw node connections 688 | for (int i = 0; i < (*networkFunc())->structure.totalConnections; i++) 689 | { 690 | in::Connection connection = (*networkFunc())->getConnection(i); 691 | 692 | if (!connection.valid) 693 | { 694 | continue; 695 | } 696 | 697 | float startAngle = connection.startNode + 1; 698 | startAngle /= (*networkFunc())->getTotalNodes(); 699 | startAngle *= PI * 2; 700 | 701 | float endAngle = connection.endNode + 1; 702 | endAngle /= (*networkFunc())->getTotalNodes(); 703 | endAngle *= PI * 2; 704 | 705 | agl::Vec startPosition = agl::pointOnCircle(startAngle); 706 | startPosition.x = (startPosition.x * (circ->getSize().x - NETWORK_PADDING)) + circ->getPosition().x; 707 | startPosition.y = (startPosition.y * (circ->getSize().x - NETWORK_PADDING)) + circ->getPosition().y; 708 | 709 | agl::Vec endPosition = agl::pointOnCircle(endAngle); 710 | endPosition.x = (endPosition.x * (circ->getSize().x - NETWORK_PADDING)) + circ->getPosition().x; 711 | endPosition.y = (endPosition.y * (circ->getSize().x - NETWORK_PADDING)) + circ->getPosition().y; 712 | 713 | agl::Vec offset = startPosition - endPosition; 714 | 715 | float angle = agl::radianToDegree(-offset.angle()); 716 | 717 | float weight = connection.weight; 718 | 719 | rect->setTexture(blank); 720 | 721 | if (weight > 0) 722 | { 723 | rect->setColor({0, (unsigned char)(weight * 255), BASE_B_VALUE}); 724 | } 725 | else 726 | { 727 | rect->setColor({(unsigned char)(-weight * 255), 0, BASE_B_VALUE}); 728 | } 729 | 730 | rect->setSize(agl::Vec{2, offset.length()}); 731 | rect->setPosition(startPosition); 732 | rect->setRotation(agl::Vec{0, 0, angle}); 733 | window.drawShape(*rect); 734 | } 735 | 736 | // draw nodes 737 | for (int i = 0; i < (*networkFunc())->getTotalNodes(); i++) 738 | { 739 | float angle = (360. / (*networkFunc())->getTotalNodes()) * (i + 1); 740 | 741 | float x = cos(angle * (3.14159 / 180)); 742 | float y = sin(angle * (3.14159 / 180)); 743 | 744 | agl::Vec pos; 745 | pos.x = x * (150 - NETWORK_PADDING); 746 | pos.y = y * (150 - NETWORK_PADDING); 747 | 748 | pos.x += position.x + 150; 749 | pos.y += position.y + 150; 750 | 751 | circ->setSize({10, 10}); 752 | 753 | circ->setPosition(pos); 754 | 755 | float nodeValue = (*networkFunc())->getNode(i).value; 756 | 757 | if (nodeValue > 0) 758 | { 759 | circ->setColor({0, (unsigned char)(nodeValue * 255), BASE_B_VALUE}); 760 | } 761 | else 762 | { 763 | circ->setColor({(unsigned char)(-nodeValue * 255), 0, BASE_B_VALUE}); 764 | } 765 | 766 | if ((pos - event->getPointerWindowPosition()).length() < 10) 767 | { 768 | selectedID = i; 769 | } 770 | 771 | window.drawShape(*circ); 772 | } 773 | 774 | rect->setRotation({0, 0, 0}); 775 | } 776 | }; 777 | 778 | class SimpleMenu : public agl::Drawable, public MenuShare 779 | { 780 | public: 781 | bool exists = false; 782 | agl::Vec position = {0, 0}; 783 | agl::Vec size = {0, 0}; 784 | std::string title = ""; 785 | 786 | void open(agl::Vec position) 787 | { 788 | exists = true; 789 | this->position = position; 790 | } 791 | 792 | void close() 793 | { 794 | exists = false; 795 | 796 | if (focusedMenu == this) 797 | { 798 | focusedMenu = nullptr; 799 | } 800 | } 801 | }; 802 | 803 | // template hell 804 | template class Menu : public SimpleMenu 805 | { 806 | public: 807 | std::tuple element; 808 | 809 | std::function requirement = []() { return true; }; 810 | 811 | template typename std::enable_if::type initTuple() 812 | { 813 | return 0; 814 | } 815 | 816 | template typename std::enable_if < i::type initTuple() 817 | { 818 | this->get().init(size.x - (2 * (MENU_BORDERTHICKNESS + MENU_PADDING))); 819 | 820 | int height = this->get().size.y + MENU_PADDING; 821 | 822 | height += initTuple(); 823 | 824 | return height; 825 | } 826 | 827 | template 828 | typename std::enable_if::type draw(agl::RenderWindow &window, 829 | agl::Vec &pen) 830 | { 831 | return; 832 | } 833 | 834 | template 835 | typename std::enable_if < 836 | i::type draw(agl::RenderWindow &window, agl::Vec &pen) 837 | { 838 | this->get().position = pen; 839 | 840 | window.draw(this->get()); 841 | 842 | pen.y += this->get().size.y + MENU_PADDING; 843 | 844 | draw(window, pen); 845 | } 846 | 847 | template void assign(Element newElement) 848 | { 849 | this->get() = newElement; 850 | this->get().init(size.x - (2 * (MENU_BORDERTHICKNESS + MENU_PADDING))); 851 | } 852 | 853 | template 854 | void assign(Element newElement, Elements... newElements) 855 | { 856 | this->get() = newElement; 857 | this->get().init(size.x - (2 * (MENU_BORDERTHICKNESS + MENU_PADDING))); 858 | 859 | assign(newElements...); 860 | } 861 | 862 | template 863 | typename std::enable_if::type pointerAssign(void *pointerStruct) 864 | { 865 | return; 866 | } 867 | 868 | template 869 | typename std::enable_if < i::type pointerAssign(void *pointerStruct) 870 | { 871 | int64_t address = (int64_t)(pointerStruct); 872 | int64_t offset = i * 8; 873 | int64_t *item = (int64_t *)(address + offset); 874 | 875 | *item = (int64_t) & this->get(); 876 | 877 | pointerAssign(pointerStruct); 878 | } 879 | 880 | Menu(std::string title, int width, ElementType... args) : element(std::make_tuple(args...)) 881 | { 882 | this->title = title; 883 | this->size.x = width; 884 | 885 | int height = initTuple(); 886 | 887 | this->size.y = height + (2 * (MENU_BORDERTHICKNESS + MENU_PADDING)); 888 | } 889 | 890 | void setupElements(ElementType... Element) 891 | { 892 | assign(Element...); 893 | } 894 | 895 | void bindPointers(void *pointerStruct) 896 | { 897 | pointerAssign(pointerStruct); 898 | } 899 | 900 | template std::tuple_element_t> &get() 901 | { 902 | return std::get(element); 903 | } 904 | 905 | void drawFunction(agl::RenderWindow &window) override 906 | { 907 | if (!exists) 908 | { 909 | return; 910 | } 911 | 912 | static agl::Vec offset; 913 | 914 | if (event->isPointerButtonPressed(agl::Button::Left)) 915 | { 916 | if (pointInArea(event->getPointerWindowPosition(), position, 917 | agl::Vec{size.x, 4 + (int)smallText->getHeight()}) && 918 | focusedMenu == nullptr) 919 | { 920 | offset = position - event->getPointerWindowPosition(); 921 | 922 | focusedMenu = this; 923 | } 924 | } 925 | else if (focusedMenu == this) 926 | { 927 | focusedMenu = nullptr; 928 | } 929 | 930 | if (focusedMenu == this) 931 | { 932 | position = event->getPointerWindowPosition() + offset; 933 | } 934 | 935 | if (requirement()) 936 | { 937 | agl::Vec pen = {MENU_BORDERTHICKNESS + MENU_PADDING, 938 | MENU_BORDERTHICKNESS + MENU_PADDING + smallText->getHeight()}; 939 | pen = pen + position; 940 | 941 | OuterArea outerArea; 942 | outerArea.position = position; 943 | outerArea.size = size + agl::Vec{0, (float)smallText->getHeight()}; 944 | 945 | window.draw(outerArea); 946 | 947 | DipArea innerArea; 948 | innerArea.position = position + agl::Vec{4, 4 + (float)smallText->getHeight()}; 949 | innerArea.size = size + agl::Vec{-8, -8}; 950 | 951 | window.draw(innerArea); 952 | 953 | draw(window, pen); 954 | } 955 | else 956 | { 957 | OuterArea outerArea; 958 | outerArea.position = position; 959 | outerArea.size = {(float)size.x, (float)smallText->getHeight() + 6}; 960 | 961 | window.draw(outerArea); 962 | } 963 | 964 | smallText->clearText(); 965 | smallText->setText(title); 966 | smallText->setColor(agl::Color::White); 967 | smallText->setPosition(position + agl::Vec{3.5, 0}); 968 | window.drawText(*smallText); 969 | } 970 | }; 971 | -------------------------------------------------------------------------------- /inc/MenuBar.hpp: -------------------------------------------------------------------------------- 1 | #include "Menu.hpp" 2 | 3 | #define BARHEIGHT 22 4 | 5 | class MenuBar : public agl::Drawable, public MenuShare 6 | { 7 | private: 8 | template void assign(T menu) 9 | { 10 | this->menu[i] = menu; 11 | } 12 | 13 | template void assign(T menu, Ts... menus) 14 | { 15 | this->menu[i] = menu; 16 | 17 | assign(menus...); 18 | } 19 | 20 | public: 21 | int length; 22 | SimpleMenu **menu; 23 | bool exists = true; 24 | 25 | template MenuBar(Ts... menus) 26 | { 27 | length = sizeof...(menus); 28 | 29 | this->menu = new SimpleMenu *[length]; 30 | 31 | assign<0>(menus...); 32 | } 33 | 34 | void drawFunction(agl::RenderWindow &window) override 35 | { 36 | if (!exists) 37 | { 38 | return; 39 | } 40 | 41 | // draw child menus 42 | 43 | for (int i = 0; i < length; i++) 44 | { 45 | window.draw(*menu[i]); 46 | } 47 | 48 | // draw bar 49 | 50 | OuterArea background; 51 | 52 | background.position = {-2, -2}; 53 | background.size = {(float)window.getState().size.x + 4, BARHEIGHT + 4}; 54 | 55 | window.draw(background); 56 | 57 | ThinAreaOut test; 58 | 59 | agl::Vec pen = {0, 0}; 60 | 61 | for (int i = 0; i < length; i++) 62 | { 63 | agl::Vec oldPen = pen; 64 | 65 | text->clearText(); 66 | text->setText(menu[i]->title); 67 | text->setPosition(oldPen + agl::Vec{9, 0}); 68 | text->setColor(agl::Color::White); 69 | pen = window.drawText(*text) + text->getPosition(); 70 | 71 | agl::Vec position = oldPen; 72 | agl::Vec size = {(pen.x - oldPen.x) + 9, 20}; 73 | 74 | if (pointInArea(event->getPointerWindowPosition(), position, size)) 75 | { 76 | static bool prev = false; 77 | 78 | if (event->isPointerButtonPressed(agl::Button::Left)) 79 | { 80 | if (!prev) 81 | { 82 | prev = true; 83 | 84 | if (!menu[i]->exists) 85 | { 86 | menu[i]->open({500, 500}); 87 | } 88 | else 89 | { 90 | menu[i]->close(); 91 | } 92 | } 93 | } 94 | else 95 | { 96 | prev = false; 97 | } 98 | 99 | if (!menu[i]->exists) 100 | { 101 | ThinAreaOut area; 102 | area.position = oldPen; 103 | area.size = {(pen.x - oldPen.x) + 9, 22}; 104 | window.draw(area); 105 | window.drawText(*text); 106 | } 107 | } 108 | 109 | if (menu[i]->exists) 110 | { 111 | ThinAreaIn area; 112 | area.position = oldPen; 113 | area.size = {(pen.x - oldPen.x) + 9, 22}; 114 | window.draw(area); 115 | window.drawText(*text); 116 | } 117 | 118 | pen.x += 9; 119 | } 120 | } 121 | 122 | ~MenuBar() 123 | { 124 | delete[] menu; 125 | } 126 | }; 127 | -------------------------------------------------------------------------------- /inc/PhysicsObj.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "AGL/include/ShaderBuilder.hpp" 4 | #include "other.hpp" 5 | #include 6 | #include 7 | 8 | struct PolyShape 9 | { 10 | std::vector> points; 11 | std::vector> normals; 12 | }; 13 | 14 | class PhysicsObj 15 | { 16 | public: 17 | bool exists; 18 | agl::Vec position; 19 | int collideCount = 0; 20 | int id = 0; 21 | bool forcable = false; 22 | bool dynamic = false; 23 | agl::Vec size = {0, 0}; 24 | agl::Vec posOffset = {0, 0}; 25 | agl::Vec velocity = {0, 0}; 26 | agl::Vec acceleration = {0, 0}; 27 | float mass = 1; 28 | float rotation = 0; 29 | float angularVelocity = 0; 30 | float inertia = 1; 31 | float invMass = 1; 32 | float invInertia = 1; 33 | float angularAcceleration = 0; 34 | int totalContacts = 0; 35 | float rotOffset = 0; 36 | float refRot = 0; 37 | float motor = 0; 38 | agl::Vec force; 39 | float oldImpulse = 0; 40 | 41 | PhysicsObj *rootConnect = nullptr; 42 | agl::Vec local1; 43 | agl::Vec local2; 44 | float maxMotor = 1; 45 | 46 | PolyShape *shape; 47 | 48 | PhysicsObj() 49 | { 50 | } 51 | 52 | void setup(agl::Vec position, agl::Vec size, float mass) 53 | { 54 | this->position = position; 55 | this->size = size; 56 | setMass(mass); 57 | } 58 | 59 | agl::Vec GetPosition() 60 | { 61 | return position; 62 | } 63 | 64 | float GetAngle() 65 | { 66 | return rotation; 67 | } 68 | 69 | agl::Vec GetLinearVelocity() 70 | { 71 | return velocity; 72 | } 73 | 74 | void calcInertia(float value) 75 | { 76 | inertia = (1 / 12.f) * mass * (size.x * size.x + size.y * size.y); 77 | } 78 | 79 | void setMass(float value) 80 | { 81 | if (value != 0) 82 | { 83 | mass = value; 84 | calcInertia(value); 85 | 86 | invMass = 1 / mass; 87 | 88 | if (inertia == 0) 89 | { 90 | invInertia = 0; 91 | } 92 | else 93 | { 94 | invInertia = 1 / inertia; 95 | } 96 | } 97 | else 98 | { 99 | mass = 0; 100 | inertia = 0; 101 | invMass = 0; 102 | invInertia = 0; 103 | } 104 | } 105 | 106 | float radToDeg() 107 | { 108 | return agl::radianToDegree(rotation); 109 | } 110 | 111 | void syncOffsets() 112 | { 113 | position += posOffset; 114 | rotation += rotOffset; 115 | 116 | posOffset = {0, 0}; 117 | rotOffset = 0; 118 | } 119 | 120 | void updatePhysics() 121 | { 122 | velocity = velocity + acceleration; 123 | angularVelocity = angularVelocity + angularAcceleration; 124 | acceleration = {0, 0}; 125 | angularAcceleration = 0; 126 | 127 | position += velocity; 128 | rotation += angularVelocity; 129 | 130 | syncOffsets(); 131 | 132 | // rotation = loop(-PI, PI, rotation); 133 | } 134 | 135 | void SetTransform(agl::Vec pos, float rot) 136 | { 137 | position = pos; 138 | rotation = rot; 139 | } 140 | 141 | void ApplyForceToCenter(agl::Vec force) 142 | { 143 | acceleration += force * invMass; 144 | } 145 | 146 | void applyForce(PhysicsObj &b, agl::Vec force, agl::Vec point) 147 | { 148 | b.acceleration += force * b.invMass; 149 | b.angularAcceleration += cross2D(point - b.position, force) * b.invInertia; 150 | } 151 | 152 | static void addJoint(PhysicsObj &b1, agl::Vec local1, PhysicsObj &b2, agl::Vec local2) 153 | { 154 | b1.rootConnect = &b2; 155 | b1.local1 = local1; 156 | b1.local2 = local2; 157 | b1.refRot = b1.rotation - b2.rotation; 158 | } 159 | 160 | void boxToPoly(PolyShape &shape) 161 | { 162 | agl::Mat4f rot; 163 | rot.rotateZ(-radToDeg()); 164 | 165 | shape.points.resize(4); 166 | shape.points[0] = position + rot * agl::Vec{-size.x, -size.y} / 2; 167 | shape.points[1] = position + rot * agl::Vec{size.x, -size.y} / 2; 168 | shape.points[2] = position + rot * agl::Vec{size.x, size.y} / 2; 169 | shape.points[3] = position + rot * agl::Vec{-size.x, size.y} / 2; 170 | 171 | shape.normals.resize(4); 172 | shape.normals[0] = rot * agl::Vec{0, -1}; 173 | shape.normals[1] = rot * agl::Vec{1, 0}; 174 | shape.normals[2] = rot * agl::Vec{0, 1}; 175 | shape.normals[3] = rot * agl::Vec{-1, 0}; 176 | 177 | this->shape = &shape; 178 | } 179 | 180 | float getJointAngle() 181 | { 182 | return loop((float)-PI, (float)PI, (rotation - rootConnect->rotation) - refRot); 183 | } 184 | 185 | static float sec(float x) 186 | { 187 | return 1. / cos(x); 188 | } 189 | static float csc(float x) 190 | { 191 | return 1. / sin(x); 192 | } 193 | 194 | static float sq(float x) 195 | { 196 | return x * x; 197 | } 198 | 199 | // depth, norm 200 | inline std::pair> getDistIfCol(agl::Vec pos) 201 | { 202 | agl::Vec offset = position - pos; 203 | 204 | float rot = offset.angle(); 205 | 206 | float regDist = offset.dot(offset); 207 | 208 | float sqDist = fmin(sq(size.x / 2 * sec(rot - rotation)), sq(size.y / 2 * csc(rot - rotation))); 209 | 210 | if (regDist > sqDist) 211 | { 212 | return std::pair(0, agl::Vec{0, 0}); 213 | } 214 | else 215 | { 216 | float depth = sqrt(sqDist) - sqrt(regDist); 217 | float fixRot = ((rot + PI / 4) > 2 * PI ? rot + PI / 4 - (2 * PI) : rot + PI / 4); 218 | std::cout << fixRot << '\n'; 219 | float normRot = int(fixRot / (PI / 2)) * (PI / 2) + rotation; 220 | 221 | return std::pair(depth, agl::Vec{-sin(normRot), cos(normRot)}); 222 | } 223 | } 224 | }; 225 | 226 | struct ConstraintFailure 227 | { 228 | PhysicsObj *b1; 229 | PhysicsObj *b2; 230 | agl::Vec inter1 = {0, 0}; 231 | agl::Vec inter2 = {0, 0}; 232 | agl::Vec r1; 233 | agl::Vec r2; 234 | agl::Vec normal = {0, 0}; 235 | float depth = 0; 236 | }; 237 | 238 | class World 239 | { 240 | public: 241 | static agl::Vec AABBnormal(PhysicsObj &box1, PhysicsObj &box2) 242 | { 243 | // Calculate the half-sizes of the boxes 244 | agl::Vec halfSize1 = box1.size * 0.5; 245 | agl::Vec halfSize2 = box2.size * 0.5; 246 | 247 | // Calculate the centers of the boxes 248 | agl::Vec center1 = box1.position; 249 | agl::Vec center2 = box2.position; 250 | 251 | // Calculate the difference in centers 252 | agl::Vec difference = center2 - center1; 253 | agl::Vec absDifference = {abs(difference.x), abs(difference.y)}; 254 | 255 | // Calculate the overlap on each axis 256 | agl::Vec overlap = absDifference - (halfSize1 + halfSize2); 257 | 258 | // Calculate the normal 259 | agl::Vec normal; 260 | if (overlap.x > 0 || overlap.y > 0) 261 | { 262 | normal = {0, 0}; 263 | } 264 | else if (overlap.x > overlap.y) 265 | { 266 | if (difference.x < 0) 267 | { 268 | normal = {-1, 0}; 269 | } 270 | else 271 | { 272 | normal = {1, 0}; 273 | } 274 | } 275 | else 276 | { 277 | if (difference.y < 0) 278 | { 279 | normal = {0, -1}; 280 | } 281 | else 282 | { 283 | normal = {0, 1}; 284 | } 285 | } 286 | 287 | return normal; 288 | } 289 | 290 | static void motor(PhysicsObj &b1) 291 | { 292 | float vel = b1.rootConnect->angularVelocity - b1.angularVelocity; 293 | float impulse = (b1.motor - vel); //* (1 / (b1.inertia + b1.rootConnect->inertia)); 294 | 295 | // float torque= 1; 296 | // impulse = std::clamp(impulse, -torque, torque); 297 | 298 | float oldImp = b1.oldImpulse; 299 | b1.oldImpulse = oldImp; 300 | impulse = impulse - oldImp; 301 | 302 | // float impulse = b1.motor; 303 | 304 | b1.angularAcceleration -= impulse * b1.invInertia; 305 | b1.rootConnect->angularAcceleration += impulse * b1.rootConnect->invInertia; 306 | 307 | // std::cout << impulse << '\n'; 308 | 309 | // float torque = 100000000; 310 | // 311 | // float Cdot = b1.angularVelocity - 312 | // b1.rootConnect->angularVelocity 313 | // - b1.motor; float impulse = (1 / (b1.rootConnect->inertia + 314 | // b1.inertia) 315 | // * Cdot); float motorImpulse = std::clamp(b1.oldImpulse + impulse, 316 | // -torque, torque); 317 | // std::cout << motorImpulse << '\n'; 318 | // impulse = motorImpulse; 319 | // b1.oldImpulse = motorImpulse; 320 | // 321 | // b1.angularAcceleration -= impulse * b1.invInertia; 322 | // b1.rootConnect->angularAcceleration += impulse * 323 | // b1.rootConnect->invInertia; 324 | } 325 | 326 | template 327 | static bool pointInBox(PolyShape &shape, agl::Vec point, ConstraintFailure &bare) 328 | { 329 | float depth = INFINITY; 330 | int index = 0; 331 | agl::Vec online; 332 | 333 | for (int i = 0; i < shape.points.size(); i++) 334 | { 335 | agl::Vec c = 336 | closestPointToLine(shape.points[i], shape.points[(i + 1) % shape.points.size()], point); 337 | 338 | float dot = -shape.normals[i].dot(c - point); 339 | 340 | if (dot > 0) 341 | { 342 | return false; 343 | } 344 | 345 | float d = (c - point).length(); 346 | 347 | if constexpr (useBare) 348 | { 349 | if (d < depth) 350 | { 351 | index = i; 352 | online = c; 353 | depth = d; 354 | } 355 | } 356 | if (i == shape.points.size() - 1) 357 | { 358 | if constexpr (useBare) 359 | { 360 | bare.inter1 = online; 361 | bare.inter2 = point; 362 | bare.normal = shape.normals[index]; 363 | bare.depth = depth; 364 | } 365 | return true; 366 | } 367 | } 368 | 369 | return false; 370 | } 371 | 372 | static void testRes(ConstraintFailure &collision, int divider) 373 | { 374 | agl::Vec rp1 = perp(collision.r1); 375 | agl::Vec rp2 = perp(collision.r2); 376 | agl::Vec offset = (collision.inter1 - collision.inter2); 377 | 378 | float restitution = 0; 379 | auto top = (offset * -(1 + restitution)).dot(collision.normal); 380 | 381 | float botl1 = std::pow(rp1.dot(collision.normal), 2) * collision.b1->invInertia; 382 | float botl2 = std::pow(rp2.dot(collision.normal), 2) * collision.b2->invInertia; 383 | 384 | auto bottom = collision.normal.dot(collision.normal * (collision.b1->invMass + collision.b2->invMass)) + 385 | botl1 + botl2; 386 | float impulse = top / bottom; 387 | 388 | impulse /= divider; 389 | 390 | agl::Vec acc1 = collision.normal * (impulse * collision.b1->invMass); 391 | agl::Vec acc2 = collision.normal * (impulse * -collision.b2->invMass); 392 | 393 | collision.b1->posOffset += acc1; 394 | collision.b2->posOffset += acc2; 395 | 396 | collision.b1->rotOffset -= rp1.dot(collision.normal * impulse) * collision.b1->invInertia; 397 | collision.b2->rotOffset += rp2.dot(collision.normal * impulse) * collision.b2->invInertia; 398 | } 399 | 400 | static void resolve(ConstraintFailure &collision, int divider) 401 | { 402 | agl::Vec rp1 = perp(collision.r1); 403 | agl::Vec rp2 = perp(collision.r2); 404 | agl::Vec relVel = (collision.b1->velocity + (rp1 * -collision.b1->angularVelocity)) - 405 | (collision.b2->velocity + (rp2 * -collision.b2->angularVelocity)); 406 | 407 | float restitution = 0; 408 | auto top = (relVel * -(1 + restitution)).dot(collision.normal); 409 | 410 | float botl1 = std::pow(rp1.dot(collision.normal), 2) * collision.b1->invInertia; 411 | float botl2 = std::pow(rp2.dot(collision.normal), 2) * collision.b2->invInertia; 412 | 413 | auto bottom = collision.normal.dot(collision.normal * (collision.b1->invMass + collision.b2->invMass)) + 414 | botl1 + botl2; 415 | float impulse = top / bottom; 416 | 417 | impulse /= divider; 418 | 419 | agl::Vec acc1 = collision.normal * (impulse * collision.b1->invMass); 420 | agl::Vec acc2 = collision.normal * (impulse * -collision.b2->invMass); 421 | 422 | collision.b1->acceleration += acc1; 423 | collision.b2->acceleration += acc2; 424 | 425 | collision.b1->angularAcceleration -= rp1.dot(collision.normal * impulse) * collision.b1->invInertia; 426 | collision.b2->angularAcceleration += rp2.dot(collision.normal * impulse) * collision.b2->invInertia; 427 | 428 | testRes(collision, divider); 429 | } 430 | 431 | static void resolve(agl::Vec input1, agl::Vec input2, float rot1, float rot2, 432 | float invInertia1, float invInertia2, float invMass1, float invMass2, 433 | agl::Vec normal, agl::Vec r1, agl::Vec r2, 434 | agl::Vec &out1, agl ::Vec &out2, float &rotOut1, float &rotOut2, 435 | int divider) 436 | { 437 | agl::Vec rp1 = perp(r1); 438 | agl::Vec rp2 = perp(r2); 439 | agl::Vec relVel = (input1 + (rp1 * -rot1)) - (input2 + (rp2 * -rot2)); 440 | 441 | float restitution = 1; 442 | auto top = (relVel * -(1 + restitution)).dot(normal); 443 | 444 | float botl1 = std::pow(rp1.dot(normal), 2) * invInertia1; 445 | float botl2 = std::pow(rp2.dot(normal), 2) * invInertia2; 446 | 447 | auto bottom = normal.dot(normal * (invMass1 + invMass2)) + botl1 + botl2; 448 | float impulse = top / bottom; 449 | 450 | impulse /= divider; 451 | 452 | agl::Vec acc1 = normal * (impulse * invMass1); 453 | agl::Vec acc2 = normal * (impulse * -invMass2); 454 | 455 | out1 += acc1; 456 | out2 += acc2; 457 | 458 | rotOut1 -= rp1.dot(normal * impulse) * invInertia1; 459 | rotOut2 += rp2.dot(normal * impulse) * invInertia2; 460 | } 461 | }; 462 | 463 | class TestObj : public PhysicsObj 464 | { 465 | public: 466 | TestObj() : PhysicsObj() 467 | { 468 | return; 469 | } 470 | }; 471 | 472 | class CollisionConstraint 473 | { 474 | public: 475 | static void probe(PhysicsObj &b1, PhysicsObj &b2, std::vector &failure) 476 | { 477 | PolyShape s1; 478 | PolyShape s2; 479 | // CHECK COLLISION 480 | b1.boxToPoly(s1); 481 | b2.boxToPoly(s2); 482 | 483 | auto compCol = [&](PhysicsObj &a, PhysicsObj &b, PolyShape &sa, PolyShape &sb) { 484 | for (agl::Vec &point : sb.points) 485 | { 486 | ConstraintFailure bare; 487 | if (World::pointInBox(sa, point, bare)) 488 | { 489 | failure.emplace_back(bare); 490 | failure.back().b1 = &a; 491 | failure.back().b2 = &b; 492 | failure.back().r1 = failure.back().b1->position - failure.back().inter1; 493 | failure.back().r2 = failure.back().b2->position - failure.back().inter2; 494 | 495 | failure.back().b1->collideCount++; 496 | failure.back().b2->collideCount++; 497 | } 498 | 499 | /* 500 | auto res = a.getDistIfCol(point); 501 | 502 | if (res.first > 0) 503 | { 504 | failure.push_back({}); 505 | failure.back().b1 = &a; 506 | failure.back().b2 = &b; 507 | failure.back().inter1 = point + (res.second 508 | * res.first); failure.back().inter2 = point; failure.back().normal = 509 | res.second; failure.back().depth = res.first; failure.back().r1 510 | = failure.back().b1->position - failure.back().inter1; 511 | failure.back().r2 = 512 | failure.back().b2->position - failure.back().inter2; 513 | 514 | failure.back().b1->collideCount++; 515 | failure.back().b2->collideCount++; 516 | } 517 | */ 518 | } 519 | }; 520 | 521 | compCol(b1, b2, s1, s2); 522 | compCol(b2, b1, s2, s1); 523 | } 524 | }; 525 | 526 | class JointConstraint 527 | { 528 | public: 529 | static void probe(PhysicsObj &b1, PhysicsObj &b2, std::vector &failure) 530 | { 531 | agl::Mat4f rot; 532 | rot.rotateZ(-b1.radToDeg()); 533 | 534 | agl::Vec local1 = b1.position + (rot * b1.local1); 535 | rot.rotateZ(-b1.rootConnect->radToDeg()); 536 | agl::Vec local2 = b1.rootConnect->position + (rot * b1.local2); 537 | 538 | agl::Vec offset = local1 - local2; 539 | agl::Vec normal = offset.normalized(); 540 | float dist = offset.length(); 541 | 542 | if (dist == 0) 543 | { 544 | return; 545 | } 546 | 547 | failure.emplace_back(); 548 | 549 | failure.back().b1 = &b1; 550 | failure.back().b2 = b1.rootConnect; 551 | failure.back().normal = normal; 552 | failure.back().depth = dist; 553 | failure.back().inter1 = local1; 554 | failure.back().inter2 = local2; 555 | failure.back().r1 = b1.position - failure.back().inter1; 556 | failure.back().r2 = b1.rootConnect->position - failure.back().inter2; 557 | 558 | failure.back().b1->collideCount++; 559 | failure.back().b2->collideCount++; 560 | } 561 | }; 562 | -------------------------------------------------------------------------------- /inc/Serializer.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | template ::value>> 9 | void recurse(U processor, T &v, std::string name = "null") 10 | { 11 | processor.process(name, v); 12 | } 13 | 14 | template void recurse(U processor, std::vector &v, std::string name = "null") 15 | { 16 | processor.process(name, v); 17 | 18 | for (auto &ele : v) 19 | { 20 | recurse(U(processor), ele, "[]"); 21 | } 22 | } 23 | 24 | template struct is_std_vector : std::false_type 25 | { 26 | }; 27 | 28 | template struct is_std_vector> : std::true_type 29 | { 30 | }; 31 | 32 | #define RECSER(x) recurse(processor, x, std::string(#x).substr(2)) 33 | 34 | class Output 35 | { 36 | public: 37 | std::ostream &stream; 38 | int indent = 0; 39 | 40 | Output(std::ostream &stream) : stream(stream) 41 | { 42 | } 43 | 44 | Output(Output &o) : stream(o.stream), indent(o.indent + 1) 45 | { 46 | } 47 | 48 | template void process(std::string name, T &value) 49 | { 50 | for (int i = 0; i < indent; i++) 51 | { 52 | stream << "\t"; 53 | } 54 | 55 | if constexpr (std::is_arithmetic::value) 56 | { 57 | stream << name << " = " << value << '\n'; 58 | } 59 | else if constexpr (is_std_vector::value) 60 | { 61 | stream << name << " &" << '\n'; 62 | } 63 | else 64 | { 65 | stream << name << " :\n"; 66 | } 67 | } 68 | }; 69 | 70 | class Input 71 | { 72 | public: 73 | std::istream &stream; 74 | 75 | Input(std::istream &stream) : stream(stream) 76 | { 77 | } 78 | 79 | Input(Input &i) : stream(i.stream) 80 | { 81 | } 82 | 83 | template void process(std::string name, T &value) 84 | { 85 | std::string buf; 86 | 87 | std::getline(stream, buf); 88 | 89 | int indent = 0; 90 | for (char c : buf) 91 | { 92 | if (c == '\t') 93 | { 94 | indent++; 95 | } 96 | else 97 | { 98 | break; 99 | } 100 | } 101 | 102 | buf = trim(buf); 103 | 104 | auto vec = stringSplit(buf, ' '); 105 | 106 | if (vec[1] == "=") 107 | { 108 | value = unstring(vec[2]); 109 | } 110 | 111 | if (vec[1] == "&") 112 | { 113 | if constexpr (is_std_vector::value) 114 | { 115 | std::streampos pos = stream.tellg(); 116 | 117 | value.clear(); 118 | 119 | int size = 0; 120 | 121 | std::string buffer; 122 | while (std::getline(stream, buffer)) 123 | { 124 | int ico = 0; 125 | 126 | for (char c : buffer) 127 | { 128 | if (c == '\t') 129 | { 130 | ico++; 131 | } 132 | else 133 | { 134 | break; 135 | } 136 | } 137 | 138 | if (ico == (indent + 1)) 139 | { 140 | size++; 141 | } 142 | else if (ico <= indent) 143 | { 144 | break; 145 | } 146 | } 147 | 148 | value.resize(size); 149 | 150 | stream.clear(); 151 | stream.seekg(pos); 152 | } 153 | } 154 | } 155 | 156 | static std::vector stringSplit(const std::string &str, char delimiter) 157 | { 158 | std::istringstream iss(str); 159 | std::string token; 160 | std::vector tokens; 161 | 162 | while (std::getline(iss, token, delimiter)) 163 | { 164 | tokens.push_back(token); 165 | } 166 | 167 | return tokens; 168 | } 169 | 170 | static std::string trim(const std::string &str) 171 | { 172 | const auto start = str.find_first_not_of(" \t"); 173 | if (start == std::string::npos) 174 | { 175 | return ""; 176 | } 177 | 178 | const auto end = str.find_last_not_of(" \t"); 179 | return str.substr(start, end - start + 1); 180 | } 181 | 182 | template T unstring(std::string &val) 183 | { 184 | if constexpr (std::is_same()) 185 | { 186 | return val[0]; 187 | } 188 | if constexpr (std::is_integral()) 189 | { 190 | return std::stoll(val); 191 | } 192 | else if constexpr (std::is_same()) 193 | { 194 | return std::stof(val); 195 | } 196 | else if constexpr (std::is_same()) 197 | { 198 | return std::stod(val); 199 | } 200 | 201 | return T(); 202 | } 203 | }; 204 | -------------------------------------------------------------------------------- /inc/Simulation.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Buffer.hpp" 4 | #include "EnDex.hpp" 5 | #include "Food.hpp" 6 | #include "Meat.hpp" 7 | #include "SimulationRules.hpp" 8 | #include "ViteSeg.hpp" 9 | #include "macro.hpp" 10 | #include 11 | 12 | class Simulation 13 | { 14 | public: 15 | SimulationRules simulationRules; 16 | EnDex *env; 17 | 18 | bool active; 19 | 20 | int frame = 0; 21 | 22 | int &foodCap = simulationRules.foodCap; 23 | float &energyCostMultiplier = simulationRules.energyCostMultiplier; 24 | 25 | std::vector startingGenome = { 26 | ViteGenome{{24, 24}, 0, 0, 0, 100}, ViteGenome{{10, 18}, 0, 0, 0, 100}, ViteGenome{{4, 18}, 0, 0, 0, 100}}; 27 | 28 | Simulation() 29 | { 30 | } 31 | 32 | void create(SimulationRules simulationRules, int seed); 33 | void destroy(); 34 | 35 | void threadableUpdate(); 36 | void updateSimulation(); 37 | void update(); 38 | 39 | static Buffer creatureDataToBuffer(CreatureData &creatureData); 40 | static CreatureData bufferToCreatureData(Buffer buffer); 41 | 42 | void addCreature(std::vector genome, agl::Vec position); 43 | void removeCreature(std::list::iterator viteSeg); 44 | 45 | void addFood(agl::Vec position); 46 | void removeFood(std::list::iterator food); 47 | 48 | void addMeat(agl::Vec position); 49 | void addMeat(agl::Vec position, float energy); 50 | void removeMeat(std::list::iterator meat); 51 | }; 52 | -------------------------------------------------------------------------------- /inc/SimulationRules.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "CreatureData.hpp" 4 | #include "Serializer.hpp" 5 | #include "macro.hpp" 6 | #include 7 | 8 | class SimulationRules 9 | { 10 | public: 11 | // starting 12 | agl::Vec size = {10000, 10000}; 13 | agl::Vec gridResolution = {10, 10}; 14 | int startingCreatures = 10; 15 | 16 | // variable 17 | // int preferedCreatures; 18 | // int penaltyBuffer; 19 | // int penaltyPeriod; 20 | 21 | int foodCap = 1000; 22 | float energyCostMultiplier = ENERGYCOSTMULTIPLIER; 23 | 24 | int threads = THREADS; 25 | 26 | float learningRate = .1f; 27 | int memory = 240; 28 | int brainMutation = 3; 29 | int bodyMutation = 50; 30 | float exploration = .5f; 31 | float vaporize = .9f; 32 | std::vector startBody = { 33 | {{24, 24}, {}}, 34 | {{4, 24}, {}}, 35 | }; 36 | std::vector startBrain = {in::Connection(1, 4, 1)}; 37 | int maxConnections; 38 | }; 39 | 40 | template void recurse(T processor, in::Connection &c, std::string name = "null") 41 | { 42 | processor.process(name, c); 43 | 44 | RECSER(c.startNode); 45 | RECSER(c.endNode); 46 | RECSER(c.weight); 47 | RECSER(c.id); 48 | RECSER(c.valid); 49 | RECSER(c.exists); 50 | } 51 | 52 | template void recurse(T processor, SimulationRules &s, std::string name = "null") 53 | { 54 | processor.process(name, s); 55 | 56 | RECSER(s.size); 57 | RECSER(s.gridResolution); 58 | RECSER(s.startingCreatures); 59 | RECSER(s.foodCap); 60 | RECSER(s.energyCostMultiplier); 61 | RECSER(s.threads); 62 | RECSER(s.learningRate); 63 | RECSER(s.memory); 64 | RECSER(s.brainMutation); 65 | RECSER(s.bodyMutation); 66 | RECSER(s.exploration); 67 | RECSER(s.vaporize); 68 | RECSER(s.startBody); 69 | RECSER(s.startBrain); 70 | RECSER(s.maxConnections); 71 | } 72 | -------------------------------------------------------------------------------- /inc/ThreadPool.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | class ThreadPool 10 | { 11 | public: 12 | std::thread **worker = nullptr; 13 | std::mutex jobMutex; 14 | std::queue> jobList; 15 | std::function *job = nullptr; 16 | std::condition_variable isJobAvailable; 17 | int size; 18 | bool terminateSignal = false; 19 | std::atomic count = 0; 20 | 21 | void threadLoop(int id) 22 | { 23 | while (true) 24 | { 25 | job[id] = nullptr; 26 | { 27 | std::unique_lock lock(jobMutex); 28 | isJobAvailable.wait(lock, [this]() { return !jobList.empty() || terminateSignal; }); 29 | 30 | if (terminateSignal) 31 | { 32 | return; 33 | } 34 | 35 | count++; 36 | job[id] = jobList.front(); 37 | jobList.pop(); 38 | } 39 | job[id](); 40 | count--; 41 | } 42 | } 43 | 44 | ThreadPool(int size) : size(size) 45 | { 46 | worker = new std::thread *[size]; 47 | job = new std::function[size]; 48 | 49 | for (int i = 0; i < size; i++) 50 | { 51 | worker[i] = new std::thread(&ThreadPool::threadLoop, this, i); 52 | } 53 | 54 | isJobAvailable.notify_one(); 55 | } 56 | 57 | void queue(std::function func) 58 | { 59 | { 60 | std::unique_lock lock(jobMutex); 61 | jobList.push(func); 62 | } 63 | isJobAvailable.notify_one(); 64 | } 65 | 66 | bool active() 67 | { 68 | if (count || jobList.size()) 69 | { 70 | return true; 71 | } 72 | 73 | return false; 74 | } 75 | 76 | ~ThreadPool() 77 | { 78 | { 79 | std::unique_lock lock(jobMutex); 80 | terminateSignal = true; 81 | } 82 | 83 | isJobAvailable.notify_all(); 84 | 85 | for (int i = 0; i < size; i++) 86 | { 87 | worker[i]->join(); 88 | delete worker[i]; 89 | } 90 | 91 | delete[] worker; 92 | 93 | delete[] job; 94 | } 95 | }; 96 | 97 | // class ThreadDistribute 98 | // { 99 | // public: 100 | // struct Worker 101 | // { 102 | // std::thread *thread = nullptr; 103 | // std::queue> jobList; 104 | // int cursor = 0; 105 | // } *worker; 106 | // 107 | // std::function *job = nullptr; 108 | // int size; 109 | // bool terminateSignal = false; 110 | // 111 | // static void threadLoop(Worker &worker, bool &terminateSignal) 112 | // { 113 | // while (true) 114 | // { 115 | // while (worker.cursor < worker.jobList.size() && terminateSignal == false) 116 | // { 117 | // } 118 | // 119 | // if (terminateSignal) 120 | // { 121 | // return; 122 | // } 123 | // 124 | // worker.jobList.front()(); 125 | // 126 | // worker.cursor++; 127 | // } 128 | // } 129 | // 130 | // ThreadDistribute(int size) : size(size) 131 | // { 132 | // worker = new Worker[size]; 133 | // 134 | // for (int i = 0; i < size; i++) 135 | // { 136 | // worker[i].thread = new std::thread(threadLoop, worker[i], terminateSignal); 137 | // } 138 | // } 139 | // 140 | // void queue(std::function func, int id) 141 | // { 142 | // worker[id].jobList.push(func); 143 | // } 144 | // 145 | // bool active() 146 | // { 147 | // for (int i = 0; i < size; i++) 148 | // { 149 | // if (worker[i].cursor >= worker[i].jobList.size()) 150 | // { 151 | // return true; 152 | // } 153 | // } 154 | // 155 | // return false; 156 | // } 157 | // 158 | // void clear() 159 | // { 160 | // for(int i = 0; i < size; i++) 161 | // { 162 | // worker[i].jobList = std::queue>(); 163 | // worker[i].cursor = 0; 164 | // } 165 | // } 166 | // 167 | // ~ThreadDistribute() 168 | // { 169 | // terminateSignal = true; 170 | // 171 | // for (int i = 0; i < size; i++) 172 | // { 173 | // worker[i].thread->join(); 174 | // 175 | // delete worker[i].thread; 176 | // } 177 | // 178 | // delete[] worker; 179 | // } 180 | // }; 181 | -------------------------------------------------------------------------------- /inc/ViteSeg.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "PhysicsObj.hpp" 4 | 5 | class ViteGenome 6 | { 7 | public: 8 | agl::Vec size; 9 | float armour; 10 | float damage; 11 | float muscle; 12 | int hue; 13 | }; 14 | 15 | class ViteSeg : public PhysicsObj 16 | { 17 | public: 18 | float health; 19 | float energy; 20 | 21 | int geneIndex; 22 | std::vector genome; 23 | 24 | ViteSeg *parent; 25 | std::vector children; 26 | 27 | void setup(agl::Vec pos = {0, 0}) 28 | { 29 | PhysicsObj::setup(pos, genome[geneIndex].size, 30 | (genome[geneIndex].size.x * genome[geneIndex].size.y) / 100.); 31 | 32 | if(parent != nullptr) 33 | { 34 | position.y = parent->position.y + parent->size.y / 2 + size.y / 2; 35 | position.x = parent->position.x; 36 | } 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /inc/macro.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // sets the max FPS, set to 0 to disable 4 | // disable vsync to go above monitor refresh rate 5 | #define TARGETFPS 0 6 | // sets if vysnc should be on 7 | #define VSYNC true 8 | 9 | // output av pop, size, speed, sight in a format interprettable be something 10 | // like gnuplot 11 | #define LOGCREATUREDATA 12 | 13 | // food avoids other food, value is pressure multiplier 14 | #define FOODPRESSURE 20 15 | 16 | // food slowly drifts to a random location, value is max range that the location 17 | // is 18 | // #define ACTIVEFOOD 500 19 | 20 | // food experiences drag, value is drag coeficient 21 | #define FOODDRAG 0.0005f 22 | 23 | // food experiences a pushback force at the border of the simulation 24 | #define FOODBORDER 25 | 26 | #define VITEDENS (1. / 144.) 27 | 28 | #define THREADS 1 29 | #define EATRADIUS 20 30 | #define DAMAGE 4 31 | 32 | #define FOODVOL 40 33 | #define MEATVOL 60 34 | #define LEACHVOL 1 35 | 36 | #define FOODCAP 37 | 38 | #define BITEDELAY 20 39 | 40 | #define FOODENERGY 1 41 | #define MEATENERGY 1 42 | 43 | #define RAY_LENGTH 1000 44 | 45 | #define CONSTANT_INPUT 0 46 | #define X_INPUT 1 47 | #define Y_INPUT 2 48 | #define ROTATION_INPUT 3 49 | #define SPEED_INPUT 4 50 | #define FOOD_DISTANCE 5 51 | #define FOOD_ROTATION 6 52 | #define CREATURE_DISTANCE 7 53 | #define CREATURE_ROTATION 8 54 | #define ENERGY_INPUT 9 55 | #define HEALTH_INPUT 10 56 | #define LIFE_INPUT 11 57 | #define MEAT_DISTANCE 12 58 | #define MEAT_ROTATION 13 59 | #define CREATURE_PREFERENCE 14 60 | 61 | #define PREGNANCY_COST 1 62 | #define METABOLISM 1 63 | 64 | #define MENU_PADDING 1 65 | 66 | #define BASE_B_VALUE 63 67 | 68 | #define WIDTH 1300 69 | #define HEIGHT 700 70 | //#define WIDTH 1920 71 | //#define HEIGHT 1080 72 | 73 | #define CLEARCOLOR \ 74 | { \ 75 | 20, 20, 30 \ 76 | } 77 | 78 | #define NETWORK_PADDING 20 79 | 80 | #define EXTRA_BYTES 6 81 | 82 | #define MENU_BORDERTHICKNESS (float)6 83 | #define MENU_DECORATIONHEIGHT (float)(4 + (MENU_BORDERTHICKNESS * 4)) 84 | 85 | #define MENU_BORDEREDGE (float)2 86 | 87 | #define ENERGYCOSTMULTIPLIER 0.0003f 88 | 89 | #define ENVTYPES ViteSeg, Food, Meat, JointConstraint 90 | -------------------------------------------------------------------------------- /inc/other.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | float loop(float min, float max, float value); 5 | 6 | float vectorAngle(agl::Vec vec); 7 | 8 | agl::Color hueToRGB(int hue); 9 | 10 | int roundUp(float input, int period); 11 | 12 | struct Debug 13 | { 14 | static std::vector log; 15 | }; 16 | 17 | float cross2D(agl::Vec a, agl::Vec b); 18 | 19 | agl::Vec perp(agl::Vec vec); 20 | 21 | agl::Vec closestPointToLine(agl::Vec a, agl::Vec b, agl::Vec p); 22 | -------------------------------------------------------------------------------- /lib/updateAGL.sh: -------------------------------------------------------------------------------- 1 | rm -vrf AGL 2 | 3 | git clone https://github.com/4t-2/AGL 4 | 5 | mv AGL/AGL AGLrenamed 6 | 7 | rm -vrf AGL 8 | 9 | mv AGLrenamed AGL 10 | -------------------------------------------------------------------------------- /lib/updateIN.sh: -------------------------------------------------------------------------------- 1 | rm -vrf IN 2 | 3 | git clone https://github.com/4t-2/IntelligentNetworks 4 | 5 | mv IntelligentNetworks/IntNet IN 6 | 7 | rm -vrf IntelligentNetworks 8 | -------------------------------------------------------------------------------- /linecount.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | IN="$(search .cpp)" 4 | 5 | mails=$(echo $IN | tr ";" "\n") 6 | 7 | for addr in $mails 8 | do 9 | let total="$(cat $addr | wc -l)"+total 10 | done 11 | 12 | echo $total 13 | -------------------------------------------------------------------------------- /src/Buffer.cpp: -------------------------------------------------------------------------------- 1 | #include "../inc/Buffer.hpp" 2 | 3 | #include 4 | 5 | Buffer::Buffer(int size) 6 | { 7 | this->size = size; 8 | data = new unsigned char[this->size]; 9 | 10 | return; 11 | } 12 | 13 | Buffer::Buffer(const Buffer &buffer) 14 | { 15 | size = buffer.size; 16 | delete[] data; 17 | data = new unsigned char[size]; 18 | 19 | for (int i = 0; i < size; i++) 20 | { 21 | data[i] = buffer.data[i]; 22 | } 23 | 24 | return; 25 | } 26 | 27 | Buffer::Buffer() 28 | { 29 | data = nullptr; 30 | 31 | return; 32 | } 33 | 34 | Buffer::~Buffer() 35 | { 36 | delete[] data; 37 | 38 | return; 39 | } 40 | 41 | void Buffer::operator=(Buffer &buffer) 42 | { 43 | size = buffer.size; 44 | delete[] data; 45 | data = new unsigned char[size]; 46 | 47 | for (int i = 0; i < size; i++) 48 | { 49 | data[i] = buffer.data[i]; 50 | } 51 | 52 | return; 53 | } 54 | 55 | void Buffer::printBits() 56 | { 57 | for (int x = 0; x < size; x++) 58 | { 59 | for (int i = 0; i < 8; i++) 60 | { 61 | printf("%d", !!((data[x] << i) & 0x80)); 62 | } 63 | 64 | printf(" "); 65 | } 66 | 67 | printf("\n"); 68 | } 69 | -------------------------------------------------------------------------------- /src/Creature.cpp: -------------------------------------------------------------------------------- 1 | #include "../inc/Creature.hpp" 2 | #include "../inc/Buffer.hpp" 3 | #include 4 | 5 | 6 | Creature::Creature() 7 | { 8 | return; 9 | } 10 | 11 | void Creature::clear() 12 | { 13 | position = {0, 0}; 14 | velocity = {0, 0}; 15 | force = {0, 0}; 16 | rotation = 0; 17 | // radius = 0; 18 | eating = false; 19 | layingEgg = false; 20 | energy = 0; 21 | health = 0; 22 | 23 | return; 24 | } 25 | 26 | Creature::~Creature() 27 | { 28 | this->clear(); 29 | } 30 | 31 | float closerObject(agl::Vec offset, float nearestDistance) 32 | { 33 | return nearestDistance; 34 | } 35 | 36 | void Creature::learnBrain(SimulationRules &simRules) 37 | { 38 | } 39 | 40 | void Creature::updateNetwork() 41 | { 42 | // if (creatureData.usePG) 43 | // { 44 | // int memSlot = (maxLife - life) % simulationRules->memory; 45 | // 46 | // if (memSlot == 0) 47 | // { 48 | // for (int i = 0; i < network->structure.totalOutputNodes; i++) 49 | // { 50 | // shift[i] = (((rand() / (float)RAND_MAX) * 2) - 1) * simulationRules->exploration; 51 | // } 52 | // } 53 | // 54 | // for (int i = 0; i < network->structure.totalInputNodes; i++) 55 | // { 56 | // memory[memSlot].state[i] = network->inputNode[i]->value; 57 | // if (std::isnan(memory[memSlot].state[i])) 58 | // { 59 | // std::cout << life << " nan " << i << '\n'; 60 | // } 61 | // } 62 | // 63 | // if (std::isnan(reward)) 64 | // { 65 | // std::cout << "reward" << '\n'; 66 | // } 67 | // memory[memSlot].reward = reward; 68 | // reward = 0; 69 | // 70 | // for (int i = 0; i < network->structure.totalOutputNodes; i++) 71 | // { 72 | // memory[memSlot].action[i] = network->outputNode[i].value; 73 | // if (std::isnan(memory[memSlot].action[i])) 74 | // { 75 | // std::cout << life << " nan action " << i << '\n'; 76 | // } 77 | // } 78 | // } 79 | // 80 | // if ((maxLife - life) % simulationRules->memory == 0 && maxLife != life && creatureData.usePG) 81 | // { 82 | // float loss = 0; 83 | // 84 | // for (int x = simulationRules->memory - 1; x >= 0; x--) 85 | // { 86 | // for (int y = 1; (x + y) < simulationRules->memory; y++) 87 | // { 88 | // float old = memory[x].reward; 89 | // memory[x].reward += memory[x + y].reward * std::pow(simulationRules->vaporize, y); 90 | // } 91 | // 92 | // loss += memory[x].reward; 93 | // } 94 | // 95 | // loss /= simulationRules->memory; 96 | // 97 | // int oldLoss = loss; 98 | // loss -= baseline; 99 | // 100 | // baseline = oldLoss; 101 | // 102 | // std::vector gradients; 103 | // 104 | // network->setupGradients(&gradients); 105 | // 106 | // for (int i = 0; i < simulationRules->memory; i++) 107 | // { 108 | // for (int x = 0; x < network->structure.totalInputNodes; x++) 109 | // { 110 | // network->setInputNode(x, memory[i].state[x]); 111 | // } 112 | // 113 | // network->update(); 114 | // 115 | // std::vector target(network->structure.totalOutputNodes); 116 | // 117 | // for (int x = 0; x < network->structure.totalOutputNodes; x++) 118 | // { 119 | // target[x] = memory[i].action[x]; 120 | // } 121 | // 122 | // network->calcGradients(&gradients, target); 123 | // } 124 | // 125 | // network->learningRate = simulationRules->learningRate; 126 | // network->applyGradients(gradients, loss, simulationRules->memory); 127 | // } 128 | 129 | /*int node = 2;*/ 130 | /**/ 131 | /*network->setInputNode(0, 1);*/ 132 | /*network->setInputNode(1, sinf((maxLife - life) / 20.f));*/ 133 | /**/ 134 | /*for (int i = 0; i < segments.size(); i++)*/ 135 | /*{*/ 136 | /* if (segments[i]->rootConnect != nullptr)*/ 137 | /* {*/ 138 | /* network->setInputNode(node, segments[i]->getJointAngle() / (float)(PI / 2));*/ 139 | /* node++;*/ 140 | /* network->setInputNode(node, segments[i]->motor / (float)(PI / 2));*/ 141 | /* node++;*/ 142 | /* }*/ 143 | /*}*/ 144 | /**/ 145 | /*network->update();*/ 146 | 147 | // for (int i = 0; i < network->structure.totalOutputNodes; i++) 148 | // { 149 | // network->outputNode[i].value += shift[i]; 150 | // network->outputNode[i].value = 151 | // std::clamp(network->outputNode[i].value, -1, 1); 152 | // } 153 | } 154 | 155 | void Creature::updateActions() 156 | { 157 | int node = 0; 158 | 159 | for (auto &seg : segments) 160 | { 161 | if (seg->rootConnect != nullptr) 162 | { 163 | /*float ang = seg->getJointAngle();*/ 164 | /*float net = network->outputNode[node].value * (float)(PI / 2);*/ 165 | /**/ 166 | /*// float net = sin(frame / 20.);*/ 167 | /*// std::cout << ang << '\n';*/ 168 | /**/ 169 | /*float diff = ang - net;*/ 170 | /*// std::cout << diff << '\n';*/ 171 | /**/ 172 | /*seg->motor = (1 / 6.f * diff) * seg->maxMotor;*/ 173 | /*// std::cout << agl::radianToDegree(joint[i].getAngle()) << '\n';*/ 174 | /**/ 175 | /*node++;*/ 176 | } 177 | } 178 | 179 | life--; 180 | 181 | return; 182 | } 183 | -------------------------------------------------------------------------------- /src/CreatureData.cpp: -------------------------------------------------------------------------------- 1 | #include "../inc/CreatureData.hpp" 2 | 3 | CreatureData::CreatureData() 4 | { 5 | netStr = nullptr; 6 | 7 | return; 8 | } 9 | 10 | CreatureData::CreatureData(float sight, int hue, std::vector &segs, std::vector &cons, int maxCon) 11 | { 12 | this->sight = sight; 13 | this->hue = hue; 14 | 15 | // default design 16 | 17 | sd = segs; 18 | 19 | std::vector vec = cons; 20 | 21 | while (vec.size() < maxCon) 22 | { 23 | in::Connection c; 24 | c.id = -1; 25 | c.valid = false; 26 | c.exists = false; 27 | c.weight = -1; 28 | c.startNode = -1; 29 | c.endNode = -1; 30 | vec.push_back(c); 31 | } 32 | 33 | netStr = new in::NetworkStructure(maxCon, totalSegJoints(sd) * 2 + 2, 0, totalSegJoints(sd), vec); 34 | 35 | return; 36 | } 37 | 38 | CreatureData::CreatureData(const CreatureData &creatureData) 39 | { 40 | delete netStr; 41 | netStr = new in::NetworkStructure(*creatureData.netStr); 42 | 43 | sight = creatureData.sight; 44 | hue = creatureData.hue; 45 | startEnergy = creatureData.startEnergy; 46 | preference = creatureData.preference; 47 | metabolism = creatureData.metabolism; 48 | useNEAT = creatureData.useNEAT; 49 | usePG = creatureData.usePG; 50 | sd = creatureData.sd; 51 | } 52 | 53 | void CreatureData::operator=(CreatureData &creatureData) 54 | { 55 | delete netStr; 56 | netStr = new in::NetworkStructure(*creatureData.netStr); 57 | 58 | sight = creatureData.sight; 59 | hue = creatureData.hue; 60 | startEnergy = creatureData.startEnergy; 61 | preference = creatureData.preference; 62 | metabolism = creatureData.metabolism; 63 | useNEAT = creatureData.useNEAT; 64 | usePG = creatureData.usePG; 65 | sd = creatureData.sd; 66 | } 67 | 68 | CreatureData::~CreatureData() 69 | { 70 | delete netStr; 71 | 72 | return; 73 | } 74 | 75 | int CreatureData::totalSegJoints(std::vector &segs) 76 | { 77 | int total = 0; 78 | 79 | for (int i = 0; i < segs.size(); i++) 80 | { 81 | if (i != 0) 82 | { 83 | total++; 84 | } 85 | 86 | total += segs[i].branch.size() * 2; 87 | } 88 | 89 | return total; 90 | } 91 | -------------------------------------------------------------------------------- /src/Egg.cpp: -------------------------------------------------------------------------------- 1 | #include "../inc/Egg.hpp" 2 | 3 | void Egg::setup(CreatureData &creatureData) 4 | { 5 | this->creatureData = creatureData; 6 | 7 | timeleft = 100; 8 | 9 | return; 10 | } 11 | 12 | void Egg::update() 13 | { 14 | timeleft--; 15 | } 16 | 17 | void Egg::clear() 18 | { 19 | timeleft = 0; 20 | } 21 | -------------------------------------------------------------------------------- /src/Menu.cpp: -------------------------------------------------------------------------------- 1 | #include "../inc/Menu.hpp" 2 | agl::Event *MenuShare::event; 3 | agl::Text *MenuShare::text; 4 | agl::Text *MenuShare::smallText; 5 | agl::Rectangle *MenuShare::rect; 6 | agl::Circle *MenuShare::circ; 7 | agl::Texture *MenuShare::border; 8 | agl::Texture *MenuShare::blank; 9 | void *MenuShare::focusedMenu; 10 | bool *MenuShare::leftClick; 11 | FocusableElement *FocusableElement::focusedField; 12 | agl::Shader *MenuShare::menuShader; 13 | agl::Shader *MenuShare::baseShader; 14 | agl::Camera *MenuShare::camera; 15 | -------------------------------------------------------------------------------- /src/Simulation.cpp: -------------------------------------------------------------------------------- 1 | #include "../inc/Simulation.hpp" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #define newEnergyDensity(biomass, bioEnergy, additional, addEnergy) \ 13 | ((biomass * bioEnergy) + (additional * addEnergy)) / (biomass + additional) 14 | 15 | void randomData(Buffer *buffer) 16 | { 17 | for (int i = 0; i < buffer->size; i++) 18 | { 19 | for (int x = 0; x < 8; x++) 20 | { 21 | int bit = (((float)rand() / (float)RAND_MAX) * 2); 22 | buffer->data[i] = buffer->data[i] | (bit << x); 23 | } 24 | } 25 | 26 | return; 27 | } 28 | 29 | int generateRandomNumber(int min, int max) 30 | { 31 | return min + rand() % (max - min + 1); 32 | } 33 | 34 | void Simulation::create(SimulationRules simulationRules, int seed) 35 | { 36 | active = true; 37 | frame = 0; 38 | 39 | this->simulationRules = simulationRules; 40 | 41 | srand(seed); 42 | 43 | env = new EnDex; 44 | /*env.setupGrid(simulationRules.size, simulationRules.gridResolution);*/ 45 | 46 | for (int i = 0; i < simulationRules.startingCreatures; i++) 47 | { 48 | CreatureData creatureData(1, generateRandomNumber(0, 255), simulationRules.startBody, 49 | simulationRules.startBrain, simulationRules.maxConnections); 50 | 51 | creatureData.useNEAT = true; 52 | creatureData.usePG = false; 53 | creatureData.preference = 1; 54 | creatureData.metabolism = METABOLISM; 55 | 56 | agl::Vec position; 57 | position.x = (rand() / (float)RAND_MAX) * simulationRules.size.x; 58 | position.y = (rand() / (float)RAND_MAX) * simulationRules.size.y; 59 | 60 | this->addCreature(startingGenome, position); 61 | } 62 | 63 | for (int i = 0; i < foodCap; i++) 64 | { 65 | this->addFood({(float)rand() / (float)RAND_MAX * simulationRules.size.x, 66 | (float)rand() / (float)RAND_MAX * simulationRules.size.y}); 67 | } 68 | 69 | foodCap = simulationRules.foodCap; 70 | 71 | /*env.setThreads(simulationRules.threads);*/ 72 | 73 | return; 74 | } 75 | 76 | void Simulation::destroy() 77 | { 78 | active = false; 79 | 80 | delete env; 81 | /*env.destroy();*/ 82 | } 83 | 84 | void Simulation::addCreature(std::vector genome, agl::Vec pos) 85 | { 86 | ViteSeg &vite1 = env->addEntity(); 87 | vite1.genome = genome; 88 | vite1.geneIndex = 0; 89 | vite1.health = 0; 90 | vite1.energy = 0; 91 | vite1.parent = nullptr; 92 | vite1.setup({100, 100}); 93 | 94 | ViteSeg &vite2 = env->addEntity(); 95 | vite2.genome = genome; 96 | vite2.geneIndex = 1; 97 | vite2.health = 0; 98 | vite2.energy = 0; 99 | vite2.parent = &vite1; 100 | vite2.setup(); 101 | PhysicsObj::addJoint(vite2, {0, -vite2.size.y / 2}, *vite2.parent, {0, vite2.parent->size.y / 2}); 102 | 103 | ViteSeg &vite3 = env->addEntity(); 104 | vite3.genome = genome; 105 | vite3.geneIndex = 2; 106 | vite3.health = 0; 107 | vite3.energy = 0; 108 | vite3.parent = &vite2; 109 | vite3.setup(); 110 | PhysicsObj::addJoint(vite3, {0, -vite3.size.y / 2}, *vite3.parent, {0, vite3.parent->size.y / 2}); 111 | 112 | /**/ 113 | /* Creature &newCreature = env->addEntity();*/ 114 | /* // INPUT*/ 115 | /* // constant*/ 116 | /* // x pos*/ 117 | /* // y pos*/ 118 | /* // rotation*/ 119 | /* // speed*/ 120 | /* // Ray[i] distance to object*/ 121 | /* // Ray[i] object type (-1 = creature, 0 = nothing, 1 = food)*/ 122 | /* //*/ 123 | /* // OUTPUT*/ 124 | /* // Move foward*/ 125 | /* // Move backward*/ 126 | /* // Turn right*/ 127 | /* // Turn left*/ 128 | /* // Eat*/ 129 | /* // Lay egg*/ 130 | /**/ 131 | /* newCreature.creatureData = creatureData;*/ 132 | /**/ 133 | /* // sight = 1;*/ 134 | /* // speed = 1;*/ 135 | /* // size = 1;*/ 136 | /**/ 137 | /* newCreature.health = 100;*/ 138 | /* newCreature.life = 60 * 60 * 10;*/ 139 | /**/ 140 | /* newCreature.maxEnergy = 100;*/ 141 | /* newCreature.maxHealth = 100;*/ 142 | /* newCreature.maxLife = 60 * 60;*/ 143 | /**/ 144 | /* newCreature.maxBiomass = 100;*/ 145 | /* newCreature.biomass = 0;*/ 146 | /* newCreature.energyDensity = 0.0;*/ 147 | /**/ 148 | /* // newCreature.radius = 12.5 * size;*/ 149 | /**/ 150 | /* newCreature.eggHealthCost = (newCreature.maxHealth / 2);*/ 151 | /* newCreature.eggEnergyCost = (newCreature.maxEnergy / 10);*/ 152 | /* newCreature.eggTotalCost = newCreature.eggHealthCost + 153 | * newCreature.eggEnergyCost;*/ 154 | /* newCreature.eggDesposit = 0;*/ 155 | /**/ 156 | /* newCreature.energy = creatureData.startEnergy + 1;*/ 157 | /**/ 158 | /* PhysicsObj *lastSpine = nullptr;*/ 159 | /**/ 160 | /* int totalJoints = 0;*/ 161 | /*#define MASSCALC(size, dens) size.x *size.y *dens*/ 162 | /**/ 163 | /* for (int i = 0; i < creatureData.sd.size(); i++)*/ 164 | /* {*/ 165 | /* if (i != 0)*/ 166 | /* {*/ 167 | /* TestObj &en = env->addEntity();*/ 168 | /**/ 169 | /* en.setup(lastSpine->position +*/ 170 | /* agl::Vec{0, 171 | * (lastSpine->size.y / 2) + (creatureData.sd[i].size.y / 2)},*/ 172 | /* creatureData.sd[i].size, VITEDENS * 173 | * creatureData.sd[i].size.x * creatureData.sd[i].size.y);*/ 174 | /**/ 175 | /* PhysicsObj::addJoint(en, {0, -en.size.y / 2}, 176 | * *lastSpine, {0, lastSpine->size.y / 2});*/ 177 | /* totalJoints++;*/ 178 | /**/ 179 | /* en.maxMotor = std::min(en.size.x, lastSpine->size.x) * 180 | * (1 / 4.f);*/ 181 | /**/ 182 | /* newCreature.segments.emplace_back(&en);*/ 183 | /* }*/ 184 | /* else*/ 185 | /* {*/ 186 | /* static_cast(newCreature)*/ 187 | /* .setup(pos, creatureData.sd[0].size, VITEDENS * 188 | * creatureData.sd[i].size.x * creatureData.sd[i].size.y);*/ 189 | /* newCreature.segments.emplace_back(&newCreature);*/ 190 | /* }*/ 191 | /* (void)totalJoints;*/ 192 | /**/ 193 | /* lastSpine = newCreature.segments.back();*/ 194 | /**/ 195 | /* PhysicsObj *lastLimb[2] = {nullptr, nullptr};*/ 196 | /**/ 197 | /* lastLimb[0] = lastSpine;*/ 198 | /* lastLimb[1] = lastSpine;*/ 199 | /**/ 200 | /* for (int x = 0; x < creatureData.sd[i].branch.size(); x++)*/ 201 | /* {*/ 202 | /* for (int s = -1; s < 2; s += 2)*/ 203 | /* {*/ 204 | /* TestObj &en = env->addEntity();*/ 205 | /**/ 206 | /* en.setup(lastLimb[(s + 1) / 2]->position +*/ 207 | /* agl::Vec{*/ 208 | /* (lastLimb[(s + 209 | * 1) / 2]->size.x / 2) + (creatureData.sd[i].branch[x].size.y / 2), 0} **/ 210 | /* (float)s,*/ 211 | /**/ 212 | /* creatureData.sd[i].branch[x].size, 213 | * MASSCALC(creatureData.sd[i].branch[x].size, VITEDENS));*/ 214 | /**/ 215 | /* en.rotation = (float)PI / 2 * -s;*/ 216 | /**/ 217 | /* PhysicsObj::addJoint(en, {0, -en.size.y / 2}, 218 | * *lastLimb[(s + 1) / 2],*/ 219 | /* {lastLimb[(s 220 | * + 1) / 2]->size.x / 2 * s, 0});*/ 221 | /* totalJoints++;*/ 222 | /**/ 223 | /* newCreature.segments.emplace_back(&en);*/ 224 | /**/ 225 | /* en.maxMotor = std::min(en.size.x, lastLimb[(s + 226 | * 1) / 2]->size.y) * (1 / 4.f);*/ 227 | /**/ 228 | /* lastLimb[(s + 1) / 2] = &en;*/ 229 | /* }*/ 230 | /* }*/ 231 | /* }*/ 232 | /**/ 233 | /* // // newCreature.rotation = ((float)rand() / (float)RAND_MAX) * PI * 234 | * 2;*/ 235 | /* //*/ 236 | /* // newCreature.segments.emplace_back(&newCreature);*/ 237 | /* //*/ 238 | /* // auto &r0 = env.addEntity();*/ 239 | /* // {*/ 240 | /* // r0.setup({position.x, position.y + newCreature.size.y}, {4,*/ 241 | /* // newCreature.size.y}, 1);*/ 242 | /* //*/ 243 | /* // PhysicsObj::addJoint(r0, {0, -r0.size.y / 2}, newCreature, {0,*/ 244 | /* // newCreature.size.y / 2}); r0.motor = .1;*/ 245 | /* //*/ 246 | /* // newCreature.segments.emplace_back(&r0);*/ 247 | /* // }*/ 248 | /* //*/ 249 | /* // {*/ 250 | /* // auto &r1 = env.addEntity();*/ 251 | /* // {*/ 252 | /* // r1.setup(newCreature.position + agl::Vec{newCreature.size.x*/ 254 | /* // / 2 + 8, 0}, {2, 16}, 1); r1.rotation = -PI / 2;*/ 255 | /* //*/ 256 | /* // PhysicsObj::addJoint(r1, {0, -r1.size.y / 2}, 257 | * newCreature,*/ 258 | /* // {newCreature.size.x / 2, 0});*/ 259 | /* //*/ 260 | /* // newCreature.segments.emplace_back(&r1);*/ 261 | /* // }*/ 262 | /* // }*/ 263 | /* // {*/ 264 | /* // auto &r1 = env.addEntity();*/ 265 | /* // {*/ 266 | /* // r1.setup(newCreature.position + agl::Vec{-newCreature.size.x / 2 - 8, 0}, {2, 16}, 1); 268 | * r1.rotation = PI*/ 269 | /* // / 2;*/ 270 | /* //*/ 271 | /* // PhysicsObj::addJoint(r1, {0, -r1.size.y / 2}, 272 | * newCreature,*/ 273 | /* // {-newCreature.size.x / 2, 0});*/ 274 | /* //*/ 275 | /* // newCreature.segments.emplace_back(&r1);*/ 276 | /* // }*/ 277 | /* // }*/ 278 | /* //*/ 279 | /* // // newCreature.position.x += newCreature.size.x / 2;*/ 280 | /* // // newCreature.position.y += newCreature.size.y / 2;*/ 281 | /* // // newCreature.rotation = PI / 2;*/ 282 | } 283 | 284 | void Simulation::removeCreature(std::list::iterator vite) 285 | { 286 | env->removeEntity(vite); 287 | 288 | return; 289 | } 290 | 291 | void Simulation::addFood(agl::Vec position) 292 | { 293 | Food &newFood = env->addEntity(); 294 | newFood.position = position; 295 | 296 | #ifdef ACTIVEFOOD 297 | newFood.nextRandPos(simulationRules.size); 298 | #endif 299 | } 300 | 301 | void Simulation::removeFood(std::list::iterator food) 302 | { 303 | env->removeEntity(food, [&](Food &food) {}); 304 | 305 | return; 306 | } 307 | 308 | void Simulation::addMeat(agl::Vec position, float energy) 309 | { 310 | Meat &newMeat = env->addEntity(); 311 | newMeat.position = position; 312 | // newMeat.radius = (energy / 50.) * 5; 313 | newMeat.rotation = ((float)rand() / (float)RAND_MAX) * 360; 314 | newMeat.lifetime = newMeat.energyVol * 288; 315 | } 316 | 317 | void Simulation::addMeat(agl::Vec position) 318 | { 319 | this->addMeat(position, 50); 320 | } 321 | 322 | void Simulation::removeMeat(std::list::iterator meat) 323 | { 324 | env->removeEntity(meat, [&](Meat &meat) {}); 325 | 326 | return; 327 | } 328 | 329 | float mutShift(float f, float min, float max) 330 | { 331 | float push = ((float)rand() / (float)RAND_MAX); 332 | push -= .5; 333 | push /= 2; 334 | 335 | return std::max((float)min, std::min(max, f + push)); 336 | } 337 | 338 | void recurseSegs(std::vector &sd) 339 | { 340 | for (SegmentData &s : sd) 341 | { 342 | if (generateRandomNumber(0, 1)) 343 | { 344 | agl::Vec delta = {generateRandomNumber(-1, 1), generateRandomNumber(-1, 1)}; 345 | 346 | s.size += delta; 347 | } 348 | 349 | if (s.size.x < 1) 350 | { 351 | s.size.x = 1; 352 | } 353 | else if (s.size.y < 1) 354 | { 355 | s.size.y = 1; 356 | } 357 | 358 | recurseSegs(s.branch); 359 | } 360 | } 361 | 362 | void mutateBodu(in::NetworkStructure *netStr, std::vector &sd) 363 | { 364 | if (1) // remove 365 | { 366 | int seg = 1; 367 | 368 | int del = 1 + CreatureData::totalSegJoints(sd[seg].branch); 369 | 370 | sd.erase(std::next(sd.begin(), seg)); 371 | 372 | int node = 2 + (2 * seg) + netStr->totalInputNodes + netStr->totalHiddenNodes; 373 | 374 | for (int i = node; i < (node + del); i++) 375 | { 376 | for (int x = 0; x < netStr->totalConnections; x++) 377 | { 378 | if (netStr->connection[x].endNode == node || netStr->connection[x].startNode == node) 379 | { 380 | netStr->removeConnection(x); 381 | continue; 382 | } 383 | 384 | if (netStr->connection[x].endNode >= (node + del)) 385 | { 386 | ((in::Connection *)&netStr->connection[x])->endNode -= del; 387 | } 388 | else if (netStr->connection[x].startNode >= (node + del)) 389 | { 390 | ((in::Connection *)&netStr->connection[x])->endNode -= del; 391 | } 392 | } 393 | } 394 | } 395 | else if (0) // add 396 | { 397 | int seg = 0; 398 | 399 | sd.insert(std::next(sd.begin(), seg), {sd[seg].size}); 400 | } 401 | else if (0) // duplicate 402 | { 403 | int seg = 0; 404 | 405 | sd.insert(std::next(sd.begin(), seg), sd[seg]); 406 | Debug::log.emplace_back(std::to_string(sd.size()) + " is new"); 407 | } 408 | } 409 | 410 | bool inRange(int num, int min, int max) 411 | { 412 | return num >= min && num <= max ? true : false; 413 | } 414 | 415 | int segTotalOneSided(std::vector &segs) 416 | { 417 | int total = 0; 418 | 419 | for (int i = 0; i < segs.size(); i++) 420 | { 421 | if (i != 0) 422 | { 423 | total++; 424 | } 425 | 426 | total += segs[i].branch.size(); 427 | } 428 | 429 | return total; 430 | } 431 | 432 | void mutate(CreatureData *creatureData, int bodyMutation, int networkCycles) 433 | { 434 | creatureData->hue = mutShift(creatureData->hue / 60., 0, 359. / 60) * 60; 435 | 436 | { 437 | int perc = generateRandomNumber(0, 4); 438 | 439 | if (perc == 0) 440 | { 441 | int choice = generateRandomNumber(0, 1); 442 | 443 | std::vector jointMap; 444 | 445 | for (int i = 0; i < creatureData->netStr->totalNodes; i++) 446 | { 447 | jointMap.push_back(i); 448 | } 449 | 450 | if (choice == 0 && creatureData->sd.size() > 1) // remove 451 | { 452 | int segTot = CreatureData::totalSegJoints(creatureData->sd); 453 | (void)segTot; 454 | int segTotOneSided = segTotalOneSided(creatureData->sd); 455 | 456 | int seg = generateRandomNumber(1, segTotOneSided); 457 | 458 | int del = 0; 459 | 460 | int segTrack = 0; 461 | int actualNode = -1; 462 | 463 | for (int i = 0; i < creatureData->sd.size(); i++) 464 | { 465 | if (seg == segTrack) 466 | { 467 | del = creatureData->sd[i].branch.size() + 1; 468 | creatureData->sd.erase(std::next(creatureData->sd.begin(), i)); 469 | goto exit1; 470 | } 471 | segTrack++; 472 | actualNode++; 473 | for (int x = 0; x < creatureData->sd[i].branch.size(); x++) 474 | { 475 | if (seg == segTrack) 476 | { 477 | del = 1; 478 | creatureData->sd[i].branch.erase(std::next(creatureData->sd[i].branch.begin(), x)); 479 | goto exit1; 480 | } 481 | segTrack++; 482 | actualNode += 2; 483 | } 484 | } 485 | 486 | exit1:; 487 | 488 | for (auto it = jointMap.begin(); it != jointMap.end();) 489 | { 490 | int node = *it; 491 | 492 | if (node == (actualNode * 2) + 2) 493 | { 494 | it = jointMap.erase(it, std::next(it, del * 2)); 495 | 496 | continue; 497 | } 498 | if (node == creatureData->netStr->totalInputNodes + actualNode) 499 | { 500 | it = jointMap.erase(it, std::next(it, del)); 501 | continue; 502 | } 503 | 504 | it++; 505 | } 506 | 507 | for (int i = 0; i < creatureData->netStr->totalConnections; i++) 508 | { 509 | in::Connection *con = (in::Connection *)&creatureData->netStr->connection[i]; 510 | 511 | if (!con->exists || !con->valid) 512 | { 513 | continue; 514 | } 515 | 516 | if (inRange(con->startNode, (actualNode * 2) + 2, (actualNode * 2) + 2 + (del * 2) - 1)) 517 | { 518 | creatureData->netStr->removeConnection(i); 519 | } 520 | if (inRange(con->startNode, creatureData->netStr->totalInputNodes + actualNode, 521 | creatureData->netStr->totalInputNodes + actualNode + del - 1)) 522 | { 523 | creatureData->netStr->removeConnection(i); 524 | } 525 | if (inRange(con->endNode, creatureData->netStr->totalInputNodes + actualNode, 526 | creatureData->netStr->totalInputNodes + actualNode + del - 1)) 527 | { 528 | creatureData->netStr->removeConnection(i); 529 | } 530 | } 531 | } 532 | else if (choice == 1) // extend 533 | { 534 | int segTot = CreatureData::totalSegJoints(creatureData->sd); 535 | (void)segTot; 536 | int segTotOneSided = segTotalOneSided(creatureData->sd); 537 | (void)segTotOneSided; 538 | 539 | int seg = generateRandomNumber(0, creatureData->sd.size() - 1); 540 | 541 | enum ExTy 542 | { 543 | Length, 544 | Split 545 | } et; 546 | 547 | int actualNode = 0; 548 | 549 | for (int i = 0; i < creatureData->sd.size(); i++) 550 | { 551 | if (i == seg) 552 | { 553 | if (i == (creatureData->sd.size() - 1)) 554 | { 555 | creatureData->sd.push_back({creatureData->sd[i].size / 2}); 556 | et = Length; 557 | } 558 | else 559 | { 560 | agl::Vec size; 561 | if (creatureData->sd[i].branch.size() == 0) 562 | { 563 | size = creatureData->sd[i].size / 2; 564 | } 565 | else 566 | { 567 | size = creatureData->sd[i].branch.back().size / 2; 568 | } 569 | 570 | creatureData->sd[i].branch.push_back({size}); 571 | et = Split; 572 | } 573 | break; 574 | } 575 | 576 | actualNode += 1 + creatureData->sd[i].branch.size(); 577 | } 578 | 579 | for (auto it = jointMap.begin(); it != jointMap.end();) 580 | { 581 | int node = *it; 582 | 583 | if (node == (actualNode * 2) + 2 - 1) 584 | { 585 | it = jointMap.insert(std::next(it, 1), -69); 586 | it = jointMap.insert(std::next(it, 1), -69); 587 | 588 | if (et == Split) 589 | { 590 | it = jointMap.insert(std::next(it, 1), -69); 591 | it = jointMap.insert(std::next(it, 1), -69); 592 | } 593 | 594 | it = std::next(it, 1); 595 | 596 | continue; 597 | } 598 | if (node == creatureData->netStr->totalInputNodes + actualNode - 1) 599 | { 600 | it = jointMap.insert(std::next(it, 1), -69); 601 | 602 | if (et == Split) 603 | { 604 | it = jointMap.insert(std::next(it, 1), -69); 605 | } 606 | 607 | it = std::next(it, 1); 608 | continue; 609 | } 610 | 611 | it++; 612 | } 613 | } 614 | 615 | for (int i = 0; i < creatureData->netStr->totalConnections; i++) 616 | { 617 | in::Connection *con = (in::Connection *)&creatureData->netStr->connection[i]; 618 | for (int i = 0; i < jointMap.size(); i++) 619 | { 620 | if (jointMap[i] == con->startNode) 621 | { 622 | con->startNode = i; 623 | } 624 | if (jointMap[i] == con->endNode) 625 | { 626 | con->endNode = i; 627 | } 628 | } 629 | } 630 | 631 | (int &)creatureData->netStr->totalInputNodes = CreatureData::totalSegJoints(creatureData->sd) * 2 + 2; 632 | (int &)creatureData->netStr->totalOutputNodes = CreatureData::totalSegJoints(creatureData->sd); 633 | (int &)creatureData->netStr->totalNodes = 634 | (int &)creatureData->netStr->totalInputNodes + (int &)creatureData->netStr->totalOutputNodes; 635 | } 636 | } 637 | 638 | recurseSegs(creatureData->sd); 639 | 640 | if (!creatureData->useNEAT) 641 | { 642 | return; 643 | } 644 | 645 | for (int i = 0; i < networkCycles; i++) 646 | { 647 | int nonExistIndex = -1; 648 | 649 | in::Connection *connection = (in::Connection *)creatureData->netStr->connection; 650 | 651 | for (int i = 0; i < creatureData->netStr->totalConnections; i++) 652 | { 653 | if (!connection[i].exists) 654 | { 655 | nonExistIndex = i; 656 | break; 657 | } 658 | } 659 | 660 | int max = 3; 661 | 662 | if (nonExistIndex == -1) 663 | { 664 | max = 1; 665 | } 666 | (void)max; 667 | 668 | int type = generateRandomNumber(0, 3); 669 | 670 | // 0 - mutate weight 671 | // 1 - remove connection 672 | // 2 - Add node 673 | // 3 - Add connection 674 | 675 | if (type == 0) 676 | { 677 | int index = round((rand() / (float)RAND_MAX) * (creatureData->netStr->totalConnections - 1)); 678 | int start = connection[index].startNode; 679 | int end = connection[index].endNode; 680 | (void)start; 681 | (void)end; 682 | connection[index].weight = ((rand() / (float)RAND_MAX) * 4) - 2; 683 | } 684 | else if (type == 1) 685 | { 686 | int index = round((rand() / (float)RAND_MAX) * (creatureData->netStr->totalConnections - 1)); 687 | 688 | creatureData->netStr->removeConnection(index); 689 | } 690 | else if (type == 2) 691 | { 692 | int node = -1; 693 | 694 | for (int x = 0; x < creatureData->netStr->totalHiddenNodes; x++) 695 | { 696 | node = x + creatureData->netStr->totalInputNodes; 697 | 698 | for (int i = 0; i < creatureData->netStr->totalConnections; i++) 699 | { 700 | if (!connection[i].exists) 701 | { 702 | continue; 703 | } 704 | 705 | if (connection[i].startNode == node || connection[i].endNode == node) 706 | { 707 | node = -1; 708 | } 709 | } 710 | 711 | if (node != -1) 712 | { 713 | break; 714 | } 715 | } 716 | 717 | if (node != -1) 718 | { 719 | int index = round((rand() / (float)RAND_MAX) * (creatureData->netStr->totalConnections - 1)); 720 | 721 | connection[nonExistIndex].exists = true; 722 | connection[nonExistIndex].startNode = node; 723 | connection[nonExistIndex].endNode = connection[index].endNode; 724 | connection[nonExistIndex].weight = 1; 725 | 726 | connection[index].endNode = node; 727 | } 728 | } 729 | else if (type == 3) 730 | { 731 | std::vector hiddenNodes; 732 | hiddenNodes.reserve(creatureData->netStr->totalConnections); 733 | 734 | for (int i = 0; i < creatureData->netStr->totalConnections; i++) 735 | { 736 | if (!connection[i].exists) 737 | { 738 | continue; 739 | } 740 | 741 | if (connection[i].startNode < 742 | (creatureData->netStr->totalInputNodes + creatureData->netStr->totalOutputNodes)) 743 | { 744 | auto it = std::find(hiddenNodes.begin(), hiddenNodes.end(), connection[i].startNode); 745 | if (it != hiddenNodes.end()) 746 | { 747 | hiddenNodes.emplace_back(connection[i].startNode); 748 | } 749 | } 750 | } 751 | 752 | int startNode = 753 | round((rand() / (float)RAND_MAX) * (creatureData->netStr->totalInputNodes + hiddenNodes.size() - 1)); 754 | int endNode = 755 | round((rand() / (float)RAND_MAX) * (creatureData->netStr->totalOutputNodes + hiddenNodes.size() - 1)); 756 | 757 | if (startNode >= creatureData->netStr->totalInputNodes) 758 | { 759 | startNode -= creatureData->netStr->totalInputNodes; 760 | startNode = hiddenNodes[startNode]; 761 | } 762 | 763 | if (endNode >= creatureData->netStr->totalOutputNodes) 764 | { 765 | endNode -= creatureData->netStr->totalOutputNodes; 766 | endNode = hiddenNodes[startNode]; 767 | } 768 | else 769 | { 770 | endNode += creatureData->netStr->totalInputNodes; 771 | } 772 | 773 | connection[nonExistIndex].exists = true; 774 | connection[nonExistIndex].valid = true; 775 | connection[nonExistIndex].startNode = startNode; 776 | connection[nonExistIndex].endNode = endNode; 777 | connection[nonExistIndex].weight = ((rand() / (float)RAND_MAX) * 4) - 2; 778 | } 779 | } 780 | } 781 | 782 | template void correctPosition(T &circle, U &otherCircle) 783 | { 784 | agl::Vec circleOffset = otherCircle.position - circle.position; 785 | 786 | float circleDistance = circleOffset.length(); 787 | 788 | float circleOverlap = (otherCircle.radius + circle.radius) - circleDistance; 789 | 790 | if (circleOverlap > 0) 791 | { 792 | if (circleDistance == 0) 793 | { 794 | circleOffset = {rand() / (float)RAND_MAX - (float).5, rand() / (float)RAND_MAX - (float).5}; 795 | circleDistance = circleOffset.length(); 796 | circleOverlap = (otherCircle.radius + circle.radius) - circleDistance; 797 | } 798 | 799 | agl::Vec offsetNormal = circleOffset.normalized(); 800 | 801 | if (std::isnan(offsetNormal.x)) 802 | { 803 | offsetNormal.x = 1; 804 | offsetNormal.y = 0; 805 | } 806 | 807 | agl::Vec pushback = offsetNormal * circleOverlap; 808 | 809 | float actingMass = circle.mass > otherCircle.mass ? otherCircle.mass : circle.mass; 810 | 811 | circle.posOffset -= pushback * (otherCircle.mass / (circle.mass + otherCircle.mass)); 812 | otherCircle.posOffset += pushback * (circle.mass / (circle.mass + otherCircle.mass)); 813 | 814 | circle.force -= pushback * actingMass; 815 | otherCircle.force += pushback * actingMass; 816 | } 817 | 818 | #ifdef FOODPRESSURE 819 | else if constexpr (std::is_same_v && std::is_same_v) 820 | { 821 | if (circleDistance < 700) 822 | { 823 | float forceScalar = FOODPRESSURE / (circleDistance * circleDistance); 824 | 825 | agl::Vec force = circleOffset.normalized() * forceScalar; 826 | 827 | circle.force -= force; 828 | otherCircle.force += force; 829 | } 830 | } 831 | #endif 832 | } 833 | 834 | void multithreadedRecurse(int size, std::function lambda) 835 | { 836 | auto recurse = [&lambda](int start, int end) { 837 | for (int i = start; i <= end; i++) 838 | { 839 | lambda(i); 840 | } 841 | }; 842 | 843 | std::thread **thread = new std::thread *[THREADS]; 844 | 845 | int i = 0; 846 | 847 | for (i = 0; i < THREADS - 1; i++) 848 | { 849 | int start = (size / THREADS) * i; 850 | int end = (size / THREADS) * (i + 1) - 1; 851 | 852 | thread[i] = new std::thread(recurse, start, end); 853 | } 854 | 855 | int start = (size / THREADS) * i; 856 | int end = size - 1; 857 | 858 | thread[i] = new std::thread(recurse, start, end); 859 | 860 | for (int i = 0; i < THREADS; i++) 861 | { 862 | thread[i]->join(); 863 | delete thread[i]; 864 | } 865 | 866 | delete[] thread; 867 | } 868 | 869 | agl::Vec indexToPosition(int i, agl::Vec size) 870 | { 871 | return {i % size.x, i / size.x}; 872 | } 873 | 874 | void oldAirRes(PhysicsObj &o) 875 | { 876 | float velAng = o.velocity.angle(); 877 | 878 | if (!std::isnan(velAng)) 879 | { 880 | float velMag = o.velocity.length(); 881 | agl::Vec velNor = o.velocity.normalized(); 882 | 883 | float relAng = velAng - o.GetAngle(); 884 | 885 | float side1 = abs(o.size.x * cos(relAng)); 886 | float side2 = abs(o.size.y * sin(relAng)); 887 | 888 | // agl::Vec norm = {-cos(relAng), -sin(relAng)}; 889 | 890 | constexpr float density = .04; 891 | 892 | agl::Vec drag1 = velNor * -(velMag * velMag * density * side1); 893 | // drag1 = {drag1.x * norm.x, drag1.y * 894 | // norm.y}; norm = perp(norm); 895 | agl::Vec drag2 = velNor * -(velMag * velMag * density * side2); 896 | // drag2 = {drag2.x * norm.x, drag2.y * 897 | // norm.y}; 898 | 899 | o.ApplyForceToCenter(drag1 + drag2); 900 | } 901 | } 902 | 903 | void calcAirResForSide(PhysicsObj &o, agl::Vec norm, std::function trigFunc, float relAng, 904 | float side1, float side2, float velMag) 905 | { 906 | constexpr float density = .04; 907 | 908 | agl::Vec size = {abs(side1 * trigFunc(relAng)), velMag * velMag}; 909 | float mass = size.x * size.y * density; 910 | float inertia = (1 / 12.) * mass * (size.x * size.x + size.y * size.y); 911 | 912 | agl::Vec airAccLin; 913 | float airAccRot; 914 | 915 | agl::Vec r1 = norm * side2 / 2; 916 | 917 | agl::Vec rp1 = perp(r1); 918 | agl::Vec rp2 = perp(norm * velMag / -2); 919 | (void)rp2; 920 | agl::Vec startVel = (o.velocity + (rp1 * -o.angularVelocity)); 921 | 922 | agl::Vec outAcc = {0, 0}; 923 | float outRot = 0; 924 | 925 | World::resolve(o.velocity, {0, 0}, o.angularVelocity, 0, o.invInertia, 1 / inertia, o.invMass, 1 / mass, norm, r1, 926 | norm * velMag / -2, outAcc, airAccLin, outRot, airAccRot, 1); 927 | 928 | agl::Vec offVel = (outAcc + (rp1 * -outRot)); 929 | 930 | float l1 = offVel.length(); 931 | float l2 = startVel.length(); 932 | 933 | if (l1 > l2) 934 | { 935 | outAcc /= l1 / l2; 936 | outRot /= l1 / l2; 937 | } 938 | 939 | o.acceleration += outAcc; 940 | o.angularAcceleration += outRot; 941 | } 942 | 943 | void newAirRes(PhysicsObj &o) 944 | { 945 | float velAng = o.velocity.angle(); 946 | 947 | agl::Mat4f rot; 948 | rot.rotateZ(-o.radToDeg()); 949 | 950 | agl::Vec norms[4]; 951 | norms[0] = rot * agl::Vec{0, -1}; 952 | norms[1] = rot * agl::Vec{1, 0}; 953 | norms[2] = rot * agl::Vec{0, 1}; 954 | norms[3] = rot * agl::Vec{-1, 0}; 955 | 956 | float velMag = o.velocity.length(); 957 | agl::Vec velNor = o.velocity.normalized(); 958 | (void)velNor; 959 | float relAng = velAng - o.GetAngle(); 960 | 961 | for (int i = 0; i < 4; i++) 962 | { 963 | auto norm = norms[i]; 964 | if (norm.dot(o.velocity) > 0) 965 | { 966 | calcAirResForSide(o, norm, i % 2 ? sinf : cosf, relAng, i % 2 ? o.size.y : o.size.x, 967 | i % 2 ? o.size.x : o.size.y, velMag); 968 | } 969 | } 970 | } 971 | 972 | class CollisionSystem 973 | { 974 | template void func(T &circle, U &otherCircle) 975 | { 976 | } 977 | }; 978 | 979 | void Simulation::updateSimulation() 980 | { 981 | // adding more food 982 | 983 | for (; env->getList().size() < foodCap;) 984 | { 985 | agl::Vec position; 986 | position.x = (rand() / (float)RAND_MAX) * simulationRules.size.x; 987 | position.y = (rand() / (float)RAND_MAX) * simulationRules.size.y; 988 | 989 | this->addFood(position); 990 | } 991 | 992 | env->interact([](PhysicsObj &circle, PhysicsObj &otherCircle) -> void { 993 | std::vector failure; 994 | 995 | if (circle.rootConnect != &otherCircle && otherCircle.rootConnect != &circle) 996 | { 997 | CollisionConstraint::probe(circle, otherCircle, failure); 998 | } 999 | 1000 | for (ConstraintFailure &f : failure) 1001 | { 1002 | World::resolve(f, failure.size()); 1003 | } 1004 | }); 1005 | 1006 | /*std::function([](PhysicsObj &circle) -> float { return 100; }),*/ 1007 | 1008 | /*env->interact(std::function([](Food &circle, Food &otherCircle) -> void {*/ 1009 | /* std::vector failure;*/ 1010 | /**/ 1011 | /* agl::Vec circleOffset = otherCircle.position - 1012 | * circle.position;*/ 1013 | /**/ 1014 | /* float circleDistance = circleOffset.length();*/ 1015 | /* if (circleDistance < 700)*/ 1016 | /* {*/ 1017 | /* float forceScalar = FOODPRESSURE / (circleDistance * 1018 | * circleDistance);*/ 1019 | /**/ 1020 | /* agl::Vec force = circleOffset.normalized() * 1021 | * forceScalar;*/ 1022 | /**/ 1023 | /* circle.acceleration -= force * circle.invMass;*/ 1024 | /* otherCircle.acceleration += force * circle.invMass;*/ 1025 | /* }*/ 1026 | /*}));*/ 1027 | /*std::function([](Food &circle) -> float { return 100; })*/ 1028 | /*env->interact(std::function([](Creature &creature, Food &food) {*/ 1029 | /* for (auto &seg : creature.segments)*/ 1030 | /* {*/ 1031 | /* if ((seg->position - food.position).length() < 20)*/ 1032 | /* {*/ 1033 | /* creature.biomass += 1;*/ 1034 | /* food.exists = false;*/ 1035 | /* }*/ 1036 | /* }*/ 1037 | /*}));*/ 1038 | /*std::function([](Creature &creature) { return ((creature.size.x + 1039 | * creature.size.y) / 2) * 4; }));*/ 1040 | 1041 | /*while (env.pool.active())*/ 1042 | /*{*/ 1043 | /*}*/ 1044 | 1045 | /*env.clearGrid();*/ 1046 | 1047 | env->view([&](PhysicsObj &o) { 1048 | if (o.collideCount) 1049 | { 1050 | o.acceleration /= o.collideCount; 1051 | o.angularAcceleration /= o.collideCount; 1052 | o.posOffset /= o.collideCount; 1053 | o.rotOffset /= o.collideCount; 1054 | 1055 | o.collideCount = 0; 1056 | } 1057 | 1058 | newAirRes(o); 1059 | 1060 | o.updatePhysics(); 1061 | }); 1062 | 1063 | env->view([&](PhysicsObj &o) { 1064 | std::vector cf; 1065 | 1066 | if (o.rootConnect != nullptr) 1067 | { 1068 | World::motor(o); 1069 | JointConstraint::probe(o, *o.rootConnect, cf); 1070 | } 1071 | 1072 | for (ConstraintFailure &c : cf) 1073 | { 1074 | World::resolve(c, cf.size()); 1075 | } 1076 | }); 1077 | 1078 | env->view([](Meat &meat) { 1079 | meat.lifetime--; 1080 | 1081 | if (meat.lifetime < 0) 1082 | { 1083 | meat.exists = false; 1084 | return; 1085 | } 1086 | }); 1087 | env->view([&](Food &food) { 1088 | PhysicsObj &circle = food; 1089 | (void)circle; 1090 | 1091 | #ifdef ACTIVEFOOD 1092 | if ((food->nextPos - food->position).length() < 50) 1093 | { 1094 | food->nextRandPos(simulationRules.size); 1095 | } 1096 | 1097 | food->force += (food->nextPos - food->position).normalized() / 100; 1098 | #endif 1099 | 1100 | #ifdef FOODBORDER 1101 | if (food.position.x < 0) 1102 | { 1103 | food.ApplyForceToCenter({1, 0}); 1104 | } 1105 | if (food.position.x > simulationRules.size.x) 1106 | { 1107 | food.ApplyForceToCenter({-1, 0}); 1108 | } 1109 | 1110 | if (food.position.y < 0) 1111 | { 1112 | food.ApplyForceToCenter({0, 1}); 1113 | } 1114 | if (food.position.y > simulationRules.size.y) 1115 | { 1116 | food.ApplyForceToCenter({0, -1}); 1117 | } 1118 | #endif 1119 | }); 1120 | /*env->view([this](Creature &creature) {*/ 1121 | /* creature.updateNetwork();*/ 1122 | /* creature.updateActions();*/ 1123 | /**/ 1124 | /* // std::cout << creature.position << '\n';*/ 1125 | /**/ 1126 | /* // egg laying*/ 1127 | /* if (creature.layingEgg)*/ 1128 | /* {*/ 1129 | /* if (creature.energy > creature.eggTotalCost)*/ 1130 | /* {*/ 1131 | /* creature.incubating = true;*/ 1132 | /* // creature.reward += 50;*/ 1133 | /* }*/ 1134 | /* }*/ 1135 | /**/ 1136 | /* int iBio = (int)creature.biomass;*/ 1137 | /* for (int i = 0; i < iBio; i++)*/ 1138 | /* {*/ 1139 | /* CreatureData creatureData = creature.creatureData;*/ 1140 | /**/ 1141 | /* mutate(&creatureData, simulationRules.bodyMutation, 1142 | * simulationRules.brainMutation);*/ 1143 | /**/ 1144 | /* creatureData.startEnergy = creature.eggEnergyCost;*/ 1145 | /**/ 1146 | /* agl::Vec pos;*/ 1147 | /* pos.x = simulationRules.size.x * ((float)rand() / 1148 | * (float)RAND_MAX);*/ 1149 | /* pos.y = simulationRules.size.y * ((float)rand() / 1150 | * (float)RAND_MAX);*/ 1151 | /**/ 1152 | /* this->addEgg(creatureData, pos);*/ 1153 | /**/ 1154 | /* creature.incubating = false;*/ 1155 | /* creature.eggDesposit = 0;*/ 1156 | /* }*/ 1157 | /**/ 1158 | /* creature.biomass = 0;*/ 1159 | /**/ 1160 | /* // tired creature damage*/ 1161 | /* if (creature.energy <= 0)*/ 1162 | /* {*/ 1163 | /* // creature.health--;*/ 1164 | /* creature.energy = 0;*/ 1165 | /* }*/ 1166 | /**/ 1167 | /* // age damage*/ 1168 | /* if (creature.life < 0)*/ 1169 | /* {*/ 1170 | /* creature.health--;*/ 1171 | /* }*/ 1172 | /**/ 1173 | /* // killing creature*/ 1174 | /* if (creature.health <= 0)*/ 1175 | /* {*/ 1176 | /* // this->addMeat(creature.position, creature.maxHealth / 4);*/ 1177 | /* creature.exists = false;*/ 1178 | /* return;*/ 1179 | /* }*/ 1180 | /**/ 1181 | /* if (creature.velocity.length() > 10)*/ 1182 | /* {*/ 1183 | /* creature.exists = false;*/ 1184 | /* return;*/ 1185 | /* }*/ 1186 | /**/ 1187 | /* if (creature.energy > creature.maxEnergy)*/ 1188 | /* {*/ 1189 | /* creature.energy = creature.maxEnergy;*/ 1190 | /* }*/ 1191 | /**/ 1192 | /* for (auto itx = creature.segments.begin(); itx != 1193 | * creature.segments.end(); itx++)*/ 1194 | /* {*/ 1195 | /* for (auto ity = std::next(itx, 1); ity != 1196 | * creature.segments.end(); ity++)*/ 1197 | /* {*/ 1198 | /* PhysicsObj &b1 = **itx;*/ 1199 | /* PhysicsObj &b2 = **ity;*/ 1200 | /**/ 1201 | /* std::vector cf;*/ 1202 | /**/ 1203 | /* if (b1.rootConnect == &b2)*/ 1204 | /* {*/ 1205 | /* World::motor(b1);*/ 1206 | /* JointConstraint::probe(b1, b2, cf);*/ 1207 | /* }*/ 1208 | /* else if (b2.rootConnect == &b1)*/ 1209 | /* {*/ 1210 | /* World::motor(b2);*/ 1211 | /* JointConstraint::probe(b2, b1, cf);*/ 1212 | /* }*/ 1213 | /**/ 1214 | /* for (ConstraintFailure &c : cf)*/ 1215 | /* {*/ 1216 | /* World::resolve(c, cf.size());*/ 1217 | /* }*/ 1218 | /* }*/ 1219 | /* }*/ 1220 | /*});*/ 1221 | 1222 | /*while (env.pool.active())*/ 1223 | /*{*/ 1224 | /*}*/ 1225 | } 1226 | 1227 | void Simulation::update() 1228 | { 1229 | // this->threadableUpdate(); 1230 | this->updateSimulation(); 1231 | 1232 | frame++; 1233 | } 1234 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "../inc/MenuBar.hpp" 4 | #include "../inc/Simulation.hpp" 5 | #include "AGL/include/external.hpp" 6 | 7 | #include "../inc/EnDex.hpp" 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | class Listener 21 | { 22 | private: 23 | std::function first; 24 | std::function hold; 25 | std::function last; 26 | bool pastState = false; 27 | 28 | public: 29 | Listener(std::function first, std::function hold, std::function last); 30 | void update(bool state); 31 | }; 32 | 33 | Listener::Listener(std::function first, std::function hold, std::function last) 34 | { 35 | this->first = first; 36 | this->hold = hold; 37 | this->last = last; 38 | } 39 | 40 | void Listener::update(bool state) 41 | { 42 | if (state) 43 | { 44 | if (pastState) 45 | { 46 | hold(); 47 | } 48 | else 49 | { 50 | first(); 51 | 52 | pastState = true; 53 | } 54 | } 55 | else if (pastState) 56 | { 57 | last(); 58 | pastState = false; 59 | } 60 | } 61 | 62 | int getMillisecond() 63 | { 64 | auto timepoint = std::chrono::system_clock::now().time_since_epoch(); 65 | return std::chrono::duration_cast(timepoint).count(); 66 | } 67 | 68 | agl::Vec getCursorScenePosition(agl::Vec cursorWinPos, agl::Vec winSize, float winScale, 69 | agl::Vec cameraPos) 70 | { 71 | return ((cursorWinPos - (winSize * .5)) * winScale) + cameraPos; 72 | } 73 | 74 | template bool contains(std::list &list, T *p) 75 | { 76 | return std::find_if(list.begin(), list.end(), [&](T &d) { return &d == p; }) != list.end(); 77 | } 78 | 79 | GLuint lowResFBO, lowResTexture; 80 | int LOW_RES_WIDTH = 0; 81 | int LOW_RES_HEIGHT = 0; 82 | 83 | // Initialize the low-resolution framebuffer 84 | void initLowResFramebuffer() 85 | { 86 | // Generate and bind the framebuffer 87 | glGenFramebuffers(1, &lowResFBO); 88 | glBindFramebuffer(GL_FRAMEBUFFER, lowResFBO); 89 | 90 | // Create a texture for the framebuffer 91 | glGenTextures(1, &lowResTexture); 92 | glBindTexture(GL_TEXTURE_2D, lowResTexture); 93 | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, LOW_RES_WIDTH, LOW_RES_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); 94 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); 95 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); 96 | 97 | // Attach the texture to the framebuffer 98 | glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, lowResTexture, 0); 99 | 100 | // Check if framebuffer is complete 101 | if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) 102 | { 103 | std::cout << "Framebuffer is not complete!" << std::endl; 104 | } 105 | 106 | glBindFramebuffer(GL_FRAMEBUFFER, 0); 107 | } 108 | 109 | void deleteFrameBuffer() 110 | { 111 | glDeleteFramebuffers(1, &lowResFBO); 112 | glDeleteTextures(1, &lowResTexture); 113 | } 114 | 115 | class Animal 116 | { 117 | }; 118 | 119 | class Man : Animal 120 | { 121 | }; 122 | 123 | class Dog : Animal 124 | { 125 | }; 126 | 127 | int main() 128 | { 129 | /*{*/ 130 | /* EnDex ed;*/ 131 | /* ed.addEntity();*/ 132 | /* ed.addEntity();*/ 133 | /* ed.addEntity();*/ 134 | /* ed.addEntity();*/ 135 | /* ed.view([](auto &e){std::cout << "man" << '\n';});*/ 136 | /*}*/ 137 | /**/ 138 | /*return 0;*/ 139 | printf("Starting AGL\n"); 140 | 141 | agl::RenderWindow window; 142 | window.setup({WIDTH, HEIGHT}, "EvolutionSimulator"); 143 | window.setClearColor(CLEARCOLOR); 144 | window.setFPS(0); 145 | 146 | agl::Vec windowSize; 147 | 148 | glDisable(GL_DEPTH_TEST); 149 | 150 | // window.GLEnable(GL_ALPHA_TEST); 151 | // glAlphaFunc(GL_GREATER, 0.1f); 152 | 153 | window.setSwapInterval(1); 154 | 155 | agl::Event event; 156 | event.setWindow(window); 157 | 158 | agl::Shader simpleShader; 159 | simpleShader.loadFromFile("./shader/vert.glsl", "./shader/frag.glsl"); 160 | 161 | agl::Shader gridShader; 162 | gridShader.loadFromFile("./shader/gridvert.glsl", "./shader/grid.glsl"); 163 | 164 | agl::Shader viteShader; 165 | viteShader.loadFromFile("./shader/viteVert.glsl", "./shader/vite.glsl"); 166 | 167 | agl::Shader menuShader; 168 | menuShader.loadFromFile("./shader/menuVert.glsl", "./shader/menu.glsl"); 169 | 170 | agl::Camera camera; 171 | camera.setOrthographicProjection(0, WIDTH, HEIGHT, 0, 0.1, 100); 172 | agl::Vec cameraPosition = {0, 0}; 173 | camera.setView({cameraPosition.x, cameraPosition.y, 50}, {0, 0, 0}, {0, 1, 0}); 174 | 175 | agl::Camera guiCamera; 176 | guiCamera.setOrthographicProjection(0, WIDTH, HEIGHT, 0, 0.1, 100); 177 | guiCamera.setView({0, 0, 50}, {0, 0, 0}, {0, 1, 0}); 178 | 179 | agl::Texture foodTexture; 180 | foodTexture.loadFromFile("./img/food.png"); 181 | 182 | agl::Texture creatureBodyTexture; 183 | creatureBodyTexture.loadFromFile("./img/creatureBody.png"); 184 | 185 | agl::Texture creatureExtraTexture; 186 | creatureExtraTexture.loadFromFile("./img/creatureExtra.png"); 187 | 188 | agl::Texture eggTexture; 189 | eggTexture.loadFromFile("./img/egg.png"); 190 | 191 | agl::Texture meatTexture; 192 | meatTexture.loadFromFile("./img/meat.png"); 193 | 194 | agl::Texture blank; 195 | blank.setBlank(); 196 | 197 | agl::Font font; 198 | font.setup("./font/font.ttf", 16); 199 | /*font.setup("/usr/share/fonts/TTF/Arial.TTF", 16);*/ 200 | 201 | agl::Font smallFont; 202 | smallFont.setup("./font/font.ttf", 12); 203 | /*smallFont.setup("/usr/share/fonts/TTF/Arial.TTF", 12);*/ 204 | 205 | agl::Rectangle background; 206 | background.setTexture(&blank); 207 | background.setColor(CLEARCOLOR); 208 | background.setPosition({0, 0, 0}); 209 | 210 | agl::Rectangle foodShape; 211 | foodShape.setTexture(&foodTexture); 212 | foodShape.setColor(agl::Color::Green); 213 | foodShape.setSize(agl::Vec{-10, -10, 0}); 214 | foodShape.setOffset({5, 5, 30}); 215 | 216 | agl::Rectangle creatureShape; 217 | creatureShape.setTexture(&creatureBodyTexture); 218 | creatureShape.setColor(agl::Color::White); 219 | creatureShape.setSize(agl::Vec{25, 60, 0}); 220 | creatureShape.setOffset(agl::Vec{-12.5, -12.5, 30}); 221 | 222 | agl::Rectangle eggShape; 223 | eggShape.setTexture(&eggTexture); 224 | eggShape.setColor(agl::Color::White); 225 | eggShape.setSize(agl::Vec{15, 15, 0}); 226 | eggShape.setOffset({7.5, 7.5, 30}); 227 | 228 | agl::Rectangle meatShape; 229 | meatShape.setTexture(&meatTexture); 230 | meatShape.setColor(agl::Color::White); 231 | meatShape.setSize(agl::Vec{-10, -10, 0}); 232 | meatShape.setOffset({5, 5, 30}); 233 | 234 | agl::Rectangle rayShape; 235 | rayShape.setTexture(&blank); 236 | rayShape.setColor(agl::Color::White); 237 | rayShape.setSize(agl::Vec{1, RAY_LENGTH}); 238 | rayShape.setOffset(agl::Vec{-0.5, 0, 0}); 239 | 240 | agl::Rectangle blankRect; 241 | blankRect.setTexture(&blank); 242 | 243 | printf("loading simulation rules from sim.conf\n"); 244 | 245 | SimulationRules simulationRules; 246 | 247 | { 248 | std::fstream fs("./conf/sim.conf", std::ios::in); 249 | recurse(Input(fs), simulationRules, "simulationRules"); 250 | recurse(Output(std::cout), simulationRules, "simulationRules"); 251 | } 252 | 253 | background.setSize(simulationRules.size); 254 | 255 | printf("starting sim\n"); 256 | 257 | // background.setPosition(simulationRules.size * .5); 258 | 259 | Simulation simulation{}; 260 | simulation.active = 0; 261 | // simulation.create(simulationRules, 0); 262 | 263 | float fps = 0; 264 | std::string nodeName; 265 | 266 | bool leftClick; 267 | bool previousLeftClick; 268 | (void)previousLeftClick; 269 | 270 | Listener leftClickListener([&]() { leftClick = true; }, [&]() { leftClick = false; }, [&]() { leftClick = false; }); 271 | 272 | // menu shit 273 | 274 | MenuShare::init(&blank, &font, &smallFont, &event, &leftClick); 275 | MenuShare::menuShader = &menuShader; 276 | MenuShare::baseShader = &simpleShader; 277 | MenuShare::camera = &guiCamera; 278 | 279 | // leftMenu 280 | 281 | struct 282 | { 283 | ButtonElement *food; 284 | ButtonElement *meat; 285 | ButtonElement *select; 286 | ButtonElement *kill; 287 | SpacerElement *sp1; 288 | ButtonElement *forceFood; 289 | ButtonElement *forceMeat; 290 | ButtonElement *forceCreature; 291 | FieldElement *forceMultiplier; 292 | SpacerElement *sp2; 293 | ButtonElement *sendTo; 294 | } leftMenuPointers; 295 | 296 | Menu leftMenu("LeftMenu", 200, // 297 | ButtonElement{"Food"}, // 298 | ButtonElement{"Meat"}, // 299 | ButtonElement{"Select"}, // 300 | ButtonElement{"Kill"}, // 301 | SpacerElement{}, // 302 | ButtonElement{"ForceFood"}, // 303 | ButtonElement{"ForceMeat"}, // 304 | ButtonElement{"ForceCreature"}, // 305 | FieldElement{"ForceMult", 1.0}, // 306 | SpacerElement{}, // 307 | ButtonElement{"SendTo"} // 308 | ); 309 | 310 | leftMenu.bindPointers(&leftMenuPointers); 311 | 312 | // simRules 313 | 314 | struct 315 | { 316 | FieldElement *maxFood; 317 | FieldElement *energyCostMultiplier; 318 | FieldElement *learnRate; 319 | FieldElement *brainMutation; 320 | FieldElement *bodyMutation; 321 | FieldElement *exploration; 322 | FieldElement *vaporize; 323 | } simRulesPointers; 324 | 325 | simulation.foodCap = simulationRules.foodCap; 326 | 327 | Menu simRules("SimRules", 200, // 328 | FieldElement{"maxFd", (simulation.foodCap)}, // 329 | FieldElement{"EnCoMu", (simulation.energyCostMultiplier)}, // 330 | FieldElement{"Lrate", (simulationRules.learningRate)}, // 331 | FieldElement{"braMut", (simulationRules.brainMutation)}, // 332 | FieldElement{"bodMut", (simulationRules.bodyMutation)}, // 333 | FieldElement{"xplor", (simulationRules.exploration)}, // 334 | FieldElement{"vapor", (simulationRules.vaporize)} // 335 | ); 336 | 337 | simRules.bindPointers(&simRulesPointers); 338 | 339 | // quitmenu 340 | 341 | struct 342 | { 343 | TextElement *text; 344 | ButtonElement *confirm; 345 | ButtonElement *cancel; 346 | } quitMenuPointers; 347 | 348 | Menu quitMenu("Quit", 100, // 349 | TextElement{"Quit"}, // 350 | ButtonElement{"Confirm"}, // 351 | ButtonElement{"Cancel"} // 352 | ); 353 | quitMenu.bindPointers(&quitMenuPointers); 354 | 355 | // simMenu 356 | 357 | struct 358 | { 359 | FieldElement *sizeX; 360 | FieldElement *sizeY; 361 | FieldElement *gridX; 362 | FieldElement *gridY; 363 | FieldElement *threads; 364 | FieldElement *memory; 365 | FieldElement *startingCreatures; 366 | FieldElement *seed; 367 | FieldElement *simCycles; 368 | ButtonElement *start; 369 | ButtonElement *kill; 370 | ButtonElement *pause; 371 | } simMenuPointers; 372 | 373 | Menu simMenu("simMenu", 175, // 374 | FieldElement{"sizeX", (simulationRules.size.x)}, // 375 | FieldElement{"sizeY", (simulationRules.size.y)}, // 376 | FieldElement{"gridX", (simulationRules.gridResolution.x)}, // 377 | FieldElement{"gridY", (simulationRules.gridResolution.y)}, // 378 | FieldElement{"Thread", (simulationRules.threads)}, // 379 | FieldElement{"CreMem", (simulationRules.memory)}, // 380 | FieldElement{"startCreature", (simulationRules.startingCreatures)}, // 381 | FieldElement{"seed", 0}, // 382 | FieldElement{"simCycles", 1.0}, // 383 | ButtonElement{"START"}, // 384 | ButtonElement{"KILL"}, // 385 | ButtonElement{"PAUSE"} // 386 | ); 387 | 388 | simMenu.bindPointers(&simMenuPointers); 389 | 390 | // debugLog 391 | 392 | struct 393 | { 394 | TextElement *t1; 395 | TextElement *t2; 396 | TextElement *t3; 397 | TextElement *t4; 398 | TextElement *t5; 399 | TextElement *t6; 400 | TextElement *t7; 401 | TextElement *t8; 402 | } debugLogPointers; 403 | 404 | Menu debugLog("DebugLog", 400, TextElement{""}, TextElement{""}, TextElement{""}, TextElement{""}, TextElement{""}, 405 | TextElement{""}, TextElement{""}, TextElement{""}); 406 | 407 | debugLog.bindPointers(&debugLogPointers); 408 | 409 | auto sendDebugLog = [&](std::string str) { 410 | debugLogPointers.t1->str = debugLogPointers.t2->str; 411 | debugLogPointers.t2->str = debugLogPointers.t3->str; 412 | debugLogPointers.t3->str = debugLogPointers.t4->str; 413 | debugLogPointers.t4->str = debugLogPointers.t5->str; 414 | debugLogPointers.t5->str = debugLogPointers.t6->str; 415 | debugLogPointers.t6->str = debugLogPointers.t7->str; 416 | debugLogPointers.t7->str = debugLogPointers.t8->str; 417 | 418 | debugLogPointers.t8->str = str; 419 | }; 420 | (void)sendDebugLog; 421 | // menubar 422 | 423 | MenuBar menuBar(&quitMenu, // 424 | &simMenu, // 425 | &leftMenu, // 426 | &simRules, // 427 | &debugLog // 428 | ); 429 | 430 | bool mHeld = false; 431 | bool b1Held = false; 432 | bool ReturnHeld = false; 433 | (void)mHeld; 434 | (void)ReturnHeld; 435 | 436 | bool skipRender = false; 437 | 438 | float sizeMultiplier = 1; 439 | 440 | printf("entering sim loop\n"); 441 | 442 | bool quiting = false; 443 | (void)quiting; 444 | 445 | void *selected; 446 | 447 | while (!event.windowClose()) 448 | { 449 | static int milliDiff = 0; 450 | int start = getMillisecond(); 451 | 452 | event.poll(); 453 | 454 | if (!simMenuPointers.pause->state && simulation.active) 455 | { 456 | static float cycle = 0; 457 | 458 | cycle += simMenuPointers.simCycles->value; 459 | 460 | for (int i = 0; i < cycle; i++) 461 | { 462 | cycle--; 463 | simulation.update(); 464 | } 465 | } 466 | 467 | agl::Vec topLeftGrid; 468 | agl::Vec bottomRightGrid; 469 | 470 | if (skipRender) 471 | { 472 | goto skipRendering; 473 | } 474 | 475 | window.clear(); 476 | 477 | // Simulation rendering 478 | 479 | window.getShaderUniforms(gridShader); 480 | gridShader.use(); 481 | 482 | window.updateMvp(camera); 483 | 484 | glUniform1f(gridShader.getUniformLocation("scale"), sizeMultiplier); 485 | 486 | window.drawShape(background); 487 | 488 | window.getShaderUniforms(simpleShader); 489 | simpleShader.use(); 490 | 491 | if (!simulation.active) 492 | { 493 | goto skipSimRender; 494 | } 495 | 496 | // First pass: Render to low-resolution framebuffer 497 | glBindFramebuffer(GL_FRAMEBUFFER, lowResFBO); 498 | glViewport(0, 0, LOW_RES_WIDTH, LOW_RES_HEIGHT); 499 | 500 | // Clear the framebuffer 501 | glClearColor(0, 0, 0, 0); 502 | glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 503 | 504 | { 505 | agl::Camera worldCam; 506 | worldCam.setOrthographicProjection(0, simulationRules.size.x, simulationRules.size.y, 0, 0.1, 100); 507 | worldCam.setView({0, 0, 50}, {0, 0, 0}, {0, 1, 0}); 508 | window.updateMvp(worldCam); 509 | } 510 | 511 | { 512 | /*agl::Vec tlPos = getCursorScenePosition({0, 0}, windowSize, 513 | * sizeMultiplier, cameraPosition);*/ 514 | /*topLeftGrid = 515 | * simulation.env.toGridPosition(tlPos);*/ 516 | /**/ 517 | /*agl::Vec brPos = getCursorScenePosition(windowSize, 518 | * windowSize, sizeMultiplier, cameraPosition);*/ 519 | /*bottomRightGrid = 520 | * simulation.env.toGridPosition(brPos);*/ 521 | } 522 | 523 | // Draw food 524 | simulation.env->view([&](auto &food) { 525 | agl::Vec position = food.position; 526 | foodShape.setPosition(position); 527 | foodShape.setOffset(food.size / -2); 528 | foodShape.setSize(food.size); 529 | foodShape.setRotation({0, 0, -food.radToDeg()}); 530 | window.drawShape(foodShape); 531 | }); 532 | 533 | simulation.env->view([&](auto &meat) { 534 | meatShape.setPosition(meat.position); 535 | meatShape.setSize(meat.size); 536 | meatShape.setOffset(meat.size / -2); 537 | meatShape.setRotation({0, 0, -meat.radToDeg()}); 538 | window.drawShape(meatShape); 539 | }); 540 | 541 | window.getShaderUniforms(viteShader); 542 | viteShader.use(); 543 | 544 | glUniform1f(viteShader.getUniformLocation("time"), simulation.frame); 545 | 546 | { 547 | agl::Camera worldCam; 548 | worldCam.setOrthographicProjection(0, simulationRules.size.x, simulationRules.size.y, 0, 0.1, 100); 549 | worldCam.setView({0, 0, 50}, {0, 0, 0}, {0, 1, 0}); 550 | window.updateMvp(worldCam); 551 | } 552 | 553 | // draw creature 554 | simulation.env->view([&](ViteSeg &seg) { 555 | agl::Mat4f ident; 556 | agl::Mat4f trans; 557 | agl::Mat4f off; 558 | agl::Mat4f rotat; 559 | agl::Mat4f scale; 560 | 561 | ident.identity(); 562 | 563 | glUniform1f(viteShader.getUniformLocation("scaleX"), seg.size.x); 564 | glUniform1f(viteShader.getUniformLocation("scaleY"), seg.size.y); 565 | 566 | viteShader.setUniform(viteShader.getUniformLocation("top"), ident); 567 | viteShader.setUniform(viteShader.getUniformLocation("bottom"), ident); 568 | glUniform1f(viteShader.getUniformLocation("isJoint"), 0); 569 | 570 | blankRect.setPosition(seg.position); 571 | blankRect.setOffset(seg.size * -.5); 572 | blankRect.setRotation({0, 0, -seg.radToDeg()}); 573 | blankRect.setSize(seg.size); 574 | 575 | agl::Color c = hueToRGB(seg.genome[seg.geneIndex].hue); 576 | 577 | blankRect.setColor(c); 578 | 579 | window.drawShape(blankRect); 580 | 581 | if (seg.rootConnect != nullptr) 582 | { 583 | glUniform1f(viteShader.getUniformLocation("isJoint"), 1); 584 | auto &root = *seg.rootConnect; 585 | 586 | trans.translate(root.position); 587 | off.translate(seg.local2 - agl::Vec{root.size.x / 2, 0, 0}); 588 | rotat.rotate({0, 0, -root.radToDeg()}); 589 | scale.scale({root.size.x, 0, 1}); 590 | viteShader.setUniform(viteShader.getUniformLocation("top"), trans * rotat * off * scale); 591 | 592 | trans.translate(seg.position); 593 | off.translate(seg.local1 - agl::Vec{seg.size.x / 2, 0, 0}); 594 | rotat.rotate({0, 0, -seg.radToDeg()}); 595 | scale.scale({seg.size.x, 0, 1}); 596 | viteShader.setUniform(viteShader.getUniformLocation("bottom"), trans * rotat * off * scale); 597 | 598 | blankRect.setPosition({0, 0}); 599 | blankRect.setOffset({0, 0}); 600 | blankRect.setRotation({0, 0, 0}); 601 | blankRect.setSize({1, 1}); 602 | blankRect.setColor(hueToRGB(seg.genome[seg.geneIndex].hue)); 603 | 604 | window.drawShape(blankRect); 605 | } 606 | }); 607 | 608 | window.getShaderUniforms(simpleShader); 609 | simpleShader.use(); 610 | window.updateMvp(camera); 611 | 612 | // Second pass: Render the low-res texture to the screen 613 | glBindFramebuffer(GL_FRAMEBUFFER, 0); 614 | glViewport(0, 0, windowSize.x, windowSize.y); 615 | window.setClearColor(CLEARCOLOR); 616 | 617 | // Clear the default framebuffer 618 | 619 | // Use a shader program that simply samples from the texture 620 | 621 | { 622 | blankRect.setColor(agl::Color::White); 623 | blankRect.setSize({(float)simulationRules.size.x, (float)-simulationRules.size.y}); 624 | blankRect.setOffset({0, 0, 0}); 625 | 626 | agl::Texture texture; 627 | 628 | *((GLuint *)&texture) = lowResTexture; 629 | 630 | blankRect.setTexture(&texture); 631 | 632 | blankRect.setPosition({0, (float)simulationRules.size.y, 0}); 633 | blankRect.setRotation({ 634 | 0, 635 | 0, 636 | 0, 637 | }); 638 | blankRect.setTextureScaling({1, 1, 1}); 639 | blankRect.setTextureTranslation({0, 0, 0}); 640 | 641 | window.drawShape(blankRect); 642 | } 643 | 644 | blankRect.setTexture(&blank); 645 | 646 | skipSimRender:; 647 | 648 | window.getShaderUniforms(simpleShader); 649 | simpleShader.use(); 650 | 651 | // gui rendering 652 | 653 | fps = (1000. / milliDiff); 654 | 655 | window.updateMvp(guiCamera); 656 | 657 | /*if (focusCreature != nullptr)*/ 658 | /*{*/ 659 | /* if (contains(simulation.env->getList(), focusCreature))*/ 660 | /* {*/ 661 | /* int node = creatureNetworkPointers.network->selectedID;*/ 662 | /**/ 663 | /* nodeName = "";*/ 664 | /**/ 665 | /* if (node < focusCreature->network->structure.totalInputNodes)*/ 666 | /* {*/ 667 | /* switch (node)*/ 668 | /* {*/ 669 | /* case 0:*/ 670 | /* nodeName = "Constant";*/ 671 | /* break;*/ 672 | /* case 1:*/ 673 | /* nodeName = "Sin";*/ 674 | /* break;*/ 675 | /* default:*/ 676 | /* if (node % 2 == 0)*/ 677 | /* {*/ 678 | /* nodeName = "Angle " + 679 | * std::to_string(node - 1);*/ 680 | /* }*/ 681 | /* else*/ 682 | /* {*/ 683 | /* nodeName = "Motor " + 684 | * std::to_string(node - 2);*/ 685 | /* }*/ 686 | /* break;*/ 687 | /* }*/ 688 | /* }*/ 689 | /* else*/ 690 | /* {*/ 691 | /* if (node < focusCreature->network->structure.totalNodes 692 | * -*/ 693 | /* focusCreature->network->structure.totalOutputNodes)*/ 694 | /* {*/ 695 | /* nodeName =*/ 696 | /* "Hidden " + std::to_string(node - 697 | * focusCreature->network->structure.totalInputNodes + 1);*/ 698 | /* }*/ 699 | /* else*/ 700 | /* {*/ 701 | /* nodeName =*/ 702 | /* "Move " + std::to_string(((node - 703 | * focusCreature->network->structure.totalInputNodes) -*/ 704 | /* focusCreature->network->structure.totalHiddenNodes) 705 | * +*/ 706 | /* 1);*/ 707 | /* }*/ 708 | /* }*/ 709 | /**/ 710 | /* nodeName +=*/ 711 | /* ": " +*/ 712 | /* std::to_string(focusCreature->network->getNode(creatureNetworkPointers.network->selectedID).value);*/ 713 | /* }*/ 714 | /* else*/ 715 | /* {*/ 716 | /* focusCreature = nullptr;*/ 717 | /* }*/ 718 | /*}*/ 719 | 720 | for (std::string &msgLog : Debug::log) 721 | { 722 | debugLog.get<0>().str = debugLog.get<1>().str; 723 | debugLog.get<1>().str = debugLog.get<2>().str; 724 | debugLog.get<2>().str = debugLog.get<3>().str; 725 | debugLog.get<3>().str = debugLog.get<4>().str; 726 | debugLog.get<4>().str = debugLog.get<5>().str; 727 | debugLog.get<5>().str = debugLog.get<6>().str; 728 | debugLog.get<6>().str = debugLog.get<7>().str; 729 | 730 | debugLog.get<7>().str = msgLog; 731 | } 732 | 733 | Debug::log.clear(); 734 | 735 | // window.getShaderUniforms(menuShader); 736 | // menuShader.use(); 737 | // 738 | // window.updateMvp(guiCamera); 739 | 740 | window.draw(menuBar); 741 | 742 | window.display(); 743 | 744 | skipRendering:; 745 | 746 | // quit? 747 | 748 | if (quitMenuPointers.confirm->state) 749 | { 750 | break; 751 | } 752 | if (quitMenuPointers.cancel->state) 753 | { 754 | quitMenu.close(); 755 | quitMenuPointers.cancel->state = false; 756 | } 757 | 758 | if (simMenuPointers.kill->state && simulation.active) 759 | { 760 | simulation.destroy(); 761 | 762 | deleteFrameBuffer(); 763 | } 764 | else if (simMenuPointers.start->state && !simulation.active) 765 | { 766 | simulationRules.size.x = simMenuPointers.sizeX->value; 767 | simulationRules.size.y = simMenuPointers.sizeY->value; 768 | simulationRules.gridResolution.x = simMenuPointers.gridX->value; 769 | simulationRules.gridResolution.y = simMenuPointers.gridY->value; 770 | simulationRules.startingCreatures = simMenuPointers.startingCreatures->value; 771 | simulationRules.threads = simMenuPointers.threads->value; 772 | simulationRules.foodCap = simRulesPointers.maxFood->value; 773 | 774 | simulation.create(simulationRules, simMenuPointers.seed->value); 775 | 776 | background.setSize(simulationRules.size); 777 | 778 | LOW_RES_WIDTH = simulationRules.size.x / 1; 779 | LOW_RES_HEIGHT = simulationRules.size.y / 1; 780 | initLowResFramebuffer(); 781 | } 782 | 783 | if (event.keybuffer.find('h') != std::string::npos && FocusableElement::focusedField == nullptr) 784 | { 785 | menuBar.exists = !menuBar.exists; 786 | } 787 | 788 | if (!simulation.active) 789 | { 790 | goto deadSim; 791 | } 792 | 793 | // input 794 | 795 | if (event.isKeyPressed(agl::Key::R)) 796 | { 797 | } 798 | 799 | { 800 | } 801 | 802 | if (event.isPointerButtonPressed(agl::Button::Left)) 803 | { 804 | if (menuBar.exists) 805 | { 806 | for (int i = 0; i < menuBar.length; i++) 807 | { 808 | SimpleMenu *menu = menuBar.menu[i]; 809 | 810 | if (pointInArea(event.getPointerWindowPosition(), menu->position, menu->size) && menu->exists) 811 | { 812 | goto endif; 813 | } 814 | } 815 | } 816 | 817 | if (leftMenuPointers.food->state) // add food 818 | { 819 | simulation.addFood(getCursorScenePosition(event.getPointerWindowPosition(), windowSize, sizeMultiplier, 820 | cameraPosition)); 821 | } 822 | if (leftMenuPointers.meat->state) // add meat 823 | { 824 | simulation.addMeat(getCursorScenePosition(event.getPointerWindowPosition(), windowSize, sizeMultiplier, 825 | cameraPosition)); 826 | } 827 | if (leftMenuPointers.select->state) // select creature 828 | { 829 | } 830 | if (leftMenuPointers.kill->state) // kill creature 831 | { 832 | // simulation.env.view([&](auto &creature, auto 833 | // it) { agl::Vec mouse; mouse.x = 834 | // ((event.getPointerWindowPosition().x - (windowSize.x * 835 | // .5)) * sizeMultiplier) + cameraPosition.x; 836 | // mouse.y 837 | // = 838 | // ((event.getPointerWindowPosition().y - (windowSize.y * 839 | // .5)) * sizeMultiplier) + 840 | // cameraPosition.y; 841 | // 842 | // float distance = (mouse - creature.position).length(); 843 | // 844 | // if (distance < creature.radius) 845 | // { 846 | // it--; 847 | // simulation.addMeat(creature.position, 848 | // creature.maxHealth / 4); 849 | // simulation.env.removeEntity(it); 850 | // 851 | // return; 852 | // } 853 | // }); 854 | } 855 | if (leftMenuPointers.forceFood->state) 856 | { 857 | agl::Vec cursorRelPos = getCursorScenePosition(event.getPointerWindowPosition(), windowSize, 858 | sizeMultiplier, cameraPosition); 859 | 860 | /*topLeftGrid = simulation.env.toGridPosition(cursorRelPos - 861 | * agl::Vec{1000, 1000});*/ 862 | 863 | /*bottomRightGrid = simulation.env.toGridPosition(cursorRelPos + 864 | * agl::Vec{1000, 1000});*/ 865 | 866 | simulation.env->view([&](Food &food) { 867 | agl::Vec offset = food.position - cursorRelPos; 868 | float distance = offset.length(); 869 | 870 | float forceScalar = leftMenuPointers.forceMultiplier->value / distance; 871 | 872 | agl::Vec force = offset.normalized() * forceScalar; 873 | 874 | food.ApplyForceToCenter(force); 875 | }); 876 | { 877 | } 878 | } 879 | if (leftMenuPointers.forceMeat->state) 880 | { 881 | agl::Vec cursorRelPos = getCursorScenePosition(event.getPointerWindowPosition(), windowSize, 882 | sizeMultiplier, cameraPosition); 883 | (void)cursorRelPos; 884 | 885 | // simulation.env.getArea( 886 | // [&](Meat &meat) { 887 | // agl::Vec offset = meat.position 888 | // - cursorRelPos; float distance = 889 | // offset.length(); 890 | // 891 | // float forceScalar = 892 | // leftMenuPointers.forceMultiplier->value / distance; 893 | // 894 | // agl::Vec force = offset.normalized() * 895 | // forceScalar; 896 | // 897 | // meat.force += force; 898 | // }, 899 | // simulation.env.toGridPosition(cursorRelPos)); 900 | } 901 | if (leftMenuPointers.forceCreature->state) 902 | { 903 | agl::Vec cursorRelPos = getCursorScenePosition(event.getPointerWindowPosition(), windowSize, 904 | sizeMultiplier, cameraPosition); 905 | (void)cursorRelPos; 906 | // NOTE force is disabled 907 | // simulation.env.getArea( 908 | // [&](Creature &creature) { 909 | // agl::Vec offset = creature.position 910 | // - cursorRelPos; float distance = 911 | // offset.length(); 912 | // 913 | // float forceScalar = 914 | // leftMenuPointers.forceMultiplier->value / distance; 915 | // 916 | // agl::Vec force = offset.normalized() * 917 | // forceScalar; 918 | // 919 | // creature.force += force; 920 | // 921 | // sendDebugLog(std::to_string(force.length())); 922 | // }, 923 | // simulation.env.toGridPosition(cursorRelPos)); 924 | } 925 | if (leftMenuPointers.sendTo->state) 926 | { 927 | } 928 | 929 | endif:; 930 | } 931 | 932 | simulation.foodCap = simRulesPointers.maxFood->value; 933 | simulation.energyCostMultiplier = simRulesPointers.energyCostMultiplier->value; 934 | simulation.simulationRules.learningRate = simRulesPointers.learnRate->value; 935 | simulation.simulationRules.brainMutation = simRulesPointers.brainMutation->value; 936 | simulation.simulationRules.bodyMutation = simRulesPointers.bodyMutation->value; 937 | simulation.simulationRules.exploration = simRulesPointers.exploration->value; 938 | simulation.simulationRules.vaporize = simRulesPointers.vaporize->value; 939 | 940 | deadSim:; 941 | 942 | // camera movement 943 | 944 | static agl::Vec cameraOffset; 945 | static agl::Vec startPos; 946 | 947 | if (event.isPointerButtonPressed(agl::Button::Middle)) 948 | { 949 | if (b1Held) // holding click 950 | { 951 | cameraPosition = cameraPosition - cameraOffset; 952 | 953 | cameraOffset = startPos - event.getPointerWindowPosition(); 954 | cameraOffset.x *= sizeMultiplier; 955 | cameraOffset.y *= sizeMultiplier; 956 | 957 | cameraPosition.x += cameraOffset.x; 958 | cameraPosition.y += cameraOffset.y; 959 | } 960 | else // first click 961 | { 962 | window.setCursorShape(agl::CursorType::Arrow); 963 | startPos = event.getPointerWindowPosition(); 964 | b1Held = true; 965 | } 966 | } 967 | else if (b1Held) // let go 968 | { 969 | window.setCursorShape(agl::CursorType::Arrow); 970 | cameraOffset = {0, 0}; 971 | b1Held = false; 972 | } 973 | 974 | static float cameraSpeed = 4; 975 | (void)cameraSpeed; 976 | 977 | const float sizeDelta = .2; 978 | 979 | if (event.scroll == agl::Up) 980 | { 981 | float scale = sizeDelta * sizeMultiplier; 982 | 983 | agl::Vec oldPos = 984 | getCursorScenePosition(event.getPointerWindowPosition(), windowSize, sizeMultiplier, cameraPosition); 985 | 986 | sizeMultiplier -= scale; 987 | 988 | agl::Vec newPos = 989 | getCursorScenePosition(event.getPointerWindowPosition(), windowSize, sizeMultiplier, cameraPosition); 990 | 991 | agl::Vec offset = oldPos - newPos; 992 | 993 | cameraPosition = cameraPosition + offset; 994 | } 995 | if (event.scroll == agl::Down) 996 | { 997 | float scale = sizeDelta * sizeMultiplier; 998 | 999 | agl::Vec oldPos = 1000 | getCursorScenePosition(event.getPointerWindowPosition(), windowSize, sizeMultiplier, cameraPosition); 1001 | 1002 | sizeMultiplier += scale; 1003 | 1004 | agl::Vec newPos = 1005 | getCursorScenePosition(event.getPointerWindowPosition(), windowSize, sizeMultiplier, cameraPosition); 1006 | 1007 | agl::Vec offset = oldPos - newPos; 1008 | 1009 | cameraPosition = cameraPosition + offset; 1010 | } 1011 | 1012 | window.setViewport(0, 0, windowSize.x, windowSize.y); 1013 | 1014 | camera.setOrthographicProjection(-((windowSize.x / 2.) * sizeMultiplier), 1015 | ((windowSize.x / 2.) * sizeMultiplier), ((windowSize.y / 2.) * sizeMultiplier), 1016 | -((windowSize.y / 2.) * sizeMultiplier), 0.1, 100); 1017 | camera.setView({cameraPosition.x, cameraPosition.y, 50}, {cameraPosition.x, cameraPosition.y, 0}, {0, 1, 0}); 1018 | 1019 | guiCamera.setOrthographicProjection(0, windowSize.x, windowSize.y, 0, 0.1, 100); 1020 | 1021 | windowSize = window.getState().size; 1022 | 1023 | leftClickListener.update(event.isPointerButtonPressed(agl::Button::Left)); 1024 | 1025 | milliDiff = getMillisecond() - start; 1026 | 1027 | // std::cout << simulation.foodCap << '\n'; 1028 | } 1029 | 1030 | if (simulation.active) 1031 | { 1032 | simulation.destroy(); 1033 | } 1034 | 1035 | MenuShare::destroy(); 1036 | 1037 | font.deleteFont(); 1038 | 1039 | foodTexture.deleteTexture(); 1040 | creatureBodyTexture.deleteTexture(); 1041 | creatureExtraTexture.deleteTexture(); 1042 | eggTexture.deleteTexture(); 1043 | blank.deleteTexture(); 1044 | 1045 | simpleShader.deleteProgram(); 1046 | gridShader.deleteProgram(); 1047 | 1048 | window.close(); 1049 | 1050 | return 0; 1051 | } 1052 | -------------------------------------------------------------------------------- /src/other.cpp: -------------------------------------------------------------------------------- 1 | #include "../inc/other.hpp" 2 | #include 3 | 4 | std::vector Debug::log; 5 | 6 | float loop(float min, float max, float value) 7 | { 8 | return value - (max + abs(min)) * int(value / max); 9 | } 10 | 11 | float vectorAngle(agl::Vec vec) 12 | { 13 | float angle = atan(vec.x / vec.y); 14 | 15 | if (vec.y < 0) 16 | { 17 | angle *= -1; 18 | 19 | if (vec.x > 0) 20 | { 21 | angle = PI - angle; 22 | } 23 | else 24 | { 25 | angle = -(PI + angle); 26 | } 27 | } 28 | 29 | return angle; 30 | } 31 | 32 | agl::Color hueToRGB(int hue) 33 | { 34 | hue = hue % 360; 35 | agl::Color color; 36 | 37 | if (hue < 60) 38 | { 39 | color.r = 255; 40 | color.g = float(hue - 0) / 60 * 255; 41 | color.b = 0; 42 | } 43 | else if (hue < 120) 44 | { 45 | color.r = 255 - (float(hue - 60) / 60 * 255); 46 | color.g = 255; 47 | color.b = 0; 48 | } 49 | else if (hue < 180) 50 | { 51 | color.r = 0; 52 | color.g = 255; 53 | color.b = float(hue - 120) / 60 * 255; 54 | } 55 | else if (hue < 240) 56 | { 57 | color.r = 0; 58 | color.g = 255 - (float(hue - 180) / 60 * 255); 59 | color.b = 255; 60 | } 61 | else if (hue < 300) 62 | { 63 | color.r = float(hue - 240) / 60 * 255; 64 | color.g = 0; 65 | color.b = 255; 66 | } 67 | else if (hue < 360) 68 | { 69 | color.r = 255; 70 | color.g = 0; 71 | color.b = 255 - (float(hue - 300) / 60 * 255); 72 | } 73 | 74 | return color; 75 | } 76 | 77 | int roundUp(float input, int period) 78 | { 79 | float amount = input / period; 80 | amount += (amount - (int)amount) > 0; 81 | 82 | return (int)amount * period; 83 | } 84 | 85 | float cross2D(agl::Vec a, agl::Vec b) 86 | { 87 | return a.x * b.y - a.y * b.x; 88 | } 89 | 90 | agl::Vec perp(agl::Vec vec) 91 | { 92 | return {-vec.y, vec.x}; 93 | } 94 | 95 | agl::Vec closestPointToLine(agl::Vec a, agl::Vec b, agl::Vec p) 96 | { 97 | auto ab = b - a; 98 | auto ap = p - a; 99 | 100 | float proj = ap.dot(ab); 101 | float abLenSq = ab.dot(ab); 102 | float d = proj / abLenSq; 103 | 104 | if (d <= 0) 105 | { 106 | return a; 107 | } 108 | else if (d >= 1) 109 | { 110 | return b; 111 | } 112 | else 113 | { 114 | return a + ab * d; 115 | } 116 | } 117 | --------------------------------------------------------------------------------