├── .env.dist ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── air.toml ├── assets ├── .gitkeep ├── fonts │ └── FreeSans.ttf └── grf │ ├── corrupted.grf │ ├── custom.grf │ ├── incorrect-version.grf │ ├── not-grf.grf │ └── with-files.grf ├── cmd ├── grfexplorer │ ├── main.go │ └── main2.go └── sdlclient │ └── main.go ├── examples └── 3d │ ├── bindata.go │ ├── main.go │ └── renderer │ └── sprite.go ├── go.mod ├── go.sum ├── internal ├── bytesutil │ └── bytes.go ├── camera │ └── camera.go ├── char │ ├── accessory.go │ └── sprite.go ├── character │ ├── actionindex │ │ └── actionindex.go │ ├── actionplaymode │ │ └── actionindex.go │ ├── attachments.go │ ├── character.go │ ├── directiontype │ │ └── statetype.go │ ├── gender.go │ ├── jobid │ │ └── jobid.go │ ├── jobsprite.go │ ├── jobspriteid │ │ └── jobspriteid.go │ └── statetype │ │ └── statetype.go ├── component │ ├── character_attachment_component.go │ ├── character_sprite_render_info_component.go │ └── character_state_component.go ├── entity │ └── character.go ├── fileformat │ ├── act │ │ └── act_file.go │ ├── gat │ │ └── gat_file.go │ ├── gnd │ │ └── gnd_file.go │ ├── grf │ │ ├── des │ │ │ └── des.go │ │ ├── grf_entry.go │ │ ├── grf_entry_tree.go │ │ ├── grf_file.go │ │ ├── grf_test.go │ │ └── zlib.go │ └── spr │ │ ├── spr_file.go │ │ └── spr_file_test.go ├── graphic │ ├── caching │ │ └── texture.go │ ├── geometry.go │ ├── geometry │ │ └── plane.go │ ├── graphic.go │ ├── renderable.go │ ├── rgba.go │ ├── texture.go │ └── transform.go ├── grfexplorer │ └── grfexplorer.go ├── opengl │ ├── opengl.go │ ├── program.go │ ├── state.go │ └── vbo.go ├── romap │ └── map.go ├── system │ ├── character_action_system.go │ ├── character_render.go │ └── opengl │ │ ├── render_command.go │ │ ├── render_system.go │ │ └── shaders │ │ ├── box.frag │ │ ├── box.vert │ │ ├── sprite.frag │ │ └── sprite.vert └── window │ └── keystate.go └── pkg ├── graphics ├── renderer │ ├── shaders │ │ ├── sprite.frag │ │ └── sprite.vert │ └── sprite_renderer.go └── shader.go └── version └── version.go /.env.dist: -------------------------------------------------------------------------------- 1 | GRF_FILE_PATH=/path/to/data.grf -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .env 2 | .DS_Store 3 | tmp 4 | bin 5 | 6 | assets/grf/ 7 | assets/out/ 8 | assets/build/ 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Output directory for binaries 2 | BIN_DIR := ./bin 3 | 4 | # Source directories and target binaries 5 | SRC_SDLCLIENT := cmd/sdlclient/main.go 6 | TARGET_SDLCLIENT := $(BIN_DIR)/midgarts 7 | 8 | SRC_GRFEXPLORER := cmd/grfexplorer/main.go 9 | TARGET_GRFEXPLORER := $(BIN_DIR)/grfexplorer 10 | 11 | # ==================================================================================== # 12 | # HELPERS 13 | # ==================================================================================== # 14 | 15 | ## help: print this help message 16 | .PHONY: help 17 | help: 18 | @echo 'Usage:' 19 | @sed -n 's/^##//p' ${MAKEFILE_LIST} | column -t -s ':' | sed -e 's/^/ /' 20 | 21 | # ==================================================================================== # 22 | # BUILD 23 | # ==================================================================================== # 24 | 25 | ## all: builds all binaries 26 | .PHONY: all 27 | all: build build-grfexplorer 28 | 29 | ## build: builds sdlclient 30 | build: 31 | @mkdir -p $(BIN_DIR) 32 | go build -o $(TARGET_SDLCLIENT) $(SRC_SDLCLIENT) 33 | 34 | ## build-grfexplorer: builds grfexplorer 35 | build-grfexplorer: 36 | @mkdir -p $(BIN_DIR) 37 | go build -o $(TARGET_GRFEXPLORER) $(SRC_GRFEXPLORER) 38 | 39 | # ==================================================================================== # 40 | # DEVELOPMENT 41 | # ==================================================================================== # 42 | 43 | ## run: run the cmd/web application 44 | .PHONY: run 45 | run: 46 | go run github.com/cosmtrek/air@v1.40.4 --c="./air.toml" 47 | 48 | 49 | # ==================================================================================== # 50 | # QUALITY CONTROL 51 | # ==================================================================================== # 52 | 53 | ## tidy: format code and tidy modfile 54 | .PHONY: tidy 55 | tidy: 56 | go fmt ./... 57 | go mod tidy -v 58 | 59 | ## audit: run quality control checks 60 | .PHONY: audit 61 | audit: 62 | go vet ./... 63 | go run honnef.co/go/tools/cmd/staticcheck@latest -checks=all,-ST1000,-U1000 ./... 64 | go test -race -vet=off ./... 65 | go mod verify 66 | 67 | ## test: run tests 68 | .PHONY: test 69 | test: 70 | go test -race -vet=off ./... 71 | 72 | ## clean: clean binaries 73 | .PHONY: clean 74 | clean: 75 | @rm -rf $(BIN_DIR) 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Midgarts Client 3 | 4 | Welcome to the **Midgarts Client**, a graphical client primarily built using SDL2, OpenGL, and various custom and third-party libraries. The project is designed to create an interactive and visually appealing environment for manipulating and rendering game characters and actions. The application showcases entities, systems, and OpenGL integration for real-time character movement and rendering. 5 | 6 | Current Screenshots: 7 | 8 |

9 | 10 | 11 |

12 |

13 | 14 | 15 |

