├── .editorconfig ├── .github └── FUNDING.yml ├── .gitignore ├── CMakeLists.txt ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── assets └── img │ ├── PayPal.png │ ├── TMatrix.gif │ └── TMatrix.png ├── completions ├── tmatrix-completion.bash ├── tmatrix-completion.tcsh └── tmatrix-completion.zsh ├── include ├── Active.h ├── Color.h ├── CountdownTimer.h ├── DecimalFraction.h ├── HasTerminal.h ├── MatrixChar.h ├── Parser.h ├── Rain.h ├── RainColumn.h ├── RainStreak.h ├── Random.h ├── Range.h ├── Terminal.h ├── TerminalChar.h └── tmatrix.h ├── src ├── HasTerminal.cpp ├── MatrixChar.cpp ├── Parser.cpp ├── Rain.cpp ├── RainColumn.cpp ├── RainStreak.cpp ├── Random.cpp ├── Terminal.cpp ├── TerminalChar.cpp └── tmatrix.cpp └── tmatrix.6 /.editorconfig: -------------------------------------------------------------------------------- 1 | [*] 2 | charset = utf-8 3 | end_of_line = lf 4 | insert_final_newline = true 5 | indent_style = tab 6 | tab_width = 8 7 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | liberapay: M4444 2 | custom: "https://www.paypal.me/4milos" 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | installation* 3 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Version 3.8 is the first version that supports CXX_STANDARD 17. 2 | cmake_minimum_required(VERSION 3.8) 3 | project(TMatrix CXX) 4 | 5 | # Use the C++17 standard. 6 | set(CMAKE_CXX_STANDARD 17) 7 | set(CMAKE_CXX_STANDARD_REQUIRED ON) 8 | 9 | # Setup different build types. Release is the default. 10 | if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) 11 | set(CMAKE_BUILD_TYPE Release) 12 | endif() 13 | set(CMAKE_CXX_FLAGS "-Wall -Wextra -Wpedantic") 14 | set(CMAKE_CXX_FLAGS_RELEASE "-O2") 15 | set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g") 16 | set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g") 17 | 18 | # Add linking with pthread. 19 | set(CMAKE_EXE_LINKER_FLAGS "-pthread") 20 | 21 | # Add the required ncurses library. 22 | set(CURSES_NEED_NCURSES TRUE) 23 | find_package(Curses REQUIRED) 24 | link_libraries(${CURSES_LIBRARIES}) 25 | 26 | # Link libatomic explicitly because some platforms require it. 27 | find_library(ATOMIC_LIB atomic) 28 | # Check if libatomic is present (it may not be, for example on macOS). 29 | if(ATOMIC_LIB) 30 | link_libraries(${ATOMIC_LIB}) 31 | endif() 32 | 33 | # Add all the .cpp files. 34 | file(GLOB tmatrix_SRC "src/*.cpp") 35 | add_executable(tmatrix ${tmatrix_SRC}) 36 | 37 | # Specify the include directory. 38 | include_directories(include) 39 | 40 | # Specify how to compress the man page. 41 | configure_file(tmatrix.6 ${PROJECT_BINARY_DIR}/tmatrix.6) 42 | add_custom_command(OUTPUT tmatrix.6.gz 43 | COMMAND gzip -f tmatrix.6 44 | DEPENDS tmatrix.6 45 | ) 46 | add_custom_target(manpage ALL DEPENDS tmatrix.6.gz) 47 | 48 | # If the user didn't change the default install prefix set it to "/usr" 49 | if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) 50 | set(CMAKE_INSTALL_PREFIX "/usr" CACHE PATH "..." FORCE) 51 | endif() 52 | 53 | # Install tmatrix binary and manpage. 54 | install(TARGETS tmatrix DESTINATION bin) 55 | install(FILES ${PROJECT_BINARY_DIR}/tmatrix.6.gz DESTINATION share/man/man6) 56 | 57 | # Install bash and zsh completion scripts. 58 | install(FILES completions/tmatrix-completion.bash 59 | DESTINATION share/bash-completion/completions 60 | RENAME tmatrix 61 | ) 62 | install(FILES completions/tmatrix-completion.zsh 63 | DESTINATION share/zsh/site-functions 64 | RENAME _tmatrix 65 | ) 66 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | Thanks for considering contributing to this project. 3 | Every contribution is welcome. 4 | A contribution can be a suggestion, a bug report, a feature request or a patch that fixes a bug, makes the code better or improves performance. 5 | You can [email](mailto:mc.cm.mail@gmail.com) them to me directly or submit them at the appropriate place explained in further text. 6 | By default every contributor whose contribution gets approved will be acknowledged in the README. 7 | If you don't wish to be acknowledged, please specify that when submitting your contribution. 8 | 9 | ## Reporting bugs and adding suggestions 10 | If you find a bug or a behavior that doesn't seem right or you have a suggestion for improving the project, you can report it in the [Issues](../../issues) tab with the appropriate tag. 11 | In the report describe what behavior you observed (screenshots/videos are always helpful), what would you expect to see and how others can recreate the behavior. 12 | 13 | ## Submitting patches 14 | If you created a bug fix, simplified the code or improved performance, you can create a pull request in the [Pull requests](../../pulls) tab. 15 | 16 | ### Commit message 17 | The title of the commit message should be descriptive but concise. 18 | It should be in the past simple tense and no longer than 72 characters. 19 | Preferably, the first word should classify the change the commit is making. 20 | For examples see the previous commits titles (`git log --oneline`). 21 | If further details are need, they should go in the commit message below the title. 22 | The lines in the commit message shouldn't exceed 76 characters. 23 | 24 | ### Coding conventions 25 | This project tends to follow the [C++ Core Guidelines](https://github.com/isocpp/CppCoreGuidelines), though there might be some custom conventions. 26 | Just follow the code around your change and you should be able to infer what they are. 27 | 28 | ### Bug fix 29 | If you created a patch that fixes the bug, please also submit a description of the bug and how it can be reproduced. 30 | 31 | ### Code style change 32 | If you find that some part of the code can be simplified or reorganized in a better way without negatively affecting it's runtime you can submit this a style change patch. 33 | 34 | ### Performance improvements 35 | If you are submitting a patch that improves the performance, please also submit the results of the testing/benchmark you've done to confirm the improvement, a description of the environment you are running and a procedure detailing how this process can be potentially reproduced. 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | ----------------------------------------------------------------------------- 342 | Note: 343 | Individual files contain the following tag instead of the full license text: 344 | 345 | SPDX-License-Identifier: GPL-2.0-only 346 | 347 | This enables machine processing of license information based on the SPDX 348 | License Identifiers that are here available: http://spdx.org/licenses/ 349 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TMatrix 2 | 3 | [![\[Latest GitHub release\]](https://img.shields.io/github/v/release/M4444/TMatrix)](https://github.com/M4444/TMatrix/releases) 4 | [![\[License\]](https://img.shields.io/badge/license-GPL--2.0--only-green)](https://github.com/M4444/TMatrix/blob/master/LICENSE) 5 | 6 | [![Codacy Badge](https://api.codacy.com/project/badge/Grade/995dada1ec344743921cdd10fc118f3a)](https://www.codacy.com/manual/M4444/TMatrix?utm_source=github.com&utm_medium=referral&utm_content=M4444/TMatrix&utm_campaign=Badge_Grade) 7 | [![Language grade: C/C++](https://img.shields.io/lgtm/grade/cpp/g/M4444/TMatrix.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/M4444/TMatrix/context:cpp) 8 | 9 | TMatrix is a program that simulates the digital rain from The Matrix. 10 | It's focused on being the most accurate replica of the digital rain effect achievable on a typical terminal, while also being customizable and performant. 11 | 12 | ## Installation 13 | 14 | [![Packaging status](https://repology.org/badge/vertical-allrepos/tmatrix-m4444.svg)](https://repology.org/project/tmatrix-m4444/versions) 15 | 16 | ### Install on Arch Linux [![AUR votes](https://img.shields.io/aur/votes/tmatrix-git)](https://aur.archlinux.org/packages/tmatrix-git) 17 | 18 | Install [`tmatrix-git`](https://aur.archlinux.org/packages/tmatrix-git/) from 19 | the AUR. For example, with an [AUR helper](https://wiki.archlinux.org/index.php/AUR_helpers) 20 | such as [`yay`](https://aur.archlinux.org/packages/yay/): 21 | ```shell 22 | yay -S tmatrix-git 23 | ``` 24 | 25 | ### Install on any Nix system 26 | ```shell 27 | nix-env -f '' -iA tmatrix 28 | ``` 29 | 30 | ### Install on openSUSE Linux 31 | 32 | The package can be installed from the community repo: 33 | #### Note: if you are using other versions insted of Tubleweed uncomment the one you're using and delete the others. 34 | ```shell 35 | DISTRIBUTION=Tumbleweed 36 | #DISTRIBUTION=Slowroll 37 | #DISTRIBUTION=Leap_15.6 38 | #DISTRIBUTION=Leap_15.5 39 | 40 | zypper addrepo "https://download.opensuse.org/repositories/home:kosmonaut2001/openSUSE_${DISTRIBUTION}/home:kosmonaut2000.repo" 41 | zypper refresh 42 | zypper install TMatrix 43 | ``` 44 | 45 | ### Download and install on other GNU/Linux distributions 46 | The prebuilt TMatrix uses **version 5** of the ncurses library. 47 | To install the library on Ubuntu or Debian run: 48 | ```shell 49 | sudo apt-get install libncurses5 50 | ``` 51 | Now that you have the required library you can install and run tmatrix: 52 | ```shell 53 | wget -q https://github.com/M4444/TMatrix/releases/download/v1.4/installation.tar.gz 54 | tar -zxvf installation.tar.gz 55 | cd installation 56 | sudo ./install.sh 57 | ``` 58 | To check if it installed correctly run: 59 | ```shell 60 | tmatrix --version 61 | ``` 62 | 63 | #### Uninstall 64 | ```shell 65 | sudo rm -f /usr/bin/tmatrix \ 66 | /usr/share/man/man6/tmatrix.6.gz \ 67 | /usr/share/bash-completion/completions/tmatrix \ 68 | /usr/share/zsh/site-functions/_tmatrix 69 | ``` 70 | To check if anything was left behind you can run: 71 | ```shell 72 | locate tmatrix 73 | ``` 74 | 75 | ### Build and install from source 76 | #### Tools 77 | This project uses C++17 so you'll need the latest tools in order you build it: 78 | - [CMake 3.8+](https://cmake.org/download/) 79 | - [GCC 7+](https://gcc.gnu.org/) or [Clang 5+](http://releases.llvm.org/) 80 | 81 | #### Library 82 | - [ncurses](https://www.gnu.org/software/ncurses/) 83 | 84 | #### Commands 85 | ```shell 86 | git clone https://github.com/M4444/TMatrix.git 87 | cd TMatrix 88 | mkdir -p build && cd build 89 | cmake .. 90 | make -j8 91 | sudo make install 92 | ``` 93 | 94 | ## Info 95 | 96 | ### Options 97 | TMatrix is very customizable. 98 | You can change the starting title text, the color of the background and the characters, the speed, length and separations of the rain streaks. 99 | During execution you can use `p` to pause and `q` to quit. 100 | 101 | For a full description of all the options run `man tmatrix` or `tmatrix --help`. 102 | 103 | ### Contributing 104 | Suggestions, bug reports and patch submissions are all welcome. 105 | You can create an [issue](../../issues), send a [pull requests](../../pulls) of just send an [email](mailto:mc.cm.mail@gmail.com). 106 | For details see [CONTRIBUTING.md](../master/CONTRIBUTING.md). 107 | 108 | ### Author 109 | Written and maintained by Miloš Stojanović ([mc.cm.mail@gmail.com](mailto:mc.cm.mail@gmail.com)). 110 | 111 | ### Acknowledgments 112 | Thanks to: 113 | - [Infinisil](https://github.com/Infinisil) for creating a Nix package 114 | - [filalex77](https://github.com/filalex77) for creating a Gentoo Linux package, adding bash, zsh and tcsh completions scripts and a .editorconfig file 115 | - [eliasrg](https://github.com/eliasrg) for creating and maintaining the Arch Linux package, clarifying the installation options on Arch Linux, adding CMake install commands for the man page and helping in the creation of completions scripts 116 | - [Makefile-dot-in](https://github.com/Makefile-dot-in) for fixing a problem linking atomic on Android 117 | - [sebpardo](https://github.com/sebpardo) for pointing out a typo in the man page 118 | - [fosspill](https://github.com/fosspill) for correcting the name of the required ncurses library 119 | - [meskarune](https://github.com/meskarune) for the idea and helpful suggestions for creating the 'fade' and 'rainbow' options 120 | - [taschenlampe](https://github.com/taschenlampe) for creating a openSUSE Linux package and reporting an issue with the install script 121 | 122 | ### License 123 | TMatrix is licensed under the `GPL-2.0-only` - see the [LICENSE](../master/LICENSE) file for details. 124 | 125 | ### Donations 126 | If you wish to send a donation you can do so here [![Liberapay](https://liberapay.com/assets/widgets/donate.svg)](https://liberapay.com/M4444/donate) or here [![PayPal](assets/img/PayPal.png?raw=true)](https://www.paypal.com/paypalme/4milos). 127 | 128 | ### How it looks 129 | ![](assets/img/TMatrix.png?raw=true) 130 | ![](assets/img/TMatrix.gif?raw=true) 131 | -------------------------------------------------------------------------------- /assets/img/PayPal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/M4444/TMatrix/4c61c540f1f463e598a6d72a127383cc9edb2214/assets/img/PayPal.png -------------------------------------------------------------------------------- /assets/img/TMatrix.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/M4444/TMatrix/4c61c540f1f463e598a6d72a127383cc9edb2214/assets/img/TMatrix.gif -------------------------------------------------------------------------------- /assets/img/TMatrix.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/M4444/TMatrix/4c61c540f1f463e598a6d72a127383cc9edb2214/assets/img/TMatrix.png -------------------------------------------------------------------------------- /completions/tmatrix-completion.bash: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2018-2023 Miloš Stojanović 2 | # 3 | # SPDX-License-Identifier: GPL-2.0-only 4 | 5 | _tmatrix() { 6 | local cur prev split 7 | _init_completion -s || return 8 | 9 | local colors=(default white gray black red green yellow blue magenta cyan) 10 | 11 | case $prev in 12 | --help|--version|--fade|--no-fade) 13 | return 14 | ;; 15 | --background|-c|--color|-C) 16 | COMPREPLY=( $(compgen -W '${colors[*]}' -- "${cur}") ) 17 | return 18 | ;; 19 | --mode) 20 | COMPREPLY=( $(compgen -W 'default dense' -- "${cur}") ) 21 | return 22 | ;; 23 | esac 24 | 25 | $split && return 26 | 27 | if [[ $cur == -* ]]; then 28 | COMPREPLY=( $(compgen -W '$(_parse_help "$1")' -- "$cur") ) 29 | COMPREPLY+=( $(compgen -W '-s -f -G -g -C -c -t' -- "$cur") ) 30 | [[ "${COMPREPLY[0]}" == *= ]] && compopt -o nospace 31 | return 32 | fi 33 | } && complete -F _tmatrix tmatrix 34 | -------------------------------------------------------------------------------- /completions/tmatrix-completion.tcsh: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2018-2023 Miloš Stojanović 2 | # 3 | # SPDX-License-Identifier: GPL-2.0-only 4 | # 5 | # To use this completion script: 6 | # 1) Copy this file to ${HOME}: 7 | # cp tmatrix-completion.tcsh ~/.tmatrix-completion.tcsh 8 | # 2) Add the following line to your .tcshrc/.cshrc: 9 | # source ~/.tmatrix-completion.tcsh 10 | 11 | set tmatrix_short_options = (\ 12 | -s \ 13 | -f \ 14 | -G \ 15 | -l \ 16 | -r \ 17 | -C \ 18 | -c \ 19 | -t \ 20 | ) 21 | 22 | set tmatrix_long_options = (\ 23 | --mode \ 24 | --steps-per-sec \ 25 | --fall-speed \ 26 | --start-gap \ 27 | --gap \ 28 | --fade \ 29 | --no-fade \ 30 | --color \ 31 | --background \ 32 | --title \ 33 | ) 34 | 35 | set tmatrix_modes = ( default dense ) 36 | 37 | set tmatrix_colors = (\ 38 | default \ 39 | white \ 40 | gray \ 41 | black \ 42 | red \ 43 | green \ 44 | yellow \ 45 | blue \ 46 | magenta \ 47 | cyan \ 48 | ) 49 | 50 | complete tmatrix \ 51 | 'n/-c/$tmatrix_colors/' \ 52 | 'n/-C/$tmatrix_colors/' \ 53 | 'c/--color=/$tmatrix_colors/' \ 54 | 'c/--background=/$tmatrix_colors/' \ 55 | 'c/--mode=/$tmatrix_modes/' \ 56 | 'n/--help/n/' \ 57 | 'n/--version/n/' \ 58 | 'n/--fade/n/' \ 59 | 'n/--no-fade/n/' \ 60 | 'C/--h/(--help)/' \ 61 | 'C/--v/(--version)/' \ 62 | 'C/--f/(--fade)/' \ 63 | 'C/--n/(--no-fade)/' \ 64 | 'C/--/$tmatrix_long_options/=/' \ 65 | 'C/-/$tmatrix_short_options/' \ 66 | 'p/*/n/' # don't complete file names and alike 67 | -------------------------------------------------------------------------------- /completions/tmatrix-completion.zsh: -------------------------------------------------------------------------------- 1 | #compdef tmatrix 2 | 3 | # Copyright (C) 2018-2023 Miloš Stojanović 4 | # 5 | # SPDX-License-Identifier: GPL-2.0-only 6 | 7 | local colors=(default white gray black red green yellow blue magenta cyan) 8 | 9 | _arguments \ 10 | --mode=-"[Set the mode of the rain]:"\ 11 | "mode:(default dense)" \ 12 | {-C+,--color=-}"[Set the color of the characters]:"\ 13 | "color:(${colors[*]})" \ 14 | {-c+,--background=-}"[Set the color of the background]:"\ 15 | "color:(${colors[*]})" \ 16 | -- 17 | -------------------------------------------------------------------------------- /include/Active.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #ifndef ACTIVE_H 8 | #define ACTIVE_H 9 | 10 | class Active { 11 | public: 12 | virtual ~Active() = default; 13 | virtual void Update() = 0; 14 | }; 15 | 16 | #endif 17 | -------------------------------------------------------------------------------- /include/Color.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #ifndef COLOR_H 8 | #define COLOR_H 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | struct Color { 15 | const char* Foreground; 16 | const char* Background; 17 | const char* Shade1; 18 | const char* Shade2; 19 | const char* Shade3; 20 | const char* Shade4; 21 | 22 | static constexpr std::size_t GetPrefixSize(bool isFade) 23 | { 24 | return isFade ? sizeof("\033[38;5;234m") : sizeof("\033[100m"); 25 | } 26 | 27 | static constexpr Color GetColor(std::string_view color) { 28 | if (color == "default") { 29 | return Color {"\033[39m", "\033[49m", 30 | "\033[38;5;10m", "\033[38;5;28m", 31 | "\033[38;5;22m", "\033[38;5;234m" }; 32 | } else if (color == "white") { 33 | return Color {"\033[97m", "\033[107m", 34 | "\033[38;5;15m", "\033[38;5;246m", 35 | "\033[38;5;240m", "\033[38;5;234m" }; 36 | } else if (color == "gray") { 37 | return Color {"\033[90m", "\033[100m", 38 | "\033[38;5;246m", "\033[38;5;242m", 39 | "\033[38;5;238m", "\033[38;5;234m" }; 40 | } else if (color == "black") { 41 | return Color {"\033[30m", "\033[40m", 42 | "\033[38;5;240m", "\033[38;5;238m", 43 | "\033[38;5;236m", "\033[38;5;234m" }; 44 | } else if (color == "red") { 45 | return Color {"\033[31m", "\033[41m", 46 | "\033[38;5;196m", "\033[38;5;124m", 47 | "\033[38;5;52m", "\033[38;5;234m" }; 48 | } else if (color == "green") { 49 | return Color {"\033[92m", "\033[42m", 50 | "\033[38;5;10m", "\033[38;5;28m", 51 | "\033[38;5;22m", "\033[38;5;234m" }; 52 | } else if (color == "yellow") { 53 | return Color {"\033[33m", "\033[43m", 54 | "\033[38;5;226m", "\033[38;5;178m", 55 | "\033[38;5;94m", "\033[38;5;234m" }; 56 | } else if (color == "blue") { 57 | return Color {"\033[34m", "\033[44m", 58 | "\033[38;5;33m", "\033[38;5;26m", 59 | "\033[38;5;18m", "\033[38;5;234m" }; 60 | } else if (color == "magenta") { 61 | return Color {"\033[35m", "\033[45m", 62 | "\033[38;5;201m", "\033[38;5;127m", 63 | "\033[38;5;53m", "\033[38;5;234m" }; 64 | } else if (color == "cyan") { 65 | return Color {"\033[36m", "\033[46m", 66 | "\033[38;5;51m", "\033[38;5;38m", 67 | "\033[38;5;24m", "\033[38;5;234m" }; 68 | } else { 69 | throw std::invalid_argument("Color isn't valid."); 70 | } 71 | } 72 | }; 73 | 74 | #endif 75 | -------------------------------------------------------------------------------- /include/CountdownTimer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #ifndef COUNTDOWN_TIMER_H 8 | #define COUNTDOWN_TIMER_H 9 | 10 | #include 11 | #include "Active.h" 12 | 13 | class CountdownTimer final : public Active { 14 | int StartingTime; 15 | int CurrentTime; 16 | public: 17 | CountdownTimer(int ST) : StartingTime{ST}, CurrentTime{ST} {} 18 | CountdownTimer(int ST, int CT) : StartingTime{ST}, CurrentTime{CT} { 19 | if (CT > ST) { 20 | throw std::invalid_argument("Current time is greater than starting time."); 21 | } 22 | } 23 | 24 | bool HasExpired() const { return CurrentTime <= 0; } 25 | bool IsZeroTimer() const { return StartingTime == 0; } 26 | 27 | void Update() final 28 | { 29 | CurrentTime--; 30 | } 31 | void Reset() 32 | { 33 | CurrentTime = StartingTime; 34 | } 35 | void ResetWithStartingTime(int ST) 36 | { 37 | StartingTime = ST; 38 | Reset(); 39 | } 40 | }; 41 | 42 | #endif 43 | -------------------------------------------------------------------------------- /include/DecimalFraction.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #ifndef DECIMAL_FRACTION_H 8 | #define DECIMAL_FRACTION_H 9 | 10 | #include 11 | #include 12 | 13 | class DecimalFraction { 14 | // For example 1.2 is represented as 12. 15 | int Representation; 16 | public: 17 | constexpr DecimalFraction() : Representation{0} {} 18 | constexpr DecimalFraction(const DecimalFraction& DF) : 19 | Representation{DF.Representation} {} 20 | constexpr DecimalFraction(int IntegerPart, int FractionalPart = 0) : 21 | Representation{ 22 | IntegerPart * 10 + (IntegerPart < 0 ? - FractionalPart : FractionalPart) 23 | } 24 | { 25 | if (FractionalPart > 9 || FractionalPart < 0) { 26 | throw std::invalid_argument("Fractional part must to be in range 0-9."); 27 | } 28 | } 29 | 30 | constexpr int GetIntegerPart() const { return Representation / 10; } 31 | constexpr int GetFractionalPart() const { return Representation % 10; } 32 | 33 | constexpr DecimalFraction GetFloor() const { return Representation / 10; } 34 | 35 | constexpr bool operator>(const DecimalFraction& DF) const 36 | { 37 | return Representation > DF.Representation; 38 | } 39 | 40 | constexpr bool operator==(const DecimalFraction& DF) const 41 | { 42 | return Representation == DF.Representation; 43 | } 44 | 45 | constexpr DecimalFraction& operator+=(const DecimalFraction& DF) 46 | { 47 | Representation += DF.Representation; 48 | return *this; 49 | } 50 | 51 | constexpr DecimalFraction operator-(const DecimalFraction& DF) const 52 | { 53 | int result {Representation - DF.Representation}; 54 | return {result / 10, result % 10}; 55 | } 56 | 57 | constexpr DecimalFraction& operator=(const DecimalFraction& DF) 58 | { 59 | Representation = DF.Representation; 60 | return *this; 61 | } 62 | 63 | std::string to_string() const 64 | { 65 | return std::to_string(Representation / 10) + "." + std::to_string(Representation % 10); 66 | } 67 | }; 68 | 69 | #endif 70 | -------------------------------------------------------------------------------- /include/HasTerminal.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #ifndef HAS_TERMINAL_H 8 | #define HAS_TERMINAL_H 9 | 10 | class Terminal; 11 | 12 | struct HasTerminal { 13 | static Terminal* terminal; 14 | static void SetTerminal(Terminal* term) 15 | { 16 | terminal = term; 17 | } 18 | }; 19 | 20 | #endif 21 | -------------------------------------------------------------------------------- /include/MatrixChar.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #ifndef MATRIX_CHAR_H 8 | #define MATRIX_CHAR_H 9 | 10 | #include 11 | #include "Active.h" 12 | #include "CountdownTimer.h" 13 | #include "HasTerminal.h" 14 | 15 | class MatrixChar final : public Active, public HasTerminal { 16 | const unsigned x; 17 | const unsigned y; 18 | CountdownTimer UpdateTimer; 19 | size_t MCharIndex {GetRandomMCharIndex()}; 20 | int ColorShade {0}; 21 | 22 | static size_t GetRandomMCharIndex(); 23 | void SetRandomMChar(); 24 | void Draw() const; 25 | void Erase() const; 26 | public: 27 | static constexpr std::size_t MCHAR_SIZE {sizeof("𐌇")-1}; 28 | static constexpr std::size_t ALL_MCHARS_LENGTH {57}; 29 | static constexpr std::array ALL_MCHARS { 30 | "ハ", "ミ", "ヒ", "ー", "ウ", "シ", "ナ", "モ", "ニ", "サ", 31 | "ワ", "ツ", "オ", "リ", "ア", "ホ", "テ", "マ", "ケ", "メ", 32 | "エ", "カ", "キ", "ム", "ユ", "ラ", "セ", "ネ", "ス", "タ", 33 | "ヌ", "ヘ", "𐌇", "0", "1", "2", "3", "4", "5", "7", 34 | "8", "9", "Z", ":", ".", "・", "=", "*", "+", "-", 35 | "<", ">", "¦", "|", "╌", " ", "\"" 36 | }; 37 | 38 | MatrixChar(unsigned X, unsigned Y, int UpdateRate, int UpdateTime) : x{X}, y{Y}, 39 | UpdateTimer{UpdateRate, UpdateTime} { 40 | Draw(); 41 | } 42 | ~MatrixChar() { 43 | Erase(); 44 | } 45 | 46 | static const char *GetMChar(std::size_t index) 47 | { 48 | return ALL_MCHARS[index]; 49 | } 50 | 51 | static const char *GetEmptyMChar() 52 | { 53 | return ALL_MCHARS[ALL_MCHARS_LENGTH-2]; 54 | } 55 | 56 | unsigned GetVerticalOffset(unsigned verticalPosition) { 57 | return verticalPosition - y; 58 | } 59 | 60 | void Update() final; 61 | void SetColorShade(int colorShade); 62 | }; 63 | 64 | #endif 65 | -------------------------------------------------------------------------------- /include/Parser.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #ifndef PARSER_H 8 | #define PARSER_H 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include "Rain.h" 17 | #include "tmatrix.h" 18 | 19 | namespace Parser { 20 | constexpr int MAX_LINE_LENGTH {80}; 21 | constexpr size_t SHORT_GAP_PREFIX {2}; 22 | constexpr size_t LONG_GAP_PREFIX {6}; 23 | constexpr std::string_view SEPARATOR {" "}; 24 | 25 | struct OutputVariables { 26 | int& stepsPerSecond; 27 | RainProperties& rainProperties; 28 | std::wstring& title; 29 | }; 30 | 31 | enum OptionType { VERSION, HELP, BOOL, MODE, NUMERIC, RANGE, COLOR, TEXT }; 32 | struct Option { 33 | const OptionType Type; 34 | const std::string ShortLiteral; 35 | const std::string LongLiteral; 36 | const std::vector HelpText; 37 | const std::function ProcessArgument; 38 | 39 | static std::string GetValueName(OptionType type); 40 | std::string GetUsage() const; 41 | std::string GetLiterals() const; 42 | bool HasShortLiteral() const { return (ShortLiteral.length() != 0); } 43 | bool MatchesArgument (std::string_view argument) const; 44 | std::pair GetPrefixSuffixSplit(std::string_view argument) const; 45 | }; 46 | 47 | //---Parser-functions--------------------------------------------------- 48 | bool StartsWith(std::string_view str, std::string_view prefix); 49 | bool ParseCmdLineArgs(std::vector arguments, 50 | const OutputVariables& out); 51 | void PrintInvalidValue(std::string_view prefix, std::string_view suffix); 52 | 53 | void ParseRuntimeInput(char c, bool &paused); 54 | 55 | //---VERSION------------------------------------------------------------ 56 | void PrintVersion(); 57 | //---HELP--------------------------------------------------------------- 58 | void PrintUsage(bool full); 59 | std::vector CreateUsageHeader(); 60 | std::size_t FindLongestLiteralsLength(); 61 | void PrintUsageLine(const Option &option, std::size_t longestLiterals); 62 | void PrintSpecificOptionType(OptionType type, std::size_t longestLiterals); 63 | //---STEPS-PER-SECONDS-------------------------------------------------- 64 | void SetStepsPerSecond(std::string_view value, int &stepsPerSecond); 65 | int ReturnValidNumber(std::string_view value); 66 | //---------------------------------------------------------------------- 67 | void SetRainProperties(std::string_view mode, RainProperties &rainProperties); 68 | //---RANGE-------------------------------------------------------------- 69 | Range SplitRange(std::string_view range); 70 | //---SPEED-------------------------------------------------------------- 71 | void SetSpeedRange(std::string_view range, RainProperties &rainProperties); 72 | //---LENGTH------------------------------------------------------------- 73 | void SetLengthRange(std::string_view range, RainProperties &rainProperties); 74 | //---STARTING-GAP-RANGE------------------------------------------------- 75 | void SetStartingGapRange(std::string_view range, RainProperties &rainProperties); 76 | //---GAP-RANGE---------------------------------------------------------- 77 | void SetGapRange(std::string_view range, RainProperties &rainProperties); 78 | //---CHARACTER-UPDATE-RATE---------------------------------------------- 79 | void SetCharUpdateRateRange(std::string_view range, RainProperties &rainProperties); 80 | //---FADE--------------------------------------------------------------- 81 | void SetFade(bool fade, RainProperties &rainProperties); 82 | //---COLOR-------------------------------------------------------------- 83 | void SetColor(std::string_view color, RainProperties &rainProperties); 84 | //---BACKGROUND-COLOR--------------------------------------------------- 85 | void SetBackgroundColor(std::string_view color, RainProperties &rainProperties); 86 | //---TITLE-------------------------------------------------------------- 87 | void SetTitle(std::string_view title, RainProperties& rainProperties, std::wstring& wtitle); 88 | 89 | const std::array Options { 90 | Option{ 91 | VERSION, "", "--version", 92 | { "Output version information and exit "}, 93 | [](std::string_view, const OutputVariables&) { PrintVersion(); } 94 | }, 95 | Option{ 96 | HELP, "", "--help", 97 | { "Display this help and exit "}, 98 | [](std::string_view, const OutputVariables&) { PrintUsage(true); } 99 | }, 100 | Option{ 101 | MODE, "", "--mode", 102 | { 103 | "Set the mode of the rain", 104 | "Available modes: default, dense" 105 | }, 106 | [](std::string_view mode, const OutputVariables& out) 107 | { 108 | SetRainProperties(mode, out.rainProperties); 109 | } 110 | }, 111 | Option{ 112 | NUMERIC, "-s", "--steps-per-sec", 113 | { 114 | "Run this many steps per second", 115 | " can range from " + std::to_string(MIN_STEPS_PER_SECOND) + 116 | " to " + std::to_string(MAX_STEPS_PER_SECOND), 117 | "Default: " + std::to_string(DEFAULT_STEPS_PER_SECOND) 118 | }, 119 | [](std::string_view value, const OutputVariables& out) 120 | { 121 | SetStepsPerSecond(value, out.stepsPerSecond); 122 | } 123 | }, 124 | Option{ 125 | RANGE, "-f", "--fall-speed", 126 | { 127 | "Set the range for the fall speed", 128 | "The speeds can have decimal parts (e.g. 1.2)", 129 | "with increment of 0.1", 130 | "The maximal fall speed value is " + Rain::MAX_FALL_SPEED.to_string(), 131 | "Default: " + 132 | Rain::DEFAULT_PROPERTIES.RainColumnSpeed.GetMin().to_string() + ',' + 133 | Rain::DEFAULT_PROPERTIES.RainColumnSpeed.GetMax().to_string() 134 | 135 | }, 136 | [](std::string_view range, const OutputVariables& out) 137 | { 138 | SetSpeedRange(range, out.rainProperties); 139 | } 140 | }, 141 | Option{ 142 | RANGE, "-G", "--start-gap", 143 | { 144 | "Set the range for the starting gaps", 145 | "Default: " + 146 | std::to_string(Rain::DEFAULT_PROPERTIES.RainColumnStartingGap.GetMin()) + ',' + 147 | std::to_string(Rain::DEFAULT_PROPERTIES.RainColumnStartingGap.GetMax()) 148 | }, 149 | [](std::string_view range, const OutputVariables& out) 150 | { 151 | SetStartingGapRange(range, out.rainProperties); 152 | } 153 | }, 154 | Option{ 155 | RANGE, "-g", "--gap", 156 | { 157 | "Set the range for the gaps between streaks", 158 | "Default: " + 159 | std::to_string(Rain::DEFAULT_PROPERTIES.RainColumnGap.GetMin()) + ',' + 160 | std::to_string(Rain::DEFAULT_PROPERTIES.RainColumnGap.GetMax()) 161 | }, 162 | [](std::string_view range, const OutputVariables& out) 163 | { 164 | SetGapRange(range, out.rainProperties); 165 | } 166 | }, 167 | Option{ 168 | RANGE, "-l", "", 169 | { 170 | "Set the range for the length of rain streaks", 171 | "The minimal length value is " + std::to_string(Rain::MIN_LENGTH), 172 | "Default: " + 173 | std::to_string(Rain::DEFAULT_PROPERTIES.RainStreakLength.GetMin()) + ',' + 174 | std::to_string(Rain::DEFAULT_PROPERTIES.RainStreakLength.GetMax()) 175 | }, 176 | [](std::string_view range, const OutputVariables& out) 177 | { 178 | SetLengthRange(range, out.rainProperties); 179 | } 180 | }, 181 | Option{ 182 | RANGE, "-r", "", 183 | { 184 | "Set the range for the character update rate", 185 | "The values correspond to the number of steps", 186 | "before the change and 0 represents no change", 187 | "Default: " + 188 | std::to_string(Rain::DEFAULT_PROPERTIES.MCharUpdateRate.GetMin()) + ',' + 189 | std::to_string(Rain::DEFAULT_PROPERTIES.MCharUpdateRate.GetMax()) 190 | }, 191 | [](std::string_view range, const OutputVariables& out) 192 | { 193 | SetCharUpdateRateRange(range, out.rainProperties); 194 | } 195 | }, 196 | Option{ 197 | BOOL, "", "--fade", 198 | { 199 | "Enable fading characters (Default)" 200 | }, 201 | [](std::string_view, const OutputVariables& out) 202 | { 203 | SetFade(true, out.rainProperties); 204 | } 205 | }, 206 | Option{ 207 | BOOL, "", "--no-fade", 208 | { 209 | "Disable fading characters" 210 | }, 211 | [](std::string_view, const OutputVariables& out) 212 | { 213 | SetFade(false, out.rainProperties); 214 | } 215 | }, 216 | Option{ 217 | COLOR, "-C", "--color", 218 | { 219 | "Set the color of the characters", 220 | "Available colors: default, white, gray, black,", 221 | "red, green, yellow, blue, magenta, cyan", 222 | "Default: green" 223 | }, 224 | [](std::string_view color, const OutputVariables& out) 225 | { 226 | SetColor(color, out.rainProperties); 227 | } 228 | }, 229 | Option{ 230 | COLOR, "-c", "--background", 231 | { 232 | "Set the color of the background", 233 | "Available colors: default, white, gray, black,", 234 | "red, green, yellow, blue, magenta, cyan" 235 | }, 236 | [](std::string_view color, const OutputVariables& out) 237 | { 238 | SetBackgroundColor(color, out.rainProperties); 239 | } 240 | }, 241 | Option{ 242 | TEXT, "-t", "--title", 243 | { 244 | "Set the title that appears in the rain", 245 | "Note: the title needs to fit within the", 246 | "terminal window in order to be displayed" 247 | }, 248 | [](std::string_view title, const OutputVariables& out) 249 | { 250 | SetTitle(title, out.rainProperties, out.title); 251 | } 252 | } 253 | }; 254 | } 255 | 256 | #endif 257 | -------------------------------------------------------------------------------- /include/Rain.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #ifndef RAIN_H 8 | #define RAIN_H 9 | 10 | #include 11 | #include 12 | #include 13 | #include "Active.h" 14 | #include "Color.h" 15 | #include "DecimalFraction.h" 16 | #include "RainColumn.h" 17 | #include "RainStreak.h" 18 | #include "Range.h" 19 | #include "Terminal.h" 20 | 21 | struct RainProperties { 22 | Range RainColumnSpeed; 23 | Range RainColumnStartingGap; 24 | Range RainColumnGap; 25 | Range RainStreakLength; 26 | Range MCharUpdateRate; 27 | bool Fade; 28 | Color CharacterColor; 29 | Color BackgroundColor; 30 | std::wstring_view Title; 31 | }; 32 | 33 | class Rain : public Active { 34 | std::vector RainColumns; 35 | const RainProperties Properties; 36 | Terminal* terminal; 37 | 38 | DecimalFraction GetRandomSpeed() const; 39 | int GetRandomStartingGap() const; 40 | public: 41 | static constexpr RainProperties DEFAULT_PROPERTIES { 42 | {{0, 5}, {1, 5}}, {10, 30}, {0, 40}, {1, 30}, {10, 20}, 43 | true, Color::GetColor("green"), Color::GetColor("black"), 44 | L" T M A T R I X " 45 | }; 46 | static constexpr RainProperties DENSE_PROPERTIES { 47 | {1, 2}, {4, 9}, {4, 9}, {4, 20}, {5, 7}, 48 | false, Color::GetColor("green"), Color::GetColor("default"), 49 | L" T M A T R I X " 50 | }; 51 | static constexpr DecimalFraction MAX_FALL_SPEED {10}; 52 | static constexpr int MIN_LENGTH {1}; 53 | 54 | Rain(const RainProperties& RP, Terminal* T); 55 | 56 | void Reset(); 57 | void Update() final; 58 | virtual void UpdateStreakColors(RainStreak& rainStreak) const = 0; 59 | int GetRandomLength() const; 60 | int GetRandomGap() const; 61 | std::pair GetRandomUpdateRateAndTime() const; 62 | }; 63 | 64 | class FadingRain final : public Rain { 65 | public: 66 | using Rain::Rain; 67 | void UpdateStreakColors(RainStreak& rainStreak) const; 68 | }; 69 | 70 | class NonFadingRain final : public Rain { 71 | public: 72 | using Rain::Rain; 73 | void UpdateStreakColors(RainStreak& rainStreak) const; 74 | }; 75 | 76 | #endif 77 | -------------------------------------------------------------------------------- /include/RainColumn.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #ifndef RAIN_COLUMN_H 8 | #define RAIN_COLUMN_H 9 | 10 | #include 11 | #include "Active.h" 12 | #include "CountdownTimer.h" 13 | #include "DecimalFraction.h" 14 | #include "HasTerminal.h" 15 | #include "RainStreak.h" 16 | #include "Random.h" 17 | 18 | class Rain; 19 | 20 | class RainColumn final : public Active, public HasTerminal { 21 | const Rain *rain; 22 | const unsigned x; 23 | std::vector Speeds; 24 | int SpeedIndex; 25 | CountdownTimer GapTimer; 26 | wchar_t TitleChar; 27 | const RainStreak *FirstRainStreak {nullptr}; 28 | bool CreatedRainStreak {false}; 29 | bool EmptyRainStreakSlot {true}; 30 | std::list RainStreaks; 31 | public: 32 | RainColumn(const Rain *R, unsigned X, DecimalFraction S, int G, wchar_t TC) : 33 | rain{R}, x{X}, GapTimer{G}, TitleChar{TC} 34 | { 35 | GenerateSpeeds(S); 36 | SpeedIndex = Random::Random(Speeds.size()); 37 | } 38 | 39 | void GenerateSpeeds(DecimalFraction Speed); 40 | 41 | void Step(); 42 | void Update() final; 43 | }; 44 | 45 | #endif 46 | -------------------------------------------------------------------------------- /include/RainStreak.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #ifndef RAIN_STREAK_H 8 | #define RAIN_STREAK_H 9 | 10 | #include 11 | #include "Active.h" 12 | #include "HasTerminal.h" 13 | #include "MatrixChar.h" 14 | 15 | class Rain; 16 | 17 | class RainStreak final : public Active, public HasTerminal { 18 | const Rain *rain; 19 | const unsigned x; 20 | unsigned y {0}; 21 | const unsigned Length; 22 | bool FullyEnteredScreen {false}; 23 | bool ReachedScreenMiddle {false}; 24 | bool LeftScreenMiddle {false}; 25 | bool OutOfScreen {false}; 26 | std::deque MChars; 27 | public: 28 | RainStreak(const Rain *R, unsigned col, unsigned len) : 29 | rain{R}, x{col}, Length{len} {} 30 | 31 | bool HasFullyEnteredScreen() const { return FullyEnteredScreen; } 32 | bool HasReachedScreenMiddle() const { return ReachedScreenMiddle; } 33 | bool HasLeftScreenMiddle() const { return LeftScreenMiddle; } 34 | bool IsOutOfScreen() const { return OutOfScreen; } 35 | void Update() final; 36 | void UpdateShadeColors(); 37 | void RemoveGlowFromPreviousHead(); 38 | }; 39 | 40 | #endif 41 | -------------------------------------------------------------------------------- /include/Random.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #ifndef RANDOM_H 8 | #define RANDOM_H 9 | 10 | #include "DecimalFraction.h" 11 | #include "Range.h" 12 | 13 | namespace Random { 14 | // Returns a random integer in the range [range.min, range.max] 15 | int Random(Range range); 16 | // Returns a random integer in the range [min, max] 17 | int Random(int min, int max); 18 | // Returns a random integer in the range [0, range-1] 19 | int Random(int range); 20 | // Returns a random decimal fraction in the range [range.min, range.max] 21 | DecimalFraction Random(Range range); 22 | } 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /include/Range.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #ifndef RANGE_H 8 | #define RANGE_H 9 | 10 | #include 11 | 12 | template 13 | class Range { 14 | T min; 15 | T max; 16 | public: 17 | constexpr Range() = default; 18 | constexpr Range(T Min, T Max) : min{Min}, max{Max} { 19 | if (Min > Max) { 20 | throw std::range_error("Min is greater than max."); 21 | } 22 | } 23 | constexpr Range(T range) : min{0}, max{range-1} { 24 | if (range == 0) { 25 | throw std::range_error("range can't be zero."); 26 | } 27 | } 28 | 29 | T GetMin() const { return min; } 30 | T GetMax() const { return max; } 31 | }; 32 | 33 | template Range(T, T) -> Range; 34 | 35 | #endif 36 | -------------------------------------------------------------------------------- /include/Terminal.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #ifndef TERMINAL_H 8 | #define TERMINAL_H 9 | 10 | #include 11 | #include "Color.h" 12 | #include "TerminalChar.h" 13 | 14 | class Terminal { 15 | protected: 16 | unsigned NumberOfRows {0}; 17 | unsigned NumberOfColumns {0}; 18 | public: 19 | Terminal(); 20 | virtual ~Terminal(); 21 | 22 | unsigned GetNumberOfRows() { return NumberOfRows; } 23 | unsigned GetNumberOfColumns() { return NumberOfColumns; } 24 | 25 | virtual void Reset() = 0; 26 | virtual void Draw(unsigned x, unsigned y, const char *mchar, int colorShade) = 0; 27 | virtual void Erase(unsigned x, unsigned y) = 0; 28 | virtual void DrawTitle(unsigned x, unsigned y, wchar_t tchar) = 0; 29 | virtual void Flush() = 0; 30 | }; 31 | 32 | template 33 | class ColorTerminal : public Terminal { 34 | using TCharType = TerminalChar; 35 | 36 | std::vector ScreenBuffer; 37 | public: 38 | ColorTerminal(const Color& color, const Color& background_color); 39 | 40 | void Reset() final; 41 | void Draw(unsigned x, unsigned y, const char *mchar, int colorShade) final; 42 | void Erase(unsigned x, unsigned y) final; 43 | void DrawTitle(unsigned x, unsigned y, wchar_t tchar) final; 44 | void Flush() final; 45 | }; 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /include/TerminalChar.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #ifndef TERMINAL_CHAR_H 8 | #define TERMINAL_CHAR_H 9 | 10 | #include "Color.h" 11 | #include "MatrixChar.h" 12 | 13 | template 14 | struct BaseTerminalChar { 15 | static constexpr std::size_t PREFIX_SIZE {Color::GetPrefixSize(F)-1}; 16 | 17 | static const char *GLOWING_COLOR_ESC_SEQ; 18 | static const char *NORMAL_COLOR_ESC_SEQ; 19 | 20 | // Non-static members 21 | char prefix[PREFIX_SIZE]; 22 | char MChar[MatrixChar::MCHAR_SIZE]; 23 | 24 | BaseTerminalChar() 25 | { 26 | Clear(); 27 | } 28 | 29 | void Clear(); 30 | 31 | void SetFullTitleChar(wchar_t tchar); 32 | }; 33 | 34 | template 35 | struct TerminalChar; 36 | 37 | template <> 38 | struct TerminalChar : public BaseTerminalChar { 39 | static const char *NORMAL_COLOR_ESC_SEQ_2; 40 | static const char *NORMAL_COLOR_ESC_SEQ_3; 41 | static const char *NORMAL_COLOR_ESC_SEQ_4; 42 | 43 | static void SetColor(const Color& color); 44 | 45 | void SetFullMChar(const char *mchar, int colorShade); 46 | }; 47 | 48 | template <> 49 | struct TerminalChar : public BaseTerminalChar { 50 | static void SetColor(const Color& color); 51 | 52 | void SetFullMChar(const char *mchar, int colorShade); 53 | }; 54 | 55 | #endif 56 | -------------------------------------------------------------------------------- /include/tmatrix.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #ifndef TMATRIX_H 8 | #define TMATRIX_H 9 | 10 | constexpr double VERSION_NUMBER {1.4}; 11 | 12 | constexpr int MIN_STEPS_PER_SECOND {1}; 13 | constexpr int MAX_STEPS_PER_SECOND {60}; 14 | constexpr int DEFAULT_STEPS_PER_SECOND {10}; 15 | 16 | #endif 17 | -------------------------------------------------------------------------------- /src/HasTerminal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #include "HasTerminal.h" 8 | 9 | Terminal* HasTerminal::terminal; 10 | -------------------------------------------------------------------------------- /src/MatrixChar.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #include "MatrixChar.h" 8 | #include "Random.h" 9 | #include "Terminal.h" 10 | 11 | size_t MatrixChar::GetRandomMCharIndex() 12 | { 13 | return static_cast(Random::Random(ALL_MCHARS.size())); 14 | } 15 | 16 | void MatrixChar::SetRandomMChar() 17 | { 18 | size_t newIndex {GetRandomMCharIndex()}; 19 | while (MCharIndex == newIndex) { 20 | newIndex = GetRandomMCharIndex(); 21 | } 22 | 23 | MCharIndex = newIndex; 24 | } 25 | 26 | void MatrixChar::Draw() const 27 | { 28 | terminal->Draw(x, y, ALL_MCHARS[MCharIndex], ColorShade); 29 | } 30 | 31 | void MatrixChar::Erase() const 32 | { 33 | terminal->Erase(x, y); 34 | } 35 | 36 | void MatrixChar::Update() 37 | { 38 | if (UpdateTimer.IsZeroTimer()) { 39 | return; 40 | } 41 | 42 | if (UpdateTimer.HasExpired()) { 43 | UpdateTimer.Reset(); 44 | SetRandomMChar(); 45 | Draw(); 46 | } 47 | UpdateTimer.Update(); 48 | } 49 | 50 | void MatrixChar::SetColorShade(int colorShade) 51 | { 52 | if (colorShade != ColorShade) { 53 | ColorShade = colorShade; 54 | Draw(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/Parser.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include "Color.h" 16 | #include "Parser.h" 17 | 18 | namespace Parser { 19 | std::string Option::GetValueName(OptionType type) 20 | { 21 | switch (type) { 22 | case VERSION: 23 | case HELP: 24 | case BOOL: 25 | return ""; 26 | case MODE: 27 | return "MODE"; 28 | case NUMERIC: 29 | return "VALUE"; 30 | case RANGE: 31 | return "RANGE"; 32 | case COLOR: 33 | return "COLOR"; 34 | case TEXT: 35 | return "TEXT"; 36 | } 37 | return ""; 38 | } 39 | 40 | std::string Option::GetUsage() const 41 | { 42 | std::string valueName {GetValueName(Type)}; 43 | switch (Type) { 44 | case VERSION: 45 | case HELP: 46 | case BOOL: 47 | return "[" + LongLiteral + ']'; 48 | case MODE: 49 | case NUMERIC: 50 | case RANGE: 51 | case COLOR: 52 | case TEXT: 53 | if (ShortLiteral != "" && LongLiteral != "") { 54 | return "[" + ShortLiteral + " " + valueName + " | " + 55 | LongLiteral + "=" + valueName + "]"; 56 | } else if (ShortLiteral != "") { 57 | return "[" + ShortLiteral + " " + valueName + "]"; 58 | } else { 59 | return "[" + LongLiteral + "=" + valueName + "]"; 60 | } 61 | } 62 | return ""; 63 | } 64 | 65 | std::string Option::GetLiterals() const 66 | { 67 | std::string valueName {GetValueName(Type)}; 68 | switch (Type) { 69 | case VERSION: 70 | case HELP: 71 | case BOOL: 72 | return LongLiteral; 73 | case MODE: 74 | case NUMERIC: 75 | case RANGE: 76 | case COLOR: 77 | case TEXT: 78 | if (ShortLiteral != "" && LongLiteral != "") { 79 | return ShortLiteral + ", " + LongLiteral + "=" + valueName; 80 | } else if (ShortLiteral != "") { 81 | return ShortLiteral + " " + valueName; 82 | } else { 83 | return LongLiteral + "=" + valueName; 84 | } 85 | } 86 | return ""; 87 | } 88 | 89 | std::pair Option::GetPrefixSuffixSplit(std::string_view argument) const 90 | { 91 | std::string literal; 92 | if (StartsWith(argument, "--") && LongLiteral != "") { 93 | literal = LongLiteral; 94 | if (Type == MODE || 95 | Type == NUMERIC || 96 | Type == RANGE || 97 | Type == COLOR || 98 | Type == TEXT) { 99 | literal += '='; 100 | } 101 | } else if (StartsWith(argument, "-") && ShortLiteral != "") { 102 | literal = ShortLiteral; 103 | } else { 104 | throw std::invalid_argument("Invalid argument format."); 105 | } 106 | 107 | if (argument.size() < literal.size()) { 108 | throw std::invalid_argument("Argument is too big."); 109 | } 110 | std::string_view prefix {argument.substr(0, literal.length())}; 111 | std::string_view suffix {argument.substr(literal.length())}; 112 | if (prefix != literal) { 113 | throw std::invalid_argument("Prefix doesn't match."); 114 | } 115 | return {prefix, suffix}; 116 | } 117 | 118 | bool Option::MatchesArgument (std::string_view argument) const 119 | { 120 | try { 121 | GetPrefixSuffixSplit(argument); 122 | } catch (const std::invalid_argument&) { 123 | return false; 124 | } 125 | return true; 126 | } 127 | 128 | //---Parser-functions--------------------------------------------------- 129 | bool StartsWith(std::string_view str, std::string_view prefix) { 130 | return (str.substr(0, prefix.length()) == prefix); 131 | } 132 | 133 | bool ParseCmdLineArgs(std::vector arguments, 134 | const OutputVariables& out) 135 | { 136 | SetRainProperties("default", out.rainProperties); 137 | for (decltype(arguments)::size_type i = 0; i < arguments.size(); i++) { 138 | std::string_view argument {arguments[i]}; 139 | 140 | bool matched {false}; 141 | for (const Option &option : Options) { 142 | if (!option.MatchesArgument(argument)) { 143 | continue; 144 | } 145 | auto [prefix, suffix] { option.GetPrefixSuffixSplit(argument) }; 146 | matched = true; 147 | switch (option.Type) { 148 | case VERSION: 149 | case HELP: 150 | case BOOL: 151 | if (suffix != "") { 152 | matched = false; 153 | break; 154 | } 155 | option.ProcessArgument(argument, out); 156 | if (option.Type != BOOL) { 157 | return false; 158 | } 159 | break; 160 | case MODE: 161 | case NUMERIC: 162 | case RANGE: 163 | case COLOR: 164 | case TEXT: 165 | if (suffix == "") { 166 | try { 167 | suffix = arguments.at(++i); 168 | } catch (const std::out_of_range&) { 169 | std::cout << "No value specified for " << argument << '\n'; 170 | PrintUsage(false); 171 | return false; 172 | } 173 | if (StartsWith(prefix, "--")) { 174 | std::cout << "No value specified for " << argument << '\n'; 175 | PrintUsage(false); 176 | return false; 177 | } 178 | } 179 | 180 | try { 181 | option.ProcessArgument(suffix, out); 182 | } catch (const std::out_of_range&) { 183 | PrintInvalidValue(prefix, suffix); 184 | return false; 185 | } catch (const std::invalid_argument&) { 186 | PrintInvalidValue(prefix, suffix); 187 | return false; 188 | } catch (const std::range_error&) { 189 | std::cout << "Invalid values '" << suffix; 190 | std::cout << "' specified for " << prefix << '\n'; 191 | std::cout << "The first value must be"; 192 | std::cout << " greater than the second." << '\n'; 193 | return false; 194 | } 195 | break; 196 | } 197 | } 198 | if (!matched) { 199 | std::cout << "Unknown option: " << argument << '\n'; 200 | PrintUsage(false); 201 | return false; 202 | } 203 | } 204 | return true; 205 | } 206 | 207 | void PrintInvalidValue(std::string_view prefix, std::string_view suffix) 208 | { 209 | std::cout << "Invalid value '" << suffix; 210 | std::cout << "' specified for " << prefix << '\n'; 211 | std::cout << "Try 'tmatrix --help' for more information." << '\n'; 212 | } 213 | 214 | void ParseRuntimeInput(char c, bool &paused) 215 | { 216 | switch (c) { 217 | case 'p': 218 | case 'P': 219 | paused = !paused; 220 | break; 221 | case 'q': 222 | case 'Q': 223 | std::raise(SIGTERM); 224 | break; 225 | } 226 | } 227 | 228 | //---VERSION------------------------------------------------------------ 229 | void PrintVersion() 230 | { 231 | std::cout.precision(1); 232 | std::cout << "tmatrix version " << std::fixed << VERSION_NUMBER << '\n'; 233 | std::cout << '\n'; 234 | std::cout << "Copyright (C) 2018-2023 Miloš Stojanović" << '\n'; 235 | std::cout << "SPDX-License-Identifier: GPL-2.0-only" << '\n'; 236 | } 237 | 238 | //---HELP--------------------------------------------------------------- 239 | void PrintUsage(bool full) 240 | { 241 | std::vector header {CreateUsageHeader()}; 242 | for (std::string_view line : header) { 243 | std::cout << line << '\n'; 244 | } 245 | 246 | if (full) { 247 | std::cout << "Simulates the digital rain effect from The Matrix." << '\n'; 248 | std::cout << "Use 'p' to pause and 'q' to quit." << '\n'; 249 | std::cout << '\n'; 250 | 251 | std::size_t longestLiterals {FindLongestLiteralsLength()}; 252 | for (const Option &option : Options) { 253 | if (option.Type != HELP && option.Type != VERSION) { 254 | PrintUsageLine(option, longestLiterals); 255 | } 256 | } 257 | // Print help and version at the end 258 | PrintSpecificOptionType(HELP, longestLiterals); 259 | PrintSpecificOptionType(VERSION, longestLiterals); 260 | std::cout << '\n'; 261 | std::cout << "RANGE is a pair of numbers separated by a comma: MIN,MAX." << '\n'; 262 | std::cout << "It specifies the boundaries of a set from which random numbers are picked." << '\n'; 263 | } 264 | } 265 | 266 | std::vector CreateUsageHeader() 267 | { 268 | std::vector usage {"Usage: tmatrix"}; 269 | const auto usageStartLength {usage.back().length()}; 270 | 271 | for (const Option &option : Options) { 272 | if (usage.back().length() + 1 + option.GetUsage().length() > MAX_LINE_LENGTH) { 273 | usage.emplace_back(usageStartLength, ' '); 274 | } 275 | usage.back() += ' ' + option.GetUsage(); 276 | } 277 | 278 | return usage; 279 | } 280 | 281 | std::size_t FindLongestLiteralsLength() 282 | { 283 | std::size_t longest {0}; 284 | for (const Option &option : Options) { 285 | std::size_t current {option.GetLiterals().length()}; 286 | current += option.HasShortLiteral() ? SHORT_GAP_PREFIX : LONG_GAP_PREFIX; 287 | if (current > longest) { 288 | longest = current; 289 | } 290 | } 291 | 292 | return longest; 293 | } 294 | 295 | void PrintUsageLine(const Option &option, std::size_t longestLiterals) 296 | { 297 | size_t gapSize {option.HasShortLiteral() ? SHORT_GAP_PREFIX : LONG_GAP_PREFIX}; 298 | std::string line(gapSize, ' '); 299 | line += option.GetLiterals(); 300 | line += std::string(longestLiterals-line.length(), ' '); 301 | line += SEPARATOR; 302 | for (std::size_t i = 0; i < option.HelpText.size(); i++) { 303 | if (i != 0) { 304 | line += std::string(longestLiterals+SEPARATOR.length(), ' '); 305 | } 306 | line += option.HelpText[i]; 307 | line += '\n'; 308 | } 309 | std::cout << line; 310 | } 311 | 312 | void PrintSpecificOptionType(OptionType type, std::size_t longestLiterals) 313 | { 314 | for (const Option &option : Options) { 315 | if (option.Type == type) { 316 | PrintUsageLine(option, longestLiterals); 317 | } 318 | } 319 | } 320 | 321 | //---FADE--------------------------------------------------------------- 322 | void SetFade(bool fade, RainProperties &rainProperties) 323 | { 324 | rainProperties.Fade = fade; 325 | } 326 | //---STEPS-PER-SECONDS-------------------------------------------------- 327 | void SetStepsPerSecond(std::string_view value, int &stepsPerSecond) 328 | { 329 | stepsPerSecond = ReturnValidNumber(value); 330 | if (stepsPerSecond < MIN_STEPS_PER_SECOND || 331 | stepsPerSecond > MAX_STEPS_PER_SECOND) { 332 | throw std::out_of_range("Value is out of range."); 333 | } 334 | } 335 | 336 | int ReturnValidNumber(std::string_view value) 337 | { 338 | if (value.length() == 0 || 339 | std::any_of(value.begin(), value.end(), 340 | [](unsigned char c) { return !std::isdigit(c); })) { 341 | throw std::invalid_argument("Number isn't valid."); 342 | } 343 | 344 | return std::atoi(value.data()); 345 | } 346 | 347 | DecimalFraction ReturnValidDecimalFraction(std::string_view value) 348 | { 349 | int IntegerPart {0}; 350 | int FractionPart {0}; 351 | 352 | auto pointPlace {value.find('.')}; 353 | if (pointPlace == 0) { 354 | std::string_view FractionPartString {value.substr(pointPlace + 1)}; 355 | if (FractionPartString.length() > 1) { 356 | throw std::invalid_argument("Fractional part is too long."); 357 | } 358 | FractionPart = ReturnValidNumber(FractionPartString); 359 | } 360 | else if (pointPlace == value.length() - 1) { 361 | IntegerPart = ReturnValidNumber(value.substr(0, pointPlace)); 362 | } 363 | else if (pointPlace == std::string_view::npos) { 364 | IntegerPart = ReturnValidNumber(value); 365 | } 366 | else { 367 | IntegerPart = ReturnValidNumber(value.substr(0, pointPlace)); 368 | 369 | std::string_view FractionPartString {value.substr(pointPlace + 1)}; 370 | if (FractionPartString.length() > 1) { 371 | throw std::invalid_argument("Fractional part is too long."); 372 | } 373 | FractionPart = ReturnValidNumber(FractionPartString); 374 | } 375 | return {IntegerPart, FractionPart}; 376 | } 377 | //---------------------------------------------------------------------- 378 | void SetRainProperties(std::string_view mode, RainProperties &rainProperties) 379 | { 380 | if (mode == "default") { 381 | rainProperties = Rain::DEFAULT_PROPERTIES; 382 | } else if (mode == "dense") { 383 | rainProperties = Rain::DENSE_PROPERTIES; 384 | } else { 385 | throw std::invalid_argument("Mode isn't valid."); 386 | } 387 | } 388 | 389 | //---RANGE-------------------------------------------------------------- 390 | Range SplitRange(std::string_view range) 391 | { 392 | auto commaPlace {range.find(',')}; 393 | if (commaPlace == std::string_view::npos) { 394 | throw std::invalid_argument("No comma found in range argument."); 395 | } 396 | int min {ReturnValidNumber(range.substr(0, commaPlace))}; 397 | int max {ReturnValidNumber(range.substr(commaPlace + 1))}; 398 | return {min, max}; 399 | } 400 | 401 | Range SplitDecimalFractionRange(std::string_view range) 402 | { 403 | auto commaPlace {range.find(',')}; 404 | if (commaPlace == std::string_view::npos) { 405 | throw std::invalid_argument("No comma found in range argument."); 406 | } 407 | DecimalFraction min {ReturnValidDecimalFraction(range.substr(0, commaPlace))}; 408 | DecimalFraction max {ReturnValidDecimalFraction(range.substr(commaPlace + 1))}; 409 | return {min, max}; 410 | } 411 | //---SPEED-------------------------------------------------------------- 412 | void SetSpeedRange(std::string_view range, RainProperties &rainProperties) 413 | { 414 | rainProperties.RainColumnSpeed = SplitDecimalFractionRange(range); 415 | if (rainProperties.RainColumnSpeed.GetMax() > Rain::MAX_FALL_SPEED) { 416 | throw std::out_of_range("Value is out of range."); 417 | } 418 | } 419 | //---STARTING-GAP-RANGE------------------------------------------------- 420 | void SetStartingGapRange(std::string_view range, RainProperties &rainProperties) 421 | { 422 | rainProperties.RainColumnStartingGap = SplitRange(range); 423 | } 424 | //---GAP-RANGE---------------------------------------------------------- 425 | void SetGapRange(std::string_view range, RainProperties &rainProperties) 426 | { 427 | rainProperties.RainColumnGap = SplitRange(range); 428 | } 429 | //---LENGTH------------------------------------------------------------- 430 | void SetLengthRange(std::string_view range, RainProperties &rainProperties) 431 | { 432 | rainProperties.RainStreakLength = SplitRange(range); 433 | if (rainProperties.RainStreakLength.GetMin() < Rain::MIN_LENGTH) { 434 | throw std::out_of_range("Value is out of range."); 435 | } 436 | } 437 | //---CHARACTER-UPDATE-RATE---------------------------------------------- 438 | void SetCharUpdateRateRange(std::string_view range, RainProperties &rainProperties) 439 | { 440 | rainProperties.MCharUpdateRate = SplitRange(range); 441 | } 442 | //---COLOR-------------------------------------------------------------- 443 | void SetColor(std::string_view color, RainProperties &rainProperties) 444 | { 445 | rainProperties.CharacterColor = Color::GetColor(color); 446 | } 447 | //---BACKGROUND-COLOR--------------------------------------------------- 448 | void SetBackgroundColor(std::string_view color, RainProperties &rainProperties) 449 | { 450 | rainProperties.BackgroundColor = Color::GetColor(color); 451 | } 452 | //---TITLE-------------------------------------------------------------- 453 | void SetTitle(std::string_view title, RainProperties& rainProperties, std::wstring& wtitle) 454 | { 455 | // Convert (const char *) to wstring 456 | std::setlocale(LC_ALL, "en_US.utf8"); 457 | std::mbtowc(nullptr, nullptr, 0); 458 | const char* ptr = title.data(); 459 | const size_t byte_len = title.length(); 460 | int len; 461 | for (wchar_t wc; (len = std::mbtowc(&wc, ptr, byte_len)) > 0; ptr += len) { 462 | wtitle.push_back(wc); 463 | } 464 | rainProperties.Title = wtitle; 465 | } 466 | } 467 | -------------------------------------------------------------------------------- /src/Rain.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #include 8 | #include "Rain.h" 9 | #include "Random.h" 10 | #include "Terminal.h" 11 | 12 | Rain::Rain(const RainProperties& RP, Terminal* T) : Properties{RP}, terminal{T} 13 | { 14 | RainColumn::SetTerminal(T); 15 | RainStreak::SetTerminal(T); 16 | MatrixChar::SetTerminal(T); 17 | Reset(); 18 | } 19 | 20 | void Rain::Reset() 21 | { 22 | // Create all the rain columns 23 | unsigned numberOfColumns {terminal->GetNumberOfColumns()}; 24 | size_t titleLength {Properties.Title.length()}; 25 | 26 | size_t titleCharIndex {0}; 27 | RainColumns.clear(); 28 | RainColumns.reserve(numberOfColumns); 29 | for (unsigned i = 0; i < numberOfColumns; i++) { 30 | bool titleColumn {numberOfColumns >= titleLength && titleLength > 0 && 31 | i + std::ceil(titleLength/2.0) >= numberOfColumns/2 && 32 | i < numberOfColumns/2 + std::floor(titleLength/2.0)}; 33 | wchar_t titleChar {titleColumn ? Properties.Title[titleCharIndex++] : '\0'}; 34 | RainColumns.emplace_back(this, i, GetRandomSpeed(), GetRandomStartingGap(), 35 | titleChar); 36 | } 37 | } 38 | 39 | void Rain::Update() 40 | { 41 | for (RainColumn &rc : RainColumns) { 42 | rc.Update(); 43 | } 44 | } 45 | 46 | DecimalFraction Rain::GetRandomSpeed() const 47 | { 48 | return Random::Random(Properties.RainColumnSpeed); 49 | } 50 | 51 | int Rain::GetRandomStartingGap() const 52 | { 53 | return Random::Random(Properties.RainColumnStartingGap); 54 | } 55 | 56 | int Rain::GetRandomLength() const 57 | { 58 | return Random::Random(Properties.RainStreakLength); 59 | } 60 | 61 | int Rain::GetRandomGap() const 62 | { 63 | return Random::Random(Properties.RainColumnGap); 64 | } 65 | 66 | std::pair Rain::GetRandomUpdateRateAndTime() const 67 | { 68 | int UpdateRate {Random::Random(Properties.MCharUpdateRate)}; 69 | int UpdateTime {UpdateRate ? Random::Random(UpdateRate) : 0}; 70 | return {UpdateRate, UpdateTime}; 71 | } 72 | 73 | void FadingRain::UpdateStreakColors(RainStreak& rainStreak) const 74 | { 75 | rainStreak.UpdateShadeColors(); 76 | } 77 | 78 | void NonFadingRain::UpdateStreakColors(RainStreak& rainStreak) const 79 | { 80 | rainStreak.RemoveGlowFromPreviousHead(); 81 | } 82 | -------------------------------------------------------------------------------- /src/RainColumn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #include 8 | #include "Rain.h" 9 | #include "RainColumn.h" 10 | #include "Terminal.h" 11 | 12 | void RainColumn::GenerateSpeeds(DecimalFraction speed) 13 | { 14 | // Generates an array of integer speeds whose cumulative average is equal 15 | // to the specified speed. The order is also such that the average of any 16 | // sampled subset should be as close to the specified speed as possible 17 | // to create a nice, consistent visual. 18 | DecimalFraction speedAproximation {speed}; 19 | DecimalFraction trueSum {speed}; 20 | DecimalFraction sumOfIntegerSpeeds {0}; 21 | while (true) { 22 | DecimalFraction integerSpeed {speedAproximation.GetFloor()}; 23 | Speeds.emplace_back(integerSpeed.GetIntegerPart()); 24 | if (integerSpeed == speedAproximation) 25 | return; 26 | sumOfIntegerSpeeds += integerSpeed; 27 | trueSum += speed; 28 | speedAproximation = trueSum - sumOfIntegerSpeeds; 29 | } 30 | } 31 | 32 | void RainColumn::Step() 33 | { 34 | if (EmptyRainStreakSlot) { 35 | if (!GapTimer.HasExpired()) { 36 | GapTimer.Update(); 37 | } else { 38 | // Create new streak 39 | RainStreaks.emplace_back(rain, x, rain->GetRandomLength()); 40 | if (!CreatedRainStreak) { 41 | FirstRainStreak = &RainStreaks.back(); 42 | CreatedRainStreak = true; 43 | } 44 | EmptyRainStreakSlot = false; 45 | } 46 | } 47 | 48 | if (!RainStreaks.empty()) { 49 | // Update all the RainStreaks 50 | for (RainStreak &rs : RainStreaks) { 51 | rs.Update(); 52 | } 53 | 54 | const auto& Head {RainStreaks.back()}; 55 | // Check if a title character needs to be drawn 56 | bool ContainsTitle {TitleChar != '\0'}; 57 | if (ContainsTitle && FirstRainStreak && 58 | FirstRainStreak->HasReachedScreenMiddle() && 59 | !FirstRainStreak->HasLeftScreenMiddle() && TitleChar != ' ') { 60 | terminal->DrawTitle(x, terminal->GetNumberOfRows()/2, TitleChar); 61 | } 62 | // Check if an empty slot appeared 63 | if ((!ContainsTitle || !FirstRainStreak || 64 | FirstRainStreak->HasReachedScreenMiddle()) && 65 | Head.HasFullyEnteredScreen() && !EmptyRainStreakSlot) { 66 | EmptyRainStreakSlot = true; 67 | GapTimer.ResetWithStartingTime(rain->GetRandomGap()); 68 | } 69 | 70 | // Delete RainStreaks that are out of screen 71 | while (!RainStreaks.empty() && RainStreaks.front().IsOutOfScreen()) { 72 | RainStreaks.pop_front(); 73 | FirstRainStreak = nullptr; 74 | } 75 | } 76 | } 77 | 78 | void RainColumn::Update() 79 | { 80 | for (int i = 0; i < Speeds[SpeedIndex]; i++) { 81 | Step(); 82 | } 83 | SpeedIndex = (SpeedIndex + 1) % Speeds.size(); 84 | } 85 | -------------------------------------------------------------------------------- /src/RainStreak.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #include "Rain.h" 8 | #include "RainStreak.h" 9 | #include "Terminal.h" 10 | 11 | void RainStreak::Update() 12 | { 13 | if (FullyEnteredScreen) { 14 | if (!MChars.empty()) { 15 | // Delete the tail MChar 16 | MChars.pop_back(); 17 | } else { 18 | OutOfScreen = true; 19 | } 20 | } 21 | rain->UpdateStreakColors(*this); 22 | unsigned numberOfRows {terminal->GetNumberOfRows()}; 23 | // Create a new head MChar 24 | if (y < numberOfRows) { 25 | auto [updateRate, updateTime] { rain->GetRandomUpdateRateAndTime() }; 26 | 27 | MChars.emplace_front(x, y, updateRate, updateTime); 28 | } 29 | // Advance position 30 | y++; 31 | // Check if the tail MChar has entered the screen 32 | if (y >= Length) { 33 | FullyEnteredScreen = true; 34 | } 35 | // Check if the head MChar has reached the screen middle 36 | if (y > numberOfRows/2) { 37 | ReachedScreenMiddle = true; 38 | if (y > numberOfRows/2 + Length + 1) { 39 | LeftScreenMiddle = true; 40 | } 41 | } 42 | // Update all the MChars 43 | for (MatrixChar &mc : MChars) { 44 | mc.Update(); 45 | } 46 | } 47 | 48 | void RainStreak::UpdateShadeColors() 49 | { 50 | if (!MChars.empty()) { 51 | for (MatrixChar &mc : MChars) { 52 | unsigned position = mc.GetVerticalOffset(y); 53 | if (position < Length/2) { 54 | mc.SetColorShade(1); 55 | } else if (position < (3*Length)/4) { 56 | mc.SetColorShade(2); 57 | } else if (position <= (7*Length)/8) { 58 | mc.SetColorShade(3); 59 | } else { 60 | mc.SetColorShade(4); 61 | } 62 | } 63 | } 64 | } 65 | 66 | void RainStreak::RemoveGlowFromPreviousHead() 67 | { 68 | if (!MChars.empty()) { 69 | MChars.front().SetColorShade(1); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/Random.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #include 8 | #include "Random.h" 9 | 10 | namespace Random { 11 | static std::random_device RandomDevice {}; 12 | static std::mt19937 RandomEngine {RandomDevice()}; 13 | 14 | int Random(Range range) 15 | { 16 | std::uniform_int_distribution<> distribution {range.GetMin(), range.GetMax()}; 17 | return distribution(RandomEngine); 18 | } 19 | 20 | int Random(int min, int max) 21 | { 22 | return Random(Range(min, max)); 23 | } 24 | 25 | int Random(int range) 26 | { 27 | return Random(Range(range)); 28 | } 29 | 30 | DecimalFraction Random(Range range) 31 | { 32 | const DecimalFraction minDF {range.GetMin()}; 33 | const DecimalFraction maxDF {range.GetMax()}; 34 | const int min {minDF.GetIntegerPart() * 10 + minDF.GetFractionalPart()}; 35 | const int max {maxDF.GetIntegerPart() * 10 + maxDF.GetFractionalPart()}; 36 | const int random {Random(min, max)}; 37 | return {random / 10, random % 10}; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Terminal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include "Terminal.h" 12 | 13 | Terminal::Terminal() 14 | { 15 | initscr(); 16 | savetty(); 17 | nonl(); 18 | cbreak(); 19 | noecho(); 20 | timeout(0); 21 | leaveok(stdscr, TRUE); 22 | curs_set(0); 23 | 24 | // Disable C stream sync 25 | std::ios::sync_with_stdio(false); 26 | 27 | // Calling this here first prevents delay in the main loop. 28 | getch(); 29 | } 30 | 31 | Terminal::~Terminal() 32 | { 33 | curs_set(1); 34 | clear(); 35 | refresh(); 36 | resetty(); 37 | endwin(); 38 | } 39 | 40 | template 41 | ColorTerminal::ColorTerminal(const Color& color, const Color& background_color) 42 | { 43 | // Set bold style 44 | std::cout << "\033[1m"; 45 | // Set foreground color 46 | TCharType::SetColor(color); 47 | // Set background color 48 | std::cout << background_color.Background; 49 | 50 | Reset(); 51 | } 52 | 53 | // Instantiate both versions of the constructor 54 | template ColorTerminal::ColorTerminal(const Color& color, const Color& background_color); 55 | template ColorTerminal::ColorTerminal(const Color& color, const Color& background_color); 56 | 57 | template 58 | void ColorTerminal::Reset() 59 | { 60 | struct winsize windowSize; 61 | ioctl(STDOUT_FILENO, TIOCGWINSZ, &windowSize); 62 | NumberOfRows = windowSize.ws_row; 63 | NumberOfColumns = windowSize.ws_col; 64 | 65 | ScreenBuffer = std::vector(static_cast(NumberOfColumns*NumberOfRows), 66 | TCharType()); 67 | } 68 | 69 | template 70 | void ColorTerminal::Draw(unsigned x, unsigned y, const char *mchar, int colorShade) 71 | { 72 | // Assumes that x and y are in bounds 73 | ScreenBuffer[y*NumberOfColumns + x].SetFullMChar(mchar, colorShade); 74 | } 75 | 76 | template 77 | void ColorTerminal::Erase(unsigned x, unsigned y) 78 | { 79 | if (x > NumberOfColumns-1 || y > NumberOfRows-1) { 80 | return; 81 | } 82 | 83 | ScreenBuffer[y*NumberOfColumns + x].Clear(); 84 | } 85 | 86 | template 87 | void ColorTerminal::DrawTitle(unsigned x, unsigned y, wchar_t tchar) 88 | { 89 | // Assumes that x and y are in bounds 90 | ScreenBuffer[y*NumberOfColumns + x].SetFullTitleChar(tchar); 91 | } 92 | 93 | template 94 | void ColorTerminal::Flush() 95 | { 96 | std::cout.write(reinterpret_cast(ScreenBuffer.data()), 97 | static_cast(ScreenBuffer.size() * sizeof(TCharType))); 98 | std::cout << std::flush; 99 | // Move cursor to the start of the screen 100 | std::cout << "\033[0;0H"; 101 | } 102 | -------------------------------------------------------------------------------- /src/TerminalChar.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include "TerminalChar.h" 12 | 13 | template <> 14 | const char *BaseTerminalChar::GLOWING_COLOR_ESC_SEQ {Color::GetColor("white").Shade1}; 15 | template <> 16 | const char *BaseTerminalChar::NORMAL_COLOR_ESC_SEQ {nullptr}; 17 | template <> 18 | const char *BaseTerminalChar::GLOWING_COLOR_ESC_SEQ {Color::GetColor("white").Foreground}; 19 | template <> 20 | const char *BaseTerminalChar::NORMAL_COLOR_ESC_SEQ {nullptr}; 21 | 22 | const char *TerminalChar::NORMAL_COLOR_ESC_SEQ_2 {nullptr}; 23 | const char *TerminalChar::NORMAL_COLOR_ESC_SEQ_3 {nullptr}; 24 | const char *TerminalChar::NORMAL_COLOR_ESC_SEQ_4 {nullptr}; 25 | 26 | template 27 | void BaseTerminalChar::Clear() 28 | { 29 | std::memcpy(&prefix, NORMAL_COLOR_ESC_SEQ, PREFIX_SIZE); 30 | std::memcpy(&MChar, MatrixChar::GetEmptyMChar(), MatrixChar::MCHAR_SIZE); 31 | } 32 | // Instantiate both versions of the Clear() 33 | template void BaseTerminalChar::Clear(); 34 | template void BaseTerminalChar::Clear(); 35 | 36 | template 37 | void BaseTerminalChar::SetFullTitleChar(wchar_t tchar) 38 | { 39 | std::memcpy(&prefix, GLOWING_COLOR_ESC_SEQ, PREFIX_SIZE); 40 | std::memset(&MChar, '\0', MatrixChar::MCHAR_SIZE); 41 | 42 | // Convert wchar to (const char *) 43 | std::string tchar_buffer(MB_CUR_MAX, '\0'); 44 | int tchar_size = std::wctomb(&tchar_buffer[0], tchar); 45 | if (tchar_size > 0) { 46 | std::memcpy(&MChar, tchar_buffer.data(), 47 | std::min(static_cast(tchar_size), 48 | MatrixChar::MCHAR_SIZE)); 49 | } 50 | } 51 | // Instantiate both versions of the SetFullTitleChar() 52 | template void BaseTerminalChar::SetFullTitleChar(wchar_t tchar); 53 | template void BaseTerminalChar::SetFullTitleChar(wchar_t tchar); 54 | 55 | void TerminalChar::SetColor(const Color& color) 56 | { 57 | NORMAL_COLOR_ESC_SEQ = color.Shade1; 58 | NORMAL_COLOR_ESC_SEQ_2 = color.Shade2; 59 | NORMAL_COLOR_ESC_SEQ_3 = color.Shade3; 60 | NORMAL_COLOR_ESC_SEQ_4 = color.Shade4; 61 | } 62 | 63 | void TerminalChar::SetFullMChar(const char *mchar, int colorShade) 64 | { 65 | switch (colorShade) { 66 | case 0: 67 | std::memcpy(&prefix, GLOWING_COLOR_ESC_SEQ, PREFIX_SIZE); 68 | break; 69 | case 1: 70 | default: 71 | std::memcpy(&prefix, NORMAL_COLOR_ESC_SEQ, PREFIX_SIZE); 72 | break; 73 | case 2: 74 | std::memcpy(&prefix, NORMAL_COLOR_ESC_SEQ_2, PREFIX_SIZE); 75 | break; 76 | case 3: 77 | std::memcpy(&prefix, NORMAL_COLOR_ESC_SEQ_3, PREFIX_SIZE); 78 | break; 79 | case 4: 80 | std::memcpy(&prefix, NORMAL_COLOR_ESC_SEQ_4, PREFIX_SIZE); 81 | break; 82 | } 83 | std::memcpy(&MChar, mchar, MatrixChar::MCHAR_SIZE); 84 | } 85 | 86 | void TerminalChar::SetColor(const Color& color) 87 | { 88 | GLOWING_COLOR_ESC_SEQ = Color::GetColor("white").Foreground; 89 | NORMAL_COLOR_ESC_SEQ = color.Foreground; 90 | } 91 | 92 | void TerminalChar::SetFullMChar(const char *mchar, int colorShade) 93 | { 94 | switch (colorShade) { 95 | case 0: 96 | std::memcpy(&prefix, GLOWING_COLOR_ESC_SEQ, PREFIX_SIZE); 97 | break; 98 | case 1: 99 | default: 100 | std::memcpy(&prefix, NORMAL_COLOR_ESC_SEQ, PREFIX_SIZE); 101 | break; 102 | } 103 | std::memcpy(&MChar, mchar, MatrixChar::MCHAR_SIZE); 104 | } 105 | -------------------------------------------------------------------------------- /src/tmatrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2023 Miloš Stojanović 3 | * 4 | * SPDX-License-Identifier: GPL-2.0-only 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include "Parser.h" 17 | #include "Rain.h" 18 | #include "Terminal.h" 19 | #include "tmatrix.h" 20 | 21 | using namespace std::chrono_literals; 22 | 23 | static std::atomic resizeTriggered {false}; 24 | static std::condition_variable renderingConditionVariable; 25 | static std::mutex mutexOfRenderingConditionVariable; 26 | 27 | [[noreturn]] static void render(const RainProperties &rainProperties) 28 | { 29 | Color color = rainProperties.CharacterColor; 30 | Color background_color = rainProperties.BackgroundColor; 31 | std::shared_ptr terminal { 32 | rainProperties.Fade 33 | ? std::static_pointer_cast( 34 | std::make_shared>(color, background_color)) 35 | : std::static_pointer_cast( 36 | std::make_shared>(color, background_color)) 37 | }; 38 | 39 | std::shared_ptr rain { 40 | rainProperties.Fade 41 | ? std::static_pointer_cast( 42 | std::make_shared(rainProperties, terminal.get())) 43 | : std::static_pointer_cast( 44 | std::make_shared(rainProperties, terminal.get())) 45 | }; 46 | std::unique_lock mutexLock(mutexOfRenderingConditionVariable); 47 | while (true) { 48 | renderingConditionVariable.wait(mutexLock); 49 | if (resizeTriggered.exchange(false)) { 50 | terminal->Reset(); 51 | rain->Reset(); 52 | rain->Update(); 53 | } 54 | terminal->Flush(); 55 | rain->Update(); 56 | } 57 | } 58 | 59 | int main(int argc, char *argv[]) 60 | { 61 | int stepsPerSecond {DEFAULT_STEPS_PER_SECOND}; 62 | RainProperties rainProperties; 63 | std::wstring title; 64 | 65 | if (Parser::ParseCmdLineArgs(std::vector(argv+1, argv+argc), 66 | {stepsPerSecond, rainProperties, title})) { 67 | std::signal(SIGWINCH, [](int) { resizeTriggered.store(true); }); 68 | 69 | std::thread rendering_thread([&]{ render(rainProperties); }); 70 | 71 | bool paused {false}; 72 | std::unique_lock mutexLock(mutexOfRenderingConditionVariable); 73 | while (true) { 74 | Parser::ParseRuntimeInput(static_cast(getch()), paused); 75 | mutexLock.unlock(); 76 | if (!paused) { 77 | renderingConditionVariable.notify_one(); 78 | } 79 | std::this_thread::sleep_for(1.0s/stepsPerSecond); 80 | mutexLock.lock(); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /tmatrix.6: -------------------------------------------------------------------------------- 1 | .TH TMatrix 6 "10 June 2023" "TMatrix Version 1.4" 2 | .SH NAME 3 | TMatrix \- Terminal based replica of the digital rain from The Matrix 4 | .SH SYNOPSIS 5 | .nf 6 | \fItmatrix\fR [--version] [--help] [--mode=MODE] 7 | [-s VALUE | --steps-per-sec=VALUE] 8 | [-f RANGE | --fall-speed=RANGE] [-G RANGE | --start-gap=RANGE] 9 | [-g RANGE | --gap=RANGE] [-l RANGE] [-r RANGE] [--fade] 10 | [--no-fade] [-C COLOR | --color=COLOR] 11 | [-c COLOR | --background=COLOR] [-t TEXT | --title=TEXT] 12 | .fi 13 | .SH DESCRIPTION 14 | Simulates the digital rain effect from The Matrix. 15 | .SH OPTIONS 16 | .TP 4 17 | \-\-version 18 | Output version information and exit. 19 | .TP 4 20 | \-\-help 21 | Display this help and exit. 22 | .TP 4 23 | \-\-mode=MODE 24 | Set the mode of the rain. 25 | .br 26 | Available modes: \fBdefault\fR, \fBdense\fR. 27 | .TP 4 28 | \-s, \-\-steps-per-sec=VALUE 29 | Run this many steps per second. 30 | .br 31 | VALUE can range from \fB1\fR to \fB60\fR. 32 | .br 33 | Default: \fI10\fR. 34 | .TP 4 35 | \-f, --fall-speed=RANGE 36 | Set the range for the fall speed. 37 | .br 38 | The speeds can have \fBdecimal parts\fR (e.g. \fB1.2\fR) with increment of \fB0.1\fR. 39 | .br 40 | The maximal fall speed value is \fB10.0\fR. 41 | .br 42 | Default: \fI0.5,1.5\fR. 43 | .TP 4 44 | \-G, --start-gap=RANGE 45 | Set the range for the starting gaps. 46 | .br 47 | Default: \fI10,50\fR. 48 | .TP 4 49 | \-g, --gap=RANGE 50 | Set the range for the gaps between streaks. 51 | .br 52 | Default: \fI0,40\fR. 53 | .TP 4 54 | \-l RANGE 55 | Set the range for the length of rain streaks. 56 | .br 57 | The minimal length value is \fB1\fR. 58 | .br 59 | Default: \fI1,30\fR. 60 | .TP 4 61 | \-r RANGE 62 | Set the range for the character update rate. 63 | .br 64 | The values correspond to the number of steps before the change. 65 | .br 66 | \fB0\fR represents no change. 67 | .br 68 | Default: \fI10,20\fR. 69 | .TP 4 70 | \-\-fade 71 | Enable fading characters. (Default) 72 | .TP 4 73 | \-\-no\-fade 74 | Disable fading characters. 75 | .TP 4 76 | \-C, --color=COLOR 77 | Set the color of the characters. 78 | .br 79 | Available colors: \fBdefault\fR, \fBwhite\fR, \fBgray\fR, \fBblack\fR, \fBred\fR, \fBgreen\fR, 80 | .br 81 | \fByellow\fR, \fBblue\fR, \fBmagenta\fR, \fBcyan\fR. 82 | .br 83 | Default: \fIgreen\fR. 84 | .TP 4 85 | \-c, --background=COLOR 86 | Set the color of the background. 87 | .br 88 | Available colors: \fBdefault\fR, \fBwhite\fR, \fBgray\fR, \fBblack\fR, \fBred\fR, \fBgreen\fR, 89 | .br 90 | \fByellow\fR, \fBblue\fR, \fBmagenta\fR, \fBcyan\fR. 91 | .TP 4 92 | \-t, --title=TEXT 93 | Set the title that appears in the rain. 94 | .br 95 | \fINote\fR: the title needs to fit within the terminal window 96 | .br 97 | in order to be displayed. 98 | .PP 99 | RANGE is a pair of numbers separated by a comma: MIN,MAX. 100 | .br 101 | It specifies the boundaries of a set from which random numbers are picked. 102 | .SH Real-time commands 103 | .TP 4 104 | p 105 | Pause 106 | .TP 4 107 | q 108 | Quit 109 | .SH AUTHORS 110 | Written by Miloš Stojanović 111 | .SH LICENSE 112 | Copyright (C) 2018-2023 Miloš Stojanović 113 | .br 114 | SPDX-License-Identifier: GPL-2.0-only 115 | .SH SEE ALSO 116 | .BR cmatrix (1) 117 | --------------------------------------------------------------------------------