16 | 17 | --- 18 | 19 | ## Table of Contents 20 | 21 | - [Project Overview](#project-overview) 22 | - [Features](#features) 23 | - [Requirements](#requirements) 24 | - [Setup](#setup) 25 | - [Usage](#usage) 26 | - [Folder Structure](#folder-structure) 27 | - [License](#license) 28 | 29 | --- 30 | 31 | ## Project Overview 32 | 33 | The Midgarts Client uses the **Entity-Component-System (ECS)** architecture to manage game objects and their interactions. It focuses on simulating a modeled game environment, rendering scene objects (like characters), and controlling game entities. 34 | 35 | The main goals include: 36 | - Configuring characters with properties like job sprites, direction, position, and states. 37 | - Using **OpenGL** for rendering. 38 | - SDL2 for window and event management. 39 | - Integration with GRF file format for asset loading. 40 | 41 | --- 42 | 43 | ## Features 44 | 45 | 1. **Character Creation and Rendering**: 46 | - Multiple characters with configurable sprites, positions, and states. 47 | - Supports movement and states like "Standing" and "Walking". 48 | 49 | 2. **OpenGL Integration**: 50 | - Real-time rendering of characters using a perspective camera. 51 | - Efficient use of OpenGL viewport settings and caching. 52 | 53 | 3. **Keyboard and Mouse Controls**: 54 | - Move characters using `W`, `A`, `S`, `D` keys. 55 | - Adjust camera position using `Z`, `X`, `C`, `V` keys. 56 | - Mouse-click-based direction control. 57 | 58 | 4. **Game Assets from GRF Files**: 59 | - Reads sprite data and configuration files from `.grf` file systems. 60 | 61 | 5. **Modular Architecture with ECS**: 62 | - Encapsulation of rendering and action logic into systems. 63 | - Seamless addition/removal of entities or other systems. 64 | 65 | 6. **Logging and Debugging**: 66 | - Uses [zerolog](https://github.com/rs/zerolog) for structured logging. 67 | - Debug output including input states and errors. 68 | 69 | --- 70 | 71 | ## Requirements 72 | 73 | To build and run the Midgarts Client, the following dependencies must be installed: 74 | 75 | - **Go SDK 1.21 or later** 76 | - **Libraries**: 77 | - [Engo ECS](https://github.com/EngoEngine/ecs): Entity-Component-System architecture. 78 | - [SDL2](https://github.com/veandco/go-sdl2): SDL2 bindings for Go (For windowing and events). 79 | - [OpenGL](https://github.com/go-gl/gl): OpenGL bindings for Go. 80 | - [MathGL](https://github.com/go-gl/mathgl): Vector and matrix operations. 81 | - [Godotenv](https://github.com/joho/godotenv): Automatic `.env` file loading. 82 | - [GRF](https://github.com/project-midgard/midgarts/internal/fileformat/grf): Custom library for `.grf` files. 83 | - [Zerolog](https://github.com/rs/zerolog): Structured and fast logging. 84 | 85 | --- 86 | 87 | ## Setup 88 | 89 | ### Step 1: Clone the Repository 90 | 91 | ```sh 92 | git clone 93 | cd midgarts-client 94 | ``` 95 | 96 | ### Step 2: Install Dependencies 97 | 98 | Use Go to download all the required modules: 99 | 100 | ```sh 101 | go mod tidy 102 | ``` 103 | 104 | ### Step 3: Set Environment Variables 105 | 106 | The application requires the `.env` file or environmental variable `GRF_FILE_PATH` to locate required assets: 107 | 108 | ```env 109 | GRF_FILE_PATH=/path/to/your/grf/file 110 | ``` 111 | 112 | ### Step 4: Run the Application 113 | 114 | After setting up everything, simply run: 115 | 116 | ```sh 117 | go run main.go 118 | ``` 119 | 120 | --- 121 | 122 | ## Usage 123 | 124 | ### Controls 125 | 126 | #### **Character Movement** 127 | | Action | Input | 128 | |-----------------------------|---------------------------------------------| 129 | | Move Up | `W` | 130 | | Move Down | `S` | 131 | | Move Left | `A` | 132 | | Move Right | `D` | 133 | | Diagonal Movement | `W+D`, `W+A`, `S+D`, `S+A` | 134 | 135 | #### **Character Direction via Mouse** 136 | | Action | Input | 137 | |--------------------------------------|--------------------------------| 138 | | Set Direction (Mouse Click) | Top-left, Bottom-left, etc. in respective viewport | 139 | 140 | #### **Camera Controls** 141 | | Action | Input | 142 | |--------------------------|----------| 143 | | Move Camera Backward | `Z` | 144 | | Move Camera Forward | `X` | 145 | | Move Camera Left | `C` | 146 | | Move Camera Right | `V` | 147 | 148 | --- 149 | 150 | ## Folder Structure 151 | 152 | The following are some key directories in the project: 153 | 154 | - **`internal/camera`**: Perspective camera logic. 155 | - **`internal/character`**: Character properties (direction, state, jobs, etc.). 156 | - **`internal/entity`**: Definitions for character entities. 157 | - **`internal/system`**: Systems for action handling and rendering logic. 158 | - **`internal/window`**: SDL2-based window utilities. 159 | - **`pkg/version`**: Application version management. 160 | 161 | --- 162 | 163 | ## License 164 | 165 | This project is licensed under the MIT License. For more details, refer to the `LICENSE` file. 166 | 167 | --- 168 | 169 | Enjoy building with the Midgarts Client! For contributions or bug reporting, please reach out via the project's issue tracker. 170 | -------------------------------------------------------------------------------- /air.toml: -------------------------------------------------------------------------------- 1 | root = "." 2 | testdata_dir = "testdata" 3 | tmp_dir = "tmp" 4 | 5 | [build] 6 | args_bin = [] 7 | bin = "./tmp/midgarts" 8 | cmd = "go build -ldflags='-s' -o=./tmp/midgarts ./cmd/sdlclient" 9 | delay = 0 10 | exclude_dir = ["bin", "tmp"] 11 | exclude_file = [] 12 | exclude_regex = ["_test.go"] 13 | exclude_unchanged = false 14 | follow_symlink = false 15 | full_bin = "" 16 | include_dir = [] 17 | include_ext = ["go", "frag"] 18 | include_file = [] 19 | kill_delay = "0s" 20 | log = "build-errors.log" 21 | rerun = false 22 | rerun_delay = 500 23 | send_interrupt = false 24 | stop_on_error = false 25 | 26 | [color] 27 | app = "" 28 | build = "yellow" 29 | main = "magenta" 30 | runner = "green" 31 | watcher = "cyan" 32 | 33 | [log] 34 | main_only = false 35 | time = false 36 | 37 | [misc] 38 | clean_on_exit = true 39 | 40 | [screen] 41 | clear_on_rebuild = false 42 | keep_scroll = true 43 | -------------------------------------------------------------------------------- /assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drgomesp/midgarts/62a3098d296522b5758c244daead59a8a866c463/assets/.gitkeep -------------------------------------------------------------------------------- /assets/fonts/FreeSans.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drgomesp/midgarts/62a3098d296522b5758c244daead59a8a866c463/assets/fonts/FreeSans.ttf -------------------------------------------------------------------------------- /assets/grf/corrupted.grf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drgomesp/midgarts/62a3098d296522b5758c244daead59a8a866c463/assets/grf/corrupted.grf -------------------------------------------------------------------------------- /assets/grf/custom.grf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drgomesp/midgarts/62a3098d296522b5758c244daead59a8a866c463/assets/grf/custom.grf -------------------------------------------------------------------------------- /assets/grf/incorrect-version.grf: -------------------------------------------------------------------------------- 1 | Master of Magic -------------------------------------------------------------------------------- /assets/grf/not-grf.grf: -------------------------------------------------------------------------------- 1 | This is a text file disguise as grf to check file loading -------------------------------------------------------------------------------- /assets/grf/with-files.grf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drgomesp/midgarts/62a3098d296522b5758c244daead59a8a866c463/assets/grf/with-files.grf -------------------------------------------------------------------------------- /cmd/grfexplorer/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "strings" 7 | 8 | g "github.com/AllenDang/giu" 9 | "github.com/rs/zerolog" 10 | "github.com/rs/zerolog/log" 11 | "golang.org/x/text/encoding/charmap" 12 | 13 | "github.com/project-midgard/midgarts/internal/fileformat/act" 14 | "github.com/project-midgard/midgarts/internal/fileformat/grf" 15 | "github.com/project-midgard/midgarts/internal/fileformat/spr" 16 | ) 17 | 18 | var grfFile *grf.File 19 | var imageWidget = &g.ImageWidget{} 20 | var fileInfoWidget g.Widget 21 | var loadedImageName string 22 | var currentEntry *grf.Entry 23 | 24 | func init() { 25 | zerolog.SetGlobalLevel(zerolog.TraceLevel) 26 | log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) 27 | 28 | var err error 29 | grfFile, err = grf.Load("./assets/grf/data.grf") 30 | noErr(err) 31 | 32 | } 33 | 34 | func main() { 35 | wnd := g.NewMasterWindow("Hello world", 640, 480, 0, nil) 36 | wnd.Run(Run) 37 | } 38 | 39 | func Run() { 40 | g.SingleWindowWithMenuBar("splitter").Layout( 41 | g.MenuBar().Layout( 42 | g.Menu("File").Layout( 43 | g.MenuItem("Open"), 44 | g.MenuItem("Save"), 45 | // You could add any kind of widget here, not just menu item. 46 | g.Menu("Save as ...").Layout( 47 | g.MenuItem("Excel file"), 48 | g.MenuItem("CSV file"), 49 | g.Button("Button inside menu"), 50 | ), 51 | ), 52 | ), 53 | g.SplitLayout("Split", g.DirectionHorizontal, true, 300, 54 | buildEntryTreeNodes(), 55 | g.Layout{ 56 | fileInfoWidget, 57 | imageWidget, 58 | //g.SliderInt("SliderInt", &imageScaleMultiplier, 1, 4), 59 | g.Custom(func() { 60 | if g.IsItemActive() { 61 | loadImage(loadedImageName) 62 | } 63 | }), 64 | }, 65 | ), 66 | ) 67 | } 68 | 69 | func onClickEntry(entryName string) { 70 | if strings.Contains(entryName, ".act") { 71 | var err error 72 | if currentEntry, err = grfFile.GetEntry(entryName); err != nil { 73 | panic("kurwa!") 74 | } 75 | 76 | actFile, err := act.Load(currentEntry.Data) 77 | log.Printf("actFile = %+v\n", actFile) 78 | } 79 | 80 | if strings.Contains(entryName, ".spr") { 81 | var err error 82 | if currentEntry, err = grfFile.GetEntry(entryName); err != nil { 83 | panic("kurwa!") 84 | } 85 | 86 | loadImage(entryName) 87 | loadFileInfo() 88 | } 89 | } 90 | 91 | func loadFileInfo() { 92 | sprFile, _ := spr.Load(currentEntry.Data) 93 | 94 | fileInfoWidget = g.Layout{ 95 | g.Line( 96 | g.Group().Layout( 97 | g.Label("File Info"), 98 | g.Table("Table"). 99 | Columns( 100 | g.Column(""), 101 | g.Column(""), 102 | ). 103 | Rows( 104 | g.Row(g.Label("Width").Wrapped(true), g.Label(fmt.Sprintf("%d", sprFile.Frames[0].Width))), 105 | g.Row(g.Label("Height").Wrapped(true), g.Label(fmt.Sprintf("%d", sprFile.Frames[0].Height))), 106 | ), 107 | ), 108 | ), 109 | } 110 | } 111 | 112 | func getDecodedFolder(buf []byte) (string, error) { 113 | folderNameBytes, err := charmap.Windows1252.NewDecoder().Bytes(buf) 114 | return string(folderNameBytes), err 115 | } 116 | 117 | func buildEntryTreeNodes() g.Layout { 118 | entries := grfFile.GetEntryTree() 119 | 120 | var nodes []interface{} 121 | 122 | entries.Traverse(entries.Root, func(n *grf.EntryTreeNode) { 123 | selectableNodes := make([]g.Widget, 0) 124 | nodeEntries := make([]interface{}, 0) 125 | //body_file_path=data/sprite/Àΰ£Á·/¸öÅë/³²/Á¦Ã¶°ø_³² 126 | 127 | decodedFolderA, err := getDecodedFolder([]byte{0xC0, 0xCE, 0xB0, 0xA3, 0xC1, 0xB7}) 128 | if err != nil { 129 | panic(err) 130 | } 131 | 132 | _ = decodedFolderA 133 | if strings.Contains(n.Value, "data/sprite") { 134 | for _, e := range grfFile.GetEntries(n.Value) { 135 | if strings.Contains(e.Name, ".spr") { 136 | nodeEntries = append(nodeEntries, e.Name) 137 | } 138 | } 139 | 140 | var decodedDirName []byte 141 | var err error 142 | if decodedDirName, err = charmap.Windows1252.NewDecoder().Bytes([]byte(n.Value)); err != nil { 143 | panic(err) 144 | } 145 | 146 | if len(nodeEntries) > 0 { 147 | node := g.TreeNode(fmt.Sprintf("%s (%d)", decodedDirName, len(nodeEntries))) 148 | selectableNodes = g.RangeBuilder("selectableNodes", nodeEntries, func(i int, v interface{}) g.Widget { 149 | var decodedStr string 150 | var err error 151 | if decodedStr, err = charmap.Windows1252.NewDecoder().String(v.(string)); err != nil { 152 | panic(err) 153 | } 154 | 155 | return g.Selectable(decodedStr).OnClick(func() { 156 | onClickEntry(v.(string)) 157 | }) 158 | }) 159 | 160 | node.Layout(selectableNodes...) 161 | nodes = append(nodes, node) 162 | } 163 | } 164 | }) 165 | 166 | tree := g.RangeBuilder("entries", nodes, func(i int, v interface{}) g.Widget { 167 | return v.(g.Widget) 168 | }) 169 | 170 | return g.Layout{tree} 171 | } 172 | 173 | //func buildEntryTreeNodes() g.Layout { 174 | //if grfFile == nil { 175 | // return g.Layout{} 176 | //} 177 | // 178 | //var nodes []interface{} 179 | //grfFile.GetEntryTree().Traverse(grfFile.GetEntryTree().Root, func(n *grf.EntryTreeNode) { 180 | // selectableNodes := make([]g.Widget, 0) 181 | // var nodeEntries []interface{} 182 | // 183 | // for _, e := range grfFile.GetEntries(n.Value) { 184 | // nodeEntries = append(nodeEntries, e.Name) 185 | // } 186 | // 187 | // var decodedDirName []byte 188 | // var err error 189 | // if decodedDirName, err = charmap.Windows1252.NewDecoder().Bytes([]byte(n.Value)); err != nil { 190 | // panic(err) 191 | // } 192 | // 193 | // node := g.TreeNode(fmt.Sprintf("%s (%d)", decodedDirName, len(nodeEntries))) 194 | // selectableNodes = g.RangeBuilder("selectableNodes", nodeEntries, func(i int, v interface{}) g.Widget { 195 | // var decodedStr string 196 | // var err error 197 | // if decodedStr, err = charmap.Windows1252.NewDecoder().String(v.(string)); err != nil { 198 | // panic(err) 199 | // } 200 | // 201 | // return g.Selectable(decodedStr).OnClick(func() { 202 | // onClickEntry(v.(string)) 203 | // }) 204 | // }) 205 | // 206 | // node.Layout(selectableNodes...) 207 | // nodes = append(nodes, node) 208 | //}) 209 | // 210 | //tree := g.RangeBuilder("entries", nodes, func(i int, v interface{}) g.Widget { 211 | // return v.(g.Widget) 212 | //}) 213 | // 214 | //return g.Layout{tree} 215 | //} 216 | 217 | var spriteTexture *g.Texture 218 | 219 | func loadImage(name string) *g.Texture { 220 | if grfFile == nil { 221 | return nil 222 | } 223 | 224 | sprFile, _ := spr.Load(currentEntry.Data) 225 | img := sprFile.ImageAt(0) 226 | //mul := int(imageScaleMultiplier) 227 | //img = transform.Resize(img, img.Bounds().Max.X*mul, img.Bounds().Max.Y*mul, transform.Linear) 228 | 229 | go func() { 230 | spriteTexture, _ = g.NewTextureFromRgba(img.RGBA) 231 | imageWidget = g.Image(spriteTexture).Size(float32(img.Bounds().Max.X), float32(img.Bounds().Max.Y)) 232 | loadedImageName = name 233 | }() 234 | 235 | return nil 236 | } 237 | 238 | func noErr(err error) bool { 239 | if err != nil { 240 | log.Fatal().Err(err).Send() 241 | } 242 | 243 | return true 244 | } 245 | -------------------------------------------------------------------------------- /cmd/grfexplorer/main2.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // 4 | //import ( 5 | // "os" 6 | // 7 | // g "github.com/AllenDang/giu" 8 | // "github.com/rs/zerolog" 9 | // "github.com/rs/zerolog/log" 10 | // 11 | // "github.com/project-midgard/midgarts/internal/character" 12 | // "github.com/project-midgard/midgarts/internal/character/jobspriteid" 13 | // "github.com/project-midgard/midgarts/internal/fileformat/grf" 14 | // "github.com/project-midgard/midgarts/pkg/char" 15 | //) 16 | // 17 | //var GRF *grf.File 18 | // 19 | //var WidgetChar g.Widget 20 | //var SpriteLoader *char.SpriteLoader 21 | //var SpriteCache map[character.GenderType]map[jobspriteid.Type]map[character.HeadIndex]*char.Sprite 22 | // 23 | //func init() { 24 | // zerolog.SetGlobalLevel(zerolog.TraceLevel) 25 | // log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) 26 | // 27 | // var err error 28 | // GRF, err = grf.Load("./assets/grf/data.grf") 29 | // noErr(err) 30 | // 31 | // SpriteLoader = char.NewSpriteLoader(GRF) 32 | // SpriteCache = make(map[character.GenderType]map[jobspriteid.Type]map[character.HeadIndex]*char.Sprite) 33 | //} 34 | // 35 | //func main() { 36 | // wnd := g.NewMasterWindow("Hello world", 640, 480, 0, nil) 37 | // wnd.Run(Run) 38 | //} 39 | // 40 | //func Run() { 41 | // go func() { 42 | // var err error 43 | // var sprite *char.Sprite 44 | // 45 | // if found, exists := SpriteCache[character.Female][jobspriteid.Blacksmith][23]; exists { 46 | // sprite = found 47 | // } else { 48 | // sprite, err = SpriteLoader.LoadSprite( 49 | // character.Female, 50 | // jobspriteid.Blacksmith, 51 | // 23, 52 | // 0, 53 | // ) 54 | // 55 | // if noErr(err) { 56 | // SpriteCache[character.Female] = make(map[jobspriteid.Type]map[character.HeadIndex]*char.Sprite, 0) 57 | // SpriteCache[character.Female][jobspriteid.Blacksmith] = make(map[character.HeadIndex]*char.Sprite, 0) 58 | // SpriteCache[character.Female][jobspriteid.Blacksmith][23] = sprite 59 | // 60 | // var btex *g.Texture 61 | // btex, err = g.NewTextureFromRgba(sprite.Image) 62 | // noErr(err) 63 | // 64 | // bsize := sprite.Image.Rect.Size() 65 | // WidgetChar = g.Image(btex).Size(float32(bsize.X), float32(bsize.Y)) 66 | // } 67 | // } 68 | // }() 69 | // 70 | // g.SingleWindowWithMenuBar("splitter").Layout( 71 | // g.MenuBar().Layout( 72 | // g.Menu("File").Layout( 73 | // g.MenuItem("Open"), 74 | // g.MenuItem("Save"), 75 | // // You could add any kind of widget here, not just menu item. 76 | // g.Menu("Save as ...").Layout( 77 | // g.MenuItem("Excel file"), 78 | // g.MenuItem("CSV file"), 79 | // g.Button("Button inside menu"), 80 | // ), 81 | // ), 82 | // ), 83 | // WidgetChar, 84 | // ) 85 | //} 86 | // 87 | //func noErr(err error) bool { 88 | // if err != nil { 89 | // log.Fatal().Err(err).Send() 90 | // } 91 | // 92 | // return true 93 | //} 94 | -------------------------------------------------------------------------------- /cmd/sdlclient/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "time" 7 | 8 | "github.com/EngoEngine/ecs" 9 | "github.com/davecgh/go-spew/spew" 10 | "github.com/go-gl/gl/v3.2-core/gl" 11 | "github.com/go-gl/mathgl/mgl32" 12 | _ "github.com/joho/godotenv/autoload" 13 | "github.com/rs/zerolog" 14 | "github.com/rs/zerolog/log" 15 | "github.com/veandco/go-sdl2/sdl" 16 | 17 | "github.com/project-midgard/midgarts/internal/camera" 18 | "github.com/project-midgard/midgarts/internal/character" 19 | "github.com/project-midgard/midgarts/internal/character/directiontype" 20 | "github.com/project-midgard/midgarts/internal/character/jobspriteid" 21 | "github.com/project-midgard/midgarts/internal/character/statetype" 22 | "github.com/project-midgard/midgarts/internal/entity" 23 | "github.com/project-midgard/midgarts/internal/fileformat/gat" 24 | "github.com/project-midgard/midgarts/internal/fileformat/grf" 25 | "github.com/project-midgard/midgarts/internal/graphic/caching" 26 | "github.com/project-midgard/midgarts/internal/system" 27 | "github.com/project-midgard/midgarts/internal/system/opengl" 28 | "github.com/project-midgard/midgarts/internal/window" 29 | "github.com/project-midgard/midgarts/pkg/version" 30 | ) 31 | 32 | const ( 33 | WindowWidth = 960 34 | WindowHeight = 720 35 | AspectRatio = float32(WindowWidth) / float32(WindowHeight) 36 | FPS = 60 37 | ) 38 | 39 | var ( 40 | GrfFilePath = os.Getenv("GRF_FILE_PATH") 41 | ) 42 | 43 | func init() { 44 | zerolog.SetGlobalLevel(zerolog.TraceLevel) 45 | log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) 46 | } 47 | 48 | func main() { 49 | var err error 50 | if err = sdl.Init(sdl.INIT_EVERYTHING); err != nil { 51 | log.Fatal().Err(err).Msg("failed to load sdl") 52 | } 53 | defer sdl.Quit() 54 | 55 | desktop, err := sdl.GetDesktopDisplayMode(0) 56 | if err != nil { 57 | log.Fatal().Err(err).Msg("getting desktop display mode") 58 | } 59 | 60 | var win *sdl.Window 61 | if win, err = sdl.CreateWindow( 62 | fmt.Sprintf("Midgarts Client - %s", version.Get()), 63 | desktop.W-WindowWidth, 64 | 0, 65 | WindowWidth, 66 | WindowHeight, 67 | sdl.WINDOW_OPENGL, 68 | ); err != nil { 69 | panic(err) 70 | } 71 | defer func() { 72 | _ = win.Destroy() 73 | }() 74 | 75 | err = sdl.GLSetAttribute(sdl.GL_CONTEXT_MAJOR_VERSION, 3) 76 | if err != nil { 77 | panic(err) 78 | } 79 | 80 | err = sdl.GLSetAttribute(sdl.GL_CONTEXT_MINOR_VERSION, 2) 81 | if err != nil { 82 | panic(err) 83 | } 84 | 85 | err = sdl.GLSetAttribute(sdl.GL_CONTEXT_PROFILE_MASK, sdl.GL_CONTEXT_PROFILE_CORE) 86 | if err != nil { 87 | panic(err) 88 | } 89 | 90 | context, err := win.GLCreateContext() 91 | if err != nil { 92 | panic(err) 93 | } 94 | defer sdl.GLDeleteContext(context) 95 | 96 | if err := gl.Init(); err != nil { 97 | panic(err) 98 | } 99 | version := gl.GoStr(gl.GetString(gl.VERSION)) 100 | log.Info().Msgf("OpenGL version: %s", version) 101 | 102 | var grfFile *grf.File 103 | if grfFile, err = grf.Load(GrfFilePath); err != nil { 104 | log.Fatal().Err(err).Msg("failed to load grf file") 105 | } 106 | 107 | e, err := grfFile.GetEntry("data/izlude.gat") 108 | if err != nil { 109 | log.Fatal().Err(err).Msg("failed to get gat entry") 110 | } 111 | groundAltitude, err := gat.Load(e.Data) 112 | if err != nil { 113 | log.Fatal().Err(err).Msg("failed to load gat") 114 | } 115 | _ = groundAltitude 116 | 117 | gl.Viewport(0, 0, WindowWidth, WindowHeight) 118 | 119 | cam := camera.NewPerspectiveCamera(0.638, AspectRatio, 0.1, 1000.0) 120 | cam.ResetAngleAndY(WindowWidth, WindowHeight) 121 | 122 | ks := window.NewKeyState(win) 123 | 124 | w := ecs.World{} 125 | renderSys := system.NewCharacterRenderSystem(grfFile, caching.NewCachedTextureProvider()) 126 | actionSystem := system.NewCharacterActionSystem(grfFile) 127 | 128 | c1 := entity.NewCharacter(character.Male, jobspriteid.Knight, 23) 129 | c1.HasShield = true 130 | c2 := entity.NewCharacter(character.Male, jobspriteid.Knight, 22) 131 | c2.HasShield = true 132 | c3 := entity.NewCharacter(character.Male, jobspriteid.Swordsman, 14) 133 | c3.HasShield = true 134 | c4 := entity.NewCharacter(character.Female, jobspriteid.Alchemist, 16) 135 | c5 := entity.NewCharacter(character.Male, jobspriteid.Bard, 19) 136 | c6 := entity.NewCharacter(character.Female, jobspriteid.MonkH, 27) 137 | c7 := entity.NewCharacter(character.Male, jobspriteid.Crusader2, 30) 138 | c8 := entity.NewCharacter(character.Male, jobspriteid.Assassin, 17) 139 | c9 := entity.NewCharacter(character.Male, jobspriteid.Monk, 15) 140 | c10 := entity.NewCharacter(character.Female, jobspriteid.Wizard, 19) 141 | c11 := entity.NewCharacter(character.Female, jobspriteid.Sage, 4) 142 | c12 := entity.NewCharacter(character.Female, jobspriteid.Dancer, 16) 143 | 144 | c1.SetPosition(mgl32.Vec3{0, 44, -1}) 145 | c2.SetPosition(mgl32.Vec3{4, 44, 0}) 146 | c3.SetPosition(mgl32.Vec3{8, 44, 0}) 147 | c4.SetPosition(mgl32.Vec3{0, 40, 0}) 148 | c5.SetPosition(mgl32.Vec3{4, 40, 0}) 149 | c6.SetPosition(mgl32.Vec3{8, 40, 0}) 150 | c7.SetPosition(mgl32.Vec3{0, 36, 0}) 151 | c8.SetPosition(mgl32.Vec3{4, 36, 0}) 152 | c9.SetPosition(mgl32.Vec3{8, 36, 0}) 153 | c10.SetPosition(mgl32.Vec3{0, 32, 0}) 154 | c11.SetPosition(mgl32.Vec3{4, 32, 0}) 155 | c12.SetPosition(mgl32.Vec3{8, 32, 0}) 156 | 157 | var actionable *system.CharacterActionable 158 | var renderable *system.CharacterRenderable 159 | w.AddSystemInterface(actionSystem, actionable, nil) 160 | w.AddSystemInterface(renderSys, renderable, nil) 161 | w.AddSystem(opengl.NewOpenGLRenderSystem(cam, renderSys.RenderCommands)) 162 | 163 | w.AddEntity(c1) 164 | w.AddEntity(c2) 165 | w.AddEntity(c3) 166 | w.AddEntity(c4) 167 | w.AddEntity(c5) 168 | w.AddEntity(c6) 169 | w.AddEntity(c7) 170 | w.AddEntity(c8) 171 | w.AddEntity(c9) 172 | w.AddEntity(c10) 173 | w.AddEntity(c11) 174 | w.AddEntity(c12) 175 | 176 | c1.SetState(statetype.StandBy) 177 | 178 | shouldStop := false 179 | 180 | var refreshPeriod = time.Second / FPS 181 | 182 | for !shouldStop { 183 | frameStart := time.Now() 184 | for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() { 185 | switch eventType := event.(type) { 186 | case *sdl.QuitEvent: 187 | println("Quit") 188 | shouldStop = true 189 | break 190 | case *sdl.MouseButtonEvent: 191 | halfWidth := WindowWidth / 2 192 | halfHeight := WindowHeight / 2 193 | 194 | if eventType.Type == sdl.MOUSEBUTTONDOWN { 195 | if int(eventType.X) < halfWidth { 196 | if int(eventType.Y) < halfHeight { 197 | c1.Direction = directiontype.NorthWest 198 | } else if int(eventType.Y) > halfHeight { 199 | c1.Direction = directiontype.SouthWest 200 | } else { 201 | c1.Direction = directiontype.West 202 | } 203 | } 204 | 205 | if int(eventType.X) > halfWidth { 206 | if int(eventType.Y) < halfHeight { 207 | c1.Direction = directiontype.NorthEast 208 | } else if int(eventType.Y) > halfHeight { 209 | c1.Direction = directiontype.SouthEast 210 | } else { 211 | c1.Direction = directiontype.East 212 | } 213 | } 214 | 215 | spew.Dump(eventType) 216 | //} 217 | break 218 | } 219 | } 220 | 221 | ks.Update(event) 222 | } 223 | 224 | const MovementRate = float32(0.065) 225 | 226 | p1 := c1.Position() 227 | 228 | // char controls 229 | if ks.Pressed(sdl.K_w) && ks.Pressed(sdl.K_d) { 230 | c1.Direction = directiontype.NorthEast 231 | c1.SetState(statetype.Walking) 232 | c1.SetPosition(mgl32.Vec3{p1.X() - MovementRate, p1.Y() + MovementRate, p1.Z()}) 233 | } else if ks.Pressed(sdl.K_w) && ks.Pressed(sdl.K_a) { 234 | c1.Direction = directiontype.NorthWest 235 | c1.SetState(statetype.Walking) 236 | c1.SetPosition(mgl32.Vec3{p1.X() + MovementRate, p1.Y() + MovementRate, p1.Z()}) 237 | } else if ks.Pressed(sdl.K_s) && ks.Pressed(sdl.K_d) { 238 | c1.Direction = directiontype.SouthEast 239 | c1.SetState(statetype.Walking) 240 | c1.SetPosition(mgl32.Vec3{p1.X() - MovementRate, p1.Y() - MovementRate, p1.Z()}) 241 | } else if ks.Pressed(sdl.K_s) && ks.Pressed(sdl.K_a) { 242 | c1.Direction = directiontype.SouthWest 243 | c1.SetPosition(mgl32.Vec3{p1.X() + MovementRate, p1.Y() - MovementRate, p1.Z()}) 244 | c1.SetState(statetype.Walking) 245 | } else if ks.Pressed(sdl.K_w) { 246 | c1.Direction = directiontype.North 247 | c1.SetState(statetype.Walking) 248 | c1.SetPosition(mgl32.Vec3{p1.X(), p1.Y() + MovementRate, p1.Z()}) 249 | } else if ks.Pressed(sdl.K_s) { 250 | c1.Direction = directiontype.South 251 | c1.SetState(statetype.Walking) 252 | c1.SetPosition(mgl32.Vec3{p1.X(), p1.Y() - MovementRate, p1.Z()}) 253 | } else if ks.Pressed(sdl.K_d) { 254 | c1.Direction = directiontype.East 255 | c1.SetState(statetype.Walking) 256 | c1.SetPosition(mgl32.Vec3{p1.X() - MovementRate, p1.Y(), p1.Z()}) 257 | } else if ks.Pressed(sdl.K_a) { 258 | c1.Direction = directiontype.West 259 | c1.SetState(statetype.Walking) 260 | c1.SetPosition(mgl32.Vec3{p1.X() + MovementRate, p1.Y(), p1.Z()}) 261 | // 262 | //p2 := c2.Position() 263 | //c2.Direction = directiontype.West 264 | //c2.SetState(statetype.Walking) 265 | //c2.SetPosition(mgl32.Vec3{p2.X() + MovementRate, p2.Y(), p2.Z()}) 266 | } else { 267 | //c1.SetState(statetype.StandBy) 268 | c1.SetState(statetype.StandBy) 269 | } 270 | 271 | // camera controls 272 | if ks.Pressed(sdl.K_z) { 273 | cam.SetPosition(mgl32.Vec3{cam.Position().X(), cam.Position().Y(), cam.Position().Z() + 0.2}) 274 | } else if ks.Pressed(sdl.K_x) { 275 | cam.SetPosition(mgl32.Vec3{cam.Position().X(), cam.Position().Y(), cam.Position().Z() - 0.2}) 276 | } else if ks.Pressed(sdl.K_c) { 277 | cam.SetPosition(mgl32.Vec3{cam.Position().X() - 0.2, cam.Position().Y(), cam.Position().Z()}) 278 | } else if ks.Pressed(sdl.K_v) { 279 | cam.SetPosition(mgl32.Vec3{cam.Position().X() + 0.2, cam.Position().Y(), cam.Position().Z()}) 280 | } 281 | 282 | //c2.SetState(statetype.StandBy) 283 | 284 | frameStart = time.Now() 285 | frameDelta := frameStart.Sub(frameStart) 286 | 287 | w.Update(float32(frameDelta.Seconds())) 288 | 289 | win.GLSwap() 290 | 291 | time.Sleep(refreshPeriod) 292 | } 293 | } 294 | -------------------------------------------------------------------------------- /examples/3d/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | stdlog "log" 5 | "math" 6 | "os" 7 | "time" 8 | 9 | "github.com/go-gl/gl/v3.2-core/gl" 10 | "github.com/go-gl/mathgl/mgl32" 11 | "github.com/golang-ui/nuklear/nk" 12 | "github.com/rs/zerolog" 13 | "github.com/rs/zerolog/log" 14 | "github.com/veandco/go-sdl2/sdl" 15 | "github.com/xlab/closer" 16 | 17 | "github.com/project-midgard/midgarts/internal/camera" 18 | "github.com/project-midgard/midgarts/internal/graphic" 19 | "github.com/project-midgard/midgarts/internal/graphic/geometry" 20 | "github.com/project-midgard/midgarts/internal/opengl" 21 | "github.com/project-midgard/midgarts/internal/window" 22 | ) 23 | 24 | const ( 25 | WindowWidth = int32(1920) 26 | WindowHeight = int32(1080) 27 | AspectRatio = float32(WindowWidth) / float32(WindowHeight) 28 | FPS = 60 29 | 30 | maxVertexBuffer = 512 * 1024 31 | maxElementBuffer = 128 * 1024 32 | ) 33 | 34 | func init() { 35 | zerolog.SetGlobalLevel(zerolog.TraceLevel) 36 | log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) 37 | } 38 | 39 | func main() { 40 | var err error 41 | sdl.Init(sdl.INIT_EVERYTHING) 42 | 43 | win, err := sdl.CreateWindow("Nuklear Demo", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, WindowWidth, WindowHeight, sdl.WINDOW_OPENGL) 44 | if err != nil { 45 | closer.Fatalln(err) 46 | } 47 | defer win.Destroy() 48 | 49 | sdl.GLSetAttribute(sdl.GL_CONTEXT_MAJOR_VERSION, 3) 50 | sdl.GLSetAttribute(sdl.GL_CONTEXT_MINOR_VERSION, 2) 51 | sdl.GLSetAttribute(sdl.GL_CONTEXT_PROFILE_MASK, sdl.GL_CONTEXT_PROFILE_CORE) 52 | 53 | glContext, err := win.GLCreateContext() 54 | if err != nil { 55 | closer.Fatalln(err) 56 | } 57 | _ = glContext 58 | 59 | width, height := win.GetSize() 60 | log.Printf("SDL2: created window %dx%d", width, height) 61 | 62 | if err := gl.Init(); err != nil { 63 | closer.Fatalln("opengl: init failed:", err) 64 | } 65 | 66 | gl.Viewport(0, 0, int32(width), int32(height)) 67 | 68 | exitC := make(chan struct{}, 1) 69 | doneC := make(chan struct{}, 1) 70 | closer.Bind(func() { 71 | close(exitC) 72 | <-doneC 73 | }) 74 | 75 | state := &State{ 76 | bgColor: nk.NkRgba(28, 48, 62, 255), 77 | } 78 | _ = state 79 | fpsTicker := time.NewTicker(time.Second / 30) 80 | 81 | cam := camera.NewPerspectiveCamera(0.638, AspectRatio, 0.1, 1000.0) 82 | cam.ResetAngleAndY(WindowWidth, WindowHeight) 83 | 84 | ks := window.NewKeyState(win) 85 | 86 | gl.Viewport(0, 0, WindowWidth, WindowHeight) 87 | context, err := win.GLCreateContext() 88 | if err != nil { 89 | closer.Fatalln(err) 90 | } 91 | 92 | ctx := nk.NkPlatformInit(win, context, nk.PlatformInstallCallbacks) 93 | atlas := nk.NewFontAtlas() 94 | nk.NkFontStashBegin(&atlas) 95 | sansFont := nk.NkFontAtlasAddFromBytes(atlas, MustAsset("assets/FreeSans.ttf"), 16, nil) 96 | nk.NkFontStashEnd() 97 | if sansFont != nil { 98 | nk.NkStyleSetFont(ctx, sansFont.Handle()) 99 | } 100 | 101 | //gls := opengl.InitOpenGL() 102 | for { 103 | select { 104 | case <-exitC: 105 | nk.NkPlatformShutdown() 106 | sdl.Quit() 107 | fpsTicker.Stop() 108 | close(doneC) 109 | return 110 | case <-fpsTicker.C: 111 | for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() { 112 | switch event.(type) { 113 | case *sdl.QuitEvent: 114 | close(exitC) 115 | } 116 | 117 | ks.Update(event) 118 | } 119 | 120 | // camera controls 121 | if ks.Pressed(sdl.K_z) { 122 | cam.SetPosition(mgl32.Vec3{cam.Position().X(), cam.Position().Y(), cam.Position().Z() + 1.0}) 123 | } else if ks.Pressed(sdl.K_x) { 124 | cam.SetPosition(mgl32.Vec3{cam.Position().X(), cam.Position().Y(), cam.Position().Z() - 1.0}) 125 | } else if ks.Pressed(sdl.K_c) { 126 | cam.SetPosition(mgl32.Vec3{cam.Position().X() - 1.0, cam.Position().Y(), cam.Position().Z()}) 127 | } else if ks.Pressed(sdl.K_v) { 128 | cam.SetPosition(mgl32.Vec3{cam.Position().X() + 1.0, cam.Position().Y(), cam.Position().Z()}) 129 | } 130 | 131 | { 132 | gfxMain(win, state, ctx, cam, nil) 133 | } 134 | 135 | } 136 | } 137 | } 138 | 139 | func flag(v bool) int32 { 140 | if v { 141 | return 1 142 | } 143 | return 0 144 | } 145 | 146 | func gfxMain(win *sdl.Window, state *State, ctx *nk.Context, cam *camera.Camera, gls *opengl.State) { 147 | nk.NkPlatformNewFrame() 148 | 149 | // Layout 150 | bounds := nk.NkRect(50, 50, 230, 250) 151 | update := nk.NkBegin(ctx, "Demo", bounds, 152 | nk.WindowBorder|nk.WindowMovable|nk.WindowScalable|nk.WindowMinimizable|nk.WindowTitle) 153 | 154 | if update > 0 { 155 | nk.NkLayoutRowStatic(ctx, 30, 80, 1) 156 | { 157 | if nk.NkButtonLabel(ctx, "button") > 0 { 158 | stdlog.Println("[INFO] button pressed!") 159 | } 160 | } 161 | nk.NkLayoutRowDynamic(ctx, 30, 2) 162 | { 163 | if nk.NkOptionLabel(ctx, "easy", flag(state.opt == Easy)) > 0 { 164 | state.opt = Easy 165 | } 166 | if nk.NkOptionLabel(ctx, "hard", flag(state.opt == Hard)) > 0 { 167 | state.opt = Hard 168 | } 169 | } 170 | nk.NkLayoutRowDynamic(ctx, 25, 1) 171 | { 172 | nk.NkPropertyInt(ctx, "Compression:", 0, &state.prop, 100, 10, 1) 173 | } 174 | nk.NkLayoutRowDynamic(ctx, 20, 1) 175 | { 176 | nk.NkLabel(ctx, "background:", nk.TextLeft) 177 | } 178 | nk.NkLayoutRowDynamic(ctx, 25, 1) 179 | { 180 | size := nk.NkVec2(nk.NkWidgetWidth(ctx), 400) 181 | if nk.NkComboBeginColor(ctx, state.bgColor, size) > 0 { 182 | nk.NkLayoutRowDynamic(ctx, 120, 1) 183 | cf := nk.NkColorCf(state.bgColor) 184 | cf = nk.NkColorPicker(ctx, cf, nk.ColorFormatRGBA) 185 | state.bgColor = nk.NkRgbCf(cf) 186 | nk.NkLayoutRowDynamic(ctx, 25, 1) 187 | r, g, b, a := state.bgColor.RGBAi() 188 | r = nk.NkPropertyi(ctx, "#R:", 0, r, 255, 1, 1) 189 | g = nk.NkPropertyi(ctx, "#G:", 0, g, 255, 1, 1) 190 | b = nk.NkPropertyi(ctx, "#B:", 0, b, 255, 1, 1) 191 | a = nk.NkPropertyi(ctx, "#A:", 0, a, 255, 1, 1) 192 | state.bgColor.SetRGBAi(r, g, b, a) 193 | nk.NkComboEnd(ctx) 194 | } 195 | } 196 | } 197 | nk.NkEnd(ctx) 198 | 199 | // Render 200 | bg := make([]float32, 4) 201 | nk.NkColorFv(bg, state.bgColor) 202 | width, height := win.GetSize() 203 | gl.Viewport(0, 0, int32(width), int32(height)) 204 | gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) 205 | 206 | { 207 | gl.UseProgram(gls.Program().ID()) 208 | plane := geometry.NewPlane(50, 60, nil) 209 | 210 | view := cam.ViewMatrix() 211 | viewu := gl.GetUniformLocation(gls.Program().ID(), gl.Str("view\x00")) 212 | gl.UniformMatrix4fv(viewu, 1, false, &view[0]) 213 | 214 | model := plane.Model() 215 | modelu := gl.GetUniformLocation(gls.Program().ID(), gl.Str("model\x00")) 216 | gl.UniformMatrix4fv(modelu, 1, false, &model[0]) 217 | 218 | projection := cam.ProjectionMatrix() 219 | projectionu := gl.GetUniformLocation(gls.Program().ID(), gl.Str("projection\x00")) 220 | gl.UniformMatrix4fv(projectionu, 1, false, &projection[0]) 221 | 222 | sizeu := gl.GetUniformLocation(gls.Program().ID(), gl.Str("size\x00")) 223 | s := float32(1.0) 224 | gl.Uniform2fv(sizeu, 1, &s) 225 | 226 | offsetu := gl.GetUniformLocation(gls.Program().ID(), gl.Str("offset\x00")) 227 | o := float32(0.0) 228 | gl.Uniform2fv(offsetu, 1, &o) 229 | 230 | iden := mgl32.Ident4() 231 | rotation := iden.Mul4(mgl32.HomogRotate3D(math.Pi/180, graphic.Backwards)) 232 | rotationu := gl.GetUniformLocation(gls.Program().ID(), gl.Str("rotation\x00")) 233 | gl.UniformMatrix4fv(rotationu, 1, false, &rotation[0]) 234 | 235 | plane.Render(gls) 236 | } 237 | 238 | nk.NkPlatformRender(nk.AntiAliasingOn, maxVertexBuffer, maxElementBuffer) 239 | 240 | win.GLSwap() 241 | } 242 | 243 | type Option uint8 244 | 245 | const ( 246 | Easy Option = 0 247 | Hard Option = 1 248 | ) 249 | 250 | type State struct { 251 | bgColor nk.Color 252 | prop int32 253 | opt Option 254 | } 255 | 256 | func onError(code int32, msg string) { 257 | log.Printf("[ERR]: error %d: %s", code, msg) 258 | } 259 | -------------------------------------------------------------------------------- /examples/3d/renderer/sprite.go: -------------------------------------------------------------------------------- 1 | package renderer 2 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/project-midgard/midgarts 2 | 3 | go 1.16 4 | 5 | require ( 6 | github.com/AllenDang/giu v0.5.3 7 | github.com/EngoEngine/ecs v1.0.5 8 | github.com/davecgh/go-spew v1.1.1 9 | github.com/go-gl/gl v0.0.0-20211210172815-726fda9656d6 10 | github.com/go-gl/glfw v0.0.0-20221017161538-93cebf72946b // indirect 11 | github.com/go-gl/mathgl v1.0.0 12 | github.com/golang-ui/nuklear v0.0.0-20220830122737-d1c7e248721c 13 | github.com/google/uuid v1.2.0 14 | github.com/joho/godotenv v1.3.0 15 | github.com/pkg/errors v0.9.1 16 | github.com/rs/zerolog v1.26.1 17 | github.com/stretchr/testify v1.7.0 18 | github.com/veandco/go-sdl2 v0.4.25 19 | github.com/xlab/android-go v0.0.0-20221014001251-3dab312ceaf9 // indirect 20 | github.com/xlab/closer v1.1.0 21 | golang.org/x/text v0.3.6 22 | ) 23 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/AllenDang/giu v0.5.3 h1:XFQdiiGWGulYen8Ebvri3Oe3DMFl5gY/7bKNtJxhOjM= 2 | github.com/AllenDang/giu v0.5.3/go.mod h1:s8+ELvV41d5N5oB7N51qmAUukz4dDNT1dVHDp4m/w2g= 3 | github.com/EngoEngine/ecs v1.0.5 h1:S21KTClrAqC862BFR5wTkd6uEYQ0Aw/ob9RjKPt0e30= 4 | github.com/EngoEngine/ecs v1.0.5/go.mod h1:A8AYbzKIsl+t4qafmLL3t4H6cXdfGo4CIHl7EN100iM= 5 | github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= 6 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 7 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 8 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 9 | github.com/faiface/mainthread v0.0.0-20171120011319-8b78f0a41ae3 h1:baVdMKlASEHrj19iqjARrPbaRisD7EuZEVJj6ZMLl1Q= 10 | github.com/faiface/mainthread v0.0.0-20171120011319-8b78f0a41ae3/go.mod h1:VEPNJUlxl5KdWjDvz6Q1l+rJlxF2i6xqDeGuGAxa87M= 11 | github.com/go-gl/gl v0.0.0-20190320180904-bf2b1f2f34d7/go.mod h1:482civXOzJJCPzJ4ZOX/pwvXBWSnzD4OKMdH4ClKGbk= 12 | github.com/go-gl/gl v0.0.0-20211210172815-726fda9656d6 h1:zDw5v7qm4yH7N8C8uWd+8Ii9rROdgWxQuGoJ9WDXxfk= 13 | github.com/go-gl/gl v0.0.0-20211210172815-726fda9656d6/go.mod h1:9YTyiznxEY1fVinfM7RvRcjRHbw2xLBJ3AAGIT0I4Nw= 14 | github.com/go-gl/glfw v0.0.0-20221017161538-93cebf72946b h1:2hdUMUOJuLQkhaPAwoyOeSzoaBydYEkXkBEuqDuDBfg= 15 | github.com/go-gl/glfw v0.0.0-20221017161538-93cebf72946b/go.mod h1:wyvWpaEu9B/VQiV1jsPs7Mha9I7yto/HqIBw197ZAzk= 16 | github.com/go-gl/glfw/v3.3/glfw v0.0.0-20210311203641-62640a716d48 h1:QrUfZrT8n72FUuiABt4tbu8PwDnOPAbnj3Mql1UhdRI= 17 | github.com/go-gl/glfw/v3.3/glfw v0.0.0-20210311203641-62640a716d48/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= 18 | github.com/go-gl/mathgl v1.0.0 h1:t9DznWJlXxxjeeKLIdovCOVJQk/GzDEL7h/h+Ro2B68= 19 | github.com/go-gl/mathgl v1.0.0/go.mod h1:yhpkQzEiH9yPyxDUGzkmgScbaBVlhC06qodikEM0ZwQ= 20 | github.com/go-resty/resty/v2 v2.3.0 h1:JOOeAvjSlapTT92p8xiS19Zxev1neGikoHsXJeOq8So= 21 | github.com/go-resty/resty/v2 v2.3.0/go.mod h1:UpN9CgLZNsv4e9XG50UU8xdI0F43UQ4HmxLBDwaroHU= 22 | github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= 23 | github.com/golang-ui/nuklear v0.0.0-20220830122737-d1c7e248721c h1:UH8nJr1awnYxfYItPX0ZlvAEEeC2c3rGcgPsOnYpxhI= 24 | github.com/golang-ui/nuklear v0.0.0-20220830122737-d1c7e248721c/go.mod h1:xX2vbAOtImdmMK3nPye2JyxCZbPmbjg/IVBIzuxReKU= 25 | github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs= 26 | github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 27 | github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc= 28 | github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= 29 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= 30 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 31 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 32 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 33 | github.com/rs/xid v1.3.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= 34 | github.com/rs/zerolog v1.26.1 h1:/ihwxqH+4z8UxyI70wM1z9yCvkWcfz/a3mj48k/Zngc= 35 | github.com/rs/zerolog v1.26.1/go.mod h1:/wSSJWX7lVrsOwlbyTRSOJvqRlc+WjWlfes+CiJ+tmc= 36 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 37 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 38 | github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= 39 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 40 | github.com/veandco/go-sdl2 v0.4.25 h1:J5ac3KKOccp/0xGJA1PaNYKPUcZm19IxhDGs8lJofPI= 41 | github.com/veandco/go-sdl2 v0.4.25/go.mod h1:OROqMhHD43nT4/i9crJukyVecjPNYYuCofep6SNiAjY= 42 | github.com/xlab/android-go v0.0.0-20221014001251-3dab312ceaf9 h1:gGO62iqn+KRAAHuaTj28knIfP5X03pgnLBw8f/XHH7s= 43 | github.com/xlab/android-go v0.0.0-20221014001251-3dab312ceaf9/go.mod h1:cX5Ob29gFddv5hlAJN3tmNcvHuNQwUXzIP06azWW1M8= 44 | github.com/xlab/closer v1.1.0 h1:yrDiOXjd/B7pZ3lZkl/EZ1gWrR2M2N5XpBnixynm4mc= 45 | github.com/xlab/closer v1.1.0/go.mod h1:Ff8YcUPbn5jju6nClrMCmJHQABM0S/obEK0za/1yVMk= 46 | github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= 47 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 48 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 49 | golang.org/x/crypto v0.0.0-20211215165025-cf75a172585e/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= 50 | golang.org/x/image v0.0.0-20190321063152-3fc05d484e9f h1:FO4MZ3N56GnxbqxGKqh+YTzUWQ2sDwtFQEZgLOxh9Jc= 51 | golang.org/x/image v0.0.0-20190321063152-3fc05d484e9f/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= 52 | golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= 53 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 54 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 55 | golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= 56 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 57 | golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d h1:20cMwl2fHAzkJMEA+8J4JgqBQcQGzbisXo31MIeenXI= 58 | golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= 59 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 60 | golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 61 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 62 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 63 | golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 64 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 65 | golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 66 | golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 67 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 68 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 69 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 70 | golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= 71 | golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 72 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 73 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 74 | golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= 75 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 76 | golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 77 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 78 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 79 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 80 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= 81 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 82 | -------------------------------------------------------------------------------- /internal/bytesutil/bytes.go: -------------------------------------------------------------------------------- 1 | package bytesutil 2 | 3 | import ( 4 | "encoding/binary" 5 | "github.com/pkg/errors" 6 | "io" 7 | "io/ioutil" 8 | "strings" 9 | ) 10 | 11 | func SkipBytes(buf io.ReadSeeker, n int64) error { 12 | if _, err := ioutil.ReadAll(io.LimitReader(buf, n)); err != nil { 13 | return errors.Wrapf(err, "could not skip %d bytes\n", n) 14 | } 15 | 16 | return nil 17 | } 18 | 19 | func ReadString(buf io.Reader, length int) (string, error) { 20 | str := make([]byte, length) 21 | _ = binary.Read(buf, binary.LittleEndian, &str) 22 | 23 | return strings.Split(string(str), string('\x00'))[0], nil 24 | } 25 | -------------------------------------------------------------------------------- /internal/camera/camera.go: -------------------------------------------------------------------------------- 1 | package camera 2 | 3 | import ( 4 | "math" 5 | 6 | "github.com/go-gl/mathgl/mgl32" 7 | 8 | "github.com/project-midgard/midgarts/internal/graphic" 9 | ) 10 | 11 | type Projection int 12 | 13 | const ( 14 | Perspective = Projection(iota) 15 | ) 16 | 17 | const ( 18 | Yaw = float32(270.0) 19 | Pitch = float32(-60.0) 20 | ) 21 | 22 | type Camera struct { 23 | *graphic.Transform 24 | target *graphic.Transform 25 | projectionType Projection 26 | fov, aspect, near, far float32 27 | projectionMatrix, viewMatrix mgl32.Mat4 28 | front, right, up mgl32.Vec3 29 | yaw, pitch float32 30 | distance float32 31 | targetRotation mgl32.Vec3 32 | altitude float32 33 | } 34 | 35 | func NewPerspectiveCamera(fov, aspect, near, far float32) *Camera { 36 | cam := &Camera{ 37 | Transform: graphic.NewTransform(mgl32.Vec3{0, 40.0, 0}), 38 | projectionType: Perspective, 39 | aspect: aspect, 40 | fov: fov, 41 | near: near, 42 | far: far, 43 | distance: 30.0, 44 | altitude: 50.0, 45 | front: mgl32.Vec3{0, 0, -1}, 46 | } 47 | 48 | cam.projectionMatrix = mgl32.Perspective(cam.fov, cam.aspect, cam.near, cam.far) 49 | 50 | return cam 51 | } 52 | 53 | func (c *Camera) createViewMatrix() mgl32.Mat4 { 54 | return mgl32.LookAt( 55 | c.Position().X(), 56 | c.Position().Y(), 57 | c.Position().Z(), 58 | c.Position().X()+graphic.Forward.X(), 59 | c.Position().Y()+graphic.Forward.Y(), 60 | c.Position().Z()+graphic.Forward.Z(), 61 | graphic.Up.X(), 62 | graphic.Up.Y(), 63 | graphic.Up.Z(), 64 | ) 65 | } 66 | 67 | func (c *Camera) ViewMatrix() mgl32.Mat4 { 68 | c.viewMatrix = c.createViewMatrix() 69 | return c.viewMatrix 70 | } 71 | 72 | func (c *Camera) ProjectionMatrix() mgl32.Mat4 { 73 | return c.projectionMatrix 74 | } 75 | 76 | func (c *Camera) ResetAngleAndY(windowWidth, windowHeight int32) { 77 | c.yaw = Yaw 78 | c.pitch = Pitch 79 | c.SetY(45) 80 | c.Rotate(c.pitch, c.yaw) 81 | c.UpdateVisibleZRange(windowWidth, windowHeight) 82 | } 83 | 84 | func (c *Camera) SetY(y float32) { 85 | c.SetPosition(mgl32.Vec3{c.Position().X(), y, c.Position().Z() - 32}) 86 | } 87 | 88 | func (c *Camera) Rotate(yaw float32, pitch float32) { 89 | c.front = mgl32.Vec3{ 90 | float32(math.Cos(float64(mgl32.DegToRad(pitch))) * math.Cos(float64(mgl32.DegToRad(yaw)))), 91 | float32(math.Cos(float64(mgl32.DegToRad(pitch)))), 92 | float32(math.Cos(float64(mgl32.DegToRad(pitch))) * math.Sin(float64(mgl32.DegToRad(yaw)))), 93 | } 94 | 95 | c.right = c.front.Cross(graphic.Up) 96 | c.up = c.right.Cross(c.front) 97 | c.UpdateVisibleZRange(0, 0) 98 | } 99 | 100 | func (c *Camera) UpdateVisibleZRange(width int32, height int32) { 101 | view := c.createViewMatrix() 102 | _ = view 103 | } 104 | -------------------------------------------------------------------------------- /internal/char/accessory.go: -------------------------------------------------------------------------------- 1 | package char 2 | 3 | // 4 | //import ( 5 | // "image" 6 | // "image/color" 7 | // 8 | // "github.com/project-midgard/midgarts/internal/character" 9 | //) 10 | // 11 | //type Accessory struct { 12 | // Color *image.Uniform 13 | // Type character.AttachmentType 14 | // Offset image.Point 15 | // PositionFrame image.Point 16 | // PositionLayer image.Point 17 | // Image *image.RGBA 18 | //} 19 | // 20 | //func NewAccessory( 21 | // elem character.AttachmentType, 22 | // offset, 23 | // positionFrame, 24 | // positionLayer image.Point, 25 | // img *image.RGBA, 26 | //) Accessory { 27 | // var c *image.Uniform 28 | // 29 | // Blue := color.RGBA{R: 0, G: 0, B: 255, A: 255} 30 | // Green := color.RGBA{R: 0, G: 255, B: 0, A: 255} 31 | // Red := color.RGBA{R: 255, G: 0, B: 0, A: 255} 32 | // 33 | // switch elem { 34 | // case character.AttachmentShadow: 35 | // c = &image.Uniform{C: Red} 36 | // case character.AttachmentBody: 37 | // c = &image.Uniform{C: Green} 38 | // case character.AttachmentHead: 39 | // c = &image.Uniform{C: Blue} 40 | // } 41 | // 42 | // return Accessory{ 43 | // c, 44 | // elem, 45 | // offset, 46 | // positionFrame, 47 | // positionLayer, 48 | // img, 49 | // } 50 | //} 51 | // 52 | //// Anchor takes a set of accessories, calculates the proper anchor 53 | //// points for each one of them and returns a new set of accessories 54 | //// with the calculated anchor points. 55 | //func Anchor(accessories ...Accessory) []Accessory { 56 | // var anchor image.Point 57 | // 58 | // res := make([]Accessory, 0) 59 | // for _, acc := range accessories { 60 | // var pos image.Point 61 | // 62 | // if acc.Type != character.AttachmentBody && 63 | // acc.Type != character.AttachmentShield { 64 | // pos.X = anchor.X - acc.PositionFrame.X 65 | // pos.Y = anchor.Y - acc.PositionFrame.Y 66 | // } 67 | // 68 | // acc.Offset.X = acc.PositionFrame.X + pos.X 69 | // acc.Offset.Y = acc.PositionFrame.Y + pos.Y 70 | // 71 | // res = append(res, acc) 72 | // 73 | // anchor.X = acc.PositionFrame.X 74 | // anchor.Y = acc.PositionFrame.Y 75 | // } 76 | // 77 | // return res 78 | //} 79 | -------------------------------------------------------------------------------- /internal/char/sprite.go: -------------------------------------------------------------------------------- 1 | package char 2 | 3 | // 4 | //import ( 5 | // "image" 6 | // "image/draw" 7 | // 8 | // "github.com/rs/zerolog/log" 9 | // 10 | // "github.com/project-midgard/midgarts/internal/character" 11 | // "github.com/project-midgard/midgarts/internal/character/jobspriteid" 12 | // "github.com/project-midgard/midgarts/internal/component" 13 | // "github.com/project-midgard/midgarts/internal/fileformat/grf" 14 | //) 15 | // 16 | //type Sprite struct { 17 | // Image *image.RGBA 18 | //} 19 | // 20 | //type SpriteLoader struct { 21 | // *grf.File 22 | //} 23 | // 24 | //func NewSpriteLoader(grfFile *grf.File) *SpriteLoader { 25 | // return &SpriteLoader{grfFile} 26 | //} 27 | // 28 | //func (s *SpriteLoader) LoadSprite( 29 | // gender character.GenderType, 30 | // jid jobspriteid.Type, 31 | // headIndex character.HeadIndex, 32 | // spriteIndex character.SpriteIndex, 33 | //) (*Sprite, error) { 34 | // attachments, err := component.NewCharacterAttachmentComponent( 35 | // s.File, 36 | // component.CharacterAttachmentComponentConfig{ 37 | // Gender: gender, 38 | // JobSpriteID: jid, 39 | // HeadIndex: headIndex, 40 | // }, 41 | // ) 42 | // if err != nil { 43 | // return nil, err 44 | // } 45 | // 46 | // // Set the shaders to the first 47 | // // Set action index to the default "idle" action 48 | // actionIndex := 0 49 | // // Set the frame index to the first action frame 50 | // frameIndex := 0 51 | // // Set the base layer 52 | // layerIndex := 0 53 | // 54 | // accessories := make([]Accessory, character.NumAttachments-1) 55 | // for t, att := range attachments.Files { 56 | // action := att.ACT.Actions[actionIndex] 57 | // frame := action.Frames[frameIndex] 58 | // 59 | // framePos := image.Point{ 60 | // X: int(frame.Positions[0][0]), 61 | // Y: int(frame.Positions[0][1]), 62 | // } 63 | // layerPos := image.Point{ 64 | // X: int(frame.Layers[layerIndex].Position[0]), 65 | // Y: int(frame.Layers[layerIndex].Position[1]), 66 | // } 67 | // 68 | // accessories[t] = NewAccessory( 69 | // t, image.Point{}, framePos, layerPos, att.SPR.ImageAt(0).RGBA, 70 | // ) 71 | // } 72 | // 73 | // accessories = Anchor(accessories...) 74 | // 75 | // w := 50 76 | // h := 80 77 | // canvas := image.NewRGBA(image.Rect(0, 0, w, h)) 78 | // 79 | // draw.Draw(canvas, canvas.Bounds(), &image.Uniform{C: image.White}, image.ZP, draw.Over) 80 | // 81 | // //var anchor image.Point 82 | // for _, acc := range accessories { 83 | // origin := image.Point{} 84 | // size := acc.Image.Bounds() 85 | // 86 | // rect := image.Rect(0, canvas.Bounds().Dy()-size.Dy(), size.Dx(), canvas.Bounds().Dy()) 87 | // 88 | // //anchor = acc.Offset 89 | // draw.Draw(canvas, rect.Add(acc.Offset), acc.Color, origin, draw.Over) 90 | // //draw.Draw(canvas, rect.Add(acc.Offset), acc.Image, origin, draw.Over) 91 | // //draw.Draw(canvas, rect, acc.Image, origin.Sub(offset), draw.Over) 92 | // //size := acc.Image.Rect.Size() 93 | // //origin := image.Point{X: 0, Y: canvas.Bounds().Dy() - size.Y} 94 | // // 95 | // ////var origin image.Point 96 | // // 97 | // ////pos := image.Point{X: origin.X + acc.PositionAnchor.X, Y: origin.Y + acc.PositionAnchor.Y} 98 | // ////origin = origin.Add(acc.PositionAnchor.Point()) 99 | // ////origin = image.Point{X: origin.X + acc.PositionAnchor.X, Y: origin.Y + acc.PositionAnchor.Y} 100 | // // 101 | // 102 | // // 103 | // //rect := image.Rect(origin.X, origin.Y, size.X, size.Y) 104 | // ////offset := image.Point{} 105 | // //draw.Draw(canvas, rect, acc.Color, origin, draw.Over) 106 | // ////draw.Draw(canvas, canvas.Rect, acc.Image, image.ZP, draw.Over) 107 | // } 108 | // 109 | // log.Debug().Msg("\n") 110 | // 111 | // return &Sprite{canvas}, nil 112 | //} 113 | -------------------------------------------------------------------------------- /internal/character/actionindex/actionindex.go: -------------------------------------------------------------------------------- 1 | package actionindex 2 | 3 | import ( 4 | "fmt" 5 | "github.com/project-midgard/midgarts/internal/character/statetype" 6 | "log" 7 | ) 8 | 9 | type Type int 10 | 11 | const ( 12 | Idle Type = 0 13 | Walking Type = 8 14 | Sitting Type = 16 15 | PickingItem Type = 24 16 | StandBy Type = 32 17 | Attacking1 Type = 40 18 | ReceivingDamage Type = 48 19 | Freeze1 Type = 56 20 | Dead Type = 65 21 | Freeze2 Type = 72 22 | Attacking2 Type = 80 23 | Attacking3 Type = 88 24 | CastingSpell Type = 96 25 | ) 26 | 27 | func GetActionIndex(s statetype.Type) (t Type) { 28 | switch s { 29 | case statetype.Attacking: 30 | return Attacking3 31 | case statetype.Walking: 32 | return Walking 33 | case statetype.Idle: 34 | return Idle 35 | case statetype.StandBy: 36 | return StandBy 37 | default: 38 | log.Fatal(fmt.Sprintf("state type '%v' not supported\n", s)) 39 | } 40 | 41 | return 42 | } 43 | 44 | func GetStateType(s Type) (t statetype.Type) { 45 | switch s { 46 | case Idle: 47 | return statetype.Idle 48 | case Walking: 49 | return statetype.Walking 50 | case StandBy: 51 | return statetype.StandBy 52 | default: 53 | panic(fmt.Sprintf("state type '%v' not supported\n", s)) 54 | } 55 | 56 | return 57 | } 58 | -------------------------------------------------------------------------------- /internal/character/actionplaymode/actionindex.go: -------------------------------------------------------------------------------- 1 | package actionplaymode 2 | 3 | type Type int 4 | 5 | const ( 6 | Repeat Type = iota 7 | PlayThenHold 8 | Once 9 | Reverse 10 | FixFrame 11 | ) 12 | -------------------------------------------------------------------------------- /internal/character/attachments.go: -------------------------------------------------------------------------------- 1 | package character 2 | 3 | type AttachmentType int 4 | 5 | const ( 6 | AttachmentShadow = AttachmentType(iota) 7 | AttachmentBody 8 | AttachmentHead 9 | AttachmentShield 10 | NumAttachments 11 | ) 12 | 13 | func (e AttachmentType) String() (att string) { 14 | switch e { 15 | case AttachmentShadow: 16 | att = "AttachmentShadow" 17 | case AttachmentBody: 18 | att = "AttachmentBody" 19 | case AttachmentHead: 20 | att = "AttachmentHead" 21 | case AttachmentShield: 22 | att = "AttachmentShield" 23 | default: 24 | panic("unsupported attachment type") 25 | } 26 | 27 | return att 28 | } 29 | 30 | func Attachments() []AttachmentType { 31 | return []AttachmentType{ 32 | AttachmentShadow, 33 | AttachmentBody, 34 | AttachmentHead, 35 | AttachmentShield, 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /internal/character/character.go: -------------------------------------------------------------------------------- 1 | package character 2 | 3 | var ( 4 | MaleFilePathf = "data/sprite/%s/%s/³²/%s_³²" 5 | FemaleFilePathf = "data/sprite/%s/%s/¿©/%s_¿©" 6 | ) 7 | 8 | type HeadIndex int 9 | type SpriteIndex int 10 | -------------------------------------------------------------------------------- /internal/character/directiontype/statetype.go: -------------------------------------------------------------------------------- 1 | package directiontype 2 | 3 | var DirectionTable = [8]int{6, 5, 4, 3, 2, 1, 0, 7} 4 | 5 | type Type uint8 6 | 7 | const ( 8 | South Type = iota 9 | SouthWest 10 | West 11 | NorthWest 12 | North 13 | NorthEast 14 | East 15 | SouthEast 16 | ) 17 | -------------------------------------------------------------------------------- /internal/character/gender.go: -------------------------------------------------------------------------------- 1 | package character 2 | 3 | type GenderType byte 4 | 5 | const ( 6 | Male GenderType = iota 7 | Female 8 | ) 9 | 10 | func (t GenderType) String() string { 11 | if t == Male { 12 | return "m" 13 | } else { 14 | return "f" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /internal/character/jobid/jobid.go: -------------------------------------------------------------------------------- 1 | package jobid 2 | 3 | type Type int 4 | 5 | const ( 6 | Crusader = Type(iota) 7 | Swordsman 8 | Archer 9 | Ranger 10 | Assassin 11 | Rogue 12 | Knight 13 | Wizard 14 | Sage 15 | Alchemist 16 | Blacksmith 17 | Priest 18 | Monk 19 | Gunslinger 20 | ) 21 | 22 | func (t Type) String() string { 23 | switch t { 24 | case Crusader: 25 | return "Crusader" 26 | case Swordsman: 27 | return "Swordsman" 28 | case Archer: 29 | return "Archer" 30 | case Ranger: 31 | return "Ranger" 32 | case Assassin: 33 | return "Assassin" 34 | case Rogue: 35 | return "Rogue" 36 | case Knight: 37 | return "Knight" 38 | case Wizard: 39 | return "Wizard" 40 | case Sage: 41 | return "Sage" 42 | case Alchemist: 43 | return "Alchemist" 44 | case Blacksmith: 45 | return "Blacksmith" 46 | case Priest: 47 | return "Priest" 48 | case Monk: 49 | return "Monk" 50 | case Gunslinger: 51 | return "Gunslinger" 52 | default: 53 | return "" 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /internal/character/jobsprite.go: -------------------------------------------------------------------------------- 1 | package character 2 | 3 | import ( 4 | "golang.org/x/text/encoding/charmap" 5 | 6 | "github.com/project-midgard/midgarts/internal/character/jobspriteid" 7 | ) 8 | 9 | var JobSpriteNameTable = map[jobspriteid.Type]string{} 10 | 11 | func init() { 12 | var dst []byte 13 | 14 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xC3, 0xCA, 0xBA, 0xB8, 0xC0, 0xDA}) 15 | JobSpriteNameTable[jobspriteid.Novice] = string(dst) 16 | 17 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xB0, 0xCB, 0xBB, 0xE7}) 18 | JobSpriteNameTable[jobspriteid.Swordsman] = string(dst) 19 | 20 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xB8, 0xB6, 0xB9, 0xDD, 0xBB, 0xC7}) 21 | JobSpriteNameTable[jobspriteid.Magician] = string(dst) 22 | 23 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xB1, 0xC3, 0xBC, 0xF6}) 24 | JobSpriteNameTable[jobspriteid.Archer] = string(dst) 25 | 26 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xBC, 0xBA, 0xC1, 0xF7, 0xC0, 0xDA}) 27 | JobSpriteNameTable[jobspriteid.Alcolyte] = string(dst) 28 | 29 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xBB, 0xF3, 0xC0, 0xCE}) 30 | JobSpriteNameTable[jobspriteid.Merchant] = string(dst) 31 | 32 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xB5, 0xB5, 0xB5, 0xCF}) 33 | JobSpriteNameTable[jobspriteid.Thief] = string(dst) 34 | 35 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xB8, 0xF9, 0xC5, 0xA9}) 36 | JobSpriteNameTable[jobspriteid.Monk] = string(dst) 37 | 38 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xB1, 0xE2, 0xBB, 0xE7}) 39 | JobSpriteNameTable[jobspriteid.Knight] = string(dst) 40 | 41 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xC6, 0xE4, 0xC4, 0xDA, 0xC6, 0xE4, 0xC4, 0xDA, 0x5f, 0xB1, 0xE2, 0xBB, 0xE7}) 42 | JobSpriteNameTable[jobspriteid.Knight2] = string(dst) 43 | 44 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xC7, 0xC1, 0xB8, 0xAE, 0xBD, 0xBA, 0xC6, 0xAE}) 45 | JobSpriteNameTable[jobspriteid.Priest] = string(dst) 46 | 47 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xC0, 0xA7, 0xC0, 0xFA, 0xB5, 0xE5}) 48 | JobSpriteNameTable[jobspriteid.Wizard] = string(dst) 49 | 50 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xC1, 0xA6, 0xC3, 0xB6, 0xB0, 0xF8}) 51 | JobSpriteNameTable[jobspriteid.Blacksmith] = string(dst) 52 | 53 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xC7, 0xE5, 0xC5, 0xCD}) 54 | JobSpriteNameTable[jobspriteid.Hunter] = string(dst) 55 | 56 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xC5, 0xA9, 0xB7, 0xE7, 0xBC, 0xBC, 0xC0, 0xCC, 0xB4, 0xF5}) 57 | JobSpriteNameTable[jobspriteid.Crusader] = string(dst) 58 | 59 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xBD, 0xC5, 0xC6, 0xE4, 0xC4, 0xDA, 0xC5, 0xA9, 0xB7, 0xE7, 0xBC, 0xBC, 0xC0, 0xCC, 0xB4, 0xF5}) 60 | JobSpriteNameTable[jobspriteid.Crusader2] = string(dst) 61 | 62 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xBC, 0xBC, 0xC0, 0xCC, 0xC1, 0xF6}) 63 | JobSpriteNameTable[jobspriteid.Sage] = string(dst) 64 | 65 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xB7, 0xCE, 0xB1, 0xD7}) 66 | JobSpriteNameTable[jobspriteid.Rogue] = string(dst) 67 | 68 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xBF, 0xAC, 0xB1, 0xDD, 0xBC, 0xFA, 0xBB, 0xE7}) 69 | JobSpriteNameTable[jobspriteid.Alchemist] = string(dst) 70 | 71 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xBE, 0xEE, 0xBC, 0xBC, 0xBD, 0xC5}) 72 | JobSpriteNameTable[jobspriteid.Assassin] = string(dst) 73 | 74 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xB9, 0xD9, 0xB5, 0xE5}) 75 | JobSpriteNameTable[jobspriteid.Bard] = string(dst) 76 | 77 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xB9, 0xAB, 0xC8, 0xF1}) 78 | JobSpriteNameTable[jobspriteid.Dancer] = string(dst) 79 | 80 | dst, _ = charmap.Windows1252.NewDecoder().Bytes([]byte{0xC3, 0xA8, 0xC7, 0xC7, 0xBF, 0xC2}) 81 | JobSpriteNameTable[jobspriteid.MonkH] = string(dst) 82 | } 83 | -------------------------------------------------------------------------------- /internal/character/jobspriteid/jobspriteid.go: -------------------------------------------------------------------------------- 1 | package jobspriteid 2 | 3 | import ( 4 | "github.com/project-midgard/midgarts/internal/character/jobid" 5 | "log" 6 | ) 7 | 8 | type Type int 9 | 10 | const ( 11 | Novice = Type(0) 12 | Swordsman = Type(1) 13 | Magician = Type(2) 14 | Archer = Type(3) 15 | Alcolyte = Type(4) 16 | Merchant = Type(5) 17 | Thief = Type(6) 18 | Knight = Type(7) 19 | Priest = Type(8) 20 | Wizard = Type(9) 21 | Blacksmith = Type(10) 22 | Hunter = Type(11) 23 | Assassin = Type(12) 24 | Knight2 = Type(13) 25 | Crusader = Type(14) 26 | Monk = Type(15) 27 | Sage = Type(16) 28 | Rogue = Type(17) 29 | Alchemist = Type(18) 30 | Bard = Type(19) 31 | Dancer = Type(20) 32 | Crusader2 = Type(21) 33 | KnightH = Type(4008) 34 | MonkH = Type(4016) 35 | ) 36 | 37 | func GetJobSpriteID(jid jobid.Type, isMounted bool) (t Type) { 38 | switch jid { 39 | case jobid.Archer: 40 | return Archer 41 | case jobid.Monk: 42 | return Monk 43 | case jobid.Assassin: 44 | return Assassin 45 | case jobid.Swordsman: 46 | return Swordsman 47 | case jobid.Alchemist: 48 | return Alchemist 49 | case jobid.Knight: 50 | if isMounted { 51 | return Knight2 52 | } else { 53 | return Knight 54 | } 55 | case jobid.Crusader: 56 | if isMounted { 57 | return Crusader2 58 | } else { 59 | return Crusader 60 | } 61 | //case jobid.Thief: 62 | // return Thief 63 | //case jobid.MonkH: 64 | // return MonkH 65 | 66 | default: 67 | log.Fatalf("jobid '%v' not supported", jid) 68 | } 69 | 70 | return 71 | } 72 | 73 | func (j Type) String() string { 74 | switch j { 75 | case Novice: 76 | return "Novice" 77 | case Swordsman: 78 | return "Swordsman" 79 | case Magician: 80 | return "Magician" 81 | case Archer: 82 | return "Archer" 83 | case Alcolyte: 84 | return "Alcolyte" 85 | case Merchant: 86 | return "Merchant" 87 | case Thief: 88 | return "Thief" 89 | case Knight: 90 | return "Knight" 91 | case Priest: 92 | return "Priest" 93 | case Wizard: 94 | return "Wizard" 95 | case Blacksmith: 96 | return "Blacksmith" 97 | case Hunter: 98 | return "Hunter" 99 | case Assassin: 100 | return "Assassin" 101 | case Knight2: 102 | return "Knight2" 103 | case Crusader: 104 | return "Crusader" 105 | case Monk: 106 | return "Monk" 107 | case Sage: 108 | return "Sage" 109 | case Rogue: 110 | return "Rogue" 111 | case Alchemist: 112 | return "Alchemist" 113 | case Bard: 114 | return "Bard" 115 | case Dancer: 116 | return "Dancer" 117 | case Crusader2: 118 | return "Crusader2" 119 | case KnightH: 120 | return "KnightH" 121 | case MonkH: 122 | return "MonkH" 123 | default: 124 | log.Fatalf("unsupported jobspriteid %d\n", j) 125 | } 126 | 127 | return "" 128 | } 129 | 130 | func All() []Type { 131 | return []Type{ 132 | Novice, 133 | Swordsman, 134 | Magician, 135 | Archer, 136 | Alcolyte, 137 | Merchant, 138 | Thief, 139 | Knight, 140 | Priest, 141 | Wizard, 142 | Blacksmith, 143 | Hunter, 144 | Assassin, 145 | Knight2, 146 | Crusader, 147 | Monk, 148 | Sage, 149 | Rogue, 150 | Alchemist, 151 | Crusader2, 152 | KnightH, 153 | MonkH, 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /internal/character/statetype/statetype.go: -------------------------------------------------------------------------------- 1 | package statetype 2 | 3 | type Type string 4 | 5 | const ( 6 | Idle Type = "Idle" 7 | Walking Type = "Walking" 8 | Attacking Type = "Attacking" 9 | StandBy Type = "StandBy" 10 | ) 11 | -------------------------------------------------------------------------------- /internal/component/character_attachment_component.go: -------------------------------------------------------------------------------- 1 | package component 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | 7 | "github.com/pkg/errors" 8 | "golang.org/x/text/encoding/charmap" 9 | 10 | "github.com/project-midgard/midgarts/internal/character" 11 | "github.com/project-midgard/midgarts/internal/character/jobspriteid" 12 | "github.com/project-midgard/midgarts/internal/fileformat/grf" 13 | ) 14 | 15 | type CharacterAttachmentComponentFace interface { 16 | GetCharacterAttachmentComponent() *CharacterAttachmentComponent 17 | } 18 | 19 | // CharacterAttachmentComponent defines a component that holds state about character 20 | // character attachments (shadow, body, head...). 21 | type CharacterAttachmentComponent struct { 22 | Files map[character.AttachmentType]grf.ActionSpriteFilePair 23 | } 24 | 25 | type CharacterAttachmentComponentConfig struct { 26 | Gender character.GenderType 27 | JobSpriteID jobspriteid.Type 28 | HeadIndex character.HeadIndex 29 | EnableShield bool 30 | ShieldSpriteName string // Loaded from GRF 31 | } 32 | 33 | func NewCharacterAttachmentComponent( 34 | f *grf.File, 35 | conf CharacterAttachmentComponentConfig, 36 | ) (*CharacterAttachmentComponent, error) { 37 | cmp := &CharacterAttachmentComponent{ 38 | Files: make(map[character.AttachmentType]grf.ActionSpriteFilePair), 39 | } 40 | 41 | jobFileName := character.JobSpriteNameTable[conf.JobSpriteID] 42 | if "" == jobFileName { 43 | return cmp, fmt.Errorf("unsupported jobSpriteID: %v", conf.JobSpriteID) 44 | } 45 | 46 | decodedFolderA, err := getDecodedFolder([]byte{0xC0, 0xCE, 0xB0, 0xA3, 0xC1, 0xB7}) 47 | if err != nil { 48 | return cmp, errors.Wrap(err, "unable to decode folder name") 49 | } 50 | 51 | decodedFolderB, err := getDecodedFolder([]byte{0xB8, 0xF6, 0xC5, 0xEB}) 52 | if err != nil { 53 | return cmp, errors.Wrap(err, "unable to decode folder name") 54 | } 55 | 56 | genderPath := "³²" 57 | if conf.Gender == character.Female { 58 | genderPath = "¿©" 59 | } 60 | 61 | cmp.Files[character.AttachmentShadow], err = f.GetSpriteFiles("data/sprite/shadow") 62 | if err != nil { 63 | return cmp, errors.Wrapf(err, "could not load shadow act and spr files (%v, %s)", conf.Gender, conf.JobSpriteID) 64 | } 65 | 66 | bodyFilePath := "data/sprite/" + decodedFolderA + "/" + decodedFolderB + "/" + genderPath + "/" + jobFileName + "_" + genderPath 67 | cmp.Files[character.AttachmentBody], err = f.GetSpriteFiles(bodyFilePath) 68 | if err != nil { 69 | return cmp, errors.Wrapf(err, "could not load body act and spr files (%v, %s)", conf.Gender, conf.JobSpriteID) 70 | } 71 | 72 | headFilePath := "data/sprite/Àΰ£Á·/¸Ó¸®Åë/" + genderPath + "/" + strconv.Itoa(int(conf.HeadIndex)) + "_" + genderPath 73 | cmp.Files[character.AttachmentHead], err = f.GetSpriteFiles(headFilePath) 74 | if err != nil { 75 | return cmp, errors.Wrapf(err, "could not load head act and spr files (%v, %s)", conf.Gender, conf.JobSpriteID) 76 | } 77 | 78 | if conf.EnableShield { 79 | if conf.ShieldSpriteName == "" { 80 | conf.ShieldSpriteName = "°¡µå" 81 | } 82 | shieldFilePath := "data/sprite/¹æÆÐ/" + jobFileName + "/" + jobFileName + "_" + genderPath + "_" + conf.ShieldSpriteName 83 | cmp.Files[character.AttachmentShield], err = f.GetSpriteFiles(shieldFilePath) 84 | if err != nil { 85 | return cmp, errors.Wrapf(err, "could not load shield act and spr files (%v, %s, %s)", conf.Gender, conf.JobSpriteID, conf.ShieldSpriteName) 86 | } 87 | } 88 | 89 | return cmp, nil 90 | } 91 | 92 | func getDecodedFolder(buf []byte) (string, error) { 93 | folderNameBytes, err := charmap.Windows1252.NewDecoder().Bytes(buf) 94 | return string(folderNameBytes), err 95 | } 96 | -------------------------------------------------------------------------------- /internal/component/character_sprite_render_info_component.go: -------------------------------------------------------------------------------- 1 | package component 2 | 3 | import ( 4 | "github.com/project-midgard/midgarts/internal/character/actionindex" 5 | "github.com/project-midgard/midgarts/internal/character/directiontype" 6 | "time" 7 | ) 8 | 9 | type CharacterSpriteRenderInfoComponentFace interface { 10 | GetCharacterSpriteRenderInfoComponent() *CharacterSpriteRenderInfoComponent 11 | } 12 | 13 | type CharacterSpriteRenderInfoComponent struct { 14 | ActionIndex actionindex.Type 15 | AnimationDelay time.Duration 16 | AnimationEndsAt time.Time 17 | AnimationStartedAt time.Time 18 | Direction directiontype.Type 19 | ForcedDuration time.Duration 20 | FPSMultiplier float64 21 | IsStandingBy bool 22 | } 23 | 24 | func NewCharacterSpriteRenderInfoComponent() *CharacterSpriteRenderInfoComponent { 25 | now := time.Now() 26 | 27 | return &CharacterSpriteRenderInfoComponent{ 28 | ActionIndex: actionindex.Idle, 29 | AnimationStartedAt: now, 30 | AnimationEndsAt: now.Add(time.Millisecond * 100), 31 | Direction: directiontype.South, 32 | ForcedDuration: 0, 33 | FPSMultiplier: 1.0, 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /internal/component/character_state_component.go: -------------------------------------------------------------------------------- 1 | package component 2 | 3 | import ( 4 | "github.com/project-midgard/midgarts/internal/character/actionplaymode" 5 | "github.com/project-midgard/midgarts/internal/character/statetype" 6 | ) 7 | 8 | type CharacterStateComponentFace interface { 9 | GetCharacterStateComponent() *CharacterStateComponent 10 | } 11 | 12 | // CharacterStateComponent defines a component that holds information about character state, 13 | // such as the action (Idle, Walking...), the direction (South, North...) and state. 14 | type CharacterStateComponent struct { 15 | PlayMode actionplaymode.Type 16 | PreviousState, State statetype.Type 17 | } 18 | -------------------------------------------------------------------------------- /internal/entity/character.go: -------------------------------------------------------------------------------- 1 | package entity 2 | 3 | import ( 4 | "github.com/EngoEngine/ecs" 5 | "github.com/project-midgard/midgarts/internal/character" 6 | "github.com/project-midgard/midgarts/internal/character/actionplaymode" 7 | "github.com/project-midgard/midgarts/internal/character/jobspriteid" 8 | "github.com/project-midgard/midgarts/internal/character/statetype" 9 | "github.com/project-midgard/midgarts/internal/component" 10 | "github.com/project-midgard/midgarts/internal/graphic" 11 | ) 12 | 13 | type Character struct { 14 | *graphic.Transform 15 | *ecs.BasicEntity 16 | *component.CharacterAttachmentComponent 17 | *component.CharacterStateComponent 18 | *component.CharacterSpriteRenderInfoComponent 19 | 20 | HeadIndex character.HeadIndex 21 | Gender character.GenderType 22 | JobSpriteID jobspriteid.Type 23 | IsMounted bool 24 | MovementSpeed float64 25 | HasShield bool 26 | ShieldSpriteName string 27 | } 28 | 29 | func NewCharacter(gender character.GenderType, jobSpriteID jobspriteid.Type, headIndex character.HeadIndex) *Character { 30 | b := ecs.NewBasic() 31 | c := &Character{ 32 | BasicEntity: &b, 33 | CharacterStateComponent: &component.CharacterStateComponent{ 34 | PlayMode: actionplaymode.Repeat, 35 | State: statetype.StandBy, 36 | PreviousState: statetype.StandBy, 37 | }, 38 | CharacterSpriteRenderInfoComponent: component.NewCharacterSpriteRenderInfoComponent(), 39 | Transform: graphic.NewTransform(graphic.Origin), 40 | Gender: gender, 41 | JobSpriteID: jobSpriteID, 42 | HeadIndex: headIndex, 43 | IsMounted: true, 44 | MovementSpeed: 1.25, 45 | } 46 | 47 | return c 48 | } 49 | 50 | func (c *Character) SetCharacterStateComponent(component *component.CharacterStateComponent) { 51 | c.CharacterStateComponent = component 52 | } 53 | 54 | func (c *Character) SetCharacterAttachmentComponent(component *component.CharacterAttachmentComponent) { 55 | c.CharacterAttachmentComponent = component 56 | } 57 | 58 | func (c *Character) GetCharacterStateComponent() *component.CharacterStateComponent { 59 | return c.CharacterStateComponent 60 | } 61 | 62 | func (c *Character) GetCharacterAttachmentComponent() *component.CharacterAttachmentComponent { 63 | return c.CharacterAttachmentComponent 64 | } 65 | 66 | func (c *Character) GetCharacterSpriteRenderInfoComponent() *component.CharacterSpriteRenderInfoComponent { 67 | return c.CharacterSpriteRenderInfoComponent 68 | } 69 | 70 | func (c *Character) SetState(state statetype.Type) { 71 | c.PreviousState = c.State 72 | c.State = state 73 | } 74 | -------------------------------------------------------------------------------- /internal/fileformat/act/act_file.go: -------------------------------------------------------------------------------- 1 | package act 2 | 3 | import ( 4 | "bytes" 5 | "encoding/binary" 6 | "fmt" 7 | "github.com/project-midgard/midgarts/internal/bytesutil" 8 | "image/color" 9 | "io" 10 | ) 11 | 12 | const ( 13 | HeaderSignature = "AC" 14 | 15 | ActionDefaultDelay = 100 16 | ) 17 | 18 | type ActionFrameLayer struct { 19 | Index int32 20 | Position [2]int32 21 | SpriteFrameIndex int32 22 | Mirrored bool 23 | Scale [2]float32 24 | Color *color.RGBA 25 | Angle int32 26 | SpriteType int32 27 | Width int32 28 | Height int32 29 | } 30 | 31 | type ActionFrame struct { 32 | Layers []*ActionFrameLayer 33 | Sound int32 34 | Positions [][2]int32 35 | } 36 | 37 | type Action struct { 38 | Frames []*ActionFrame 39 | Delay uint32 40 | DurationMilliseconds uint32 41 | } 42 | 43 | type ActionFile struct { 44 | Header struct { 45 | Signature string 46 | Version float32 47 | } 48 | 49 | ActionCount uint16 50 | Actions []*Action 51 | 52 | Sounds []string 53 | } 54 | 55 | func Load(data []byte) (*ActionFile, error) { 56 | f := new(ActionFile) 57 | 58 | reader := bytes.NewReader(data) 59 | if err := f.loadHeader(reader); err != nil { 60 | return nil, err 61 | } 62 | 63 | if err := f.loadActions(reader); err != nil { 64 | return nil, err 65 | } 66 | 67 | if f.Header.Version > 2.1 { 68 | // Sound 69 | var soundLen int32 70 | _ = binary.Read(reader, binary.LittleEndian, &soundLen) 71 | f.Sounds = make([]string, soundLen) 72 | 73 | for i := 0; i < len(f.Sounds); i++ { 74 | var b [40]byte 75 | _ = binary.Read(reader, binary.LittleEndian, &b) 76 | 77 | f.Sounds[i] = string(b[:]) 78 | } 79 | } 80 | 81 | for i := 0; i < int(f.ActionCount); i++ { 82 | var d float32 83 | _ = binary.Read(reader, binary.LittleEndian, &d) 84 | 85 | act := f.Actions[i] 86 | f.Actions[i].Delay = uint32(d * 25.0) 87 | f.Actions[i].DurationMilliseconds = act.Delay * uint32(len(act.Frames)) 88 | } 89 | 90 | return f, nil 91 | } 92 | 93 | func (f *ActionFile) loadHeader(buf io.ReadSeeker) error { 94 | var signature [2]byte 95 | _ = binary.Read(buf, binary.LittleEndian, &signature) 96 | 97 | signatureStr := string(signature[:]) 98 | if signatureStr != HeaderSignature { 99 | return fmt.Errorf("invalid signature: %s\n", signature) 100 | } 101 | 102 | var major, minor byte 103 | _ = binary.Read(buf, binary.LittleEndian, &major) 104 | _ = binary.Read(buf, binary.LittleEndian, &minor) 105 | 106 | var actionCount uint16 107 | _ = binary.Read(buf, binary.LittleEndian, &actionCount) 108 | 109 | f.Header.Signature = signatureStr 110 | f.Header.Version = float32(major)/10 + float32(minor) 111 | f.ActionCount = actionCount 112 | f.Actions = make([]*Action, f.ActionCount) 113 | 114 | if err := bytesutil.SkipBytes(buf, 10); err != nil { 115 | return err 116 | } 117 | 118 | return nil 119 | } 120 | 121 | func (f *ActionFile) loadActions(buf io.ReadSeeker) error { 122 | var ( 123 | count = int(f.ActionCount) 124 | ) 125 | 126 | _ = binary.Read(buf, binary.LittleEndian, &count) 127 | 128 | for i := 0; i < count; i++ { 129 | f.Actions[i] = &Action{ 130 | Frames: f.loadActionFrames(buf), 131 | Delay: ActionDefaultDelay, 132 | DurationMilliseconds: 0, 133 | } 134 | } 135 | 136 | return nil 137 | } 138 | 139 | func (f *ActionFile) loadActionFrames(buf io.ReadSeeker) []*ActionFrame { 140 | var ( 141 | frames []*ActionFrame 142 | frameCount uint32 143 | sound int32 144 | posCount int32 145 | ) 146 | 147 | _ = binary.Read(buf, binary.LittleEndian, &frameCount) 148 | frames = make([]*ActionFrame, int(frameCount)) 149 | 150 | for i := 0; i < int(frameCount); i++ { 151 | _ = bytesutil.SkipBytes(buf, 32) 152 | 153 | positions := make([][2]int32, frameCount) 154 | layers := f.loadActionFrameLayers(buf) 155 | 156 | if f.Header.Version >= 2.0 { 157 | _ = binary.Read(buf, binary.LittleEndian, &sound) 158 | } else { 159 | sound = -1 160 | } 161 | 162 | if f.Header.Version >= 2.3 { 163 | _ = binary.Read(buf, binary.LittleEndian, &posCount) 164 | 165 | for i := 0; i < int(posCount); i++ { 166 | _ = bytesutil.SkipBytes(buf, 4) 167 | 168 | var a, b int32 169 | _ = binary.Read(buf, binary.LittleEndian, &a) 170 | _ = binary.Read(buf, binary.LittleEndian, &b) 171 | 172 | positions[i][0] = a 173 | positions[i][1] = b 174 | 175 | _ = bytesutil.SkipBytes(buf, 4) 176 | } 177 | } 178 | 179 | frames[i] = &ActionFrame{ 180 | Layers: layers, 181 | Sound: sound, 182 | Positions: positions, 183 | } 184 | } 185 | 186 | return frames 187 | } 188 | 189 | func (f *ActionFile) loadActionFrameLayers(buf io.ReadSeeker) []*ActionFrameLayer { 190 | var ( 191 | layers []*ActionFrameLayer 192 | layerCount uint32 193 | 194 | pos [2]int32 195 | spriteFrameIndex int32 196 | mirrored int32 197 | r, g, b, a byte 198 | scale [2]float32 199 | angle, spriteType, width, height int32 200 | ) 201 | 202 | _ = binary.Read(buf, binary.LittleEndian, &layerCount) 203 | layers = make([]*ActionFrameLayer, int(layerCount)) 204 | 205 | for i := 0; i < int(layerCount); i++ { 206 | _ = binary.Read(buf, binary.LittleEndian, &pos[0]) 207 | _ = binary.Read(buf, binary.LittleEndian, &pos[1]) 208 | _ = binary.Read(buf, binary.LittleEndian, &spriteFrameIndex) 209 | _ = binary.Read(buf, binary.LittleEndian, &mirrored) 210 | 211 | if f.Header.Version >= 2.0 { 212 | _ = binary.Read(buf, binary.LittleEndian, &r) 213 | _ = binary.Read(buf, binary.LittleEndian, &g) 214 | _ = binary.Read(buf, binary.LittleEndian, &b) 215 | _ = binary.Read(buf, binary.LittleEndian, &a) 216 | } else { 217 | r, g, b, a = 255, 255, 255, 255 218 | } 219 | 220 | if f.Header.Version >= 2.0 { 221 | _ = binary.Read(buf, binary.LittleEndian, &scale[0]) 222 | 223 | if f.Header.Version <= 2.3 { 224 | scale[1] = scale[0] 225 | } else { 226 | _ = binary.Read(buf, binary.LittleEndian, &scale[1]) 227 | } 228 | } 229 | 230 | if f.Header.Version >= 2.0 { 231 | _ = binary.Read(buf, binary.LittleEndian, &angle) 232 | _ = binary.Read(buf, binary.LittleEndian, &spriteType) 233 | 234 | if f.Header.Version >= 2.5 { 235 | _ = binary.Read(buf, binary.LittleEndian, &width) 236 | _ = binary.Read(buf, binary.LittleEndian, &height) 237 | } 238 | } 239 | 240 | layers[i] = &ActionFrameLayer{ 241 | Index: int32(i), 242 | Position: pos, 243 | SpriteFrameIndex: spriteFrameIndex, 244 | Mirrored: mirrored != 0, 245 | Scale: scale, 246 | Color: &color.RGBA{R: r, G: g, B: b, A: a}, 247 | Angle: angle, 248 | SpriteType: spriteType, 249 | Width: width, 250 | Height: height, 251 | } 252 | } 253 | 254 | return layers 255 | } 256 | -------------------------------------------------------------------------------- /internal/fileformat/gat/gat_file.go: -------------------------------------------------------------------------------- 1 | package gat 2 | 3 | import ( 4 | "bytes" 5 | "encoding/binary" 6 | "fmt" 7 | 8 | "github.com/project-midgard/midgarts/internal/romap" 9 | ) 10 | 11 | const HeaderSignature = "GRAT" 12 | 13 | const ( 14 | None = romap.CellTypeNone 15 | Walkable = romap.CellTypeWalkable 16 | Water = romap.CellTypeWater 17 | Snipable = romap.CellTypeSnipable 18 | ) 19 | 20 | var TypeTable = [7]romap.CellType{ 21 | Walkable | Snipable, // walkable ground 22 | None, // non-walkable ground 23 | Walkable | Snipable, // ??? 24 | Walkable | Snipable | Water, // walkable water 25 | Walkable | Snipable, // ??? 26 | Snipable, // gat (snipable) 27 | Walkable | Snipable, // ??? 28 | } 29 | 30 | type Cell struct { 31 | Cells [4]float32 32 | CellType romap.CellType 33 | } 34 | 35 | type GroundAltitudeFile struct { 36 | Version float32 37 | Width uint32 38 | Height uint32 39 | Cells []Cell 40 | } 41 | 42 | type BlockingRectangle struct { 43 | } 44 | 45 | func Load(data []byte) (f *GroundAltitudeFile, err error) { 46 | f = new(GroundAltitudeFile) 47 | reader := bytes.NewReader(data) 48 | 49 | var signature [4]byte 50 | _ = binary.Read(reader, binary.LittleEndian, &signature) 51 | 52 | if string(signature[:]) != HeaderSignature { 53 | return nil, fmt.Errorf("invalid file header signature: %s", signature) 54 | } 55 | 56 | var a, b byte 57 | _ = binary.Read(reader, binary.LittleEndian, &a) 58 | _ = binary.Read(reader, binary.LittleEndian, &b) 59 | f.Version = float32(a) + float32(b)/10 60 | 61 | var w, h uint32 62 | _ = binary.Read(reader, binary.LittleEndian, &w) 63 | _ = binary.Read(reader, binary.LittleEndian, &h) 64 | f.Width = w 65 | f.Height = h 66 | 67 | cellCount := w * h 68 | f.Cells = make([]Cell, cellCount) 69 | for i := 0; i < int(cellCount); i++ { 70 | var h1, h2, h3, h4 float32 71 | _ = binary.Read(reader, binary.LittleEndian, &h1) 72 | _ = binary.Read(reader, binary.LittleEndian, &h2) 73 | _ = binary.Read(reader, binary.LittleEndian, &h3) 74 | _ = binary.Read(reader, binary.LittleEndian, &h4) 75 | 76 | var t uint32 77 | _ = binary.Read(reader, binary.LittleEndian, &t) 78 | 79 | f.Cells[i] = Cell{ 80 | Cells: [4]float32{h1, h2, h3, h4}, 81 | CellType: TypeTable[t], 82 | } 83 | } 84 | 85 | //log.Printf("gat.GroundAltitudeFile(%v)", f) 86 | 87 | return nil, nil 88 | } 89 | -------------------------------------------------------------------------------- /internal/fileformat/gnd/gnd_file.go: -------------------------------------------------------------------------------- 1 | package gnd 2 | 3 | import ( 4 | "bytes" 5 | "encoding/binary" 6 | "github.com/project-midgard/midgarts/internal/bytesutil" 7 | "io" 8 | "log" 9 | 10 | "golang.org/x/text/encoding/charmap" 11 | ) 12 | 13 | type GroundFile struct { 14 | Version float32 15 | Width, Height uint32 16 | Zoom float32 17 | Textures []string 18 | TextureIndices []int64 19 | } 20 | 21 | type LightMapData struct { 22 | PerCell uint32 23 | Count uint32 24 | Data []byte 25 | } 26 | 27 | func Load(data []byte) (f *GroundFile, err error) { 28 | f = new(GroundFile) 29 | reader := bytes.NewReader(data) 30 | 31 | var signature [4]byte 32 | _ = binary.Read(reader, binary.LittleEndian, &signature) 33 | 34 | var a, b uint8 35 | _ = binary.Read(reader, binary.LittleEndian, &a) 36 | _ = binary.Read(reader, binary.LittleEndian, &b) 37 | f.Version = float32(a) + float32(b)/10 38 | 39 | var w, h uint32 40 | _ = binary.Read(reader, binary.LittleEndian, &w) 41 | _ = binary.Read(reader, binary.LittleEndian, &h) 42 | 43 | var zoom float32 44 | _ = binary.Read(reader, binary.LittleEndian, &zoom) 45 | 46 | f.Width = w 47 | f.Height = h 48 | f.Zoom = zoom 49 | 50 | err = f.loadTextures(reader) 51 | if err != nil { 52 | log.Fatal(err) 53 | } 54 | 55 | err = f.loadLightMaps(reader) 56 | if err != nil { 57 | log.Fatal(err) 58 | } 59 | 60 | //log.Printf("%#v\n", f) 61 | 62 | return f, nil 63 | } 64 | 65 | func (f *GroundFile) loadTextures(buf io.Reader) error { 66 | var textureCount, texturePathLength uint32 67 | _ = binary.Read(buf, binary.LittleEndian, &textureCount) 68 | _ = binary.Read(buf, binary.LittleEndian, &texturePathLength) 69 | 70 | var textures []string 71 | lookUpList := make([]int64, textureCount) 72 | 73 | for i := 0; i < int(textureCount); i++ { 74 | name, err := bytesutil.ReadString(buf, int(texturePathLength)) 75 | if err != nil { 76 | log.Fatal(err) 77 | } 78 | 79 | pos := -1 80 | for k, n := range textures { 81 | if name == n { 82 | pos = k 83 | break 84 | } 85 | } 86 | 87 | if pos == -1 { 88 | var decodedName string 89 | if decodedName, err = charmap.Windows1252.NewDecoder().String( 90 | name, 91 | ); err != nil { 92 | panic(err) 93 | } 94 | 95 | textures = append(textures, decodedName) 96 | pos = len(textures) - 1 97 | } 98 | 99 | lookUpList[i] = int64(pos) 100 | } 101 | 102 | f.Textures = textures 103 | f.TextureIndices = lookUpList 104 | 105 | return nil 106 | } 107 | 108 | func (f *GroundFile) loadLightMaps(buf io.Reader) error { 109 | var count uint32 110 | _ = binary.Read(buf, binary.LittleEndian, &count) 111 | 112 | var perCellX, perCellY uint32 113 | _ = binary.Read(buf, binary.LittleEndian, &perCellX) 114 | _ = binary.Read(buf, binary.LittleEndian, &perCellY) 115 | 116 | var sizeCell uint32 117 | _ = binary.Read(buf, binary.LittleEndian, &sizeCell) 118 | 119 | perCell := perCellX * perCellY * sizeCell 120 | 121 | _ = perCell 122 | 123 | return nil 124 | } 125 | -------------------------------------------------------------------------------- /internal/fileformat/grf/des/des.go: -------------------------------------------------------------------------------- 1 | package des 2 | 3 | import "strconv" 4 | 5 | var ( 6 | mask = [8]byte{0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01} 7 | tmp2 = make([]byte, 8) 8 | tmp = make([]byte, 8) 9 | clean = make([]byte, 8) 10 | 11 | initialPermutationTable = []byte{ 12 | 58, 50, 42, 34, 26, 18, 10, 2, 13 | 60, 52, 44, 36, 28, 20, 12, 4, 14 | 62, 54, 46, 38, 30, 22, 14, 6, 15 | 64, 56, 48, 40, 32, 24, 16, 8, 16 | 57, 49, 41, 33, 25, 17, 9, 1, 17 | 59, 51, 43, 35, 27, 19, 11, 3, 18 | 61, 53, 45, 37, 29, 21, 13, 5, 19 | 63, 55, 47, 39, 31, 23, 15, 7, 20 | } 21 | 22 | finalPermutationTable = []byte{ 23 | 40, 8, 48, 16, 56, 24, 64, 32, 24 | 39, 7, 47, 15, 55, 23, 63, 31, 25 | 38, 6, 46, 14, 54, 22, 62, 30, 26 | 37, 5, 45, 13, 53, 21, 61, 29, 27 | 36, 4, 44, 12, 52, 20, 60, 28, 28 | 35, 3, 43, 11, 51, 19, 59, 27, 29 | 34, 2, 42, 10, 50, 18, 58, 26, 30 | 33, 1, 41, 9, 49, 17, 57, 25, 31 | } 32 | 33 | transpositionTable = []byte{ 34 | 16, 7, 20, 21, 35 | 29, 12, 28, 17, 36 | 1, 15, 23, 26, 37 | 5, 18, 31, 10, 38 | 2, 8, 24, 14, 39 | 32, 27, 3, 9, 40 | 19, 13, 30, 6, 41 | 22, 11, 4, 25, 42 | } 43 | 44 | substitutionBoxTable = [][]byte{ 45 | { 46 | 0xef, 0x03, 0x41, 0xfd, 0xd8, 0x74, 0x1e, 0x47, 0x26, 0xef, 0xfb, 0x22, 0xb3, 0xd8, 0x84, 0x1e, 47 | 0x39, 0xac, 0xa7, 0x60, 0x62, 0xc1, 0xcd, 0xba, 0x5c, 0x96, 0x90, 0x59, 0x05, 0x3b, 0x7a, 0x85, 48 | 0x40, 0xfd, 0x1e, 0xc8, 0xe7, 0x8a, 0x8b, 0x21, 0xda, 0x43, 0x64, 0x9f, 0x2d, 0x14, 0xb1, 0x72, 49 | 0xf5, 0x5b, 0xc8, 0xb6, 0x9c, 0x37, 0x76, 0xec, 0x39, 0xa0, 0xa3, 0x05, 0x52, 0x6e, 0x0f, 0xd9, 50 | }, 51 | { 52 | 0xa7, 0xdd, 0x0d, 0x78, 0x9e, 0x0b, 0xe3, 0x95, 0x60, 0x36, 0x36, 0x4f, 0xf9, 0x60, 0x5a, 0xa3, 53 | 0x11, 0x24, 0xd2, 0x87, 0xc8, 0x52, 0x75, 0xec, 0xbb, 0xc1, 0x4c, 0xba, 0x24, 0xfe, 0x8f, 0x19, 54 | 0xda, 0x13, 0x66, 0xaf, 0x49, 0xd0, 0x90, 0x06, 0x8c, 0x6a, 0xfb, 0x91, 0x37, 0x8d, 0x0d, 0x78, 55 | 0xbf, 0x49, 0x11, 0xf4, 0x23, 0xe5, 0xce, 0x3b, 0x55, 0xbc, 0xa2, 0x57, 0xe8, 0x22, 0x74, 0xce, 56 | }, 57 | { 58 | 0x2c, 0xea, 0xc1, 0xbf, 0x4a, 0x24, 0x1f, 0xc2, 0x79, 0x47, 0xa2, 0x7c, 0xb6, 0xd9, 0x68, 0x15, 59 | 0x80, 0x56, 0x5d, 0x01, 0x33, 0xfd, 0xf4, 0xae, 0xde, 0x30, 0x07, 0x9b, 0xe5, 0x83, 0x9b, 0x68, 60 | 0x49, 0xb4, 0x2e, 0x83, 0x1f, 0xc2, 0xb5, 0x7c, 0xa2, 0x19, 0xd8, 0xe5, 0x7c, 0x2f, 0x83, 0xda, 61 | 0xf7, 0x6b, 0x90, 0xfe, 0xc4, 0x01, 0x5a, 0x97, 0x61, 0xa6, 0x3d, 0x40, 0x0b, 0x58, 0xe6, 0x3d, 62 | }, 63 | { 64 | 0x4d, 0xd1, 0xb2, 0x0f, 0x28, 0xbd, 0xe4, 0x78, 0xf6, 0x4a, 0x0f, 0x93, 0x8b, 0x17, 0xd1, 0xa4, 65 | 0x3a, 0xec, 0xc9, 0x35, 0x93, 0x56, 0x7e, 0xcb, 0x55, 0x20, 0xa0, 0xfe, 0x6c, 0x89, 0x17, 0x62, 66 | 0x17, 0x62, 0x4b, 0xb1, 0xb4, 0xde, 0xd1, 0x87, 0xc9, 0x14, 0x3c, 0x4a, 0x7e, 0xa8, 0xe2, 0x7d, 67 | 0xa0, 0x9f, 0xf6, 0x5c, 0x6a, 0x09, 0x8d, 0xf0, 0x0f, 0xe3, 0x53, 0x25, 0x95, 0x36, 0x28, 0xcb, 68 | }, 69 | } 70 | ) 71 | 72 | func DecodeFull(src []byte, length int, entryLength int) { 73 | var ( 74 | count = length >> 3 75 | digits = len(strconv.Itoa(entryLength)) 76 | cycle int 77 | ) 78 | 79 | // choose size of gap between two encrypted blocks 80 | // digits: 0 1 2 3 4 5 6 7 8 9 ... 81 | // cycle: 1 1 1 4 5 14 15 22 23 24 ... 82 | switch { 83 | case digits < 3: 84 | cycle = 1 85 | break 86 | case digits < 5: 87 | cycle = digits + 1 88 | break 89 | case digits < 7: 90 | cycle = digits + 9 91 | break 92 | default: 93 | cycle = digits + 15 94 | } 95 | 96 | // first 20 blocks are all des-encrypted 97 | for i := 0; i < 20 && i < count; i++ { 98 | decryptBlock(src, i*8) 99 | } 100 | 101 | for i, j := 20, -1; i < count; i++ { 102 | // decrypt block 103 | if i%cycle == 0 { 104 | decryptBlock(src, i*8) 105 | continue 106 | } 107 | 108 | j++ 109 | 110 | // de-shuffle block 111 | if j != 0 && j%7 == 0 { 112 | shuffleDec(src, i*8) 113 | } 114 | } 115 | } 116 | 117 | func DecodeHeader(src []byte) { 118 | count := len(src) >> 3 119 | 120 | // first 20 blocks are all des-encrypted 121 | for i := 0; i < 20 && i < count; i++ { 122 | decryptBlock(src, i*8) 123 | } 124 | } 125 | 126 | func decryptBlock(src []byte, index int) { 127 | initialPermutation(src, index) 128 | roundFunction(src, index) 129 | finalPermutation(src, index) 130 | } 131 | 132 | func initialPermutation(src []byte, index int) { 133 | var j int 134 | 135 | for i := 0; i < 64; i++ { 136 | j = int(initialPermutationTable[i]) - 1 137 | if src[index+((j>>3)&7)]&mask[j&7] != 0 { 138 | tmp[(i>>3)&7] |= mask[i&7] 139 | } 140 | } 141 | 142 | appendAt(src, tmp, index) 143 | appendAt(tmp, clean, 0) 144 | } 145 | 146 | func roundFunction(src []byte, index int) { 147 | for i := 0; i < 8; i++ { 148 | tmp2[i] = src[index+i] 149 | } 150 | 151 | expansion(tmp2, 0) 152 | substitutionBox(tmp2, 0) 153 | transposition(tmp2, 0) 154 | 155 | src[index+0] ^= tmp2[4] 156 | src[index+1] ^= tmp2[5] 157 | src[index+2] ^= tmp2[6] 158 | src[index+3] ^= tmp2[7] 159 | } 160 | 161 | func finalPermutation(src []byte, index int) { 162 | var j int 163 | 164 | for i := 0; i < 64; i++ { 165 | j = int(finalPermutationTable[i]) - 1 166 | if src[index+((j>>3)&7)]&mask[j&7] != 0 { 167 | tmp[(i>>3)&7] |= mask[i&7] 168 | } 169 | } 170 | 171 | appendAt(src, tmp, index) 172 | appendAt(tmp, clean, 0) 173 | } 174 | 175 | func transposition(src []byte, index int) { 176 | var j int 177 | 178 | for i := 0; i < 32; i++ { 179 | j = int(transpositionTable[i]) - 1 180 | if (src[index+(j>>3)])&mask[j&7] != 0 { 181 | tmp[(i>>3)+4] |= mask[i&7] 182 | } 183 | } 184 | 185 | appendAt(src, tmp, index) 186 | appendAt(tmp, clean, 0) 187 | } 188 | 189 | func substitutionBox(src []byte, index int) { 190 | for i := 0; i < 4; i++ { 191 | tmp[i] = substitutionBoxTable[i][src[i*2+0+index]]&0xf0 | 192 | substitutionBoxTable[i][src[i*2+1+index]]&0x0f 193 | } 194 | 195 | appendAt(src, tmp, index) 196 | appendAt(tmp, clean, 0) 197 | } 198 | 199 | func expansion(src []byte, index int) { 200 | tmp[0] = ((src[index+7] << 5) | (src[index+4] >> 3)) & 0x3f // ..0 vutsr 201 | tmp[1] = ((src[index+4] << 1) | (src[index+5] >> 7)) & 0x3f // ..srqpo n 202 | tmp[2] = ((src[index+4] << 5) | (src[index+5] >> 3)) & 0x3f // ..o nmlkj 203 | tmp[3] = ((src[index+5] << 1) | (src[index+6] >> 7)) & 0x3f // ..kjihg f 204 | tmp[4] = ((src[index+5] << 5) | (src[index+6] >> 3)) & 0x3f // ..g fedcb 205 | tmp[5] = ((src[index+6] << 1) | (src[index+7] >> 7)) & 0x3f // ..cba98 7 206 | tmp[6] = ((src[index+6] << 5) | (src[index+7] >> 3)) & 0x3f // ..8 76543 207 | tmp[7] = ((src[index+7] << 1) | (src[index+4] >> 7)) & 0x3f // ..43210 v 208 | 209 | appendAt(src, tmp, index) 210 | appendAt(tmp, clean, 0) 211 | } 212 | func shuffleDec(src []byte, index int) { 213 | var shuffleDecTable = func() [256]byte { 214 | var ( 215 | i, count int 216 | out = [256]byte{} 217 | list = []byte{0x00, 0x2b, 0x6c, 0x80, 0x01, 0x68, 0x48, 0x77, 0x60, 0xff, 0xb9, 0xc0, 0xfe, 0xeb} 218 | ) 219 | 220 | for i := 0; i < 256; i++ { 221 | out[i] = byte(i) 222 | } 223 | 224 | for i, count = 0, len(list); i < count; i += 2 { 225 | out[list[i+0]] = list[i+1] 226 | out[list[i+1]] = list[i+0] 227 | } 228 | 229 | return out 230 | }() 231 | 232 | tmp[0] = src[index+3] 233 | tmp[1] = src[index+4] 234 | tmp[2] = src[index+6] 235 | tmp[3] = src[index+0] 236 | tmp[4] = src[index+1] 237 | tmp[5] = src[index+2] 238 | tmp[6] = src[index+5] 239 | tmp[7] = shuffleDecTable[src[index+7]] 240 | appendAt(src, tmp, index) 241 | appendAt(tmp, clean, 0) 242 | } 243 | 244 | func appendAt(slice []byte, elems []byte, index int) { 245 | copy(slice[index:], elems) 246 | } 247 | -------------------------------------------------------------------------------- /internal/fileformat/grf/grf_entry.go: -------------------------------------------------------------------------------- 1 | package grf 2 | 3 | import ( 4 | "github.com/pkg/errors" 5 | "github.com/project-midgard/midgarts/internal/fileformat/grf/des" 6 | ) 7 | 8 | type entryFlags byte 9 | 10 | const ( 11 | entryHeaderLength = 4 + 4 + 4 + 1 + 4 12 | 13 | entryType entryFlags = 0x01 14 | entryTypeEncryptMixed = 0x02 15 | entryTypeEncryptHeader = 0x04 16 | ) 17 | 18 | // EntryHeader ... 19 | type EntryHeader struct { 20 | CompressedSize uint32 21 | CompressedSizeAligned uint32 22 | UncompressedSize uint32 23 | Flags entryFlags 24 | Offset uint32 25 | } 26 | 27 | // Entry ... 28 | type Entry struct { 29 | Name string 30 | Header EntryHeader 31 | Data []byte 32 | } 33 | 34 | // Decode ... 35 | func (e *Entry) Decode(data []byte) error { 36 | if e.Header.Flags&entryTypeEncryptMixed != 0 { 37 | des.DecodeFull(data, int(e.Header.CompressedSizeAligned), int(e.Header.CompressedSize)) 38 | } else if e.Header.Flags&entryTypeEncryptHeader != 0 { 39 | des.DecodeHeader(data) 40 | } 41 | 42 | if e.Header.CompressedSize == e.Header.UncompressedSize { 43 | e.Data = data 44 | return nil 45 | } 46 | 47 | data, err := decompress(data) 48 | if err != nil { 49 | return errors.Wrap(err, "could not decompress entry data") 50 | } 51 | e.Data = data 52 | 53 | return nil 54 | } 55 | -------------------------------------------------------------------------------- /internal/fileformat/grf/grf_entry_tree.go: -------------------------------------------------------------------------------- 1 | package grf 2 | 3 | import "github.com/pkg/errors" 4 | 5 | type EntryTree struct { 6 | Root *EntryTreeNode 7 | } 8 | 9 | func (t *EntryTree) Traverse(n *EntryTreeNode, f func(*EntryTreeNode)) { 10 | if n == nil { 11 | return 12 | } 13 | 14 | t.Traverse(n.Left, f) 15 | f(n) 16 | t.Traverse(n.Right, f) 17 | } 18 | 19 | func (t *EntryTree) Insert(value string, data []*Entry) error { 20 | if t.Root == nil { 21 | t.Root = &EntryTreeNode{Value: value, Data: data} 22 | return nil 23 | } 24 | 25 | return t.Root.Insert(value, data) 26 | } 27 | 28 | func (t *EntryTree) Find(s string) ([]*Entry, bool) { 29 | if t.Root == nil { 30 | return nil, false 31 | } 32 | 33 | return t.Root.Find(s) 34 | } 35 | 36 | type EntryTreeNode struct { 37 | Value string 38 | Data []*Entry 39 | Left *EntryTreeNode 40 | Right *EntryTreeNode 41 | } 42 | 43 | func (n *EntryTreeNode) Insert(value string, data []*Entry) error { 44 | if n == nil { 45 | return errors.New("could not insert value: nil tree") 46 | } 47 | 48 | switch { 49 | case value == n.Value: 50 | return nil 51 | case value < n.Value: 52 | { 53 | if n.Left == nil { 54 | n.Left = &EntryTreeNode{ 55 | Value: value, 56 | Data: data, 57 | } 58 | 59 | return nil 60 | } 61 | 62 | return n.Left.Insert(value, data) 63 | } 64 | case value > n.Value: 65 | { 66 | if n.Right == nil { 67 | n.Right = &EntryTreeNode{ 68 | Value: value, 69 | Data: data, 70 | } 71 | 72 | return nil 73 | } 74 | 75 | return n.Right.Insert(value, data) 76 | } 77 | } 78 | 79 | return nil 80 | } 81 | 82 | func (n *EntryTreeNode) Find(s string) ([]*Entry, bool) { 83 | if n == nil { 84 | return nil, false 85 | } 86 | 87 | switch { 88 | case s == n.Value: 89 | return n.Data, true 90 | case s < n.Value: 91 | return n.Left.Find(s) 92 | default: 93 | return n.Right.Find(s) 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /internal/fileformat/grf/grf_file.go: -------------------------------------------------------------------------------- 1 | package grf 2 | 3 | import ( 4 | "bufio" 5 | "compress/zlib" 6 | "encoding/binary" 7 | "fmt" 8 | "github.com/project-midgard/midgarts/internal/fileformat/act" 9 | "github.com/project-midgard/midgarts/internal/fileformat/spr" 10 | "io" 11 | "os" 12 | "path/filepath" 13 | "sort" 14 | "strings" 15 | 16 | "github.com/pkg/errors" 17 | "golang.org/x/text/encoding/charmap" 18 | ) 19 | 20 | const ( 21 | fileHeaderLength = 46 22 | fileHeaderSignature = "Master of Magic" 23 | ) 24 | 25 | type File struct { 26 | Header struct { 27 | Signature [15]byte 28 | EncryptionKey [15]byte 29 | FileTableOffset uint32 30 | EntryCount uint32 31 | ReservedFiles uint32 32 | Version uint32 33 | } 34 | 35 | // Maps to directory -> array of entries 36 | entries map[string][]*Entry 37 | entriesTree *EntryTree 38 | 39 | file *os.File 40 | } 41 | 42 | func Load(path string) (*File, error) { 43 | f, err := os.Open(path) 44 | if err != nil { 45 | return nil, err 46 | } 47 | 48 | fi, err := f.Stat() 49 | if err != nil { 50 | return nil, err 51 | } 52 | 53 | grfFile := &File{file: f, entriesTree: &EntryTree{}} 54 | 55 | err = grfFile.parseHeader(f, fi) 56 | if err != nil { 57 | return nil, errors.Wrap(err, "could not read header") 58 | } 59 | 60 | err = grfFile.parseEntries(f) 61 | if err != nil { 62 | return nil, errors.Wrap(err, "could not read entries") 63 | } 64 | 65 | return grfFile, nil 66 | } 67 | 68 | func (f *File) GetEntryDirectories() map[string][]*Entry { 69 | return f.entries 70 | } 71 | 72 | func (f *File) GetEntries(dir string) []*Entry { 73 | return f.entries[dir] 74 | } 75 | 76 | func (f *File) GetEntryTree() *EntryTree { 77 | return f.entriesTree 78 | } 79 | 80 | func (f *File) GetEntry(name string) (entry *Entry, err error) { 81 | name = strings.ToLower(name) 82 | var entries []*Entry 83 | var exists bool 84 | dir, _ := filepath.Split(name) 85 | dir = strings.TrimSuffix(dir, `/`) 86 | 87 | if entries, exists = f.entriesTree.Find(dir); !exists { 88 | return entry, fmt.Errorf("could not find directory '%s'", dir) 89 | } 90 | 91 | for _, e := range entries { 92 | if e.Name == name { 93 | entry = e 94 | break 95 | } 96 | } 97 | 98 | if entry == nil { 99 | return nil, fmt.Errorf("could not find entry '%s'", name) 100 | } 101 | 102 | if len(entry.Data) != 0 { 103 | return entry, nil 104 | } 105 | 106 | _, err = f.file.Seek(int64(entry.Header.Offset)+fileHeaderLength, io.SeekStart) 107 | if err != nil { 108 | return entry, err 109 | } 110 | 111 | data, err := readNextBytes(f.file, int(entry.Header.CompressedSizeAligned)) 112 | if err != nil { 113 | return entry, err 114 | } 115 | 116 | if err = entry.Decode(data); err != nil { 117 | return entry, err 118 | } 119 | 120 | return 121 | } 122 | 123 | type ActionSpriteFilePair struct { 124 | ACT *act.ActionFile 125 | SPR *spr.SpriteFile 126 | } 127 | 128 | func (f *File) GetSpriteFiles(name string) (ActionSpriteFilePair, error) { 129 | e, err := f.GetEntry(fmt.Sprintf("%s.act", name)) 130 | if err != nil { 131 | return ActionSpriteFilePair{}, err 132 | } 133 | 134 | actFile, err := act.Load(e.Data) 135 | if err != nil { 136 | return ActionSpriteFilePair{}, err 137 | } 138 | 139 | e, err = f.GetEntry(fmt.Sprintf("%s.spr", name)) 140 | if err != nil { 141 | return ActionSpriteFilePair{}, err 142 | } 143 | 144 | sprFile, err := spr.Load(e.Data) 145 | if err != nil { 146 | return ActionSpriteFilePair{}, err 147 | } 148 | 149 | return ActionSpriteFilePair{ 150 | ACT: actFile, 151 | SPR: sprFile, 152 | }, nil 153 | } 154 | 155 | func (f *File) Close() error { 156 | return f.file.Close() 157 | } 158 | 159 | func (f *File) parseHeader(file *os.File, fi os.FileInfo) error { 160 | err := binary.Read(file, binary.LittleEndian, &f.Header) 161 | if err != nil { 162 | return errors.Wrap(err, "could not read file") 163 | } 164 | 165 | sig := string(f.Header.Signature[:]) 166 | if sig != fileHeaderSignature { 167 | return fmt.Errorf("invalid file signature '%s'", sig) 168 | } 169 | 170 | if f.Header.Version != 0x200 { 171 | return errors.New("unsupported file version") 172 | } 173 | 174 | f.Header.FileTableOffset += fileHeaderLength 175 | 176 | if f.Header.FileTableOffset > uint32(fi.Size()) || f.Header.FileTableOffset < 0 { 177 | return errors.New("invalid file table offset") 178 | } 179 | 180 | f.Header.EntryCount = f.Header.ReservedFiles - f.Header.EntryCount - 7 181 | f.entries = make(map[string][]*Entry, f.Header.EntryCount) 182 | 183 | return nil 184 | } 185 | 186 | func (f *File) parseEntries(file *os.File) error { 187 | _, _ = file.Seek(int64(f.Header.FileTableOffset), io.SeekStart) 188 | 189 | var compressedSize, uncompressedSize uint32 190 | 191 | _ = binary.Read(file, binary.LittleEndian, &compressedSize) 192 | _ = binary.Read(file, binary.LittleEndian, &uncompressedSize) 193 | 194 | zlibReader, err := zlib.NewReader(file) 195 | if err != nil { 196 | return errors.Wrap(err, "could instantiate zlib reader") 197 | } 198 | var ( 199 | reader = bufio.NewReader(zlibReader) 200 | uniqueDirs = make(map[string]bool) 201 | fileNameDecoder = charmap.Windows1252.NewDecoder() 202 | ) 203 | 204 | for i := 0; i < int(f.Header.EntryCount); i++ { 205 | fileNameBytes, err := reader.ReadBytes(0) 206 | if err != nil { 207 | return errors.Wrap(err, "could not parse entry file name") 208 | } 209 | 210 | var d []byte 211 | if d, err = fileNameDecoder.Bytes(fileNameBytes[0 : len(fileNameBytes)-1]); err != nil { 212 | return errors.Wrap(err, "could not decode entry file name") 213 | } 214 | 215 | entry := &Entry{Data: []byte{}} 216 | 217 | if err = binary.Read(reader, binary.LittleEndian, &entry.Header); err != nil { 218 | return errors.Wrap(err, "could not read file entry header") 219 | } 220 | 221 | if entry.Header.Flags&entryType == 0 { 222 | continue 223 | } 224 | 225 | properFileName := strings.ToLower(strings.ReplaceAll(string(d), `\`, `/`)) 226 | entry.Name = properFileName 227 | dir, _ := filepath.Split(properFileName) 228 | dir = strings.TrimSuffix(dir, `/`) 229 | uniqueDirs[dir] = true 230 | 231 | f.entries[dir] = append(f.entries[dir], entry) 232 | } 233 | 234 | var dirs []string 235 | for dir := range uniqueDirs { 236 | dirs = append(dirs, dir) 237 | } 238 | 239 | sort.Slice(dirs, func(i, j int) bool { 240 | return strings.ToLower(dirs[i]) < strings.ToLower(dirs[j]) 241 | }) 242 | 243 | for _, dir := range dirs { 244 | if _, exists := f.entriesTree.Find(dir); exists { 245 | var toInsert []*Entry 246 | 247 | for _, e := range f.entries[dir] { 248 | toInsert = append(toInsert, e) 249 | } 250 | 251 | if len(toInsert) > 0 { 252 | if err = f.entriesTree.Insert(dir, toInsert); err != nil { 253 | return errors.Wrap(err, "could not insert tree nodes") 254 | } 255 | } 256 | } else { 257 | if err = f.entriesTree.Insert(dir, f.entries[dir]); err != nil { 258 | return errors.Wrap(err, "could not insert tree nodes") 259 | } 260 | } 261 | } 262 | 263 | return nil 264 | } 265 | 266 | func readNextBytes(reader io.Reader, number int) ([]byte, error) { 267 | bytesRead := make([]byte, number) 268 | 269 | n, err := reader.Read(bytesRead) 270 | if err != nil { 271 | return nil, errors.Wrap(err, "could not read next bytes") 272 | } 273 | if n != number { 274 | return nil, errors.Wrapf(err, "could not read next bytes: want %d, got %d", number, n) 275 | } 276 | return bytesRead, nil 277 | } 278 | -------------------------------------------------------------------------------- /internal/fileformat/grf/grf_test.go: -------------------------------------------------------------------------------- 1 | package grf_test 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | grf2 "github.com/project-midgard/midgarts/internal/fileformat/grf" 7 | "testing" 8 | 9 | "github.com/stretchr/testify/assert" 10 | ) 11 | 12 | const ( 13 | dataPath = "./../../data" 14 | ) 15 | 16 | func TestEntryHeaders(t *testing.T) { 17 | var tests = []struct { 18 | Name string 19 | ExpectedFileName string 20 | ExpectedEntries map[string]*grf2.Entry 21 | }{ 22 | { 23 | Name: "load file with raw data", 24 | ExpectedFileName: "raw", 25 | ExpectedEntries: map[string]*grf2.Entry{ 26 | "raw": { 27 | Header: grf2.EntryHeader{ 28 | CompressedSize: 74, 29 | CompressedSizeAligned: 74, 30 | UncompressedSize: 74, 31 | Flags: 0x01, 32 | Offset: 0, 33 | }, 34 | Data: bytes.NewBuffer(nil), 35 | }, 36 | "corrupted": { 37 | Header: grf2.EntryHeader{ 38 | CompressedSize: 132, 39 | CompressedSizeAligned: 123, 40 | UncompressedSize: 20, 41 | Flags: 0x03, 42 | Offset: 34, 43 | }, 44 | Data: bytes.NewBuffer(nil), 45 | }, 46 | "compressed": { 47 | Header: grf2.EntryHeader{ 48 | CompressedSize: 16, 49 | CompressedSizeAligned: 16, 50 | UncompressedSize: 74, 51 | Flags: 0x01, 52 | Offset: 74, 53 | }, 54 | Data: bytes.NewBuffer(nil), 55 | }, 56 | "compressed-des-header": { 57 | Header: grf2.EntryHeader{ 58 | CompressedSize: 16, 59 | CompressedSizeAligned: 16, 60 | UncompressedSize: 74, 61 | Flags: 0x05, 62 | Offset: 90, 63 | }, 64 | Data: bytes.NewBuffer(nil), 65 | }, 66 | "compressed-des-full": { 67 | Header: grf2.EntryHeader{ 68 | CompressedSize: 16, 69 | CompressedSizeAligned: 16, 70 | UncompressedSize: 74, 71 | Flags: 0x03, 72 | Offset: 106, 73 | }, 74 | Data: bytes.NewBuffer(nil), 75 | }, 76 | "big-compressed-des-full": { 77 | Header: grf2.EntryHeader{ 78 | CompressedSize: 361, 79 | CompressedSizeAligned: 368, 80 | UncompressedSize: 658, 81 | Flags: 0x03, 82 | Offset: 122, 83 | }, 84 | Data: bytes.NewBuffer(nil), 85 | }, 86 | }, 87 | }, 88 | } 89 | 90 | for _, tt := range tests { 91 | t.Run(tt.Name, func(t *testing.T) { 92 | grfFile, err := grf2.Load(fmt.Sprintf("%s/%s", dataPath, "with-files.grf")) 93 | assert.NoError(t, err) 94 | assert.Equal(t, tt.ExpectedEntries, grfFile.GetEntries("/")) 95 | }) 96 | } 97 | } 98 | 99 | func TestEntryContents(t *testing.T) { 100 | var tests = []struct { 101 | FilePath string 102 | Name string 103 | EntryName string 104 | ExpectedDataStr string 105 | }{ 106 | { 107 | FilePath: fmt.Sprintf("%s/%s", dataPath, "with-files.grf"), 108 | Name: "load file without compression or encryption", 109 | EntryName: "raw", 110 | ExpectedDataStr: "client client client client client client client client client client client client client client client", 111 | }, 112 | { 113 | FilePath: fmt.Sprintf("%s/%s", dataPath, "with-files.grf"), 114 | Name: "load file with compression and no encryption", 115 | EntryName: "compressed", 116 | ExpectedDataStr: "client client client client client client client client client client client client client client client", 117 | }, 118 | { 119 | FilePath: fmt.Sprintf("%s/%s", dataPath, "with-files.grf"), 120 | Name: "load file with compression and partial encryption", 121 | EntryName: "compressed-des-header", 122 | ExpectedDataStr: "client client client client client client client client client client client client client client client", 123 | }, 124 | { 125 | FilePath: fmt.Sprintf("%s/%s", dataPath, "with-files.grf"), 126 | Name: "load file with compression and full encryption", 127 | EntryName: "compressed-des-full", 128 | ExpectedDataStr: "client client client client client client client client client client client client client client client", 129 | }, 130 | { 131 | FilePath: fmt.Sprintf("%s/%s", dataPath, "with-files.grf"), 132 | Name: "load big file with compression and full encryption", 133 | EntryName: "big-compressed-des-full", 134 | ExpectedDataStr: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed venenatis bibendum venenatis. Aliquam quis velit urna. Suspendisse nec posuere sem. Donec risus quam, vulputate sed augue ultricies, dignissim hendrerit purus. Nulla euismod dolor enim, vel fermentum ex ultricies ac. Donec aliquet vehicula egestas. Sed accumsan velit ac mauris porta, id imperdiet purus aliquam. Phasellus et faucibus erat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Pellentesque vel nisl efficitur, euismod augue eu, consequat dui. Maecenas vestibulum tortor purus, egestas posuere tortor imperdiet eget. Nulla sit amet placerat diam.", 135 | }, 136 | } 137 | 138 | for _, tt := range tests { 139 | grfFile, err := grf2.Load(tt.FilePath) 140 | assert.NoError(t, err) 141 | 142 | t.Run(tt.Name, func(t *testing.T) { 143 | entry, err := grfFile.GetEntry(tt.EntryName) 144 | assert.NoError(t, err) 145 | assert.Equal(t, tt.ExpectedDataStr, string(entry.Data.Bytes())) 146 | }) 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /internal/fileformat/grf/zlib.go: -------------------------------------------------------------------------------- 1 | package grf 2 | 3 | import ( 4 | "bytes" 5 | "compress/zlib" 6 | "io/ioutil" 7 | ) 8 | 9 | func decompress(data []byte) ([]byte, error) { 10 | zlibReader, err := zlib.NewReader(bytes.NewReader(data)) 11 | if err != nil { 12 | return nil, err 13 | } 14 | defer zlibReader.Close() 15 | 16 | data, err = ioutil.ReadAll(zlibReader) 17 | if err != nil { 18 | return nil, err 19 | } 20 | 21 | return data, nil 22 | } 23 | -------------------------------------------------------------------------------- /internal/fileformat/spr/spr_file.go: -------------------------------------------------------------------------------- 1 | package spr 2 | 3 | import ( 4 | "bytes" 5 | "encoding/binary" 6 | "fmt" 7 | "github.com/project-midgard/midgarts/internal/bytesutil" 8 | "github.com/project-midgard/midgarts/internal/character" 9 | "github.com/project-midgard/midgarts/internal/graphic" 10 | "image" 11 | "image/color" 12 | "io" 13 | ) 14 | 15 | type FileType uint32 16 | 17 | const ( 18 | HeaderSignature = "SP" 19 | PaletteSize = 1024 20 | 21 | FileTypePAL FileType = 0 22 | FileTypeRGBA FileType = 1 23 | ) 24 | 25 | type SpriteFrame struct { 26 | SpriteType FileType 27 | Width uint16 28 | Height uint16 29 | Data []byte 30 | Compiled bool 31 | } 32 | 33 | type SpriteFile struct { 34 | Header struct { 35 | Signature string 36 | Version float32 37 | PalettedFrameCount uint16 38 | RGBAFrameCount uint16 39 | RGBAIndex uint16 40 | } 41 | 42 | Frames []*SpriteFrame 43 | Palette [PaletteSize]byte 44 | Images []*graphic.UniqueRGBA 45 | } 46 | 47 | func Load(data []byte) (f *SpriteFile, err error) { 48 | f = new(SpriteFile) 49 | reader := bytes.NewReader(data) 50 | 51 | if err := f.parseHeader(reader); err != nil { 52 | return nil, err 53 | } 54 | 55 | if f.Header.Version < 2.1 { 56 | if err = f.readPalettedFrames(reader); err != nil { 57 | return nil, err 58 | } 59 | } else { 60 | if err = f.readPalettedFramesRLE(reader); err != nil { 61 | return nil, err 62 | } 63 | } 64 | 65 | if err = f.readRGBAFrames(reader); err != nil { 66 | return nil, err 67 | } 68 | 69 | if f.Header.Version > 1.0 { 70 | reader = bytes.NewReader(data) 71 | 72 | if err = f.parsePalette(int64(len(data)-PaletteSize), reader); err != nil { 73 | return nil, err 74 | } 75 | } 76 | 77 | return f, nil 78 | } 79 | 80 | func (f *SpriteFile) parsePalette(skip int64, buf io.ReadSeeker) error { 81 | _ = bytesutil.SkipBytes(buf, skip) 82 | return binary.Read(buf, binary.LittleEndian, &f.Palette) 83 | } 84 | 85 | func (f *SpriteFile) parseHeader(buf io.ReadSeeker) error { 86 | var signature [2]byte 87 | _ = binary.Read(buf, binary.LittleEndian, &signature) 88 | 89 | signatureStr := string(signature[:]) 90 | if signatureStr != HeaderSignature { 91 | return fmt.Errorf("invalid signature: %s\n", signature) 92 | } 93 | 94 | var major, minor byte 95 | _ = binary.Read(buf, binary.LittleEndian, &major) 96 | _ = binary.Read(buf, binary.LittleEndian, &minor) 97 | version := float32(major)/10 + float32(minor) 98 | 99 | var palettedFrameCount, rgbaFrameCount uint16 100 | _ = binary.Read(buf, binary.LittleEndian, &palettedFrameCount) 101 | 102 | if version > 1.1 { 103 | _ = binary.Read(buf, binary.LittleEndian, &rgbaFrameCount) 104 | } 105 | 106 | f.Header.Signature = signatureStr 107 | f.Header.Version = version 108 | f.Header.PalettedFrameCount = palettedFrameCount 109 | f.Header.RGBAFrameCount = rgbaFrameCount 110 | f.Header.RGBAIndex = palettedFrameCount 111 | f.Frames = make([]*SpriteFrame, palettedFrameCount+rgbaFrameCount) 112 | f.Images = make([]*graphic.UniqueRGBA, palettedFrameCount+rgbaFrameCount) 113 | 114 | return nil 115 | } 116 | 117 | func (f *SpriteFile) readPalettedFrames(buf io.ReadSeeker) error { 118 | var ( 119 | width, height uint16 120 | size int 121 | data []byte 122 | palCount = int(f.Header.PalettedFrameCount) 123 | ) 124 | 125 | for i := 0; i < palCount; i++ { 126 | _ = binary.Read(buf, binary.LittleEndian, &width) 127 | _ = binary.Read(buf, binary.LittleEndian, &height) 128 | 129 | size = int(width * height) 130 | data = make([]byte, size) 131 | _ = binary.Read(buf, binary.LittleEndian, &data) 132 | 133 | f.Frames[i] = &SpriteFrame{ 134 | SpriteType: FileTypePAL, 135 | Width: width, 136 | Height: height, 137 | Data: data, 138 | } 139 | } 140 | 141 | return nil 142 | } 143 | 144 | // Parse .spr indexed images encoded with run-length encoding (RLE) 145 | func (f *SpriteFile) readPalettedFramesRLE(buf io.ReadSeeker) error { 146 | var ( 147 | width, height uint16 148 | c, count byte 149 | end, index, size int 150 | data []byte 151 | ) 152 | 153 | for i := 0; i < int(f.Header.PalettedFrameCount); i++ { 154 | _ = binary.Read(buf, binary.LittleEndian, &width) 155 | _ = binary.Read(buf, binary.LittleEndian, &height) 156 | 157 | size = int(width * height) 158 | data = make([]byte, size) 159 | index = 0 160 | 161 | var tmp uint16 162 | if err := binary.Read(buf, binary.LittleEndian, &tmp); err != nil { 163 | return err 164 | } 165 | 166 | offset, _ := buf.Seek(0, io.SeekCurrent) 167 | end = int(tmp) + int(offset) 168 | 169 | for int(offset) < end { 170 | if err := binary.Read(buf, binary.LittleEndian, &c); err != nil { 171 | return err 172 | } 173 | 174 | data[index] = c 175 | index++ 176 | 177 | if c == 0 { 178 | _ = binary.Read(buf, binary.LittleEndian, &count) 179 | 180 | if count == 0 { 181 | data[index] = count 182 | index++ 183 | } else { 184 | for j := 1; j < int(count); j++ { 185 | data[index] = c 186 | index++ 187 | } 188 | } 189 | } 190 | 191 | offset, _ = buf.Seek(0, io.SeekCurrent) 192 | } 193 | 194 | f.Frames[i] = &SpriteFrame{ 195 | SpriteType: FileTypePAL, 196 | Width: width, 197 | Height: height, 198 | Data: data, 199 | } 200 | } 201 | 202 | return nil 203 | } 204 | 205 | func (f *SpriteFile) readRGBAFrames(buf io.ReadSeeker) error { 206 | for i := 0; i < int(f.Header.RGBAFrameCount); i++ { 207 | var ( 208 | width, height uint16 209 | size int 210 | data []byte 211 | ) 212 | 213 | _ = binary.Read(buf, binary.LittleEndian, &width) 214 | _ = binary.Read(buf, binary.LittleEndian, &height) 215 | 216 | size = int(width*height) * 4 217 | data = make([]byte, size) 218 | if err := binary.Read(buf, binary.LittleEndian, &data); err != nil { 219 | return err 220 | } 221 | 222 | f.Frames[i+int(f.Header.RGBAIndex)] = &SpriteFrame{ 223 | SpriteType: FileTypeRGBA, 224 | Width: width, 225 | Height: height, 226 | Data: data, 227 | } 228 | } 229 | 230 | return nil 231 | } 232 | 233 | func (f *SpriteFile) ImageAt(index character.SpriteIndex) *graphic.UniqueRGBA { 234 | if f.Images[index] != nil { 235 | return f.Images[index] 236 | } 237 | 238 | var ( 239 | frame = f.Frames[index] 240 | width = int(frame.Width) 241 | height = int(frame.Height) 242 | data = frame.Data 243 | ) 244 | 245 | if width <= 0 || height <= 0 { 246 | return nil 247 | } 248 | 249 | img := graphic.NewUniqueRGBA(image.Rect(0, 0, width, height)) 250 | 251 | if frame.SpriteType == FileTypeRGBA { 252 | for y := 0; y < height; y++ { 253 | for x := 0; x < width; x++ { 254 | i := (x + y*width) * 4 255 | 256 | img.Set(x, y, color.RGBA{ 257 | R: data[i+3], 258 | G: data[i+2], 259 | B: data[i+1], 260 | A: data[i+0], 261 | }) 262 | } 263 | } 264 | } else { 265 | for y := 0; y < height; y++ { 266 | for x := 0; x < width; x++ { 267 | i := int(frame.Data[x+y*width]) * 4 268 | var a byte 269 | 270 | if i != 0 { 271 | a = 255 272 | } 273 | 274 | img.Set(x, y, color.RGBA{ 275 | R: f.Palette[i+0], 276 | G: f.Palette[i+1], 277 | B: f.Palette[i+2], 278 | A: a, 279 | }) 280 | } 281 | } 282 | } 283 | 284 | f.Images[index] = img 285 | return img 286 | } 287 | -------------------------------------------------------------------------------- /internal/fileformat/spr/spr_file_test.go: -------------------------------------------------------------------------------- 1 | package spr_test 2 | 3 | import "testing" 4 | 5 | func TestNewFile(t *testing.T) { 6 | 7 | } 8 | -------------------------------------------------------------------------------- /internal/graphic/caching/texture.go: -------------------------------------------------------------------------------- 1 | package caching 2 | 3 | import ( 4 | "github.com/google/uuid" 5 | 6 | graphic2 "github.com/project-midgard/midgarts/internal/graphic" 7 | ) 8 | 9 | type CachedTextureProvider map[uuid.UUID]*graphic2.Texture 10 | 11 | func NewCachedTextureProvider() CachedTextureProvider { 12 | return make(map[uuid.UUID]*graphic2.Texture) 13 | } 14 | 15 | func (t CachedTextureProvider) NewTextureFromRGBA(rgba *graphic2.UniqueRGBA) (*graphic2.Texture, error) { 16 | if txt, ok := t[rgba.ID]; ok { 17 | return txt, nil 18 | } 19 | 20 | tex, err := graphic2.NewTextureFromRGBA(rgba) 21 | if err != nil { 22 | return nil, err 23 | } 24 | 25 | t[rgba.ID] = tex 26 | return tex, nil 27 | } 28 | -------------------------------------------------------------------------------- /internal/graphic/geometry.go: -------------------------------------------------------------------------------- 1 | package graphic 2 | 3 | import ( 4 | "github.com/project-midgard/midgarts/internal/opengl" 5 | ) 6 | 7 | type Geometry struct { 8 | gls *opengl.State 9 | handleVAO uint32 10 | vbos []*opengl.VBO 11 | indices []uint32 12 | handleIndices uint32 13 | shouldUpdateIndices bool 14 | } 15 | 16 | func NewGeometry() *Geometry { 17 | geometry := &Geometry{ 18 | vbos: nil, 19 | shouldUpdateIndices: true, 20 | } 21 | 22 | return geometry 23 | } 24 | 25 | func (g *Geometry) AddVBO(vbo *opengl.VBO) *Geometry { 26 | g.vbos = append(g.vbos, vbo) 27 | return g 28 | } 29 | 30 | func (g *Geometry) VBOs() []*opengl.VBO { 31 | return g.vbos 32 | } 33 | 34 | func (g *Geometry) Indices() []uint32 { 35 | return g.indices 36 | } 37 | 38 | func (g *Geometry) SetIndices(indices ...uint32) { 39 | g.indices = indices 40 | } 41 | -------------------------------------------------------------------------------- /internal/graphic/geometry/plane.go: -------------------------------------------------------------------------------- 1 | package geometry 2 | 3 | import ( 4 | "github.com/go-gl/gl/v3.2-core/gl" 5 | 6 | "github.com/project-midgard/midgarts/internal/graphic" 7 | "github.com/project-midgard/midgarts/internal/opengl" 8 | ) 9 | 10 | const ( 11 | OnePixelSize = 1.0 / 35.0 12 | ) 13 | 14 | type Plane struct { 15 | *graphic.Graphic 16 | 17 | Geometry *graphic.Geometry 18 | Texture *graphic.Texture 19 | 20 | Width, Height float32 21 | 22 | colors []float32 23 | positions []float32 24 | } 25 | 26 | func (s *Plane) SetBounds(width, height float32) { 27 | w := width / 2 28 | h := height / 2 29 | 30 | s.positions[0] = -w 31 | s.positions[3] = w 32 | s.positions[6] = -w 33 | s.positions[9] = w 34 | 35 | s.positions[1] = h 36 | s.positions[4] = -h 37 | s.positions[7] = -h 38 | s.positions[10] = h 39 | } 40 | 41 | func (s *Plane) SetColors(colors []float32) { 42 | s.colors = colors 43 | } 44 | 45 | func (s *Plane) SetTexture(text *graphic.Texture) { 46 | s.Texture = text 47 | s.Texture.Bind(0) 48 | } 49 | 50 | func NewPlane(width, height float32, texture *graphic.Texture) *Plane { 51 | plane := &Plane{ 52 | Texture: texture, 53 | Width: width, 54 | Height: height, 55 | positions: make([]float32, 12), 56 | } 57 | 58 | plane.SetBounds(width, height) 59 | if plane.Texture != nil { 60 | plane.SetColors([]float32{ 61 | 1, 1, 1, 62 | 1, 1, 1, 63 | 1, 1, 1, 64 | 1, 1, 1, 65 | }) 66 | } else { 67 | plane.SetColors([]float32{ 68 | 1, 0, 1, 69 | 1, 0, 1, 70 | 1, 0, 1, 71 | 1, 0, 1, 72 | }) 73 | } 74 | 75 | texCoords := []float32{ 76 | 0, 0, 77 | 1, 1, 78 | 0, 1, 79 | 1, 0, 80 | } 81 | 82 | geom := graphic.NewGeometry() 83 | geom.AddVBO(opengl.NewVBO([opengl.NumVertexAttributes][]float32{ 84 | plane.positions, 85 | plane.colors, 86 | texCoords, 87 | }).AddAttribute(opengl.VertexPosition). 88 | AddAttribute(opengl.VertexColor). 89 | AddAttribute(opengl.VertexTexCoord), 90 | ).SetIndices(0, 1, 2, 3, 1, 0) 91 | 92 | plane.Geometry = geom 93 | plane.Graphic = graphic.NewGraphic(geom, gl.TRIANGLES) 94 | 95 | return plane 96 | } 97 | -------------------------------------------------------------------------------- /internal/graphic/graphic.go: -------------------------------------------------------------------------------- 1 | package graphic 2 | 3 | import ( 4 | "github.com/go-gl/gl/v3.2-core/gl" 5 | 6 | "github.com/project-midgard/midgarts/internal/opengl" 7 | ) 8 | 9 | type Graphic struct { 10 | *Transform 11 | geometry *Geometry 12 | renderMode uint32 13 | } 14 | 15 | func NewGraphic(geom *Geometry, renderMode uint32) *Graphic { 16 | return &Graphic{Transform: NewTransform(Origin), geometry: geom, renderMode: renderMode} 17 | } 18 | 19 | func (g *Graphic) Render(gls *opengl.State) { 20 | geom := g.geometry 21 | 22 | if geom.gls == nil { 23 | gl.GenVertexArrays(1, &geom.handleVAO) 24 | gl.GenBuffers(1, &geom.handleIndices) 25 | geom.gls = gls 26 | } 27 | 28 | gl.BindVertexArray(geom.handleVAO) 29 | for _, vbo := range geom.vbos { 30 | vbo.Load(gls) 31 | } 32 | 33 | if geom.shouldUpdateIndices { 34 | gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, geom.handleIndices) 35 | gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, len(geom.indices)*4, gl.Ptr(geom.indices), gl.STATIC_DRAW) 36 | geom.shouldUpdateIndices = false 37 | } 38 | 39 | gl.DrawElements(g.renderMode, int32(len(geom.Indices())*4), gl.UNSIGNED_INT, gl.Ptr(nil)) 40 | gl.BindVertexArray(0) 41 | } 42 | -------------------------------------------------------------------------------- /internal/graphic/renderable.go: -------------------------------------------------------------------------------- 1 | package graphic 2 | 3 | import "github.com/go-gl/mathgl/mgl32" 4 | 5 | type RenderInfo interface { 6 | ViewMatrix() mgl32.Mat4 7 | ProjectionMatrix() mgl32.Mat4 8 | } 9 | -------------------------------------------------------------------------------- /internal/graphic/rgba.go: -------------------------------------------------------------------------------- 1 | package graphic 2 | 3 | import ( 4 | "github.com/google/uuid" 5 | "image" 6 | ) 7 | 8 | type UniqueRGBA struct { 9 | ID uuid.UUID 10 | *image.RGBA 11 | } 12 | 13 | func NewUniqueRGBA(r image.Rectangle) *UniqueRGBA { 14 | return &UniqueRGBA{ 15 | ID: uuid.New(), 16 | RGBA: image.NewRGBA(r), 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /internal/graphic/texture.go: -------------------------------------------------------------------------------- 1 | package graphic 2 | 3 | import ( 4 | "fmt" 5 | "image" 6 | "image/draw" 7 | _ "image/png" 8 | 9 | "github.com/go-gl/gl/v3.2-core/gl" 10 | ) 11 | 12 | type Texture struct { 13 | handle uint32 14 | path string 15 | width, height, internalFormat int32 16 | format, formatType uint32 17 | magFilter, minFilter int32 18 | wrapS, wrapT int32 19 | } 20 | 21 | func (t *Texture) Bind(unit uint32) { 22 | gl.ActiveTexture(gl.TEXTURE0 + unit) 23 | gl.BindTexture(gl.TEXTURE_2D, t.handle) 24 | } 25 | 26 | func (t *Texture) Unbind(unit uint32) { 27 | gl.ActiveTexture(gl.TEXTURE0) 28 | gl.BindTexture(gl.TEXTURE_2D, 0) 29 | } 30 | 31 | type TextureProvider interface { 32 | NewTextureFromRGBA(rgba *UniqueRGBA) (tex *Texture, err error) 33 | } 34 | 35 | func NewTextureFromRGBA(rgba *UniqueRGBA) (tex *Texture, err error) { 36 | if rgba.Stride != rgba.Rect.Size().X*4 { 37 | return nil, fmt.Errorf("unsupported stride") 38 | } 39 | 40 | draw.Draw(rgba, rgba.Bounds(), rgba, image.Point{}, draw.Src) 41 | 42 | tex = &Texture{ 43 | width: int32(rgba.Rect.Size().X), 44 | height: int32(rgba.Rect.Size().Y), 45 | internalFormat: gl.RGBA8, 46 | format: gl.RGBA, 47 | formatType: gl.UNSIGNED_BYTE, 48 | magFilter: gl.NEAREST, 49 | minFilter: gl.NEAREST, 50 | wrapS: gl.CLAMP_TO_BORDER, 51 | wrapT: gl.CLAMP_TO_BORDER, 52 | } 53 | 54 | gl.GenTextures(1, &tex.handle) 55 | gl.BindTexture(gl.TEXTURE_2D, tex.handle) 56 | 57 | gl.GenerateMipmap(gl.TEXTURE_2D) 58 | 59 | gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, tex.magFilter) 60 | gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, tex.minFilter) 61 | gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, tex.wrapS) 62 | gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, tex.wrapT) 63 | 64 | gl.TexImage2D( 65 | gl.TEXTURE_2D, 66 | 0, 67 | tex.internalFormat, 68 | tex.width, 69 | tex.height, 70 | 0, 71 | tex.format, 72 | tex.formatType, 73 | gl.Ptr(&rgba.Pix[0]), 74 | ) 75 | 76 | return 77 | } 78 | -------------------------------------------------------------------------------- /internal/graphic/transform.go: -------------------------------------------------------------------------------- 1 | package graphic 2 | 3 | import ( 4 | "github.com/go-gl/mathgl/mgl32" 5 | ) 6 | 7 | var ( 8 | Origin = mgl32.Vec3{0, 0, 0} 9 | Up = mgl32.Vec3{0, 1, 0} 10 | Forward = mgl32.Vec3{0, 0, 1} 11 | Backwards = mgl32.Vec3{0, 0, -1} 12 | ) 13 | 14 | type Transform struct { 15 | position mgl32.Vec3 16 | scale mgl32.Vec3 17 | direction mgl32.Vec3 18 | rotation mgl32.Quat 19 | } 20 | 21 | func NewTransform(position mgl32.Vec3) *Transform { 22 | return &Transform{ 23 | position: position, 24 | scale: mgl32.Vec3{1, 1, 1}, 25 | direction: Forward, 26 | rotation: mgl32.AnglesToQuat(0, 0, 0, mgl32.XYZ), 27 | } 28 | } 29 | 30 | func (t *Transform) Model() mgl32.Mat4 { 31 | positionMatrix := mgl32.Translate3D(t.position.X(), t.position.Y(), t.position.Z()) 32 | scaleMatrix := mgl32.Scale3D(t.scale.X(), t.scale.Y(), t.scale.Z()) 33 | 34 | rotationX := mgl32.HomogRotate3DX(t.rotation.X()) 35 | rotationY := mgl32.HomogRotate3DY(t.rotation.Y()) 36 | rotationZ := mgl32.HomogRotate3DZ(t.rotation.Z()) 37 | 38 | rotationMatrix := rotationZ.Mul4(rotationY).Mul4(rotationX) 39 | 40 | model := positionMatrix.Mul4(rotationMatrix).Mul4(scaleMatrix) 41 | 42 | return model 43 | } 44 | 45 | func (t *Transform) Position() mgl32.Vec3 { 46 | return t.position 47 | } 48 | 49 | func (t *Transform) SetPosition(position mgl32.Vec3) { 50 | t.position = position 51 | } 52 | 53 | func (t *Transform) Scale() mgl32.Vec3 { 54 | return t.scale 55 | } 56 | 57 | func (t *Transform) SetScale(scale mgl32.Vec3) { 58 | t.scale = scale 59 | } 60 | 61 | func (t *Transform) Rotation() mgl32.Quat { 62 | return t.rotation 63 | } 64 | 65 | func (t *Transform) SetRotation(rotation mgl32.Quat) { 66 | t.rotation = rotation 67 | } 68 | -------------------------------------------------------------------------------- /internal/grfexplorer/grfexplorer.go: -------------------------------------------------------------------------------- 1 | package grfexplorer 2 | 3 | // Run implements the main program loop of the demo. It returns when the platform signals to stop. 4 | // This demo application shows some basic features of ImGui, as well as exposing the standard demo window. 5 | -------------------------------------------------------------------------------- /internal/opengl/opengl.go: -------------------------------------------------------------------------------- 1 | package opengl 2 | 3 | import ( 4 | _ "embed" 5 | "fmt" 6 | "strings" 7 | 8 | "github.com/go-gl/gl/v3.2-core/gl" 9 | ) 10 | 11 | func NewShader(vert string, frag string) *State { 12 | vertexShader, err := compileShader(vert, gl.VERTEX_SHADER) 13 | if err != nil { 14 | panic(err) 15 | } 16 | 17 | fragmentShader, err := compileShader(frag, gl.FRAGMENT_SHADER) 18 | if err != nil { 19 | panic(err) 20 | } 21 | 22 | prog := gl.CreateProgram() 23 | gl.AttachShader(prog, vertexShader) 24 | gl.AttachShader(prog, fragmentShader) 25 | gl.LinkProgram(prog) 26 | 27 | gl.Enable(gl.BLEND) 28 | gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) 29 | gl.LineWidth(2.0) 30 | gl.PointSize(2.0) 31 | 32 | gl.Enable(gl.DEPTH_TEST) 33 | gl.DepthFunc(gl.LEQUAL) 34 | 35 | gl.ClearColor(0.3, 0.3, 0.5, 1.0) 36 | 37 | return &State{ 38 | program: &Program{id: prog}, bufferCount: 0, 39 | } 40 | } 41 | 42 | func compileShader(source string, shaderType uint32) (uint32, error) { 43 | shader := gl.CreateShader(shaderType) 44 | 45 | csources, free := gl.Strs(source + "\x00") 46 | defer free() 47 | gl.ShaderSource(shader, 1, csources, nil) 48 | gl.CompileShader(shader) 49 | 50 | var status int32 51 | gl.GetShaderiv(shader, gl.COMPILE_STATUS, &status) 52 | if status == gl.FALSE { 53 | var logLength int32 54 | gl.GetShaderiv(shader, gl.INFO_LOG_LENGTH, &logLength) 55 | 56 | log := strings.Repeat("\x00", int(logLength+1)) 57 | gl.GetShaderInfoLog(shader, logLength, nil, gl.Str(log)) 58 | 59 | return 0, fmt.Errorf("failed to compile %v: %v", source, log) 60 | } 61 | 62 | return shader, nil 63 | } 64 | -------------------------------------------------------------------------------- /internal/opengl/program.go: -------------------------------------------------------------------------------- 1 | package opengl 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/go-gl/gl/v3.2-core/gl" 7 | ) 8 | 9 | type Program struct { 10 | id uint32 11 | } 12 | 13 | func NewProgram() *Program { 14 | return &Program{} 15 | } 16 | 17 | func (p *Program) GetAttribLocation(name string) int32 { 18 | if p.id == 0 { 19 | log.Fatalf("program '%v' not loaded", p.id) 20 | } 21 | 22 | return gl.GetAttribLocation(p.id, gl.Str(name+"\x00")) 23 | } 24 | 25 | func (p *Program) ID() uint32 { 26 | return p.id 27 | } 28 | -------------------------------------------------------------------------------- /internal/opengl/state.go: -------------------------------------------------------------------------------- 1 | package opengl 2 | 3 | type State struct { 4 | program *Program 5 | bufferCount int 6 | } 7 | 8 | func (s *State) Program() *Program { 9 | return s.program 10 | } 11 | -------------------------------------------------------------------------------- /internal/opengl/vbo.go: -------------------------------------------------------------------------------- 1 | package opengl 2 | 3 | import ( 4 | "unsafe" 5 | 6 | "github.com/go-gl/gl/v3.2-core/gl" 7 | ) 8 | 9 | type VBOAttributeType int 10 | 11 | const ( 12 | VertexPosition = VBOAttributeType(iota) 13 | VertexColor 14 | VertexTexCoord 15 | 16 | NumVertexAttributes 17 | ) 18 | 19 | var attribTypeNames = map[VBOAttributeType]string{ 20 | VertexPosition: "VertexPosition", 21 | VertexColor: "VertexColor", 22 | VertexTexCoord: "VertexTexCoord", 23 | } 24 | 25 | var attributeTypeSizes = map[VBOAttributeType]int{ 26 | VertexPosition: 3, 27 | VertexColor: 3, 28 | VertexTexCoord: 2, 29 | } 30 | 31 | type VBO struct { 32 | gls *State 33 | initialized bool 34 | buffers [NumVertexAttributes][]float32 35 | usage uint32 36 | attributes []VBOAttribute 37 | handles [NumVertexAttributes]uint32 38 | shouldUpdate bool 39 | buffAllocated bool 40 | } 41 | 42 | type VBOAttribute struct { 43 | Type VBOAttributeType 44 | Name string 45 | NumElements int32 46 | ByteOffset uint32 47 | ElementType uint32 48 | } 49 | 50 | func NewVBO(buffers [NumVertexAttributes][]float32) *VBO { 51 | vbo := &VBO{ 52 | gls: nil, 53 | buffers: buffers, 54 | usage: gl.STATIC_DRAW, 55 | attributes: make([]VBOAttribute, 0), 56 | shouldUpdate: true, 57 | } 58 | 59 | return vbo 60 | } 61 | 62 | func (vbo *VBO) AddAttribute(t VBOAttributeType) *VBO { 63 | vbo.attributes = append(vbo.attributes, VBOAttribute{ 64 | Type: t, 65 | Name: attribTypeNames[t], 66 | NumElements: int32(attributeTypeSizes[t]), 67 | ByteOffset: 0, 68 | ElementType: gl.FLOAT, 69 | }) 70 | 71 | return vbo 72 | } 73 | 74 | func (vbo *VBO) Load(gls *State) { 75 | if len(vbo.attributes) == 0 { 76 | return 77 | } 78 | 79 | if !vbo.buffAllocated { 80 | for loc := range vbo.attributes { 81 | gl.GenBuffers(int32(NumVertexAttributes), &vbo.handles[loc]) 82 | } 83 | vbo.buffAllocated = true 84 | } 85 | 86 | for loc, attrib := range vbo.attributes { 87 | gl.BindBuffer(gl.ARRAY_BUFFER, vbo.handles[loc]) 88 | gl.BufferData(gl.ARRAY_BUFFER, len(vbo.buffers[loc])*4, gl.Ptr(vbo.buffers[loc]), vbo.usage) 89 | 90 | gl.EnableVertexAttribArray(uint32(loc)) 91 | gl.VertexAttribPointer( 92 | uint32(loc), 93 | attrib.NumElements, 94 | attrib.ElementType, 95 | false, 96 | 0, 97 | unsafe.Pointer(uintptr(attrib.ByteOffset)), 98 | ) 99 | } 100 | 101 | vbo.gls = gls 102 | if !vbo.shouldUpdate { 103 | return 104 | } 105 | 106 | vbo.shouldUpdate = false 107 | } 108 | -------------------------------------------------------------------------------- /internal/romap/map.go: -------------------------------------------------------------------------------- 1 | package romap 2 | 3 | type CellType byte 4 | 5 | const ( 6 | CellTypeNone = CellType(1 << 0) 7 | CellTypeWalkable = CellType(1 << 1) 8 | CellTypeWater = CellType(1 << 2) 9 | CellTypeSnipable = CellType(1 << 3) 10 | ) 11 | -------------------------------------------------------------------------------- /internal/system/character_action_system.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | "log" 5 | "strconv" 6 | "time" 7 | 8 | "github.com/EngoEngine/ecs" 9 | 10 | "github.com/project-midgard/midgarts/internal/character/actionindex" 11 | "github.com/project-midgard/midgarts/internal/character/statetype" 12 | "github.com/project-midgard/midgarts/internal/component" 13 | "github.com/project-midgard/midgarts/internal/entity" 14 | "github.com/project-midgard/midgarts/internal/fileformat/grf" 15 | ) 16 | 17 | type CharacterActionable interface { 18 | component.CharacterStateComponentFace 19 | component.CharacterSpriteRenderInfoComponentFace 20 | } 21 | 22 | type CharacterActionSystem struct { 23 | grfFile *grf.File 24 | 25 | characters map[string]*entity.Character 26 | } 27 | 28 | func NewCharacterActionSystem(grfFile *grf.File) *CharacterActionSystem { 29 | return &CharacterActionSystem{ 30 | grfFile, 31 | map[string]*entity.Character{}, 32 | } 33 | } 34 | 35 | func (s *CharacterActionSystem) Add(char *entity.Character) { 36 | cmp, e := component.NewCharacterAttachmentComponent(s.grfFile, component.CharacterAttachmentComponentConfig{ 37 | Gender: char.Gender, 38 | JobSpriteID: char.JobSpriteID, 39 | HeadIndex: char.HeadIndex, 40 | }) 41 | if e != nil { 42 | log.Fatal(e) 43 | } 44 | char.SetCharacterAttachmentComponent(cmp) 45 | s.characters[strconv.Itoa(int(char.ID()))] = char 46 | } 47 | 48 | func (s *CharacterActionSystem) AddByInterface(o ecs.Identifier) { 49 | char := o.(*entity.Character) 50 | s.Add(char) 51 | } 52 | 53 | func (s *CharacterActionSystem) Update(dt float32) { 54 | for _, c := range s.characters { 55 | now := time.Now() 56 | previousAnimationHasEnded := now.After(c.AnimationEndsAt) 57 | 58 | stopPreviousAnimation := previousAnimationHasEnded 59 | if c.PreviousState != statetype.Walking { 60 | stopPreviousAnimation = true 61 | } 62 | 63 | c.ActionIndex = actionindex.GetActionIndex(c.State) 64 | 65 | if (c.State != c.PreviousState && c.State != statetype.Idle) || 66 | (c.State == statetype.Idle && stopPreviousAnimation) { 67 | c.AnimationStartedAt = now 68 | 69 | // TODO: treat special case when attacking 70 | var forcedDuration time.Duration 71 | c.ForcedDuration = forcedDuration 72 | 73 | c.FPSMultiplier = 1.0 74 | if c.State == statetype.Walking { 75 | c.FPSMultiplier = c.MovementSpeed 76 | } 77 | } 78 | c.AnimationEndsAt = now.Add(c.AnimationDelay) 79 | } 80 | } 81 | 82 | func (s *CharacterActionSystem) Remove(e ecs.BasicEntity) { 83 | delete(s.characters, strconv.Itoa(int(e.ID()))) 84 | } 85 | -------------------------------------------------------------------------------- /internal/system/character_render.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | "math" 5 | "strconv" 6 | "time" 7 | 8 | "github.com/EngoEngine/ecs" 9 | "github.com/go-gl/mathgl/mgl32" 10 | "github.com/rs/zerolog/log" 11 | 12 | "github.com/project-midgard/midgarts/internal/character" 13 | "github.com/project-midgard/midgarts/internal/character/actionindex" 14 | "github.com/project-midgard/midgarts/internal/character/actionplaymode" 15 | "github.com/project-midgard/midgarts/internal/character/directiontype" 16 | "github.com/project-midgard/midgarts/internal/component" 17 | "github.com/project-midgard/midgarts/internal/entity" 18 | "github.com/project-midgard/midgarts/internal/fileformat/act" 19 | "github.com/project-midgard/midgarts/internal/fileformat/grf" 20 | "github.com/project-midgard/midgarts/internal/fileformat/spr" 21 | "github.com/project-midgard/midgarts/internal/graphic" 22 | "github.com/project-midgard/midgarts/internal/graphic/geometry" 23 | "github.com/project-midgard/midgarts/internal/system/opengl" 24 | ) 25 | 26 | const ( 27 | SpriteScaleFactor = float32(1.0) 28 | FixedCameraDirection = 6 29 | ) 30 | 31 | type CharacterRenderable interface { 32 | ecs.BasicFace 33 | component.CharacterStateComponentFace 34 | component.CharacterAttachmentComponentFace 35 | } 36 | 37 | type CharacterRenderSystem struct { 38 | grfFile *grf.File 39 | characters map[string]*entity.Character 40 | RenderCommands *opengl.RenderCommands 41 | textureProvider graphic.TextureProvider 42 | } 43 | 44 | func NewCharacterRenderSystem(grfFile *grf.File, textureProvider graphic.TextureProvider) *CharacterRenderSystem { 45 | return &CharacterRenderSystem{ 46 | grfFile: grfFile, 47 | characters: map[string]*entity.Character{}, 48 | RenderCommands: &opengl.RenderCommands{ 49 | Sprites: []opengl.SpriteRenderCommand{}, 50 | }, 51 | textureProvider: textureProvider, 52 | } 53 | } 54 | 55 | func (s *CharacterRenderSystem) Update(dt float32) { 56 | s.RenderCommands.Sprites = []opengl.SpriteRenderCommand{} 57 | 58 | for _, char := range s.characters { 59 | s.renderCharacter(dt, char) 60 | } 61 | } 62 | 63 | func (s *CharacterRenderSystem) AddByInterface(o ecs.Identifier) { 64 | char := o.(*entity.Character) 65 | s.Add(char) 66 | } 67 | 68 | func (s *CharacterRenderSystem) Add(char *entity.Character) { 69 | cmp, err := component.NewCharacterAttachmentComponent(s.grfFile, component.CharacterAttachmentComponentConfig{ 70 | Gender: char.Gender, 71 | JobSpriteID: char.JobSpriteID, 72 | HeadIndex: char.HeadIndex, 73 | EnableShield: char.HasShield, 74 | ShieldSpriteName: char.ShieldSpriteName, 75 | }) 76 | if err != nil { 77 | log.Fatal().Err(err).Send() 78 | } 79 | 80 | char.SetCharacterAttachmentComponent(cmp) 81 | s.characters[strconv.Itoa(int(char.ID()))] = char 82 | } 83 | 84 | func (s *CharacterRenderSystem) Remove(e ecs.BasicEntity) { 85 | delete(s.characters, strconv.Itoa(int(e.ID()))) 86 | } 87 | 88 | func (s *CharacterRenderSystem) renderCharacter(dt float32, char *entity.Character) { 89 | offset := [2]float32{0, 0} 90 | 91 | direction := int(char.Direction) + directiontype.DirectionTable[FixedCameraDirection]%8 92 | behind := direction > 1 && direction < 6 93 | renderShield := char.HasShield && char.ActionIndex == actionindex.StandBy 94 | 95 | if char.ActionIndex != actionindex.Dead && char.ActionIndex != actionindex.Sitting { 96 | s.renderAttachment(dt, char, character.AttachmentShadow, &offset) 97 | } 98 | 99 | if behind && renderShield { 100 | s.renderAttachment(dt, char, character.AttachmentShield, &offset) 101 | } 102 | 103 | s.renderAttachment(dt, char, character.AttachmentBody, &offset) 104 | s.renderAttachment(dt, char, character.AttachmentHead, &offset) 105 | 106 | if !behind && renderShield { 107 | s.renderAttachment(dt, char, character.AttachmentShield, &offset) 108 | } 109 | } 110 | 111 | func (s *CharacterRenderSystem) renderAttachment( 112 | dt float32, 113 | char *entity.Character, 114 | elem character.AttachmentType, 115 | offset *[2]float32, 116 | ) { 117 | var actions []*act.Action 118 | if actions = char.Files[elem].ACT.Actions; len(actions) == 0 { 119 | return 120 | } 121 | 122 | idx := (int(char.ActionIndex) + (int(char.Direction)+directiontype.DirectionTable[FixedCameraDirection])%8) % len(actions) 123 | action := actions[idx] 124 | frameCount := int64(len(action.Frames)) 125 | timeNeededForOneFrame := int64(float64(action.Delay) * (1.0 / char.FPSMultiplier)) 126 | 127 | if char.ForcedDuration != 0 { 128 | timeNeededForOneFrame = int64(char.ForcedDuration) / frameCount 129 | } 130 | 131 | timeNeededForOneFrame = int64(math.Max(float64(timeNeededForOneFrame), 100)) 132 | elapsedTime := time.Since(char.AnimationStartedAt).Milliseconds() - int64(dt) 133 | realIndex := elapsedTime / timeNeededForOneFrame 134 | 135 | var frameIndex int64 136 | switch char.PlayMode { 137 | case actionplaymode.Repeat: 138 | frameIndex = realIndex % frameCount 139 | break 140 | } 141 | 142 | // Ignore "doridori" animation 143 | if len(action.Frames) == 3 { 144 | frameIndex = 0 145 | } 146 | 147 | var frame *act.ActionFrame 148 | if frame = action.Frames[frameIndex]; len(frame.Layers) == 0 { 149 | *offset = [2]float32{0, 0} 150 | return 151 | } 152 | 153 | position := [2]float32{0, 0} 154 | 155 | if len(frame.Positions) > 0 && 156 | elem != character.AttachmentBody && 157 | elem != character.AttachmentShield { 158 | 159 | position[0] = offset[0] - float32(frame.Positions[0][0]) 160 | position[1] = offset[1] - float32(frame.Positions[0][1]) 161 | } 162 | 163 | // Render all layers 164 | for _, layer := range frame.Layers { 165 | if layer.SpriteFrameIndex < 0 { 166 | continue 167 | } 168 | 169 | s.renderLayer(char, layer, char.Files[elem].SPR, position) 170 | } 171 | 172 | // Save offset reference 173 | if len(frame.Positions) > 0 { 174 | *offset = [2]float32{ 175 | float32(frame.Positions[0][0]), 176 | float32(frame.Positions[0][1]), 177 | } 178 | } 179 | 180 | char.AnimationDelay = time.Duration(action.DurationMilliseconds) * time.Millisecond 181 | } 182 | 183 | func (s *CharacterRenderSystem) renderLayer( 184 | char *entity.Character, 185 | layer *act.ActionFrameLayer, 186 | spr *spr.SpriteFile, 187 | offset [2]float32, 188 | ) { 189 | frameIndex := character.SpriteIndex(layer.SpriteFrameIndex) 190 | if frameIndex < 0 { 191 | return 192 | } 193 | 194 | texture, err := s.textureProvider.NewTextureFromRGBA(spr.ImageAt(frameIndex)) 195 | if err != nil { 196 | log.Fatal().Err(err).Send() 197 | } 198 | 199 | frame := spr.Frames[frameIndex] 200 | width, height := float32(frame.Width), float32(frame.Height) 201 | width *= layer.Scale[0] * SpriteScaleFactor * geometry.OnePixelSize 202 | height *= layer.Scale[1] * SpriteScaleFactor * geometry.OnePixelSize 203 | rot := float64(layer.Angle) * (math.Pi / 180) 204 | 205 | offset = [2]float32{ 206 | (float32(layer.Position[0]) + offset[0]) * geometry.OnePixelSize, 207 | (float32(layer.Position[1]) + offset[1]) * geometry.OnePixelSize, 208 | } 209 | 210 | cmd := opengl.SpriteRenderCommand{ 211 | Scale: layer.Scale, 212 | Size: mgl32.Vec2{width, height}, 213 | Position: char.Position(), 214 | Offset: mgl32.Vec2{offset[0], offset[1]}, 215 | RotationRadians: float32(rot), 216 | Texture: texture, 217 | FlipVertically: layer.Mirrored, 218 | } 219 | 220 | // This is the current API to render a shaders. Commands will 221 | // be collected by the lower-level rendering system (OpenGL). 222 | s.renderSpriteCommand(cmd) 223 | } 224 | 225 | func (s *CharacterRenderSystem) renderSpriteCommand(cmd ...opengl.SpriteRenderCommand) { 226 | s.RenderCommands.Sprites = append(s.RenderCommands.Sprites, cmd...) 227 | } 228 | -------------------------------------------------------------------------------- /internal/system/opengl/render_command.go: -------------------------------------------------------------------------------- 1 | package opengl 2 | 3 | import ( 4 | "github.com/go-gl/mathgl/mgl32" 5 | 6 | "github.com/project-midgard/midgarts/internal/graphic" 7 | ) 8 | 9 | type SpriteRenderCommand struct { 10 | Scale [2]float32 11 | Size mgl32.Vec2 12 | Position mgl32.Vec3 13 | Offset mgl32.Vec2 14 | RotationRadians float32 15 | Texture *graphic.Texture 16 | FlipVertically bool 17 | } 18 | -------------------------------------------------------------------------------- /internal/system/opengl/render_system.go: -------------------------------------------------------------------------------- 1 | package opengl 2 | 3 | import ( 4 | _ "embed" 5 | 6 | "github.com/EngoEngine/ecs" 7 | "github.com/go-gl/gl/v3.2-core/gl" 8 | "github.com/go-gl/mathgl/mgl32" 9 | 10 | "github.com/project-midgard/midgarts/internal/camera" 11 | "github.com/project-midgard/midgarts/internal/graphic" 12 | "github.com/project-midgard/midgarts/internal/graphic/geometry" 13 | "github.com/project-midgard/midgarts/internal/opengl" 14 | ) 15 | 16 | //go:embed shaders/box.vert 17 | var boxVertexShader string 18 | 19 | //go:embed shaders/box.frag 20 | var boxFragmentShader string 21 | 22 | //go:embed shaders/sprite.vert 23 | var spriteVertexShader string 24 | 25 | //go:embed shaders/sprite.frag 26 | var spriteFragmentShader string 27 | 28 | type RenderCommands struct { 29 | Sprites []SpriteRenderCommand 30 | } 31 | 32 | // RenderSystem defines an OpenGL-based rendering system. 33 | type RenderSystem struct { 34 | cam *camera.Camera 35 | renderCommands *RenderCommands 36 | 37 | // Buffer of reusable sprites 38 | spritesBuf []*geometry.Plane 39 | } 40 | 41 | func NewOpenGLRenderSystem(cam *camera.Camera, commands *RenderCommands) *RenderSystem { 42 | return &RenderSystem{ 43 | cam: cam, 44 | renderCommands: commands, 45 | spritesBuf: []*geometry.Plane{}, 46 | } 47 | } 48 | 49 | func (s *RenderSystem) Update(dt float32) { 50 | gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) 51 | 52 | // 2D Plane Box 53 | s.renderSpriteBoxes() 54 | 55 | // 2D Sprites 56 | s.renderSprites() 57 | } 58 | 59 | func (s *RenderSystem) renderSpriteBoxes() { 60 | shader := opengl.NewShader(boxVertexShader, boxFragmentShader) 61 | pid := shader.Program().ID() 62 | gl.UseProgram(pid) 63 | 64 | for _, cmd := range s.renderCommands.Sprites { 65 | if cmd.FlipVertically { 66 | cmd.Size = mgl32.Vec2{-cmd.Size.X(), cmd.Size.Y()} 67 | } 68 | 69 | box := geometry.NewPlane(0, 0, nil) 70 | box.SetColors([]float32{1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0}) 71 | box.SetBounds(cmd.Size.X(), cmd.Size.Y()) 72 | box.SetPosition(mgl32.Vec3{cmd.Position.X(), cmd.Position.Y(), cmd.Position.Z()}) 73 | 74 | view := s.cam.ViewMatrix() 75 | viewu := gl.GetUniformLocation(pid, gl.Str("view\x00")) 76 | gl.UniformMatrix4fv(viewu, 1, false, &view[0]) 77 | 78 | model := box.Model() 79 | modelu := gl.GetUniformLocation(pid, gl.Str("model\x00")) 80 | gl.UniformMatrix4fv(modelu, 1, false, &model[0]) 81 | 82 | projection := s.cam.ProjectionMatrix() 83 | projectionu := gl.GetUniformLocation(pid, gl.Str("projection\x00")) 84 | gl.UniformMatrix4fv(projectionu, 1, false, &projection[0]) 85 | 86 | sizeu := gl.GetUniformLocation(pid, gl.Str("size\x00")) 87 | gl.Uniform2fv(sizeu, 1, &cmd.Size[0]) 88 | 89 | offsetu := gl.GetUniformLocation(pid, gl.Str("offset\x00")) 90 | gl.Uniform2fv(offsetu, 1, &cmd.Offset[0]) 91 | 92 | iden := mgl32.Ident4() 93 | rotation := iden.Mul4(mgl32.HomogRotate3D(cmd.RotationRadians, graphic.Backwards)) 94 | rotationu := gl.GetUniformLocation(pid, gl.Str("rotation\x00")) 95 | gl.UniformMatrix4fv(rotationu, 1, false, &rotation[0]) 96 | 97 | gl.PolygonMode(gl.FRONT_AND_BACK, gl.LINE) 98 | box.Render(shader) 99 | } 100 | } 101 | 102 | func (s *RenderSystem) renderSprites() { 103 | shader := opengl.NewShader(spriteVertexShader, spriteFragmentShader) 104 | pid := shader.Program().ID() 105 | gl.UseProgram(pid) 106 | 107 | s.EnsureSpritesBufLen(len(s.renderCommands.Sprites)) 108 | 109 | for i, cmd := range s.renderCommands.Sprites { 110 | if cmd.FlipVertically { 111 | cmd.Size = mgl32.Vec2{-cmd.Size.X(), cmd.Size.Y()} 112 | } 113 | 114 | sprite := s.spritesBuf[i] 115 | sprite.SetBounds(cmd.Size.X(), cmd.Size.Y()) 116 | sprite.SetTexture(cmd.Texture) 117 | sprite.SetPosition(mgl32.Vec3{cmd.Position.X(), cmd.Position.Y(), cmd.Position.Z()}) 118 | sprite.Texture.Bind(0) 119 | 120 | view := s.cam.ViewMatrix() 121 | viewu := gl.GetUniformLocation(pid, gl.Str("view\x00")) 122 | gl.UniformMatrix4fv(viewu, 1, false, &view[0]) 123 | 124 | model := sprite.Model() 125 | modelu := gl.GetUniformLocation(pid, gl.Str("model\x00")) 126 | gl.UniformMatrix4fv(modelu, 1, false, &model[0]) 127 | 128 | projection := s.cam.ProjectionMatrix() 129 | projectionu := gl.GetUniformLocation(pid, gl.Str("projection\x00")) 130 | gl.UniformMatrix4fv(projectionu, 1, false, &projection[0]) 131 | 132 | sizeu := gl.GetUniformLocation(pid, gl.Str("size\x00")) 133 | gl.Uniform2fv(sizeu, 1, &cmd.Size[0]) 134 | 135 | offsetu := gl.GetUniformLocation(pid, gl.Str("offset\x00")) 136 | gl.Uniform2fv(offsetu, 1, &cmd.Offset[0]) 137 | 138 | iden := mgl32.Ident4() 139 | rotation := iden.Mul4(mgl32.HomogRotate3D(cmd.RotationRadians, graphic.Backwards)) 140 | rotationu := gl.GetUniformLocation(pid, gl.Str("rotation\x00")) 141 | gl.UniformMatrix4fv(rotationu, 1, false, &rotation[0]) 142 | 143 | gl.PolygonMode(gl.FRONT_AND_BACK, gl.FILL) 144 | sprite.Render(shader) 145 | sprite.Texture.Unbind(0) 146 | } 147 | } 148 | 149 | func (s *RenderSystem) Remove(e ecs.BasicEntity) { 150 | panic("implement me") 151 | } 152 | 153 | func (s *RenderSystem) EnsureSpritesBufLen(minLen int) { 154 | s.spritesBuf = ensureSpritesBufferLength(s.spritesBuf, minLen) 155 | } 156 | 157 | func ensureSpritesBufferLength(slice []*geometry.Plane, minLen int) []*geometry.Plane { 158 | oldLen := len(slice) 159 | 160 | if cacheOverflow := minLen - oldLen; cacheOverflow <= 0 { 161 | // no need to resize 162 | return slice 163 | } 164 | 165 | if minLen > cap(slice) { 166 | newSlice := make([]*geometry.Plane, oldLen, minLen) 167 | copy(newSlice, slice) 168 | slice = newSlice 169 | } 170 | 171 | slice = slice[0:minLen] 172 | 173 | for i := oldLen; i < minLen; i++ { 174 | slice[i] = geometry.NewPlane(0, 0, new(graphic.Texture)) 175 | } 176 | return slice 177 | } 178 | -------------------------------------------------------------------------------- /internal/system/opengl/shaders/box.frag: -------------------------------------------------------------------------------- 1 | #version 330 core 2 | 3 | in vec3 fragColor; 4 | in vec2 texCoords; 5 | 6 | out vec4 FragColor; 7 | 8 | uniform sampler2D tex; 9 | 10 | void main() { 11 | vec2 var_TexCoords = texCoords; 12 | 13 | FragColor = vec4(fragColor, 1.0); 14 | } 15 | -------------------------------------------------------------------------------- /internal/system/opengl/shaders/box.vert: -------------------------------------------------------------------------------- 1 | #version 330 core 2 | 3 | layout(location = 0) in vec3 VertexPosition; 4 | layout(location = 1) in vec3 VertexColor; 5 | layout(location = 2) in vec2 VertexTexCoord; 6 | 7 | uniform mat4 model; 8 | uniform mat4 view; 9 | uniform mat4 projection; 10 | uniform vec2 size; 11 | uniform vec2 offset; 12 | 13 | out vec3 fragColor; 14 | out vec2 texCoords; 15 | 16 | void main() { 17 | vec4 pos = vec4(VertexPosition.x, VertexPosition.y, 0.0, 1.0); 18 | pos.x += offset.x; 19 | pos.y -= offset.y; 20 | 21 | mat4 modelView = view * model; 22 | 23 | modelView[0].xyz = vec3( 1.0, 0.0, 0.0 ); 24 | modelView[1].xyz = vec3( 0.0, 1.0, 0.0 ); 25 | modelView[2].xyz = vec3( 0.0, 0.0, 1.0 ); 26 | 27 | gl_Position = projection * modelView * pos; 28 | 29 | fragColor = VertexColor; 30 | texCoords = VertexTexCoord; 31 | } 32 | -------------------------------------------------------------------------------- /internal/system/opengl/shaders/sprite.frag: -------------------------------------------------------------------------------- 1 | #version 330 core 2 | 3 | in vec3 fragColor; 4 | in vec2 texCoords; 5 | 6 | out vec4 FragColor; 7 | 8 | uniform sampler2D tex; 9 | 10 | void main() { 11 | vec2 var_TexCoords = texCoords; 12 | vec4 texColor = texture(tex, var_TexCoords); 13 | 14 | if(texColor.a < 0.1) 15 | discard; 16 | 17 | FragColor = texColor * vec4(fragColor, 1.0); 18 | } 19 | -------------------------------------------------------------------------------- /internal/system/opengl/shaders/sprite.vert: -------------------------------------------------------------------------------- 1 | #version 330 core 2 | 3 | layout(location = 0) in vec3 VertexPosition; 4 | layout(location = 1) in vec3 VertexColor; 5 | layout(location = 2) in vec2 VertexTexCoord; 6 | 7 | uniform mat4 model; 8 | uniform mat4 view; 9 | uniform mat4 projection; 10 | uniform mat4 rotation; 11 | uniform vec2 size; 12 | uniform vec2 offset; 13 | 14 | out vec3 fragColor; 15 | out vec2 texCoords; 16 | 17 | void main() { 18 | vec4 pos = vec4(VertexPosition.x, VertexPosition.y, 0.0, 1.0); 19 | pos = rotation * pos; 20 | pos.x += offset.x; 21 | pos.y -= offset.y; 22 | 23 | mat4 modelView = view * model; 24 | 25 | modelView[0].xyz = vec3( 1.0, 0.0, 0.0 ); 26 | modelView[1].xyz = vec3( 0.0, 1.0, 0.0 ); 27 | modelView[2].xyz = vec3( 0.0, 0.0, 1.0 ); 28 | 29 | gl_Position = projection * modelView * pos; 30 | 31 | fragColor = VertexColor; 32 | texCoords = VertexTexCoord; 33 | } 34 | -------------------------------------------------------------------------------- /internal/window/keystate.go: -------------------------------------------------------------------------------- 1 | package window 2 | 3 | import ( 4 | "github.com/veandco/go-sdl2/sdl" 5 | ) 6 | 7 | type KeyState struct { 8 | window *sdl.Window 9 | states map[sdl.Keycode]bool 10 | } 11 | 12 | func NewKeyState(window *sdl.Window) *KeyState { 13 | ks := new(KeyState) 14 | ks.window = window 15 | ks.states = map[sdl.Keycode]bool{ 16 | sdl.K_RETURN: false, 17 | sdl.K_ESCAPE: false, 18 | sdl.K_BACKSPACE: false, 19 | sdl.K_TAB: false, 20 | sdl.K_SPACE: false, 21 | sdl.K_EXCLAIM: false, 22 | sdl.K_QUOTEDBL: false, 23 | sdl.K_HASH: false, 24 | sdl.K_PERCENT: false, 25 | sdl.K_DOLLAR: false, 26 | sdl.K_AMPERSAND: false, 27 | sdl.K_QUOTE: false, 28 | sdl.K_LEFTPAREN: false, 29 | sdl.K_RIGHTPAREN: false, 30 | sdl.K_ASTERISK: false, 31 | sdl.K_PLUS: false, 32 | sdl.K_COMMA: false, 33 | sdl.K_MINUS: false, 34 | sdl.K_PERIOD: false, 35 | sdl.K_SLASH: false, 36 | sdl.K_0: false, 37 | sdl.K_1: false, 38 | sdl.K_2: false, 39 | sdl.K_3: false, 40 | sdl.K_4: false, 41 | sdl.K_5: false, 42 | sdl.K_6: false, 43 | sdl.K_7: false, 44 | sdl.K_8: false, 45 | sdl.K_9: false, 46 | sdl.K_COLON: false, 47 | sdl.K_SEMICOLON: false, 48 | sdl.K_LESS: false, 49 | sdl.K_EQUALS: false, 50 | sdl.K_GREATER: false, 51 | sdl.K_QUESTION: false, 52 | sdl.K_AT: false, 53 | sdl.K_LEFTBRACKET: false, 54 | sdl.K_BACKSLASH: false, 55 | sdl.K_RIGHTBRACKET: false, 56 | sdl.K_CARET: false, 57 | sdl.K_UNDERSCORE: false, 58 | sdl.K_BACKQUOTE: false, 59 | sdl.K_a: false, 60 | sdl.K_b: false, 61 | sdl.K_c: false, 62 | sdl.K_d: false, 63 | sdl.K_e: false, 64 | sdl.K_f: false, 65 | sdl.K_g: false, 66 | sdl.K_h: false, 67 | sdl.K_i: false, 68 | sdl.K_j: false, 69 | sdl.K_k: false, 70 | sdl.K_l: false, 71 | sdl.K_m: false, 72 | sdl.K_n: false, 73 | sdl.K_o: false, 74 | sdl.K_p: false, 75 | sdl.K_q: false, 76 | sdl.K_r: false, 77 | sdl.K_s: false, 78 | sdl.K_t: false, 79 | sdl.K_u: false, 80 | sdl.K_v: false, 81 | sdl.K_w: false, 82 | sdl.K_x: false, 83 | sdl.K_y: false, 84 | sdl.K_z: false, 85 | sdl.K_CAPSLOCK: false, 86 | sdl.K_F1: false, 87 | sdl.K_F2: false, 88 | sdl.K_F3: false, 89 | sdl.K_F4: false, 90 | sdl.K_F5: false, 91 | sdl.K_F6: false, 92 | sdl.K_F7: false, 93 | sdl.K_F8: false, 94 | sdl.K_F9: false, 95 | sdl.K_F10: false, 96 | sdl.K_F11: false, 97 | sdl.K_F12: false, 98 | sdl.K_PRINTSCREEN: false, 99 | sdl.K_SCROLLLOCK: false, 100 | sdl.K_PAUSE: false, 101 | sdl.K_INSERT: false, 102 | sdl.K_HOME: false, 103 | sdl.K_PAGEUP: false, 104 | sdl.K_DELETE: false, 105 | sdl.K_END: false, 106 | sdl.K_PAGEDOWN: false, 107 | sdl.K_RIGHT: false, 108 | sdl.K_LEFT: false, 109 | sdl.K_DOWN: false, 110 | sdl.K_UP: false, 111 | sdl.K_NUMLOCKCLEAR: false, 112 | sdl.K_KP_DIVIDE: false, 113 | sdl.K_KP_MULTIPLY: false, 114 | sdl.K_KP_MINUS: false, 115 | sdl.K_KP_PLUS: false, 116 | sdl.K_KP_ENTER: false, 117 | sdl.K_KP_1: false, 118 | sdl.K_KP_2: false, 119 | sdl.K_KP_3: false, 120 | sdl.K_KP_4: false, 121 | sdl.K_KP_5: false, 122 | sdl.K_KP_6: false, 123 | sdl.K_KP_7: false, 124 | sdl.K_KP_8: false, 125 | sdl.K_KP_9: false, 126 | sdl.K_KP_0: false, 127 | sdl.K_KP_PERIOD: false, 128 | sdl.K_APPLICATION: false, 129 | sdl.K_POWER: false, 130 | sdl.K_KP_EQUALS: false, 131 | sdl.K_F13: false, 132 | sdl.K_F14: false, 133 | sdl.K_F15: false, 134 | sdl.K_F16: false, 135 | sdl.K_F17: false, 136 | sdl.K_F18: false, 137 | sdl.K_F19: false, 138 | sdl.K_F20: false, 139 | sdl.K_F21: false, 140 | sdl.K_F22: false, 141 | sdl.K_F23: false, 142 | sdl.K_F24: false, 143 | sdl.K_EXECUTE: false, 144 | sdl.K_HELP: false, 145 | sdl.K_MENU: false, 146 | sdl.K_SELECT: false, 147 | sdl.K_STOP: false, 148 | sdl.K_AGAIN: false, 149 | sdl.K_UNDO: false, 150 | sdl.K_CUT: false, 151 | sdl.K_COPY: false, 152 | sdl.K_PASTE: false, 153 | sdl.K_FIND: false, 154 | sdl.K_MUTE: false, 155 | sdl.K_VOLUMEUP: false, 156 | sdl.K_VOLUMEDOWN: false, 157 | sdl.K_KP_COMMA: false, 158 | sdl.K_KP_EQUALSAS400: false, 159 | sdl.K_ALTERASE: false, 160 | sdl.K_SYSREQ: false, 161 | sdl.K_CANCEL: false, 162 | sdl.K_CLEAR: false, 163 | sdl.K_PRIOR: false, 164 | sdl.K_RETURN2: false, 165 | sdl.K_SEPARATOR: false, 166 | sdl.K_OUT: false, 167 | sdl.K_OPER: false, 168 | sdl.K_CLEARAGAIN: false, 169 | sdl.K_CRSEL: false, 170 | sdl.K_EXSEL: false, 171 | sdl.K_KP_00: false, 172 | sdl.K_KP_000: false, 173 | sdl.K_THOUSANDSSEPARATOR: false, 174 | sdl.K_DECIMALSEPARATOR: false, 175 | sdl.K_CURRENCYUNIT: false, 176 | sdl.K_CURRENCYSUBUNIT: false, 177 | sdl.K_KP_LEFTPAREN: false, 178 | sdl.K_KP_RIGHTPAREN: false, 179 | sdl.K_KP_LEFTBRACE: false, 180 | sdl.K_KP_RIGHTBRACE: false, 181 | sdl.K_KP_TAB: false, 182 | sdl.K_KP_BACKSPACE: false, 183 | sdl.K_KP_A: false, 184 | sdl.K_KP_B: false, 185 | sdl.K_KP_C: false, 186 | sdl.K_KP_D: false, 187 | sdl.K_KP_E: false, 188 | sdl.K_KP_F: false, 189 | sdl.K_KP_XOR: false, 190 | sdl.K_KP_POWER: false, 191 | sdl.K_KP_PERCENT: false, 192 | sdl.K_KP_LESS: false, 193 | sdl.K_KP_GREATER: false, 194 | sdl.K_KP_AMPERSAND: false, 195 | sdl.K_KP_DBLAMPERSAND: false, 196 | sdl.K_KP_VERTICALBAR: false, 197 | sdl.K_KP_DBLVERTICALBAR: false, 198 | sdl.K_KP_COLON: false, 199 | sdl.K_KP_HASH: false, 200 | sdl.K_KP_SPACE: false, 201 | sdl.K_KP_AT: false, 202 | sdl.K_KP_EXCLAM: false, 203 | sdl.K_KP_MEMSTORE: false, 204 | sdl.K_KP_MEMRECALL: false, 205 | sdl.K_KP_MEMCLEAR: false, 206 | sdl.K_KP_MEMADD: false, 207 | sdl.K_KP_MEMSUBTRACT: false, 208 | sdl.K_KP_MEMMULTIPLY: false, 209 | sdl.K_KP_MEMDIVIDE: false, 210 | sdl.K_KP_PLUSMINUS: false, 211 | sdl.K_KP_CLEAR: false, 212 | sdl.K_KP_CLEARENTRY: false, 213 | sdl.K_KP_BINARY: false, 214 | sdl.K_KP_OCTAL: false, 215 | sdl.K_KP_DECIMAL: false, 216 | sdl.K_KP_HEXADECIMAL: false, 217 | sdl.K_LCTRL: false, 218 | sdl.K_LSHIFT: false, 219 | sdl.K_LALT: false, 220 | sdl.K_LGUI: false, 221 | sdl.K_RCTRL: false, 222 | sdl.K_RSHIFT: false, 223 | sdl.K_RALT: false, 224 | sdl.K_RGUI: false, 225 | sdl.K_MODE: false, 226 | sdl.K_AUDIONEXT: false, 227 | sdl.K_AUDIOPREV: false, 228 | sdl.K_AUDIOSTOP: false, 229 | sdl.K_AUDIOPLAY: false, 230 | sdl.K_AUDIOMUTE: false, 231 | sdl.K_MEDIASELECT: false, 232 | sdl.K_WWW: false, 233 | sdl.K_MAIL: false, 234 | sdl.K_CALCULATOR: false, 235 | sdl.K_COMPUTER: false, 236 | sdl.K_AC_SEARCH: false, 237 | sdl.K_AC_HOME: false, 238 | sdl.K_AC_BACK: false, 239 | sdl.K_AC_FORWARD: false, 240 | sdl.K_AC_STOP: false, 241 | sdl.K_AC_REFRESH: false, 242 | sdl.K_AC_BOOKMARKS: false, 243 | sdl.K_BRIGHTNESSDOWN: false, 244 | sdl.K_BRIGHTNESSUP: false, 245 | sdl.K_DISPLAYSWITCH: false, 246 | sdl.K_KBDILLUMTOGGLE: false, 247 | sdl.K_KBDILLUMDOWN: false, 248 | sdl.K_KBDILLUMUP: false, 249 | sdl.K_EJECT: false, 250 | sdl.K_SLEEP: false, 251 | } 252 | 253 | // it's not work for OSX. Runtime Error: Terminating app due to uncaught exception 254 | // 'NSInternalInconsistencyException', 255 | // reason: 'Modifications to the layout engine must not be performed from a background thread after it has been 256 | // accessed from the main thread.' 257 | //go ks.pollEventKeys() 258 | 259 | return ks 260 | } 261 | 262 | func (ks *KeyState) Pressed(keyCode sdl.Keycode) bool { 263 | return ks.states[keyCode] 264 | } 265 | 266 | func (ks *KeyState) Update(event sdl.Event) { 267 | if event == nil { 268 | return 269 | } 270 | 271 | switch event := event.(type) { 272 | case *sdl.KeyboardEvent: 273 | if event.State == sdl.PRESSED { 274 | ks.states[event.Keysym.Sym] = true 275 | } else if event.State == sdl.RELEASED { 276 | ks.states[event.Keysym.Sym] = false 277 | } 278 | } 279 | } 280 | 281 | func (ks *KeyState) pollEventKeys() { 282 | for { 283 | for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() { 284 | switch event := event.(type) { 285 | case *sdl.KeyboardEvent: 286 | if event.State == sdl.PRESSED { 287 | ks.states[event.Keysym.Sym] = true 288 | } else if event.State == sdl.RELEASED { 289 | ks.states[event.Keysym.Sym] = false 290 | } 291 | } 292 | } 293 | } 294 | } 295 | -------------------------------------------------------------------------------- /pkg/graphics/renderer/shaders/sprite.frag: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | layout(location = 0) in vec2 texture_coordinates; 4 | 5 | layout(location = 0) out vec4 fragment_color; 6 | 7 | layout (set = 1, binding = 1) uniform sampler2D sprite_texture; 8 | 9 | layout(push_constant) uniform Constants { 10 | vec2 screen_position; 11 | vec2 screen_size; 12 | vec2 texture_position; 13 | vec2 texture_size; 14 | vec4 color; 15 | } constants; 16 | 17 | void main() { 18 | fragment_color = texture(sprite_texture, texture_coordinates) * uFragColor; 19 | } 20 | -------------------------------------------------------------------------------- /pkg/graphics/renderer/shaders/sprite.vert: -------------------------------------------------------------------------------- 1 | #version 450 2 | 3 | layout(location = 0) in vec2 position; 4 | 5 | layout(location = 0) out vec2 texture_coordinates; 6 | 7 | layout(push_constant) uniform Constants { 8 | vec2 screen_position; 9 | vec2 screen_size; 10 | vec2 texture_position; 11 | vec2 texture_size; 12 | vec4 color; 13 | } constants; 14 | 15 | void main() { 16 | vec2 vertex_position = constants.screen_position - vec2(1.0) + position * constants.screen_size; 17 | gl_Position = vec4(vertex_position, 0.0, 1.0); 18 | 19 | texture_coordinates = constants.texture_position + position * constants.texture_size; 20 | } 21 | -------------------------------------------------------------------------------- /pkg/graphics/renderer/sprite_renderer.go: -------------------------------------------------------------------------------- 1 | package renderer 2 | 3 | import ( 4 | _ "embed" 5 | 6 | "github.com/project-midgard/midgarts/pkg/graphics" 7 | ) 8 | 9 | const NumVertexAttributes = 3 10 | 11 | var ( 12 | //go:embed shaders/sprite.vert 13 | vertexShader string 14 | 15 | //go:embed shaders/sprite.frag 16 | fragmentShader string 17 | ) 18 | 19 | type Renderer struct { 20 | pipeline *graphics.Pipeline 21 | } 22 | 23 | func New() *Renderer { 24 | pipeline := graphics.StartPipeline() 25 | 26 | r := &Renderer{} 27 | r.pipeline = pipeline 28 | 29 | return r 30 | } 31 | -------------------------------------------------------------------------------- /pkg/graphics/shader.go: -------------------------------------------------------------------------------- 1 | package graphics 2 | -------------------------------------------------------------------------------- /pkg/version/version.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | import ( 4 | "fmt" 5 | "runtime/debug" 6 | ) 7 | 8 | func Get() string { 9 | var revision string 10 | var modified bool 11 | 12 | bi, ok := debug.ReadBuildInfo() 13 | if ok { 14 | for _, s := range bi.Settings { 15 | switch s.Key { 16 | case "vcs.revision": 17 | revision = s.Value 18 | case "vcs.modified": 19 | if s.Value == "true" { 20 | modified = true 21 | } 22 | } 23 | } 24 | } 25 | 26 | if revision == "" { 27 | return "unavailable" 28 | } 29 | 30 | if len(revision) > 7 { 31 | revision = revision[:7] 32 | } 33 | 34 | if modified { 35 | return fmt.Sprintf("%s-dirty", revision) 36 | } 37 | 38 | return revision 39 | } 40 | --------------------------------------------------------------------------------