├── .gitignore ├── LICENSE ├── README.md ├── build.gradle └── src ├── api └── java │ └── com │ └── xcompwiz │ └── lookingglass │ └── api │ ├── APIInstanceProvider.java │ ├── APIUndefined.java │ ├── APIVersionRemoved.java │ ├── APIVersionUndefined.java │ ├── IWorldViewAPI.java │ ├── animator │ ├── CameraAnimatorPivot.java │ ├── CameraAnimatorPlayer.java │ └── ICameraAnimator.java │ ├── event │ └── ClientWorldInfoEvent.java │ ├── hook │ └── WorldViewAPI2.java │ ├── package-info.java │ └── view │ ├── IViewCamera.java │ └── IWorldView.java └── main ├── java └── com │ └── xcompwiz │ └── lookingglass │ ├── LookingGlass.java │ ├── apiimpl │ ├── APIProviderImpl.java │ ├── APIWrapper.java │ ├── InternalAPI.java │ ├── LookingGlassAPI2Wrapper.java │ ├── LookingGlassAPIWrapper.java │ └── WrapperBuilder.java │ ├── client │ ├── ClientProxy.java │ ├── proxyworld │ │ ├── ProxyWorld.java │ │ ├── ProxyWorldManager.java │ │ ├── ViewCameraImpl.java │ │ └── WorldView.java │ └── render │ │ ├── FrameBufferContainer.java │ │ ├── RenderPortal.java │ │ └── RenderUtils.java │ ├── command │ ├── CommandBaseAdv.java │ └── CommandCreateView.java │ ├── core │ ├── CommonProxy.java │ └── LookingGlassForgeEventHandler.java │ ├── entity │ ├── EntityCamera.java │ └── EntityPortal.java │ ├── imc │ ├── IMCAPIRegister.java │ └── IMCHandler.java │ ├── log │ └── LoggerUtils.java │ ├── network │ ├── LookingGlassPacketManager.java │ ├── PacketHolder.java │ ├── ServerPacketDispatcher.java │ └── packet │ │ ├── PacketChunkInfo.java │ │ ├── PacketCloseView.java │ │ ├── PacketCreateView.java │ │ ├── PacketHandlerBase.java │ │ ├── PacketRequestChunk.java │ │ ├── PacketRequestTE.java │ │ ├── PacketRequestWorldInfo.java │ │ ├── PacketTileEntityNBT.java │ │ └── PacketWorldInfo.java │ ├── proxyworld │ ├── ChunkFinder.java │ ├── ChunkFinderManager.java │ ├── LookingGlassEventHandler.java │ ├── ModConfigs.java │ └── SubChunkUtils.java │ ├── render │ ├── PerspectiveRenderManager.java │ └── WorldViewRenderManager.java │ └── utils │ └── MathUtils.java └── resources ├── assets └── lookingglass │ └── lang │ └── en_US.lang ├── logo.png └── mcmod.info /.gitignore: -------------------------------------------------------------------------------- 1 | __* 2 | *.bak 3 | *.xlsx 4 | 5 | /releases 6 | /test 7 | 8 | /.gradle 9 | /.settings 10 | /bin 11 | /build 12 | /gradle 13 | /run 14 | 15 | /.classpath 16 | /.project 17 | /gradlew 18 | /gradlew.bat 19 | /forge*.zip 20 | 21 | /build.properties 22 | /locations.gradle 23 | 24 | /todo.txt 25 | /changes.txt 26 | /changelog.txt 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | ========================== 3 | 4 | Version 3, 29 June 2007 5 | 6 | Copyright © 2007 Free Software Foundation, Inc. <> 7 | 8 | Everyone is permitted to copy and distribute verbatim copies of this license 9 | document, but changing it is not allowed. 10 | 11 | ## Preamble 12 | 13 | The GNU General Public License is a free, copyleft license for software and other 14 | kinds of works. 15 | 16 | The licenses for most software and other practical works are designed to take away 17 | your freedom to share and change the works. By contrast, the GNU General Public 18 | License is intended to guarantee your freedom to share and change all versions of a 19 | program--to make sure it remains free software for all its users. We, the Free 20 | Software Foundation, use the GNU General Public License for most of our software; it 21 | applies also to any other work released this way by its authors. You can apply it to 22 | your programs, too. 23 | 24 | When we speak of free software, we are referring to freedom, not price. Our General 25 | Public Licenses are designed to make sure that you have the freedom to distribute 26 | copies of free software (and charge for them if you wish), that you receive source 27 | code or can get it if you want it, that you can change the software or use pieces of 28 | it in new free programs, and that you know you can do these things. 29 | 30 | To protect your rights, we need to prevent others from denying you these rights or 31 | asking you to surrender the rights. Therefore, you have certain responsibilities if 32 | you distribute copies of the software, or if you modify it: responsibilities to 33 | respect the freedom of others. 34 | 35 | For example, if you distribute copies of such a program, whether gratis or for a fee, 36 | you must pass on to the recipients the same freedoms that you received. You must make 37 | sure that they, too, receive or can get the source code. And you must show them these 38 | terms so they know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: (1) assert 41 | copyright on the software, and (2) offer you this License giving you legal permission 42 | to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains that there is 45 | no warranty for this free software. For both users' and authors' sake, the GPL 46 | requires that modified versions be marked as changed, so that their problems will not 47 | be attributed erroneously to authors of previous versions. 48 | 49 | Some devices are designed to deny users access to install or run modified versions of 50 | the software inside them, although the manufacturer can do so. This is fundamentally 51 | incompatible with the aim of protecting users' freedom to change the software. The 52 | systematic pattern of such abuse occurs in the area of products for individuals to 53 | use, which is precisely where it is most unacceptable. Therefore, we have designed 54 | this version of the GPL to prohibit the practice for those products. If such problems 55 | arise substantially in other domains, we stand ready to extend this provision to 56 | those domains in future versions of the GPL, as needed to protect the freedom of 57 | users. 58 | 59 | Finally, every program is threatened constantly by software patents. States should 60 | not allow patents to restrict development and use of software on general-purpose 61 | computers, but in those that do, we wish to avoid the special danger that patents 62 | applied to a free program could make it effectively proprietary. To prevent this, the 63 | GPL assures that patents cannot be used to render the program non-free. 64 | 65 | The precise terms and conditions for copying, distribution and modification follow. 66 | 67 | ## TERMS AND CONDITIONS 68 | 69 | ### 0. Definitions. 70 | 71 | “This License” refers to version 3 of the GNU General Public License. 72 | 73 | “Copyright” also means copyright-like laws that apply to other kinds of 74 | works, such as semiconductor masks. 75 | 76 | “The Program” refers to any copyrightable work licensed under this 77 | License. Each licensee is addressed as “you”. “Licensees” and 78 | “recipients” may be individuals or organizations. 79 | 80 | To “modify” a work means to copy from or adapt all or part of the work in 81 | a fashion requiring copyright permission, other than the making of an exact copy. The 82 | resulting work is called a “modified version” of the earlier work or a 83 | work “based on” the earlier work. 84 | 85 | A “covered work” means either the unmodified Program or a work based on 86 | the Program. 87 | 88 | To “propagate” a work means to do anything with it that, without 89 | permission, would make you directly or secondarily liable for infringement under 90 | applicable copyright law, except executing it on a computer or modifying a private 91 | copy. Propagation includes copying, distribution (with or without modification), 92 | making available to the public, and in some countries other activities as well. 93 | 94 | To “convey” a work means any kind of propagation that enables other 95 | parties to make or receive copies. Mere interaction with a user through a computer 96 | network, with no transfer of a copy, is not conveying. 97 | 98 | An interactive user interface displays “Appropriate Legal Notices” to the 99 | extent that it includes a convenient and prominently visible feature that (1) 100 | displays an appropriate copyright notice, and (2) tells the user that there is no 101 | warranty for the work (except to the extent that warranties are provided), that 102 | licensees may convey the work under this License, and how to view a copy of this 103 | License. If the interface presents a list of user commands or options, such as a 104 | menu, a prominent item in the list meets this criterion. 105 | 106 | ### 1. Source Code. 107 | 108 | The “source code” for a work means the preferred form of the work for 109 | making modifications to it. “Object code” means any non-source form of a 110 | work. 111 | 112 | A “Standard Interface” means an interface that either is an official 113 | standard defined by a recognized standards body, or, in the case of interfaces 114 | specified for a particular programming language, one that is widely used among 115 | developers working in that language. 116 | 117 | The “System Libraries” of an executable work include anything, other than 118 | the work as a whole, that (a) is included in the normal form of packaging a Major 119 | Component, but which is not part of that Major Component, and (b) serves only to 120 | enable use of the work with that Major Component, or to implement a Standard 121 | Interface for which an implementation is available to the public in source code form. 122 | A “Major Component”, in this context, means a major essential component 123 | (kernel, window system, and so on) of the specific operating system (if any) on which 124 | the executable work runs, or a compiler used to produce the work, or an object code 125 | interpreter used to run it. 126 | 127 | The “Corresponding Source” for a work in object code form means all the 128 | source code needed to generate, install, and (for an executable work) run the object 129 | code and to modify the work, including scripts to control those activities. However, 130 | it does not include the work's System Libraries, or general-purpose tools or 131 | generally available free programs which are used unmodified in performing those 132 | activities but which are not part of the work. For example, Corresponding Source 133 | includes interface definition files associated with source files for the work, and 134 | the source code for shared libraries and dynamically linked subprograms that the work 135 | is specifically designed to require, such as by intimate data communication or 136 | control flow between those subprograms and other parts of the work. 137 | 138 | The Corresponding Source need not include anything that users can regenerate 139 | automatically from other parts of the Corresponding Source. 140 | 141 | The Corresponding Source for a work in source code form is that same work. 142 | 143 | ### 2. Basic Permissions. 144 | 145 | All rights granted under this License are granted for the term of copyright on the 146 | Program, and are irrevocable provided the stated conditions are met. This License 147 | explicitly affirms your unlimited permission to run the unmodified Program. The 148 | output from running a covered work is covered by this License only if the output, 149 | given its content, constitutes a covered work. This License acknowledges your rights 150 | of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not convey, without 153 | conditions so long as your license otherwise remains in force. You may convey covered 154 | works to others for the sole purpose of having them make modifications exclusively 155 | for you, or provide you with facilities for running those works, provided that you 156 | comply with the terms of this License in conveying all material for which you do not 157 | control copyright. Those thus making or running the covered works for you must do so 158 | exclusively on your behalf, under your direction and control, on terms that prohibit 159 | them from making any copies of your copyrighted material outside their relationship 160 | with you. 161 | 162 | Conveying under any other circumstances is permitted solely under the conditions 163 | stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 164 | 165 | ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 166 | 167 | No covered work shall be deemed part of an effective technological measure under any 168 | applicable law fulfilling obligations under article 11 of the WIPO copyright treaty 169 | adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention 170 | of such measures. 171 | 172 | When you convey a covered work, you waive any legal power to forbid circumvention of 173 | technological measures to the extent such circumvention is effected by exercising 174 | rights under this License with respect to the covered work, and you disclaim any 175 | intention to limit operation or modification of the work as a means of enforcing, 176 | against the work's users, your or third parties' legal rights to forbid circumvention 177 | of technological measures. 178 | 179 | ### 4. Conveying Verbatim Copies. 180 | 181 | You may convey verbatim copies of the Program's source code as you receive it, in any 182 | medium, provided that you conspicuously and appropriately publish on each copy an 183 | appropriate copyright notice; keep intact all notices stating that this License and 184 | any non-permissive terms added in accord with section 7 apply to the code; keep 185 | intact all notices of the absence of any warranty; and give all recipients a copy of 186 | this License along with the Program. 187 | 188 | You may charge any price or no price for each copy that you convey, and you may offer 189 | support or warranty protection for a fee. 190 | 191 | ### 5. Conveying Modified Source Versions. 192 | 193 | You may convey a work based on the Program, or the modifications to produce it from 194 | the Program, in the form of source code under the terms of section 4, provided that 195 | you also meet all of these conditions: 196 | 197 | * **a)** The work must carry prominent notices stating that you modified it, and giving a 198 | relevant date. 199 | * **b)** The work must carry prominent notices stating that it is released under this 200 | License and any conditions added under section 7. This requirement modifies the 201 | requirement in section 4 to “keep intact all notices”. 202 | * **c)** You must license the entire work, as a whole, under this License to anyone who 203 | comes into possession of a copy. This License will therefore apply, along with any 204 | applicable section 7 additional terms, to the whole of the work, and all its parts, 205 | regardless of how they are packaged. This License gives no permission to license the 206 | work in any other way, but it does not invalidate such permission if you have 207 | separately received it. 208 | * **d)** If the work has interactive user interfaces, each must display Appropriate Legal 209 | Notices; however, if the Program has interactive interfaces that do not display 210 | Appropriate Legal Notices, your work need not make them do so. 211 | 212 | A compilation of a covered work with other separate and independent works, which are 213 | not by their nature extensions of the covered work, and which are not combined with 214 | it such as to form a larger program, in or on a volume of a storage or distribution 215 | medium, is called an “aggregate” if the compilation and its resulting 216 | copyright are not used to limit the access or legal rights of the compilation's users 217 | beyond what the individual works permit. Inclusion of a covered work in an aggregate 218 | does not cause this License to apply to the other parts of the aggregate. 219 | 220 | ### 6. Conveying Non-Source Forms. 221 | 222 | You may convey a covered work in object code form under the terms of sections 4 and 223 | 5, provided that you also convey the machine-readable Corresponding Source under the 224 | terms of this License, in one of these ways: 225 | 226 | * **a)** Convey the object code in, or embodied in, a physical product (including a 227 | physical distribution medium), accompanied by the Corresponding Source fixed on a 228 | durable physical medium customarily used for software interchange. 229 | * **b)** Convey the object code in, or embodied in, a physical product (including a 230 | physical distribution medium), accompanied by a written offer, valid for at least 231 | three years and valid for as long as you offer spare parts or customer support for 232 | that product model, to give anyone who possesses the object code either (1) a copy of 233 | the Corresponding Source for all the software in the product that is covered by this 234 | License, on a durable physical medium customarily used for software interchange, for 235 | a price no more than your reasonable cost of physically performing this conveying of 236 | source, or (2) access to copy the Corresponding Source from a network server at no 237 | charge. 238 | * **c)** Convey individual copies of the object code with a copy of the written offer to 239 | provide the Corresponding Source. This alternative is allowed only occasionally and 240 | noncommercially, and only if you received the object code with such an offer, in 241 | accord with subsection 6b. 242 | * **d)** Convey the object code by offering access from a designated place (gratis or for 243 | a charge), and offer equivalent access to the Corresponding Source in the same way 244 | through the same place at no further charge. You need not require recipients to copy 245 | the Corresponding Source along with the object code. If the place to copy the object 246 | code is a network server, the Corresponding Source may be on a different server 247 | (operated by you or a third party) that supports equivalent copying facilities, 248 | provided you maintain clear directions next to the object code saying where to find 249 | the Corresponding Source. Regardless of what server hosts the Corresponding Source, 250 | you remain obligated to ensure that it is available for as long as needed to satisfy 251 | these requirements. 252 | * **e)** Convey the object code using peer-to-peer transmission, provided you inform 253 | other peers where the object code and Corresponding Source of the work are being 254 | offered to the general public at no charge under subsection 6d. 255 | 256 | A separable portion of the object code, whose source code is excluded from the 257 | Corresponding Source as a System Library, need not be included in conveying the 258 | object code work. 259 | 260 | A “User Product” is either (1) a “consumer product”, which 261 | means any tangible personal property which is normally used for personal, family, or 262 | household purposes, or (2) anything designed or sold for incorporation into a 263 | dwelling. In determining whether a product is a consumer product, doubtful cases 264 | shall be resolved in favor of coverage. For a particular product received by a 265 | particular user, “normally used” refers to a typical or common use of 266 | that class of product, regardless of the status of the particular user or of the way 267 | in which the particular user actually uses, or expects or is expected to use, the 268 | product. A product is a consumer product regardless of whether the product has 269 | substantial commercial, industrial or non-consumer uses, unless such uses represent 270 | the only significant mode of use of the product. 271 | 272 | “Installation Information” for a User Product means any methods, 273 | procedures, authorization keys, or other information required to install and execute 274 | modified versions of a covered work in that User Product from a modified version of 275 | its Corresponding Source. The information must suffice to ensure that the continued 276 | functioning of the modified object code is in no case prevented or interfered with 277 | solely because modification has been made. 278 | 279 | If you convey an object code work under this section in, or with, or specifically for 280 | use in, a User Product, and the conveying occurs as part of a transaction in which 281 | the right of possession and use of the User Product is transferred to the recipient 282 | in perpetuity or for a fixed term (regardless of how the transaction is 283 | characterized), the Corresponding Source conveyed under this section must be 284 | accompanied by the Installation Information. But this requirement does not apply if 285 | neither you nor any third party retains the ability to install modified object code 286 | on the User Product (for example, the work has been installed in ROM). 287 | 288 | The requirement to provide Installation Information does not include a requirement to 289 | continue to provide support service, warranty, or updates for a work that has been 290 | modified or installed by the recipient, or for the User Product in which it has been 291 | modified or installed. Access to a network may be denied when the modification itself 292 | materially and adversely affects the operation of the network or violates the rules 293 | and protocols for communication across the network. 294 | 295 | Corresponding Source conveyed, and Installation Information provided, in accord with 296 | this section must be in a format that is publicly documented (and with an 297 | implementation available to the public in source code form), and must require no 298 | special password or key for unpacking, reading or copying. 299 | 300 | ### 7. Additional Terms. 301 | 302 | “Additional permissions” are terms that supplement the terms of this 303 | License by making exceptions from one or more of its conditions. Additional 304 | permissions that are applicable to the entire Program shall be treated as though they 305 | were included in this License, to the extent that they are valid under applicable 306 | law. If additional permissions apply only to part of the Program, that part may be 307 | used separately under those permissions, but the entire Program remains governed by 308 | this License without regard to the additional permissions. 309 | 310 | When you convey a copy of a covered work, you may at your option remove any 311 | additional permissions from that copy, or from any part of it. (Additional 312 | permissions may be written to require their own removal in certain cases when you 313 | modify the work.) You may place additional permissions on material, added by you to a 314 | covered work, for which you have or can give appropriate copyright permission. 315 | 316 | Notwithstanding any other provision of this License, for material you add to a 317 | covered work, you may (if authorized by the copyright holders of that material) 318 | supplement the terms of this License with terms: 319 | 320 | * **a)** Disclaiming warranty or limiting liability differently from the terms of 321 | sections 15 and 16 of this License; or 322 | * **b)** Requiring preservation of specified reasonable legal notices or author 323 | attributions in that material or in the Appropriate Legal Notices displayed by works 324 | containing it; or 325 | * **c)** Prohibiting misrepresentation of the origin of that material, or requiring that 326 | modified versions of such material be marked in reasonable ways as different from the 327 | original version; or 328 | * **d)** Limiting the use for publicity purposes of names of licensors or authors of the 329 | material; or 330 | * **e)** Declining to grant rights under trademark law for use of some trade names, 331 | trademarks, or service marks; or 332 | * **f)** Requiring indemnification of licensors and authors of that material by anyone 333 | who conveys the material (or modified versions of it) with contractual assumptions of 334 | liability to the recipient, for any liability that these contractual assumptions 335 | directly impose on those licensors and authors. 336 | 337 | All other non-permissive additional terms are considered “further 338 | restrictions” within the meaning of section 10. If the Program as you received 339 | it, or any part of it, contains a notice stating that it is governed by this License 340 | along with a term that is a further restriction, you may remove that term. If a 341 | license document contains a further restriction but permits relicensing or conveying 342 | under this License, you may add to a covered work material governed by the terms of 343 | that license document, provided that the further restriction does not survive such 344 | relicensing or conveying. 345 | 346 | If you add terms to a covered work in accord with this section, you must place, in 347 | the relevant source files, a statement of the additional terms that apply to those 348 | files, or a notice indicating where to find the applicable terms. 349 | 350 | Additional terms, permissive or non-permissive, may be stated in the form of a 351 | separately written license, or stated as exceptions; the above requirements apply 352 | either way. 353 | 354 | ### 8. Termination. 355 | 356 | You may not propagate or modify a covered work except as expressly provided under 357 | this License. Any attempt otherwise to propagate or modify it is void, and will 358 | automatically terminate your rights under this License (including any patent licenses 359 | granted under the third paragraph of section 11). 360 | 361 | However, if you cease all violation of this License, then your license from a 362 | particular copyright holder is reinstated (a) provisionally, unless and until the 363 | copyright holder explicitly and finally terminates your license, and (b) permanently, 364 | if the copyright holder fails to notify you of the violation by some reasonable means 365 | prior to 60 days after the cessation. 366 | 367 | Moreover, your license from a particular copyright holder is reinstated permanently 368 | if the copyright holder notifies you of the violation by some reasonable means, this 369 | is the first time you have received notice of violation of this License (for any 370 | work) from that copyright holder, and you cure the violation prior to 30 days after 371 | your receipt of the notice. 372 | 373 | Termination of your rights under this section does not terminate the licenses of 374 | parties who have received copies or rights from you under this License. If your 375 | rights have been terminated and not permanently reinstated, you do not qualify to 376 | receive new licenses for the same material under section 10. 377 | 378 | ### 9. Acceptance Not Required for Having Copies. 379 | 380 | You are not required to accept this License in order to receive or run a copy of the 381 | Program. Ancillary propagation of a covered work occurring solely as a consequence of 382 | using peer-to-peer transmission to receive a copy likewise does not require 383 | acceptance. However, nothing other than this License grants you permission to 384 | propagate or modify any covered work. These actions infringe copyright if you do not 385 | accept this License. Therefore, by modifying or propagating a covered work, you 386 | indicate your acceptance of this License to do so. 387 | 388 | ### 10. Automatic Licensing of Downstream Recipients. 389 | 390 | Each time you convey a covered work, the recipient automatically receives a license 391 | from the original licensors, to run, modify and propagate that work, subject to this 392 | License. You are not responsible for enforcing compliance by third parties with this 393 | License. 394 | 395 | An “entity transaction” is a transaction transferring control of an 396 | organization, or substantially all assets of one, or subdividing an organization, or 397 | merging organizations. If propagation of a covered work results from an entity 398 | transaction, each party to that transaction who receives a copy of the work also 399 | receives whatever licenses to the work the party's predecessor in interest had or 400 | could give under the previous paragraph, plus a right to possession of the 401 | Corresponding Source of the work from the predecessor in interest, if the predecessor 402 | has it or can get it with reasonable efforts. 403 | 404 | You may not impose any further restrictions on the exercise of the rights granted or 405 | affirmed under this License. For example, you may not impose a license fee, royalty, 406 | or other charge for exercise of rights granted under this License, and you may not 407 | initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging 408 | that any patent claim is infringed by making, using, selling, offering for sale, or 409 | importing the Program or any portion of it. 410 | 411 | ### 11. Patents. 412 | 413 | A “contributor” is a copyright holder who authorizes use under this 414 | License of the Program or a work on which the Program is based. The work thus 415 | licensed is called the contributor's “contributor version”. 416 | 417 | A contributor's “essential patent claims” are all patent claims owned or 418 | controlled by the contributor, whether already acquired or hereafter acquired, that 419 | would be infringed by some manner, permitted by this License, of making, using, or 420 | selling its contributor version, but do not include claims that would be infringed 421 | only as a consequence of further modification of the contributor version. For 422 | purposes of this definition, “control” includes the right to grant patent 423 | sublicenses in a manner consistent with the requirements of this License. 424 | 425 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license 426 | under the contributor's essential patent claims, to make, use, sell, offer for sale, 427 | import and otherwise run, modify and propagate the contents of its contributor 428 | version. 429 | 430 | In the following three paragraphs, a “patent license” is any express 431 | agreement or commitment, however denominated, not to enforce a patent (such as an 432 | express permission to practice a patent or covenant not to sue for patent 433 | infringement). To “grant” such a patent license to a party means to make 434 | such an agreement or commitment not to enforce a patent against the party. 435 | 436 | If you convey a covered work, knowingly relying on a patent license, and the 437 | Corresponding Source of the work is not available for anyone to copy, free of charge 438 | and under the terms of this License, through a publicly available network server or 439 | other readily accessible means, then you must either (1) cause the Corresponding 440 | Source to be so available, or (2) arrange to deprive yourself of the benefit of the 441 | patent license for this particular work, or (3) arrange, in a manner consistent with 442 | the requirements of this License, to extend the patent license to downstream 443 | recipients. “Knowingly relying” means you have actual knowledge that, but 444 | for the patent license, your conveying the covered work in a country, or your 445 | recipient's use of the covered work in a country, would infringe one or more 446 | identifiable patents in that country that you have reason to believe are valid. 447 | 448 | If, pursuant to or in connection with a single transaction or arrangement, you 449 | convey, or propagate by procuring conveyance of, a covered work, and grant a patent 450 | license to some of the parties receiving the covered work authorizing them to use, 451 | propagate, modify or convey a specific copy of the covered work, then the patent 452 | license you grant is automatically extended to all recipients of the covered work and 453 | works based on it. 454 | 455 | A patent license is “discriminatory” if it does not include within the 456 | scope of its coverage, prohibits the exercise of, or is conditioned on the 457 | non-exercise of one or more of the rights that are specifically granted under this 458 | License. You may not convey a covered work if you are a party to an arrangement with 459 | a third party that is in the business of distributing software, under which you make 460 | payment to the third party based on the extent of your activity of conveying the 461 | work, and under which the third party grants, to any of the parties who would receive 462 | the covered work from you, a discriminatory patent license (a) in connection with 463 | copies of the covered work conveyed by you (or copies made from those copies), or (b) 464 | primarily for and in connection with specific products or compilations that contain 465 | the covered work, unless you entered into that arrangement, or that patent license 466 | was granted, prior to 28 March 2007. 467 | 468 | Nothing in this License shall be construed as excluding or limiting any implied 469 | license or other defenses to infringement that may otherwise be available to you 470 | under applicable patent law. 471 | 472 | ### 12. No Surrender of Others' Freedom. 473 | 474 | If conditions are imposed on you (whether by court order, agreement or otherwise) 475 | that contradict the conditions of this License, they do not excuse you from the 476 | conditions of this License. If you cannot convey a covered work so as to satisfy 477 | simultaneously your obligations under this License and any other pertinent 478 | obligations, then as a consequence you may not convey it at all. For example, if you 479 | agree to terms that obligate you to collect a royalty for further conveying from 480 | those to whom you convey the Program, the only way you could satisfy both those terms 481 | and this License would be to refrain entirely from conveying the Program. 482 | 483 | ### 13. Use with the GNU Affero General Public License. 484 | 485 | Notwithstanding any other provision of this License, you have permission to link or 486 | combine any covered work with a work licensed under version 3 of the GNU Affero 487 | General Public License into a single combined work, and to convey the resulting work. 488 | The terms of this License will continue to apply to the part which is the covered 489 | work, but the special requirements of the GNU Affero General Public License, section 490 | 13, concerning interaction through a network will apply to the combination as such. 491 | 492 | ### 14. Revised Versions of this License. 493 | 494 | The Free Software Foundation may publish revised and/or new versions of the GNU 495 | General Public License from time to time. Such new versions will be similar in spirit 496 | to the present version, but may differ in detail to address new problems or concerns. 497 | 498 | Each version is given a distinguishing version number. If the Program specifies that 499 | a certain numbered version of the GNU General Public License “or any later 500 | version” applies to it, you have the option of following the terms and 501 | conditions either of that numbered version or of any later version published by the 502 | Free Software Foundation. If the Program does not specify a version number of the GNU 503 | General Public License, you may choose any version ever published by the Free 504 | Software Foundation. 505 | 506 | If the Program specifies that a proxy can decide which future versions of the GNU 507 | General Public License can be used, that proxy's public statement of acceptance of a 508 | version permanently authorizes you to choose that version for the Program. 509 | 510 | Later license versions may give you additional or different permissions. However, no 511 | additional obligations are imposed on any author or copyright holder as a result of 512 | your choosing to follow a later version. 513 | 514 | ### 15. Disclaimer of Warranty. 515 | 516 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 517 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 518 | PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER 519 | EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 520 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE 521 | QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 522 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 523 | 524 | ### 16. Limitation of Liability. 525 | 526 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY 527 | COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS 528 | PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, 529 | INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 530 | PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE 531 | OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE 532 | WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 533 | POSSIBILITY OF SUCH DAMAGES. 534 | 535 | ### 17. Interpretation of Sections 15 and 16. 536 | 537 | If the disclaimer of warranty and limitation of liability provided above cannot be 538 | given local legal effect according to their terms, reviewing courts shall apply local 539 | law that most closely approximates an absolute waiver of all civil liability in 540 | connection with the Program, unless a warranty or assumption of liability accompanies 541 | a copy of the Program in return for a fee. 542 | 543 | END OF TERMS AND CONDITIONS 544 | 545 | ## How to Apply These Terms to Your New Programs 546 | 547 | If you develop a new program, and you want it to be of the greatest possible use to 548 | the public, the best way to achieve this is to make it free software which everyone 549 | can redistribute and change under these terms. 550 | 551 | To do so, attach the following notices to the program. It is safest to attach them 552 | to the start of each source file to most effectively state the exclusion of warranty; 553 | and each file should have at least the “copyright” line and a pointer to 554 | where the full notice is found. 555 | 556 | 557 | Copyright (C) 558 | 559 | This program is free software: you can redistribute it and/or modify 560 | it under the terms of the GNU General Public License as published by 561 | the Free Software Foundation, either version 3 of the License, or 562 | (at your option) any later version. 563 | 564 | This program is distributed in the hope that it will be useful, 565 | but WITHOUT ANY WARRANTY; without even the implied warranty of 566 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 567 | GNU General Public License for more details. 568 | 569 | You should have received a copy of the GNU General Public License 570 | along with this program. If not, see . 571 | 572 | Also add information on how to contact you by electronic and paper mail. 573 | 574 | If the program does terminal interaction, make it output a short notice like this 575 | when it starts in an interactive mode: 576 | 577 | Copyright (C) 578 | This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. 579 | This is free software, and you are welcome to redistribute it 580 | under certain conditions; type 'show c' for details. 581 | 582 | The hypothetical commands 'show w' and 'show c' should show the appropriate parts of 583 | the General Public License. Of course, your program's commands might be different; 584 | for a GUI interface, you would use an “about box”. 585 | 586 | You should also get your employer (if you work as a programmer) or school, if any, to 587 | sign a “copyright disclaimer” for the program, if necessary. For more 588 | information on this, and how to apply and follow the GNU GPL, see 589 | <>. 590 | 591 | The GNU General Public License does not permit incorporating your program into 592 | proprietary programs. If your program is a subroutine library, you may consider it 593 | more useful to permit linking proprietary applications with the library. If this is 594 | what you want to do, use the GNU Lesser General Public License instead of this 595 | License. But first, please read 596 | <>. 597 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LookingGlass 2 | 3 | LookingGlass is an API mod targeted at providing tools and systems for mods to render locations in other dimensions. 4 | 5 | Since the Minecraft Client has no concept of other dimensions, LookingGlass gives it one and adds systems for the server to send information to clients about worlds other than the one the client is currently in. 6 | 7 | ## Usage Information 8 | It is advised that you work from a released API jar, rather than from the source code provided here. This will help avoid conflicts in Minecraft instances. 9 | 10 | ### Getting the API 11 | #### Maven Repo 12 | ``` 13 | repositories { 14 | maven { 15 | name "xcompwiz" 16 | url "http://maven.xcompwiz.com" 17 | } 18 | } 19 | dependencies { 20 | compile "com.xcompwiz.lookingglass:lookingglass:0.2.0.00:dev" 21 | } 22 | ``` 23 | 24 | #### Manual Download 25 | You can manually obtain an API jar from the LookingGlass CurseForge page: http://minecraft.curseforge.com/mc-mods/230541-lookingglass 26 | 27 | Once equipped with your API version of choice (the most recent one, right?), you can put it in the "jars" folder at the same level as your gradle scripts. You may need to create this folder. 28 | You can then either import the jar manually into your workspace or rerun the gradle command to build your workspace of choice: 29 | ex: gradlew.bat eclipse 30 | 31 | ### Getting Started 32 | LookingGlass uses a very robust but rather complex method of maintaining its API versions. This allows it to support older versions of the API alongside new versions, but there is a small cost of complexity. 33 | It is recommended you look at the APIInstanceProvider class. It should be well documented in its usage and how to get it. Once you have your instance of this class you are ready to get into LookingGlass's API properly. 34 | 35 | ### Available API Interfaces 36 | >It is also possible to get a list of interfaces and their available versions supported from the APIInstanceprovider 37 | 38 | Currently LookingGlass only has one API interface, the "view" API at version 1. 39 | Request your copy of this API from the instance provider using the identifier "view-1". 40 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | ext.forgeversion = "1.7.10-10.13.3.1428-1.7.10" 2 | group = "com.xcompwiz.lookingglass" // http://maven.apache.org/guides/mini/guide-naming-conventions.html 3 | ext.archivesBaseName = "lookingglass" 4 | ext.nameCased = "LookingGlass" 5 | ext.curseId = "230541" // project url is http://minecraft.curseforge.com/mc-mods/230541-lookingglass/ 6 | ext.curseReleaseType = "release" //The release type must be either 'alpha', 'beta', or 'release' 7 | ext.curseIncludeAPI = true 8 | ext.curseIncludeDev = true 9 | 10 | // define some stuff. hereafter referenced as project.varName 11 | ext.configFile = file "build.properties" 12 | ext.smallChangelog = file("changes.txt") 13 | ext.releaseChangelog = file("changelog.txt") 14 | ext.publishChangelog = file("changes.txt") 15 | ext.userHome = System.properties["user.home"] 16 | 17 | // -------------------------- 18 | // End local config 19 | // -------------------------- 20 | 21 | //Configure these through locations.gradle 22 | ext.jarDeploys = [] 23 | ext.devDeploys = [] 24 | ext.APIDeploys = [] 25 | ext.changelogDeploys = [] 26 | 27 | buildscript { 28 | repositories { 29 | mavenCentral() 30 | maven { 31 | name = "forge" 32 | url = "http://files.minecraftforge.net/maven" 33 | } 34 | maven { 35 | name = "sonatype" 36 | url = "https://oss.sonatype.org/content/repositories/snapshots/" 37 | } 38 | } 39 | dependencies { 40 | classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT' 41 | } 42 | } 43 | 44 | repositories { 45 | mavenLocal() 46 | mavenCentral() 47 | ivy { 48 | name 'Forge FS legacy' 49 | artifactPattern "http://files.minecraftforge.net/[module]/[module]-dev-[revision].[ext]" 50 | } 51 | maven { 52 | name 'ForgeFS' 53 | url 'http://files.minecraftforge.net/maven' 54 | } 55 | maven { 56 | name 'MinecraftS3' 57 | url 'http://s3.amazonaws.com/Minecraft.Download/libraries' 58 | } 59 | } 60 | 61 | apply plugin: 'curseforge' 62 | apply plugin: 'forge' 63 | 64 | if (file('locations.gradle').exists()) { 65 | apply from: 'locations.gradle' 66 | } 67 | 68 | if (file('dependencies.gradle').exists()) { 69 | apply from: 'dependencies.gradle' 70 | } 71 | 72 | configFile.withReader { 73 | // read config. it shall from now on be referenced as simply config or as project.config 74 | def prop = new Properties() 75 | prop.load(it) 76 | ext.config = new ConfigSlurper().parse prop 77 | } 78 | 79 | version = "${config.version.super}.${config.version.major}.${config.version.minor}.${config.version.build}" 80 | 81 | // Setup the forge minecraft plugin data. Specify the preferred forge/minecraft version here 82 | minecraft { 83 | version = project.forgeversion 84 | runDir = "../run/client" 85 | 86 | replace "@VERSION@", project.version 87 | } 88 | 89 | processResources 90 | { 91 | // this will ensure that this task is redone when the versions change. 92 | inputs.property "version", {"${project.version}"} 93 | inputs.property "mcversion", {project.minecraft.version} 94 | 95 | // replace stuff in mcmod.info, nothing else 96 | from(sourceSets.main.resources.srcDirs) { 97 | include 'mcmod.info' 98 | 99 | // replace version and mcversion 100 | expand 'version':"${-> project.version}", 'mcversion':project.minecraft.version 101 | } 102 | 103 | // copy everything else, thats not the mcmod.info 104 | from(sourceSets.main.resources.srcDirs) { 105 | exclude 'mcmod.info' 106 | } 107 | } 108 | 109 | // this sets our output jar to have a 'tag' of 'universal' on it 110 | // It also adds the minecraft version in a custom version name 111 | // The result is files named --.jar 112 | jar { 113 | classifier = project.version 114 | version = project.minecraft.version 115 | includeEmptyDirs = false 116 | from sourceSets.api.output 117 | } 118 | 119 | // ------------- 120 | // extra jars 121 | // ------------- 122 | 123 | // because the normal output has been made to be obfuscated 124 | task devJar(type: Jar) { 125 | from sourceSets.main.output 126 | from sourceSets.api.output 127 | from sourceSets.api.allSource 128 | classifier = 'dev' 129 | version = "${project.minecraft.version}-${project.version}" 130 | } 131 | 132 | task apiJar(type: Jar) { 133 | from sourceSets.api.output 134 | from sourceSets.api.allSource 135 | classifier = 'api' 136 | version = "${project.minecraft.version}-${project.version}" 137 | } 138 | 139 | task srcJar(type: Jar) { 140 | from sourceSets.main.java 141 | from sourceSets.api.java 142 | classifier = 'src' 143 | version = "${project.minecraft.version}-${project.version}" 144 | } 145 | 146 | build.dependsOn apiJar, devJar 147 | 148 | // specify artifacts to be uploaded 149 | artifacts { 150 | // the default jar is already here by default 151 | archives devJar 152 | archives apiJar 153 | } 154 | 155 | // --------------------------- 156 | // Changelog and Deployments 157 | // --------------------------- 158 | 159 | task("updateChangelog") { 160 | inputs.file project.smallChangelog 161 | inputs.file project.releaseChangelog 162 | outputs.file project.smallChangelog 163 | outputs.file project.releaseChangelog 164 | 165 | doLast { 166 | def small = project.smallChangelog 167 | def release = project.releaseChangelog 168 | 169 | release.text = "[${project.version}]\n${small.text}\n${release.text}" 170 | small.text = "" 171 | } 172 | } 173 | 174 | task("markChangelog") { 175 | inputs.file project.releaseChangelog 176 | outputs.file project.releaseChangelog 177 | 178 | doLast { 179 | def release = project.releaseChangelog 180 | release.text = "[RELEASE]\n${release.text}" 181 | } 182 | mustRunAfter updateChangelog 183 | } 184 | 185 | project.tasks.curse.dependsOn "markChangelog" 186 | 187 | task "deploy" // creates it for later 188 | task "deployjar" // creates it for later 189 | 190 | project.tasks.deploy.dependsOn project.tasks.deployjar 191 | 192 | project.tasks.deployjar.dependsOn project.tasks.reobf 193 | project.tasks.deployjar.dependsOn project.tasks.devJar 194 | project.tasks.deployjar.dependsOn project.tasks.apiJar 195 | 196 | jarDeploys.each { name, dir -> 197 | def deployer = task("deploy-${name}", type: Copy) { 198 | //from project.configurations.archives // jars, API jars, whatever 199 | 200 | from {project.tasks.jar.getArchivePath()} // just release jar 201 | into dir 202 | dependsOn "reobf" 203 | } 204 | project.tasks.deployjar.dependsOn deployer 205 | 206 | def deleter = task("clean-${name}") << { 207 | fileTree(dir()).each { file -> 208 | if (!file.isDirectory() && file.name.startsWith(project.archivesBaseName)) 209 | file.delete() 210 | } 211 | } 212 | deployer.dependsOn deleter 213 | } 214 | 215 | devDeploys.each { name, dir -> 216 | def deployer = task("deploy-devjar-${name}", type: Copy) { 217 | from {project.tasks.devJar.getArchivePath()} // the dev jar 218 | into dir 219 | dependsOn "devJar" 220 | mustRunAfter "deployjar" 221 | } 222 | project.tasks.deploy.dependsOn deployer 223 | 224 | def deleter = task("clean-devjar-${name}") << { 225 | fileTree(dir()).each { file -> 226 | if (!file.isDirectory() && file.name.startsWith(project.archivesBaseName) && file.name.endsWith("${project.devJar.classifier}.jar")) 227 | file.delete() 228 | } 229 | } 230 | deleter.mustRunAfter "devJar" 231 | deployer.dependsOn deleter 232 | } 233 | 234 | APIDeploys.each { name, dir -> 235 | def deployer = task("deploy-apijar-${name}", type: Copy) { 236 | from {project.tasks.apiJar.getArchivePath()} // the API 237 | into dir 238 | dependsOn "apiJar" 239 | mustRunAfter "deployjar" 240 | } 241 | project.tasks.deploy.dependsOn deployer 242 | 243 | def deleter = task("clean-apijar-${name}") << { 244 | fileTree(dir()).each { file -> 245 | if (!file.isDirectory() && file.name.startsWith(project.archivesBaseName) && file.name.endsWith("${project.apiJar.classifier}.jar")) 246 | file.delete() 247 | } 248 | } 249 | deleter.mustRunAfter "apiJar" 250 | deployer.dependsOn deleter 251 | } 252 | 253 | changelogDeploys.each { name, dir -> 254 | def deployer = task("deploy-changelog-${name}", type: Copy) { 255 | from project.releaseChangelog 256 | into dir 257 | mustRunAfter "updateChangelog" 258 | } 259 | project.tasks.deploy.dependsOn deployer 260 | } 261 | 262 | // ---------------------- 263 | // Incrementer handling 264 | // ---------------------- 265 | 266 | import java.text.DecimalFormat 267 | def formatter = new DecimalFormat('00') 268 | def formatters = [new DecimalFormat('0'), new DecimalFormat('0'), new DecimalFormat('0'), new DecimalFormat('00')] 269 | 270 | // increment tasks 271 | def types = ["super", "major", "minor", "build"] 272 | types.eachWithIndex { type, index -> 273 | def incrementer = task("increment-${type}").doLast { 274 | // increment 275 | int newNum = (config.version[type.toLowerCase()].toString().toInteger()) + 1 276 | config.version[type.toLowerCase()] = formatters[index].format(newNum) 277 | // set lower #'s to 0 278 | types.eachWithIndex { type2, index2 -> 279 | if (index2 > index) { 280 | config.version[type2.toLowerCase()] = formatters[index2].format(0) 281 | } 282 | } 283 | 284 | // write back to the file 285 | configFile.withWriter { 286 | config.toProperties().store(it, "") 287 | } 288 | project.version = "${config.version.super}.${config.version.major}.${config.version.minor}.${config.version.build}" 289 | jar.classifier = "${project.version}" 290 | devJar.version = "${project.minecraft.version}-${project.version}" 291 | apiJar.version = "${project.minecraft.version}-${project.version}" 292 | srcJar.version = "${project.minecraft.version}-${project.version}" 293 | project.tasks.sourceMainJava.replace "@VERSION@", project.version 294 | } 295 | 296 | task("deploy-$type") { 297 | dependsOn incrementer, project.tasks.updateChangelog, project.tasks.deploy 298 | group = "Mystcraft" 299 | description = "Increments ${type.toLowerCase()} by 1 and the deploys the artifacts" 300 | } 301 | 302 | project.tasks.sourceMainJava.mustRunAfter incrementer 303 | project.tasks.updateChangelog.mustRunAfter incrementer 304 | project.tasks.deploy.mustRunAfter incrementer 305 | project.tasks.uploadArchives.mustRunAfter incrementer 306 | project.tasks.processResources.mustRunAfter incrementer 307 | project.tasks.compileApiJava.mustRunAfter incrementer 308 | } 309 | 310 | curse { 311 | apiKey = config.curseforge_key // saved in my properties file. http://minecraft.curseforge.com/my-api-tokens 312 | projectId = project.curseId 313 | releaseType = project.curseReleaseType //The release type must be either 'alpha', 'beta', or 'release' 314 | 315 | changelog = project.publishChangelog.text 316 | 317 | // the default obfuscated jar is uploaded by default 318 | // artifact = project.file("some/jar/to/upload.jar") 319 | if (project.curseIncludeAPI) { 320 | additionalArtifact {project.tasks.apiJar.getArchivePath()} 321 | } 322 | if (project.curseIncludeDev) { 323 | additionalArtifact {project.tasks.devJar.getArchivePath()} 324 | } 325 | 326 | // allows you to add extra compatible MC versions. The one specified in the minecraft{} block is used by default. 327 | // addGameVersion "1.7.1" 328 | // addGameversion "1.7.0", "1.7.4" 329 | } 330 | 331 | // deployment stuff 332 | 333 | configurations { deployerJars } 334 | 335 | dependencies { deployerJars "org.apache.maven.wagon:wagon-ssh:2.2" } 336 | 337 | uploadArchives { 338 | repositories { 339 | mavenDeployer { 340 | configuration = configurations.deployerJars 341 | 342 | repository(url: config.mavenurl) { 343 | authentication(userName: config.mavenuser, password: config.mavenpass) 344 | } 345 | 346 | pom { 347 | groupId = project.group 348 | version = "${-> project.version}" 349 | artifactId = project.archivesBaseName 350 | project { 351 | name project.archivesBaseName 352 | packaging 'jar' 353 | description project.nameCased 354 | //url project.url //'https://github.com/XCompWiz/...' 355 | 356 | developers { 357 | developer { 358 | id 'XCompWiz' 359 | name 'XCompWiz' 360 | roles { role 'developer' } 361 | } 362 | } 363 | } 364 | } 365 | } 366 | } 367 | } -------------------------------------------------------------------------------- /src/api/java/com/xcompwiz/lookingglass/api/APIInstanceProvider.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.api; 2 | 3 | import java.util.Map; 4 | import java.util.Set; 5 | 6 | /** 7 | * The purpose of this interface is simply to provide instances of the API interfaces. Request an instance via IMC (see below). This interface supports 8 | * providing multiple versions of an API, so you can request ex. 'symbol-1' and always get the same interface, enabling the API to move forward without breaking 9 | * compatibility. The provider instance provided to you, as well as any API interface instances created by it, will belong to the mod which requested the 10 | * provider. 11 | * @author xcompwiz 12 | */ 13 | public interface APIInstanceProvider { 14 | 15 | /** 16 | * Returns a constructed version of the requested API. If the API requested doesn't exist then an exception will be thrown. Be wary when attempting to cast 17 | * the returned instance, as, if you try using an interface not included in the class path, you may get missing definition crashes. It is wiser to, after 18 | * verifying success, pass the object to another class dedicated to handling the casting. 19 | * @param api The name of the API and version desired, formatted as ex. "symbol-1". 20 | * @return The requested API instance as an Object. If you get an object, it is guaranteed to be of the requested API and version. 21 | */ 22 | public Object getAPIInstance(String api) throws APIUndefined, APIVersionUndefined, APIVersionRemoved; 23 | 24 | /** 25 | * Returns a collection of all available APIs by name and what versions are supported in this environment. 26 | * @return A map of API names and their available versions 27 | */ 28 | public Map> getAvailableAPIs(); 29 | 30 | //@formatter:off 31 | /* Example Usage 32 | In order to get an instance of this class, send an IMC message to LookingGlass with the key "API" and a string value which is a static method (with classpath) 33 | which takes an instance of APIInstanceProvider as it's only param. 34 | Example: FMLInterModComms.sendMessage("LookingGlass", "API", "com.xcompwiz.newmod.integration.lookingglass.register"); 35 | 36 | public static void register(APIInstanceProvider provider) { 37 | try { 38 | Object apiinst = provider.getAPIInstance("awesomeAPI-3"); 39 | OtherClass.apiGet(apiinst); //At this point, we've got an object of the right interface. 40 | } catch (APIUndefined e) { 41 | // The API we requested doesn't exist. Give up with a nice log message. 42 | } catch (APIVersionUndefined e) { 43 | // The API we requested exists, but the version we wanted is missing in the local environment. We can try falling back to an older version. 44 | } catch (APIVersionRemoved e) { 45 | // The API we requested exists, but the version we wanted has been removed and is no longer supported. Better update. 46 | } 47 | } 48 | */ 49 | //formatter:on 50 | } 51 | -------------------------------------------------------------------------------- /src/api/java/com/xcompwiz/lookingglass/api/APIUndefined.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.api; 2 | 3 | /** 4 | * Thrown in the case of an API name being unrecognized (ex. requesting 'zymbol-1') 5 | * @author xcompwiz 6 | */ 7 | public class APIUndefined extends Exception { 8 | 9 | /** 10 | * Generated Serial UID 11 | */ 12 | private static final long serialVersionUID = 7033833326135545759L; 13 | 14 | public APIUndefined(String string) { 15 | super(string); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/api/java/com/xcompwiz/lookingglass/api/APIVersionRemoved.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.api; 2 | 3 | /** 4 | * Thrown in the case of an API version having been removed entirely and no longer supported. This can be interpreted as the request being for below the minimum 5 | * supported version for the API. 6 | * @author xcompwiz 7 | */ 8 | public class APIVersionRemoved extends Exception { 9 | 10 | /** 11 | * Generated Serial UID 12 | */ 13 | private static final long serialVersionUID = -7702376017254522430L; 14 | 15 | public APIVersionRemoved(String string) { 16 | super(string); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/api/java/com/xcompwiz/lookingglass/api/APIVersionUndefined.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.api; 2 | 3 | /** 4 | * Thrown in the case of an API version not being available (ex. requesting 'symbol-4096') 5 | * @author xcompwiz 6 | */ 7 | public class APIVersionUndefined extends Exception { 8 | 9 | /** 10 | * Generated Serial UID 11 | */ 12 | private static final long serialVersionUID = -6195164554156957083L; 13 | 14 | public APIVersionUndefined(String string) { 15 | super(string); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/api/java/com/xcompwiz/lookingglass/api/IWorldViewAPI.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.api; 2 | 3 | import net.minecraft.util.ChunkCoordinates; 4 | 5 | import com.xcompwiz.lookingglass.api.view.IWorldView; 6 | 7 | import cpw.mods.fml.relauncher.Side; 8 | import cpw.mods.fml.relauncher.SideOnly; 9 | 10 | /** 11 | * @deprecated This interface will be removed in a future version. You should switch to the IWorldViewAPI2. 12 | * @author xcompwiz 13 | */ 14 | @Deprecated 15 | public interface IWorldViewAPI { 16 | 17 | /** 18 | * Creates a world viewer object which will handle the rendering and retrieval of the remote location. Can return null. 19 | * @param dimid The target dimension 20 | * @param coords The coordinates of the target location. If null, world spawn is used. 21 | * @param width Texture resolution width 22 | * @param height Texture resolution height 23 | * @return A IWorldView object for your use or null if something goes wrong. 24 | */ 25 | @SideOnly(Side.CLIENT) 26 | IWorldView createWorldView(Integer dimid, ChunkCoordinates coords, int width, int height); 27 | } 28 | -------------------------------------------------------------------------------- /src/api/java/com/xcompwiz/lookingglass/api/animator/CameraAnimatorPivot.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.api.animator; 2 | 3 | import net.minecraft.block.Block; 4 | import net.minecraft.util.ChunkCoordinates; 5 | import net.minecraft.world.IBlockAccess; 6 | 7 | import com.xcompwiz.lookingglass.api.view.IViewCamera; 8 | 9 | /** 10 | * This is a standard sample implementation of a camera animator. It simply uses the target location as a LookAt target and does a fly pivot around it. It can 11 | * be extended for more control, if desired. 12 | * @author xcompwiz 13 | */ 14 | public class CameraAnimatorPivot implements ICameraAnimator { 15 | /** This is a list of recommended, preset offsets that the animator will choose from. It's use can be overridden via function. */ 16 | private static final int[][] presets = { { 2, 5 }, { 5, 9 }, { 9, 15 }, { 1, 3 }, { 2, 1 }, { 0, 2 } }; 17 | /** This is a pair used when the animator cannot find a good path from the presets. It's use can be overridden via function. */ 18 | private static final int[] defaults = { 1, 3 }; 19 | 20 | private final IViewCamera camera; 21 | private ChunkCoordinates target; 22 | 23 | private boolean positionSet = false; 24 | 25 | private int xCenter; 26 | private int yCenter; 27 | private int zCenter; 28 | 29 | private int yUp = 0; 30 | private int radius = 0; 31 | private float pitch = 0; 32 | 33 | public CameraAnimatorPivot(IViewCamera camera) { 34 | this.camera = camera; 35 | } 36 | 37 | @Override 38 | public void setTarget(ChunkCoordinates target) { 39 | this.target = target; 40 | positionSet = false; 41 | } 42 | 43 | @Override 44 | public void update(long dt) { 45 | if (camera == null) return; 46 | camera.addRotations(dt*0.1F, 0); 47 | camera.setPitch(-pitch); 48 | 49 | double x = Math.cos(Math.toRadians(camera.getYaw() + 90)) * radius; 50 | double z = Math.sin(Math.toRadians(camera.getYaw() + 90)) * radius; 51 | camera.setLocation(xCenter + 0.5 - x, yCenter - 0.5 + yUp, zCenter + 0.5 - z); 52 | } 53 | 54 | @Override 55 | public void refresh() { 56 | if (camera == null) return; 57 | if (target == null) return; 58 | if (!positionSet) this.checkCameraY(); 59 | 60 | int chunkX = xCenter >> 4; 61 | int chunkY = yCenter >> 4; 62 | int chunkZ = zCenter >> 4; 63 | 64 | int[][] presets = this.getPresets(); 65 | 66 | for (int i = 0; i < presets.length; ++i) { 67 | if (checkPath(presets[i][0], presets[i][1], chunkX, chunkY, chunkZ)) { 68 | yUp = presets[i][0]; 69 | radius = presets[i][1]; 70 | pitch = (float) Math.toDegrees(Math.atan(((double) -yUp) / radius)); 71 | return; 72 | } 73 | } 74 | int[] defaults = this.getDefaults(); 75 | yUp = defaults[0]; 76 | radius = defaults[1]; 77 | pitch = (float) Math.toDegrees(Math.atan(((double) -yUp) / radius)); 78 | } 79 | 80 | /** 81 | * Should the selection from the offsets fail, the pair of values in this array will be used instead. 82 | * @return A pair of numbers up and distance in an array of length 2 83 | */ 84 | public int[] getDefaults() { 85 | return defaults; 86 | } 87 | 88 | /** 89 | * Overriding his function allows you specify your own offset presets. 90 | * @return An array of integer pairs up and distance from which to select the first functional pair 91 | */ 92 | public int[][] getPresets() { 93 | return presets; 94 | } 95 | 96 | /** 97 | * @author Ken Butler/shadowking97 98 | */ 99 | private boolean checkPath(int up, int distance, int chunkX, int chunkY, int chunkZ) { 100 | if ((yCenter & 15) > 15 - up) { 101 | if (isAboveNullLayer(chunkX, chunkY, chunkZ)) return false; 102 | if ((xCenter & 15) < distance) { 103 | if (isAboveNullLayer(chunkX - 1, chunkY, chunkZ)) return false; 104 | if ((zCenter & 15) < distance) { 105 | if (isAboveNullLayer(chunkX - 1, chunkY, chunkZ - 1)) return false; 106 | if (isAboveNullLayer(chunkX, chunkY, chunkZ - 1)) return false; 107 | } else if ((zCenter & 15) > 15 - distance) { 108 | if (isAboveNullLayer(chunkX - 1, chunkY, chunkZ + 1)) return false; 109 | if (isAboveNullLayer(chunkX, chunkY, chunkZ + 1)) return false; 110 | } 111 | } else if ((xCenter & 15) > 15 - distance) { 112 | if (isAboveNullLayer(chunkX + 1, chunkY, chunkZ)) return false; 113 | if ((zCenter & 15) < distance) { 114 | if (isAboveNullLayer(chunkX + 1, chunkY, chunkZ - 1)) return false; 115 | if (isAboveNullLayer(chunkX, chunkY, chunkZ - 1)) return false; 116 | } else if ((zCenter & 15) > 15 - distance) { 117 | if (isAboveNullLayer(chunkX + 1, chunkY, chunkZ + 1)) return false; 118 | if (isAboveNullLayer(chunkX, chunkY, chunkZ + 1)) return false; 119 | } 120 | } else { 121 | if ((zCenter & 15) < distance) { 122 | if (isAboveNullLayer(chunkX, chunkY, chunkZ - 1)) return false; 123 | } else if ((zCenter & 15) > 15 - distance) { 124 | if (isAboveNullLayer(chunkX, chunkY, chunkZ + 1)) return false; 125 | } 126 | } 127 | } 128 | for (int j = -distance; j <= distance; ++j) { 129 | for (int k = -distance; k <= distance; ++k) { 130 | if (!camera.getBlockData().isAirBlock(xCenter + j, yCenter + up, zCenter + k)) return false; 131 | } 132 | } 133 | return true; 134 | } 135 | 136 | /** 137 | * @author Ken Butler/shadowking97 138 | */ 139 | private boolean isAboveNullLayer(int x, int y, int z) { 140 | if (y + 1 > 15) return true; 141 | int x2 = x << 4; 142 | int z2 = z << 4; 143 | int y2 = (y << 4) + 15; 144 | int yl = (y + 1) << 4; 145 | for (int i = 0; i < 15; i++) 146 | for (int j = 0; j < 15; j++) 147 | if (!isBlockNormalCube(camera.getBlockData(), x2 + i, y2, z2 + i)) return false; 148 | if (camera.chunkLevelsExist(x, z, yl, yl + 15)) return true; 149 | return false; 150 | } 151 | 152 | private boolean isBlockNormalCube(IBlockAccess blockData, int x, int y, int z) { 153 | Block block = blockData.getBlock(x, y, z); 154 | return block.isNormalCube(blockData, x, y, z); 155 | } 156 | 157 | private void checkCameraY() { 158 | int x = target.posX; 159 | int y = target.posY; 160 | int z = target.posZ; 161 | int yBackup = y; 162 | if (camera.chunkExists(x, z)) { 163 | if (camera.getBlockData().getBlock(x, y, z).getBlocksMovement(camera.getBlockData(), x, y, z)) { 164 | while (y > 0 && camera.getBlockData().getBlock(x, --y, z).getBlocksMovement(camera.getBlockData(), x, y, z)) 165 | ; 166 | if (y == 0) y = yBackup; 167 | else y += 2; 168 | } else { 169 | while (y < 256 && !camera.getBlockData().getBlock(x, ++y, z).getBlocksMovement(camera.getBlockData(), x, y, z)) 170 | ; 171 | if (y == 256) y = yBackup; 172 | else ++y; 173 | } 174 | this.setCenterPoint(x, y, z); 175 | } 176 | } 177 | 178 | private void setCenterPoint(int x, int y, int z) { 179 | xCenter = x; 180 | yCenter = y - 1; 181 | zCenter = z; 182 | positionSet = true; 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /src/api/java/com/xcompwiz/lookingglass/api/animator/CameraAnimatorPlayer.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.api.animator; 2 | 3 | import net.minecraft.entity.Entity; 4 | import net.minecraft.util.ChunkCoordinates; 5 | 6 | import com.xcompwiz.lookingglass.api.view.IViewCamera; 7 | 8 | /** 9 | * This is a badly approximated "portal render" animator, which makes the camera move based on what direction the player is from some defined point. It doesn't 10 | * do quite what it was meant to, but it's neat enough looking, so I'll leave it be. It does make a view look more "alive" or 3D, so if you just want a slightly 11 | * animated view that doesn't look like you could walk through it, then this works great. It produces an effect more akin to Harry Potter's portraits than it 12 | * does to Portal's portals. 13 | * @author xcompwiz 14 | */ 15 | public class CameraAnimatorPlayer implements ICameraAnimator { 16 | // This is the camera object we are animating 17 | private final IViewCamera camera; 18 | 19 | // The entity was are using as our reference point, such as our portrait view. 20 | private Entity reference; 21 | // The entity we are facing. Expected to be the client side player, but could be anything, really. 22 | private Entity player; 23 | // The point we are looking at in block coordinates. 24 | private ChunkCoordinates target; 25 | 26 | private boolean updateY; 27 | private float accum; 28 | 29 | /** 30 | * 31 | * @param camera 32 | * @param reference The entity was are using as our reference point, such as our portrait view. 33 | * @param player The entity we are facing. Expected to be the client side player, but could be anything, really. 34 | */ 35 | public CameraAnimatorPlayer(IViewCamera camera, Entity reference, Entity player) { 36 | this.camera = camera; 37 | this.reference = reference; 38 | this.player = player; 39 | } 40 | 41 | /** 42 | * Sets the point we are looking at using block coordinates. 43 | */ 44 | @Override 45 | public void setTarget(ChunkCoordinates target) { 46 | this.target = new ChunkCoordinates(target); 47 | } 48 | 49 | @Override 50 | public void refresh() { 51 | updateY = true; 52 | } 53 | 54 | @Override 55 | public void update(long dt) { 56 | // This animator is incomplete and broken. It's a rough approximation I made at 4AM one night. 57 | // However, it's also pretty cool looking, so I'm not going to bother fixing it. :P 58 | // Note: Needs base yaw and pitch of view 59 | if (reference.worldObj.provider.dimensionId != player.worldObj.provider.dimensionId) return; 60 | 61 | // A standard accumulator trick to force periodic rechecks of the y position. Probably superfluous. 62 | // Ticks every 10 seconds 63 | if ((accum += dt) >= 10000) { 64 | updateY = true; 65 | accum -= 10000; 66 | } 67 | if (updateY) updateTargetPosition(); 68 | double dx = player.posX - reference.posX; 69 | double dy = player.posY - (reference.posY + player.yOffset); 70 | double dz = player.posZ - reference.posZ; 71 | double length = Math.sqrt(dx * dx + dz * dz + dy * dy); //TODO: Needs Go Faster 72 | float yaw = -(float) Math.atan2(dx, dz); 73 | yaw *= 180 / Math.PI; 74 | float pitch = (float) Math.asin(dy / length); 75 | pitch *= 180 / Math.PI; 76 | camera.setLocation(target.posX, target.posY, target.posZ); 77 | camera.setYaw(yaw); 78 | camera.setPitch(pitch); 79 | } 80 | 81 | private void updateTargetPosition() { 82 | updateY = false; 83 | int x = target.posX; 84 | int y = target.posY; 85 | int z = target.posZ; 86 | if (!camera.chunkExists(x, z)) { 87 | if (camera.getBlockData().getBlock(x, y, z).getBlocksMovement(camera.getBlockData(), x, y, z)) { 88 | while (y > 0 && camera.getBlockData().getBlock(x, --y, z).getBlocksMovement(camera.getBlockData(), x, y, z)) 89 | ; 90 | if (y == 0) y = target.posY; 91 | else y += 2; 92 | } else { 93 | while (y < 256 && !camera.getBlockData().getBlock(x, ++y, z).getBlocksMovement(camera.getBlockData(), x, y, z)) 94 | ; 95 | if (y == 256) y = target.posY; 96 | else ++y; 97 | } 98 | target.posY = y; 99 | } 100 | } 101 | 102 | } 103 | -------------------------------------------------------------------------------- /src/api/java/com/xcompwiz/lookingglass/api/animator/ICameraAnimator.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.api.animator; 2 | 3 | import net.minecraft.util.ChunkCoordinates; 4 | 5 | public interface ICameraAnimator { 6 | 7 | /** 8 | * Sets the look-at target (in block coordinates) 9 | * @param target The block target 10 | */ 11 | void setTarget(ChunkCoordinates target); 12 | 13 | /** 14 | * Allows the animator to refresh/reboot its settings 15 | */ 16 | void refresh(); 17 | 18 | /** 19 | * Tick! 20 | * @param dt Delta time in milliseconds since last render tick 21 | */ 22 | void update(long dt); 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/api/java/com/xcompwiz/lookingglass/api/event/ClientWorldInfoEvent.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.api.event; 2 | 3 | import net.minecraft.entity.player.EntityPlayerMP; 4 | import cpw.mods.fml.common.eventhandler.Event; 5 | 6 | /** 7 | * Called on the server side to allow mods to send dimension information to clients 8 | * @author xcompwiz 9 | */ 10 | public class ClientWorldInfoEvent extends Event { 11 | 12 | public final int dim; 13 | public final EntityPlayerMP player; 14 | 15 | public ClientWorldInfoEvent(int dim, EntityPlayerMP player) { 16 | this.dim = dim; 17 | this.player = player; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/api/java/com/xcompwiz/lookingglass/api/hook/WorldViewAPI2.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.api.hook; 2 | 3 | import net.minecraft.util.ChunkCoordinates; 4 | 5 | import com.xcompwiz.lookingglass.api.view.IWorldView; 6 | 7 | import cpw.mods.fml.relauncher.Side; 8 | import cpw.mods.fml.relauncher.SideOnly; 9 | 10 | /** 11 | * Available via "view-2" from the API provider 12 | * @author xcompwiz 13 | */ 14 | public interface WorldViewAPI2 { 15 | 16 | /** 17 | * Creates a world viewer object which will handle the rendering and retrieval of the remote location. Can return null. 18 | * @param dimid The target dimension 19 | * @param coords The coordinates of the target location. If null, world spawn is used. 20 | * @param width Texture resolution width 21 | * @param height Texture resolution height 22 | * @return A IWorldView object for your use or null if something goes wrong. 23 | */ 24 | @SideOnly(Side.CLIENT) 25 | IWorldView createWorldView(Integer dimid, ChunkCoordinates coords, int width, int height); 26 | 27 | /** 28 | * This function is available should you wish to explicitly have the world view clean up its framebuffer. You should not use a view after calling this on 29 | * the view. 30 | * @param worldview The view to clean up (effectively "destroy") 31 | */ 32 | void cleanupWorldView(IWorldView worldview); 33 | } 34 | -------------------------------------------------------------------------------- /src/api/java/com/xcompwiz/lookingglass/api/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * This package contains API for LookingGlass. You should never directly reference anything outside of this package (and it's sub-packages) when interacting 3 | * with LookingGlass. 4 | */ 5 | @API(owner = "LookingGlass", apiVersion = "1.0", provides = "LookingGlass|API") 6 | package com.xcompwiz.lookingglass.api; 7 | 8 | import cpw.mods.fml.common.API; 9 | 10 | -------------------------------------------------------------------------------- /src/api/java/com/xcompwiz/lookingglass/api/view/IViewCamera.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.api.view; 2 | 3 | import net.minecraft.world.IBlockAccess; 4 | 5 | public interface IViewCamera { 6 | 7 | /** 8 | * Adds par1*0.15 to the entity's yaw, and *subtracts* par2*0.15 from the pitch. Clamps pitch from -90 to 90. Both arguments in degrees. 9 | * @param yaw The yaw to be added 10 | * @param pitch The pitch to be subtracted 11 | */ 12 | public void addRotations(float yaw, int pitch); 13 | 14 | /** 15 | * Sets the yaw rotation of the camera 16 | * @param f The camera's new yaw in degrees 17 | */ 18 | public void setYaw(float f); 19 | 20 | /** 21 | * @return The camera's yaw in degrees 22 | */ 23 | public float getYaw(); 24 | 25 | /** 26 | * Sets the pitch rotation of the camera 27 | * @param f The camera's new pitch in degrees 28 | */ 29 | public void setPitch(float f); 30 | 31 | /** 32 | * @return The camera's pitch in degrees 33 | */ 34 | public float getPitch(); 35 | 36 | /** 37 | * Sets the position of the camera 38 | * @param x X Coordinate (Block space) 39 | * @param y Y Coordinate (Block space) 40 | * @param z Z Coordinate (Block space) 41 | */ 42 | public void setLocation(double x, double y, double z); 43 | 44 | /** 45 | * @return The camera's X coordinate (Block space) 46 | */ 47 | public double getX(); 48 | 49 | /** 50 | * @return The camera's Y coordinate (Block space) 51 | */ 52 | public double getY(); 53 | 54 | /** 55 | * @return The camera's Z coordinate (Block space) 56 | */ 57 | public double getZ(); 58 | 59 | /** 60 | * This is provided to allow for checking for air blocks and similar. Technically, it is a WorldClient object, but it is provided as a IBlockAccess to 61 | * discourage modifying the world. Modifying the world object would break things for everyone, so please don't do that. Should it become an issue, this will 62 | * be replaced with something that isn't a WorldClient, so be wary of casting it. 63 | * @return A read-only reference to the world which the camera inhabits 64 | */ 65 | public IBlockAccess getBlockData(); 66 | 67 | /** 68 | * An easy check for if a chunk exists in the local data copy 69 | * @param x The X coordinate in block space 70 | * @param z The Z coordinate in block space 71 | * @return True if the chunk at those coordinates is available locally 72 | */ 73 | public boolean chunkExists(int x, int z); 74 | 75 | /** 76 | * Since LookingGlass utilizes partial chunk loading to minimize data traffic and storage, it's useful to be able to check if certain levels of a chunk are 77 | * loaded locally. 78 | * @param x The X coordinate in block space 79 | * @param z The Z coordinate in block space 80 | * @param yl1 The lower (closer to 0) y coordinate of the levels to check for in block space 81 | * @param yl2 The larger (farther from 0) y coordinate of the levels to check for in block space 82 | * @return True if the levels are loaded locally 83 | */ 84 | public boolean chunkLevelsExist(int x, int z, int yl1, int yl2); 85 | } 86 | -------------------------------------------------------------------------------- /src/api/java/com/xcompwiz/lookingglass/api/view/IWorldView.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.api.view; 2 | 3 | import com.xcompwiz.lookingglass.api.animator.ICameraAnimator; 4 | 5 | public interface IWorldView { 6 | 7 | /** 8 | * @return The OpenGL texture id for rendering the view 9 | */ 10 | public int getTexture(); 11 | 12 | /** 13 | * This needs to be called to request LookingGlass rerender the view to the texture 14 | */ 15 | public void markDirty(); 16 | 17 | /** 18 | * This will be activated once the view has chunks and is ready to render 19 | * @return True if the view has been rendered to the texture. 20 | */ 21 | public boolean isReady(); 22 | 23 | /** 24 | * Sets the animator object for the camera. This will be updated before each render frame. 25 | * @param animator 26 | */ 27 | public void setAnimator(ICameraAnimator animator); 28 | 29 | /** 30 | * Returns the view's camera object. This allows you to create animators for it and adjust its location locally. 31 | * @return the entity object from which rendering is handled 32 | */ 33 | public IViewCamera getCamera(); 34 | 35 | /** 36 | * @deprecated This function no longer does anything and will be removed in an upcoming version. 37 | */ 38 | @Deprecated 39 | public void grab(); 40 | 41 | /** 42 | * @deprecated This function no longer does anything and will be removed in an upcoming version. 43 | */ 44 | @Deprecated 45 | public boolean release(); 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/LookingGlass.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass; 2 | 3 | import java.io.File; 4 | 5 | import net.minecraft.command.ServerCommandManager; 6 | import net.minecraft.server.MinecraftServer; 7 | import net.minecraftforge.common.MinecraftForge; 8 | import net.minecraftforge.common.config.Configuration; 9 | 10 | import com.google.common.collect.ImmutableList; 11 | import com.xcompwiz.lookingglass.apiimpl.APIProviderImpl; 12 | import com.xcompwiz.lookingglass.command.CommandCreateView; 13 | import com.xcompwiz.lookingglass.core.CommonProxy; 14 | import com.xcompwiz.lookingglass.core.LookingGlassForgeEventHandler; 15 | import com.xcompwiz.lookingglass.imc.IMCHandler; 16 | import com.xcompwiz.lookingglass.network.LookingGlassPacketManager; 17 | import com.xcompwiz.lookingglass.network.ServerPacketDispatcher; 18 | import com.xcompwiz.lookingglass.network.packet.PacketChunkInfo; 19 | import com.xcompwiz.lookingglass.network.packet.PacketCloseView; 20 | import com.xcompwiz.lookingglass.network.packet.PacketCreateView; 21 | import com.xcompwiz.lookingglass.network.packet.PacketRequestChunk; 22 | import com.xcompwiz.lookingglass.network.packet.PacketRequestTE; 23 | import com.xcompwiz.lookingglass.network.packet.PacketRequestWorldInfo; 24 | import com.xcompwiz.lookingglass.network.packet.PacketTileEntityNBT; 25 | import com.xcompwiz.lookingglass.network.packet.PacketWorldInfo; 26 | import com.xcompwiz.lookingglass.proxyworld.LookingGlassEventHandler; 27 | import com.xcompwiz.lookingglass.proxyworld.ModConfigs; 28 | 29 | import cpw.mods.fml.common.FMLCommonHandler; 30 | import cpw.mods.fml.common.Mod; 31 | import cpw.mods.fml.common.Mod.EventHandler; 32 | import cpw.mods.fml.common.Mod.Instance; 33 | import cpw.mods.fml.common.SidedProxy; 34 | import cpw.mods.fml.common.event.FMLInitializationEvent; 35 | import cpw.mods.fml.common.event.FMLInterModComms.IMCEvent; 36 | import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; 37 | import cpw.mods.fml.common.event.FMLPostInitializationEvent; 38 | import cpw.mods.fml.common.event.FMLPreInitializationEvent; 39 | import cpw.mods.fml.common.event.FMLServerStartingEvent; 40 | import cpw.mods.fml.common.event.FMLServerStoppedEvent; 41 | import cpw.mods.fml.common.network.NetworkRegistry; 42 | import cpw.mods.fml.common.registry.EntityRegistry; 43 | 44 | @Mod(modid = LookingGlass.MODID, name = "LookingGlass", version = LookingGlass.VERSION) 45 | public class LookingGlass { 46 | public static final String MODID = "LookingGlass"; 47 | public static final String VERSION = "@VERSION@"; 48 | 49 | @Instance(LookingGlass.MODID) 50 | public static LookingGlass instance; 51 | 52 | @SidedProxy(clientSide = "com.xcompwiz.lookingglass.client.ClientProxy", serverSide = "com.xcompwiz.lookingglass.core.CommonProxy") 53 | public static CommonProxy sidedProxy; 54 | 55 | @EventHandler 56 | public void preinit(FMLPreInitializationEvent event) { 57 | //Initialize the packet handling 58 | LookingGlassPacketManager.registerPacketHandler(new PacketCreateView(), (byte) 10); 59 | LookingGlassPacketManager.registerPacketHandler(new PacketCloseView(), (byte) 11); 60 | LookingGlassPacketManager.registerPacketHandler(new PacketWorldInfo(), (byte) 100); 61 | LookingGlassPacketManager.registerPacketHandler(new PacketChunkInfo(), (byte) 101); 62 | LookingGlassPacketManager.registerPacketHandler(new PacketTileEntityNBT(), (byte) 102); 63 | LookingGlassPacketManager.registerPacketHandler(new PacketRequestWorldInfo(), (byte) 200); 64 | LookingGlassPacketManager.registerPacketHandler(new PacketRequestChunk(), (byte) 201); 65 | LookingGlassPacketManager.registerPacketHandler(new PacketRequestTE(), (byte) 202); 66 | 67 | LookingGlassPacketManager.bus = NetworkRegistry.INSTANCE.newEventDrivenChannel(LookingGlassPacketManager.CHANNEL); 68 | LookingGlassPacketManager.bus.register(new LookingGlassPacketManager()); 69 | 70 | // Load our basic configs 71 | ModConfigs.loadConfigs(new Configuration(event.getSuggestedConfigurationFile())); 72 | 73 | // Here we use the recommended config file to establish a good place to put a log file for any proxy world error logs. Used primarily to log the full errors when ticking or rendering proxy worlds. 74 | File configroot = event.getSuggestedConfigurationFile().getParentFile(); 75 | // Main tick handler. Handles FML events. 76 | FMLCommonHandler.instance().bus().register(new LookingGlassEventHandler(new File(configroot.getParentFile(), "logs/proxyworlds.log"))); 77 | // Forge event handler 78 | MinecraftForge.EVENT_BUS.register(new LookingGlassForgeEventHandler()); 79 | 80 | // Initialize the API provider system. Beware, this way be dragons. 81 | APIProviderImpl.init(); 82 | } 83 | 84 | @EventHandler 85 | public void init(FMLInitializationEvent event) { 86 | // Our one and only entity. 87 | EntityRegistry.registerModEntity(com.xcompwiz.lookingglass.entity.EntityPortal.class, "lookingglass.portal", 216, this, 64, 10, false); 88 | 89 | sidedProxy.init(); 90 | } 91 | 92 | @EventHandler 93 | public void handleIMC(IMCEvent event) { 94 | // Catch IMC messages and send them off to our IMC handler 95 | ImmutableList messages = event.getMessages(); 96 | IMCHandler.process(messages); 97 | } 98 | 99 | @EventHandler 100 | public void postinit(FMLPostInitializationEvent event) {} 101 | 102 | @EventHandler 103 | public void serverStart(FMLServerStartingEvent event) { 104 | MinecraftServer mcserver = event.getServer(); 105 | // Register commands 106 | ((ServerCommandManager) mcserver.getCommandManager()).registerCommand(new CommandCreateView()); 107 | // Start up the packet dispatcher we use for throttled data to client. 108 | ServerPacketDispatcher.getInstance().start(); //Note: This might need to be preceded by a force init of the ServerPacketDispatcher. Doesn't seem to currently have any issues, though. 109 | } 110 | 111 | @EventHandler 112 | public void serverStop(FMLServerStoppedEvent event) { 113 | // Shutdown our throttled packet dispatcher 114 | ServerPacketDispatcher.getInstance().halt(); 115 | ServerPacketDispatcher.shutdown(); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/apiimpl/APIProviderImpl.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.apiimpl; 2 | 3 | import java.util.Collections; 4 | import java.util.HashMap; 5 | import java.util.HashSet; 6 | import java.util.Map; 7 | import java.util.Set; 8 | 9 | import com.xcompwiz.lookingglass.api.APIInstanceProvider; 10 | import com.xcompwiz.lookingglass.api.APIUndefined; 11 | import com.xcompwiz.lookingglass.api.APIVersionRemoved; 12 | import com.xcompwiz.lookingglass.api.APIVersionUndefined; 13 | import com.xcompwiz.lookingglass.log.LoggerUtils; 14 | 15 | /** 16 | * The implementation of the API provider interface. Instances of this class are given to mods requesting an API provider and bound to that mod's name. The 17 | * class also functions as the registration manager for what APIs we have available. 18 | */ 19 | public class APIProviderImpl implements APIInstanceProvider { 20 | private String modname; 21 | 22 | public APIProviderImpl(String modname) { 23 | this.modname = modname; 24 | } 25 | 26 | public String getOwnerMod() { 27 | return modname; 28 | } 29 | 30 | private HashMap instances = new HashMap(); 31 | 32 | // See parent/javadoc for doc 33 | @Override 34 | public Object getAPIInstance(String api) throws APIUndefined, APIVersionUndefined, APIVersionRemoved { 35 | Object ret = instances.get(api); 36 | // First, we check if the API has already been constructed up for this provider 37 | if (ret != null) return ret; 38 | // Get the id and version from the passed in arg 39 | String[] splitName = api.split("-"); 40 | // If we can't get a name and version then we throw APIUndefined. 41 | if (splitName.length != 2) throw new APIUndefined(api); 42 | String apiname = splitName[0]; 43 | int version = Integer.parseInt(splitName[1]); 44 | // Ask the magical constructor to provide us an instance of the API for the specified version. 45 | ret = constructAPIWrapper(modname, apiname, version); 46 | instances.put(api, ret); 47 | return ret; 48 | } 49 | 50 | private static Map> apiCtors; 51 | private static Map> apiVersions; 52 | private static Map> apiVersions_immutable_sets; 53 | private static Map> apiVersions_immutable; 54 | 55 | /** 56 | * This init function sets up the wrapper constructors for the different APIs and versions of APIs we support. 57 | */ 58 | public static void init() { 59 | // Skip if already initialized 60 | if (apiCtors != null) return; 61 | apiCtors = new HashMap>(); 62 | apiVersions = new HashMap>(); 63 | // Immutable views to the internal stuff to allow for the getAvailableAPIs functionality without breaking containment 64 | apiVersions_immutable_sets = new HashMap>(); 65 | apiVersions_immutable = Collections.unmodifiableMap(apiVersions_immutable_sets); 66 | 67 | // Register the APIs we support 68 | registerAPI("view", 1, new WrapperBuilder(LookingGlassAPIWrapper.class)); 69 | registerAPI("view", 2, new WrapperBuilder(LookingGlassAPI2Wrapper.class)); 70 | // Note that removed API versions should be registered as null. 71 | } 72 | 73 | private static void registerAPI(String apiname, int version, WrapperBuilder builder) { 74 | getVersions(apiname).add(version); 75 | getCtors(apiname).put(version, builder); 76 | } 77 | 78 | private static Map getCtors(String apiname) { 79 | Map ctors = apiCtors.get(apiname); 80 | if (ctors == null) { 81 | ctors = new HashMap(); 82 | apiCtors.put(apiname, ctors); 83 | } 84 | return ctors; 85 | } 86 | 87 | private static Set getVersions(String apiname) { 88 | Set versions = apiVersions.get(apiname); 89 | if (versions == null) { 90 | versions = new HashSet(); 91 | apiVersions.put(apiname, versions); 92 | apiVersions_immutable_sets.put(apiname, Collections.unmodifiableSet(versions)); 93 | } 94 | return versions; 95 | } 96 | 97 | /** 98 | * ** This function is voodoo.**
This is the function which actually calls the builders to produce the wrappers which implement the version of the requested API. 99 | * @param owner The name of the mod wanting the API 100 | * @param apiname The name of the API wanted 101 | * @param version The version of the API wanted 102 | * @return An object which is an instance of the interface matching the API version 103 | * @throws APIUndefined The API requested doesn't exist 104 | * @throws APIVersionUndefined The API requested exists, but the version requested is missing in the local environment 105 | * @throws APIVersionRemoved The API requested exists, but the version requested has been removed and is no longer supported 106 | */ 107 | private static Object constructAPIWrapper(String owner, String apiname, int version) throws APIUndefined, APIVersionUndefined, APIVersionRemoved { 108 | // First, check to make sure we initialized before 109 | if (apiCtors == null) throw new RuntimeException("Something is broken. The LookingGlass API Provider hasn't constructed properly."); 110 | // Get the builders for the API we want 111 | Map ctors = apiCtors.get(apiname); 112 | // If there are no builders, then the API doesn't exist 113 | if (ctors == null) throw new APIUndefined(apiname); 114 | // If the builders collection doesn't have an entry for the version we wanted, it never existed 115 | if (!ctors.containsKey(version)) throw new APIVersionUndefined(apiname + "-" + version); 116 | // Get the builder entry 117 | WrapperBuilder ctor = ctors.get(version); 118 | // If the builder is null, then the API has been removed. 119 | if (ctor == null) throw new APIVersionRemoved(apiname + "-" + version); 120 | // Now, the magic itself. Use the builder to produce an instance of the API 121 | try { 122 | return ctor.newInstance(owner); // Poof! 123 | } catch (Exception e) { 124 | // If there are any problems then we need to report them. Theoretically there shouldn't be, but one never knows. 125 | LoggerUtils.error("Caught an exception while building an API wrapper. Go kick XCompWiz."); 126 | throw new RuntimeException("Caught an exception while building an API wrapper. Go kick XCompWiz.", e); 127 | } 128 | } 129 | 130 | @Override 131 | public Map> getAvailableAPIs() { 132 | return apiVersions_immutable; 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/apiimpl/APIWrapper.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.apiimpl; 2 | 3 | public class APIWrapper { 4 | private String modname; 5 | 6 | public APIWrapper(String modname) { 7 | this.modname = modname; 8 | } 9 | 10 | public String getOwnerMod() { 11 | return modname; 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/apiimpl/InternalAPI.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.apiimpl; 2 | 3 | import java.util.HashMap; 4 | 5 | import com.xcompwiz.lookingglass.api.APIInstanceProvider; 6 | 7 | /** 8 | * This class simply manages the construction and tracking of the API provider instances. The Mystcraft version was enormously more complex and did lots more, 9 | * but I simplified it here. The class is intentionally not named APIInstanceProviderProvider.... 10 | */ 11 | public class InternalAPI { 12 | 13 | private static HashMap instances = new HashMap(); 14 | 15 | public synchronized static APIInstanceProvider getAPIProviderInstance(String modname) { 16 | APIInstanceProvider instance = instances.get(modname); 17 | if (instance == null) { 18 | instance = new APIProviderImpl(modname); 19 | instances.put(modname, instance); 20 | } 21 | return instance; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/apiimpl/LookingGlassAPI2Wrapper.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.apiimpl; 2 | 3 | import net.minecraft.util.ChunkCoordinates; 4 | 5 | import com.xcompwiz.lookingglass.api.hook.WorldViewAPI2; 6 | import com.xcompwiz.lookingglass.api.view.IWorldView; 7 | import com.xcompwiz.lookingglass.client.proxyworld.ProxyWorldManager; 8 | import com.xcompwiz.lookingglass.client.proxyworld.WorldView; 9 | 10 | import cpw.mods.fml.relauncher.Side; 11 | import cpw.mods.fml.relauncher.SideOnly; 12 | 13 | /** 14 | * This is the API wrapper (instance) class for the WorldView API at version 2. 15 | * @author xcompwiz 16 | */ 17 | public class LookingGlassAPI2Wrapper extends APIWrapper implements WorldViewAPI2 { 18 | 19 | public LookingGlassAPI2Wrapper(String modname) { 20 | super(modname); 21 | } 22 | 23 | @Override 24 | @SideOnly(Side.CLIENT) 25 | public IWorldView createWorldView(Integer dimid, ChunkCoordinates spawn, int width, int height) { 26 | return ProxyWorldManager.createWorldView(dimid, (spawn != null ? new ChunkCoordinates(spawn) : null), width, height); 27 | } 28 | 29 | @Override 30 | public void cleanupWorldView(IWorldView worldview) { 31 | if (worldview == null) return; 32 | if (!(worldview instanceof WorldView)) throw new RuntimeException("[%s] is misusing the LookingGlass API. Cannot cleanup custom IWorldView objects."); 33 | ProxyWorldManager.destroyWorldView((WorldView) worldview); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/apiimpl/LookingGlassAPIWrapper.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.apiimpl; 2 | 3 | import net.minecraft.util.ChunkCoordinates; 4 | 5 | import com.xcompwiz.lookingglass.api.IWorldViewAPI; 6 | import com.xcompwiz.lookingglass.api.view.IWorldView; 7 | import com.xcompwiz.lookingglass.client.proxyworld.ProxyWorldManager; 8 | 9 | import cpw.mods.fml.relauncher.Side; 10 | import cpw.mods.fml.relauncher.SideOnly; 11 | 12 | /** 13 | * This is the API wrapper (instance) class for the WorldView API at version 1. 14 | * @author xcompwiz 15 | */ 16 | @SuppressWarnings("deprecation") 17 | public class LookingGlassAPIWrapper extends APIWrapper implements IWorldViewAPI { 18 | 19 | public LookingGlassAPIWrapper(String modname) { 20 | super(modname); 21 | } 22 | 23 | @Override 24 | @SideOnly(Side.CLIENT) 25 | public IWorldView createWorldView(Integer dimid, ChunkCoordinates spawn, int width, int height) { 26 | return ProxyWorldManager.createWorldView(dimid, (spawn != null ? new ChunkCoordinates(spawn) : null), width, height); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/apiimpl/WrapperBuilder.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.apiimpl; 2 | 3 | import java.lang.reflect.Constructor; 4 | import java.lang.reflect.InvocationTargetException; 5 | 6 | /** 7 | * This is a bit of a magic class. We use it to build API instances (API wrappers). It requires that the target class have a constructor which takes a string. 8 | * It passes the API instance "owner" to the constructor when building the wrapper instance. Basically a cheap and easy class factory. 9 | */ 10 | public class WrapperBuilder { 11 | 12 | private final Constructor itemCtor; 13 | 14 | public WrapperBuilder(Class clazz) { 15 | try { 16 | itemCtor = clazz.getConstructor(String.class); 17 | } catch (Exception e) { 18 | throw new RuntimeException("LookingGlass has derped.", e); 19 | } 20 | } 21 | 22 | /** 23 | * Called by the APIProviderImpl to construct the API wrapper passed to it on its construction. 24 | * @param owner 25 | * @return The instance 26 | */ 27 | public Object newInstance(String owner) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { 28 | return itemCtor.newInstance(owner); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/client/ClientProxy.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.client; 2 | 3 | import net.minecraft.client.renderer.entity.Render; 4 | import net.minecraft.client.renderer.entity.RenderManager; 5 | 6 | import com.xcompwiz.lookingglass.client.render.RenderPortal; 7 | import com.xcompwiz.lookingglass.core.CommonProxy; 8 | import com.xcompwiz.lookingglass.entity.EntityPortal; 9 | 10 | import cpw.mods.fml.client.registry.RenderingRegistry; 11 | import cpw.mods.fml.relauncher.Side; 12 | import cpw.mods.fml.relauncher.SideOnly; 13 | 14 | /** 15 | * Our faithful proxy class. Allows for running code differently dependent on whether we are client- or server-side. 16 | */ 17 | @SideOnly(Side.CLIENT) 18 | public class ClientProxy extends CommonProxy { 19 | 20 | /** 21 | * Run during mod init. 22 | */ 23 | @Override 24 | public void init() { 25 | // We register the portal renderer here 26 | Render render; 27 | render = new RenderPortal(); 28 | render.setRenderManager(RenderManager.instance); 29 | RenderingRegistry.registerEntityRenderingHandler(EntityPortal.class, render); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/client/proxyworld/ProxyWorld.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.client.proxyworld; 2 | 3 | import net.minecraft.client.Minecraft; 4 | import net.minecraft.client.multiplayer.WorldClient; 5 | import net.minecraft.client.particle.EntityFireworkStarterFX; 6 | import net.minecraft.nbt.NBTTagCompound; 7 | import net.minecraft.world.WorldSettings; 8 | import net.minecraft.world.WorldSettings.GameType; 9 | import net.minecraft.world.WorldType; 10 | 11 | // FIXME: AAHH! Fake world classes! EXTERMINATE! 12 | public class ProxyWorld extends WorldClient { 13 | public ProxyWorld(int dimensionID) { 14 | super(Minecraft.getMinecraft().getNetHandler(), new WorldSettings(0L, GameType.SURVIVAL, true, false, WorldType.DEFAULT), dimensionID, Minecraft.getMinecraft().gameSettings.difficulty, Minecraft.getMinecraft().theWorld.theProfiler); 15 | } 16 | 17 | // TODO: In order to eliminate this class we may need an event in this function to allow canceling/redirecting sounds 18 | @Override 19 | public void playSound(double par1, double par3, double par5, String par7Str, float par8, float par9, boolean par10) {} 20 | 21 | // TODO: In order to eliminate this class we need to create a redirection wrapper class for the mc.effectRenderer which does this for all views. 22 | @Override 23 | public void makeFireworks(double par1, double par3, double par5, double par7, double par9, double par11, NBTTagCompound par13NBTTagCompound) { 24 | for (WorldView activeview : ProxyWorldManager.getWorldViews(this.provider.dimensionId)) { 25 | activeview.getEffectRenderer().addEffect(new EntityFireworkStarterFX(this, par1, par3, par5, par7, par9, par11, activeview.getEffectRenderer(), par13NBTTagCompound)); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/client/proxyworld/ProxyWorldManager.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.client.proxyworld; 2 | 3 | import java.util.Collection; 4 | import java.util.Collections; 5 | import java.util.HashMap; 6 | import java.util.HashSet; 7 | import java.util.Map; 8 | import java.util.WeakHashMap; 9 | 10 | import net.minecraft.client.Minecraft; 11 | import net.minecraft.client.multiplayer.WorldClient; 12 | import net.minecraft.entity.EntityLivingBase; 13 | import net.minecraft.util.ChunkCoordinates; 14 | import net.minecraftforge.common.DimensionManager; 15 | 16 | import com.xcompwiz.lookingglass.client.render.FrameBufferContainer; 17 | import com.xcompwiz.lookingglass.entity.EntityCamera; 18 | import com.xcompwiz.lookingglass.log.LoggerUtils; 19 | import com.xcompwiz.lookingglass.network.LookingGlassPacketManager; 20 | import com.xcompwiz.lookingglass.network.packet.PacketCreateView; 21 | import com.xcompwiz.lookingglass.proxyworld.ModConfigs; 22 | 23 | import cpw.mods.fml.relauncher.Side; 24 | import cpw.mods.fml.relauncher.SideOnly; 25 | 26 | @SideOnly(Side.CLIENT) 27 | public class ProxyWorldManager { 28 | private static Map proxyworlds = new HashMap(); 29 | private static Collection proxyworldset = Collections.unmodifiableCollection(proxyworlds.values()); 30 | /** We actually populate this with weak sets. This allows for the world views to be freed without us needing to do anything. */ 31 | private static Map> worldviewsets = new HashMap>(); 32 | 33 | /** 34 | * This is a complex bit. As we want to reuse the current client world when rendering, if possible, we need to handle when that world changes. We could 35 | * simply destroy all the views pointing to the existing proxy world, but that would be annoying to mods using the API. Instead, we replace our proxy world 36 | * with the new client world. This should only be called by LookingGlass, and only from the handling of the client world change detection. 37 | * @param world The new client world 38 | */ 39 | public static void handleWorldChange(WorldClient world) { 40 | if (ModConfigs.disabled) return; 41 | if (world == null) return; 42 | int dimid = world.provider.dimensionId; 43 | if (!proxyworlds.containsKey(dimid)) return; //BEST CASE! We don't have to do anything! 44 | proxyworlds.put(dimid, world); 45 | Collection worldviews = worldviewsets.get(dimid); 46 | for (WorldView view : worldviews) { 47 | // Handle the change on the view object 48 | view.replaceWorldObject(world); 49 | } 50 | } 51 | 52 | public static synchronized void detectFreedWorldViews() { 53 | FrameBufferContainer.detectFreedWorldViews(); 54 | //TODO: closeViewConnection(worldviewID); 55 | HashSet emptyLists = new HashSet(); 56 | for (Map.Entry> entry : worldviewsets.entrySet()) { 57 | if (entry.getValue().isEmpty()) emptyLists.add(entry.getKey()); 58 | } 59 | for (Integer dimId : emptyLists) { 60 | unloadProxyWorld(dimId); 61 | } 62 | } 63 | 64 | public static synchronized WorldClient getProxyworld(int dimid) { 65 | if (ModConfigs.disabled) return null; 66 | WorldClient proxyworld = proxyworlds.get(dimid); 67 | if (proxyworld == null) { 68 | if (!DimensionManager.isDimensionRegistered(dimid)) return null; 69 | // We really don't want to be doing this during a render cycle 70 | if (Minecraft.getMinecraft().thePlayer instanceof EntityCamera) return null; //TODO: This check probably needs to be altered 71 | WorldClient theWorld = Minecraft.getMinecraft().theWorld; 72 | if (theWorld != null && theWorld.provider.dimensionId == dimid) proxyworld = theWorld; 73 | if (proxyworld == null) proxyworld = new ProxyWorld(dimid); 74 | proxyworlds.put(dimid, proxyworld); 75 | worldviewsets.put(dimid, Collections.newSetFromMap(new WeakHashMap())); 76 | } 77 | return proxyworld; 78 | } 79 | 80 | private static void unloadProxyWorld(int dimId) { 81 | Collection set = worldviewsets.remove(dimId); 82 | if (set != null && set.size() > 0) LoggerUtils.warn("Unloading ProxyWorld with live views"); 83 | WorldClient proxyworld = proxyworlds.remove(dimId); 84 | WorldClient theWorld = Minecraft.getMinecraft().theWorld; 85 | if (theWorld != null && theWorld == proxyworld) return; 86 | if (proxyworld != null) net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.world.WorldEvent.Unload(proxyworld)); 87 | } 88 | 89 | public static void clearProxyworlds() { 90 | while (!proxyworlds.isEmpty()) { 91 | unloadProxyWorld(proxyworlds.keySet().iterator().next()); 92 | } 93 | } 94 | 95 | public static Collection getProxyworlds() { 96 | return proxyworldset; 97 | } 98 | 99 | public static Collection getWorldViews(int dimid) { 100 | Collection set = worldviewsets.get(dimid); 101 | if (set == null) return Collections.emptySet(); 102 | return Collections.unmodifiableCollection(set); 103 | } 104 | 105 | public static WorldView createWorldView(int dimid, ChunkCoordinates spawn, int width, int height) { 106 | if (ModConfigs.disabled) return null; 107 | if (!DimensionManager.isDimensionRegistered(dimid)) return null; 108 | 109 | WorldClient proxyworld = ProxyWorldManager.getProxyworld(dimid); 110 | if (proxyworld == null) return null; 111 | 112 | Collection worldviews = worldviewsets.get(dimid); 113 | if (worldviews == null) return null; 114 | 115 | WorldView view = new WorldView(proxyworld, spawn, width, height); 116 | 117 | // Initialize the view rendering system 118 | Minecraft mc = Minecraft.getMinecraft(); 119 | EntityLivingBase backup = mc.renderViewEntity; 120 | mc.renderViewEntity = view.camera; 121 | view.getRenderGlobal().setWorldAndLoadRenderers(proxyworld); 122 | mc.renderViewEntity = backup; 123 | 124 | // Inform the server of the new view 125 | LookingGlassPacketManager.bus.sendToServer(PacketCreateView.createPacket(view)); 126 | worldviews.add(view); 127 | return view; 128 | } 129 | 130 | //TODO: private static void closeViewConnection(long worldviewID) { 131 | //LookingGlassPacketManager.bus.sendToServer(PacketCloseView.createPacket(worldviewID)); 132 | //} 133 | 134 | /** 135 | * Handles explicit shutdown of a world view. Tells the view to clean itself up and removes it from the tracked world views here (encouraging the world to unload). 136 | * @param view The view to kill 137 | */ 138 | public static void destroyWorldView(WorldView view) { 139 | Collection set = worldviewsets.get(view.getWorldObj().provider.dimensionId); 140 | if (set != null) set.remove(view); 141 | //TODO: closeViewConnection(worldviewID); 142 | view.cleanup(); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/client/proxyworld/ViewCameraImpl.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.client.proxyworld; 2 | 3 | import net.minecraft.world.IBlockAccess; 4 | 5 | import com.xcompwiz.lookingglass.api.view.IViewCamera; 6 | import com.xcompwiz.lookingglass.entity.EntityCamera; 7 | 8 | public class ViewCameraImpl implements IViewCamera { 9 | private EntityCamera camera; 10 | 11 | public ViewCameraImpl(EntityCamera camera) { 12 | this.camera = camera; 13 | } 14 | 15 | @Override 16 | public void addRotations(float yaw, int pitch) { 17 | this.camera.setAngles(yaw, pitch); 18 | } 19 | 20 | @Override 21 | public void setYaw(float f) { 22 | this.camera.prevRotationYaw = f; 23 | this.camera.rotationYaw = f; 24 | } 25 | 26 | @Override 27 | public float getYaw() { 28 | return this.camera.rotationYaw; 29 | } 30 | 31 | @Override 32 | public void setPitch(float f) { 33 | this.camera.prevRotationPitch = f; 34 | this.camera.rotationPitch = f; 35 | } 36 | 37 | @Override 38 | public float getPitch() { 39 | return this.camera.rotationPitch; 40 | } 41 | 42 | @Override 43 | public void setLocation(double x, double y, double z) { 44 | this.camera.setLocationAndAngles(x, y, z, this.camera.rotationYaw, this.camera.rotationPitch); 45 | } 46 | 47 | @Override 48 | public double getX() { 49 | return this.camera.posX; 50 | } 51 | 52 | @Override 53 | public double getY() { 54 | return this.camera.posY; 55 | } 56 | 57 | @Override 58 | public double getZ() { 59 | return this.camera.posZ; 60 | } 61 | 62 | @Override 63 | public IBlockAccess getBlockData() { 64 | return this.camera.worldObj; 65 | } 66 | 67 | @Override 68 | public boolean chunkExists(int x, int z) { 69 | return !camera.worldObj.getChunkFromBlockCoords(x, z).isEmpty(); 70 | } 71 | 72 | @Override 73 | public boolean chunkLevelsExist(int x, int z, int yl1, int yl2) { 74 | return !camera.worldObj.getChunkFromBlockCoords(x, z).getAreLevelsEmpty(yl1, yl2); 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/client/proxyworld/WorldView.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.client.proxyworld; 2 | 3 | import net.minecraft.client.Minecraft; 4 | import net.minecraft.client.multiplayer.WorldClient; 5 | import net.minecraft.client.particle.EffectRenderer; 6 | import net.minecraft.client.renderer.RenderGlobal; 7 | import net.minecraft.util.ChunkCoordinates; 8 | import net.minecraft.util.MathHelper; 9 | 10 | import com.xcompwiz.lookingglass.api.animator.ICameraAnimator; 11 | import com.xcompwiz.lookingglass.api.view.IViewCamera; 12 | import com.xcompwiz.lookingglass.api.view.IWorldView; 13 | import com.xcompwiz.lookingglass.client.render.FrameBufferContainer; 14 | import com.xcompwiz.lookingglass.entity.EntityCamera; 15 | 16 | import cpw.mods.fml.relauncher.Side; 17 | import cpw.mods.fml.relauncher.SideOnly; 18 | 19 | @SideOnly(Side.CLIENT) 20 | public class WorldView implements IWorldView { 21 | private WorldClient worldObj; 22 | public final ChunkCoordinates coords; 23 | public final EntityCamera camera; 24 | public final IViewCamera camerawrapper; 25 | 26 | public final int width; 27 | public final int height; 28 | 29 | private boolean update; 30 | private boolean ready; 31 | private boolean hasChunks; 32 | private long last_render_time = -1; 33 | 34 | private RenderGlobal renderGlobal; 35 | private EffectRenderer effectRenderer; 36 | 37 | private FrameBufferContainer fbo; 38 | 39 | public WorldView(WorldClient worldObj, ChunkCoordinates coords, int width, int height) { 40 | this.width = width; 41 | this.height = height; 42 | this.worldObj = worldObj; 43 | this.coords = coords; 44 | this.camera = new EntityCamera(worldObj, coords); 45 | this.camerawrapper = new ViewCameraImpl(camera); 46 | this.renderGlobal = new RenderGlobal(Minecraft.getMinecraft()); 47 | this.effectRenderer = new EffectRenderer(worldObj, Minecraft.getMinecraft().getTextureManager()); 48 | // Technically speaking, this is poor practice as it leaks a reference to the view before it's done constructing. 49 | this.fbo = FrameBufferContainer.createNewFramebuffer(this, width, height); 50 | } 51 | 52 | /** 53 | * Explicitly shuts down the view. Informs the frame buffer manager that we don't want our framebuffer anymore (so it can be cleaned up for certain on the 54 | * next cleanup pass) and kills our fbo reference. The view is no longer usable after this is called. 55 | */ 56 | public void cleanup() { 57 | this.fbo = null; 58 | FrameBufferContainer.removeWorldView(this); 59 | } 60 | 61 | @Override 62 | public boolean isReady() { 63 | return fbo == null ? false : ready; 64 | } 65 | 66 | public boolean hasChunks() { 67 | return fbo == null ? false : hasChunks; 68 | } 69 | 70 | @Override 71 | public void markDirty() { 72 | update = true; 73 | } 74 | 75 | public boolean markClean() { 76 | if (fbo == null) return false; 77 | ready = true; 78 | boolean temp = update; 79 | update = false; 80 | return temp; 81 | } 82 | 83 | public int getFramebuffer() { 84 | return fbo == null ? 0 : fbo.getFramebuffer(); 85 | } 86 | 87 | public RenderGlobal getRenderGlobal() { 88 | return this.renderGlobal; 89 | } 90 | 91 | public EffectRenderer getEffectRenderer() { 92 | return this.effectRenderer; 93 | } 94 | 95 | @Override 96 | public int getTexture() { 97 | return fbo == null ? 0 : fbo.getTexture(); 98 | } 99 | 100 | @Override 101 | public void grab() {} 102 | 103 | @Override 104 | public boolean release() { 105 | return false; 106 | } 107 | 108 | public void onChunkReceived(int cx, int cz) { 109 | this.hasChunks = true; 110 | int cam_cx = MathHelper.floor_double(this.camera.posX) >> 4; 111 | int cam_cz = MathHelper.floor_double(this.camera.posZ) >> 4; 112 | if (cam_cx >= cx - 1 && cam_cx <= cx + 1 && cam_cz > cz - 1 && cam_cz < cz + 1) this.camera.refreshAnimator(); 113 | } 114 | 115 | public void updateWorldSpawn(ChunkCoordinates cc) { 116 | this.camera.updateWorldSpawn(cc); 117 | } 118 | 119 | public void startRender(long renderT) { 120 | if (this.last_render_time > 0) this.camera.tick(renderT - this.last_render_time); 121 | this.last_render_time = renderT; 122 | } 123 | 124 | @Override 125 | public void setAnimator(ICameraAnimator animator) { 126 | this.camera.setAnimator(animator); 127 | } 128 | 129 | @Override 130 | public IViewCamera getCamera() { 131 | return camerawrapper; 132 | } 133 | 134 | /** 135 | * This is a really complex bit. As we want to reuse the current client world when rendering, if possible, we need to handle when that world changes. We 136 | * could simply destroy all the views pointing to the existing proxy world, but that would be annoying to mods using the API. Instead, we replace our proxy 137 | * world with the new client world. This should only be called by LookingGlass, and only from the handling of the client world change detection. 138 | * @param world The new world 139 | */ 140 | public void replaceWorldObject(WorldClient world) { 141 | this.worldObj = world; 142 | this.camera.worldObj = world; 143 | this.effectRenderer.clearEffects(world); 144 | this.renderGlobal.setWorldAndLoadRenderers(world); 145 | } 146 | 147 | public WorldClient getWorldObj() { 148 | return this.worldObj; 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/client/render/FrameBufferContainer.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.client.render; 2 | 3 | import java.util.Collection; 4 | import java.util.HashSet; 5 | import java.util.concurrent.ConcurrentMap; 6 | 7 | import net.minecraftforge.client.MinecraftForgeClient; 8 | 9 | import org.lwjgl.opengl.EXTFramebufferObject; 10 | import org.lwjgl.opengl.GL11; 11 | import org.lwjgl.opengl.GL14; 12 | 13 | import com.google.common.collect.MapMaker; 14 | import com.xcompwiz.lookingglass.client.proxyworld.WorldView; 15 | import com.xcompwiz.lookingglass.log.LoggerUtils; 16 | 17 | public class FrameBufferContainer { 18 | /** 19 | * Using this map we can detect which FBOs should be freed. The map will delete any entry where the world view object is garbage collected. It unfortunately 20 | * can't detect that the world view is otherwise leaked, though, just when it's gone. 21 | */ 22 | private static ConcurrentMap weakfbomap = new MapMaker().weakKeys(). makeMap(); 23 | private static Collection framebuffers = new HashSet(); 24 | 25 | public static FrameBufferContainer createNewFramebuffer(WorldView view, int width, int height) { 26 | FrameBufferContainer fbo = new FrameBufferContainer(width, height); 27 | weakfbomap.put(view, fbo); 28 | framebuffers.add(fbo); 29 | return fbo; 30 | } 31 | 32 | public static void removeWorldView(WorldView view) { 33 | weakfbomap.remove(view); 34 | } 35 | 36 | public static void clearAll() { 37 | for (FrameBufferContainer fbo : framebuffers) { 38 | fbo.release(); 39 | } 40 | framebuffers.clear(); 41 | } 42 | 43 | public static synchronized void detectFreedWorldViews() { 44 | Collection unpairedFBOs = new HashSet(framebuffers); 45 | unpairedFBOs.removeAll(weakfbomap.values()); 46 | if (unpairedFBOs.isEmpty()) return; 47 | LoggerUtils.info("Freeing %d loose framebuffers from expired world views", unpairedFBOs.size()); 48 | for (FrameBufferContainer fbo : unpairedFBOs) { 49 | fbo.release(); 50 | } 51 | framebuffers.removeAll(unpairedFBOs); 52 | } 53 | 54 | public final int width; 55 | public final int height; 56 | 57 | private int framebuffer; 58 | private int depthBuffer; 59 | private int texture; 60 | 61 | private FrameBufferContainer(int width, int height) { 62 | this.width = width; 63 | this.height = height; 64 | allocateFrameBuffer(); 65 | } 66 | 67 | private void release() { 68 | freeFrameBuffer(); 69 | } 70 | 71 | public int getFramebuffer() { 72 | return framebuffer; 73 | } 74 | 75 | public int getTexture() { 76 | return texture; 77 | } 78 | 79 | // Always clean up your allocations 80 | private synchronized void freeFrameBuffer() { 81 | try { 82 | if (this.texture != 0) GL11.glDeleteTextures(this.texture); 83 | this.texture = 0; 84 | if (depthBuffer != 0) EXTFramebufferObject.glDeleteRenderbuffersEXT(depthBuffer); 85 | depthBuffer = 0; 86 | if (this.framebuffer != 0) EXTFramebufferObject.glDeleteFramebuffersEXT(this.framebuffer); 87 | this.framebuffer = 0; 88 | } catch (Exception e) { 89 | // Just in case, we make sure we don't crash. Because crashing is bad. 90 | LoggerUtils.error("Error while cleaning up a world view frame buffer."); 91 | } 92 | } 93 | 94 | // This method builds the frame buffer and texture references 95 | private void allocateFrameBuffer() { 96 | if (this.framebuffer != 0) return; 97 | 98 | this.framebuffer = EXTFramebufferObject.glGenFramebuffersEXT(); //Release via: EXTFramebufferObject.glDeleteFramebuffersEXT(framebuffer); 99 | this.depthBuffer = EXTFramebufferObject.glGenRenderbuffersEXT(); //Release via: EXTFramebufferObject.glDeleteRenderbuffersEXT(depthBuffer); 100 | 101 | EXTFramebufferObject.glBindFramebufferEXT(EXTFramebufferObject.GL_FRAMEBUFFER_EXT, this.framebuffer); 102 | 103 | EXTFramebufferObject.glBindRenderbufferEXT(EXTFramebufferObject.GL_RENDERBUFFER_EXT, depthBuffer); 104 | if (MinecraftForgeClient.getStencilBits() == 0) EXTFramebufferObject.glRenderbufferStorageEXT(EXTFramebufferObject.GL_RENDERBUFFER_EXT, GL14.GL_DEPTH_COMPONENT24, width, height); 105 | else EXTFramebufferObject.glRenderbufferStorageEXT(EXTFramebufferObject.GL_RENDERBUFFER_EXT, org.lwjgl.opengl.EXTPackedDepthStencil.GL_DEPTH24_STENCIL8_EXT, width, height); 106 | 107 | EXTFramebufferObject.glFramebufferRenderbufferEXT(EXTFramebufferObject.GL_FRAMEBUFFER_EXT, EXTFramebufferObject.GL_DEPTH_ATTACHMENT_EXT, EXTFramebufferObject.GL_RENDERBUFFER_EXT, depthBuffer); 108 | if (MinecraftForgeClient.getStencilBits() != 0) EXTFramebufferObject.glFramebufferRenderbufferEXT(EXTFramebufferObject.GL_FRAMEBUFFER_EXT, EXTFramebufferObject.GL_STENCIL_ATTACHMENT_EXT, EXTFramebufferObject.GL_RENDERBUFFER_EXT, depthBuffer); 109 | 110 | this.texture = GL11.glGenTextures(); //Release via: GL11.glDeleteTextures(colorTexture); 111 | GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.texture); 112 | GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); 113 | GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, width, height, 0, GL11.GL_RGBA, GL11.GL_INT, (java.nio.ByteBuffer) null); 114 | EXTFramebufferObject.glFramebufferTexture2DEXT(EXTFramebufferObject.GL_FRAMEBUFFER_EXT, EXTFramebufferObject.GL_COLOR_ATTACHMENT0_EXT, GL11.GL_TEXTURE_2D, this.texture, 0); 115 | 116 | EXTFramebufferObject.glBindFramebufferEXT(EXTFramebufferObject.GL_FRAMEBUFFER_EXT, 0); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/client/render/RenderPortal.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.client.render; 2 | 3 | import net.minecraft.client.renderer.Tessellator; 4 | import net.minecraft.client.renderer.entity.Render; 5 | import net.minecraft.entity.Entity; 6 | import net.minecraft.util.ResourceLocation; 7 | 8 | import org.lwjgl.opengl.GL11; 9 | 10 | import com.xcompwiz.lookingglass.api.view.IWorldView; 11 | import com.xcompwiz.lookingglass.entity.EntityPortal; 12 | 13 | public class RenderPortal extends Render { 14 | 15 | @Override 16 | public void doRender(Entity entity, double d, double d1, double d2, float f, float f1) { 17 | if (!(entity instanceof EntityPortal)) return; 18 | EntityPortal portal = (EntityPortal) entity; 19 | IWorldView activeview = portal.getActiveView(); 20 | if (activeview == null) return; 21 | 22 | int texture = activeview.getTexture(); 23 | if (texture == 0) return; 24 | 25 | int width = 2; 26 | int height = 3; 27 | double left = -width / 2.; 28 | double top = 0; 29 | 30 | activeview.markDirty(); 31 | GL11.glDisable(GL11.GL_ALPHA_TEST); 32 | GL11.glDisable(GL11.GL_LIGHTING); 33 | 34 | GL11.glPushMatrix(); 35 | GL11.glTranslatef((float) d, (float) d1, (float) d2); 36 | 37 | GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture); 38 | Tessellator tessellator = Tessellator.instance; 39 | tessellator.setColorRGBA_F(1, 1, 1, 1); 40 | tessellator.startDrawingQuads(); 41 | tessellator.addVertexWithUV(left, top, 0.0D, 0.0D, 0.0D); //inc=bl out; inc=bl down 42 | tessellator.addVertexWithUV(width + left, top, 0.0D, 1.0D, 0.0D); //dc=br out; inc=br down 43 | tessellator.addVertexWithUV(width + left, height + top, 0.0D, 1.0D, 1.0D); //dec=tr out; dec=tr up 44 | tessellator.addVertexWithUV(left, height + top, 0.0D, 0.0D, 1.0D); //inc=lt out; dec=tl up 45 | tessellator.draw(); 46 | GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); 47 | //XXX: Make the back of the portals a little nicer 48 | tessellator.setColorRGBA_F(0, 0, 1, 1); 49 | tessellator.startDrawingQuads(); 50 | tessellator.addVertexWithUV(left, height + top, 0.0D, 0.0D, 1.0D); 51 | tessellator.addVertexWithUV(width + left, height + top, 0.0D, 1.0D, 1.0D); 52 | tessellator.addVertexWithUV(width + left, top, 0.0D, 1.0D, 0.0D); 53 | tessellator.addVertexWithUV(left, top, 0.0D, 0.0D, 0.0D); 54 | tessellator.draw(); 55 | GL11.glPopMatrix(); 56 | 57 | GL11.glEnable(GL11.GL_LIGHTING); 58 | GL11.glEnable(GL11.GL_ALPHA_TEST); 59 | } 60 | 61 | @Override 62 | protected void bindEntityTexture(Entity entity) {} 63 | 64 | @Override 65 | protected ResourceLocation getEntityTexture(Entity entity) { 66 | return null; 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/client/render/RenderUtils.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.client.render; 2 | 3 | import net.minecraft.client.Minecraft; 4 | import net.minecraft.client.renderer.EntityRenderer; 5 | import net.minecraft.client.renderer.Tessellator; 6 | 7 | import org.lwjgl.opengl.EXTFramebufferObject; 8 | import org.lwjgl.opengl.GL11; 9 | 10 | import cpw.mods.fml.relauncher.Side; 11 | import cpw.mods.fml.relauncher.SideOnly; 12 | 13 | public class RenderUtils { 14 | 15 | @SideOnly(Side.CLIENT) 16 | public final static void renderWorldToTexture(float renderTime, int framebuffer, int width, int height) { 17 | if (framebuffer == 0) return; 18 | Minecraft mc = Minecraft.getMinecraft(); 19 | if (mc.skipRenderWorld) return; 20 | EntityRenderer entityRenderer = mc.entityRenderer; 21 | 22 | //Backup current render settings 23 | int heightBackup = mc.displayHeight; 24 | int widthBackup = mc.displayWidth; 25 | 26 | int thirdPersonBackup = mc.gameSettings.thirdPersonView; 27 | boolean hideGuiBackup = mc.gameSettings.hideGUI; 28 | int particleBackup = mc.gameSettings.particleSetting; 29 | boolean anaglyphBackup = mc.gameSettings.anaglyph; 30 | int renderDistanceBackup = mc.gameSettings.renderDistanceChunks; 31 | float FOVbackup = mc.gameSettings.fovSetting; 32 | 33 | //Render world 34 | try { 35 | //Set all of the render setting to work on the proxy world 36 | mc.displayHeight = height; 37 | mc.displayWidth = width; 38 | 39 | //TODO: params (FOV, Particle setting, renderDistance) 40 | mc.gameSettings.thirdPersonView = 0; 41 | mc.gameSettings.hideGUI = true; 42 | //mc.gameSettings.particleSetting = ; 43 | mc.gameSettings.anaglyph = false; 44 | //mc.gameSettings.renderDistanceChunks = ; 45 | //mc.gameSettings.fovSetting = ; 46 | 47 | //Set gl options 48 | GL11.glViewport(0, 0, mc.displayWidth, mc.displayHeight); 49 | GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); 50 | EXTFramebufferObject.glBindFramebufferEXT(EXTFramebufferObject.GL_FRAMEBUFFER_EXT, framebuffer); 51 | GL11.glClearColor(1.0f, 0.0f, 0.0f, 0.5f); 52 | GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); 53 | 54 | int i1 = mc.gameSettings.limitFramerate; 55 | if (mc.isFramerateLimitBelowMax()) { 56 | entityRenderer.renderWorld(renderTime, (1000000000 / i1)); 57 | } else { 58 | entityRenderer.renderWorld(renderTime, 0L); 59 | } 60 | } catch (Exception e) { 61 | try { 62 | //Clean up the tessellator, just in case. 63 | Tessellator.instance.draw(); 64 | } catch (Exception e2) { 65 | //It might throw an exception, but that just means we didn't need to clean it up (this time) 66 | } 67 | throw new RuntimeException("Error while rendering proxy world", e); 68 | } finally { 69 | GL11.glEnable(GL11.GL_TEXTURE_2D); 70 | EXTFramebufferObject.glBindFramebufferEXT(EXTFramebufferObject.GL_FRAMEBUFFER_EXT, 0); 71 | 72 | GL11.glViewport(0, 0, widthBackup, heightBackup); 73 | GL11.glLoadIdentity(); 74 | 75 | mc.gameSettings.thirdPersonView = thirdPersonBackup; 76 | mc.gameSettings.hideGUI = hideGuiBackup; 77 | mc.gameSettings.particleSetting = particleBackup; 78 | mc.gameSettings.anaglyph = anaglyphBackup; 79 | mc.gameSettings.renderDistanceChunks = renderDistanceBackup; 80 | mc.gameSettings.fovSetting = FOVbackup; 81 | 82 | mc.displayHeight = heightBackup; 83 | mc.displayWidth = widthBackup; 84 | } 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/command/CommandBaseAdv.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.command; 2 | 3 | import java.util.Random; 4 | 5 | import net.minecraft.command.CommandBase; 6 | import net.minecraft.command.CommandException; 7 | import net.minecraft.command.ICommandSender; 8 | import net.minecraft.command.NumberInvalidException; 9 | import net.minecraft.command.PlayerNotFoundException; 10 | import net.minecraft.command.PlayerSelector; 11 | import net.minecraft.entity.Entity; 12 | import net.minecraft.entity.player.EntityPlayerMP; 13 | import net.minecraft.server.MinecraftServer; 14 | import net.minecraft.tileentity.TileEntity; 15 | import net.minecraft.util.ChunkCoordinates; 16 | import net.minecraft.world.World; 17 | 18 | public abstract class CommandBaseAdv extends CommandBase { 19 | 20 | public void sendToAdmins(ICommandSender agent, String text, Object[] objects) { 21 | func_152373_a(agent, this, text, objects); 22 | } 23 | 24 | public static EntityPlayerMP getTargetPlayer(ICommandSender sender, String target) { 25 | EntityPlayerMP entityplayermp = PlayerSelector.matchOnePlayer(sender, target); 26 | 27 | if (entityplayermp == null) { 28 | entityplayermp = MinecraftServer.getServer().getConfigurationManager().func_152612_a(target); 29 | } 30 | if (entityplayermp == null) { throw new PlayerNotFoundException(); } 31 | return entityplayermp; 32 | } 33 | 34 | public static Integer getSenderDimension(ICommandSender sender) { 35 | World w = sender.getEntityWorld(); 36 | if (w == null) throw new CommandException("You must specify a dimension to use this command from the commandline"); 37 | return w.provider.dimensionId; 38 | } 39 | 40 | /** 41 | * Returns the given ICommandSender as a EntityPlayer or throw an exception. 42 | */ 43 | public static TileEntity getCommandSenderAsTileEntity(ICommandSender sender) { 44 | try { 45 | World world = sender.getEntityWorld(); 46 | ChunkCoordinates coords = sender.getPlayerCoordinates(); 47 | return world.getTileEntity(coords.posX, coords.posY, coords.posZ); 48 | } catch (Exception e) { 49 | throw new CommandException("Could not get tile entity"); 50 | } 51 | } 52 | 53 | public static double handleRelativeNumber(ICommandSender sender, double origin, String arg) { 54 | return handleRelativeNumber(sender, origin, arg, -30000000, 30000000); 55 | } 56 | 57 | public static double handleRelativeNumber(ICommandSender par1ICommandSender, double origin, String arg, int min, int max) { 58 | boolean relative = arg.startsWith("~"); 59 | boolean random = arg.startsWith("?"); 60 | if (random) relative = true; 61 | double d1 = relative ? origin : 0.0D; 62 | 63 | if (!relative || arg.length() > 1) { 64 | boolean flag1 = arg.contains("."); 65 | 66 | if (relative) { 67 | arg = arg.substring(1); 68 | } 69 | 70 | double d2 = parseDouble(par1ICommandSender, arg); 71 | if (random) { 72 | Random rand = new Random(); 73 | d1 += (rand.nextDouble() * 2 - 1) * d2; 74 | } else { 75 | d1 += d2; 76 | } 77 | 78 | if (!flag1 && !relative) { 79 | d1 += 0.5D; 80 | } 81 | } 82 | 83 | if (min != 0 || max != 0) { 84 | if (d1 < min) { throw new NumberInvalidException("commands.generic.double.tooSmall", new Object[] { Double.valueOf(d1), Integer.valueOf(min) }); } 85 | 86 | if (d1 > max) { throw new NumberInvalidException("commands.generic.double.tooBig", new Object[] { Double.valueOf(d1), Integer.valueOf(max) }); } 87 | } 88 | 89 | return d1; 90 | } 91 | 92 | /** 93 | * Returns the player for a username as an Entity or throws an exception. 94 | */ 95 | public static Entity parsePlayerByName(String name) throws PlayerNotFoundException { 96 | EntityPlayerMP player = MinecraftServer.getServer().getConfigurationManager().func_152612_a(name); 97 | if (player != null) { return player; } 98 | throw new PlayerNotFoundException("lookingglass.commands.generic.player.notfound", new Object[] { name }); 99 | } 100 | 101 | public static float parseFloat(ICommandSender par0ICommandSender, String par1Str) { 102 | try { 103 | return Float.parseFloat(par1Str); 104 | } catch (NumberFormatException numberformatexception) { 105 | throw new NumberInvalidException("commands.generic.num.invalid", new Object[] { par1Str }); 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/command/CommandCreateView.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.command; 2 | 3 | import net.minecraft.command.CommandException; 4 | import net.minecraft.command.ICommandSender; 5 | import net.minecraft.command.WrongUsageException; 6 | import net.minecraft.entity.Entity; 7 | import net.minecraft.util.ChunkCoordinates; 8 | import net.minecraft.world.WorldServer; 9 | import net.minecraftforge.common.DimensionManager; 10 | 11 | import com.xcompwiz.lookingglass.entity.EntityPortal; 12 | 13 | public class CommandCreateView extends CommandBaseAdv { 14 | @Override 15 | public String getCommandName() { 16 | return "lg-viewdim"; 17 | } 18 | 19 | @Override 20 | public String getCommandUsage(ICommandSender par1ICommandSender) { 21 | return "/" + this.getCommandName() + " targetdim [dim, x, y, z]"; 22 | } 23 | 24 | @Override 25 | public void processCommand(ICommandSender agent, String[] args) { 26 | int targetdim = 0; 27 | Integer dim = null; 28 | ChunkCoordinates coords = null; 29 | 30 | //XXX: Set Coordinates of view location? 31 | if (args.length > 0) { 32 | String sTarget = args[0]; 33 | targetdim = parseInt(agent, sTarget); 34 | } else { 35 | throw new WrongUsageException("Could not parse command."); 36 | } 37 | if (args.length > 4) { 38 | dim = parseInt(agent, args[1]); 39 | Entity caller = null; 40 | try { 41 | caller = getCommandSenderAsPlayer(agent); 42 | } catch (Exception e) { 43 | } 44 | int x = (int) handleRelativeNumber(agent, (caller != null ? caller.posX : 0), args[2]); 45 | int y = (int) handleRelativeNumber(agent, (caller != null ? caller.posY : 0), args[3], 0, 0); 46 | int z = (int) handleRelativeNumber(agent, (caller != null ? caller.posZ : 0), args[4]); 47 | coords = new ChunkCoordinates(x, y, z); 48 | } 49 | if (coords == null) { 50 | dim = getSenderDimension(agent); 51 | coords = agent.getPlayerCoordinates(); 52 | } 53 | if (coords == null) throw new WrongUsageException("Location Required"); 54 | 55 | WorldServer worldObj = DimensionManager.getWorld(dim); 56 | if (worldObj == null) { throw new CommandException("The target world is not loaded"); } 57 | 58 | EntityPortal portal = new EntityPortal(worldObj, targetdim, coords.posX, coords.posY, coords.posZ); 59 | worldObj.spawnEntityInWorld(portal); 60 | 61 | sendToAdmins(agent, "A window to dimension " + targetdim + " has been created.", new Object[0]); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/core/CommonProxy.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.core; 2 | 3 | public class CommonProxy { 4 | public void init() {} 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/core/LookingGlassForgeEventHandler.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.core; 2 | 3 | import java.util.List; 4 | 5 | import net.minecraft.entity.Entity; 6 | import net.minecraft.world.chunk.Chunk; 7 | import net.minecraftforge.event.world.ChunkEvent; 8 | import net.minecraftforge.event.world.WorldEvent; 9 | 10 | import com.xcompwiz.lookingglass.entity.EntityPortal; 11 | 12 | import cpw.mods.fml.common.eventhandler.SubscribeEvent; 13 | import cpw.mods.fml.relauncher.Side; 14 | import cpw.mods.fml.relauncher.SideOnly; 15 | 16 | public class LookingGlassForgeEventHandler { 17 | 18 | @SideOnly(Side.CLIENT) 19 | @SubscribeEvent 20 | public void onChunkUnload(ChunkEvent.Unload event) { 21 | if (!event.world.isRemote) return; 22 | Chunk chunk = event.getChunk(); 23 | // When we unload a chunk client side, we want to make sure that any view entities clean up. Not strictly necessary, but a good practice. 24 | // I don't trust vanilla to unload entity references quickly/correctly/completely. 25 | for (int i = 0; i < chunk.entityLists.length; ++i) { 26 | List list = chunk.entityLists[i]; 27 | for (Entity entity : list) { 28 | if (entity instanceof EntityPortal) ((EntityPortal) entity).releaseActiveView(); 29 | } 30 | } 31 | } 32 | 33 | @SideOnly(Side.CLIENT) 34 | @SubscribeEvent 35 | public void onWorldUnload(WorldEvent.Unload event) { 36 | if (!event.world.isRemote) return; 37 | // When we unload a world client side, we want to make sure that any view entities clean up. Not strictly necessary, but a good practice. 38 | // I don't trust vanilla to unload entity references quickly/correctly/completely. 39 | for (Object entity : event.world.loadedEntityList) { 40 | if (entity instanceof EntityPortal) ((EntityPortal) entity).releaseActiveView(); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/entity/EntityCamera.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.entity; 2 | 3 | import net.minecraft.block.material.Material; 4 | import net.minecraft.client.Minecraft; 5 | import net.minecraft.client.entity.EntityClientPlayerMP; 6 | import net.minecraft.entity.Entity; 7 | import net.minecraft.entity.EntityLivingBase; 8 | import net.minecraft.entity.SharedMonsterAttributes; 9 | import net.minecraft.entity.effect.EntityLightningBolt; 10 | import net.minecraft.entity.player.EntityPlayer; 11 | import net.minecraft.item.ItemStack; 12 | import net.minecraft.nbt.NBTTagCompound; 13 | import net.minecraft.potion.Potion; 14 | import net.minecraft.potion.PotionEffect; 15 | import net.minecraft.util.ChunkCoordinates; 16 | import net.minecraft.util.DamageSource; 17 | import net.minecraft.world.World; 18 | 19 | import com.xcompwiz.lookingglass.api.animator.ICameraAnimator; 20 | 21 | /** 22 | * Our camera entity. This is made a player so that we can replace the player client-side when doing rendering. 23 | * At the bottom of the class we create a bunch of method stubs to override higher level logic, so that our "player" doesn't act like one. 24 | */ 25 | public class EntityCamera extends EntityClientPlayerMP { 26 | 27 | private ICameraAnimator animator; 28 | private ChunkCoordinates target; 29 | private boolean defaultSpawn = false; 30 | 31 | private float fovmultiplier = 1; 32 | 33 | public EntityCamera(World worldObj, ChunkCoordinates spawn) { 34 | super(Minecraft.getMinecraft(), worldObj, Minecraft.getMinecraft().getSession(), null, null); 35 | this.target = spawn; 36 | if (target == null) { 37 | defaultSpawn = true; 38 | ChunkCoordinates cc = worldObj.provider.getSpawnPoint(); 39 | int y = updateTargetPosition(cc); 40 | target = new ChunkCoordinates(cc.posX, y, cc.posZ); 41 | } 42 | this.setPositionAndUpdate(target.posX, target.posY, target.posZ); 43 | } 44 | 45 | public void setAnimator(ICameraAnimator animator) { 46 | this.animator = animator; 47 | if (this.animator != null) this.animator.setTarget(target); 48 | } 49 | 50 | @Override 51 | protected void applyEntityAttributes() { 52 | super.applyEntityAttributes(); 53 | getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(1); 54 | getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.0D); 55 | } 56 | 57 | public void updateWorldSpawn(ChunkCoordinates cc) { 58 | if (defaultSpawn) { 59 | int y = updateTargetPosition(cc); 60 | target = new ChunkCoordinates(cc.posX, y, cc.posZ); 61 | this.setPositionAndUpdate(target.posX, target.posY, target.posZ); 62 | if (animator != null) animator.setTarget(cc); 63 | this.refreshAnimator(); 64 | } 65 | } 66 | 67 | private int updateTargetPosition(ChunkCoordinates target) { 68 | int x = target.posX; 69 | int y = target.posY; 70 | int z = target.posZ; 71 | if (!this.worldObj.getChunkFromBlockCoords(x, z).isEmpty()) { 72 | if (this.worldObj.getBlock(x, y, z).getBlocksMovement(this.worldObj, x, y, z)) { 73 | while (y > 0 && this.worldObj.getBlock(x, --y, z).getBlocksMovement(this.worldObj, x, y, z)) 74 | ; 75 | if (y == 0) y = target.posY; 76 | else ++y; 77 | } else { 78 | while (y < 256 && !this.worldObj.getBlock(x, ++y, z).getBlocksMovement(this.worldObj, x, y, z)) 79 | ; 80 | if (y == 256) y = target.posY; 81 | } 82 | return y; 83 | } 84 | return target.posY; 85 | } 86 | 87 | public void refreshAnimator() { 88 | if (this.animator != null) animator.refresh(); 89 | } 90 | 91 | public void tick(long dt) { 92 | if (this.animator != null) animator.update(dt); 93 | } 94 | 95 | @Override 96 | public float getFOVMultiplier() { 97 | return fovmultiplier; 98 | } 99 | 100 | public void setFOVMult(float fovmult) { 101 | fovmultiplier = fovmult; 102 | } 103 | 104 | /* 105 | * POSSIBLY UNNECESSARY CODE TO PREVENT OTHER CODE FROM RUNNING 106 | */ 107 | @Override 108 | public void onEntityUpdate() {} 109 | 110 | @Override 111 | public void onLivingUpdate() {} 112 | 113 | @Override 114 | public void onUpdate() {} 115 | 116 | @Override 117 | protected int getExperiencePoints(EntityPlayer par1EntityPlayer) { 118 | return 0; 119 | } 120 | 121 | @Override 122 | protected boolean isAIEnabled() { 123 | return false; 124 | } 125 | 126 | @Override 127 | public void writeEntityToNBT(NBTTagCompound par1NBTTagCompound) {} 128 | 129 | @Override 130 | public void readEntityFromNBT(NBTTagCompound par1NBTTagCompound) {} 131 | 132 | @Override 133 | public void setAIMoveSpeed(float par1) {} 134 | 135 | @Override 136 | protected void updateAITasks() {} 137 | 138 | @Override 139 | public ItemStack getHeldItem() { 140 | return null; 141 | } 142 | 143 | @Override 144 | public ItemStack getEquipmentInSlot(int par1) { 145 | return null; 146 | } 147 | 148 | @Override 149 | public void setCurrentItemOrArmor(int par1, ItemStack par2ItemStack) {} 150 | 151 | @Override 152 | public ItemStack[] getLastActiveItems() { 153 | return null; 154 | } 155 | 156 | @Override 157 | protected void dropEquipment(boolean par1, int par2) {} 158 | 159 | @Override 160 | protected void fall(float par1) {} 161 | 162 | @Override 163 | protected void updateFallState(double par1, boolean par3) {} 164 | 165 | @Override 166 | protected void onDeathUpdate() { 167 | this.setDead(); 168 | } 169 | 170 | @Override 171 | public EntityLivingBase getAITarget() { 172 | return null; 173 | } 174 | 175 | @Override 176 | public void setRevengeTarget(EntityLivingBase par1) {} 177 | 178 | @Override 179 | public EntityLivingBase getLastAttacker() { 180 | return null; 181 | } 182 | 183 | @Override 184 | public void setLastAttacker(Entity par1) {} 185 | 186 | @Override 187 | protected void updatePotionEffects() {} 188 | 189 | @Override 190 | public void clearActivePotions() {} 191 | 192 | @Override 193 | public boolean isPotionActive(int par1) { 194 | return false; 195 | } 196 | 197 | @Override 198 | public boolean isPotionActive(Potion par1) { 199 | return false; 200 | } 201 | 202 | @Override 203 | public PotionEffect getActivePotionEffect(Potion par1) { 204 | return null; 205 | } 206 | 207 | @Override 208 | public void addPotionEffect(PotionEffect par1) {} 209 | 210 | @Override 211 | public boolean isPotionApplicable(PotionEffect par1) { 212 | return false; 213 | } 214 | 215 | @Override 216 | public boolean isEntityUndead() { 217 | return false; 218 | } 219 | 220 | @Override 221 | public void removePotionEffectClient(int par1) {} 222 | 223 | @Override 224 | public void removePotionEffect(int par1) {} 225 | 226 | @Override 227 | protected void onNewPotionEffect(PotionEffect par1) {} 228 | 229 | @Override 230 | protected void onChangedPotionEffect(PotionEffect par1, boolean par2) {} 231 | 232 | @Override 233 | protected void onFinishedPotionEffect(PotionEffect par1) {} 234 | 235 | @Override 236 | public void heal(float par1) {} 237 | 238 | @Override 239 | public boolean attackEntityFrom(DamageSource par1, float par2) { 240 | return false; 241 | } 242 | 243 | @Override 244 | public void renderBrokenItemStack(ItemStack par1) {} 245 | 246 | @Override 247 | public void onDeath(DamageSource par1) { 248 | this.worldObj.setEntityState(this, (byte) 3); 249 | } 250 | 251 | @Override 252 | public void knockBack(Entity par1Entity, float par2, double par3, double par5) {} 253 | 254 | @Override 255 | public boolean isOnLadder() { 256 | return false; 257 | } 258 | 259 | @Override 260 | public int getTotalArmorValue() { 261 | return 0; 262 | } 263 | 264 | @Override 265 | protected float applyArmorCalculations(DamageSource par1DamageSource, float par2) { 266 | return par2; 267 | } 268 | 269 | @Override 270 | protected float applyPotionDamageCalculations(DamageSource par1DamageSource, float par2) { 271 | return par2; 272 | } 273 | 274 | @Override 275 | protected void damageEntity(DamageSource par1, float par2) {} 276 | 277 | @Override 278 | public void swingItem() {} 279 | 280 | @Override 281 | protected void updateArmSwingProgress() {} 282 | 283 | @Override 284 | public void setSprinting(boolean par1) {} 285 | 286 | @Override 287 | protected float getSoundVolume() { 288 | return 0F; 289 | } 290 | 291 | @Override 292 | public void dismountEntity(Entity par1Entity) {} 293 | 294 | @Override 295 | public void moveEntityWithHeading(float par1, float par2) {} 296 | 297 | @Override 298 | public void updateRidden() {} 299 | 300 | @Override 301 | public void setJumping(boolean par1) {} 302 | 303 | @Override 304 | public void onItemPickup(Entity par1Entity, int par2) {} 305 | 306 | @Override 307 | public boolean canEntityBeSeen(Entity par1Entity) { 308 | return false; 309 | } 310 | 311 | @Override 312 | public boolean canBeCollidedWith() { 313 | return false; 314 | } 315 | 316 | @Override 317 | public boolean canBePushed() { 318 | return false; 319 | } 320 | 321 | @Override 322 | protected boolean canTriggerWalking() { 323 | return false; 324 | } 325 | 326 | @Override 327 | public boolean handleWaterMovement() { 328 | return false; 329 | } 330 | 331 | @Override 332 | public boolean isInsideOfMaterial(Material par1Material) { 333 | return false; 334 | } 335 | 336 | @Override 337 | public boolean handleLavaMovement() { 338 | return false; 339 | } 340 | 341 | @Override 342 | public void moveFlying(float par1, float par2, float par3) {} 343 | 344 | @Override 345 | public float getBrightness(float par1) { 346 | return 0; 347 | } 348 | 349 | @Override 350 | public void applyEntityCollision(Entity par1Entity) {} 351 | 352 | @Override 353 | public boolean isBurning() { 354 | return false; 355 | } 356 | 357 | @Override 358 | public boolean isRiding() { 359 | return false; 360 | } 361 | 362 | @Override 363 | public boolean isSneaking() { 364 | return false; 365 | } 366 | 367 | @Override 368 | public boolean isInvisible() { 369 | return true; 370 | } 371 | 372 | @Override 373 | public void onStruckByLightning(EntityLightningBolt par1) {} 374 | 375 | @Override 376 | public boolean isEntityInvulnerable() { 377 | return true; 378 | } 379 | 380 | @Override 381 | public void travelToDimension(int par1) {} 382 | 383 | @Override 384 | public boolean shouldRenderInPass(int pass) { 385 | return false; 386 | } 387 | 388 | @Override 389 | protected void collideWithEntity(Entity par1Entity) {} 390 | 391 | @Override 392 | protected void collideWithNearbyEntities() {} 393 | 394 | @Override 395 | public boolean doesEntityNotTriggerPressurePlate() { 396 | return true; 397 | } 398 | } 399 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/entity/EntityPortal.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.entity; 2 | 3 | import net.minecraft.client.Minecraft; 4 | import net.minecraft.entity.Entity; 5 | import net.minecraft.nbt.NBTTagCompound; 6 | import net.minecraft.world.World; 7 | 8 | import com.xcompwiz.lookingglass.api.animator.CameraAnimatorPlayer; 9 | import com.xcompwiz.lookingglass.api.view.IWorldView; 10 | import com.xcompwiz.lookingglass.client.proxyworld.ProxyWorldManager; 11 | import com.xcompwiz.lookingglass.client.proxyworld.WorldView; 12 | 13 | import cpw.mods.fml.relauncher.Side; 14 | import cpw.mods.fml.relauncher.SideOnly; 15 | 16 | /** 17 | * Despite it's name, this isn't so much a doorway or window as it is a moving picture. More Harry Potter's portraits than Portal's portals. (Man I wish the 18 | * best example of portal rendering in games wasn't called Portal.... So hard to reference sanely.) 19 | */ 20 | public class EntityPortal extends Entity { 21 | // We store the dimension ID we point at in the dataWatcher at this index. 22 | private static final int targetID = 20; 23 | 24 | // How long the window has to live. Functions as a countdown timer. 25 | private long lifetime = 1000L; 26 | 27 | @SideOnly(Side.CLIENT) 28 | private IWorldView activeview; 29 | 30 | public EntityPortal(World world) { 31 | super(world); 32 | dataWatcher.addObject(targetID, Integer.valueOf(0)); 33 | } 34 | 35 | public EntityPortal(World world, int targetdim, int posX, int posY, int posZ) { 36 | this(world); 37 | this.setTarget(targetdim); 38 | this.setPosition(posX, posY, posZ); 39 | } 40 | 41 | /** Puts the dim id target in the datawatcher. */ 42 | private void setTarget(int targetdim) { 43 | dataWatcher.updateObject(targetID, targetdim); 44 | //XXX: Technically speaking, it might be wise to design this so that it can change targets, but that's not needed for this class. 45 | // If it was, we'd have this function kill any active views when the target changed, causing it to open a new view for the new target. 46 | } 47 | 48 | /** Gets the target dimension id */ 49 | private int getTarget() { 50 | return dataWatcher.getWatchableObjectInt(targetID); 51 | } 52 | 53 | @Override 54 | protected void entityInit() {} 55 | 56 | @Override 57 | @SideOnly(Side.CLIENT) 58 | public void setDead() { 59 | super.setDead(); 60 | releaseActiveView(); 61 | } 62 | 63 | @Override 64 | public void onUpdate() { 65 | // Countdown to die 66 | --lifetime; 67 | if (lifetime <= 0) { 68 | this.setDead(); 69 | return; 70 | } 71 | super.onUpdate(); 72 | } 73 | 74 | @SideOnly(Side.CLIENT) 75 | public IWorldView getActiveView() { 76 | if (!worldObj.isRemote) return null; 77 | if (activeview == null) { 78 | activeview = ProxyWorldManager.createWorldView(getTarget(), null, 160, 240); 79 | if (activeview != null) { 80 | // We set the player animator on our portrait. This makes the view move a little depending on how the user looks at it. Not quite a replacement for portal rendering, but cool looking anyway. 81 | activeview.setAnimator(new CameraAnimatorPlayer(activeview.getCamera(), this, Minecraft.getMinecraft().thePlayer)); 82 | } 83 | } 84 | return activeview; 85 | } 86 | 87 | @SideOnly(Side.CLIENT) 88 | public void releaseActiveView() { 89 | if (activeview != null) ProxyWorldManager.destroyWorldView((WorldView) activeview); 90 | activeview = null; 91 | } 92 | 93 | @Override 94 | protected void readEntityFromNBT(NBTTagCompound nbt) { 95 | setTarget(nbt.getInteger("Dimension")); 96 | lifetime = nbt.getLong("lifetime"); 97 | } 98 | 99 | @Override 100 | protected void writeEntityToNBT(NBTTagCompound nbt) { 101 | nbt.setInteger("Dimension", getTarget()); 102 | nbt.setLong("lifetime", lifetime); 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/imc/IMCAPIRegister.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.imc; 2 | 3 | import java.lang.reflect.Method; 4 | 5 | import com.xcompwiz.lookingglass.api.APIInstanceProvider; 6 | import com.xcompwiz.lookingglass.apiimpl.InternalAPI; 7 | import com.xcompwiz.lookingglass.imc.IMCHandler.IMCProcessor; 8 | import com.xcompwiz.lookingglass.log.LoggerUtils; 9 | 10 | import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; 11 | 12 | public class IMCAPIRegister implements IMCProcessor { 13 | 14 | @Override 15 | public void process(IMCMessage message) { 16 | if (!message.isStringMessage()) return; 17 | LoggerUtils.info(String.format("Receiving API registration request from [%s] for method %s", message.getSender(), message.getStringValue())); 18 | callbackRegistration(message.getStringValue(), message.getSender()); 19 | } 20 | 21 | /** 22 | * This handles the classpath and method location and calling for API IMC calls Based on some code from WAILA. 23 | * @param method The method (prefixed by classname) to call 24 | * @param modname The name of the mod which made the request 25 | */ 26 | public static void callbackRegistration(String method, String modname) { 27 | String[] splitName = method.split("\\."); 28 | String methodName = splitName[splitName.length - 1]; 29 | String className = method.substring(0, method.length() - methodName.length() - 1); 30 | 31 | APIInstanceProvider providerinst = InternalAPI.getAPIProviderInstance(modname); 32 | if (providerinst == null) { 33 | LoggerUtils.error(String.format("Could not initialize API provider instance for %s", modname)); 34 | return; 35 | } 36 | 37 | LoggerUtils.info(String.format("Trying to call (reflection) %s %s", className, methodName)); 38 | 39 | try { 40 | Class reflectClass = Class.forName(className); 41 | Method reflectMethod = reflectClass.getDeclaredMethod(methodName, APIInstanceProvider.class); 42 | reflectMethod.invoke(null, providerinst); 43 | LoggerUtils.info(String.format("API provided to %s", modname)); 44 | } catch (ClassNotFoundException e) { 45 | LoggerUtils.error(String.format("Could not find class %s", className)); 46 | } catch (NoSuchMethodException e) { 47 | LoggerUtils.error(String.format("Could not find method %s", methodName)); 48 | } catch (Exception e) { 49 | LoggerUtils.error(String.format("Exception while calling the method %s.%s", className, methodName)); 50 | e.printStackTrace(); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/imc/IMCHandler.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.imc; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import com.google.common.collect.ImmutableList; 7 | import com.xcompwiz.lookingglass.log.LoggerUtils; 8 | 9 | import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; 10 | 11 | public class IMCHandler { 12 | public interface IMCProcessor { 13 | public void process(IMCMessage message); 14 | } 15 | 16 | private static Map processors = new HashMap(); 17 | 18 | static { 19 | registerProcessor("api", new IMCAPIRegister()); 20 | } 21 | 22 | private static void registerProcessor(String key, IMCProcessor processor) { 23 | processors.put(key.toLowerCase(), processor); 24 | } 25 | 26 | public static void process(ImmutableList messages) { 27 | for (IMCMessage message : messages) { 28 | String key = message.key.toLowerCase(); 29 | IMCProcessor process = processors.get(key); 30 | if (process == null) { 31 | LoggerUtils.error("IMC message '%s' from [%s] unrecognized", key, message.getSender()); 32 | } 33 | try { 34 | process.process(message); 35 | } catch (Exception e) { 36 | LoggerUtils.error("Failed to process IMC message '%s' from [%s]", key, message.getSender()); 37 | e.printStackTrace(); 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/log/LoggerUtils.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.log; 2 | 3 | import org.apache.logging.log4j.Level; 4 | import org.apache.logging.log4j.LogManager; 5 | import org.apache.logging.log4j.Logger; 6 | 7 | import com.xcompwiz.lookingglass.LookingGlass; 8 | 9 | public final class LoggerUtils { 10 | private static Logger log = null; 11 | 12 | /** 13 | * Configure the logger 14 | */ 15 | private static void configureLogging() { 16 | log = LogManager.getLogger(LookingGlass.MODID); 17 | } 18 | 19 | public static void log(Level level, String message, Object... params) { 20 | if (log == null) { 21 | configureLogging(); 22 | } 23 | if (message == null) { 24 | log.log(level, "Attempted to log null message."); 25 | } else { 26 | try { 27 | message = String.format(message, params); 28 | } catch (Exception e) { 29 | } 30 | log.log(level, message); 31 | } 32 | } 33 | 34 | public static void info(String message, Object... params) { 35 | log(Level.INFO, message, params); 36 | } 37 | 38 | public static void warn(String message, Object... params) { 39 | log(Level.WARN, message, params); 40 | } 41 | 42 | public static void error(String message, Object... params) { 43 | log(Level.ERROR, message, params); 44 | } 45 | 46 | public static void debug(String message, Object... params) { 47 | //NOPE 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/network/LookingGlassPacketManager.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.network; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | 5 | import java.util.HashMap; 6 | 7 | import net.minecraft.client.Minecraft; 8 | import net.minecraft.entity.player.EntityPlayer; 9 | import net.minecraft.network.NetHandlerPlayServer; 10 | import net.minecraft.network.NetworkManager; 11 | 12 | import com.xcompwiz.lookingglass.log.LoggerUtils; 13 | import com.xcompwiz.lookingglass.network.packet.PacketHandlerBase; 14 | 15 | import cpw.mods.fml.common.eventhandler.SubscribeEvent; 16 | import cpw.mods.fml.common.network.FMLEventChannel; 17 | import cpw.mods.fml.common.network.FMLNetworkEvent.ClientCustomPacketEvent; 18 | import cpw.mods.fml.common.network.FMLNetworkEvent.ServerCustomPacketEvent; 19 | import cpw.mods.fml.common.network.internal.FMLProxyPacket; 20 | import cpw.mods.fml.relauncher.Side; 21 | import cpw.mods.fml.relauncher.SideOnly; 22 | 23 | public class LookingGlassPacketManager { 24 | 25 | public static final String CHANNEL = "lookingglass"; 26 | public static FMLEventChannel bus; 27 | 28 | private static HashMap packethandlers = new HashMap(); 29 | private static HashMap, Byte> idmap = new HashMap, Byte>(); 30 | 31 | /** 32 | * Register a new packet handler to the manager. We use pre-defined packet ids to avoid mismatched packet ids across client-server communications. 33 | * @param handler The packet handler to register 34 | * @param id The id to which the handler should be bound 35 | */ 36 | public static void registerPacketHandler(PacketHandlerBase handler, byte id) { 37 | if (packethandlers.get(id) != null) { throw new RuntimeException("Multiple id registrations for packet type on " + CHANNEL + " channel"); } 38 | packethandlers.put(id, handler); 39 | idmap.put(handler.getClass(), id); 40 | } 41 | 42 | public static byte getId(PacketHandlerBase handler) { 43 | return getId(handler.getClass()); 44 | } 45 | 46 | public static byte getId(Class handlerclass) { 47 | if (!idmap.containsKey(handlerclass)) throw new RuntimeException("Attempted to get id for unregistered network message handler."); 48 | return idmap.get(handlerclass); 49 | } 50 | 51 | @SubscribeEvent 52 | @SideOnly(Side.CLIENT) 53 | public void onPacketData(ClientCustomPacketEvent event) { 54 | FMLProxyPacket pkt = event.packet; 55 | 56 | onPacketData(event.manager, pkt, Minecraft.getMinecraft().thePlayer); 57 | } 58 | 59 | @SubscribeEvent 60 | public void onPacketData(ServerCustomPacketEvent event) { 61 | FMLProxyPacket pkt = event.packet; 62 | 63 | onPacketData(event.manager, pkt, ((NetHandlerPlayServer) event.handler).playerEntity); 64 | } 65 | 66 | public void onPacketData(NetworkManager manager, FMLProxyPacket packet, EntityPlayer player) { 67 | try { 68 | if (packet == null || packet.payload() == null) { throw new RuntimeException("Empty packet sent to " + CHANNEL + " channel"); } 69 | ByteBuf data = packet.payload(); 70 | byte type = data.readByte(); 71 | 72 | try { 73 | PacketHandlerBase handler = packethandlers.get(type); 74 | if (handler == null) { throw new RuntimeException("Unrecognized packet sent to " + CHANNEL + " channel"); } 75 | handler.handle(data, player); 76 | } catch (Exception e) { 77 | LoggerUtils.warn("PacketHandler: Failed to handle packet type " + type); 78 | LoggerUtils.warn(e.toString()); 79 | e.printStackTrace(); 80 | } 81 | } catch (Exception e) { 82 | LoggerUtils.warn("PacketHandler: Failed to read packet"); 83 | LoggerUtils.warn(e.toString()); 84 | e.printStackTrace(); 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/network/PacketHolder.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.network; 2 | 3 | import net.minecraft.entity.player.EntityPlayer; 4 | import net.minecraft.entity.player.EntityPlayerMP; 5 | import cpw.mods.fml.common.network.internal.FMLProxyPacket; 6 | 7 | /** 8 | * @author Ken Butler/shadowking97 9 | */ 10 | // TODO: This class doesn't need to exist, it's just a (Player, Packet) tuple 11 | public class PacketHolder { 12 | EntityPlayer player; 13 | FMLProxyPacket packet; 14 | 15 | public PacketHolder(EntityPlayer player, FMLProxyPacket packet) { 16 | this.player = player; 17 | this.packet = packet; 18 | } 19 | 20 | public boolean belongsToPlayer(EntityPlayer p) { 21 | return player.equals(p); 22 | } 23 | 24 | public int sendPacket() { 25 | if (packet != null) { 26 | LookingGlassPacketManager.bus.sendTo(packet, (EntityPlayerMP) player); 27 | return packet.payload().writerIndex(); 28 | } 29 | return 0; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/network/ServerPacketDispatcher.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.network; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | import net.minecraft.entity.player.EntityPlayer; 7 | 8 | import com.xcompwiz.lookingglass.proxyworld.ModConfigs; 9 | 10 | import cpw.mods.fml.common.network.internal.FMLProxyPacket; 11 | 12 | /** 13 | * This class is a variant o nthe vanilla server packet dispatcher. We use it so that we can send data to cleitns in a limited (throttled) manner. This allows 14 | * server admins to limit how much bandwidth LookingGlass consumes on a server. 15 | */ 16 | public class ServerPacketDispatcher extends Thread { 17 | 18 | private static ServerPacketDispatcher instance; 19 | 20 | private List packets; 21 | private boolean isRunning = true; 22 | 23 | private ServerPacketDispatcher() { 24 | packets = new LinkedList(); 25 | } 26 | 27 | public static ServerPacketDispatcher getInstance() { 28 | if (instance == null) instance = new ServerPacketDispatcher(); 29 | return instance; 30 | } 31 | 32 | public static void shutdown() { 33 | if (instance != null) instance.halt(); 34 | instance = null; 35 | } 36 | 37 | public void addPacket(EntityPlayer player, FMLProxyPacket packet) { 38 | synchronized (this) { 39 | packets.add(new PacketHolder(player, packet)); 40 | this.notify(); 41 | } 42 | } 43 | 44 | public void removeAllPacketsOf(EntityPlayer player) { 45 | synchronized (this) { 46 | for (int j = 0; j < packets.size(); ++j) { 47 | if (packets.get(j).belongsToPlayer(player)) { 48 | packets.remove(--j); 49 | } 50 | } 51 | } 52 | } 53 | 54 | public void tick() { 55 | int byteLimit = ModConfigs.dataRate; 56 | for (int bytes = 0; bytes < byteLimit && !packets.isEmpty();) { 57 | PacketHolder p = packets.get(0); 58 | bytes += p.sendPacket(); 59 | packets.remove(0); 60 | } 61 | } 62 | 63 | public void halt() { 64 | synchronized (this) { 65 | isRunning = false; 66 | packets.clear(); 67 | } 68 | } 69 | 70 | @Override 71 | public void run() { 72 | while (isRunning) { 73 | if (packets.size() > 0) { 74 | try { 75 | synchronized (this) { 76 | tick(); 77 | this.wait(20); 78 | } 79 | } catch (InterruptedException e) { 80 | e.printStackTrace(); 81 | } 82 | } else { 83 | try { 84 | synchronized (this) { 85 | this.wait(1000); 86 | } 87 | } catch (InterruptedException e) { 88 | e.printStackTrace(); 89 | } 90 | } 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/network/packet/PacketChunkInfo.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.network.packet; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | 5 | import java.util.concurrent.Semaphore; 6 | import java.util.zip.DataFormatException; 7 | import java.util.zip.Deflater; 8 | import java.util.zip.Inflater; 9 | 10 | import net.minecraft.client.multiplayer.WorldClient; 11 | import net.minecraft.entity.player.EntityPlayer; 12 | import net.minecraft.network.play.server.S21PacketChunkData; 13 | import net.minecraft.network.play.server.S21PacketChunkData.Extracted; 14 | import net.minecraft.world.WorldProviderSurface; 15 | import net.minecraft.world.chunk.Chunk; 16 | import net.minecraft.world.chunk.NibbleArray; 17 | import net.minecraft.world.chunk.storage.ExtendedBlockStorage; 18 | 19 | import com.xcompwiz.lookingglass.client.proxyworld.ProxyWorldManager; 20 | import com.xcompwiz.lookingglass.client.proxyworld.WorldView; 21 | import com.xcompwiz.lookingglass.log.LoggerUtils; 22 | import com.xcompwiz.lookingglass.network.LookingGlassPacketManager; 23 | 24 | import cpw.mods.fml.common.network.internal.FMLProxyPacket; 25 | 26 | /** 27 | * Based on code from Ken Butler/shadowking97 28 | */ 29 | public class PacketChunkInfo extends PacketHandlerBase { 30 | private static byte[] inflatearray; 31 | private static byte[] dataarray; 32 | private static Semaphore deflateGate = new Semaphore(1); 33 | 34 | private static int deflate(byte[] chunkData, byte[] compressedChunkData) { 35 | Deflater deflater = new Deflater(-1); 36 | if (compressedChunkData == null) return 0; 37 | int bytesize = 0; 38 | try { 39 | deflater.setInput(chunkData, 0, chunkData.length); 40 | deflater.finish(); 41 | bytesize = deflater.deflate(compressedChunkData); 42 | } finally { 43 | deflater.end(); 44 | } 45 | return bytesize; 46 | } 47 | 48 | public static FMLProxyPacket createPacket(Chunk chunk, boolean includeinit, int subid, int dim) { 49 | int xPos = chunk.xPosition; 50 | int zPos = chunk.zPosition; 51 | Extracted extracted = getMapChunkData(chunk, includeinit, subid); 52 | int yMSBPos = extracted.field_150281_c; 53 | int yPos = extracted.field_150280_b; 54 | byte[] chunkData = extracted.field_150282_a; 55 | 56 | deflateGate.acquireUninterruptibly(); 57 | byte[] compressedChunkData = new byte[chunkData.length]; 58 | int len = deflate(chunkData, compressedChunkData); 59 | deflateGate.release(); 60 | 61 | // This line may look like black magic (and, well, it is), but it's actually just returning a class reference for this class. Copy-paste safe. 62 | ByteBuf data = PacketHandlerBase.createDataBuffer((Class) new Object() {}.getClass().getEnclosingClass()); 63 | 64 | data.writeInt(dim); 65 | data.writeInt(xPos); 66 | data.writeInt(zPos); 67 | data.writeBoolean(includeinit); 68 | data.writeShort((short) (yPos & 65535)); 69 | data.writeShort((short) (yMSBPos & 65535)); 70 | data.writeInt(len); 71 | data.writeInt(chunkData.length); 72 | data.ensureWritable(len); 73 | data.writeBytes(compressedChunkData, 0, len); 74 | 75 | return buildPacket(data); 76 | } 77 | 78 | @Override 79 | public void handle(ByteBuf in, EntityPlayer player) { 80 | int dim = in.readInt(); 81 | int xPos = in.readInt(); 82 | int zPos = in.readInt(); 83 | boolean reqinit = in.readBoolean(); 84 | short yPos = in.readShort(); 85 | short yMSBPos = in.readShort(); 86 | int compressedsize = in.readInt(); 87 | int uncompressedsize = in.readInt(); 88 | byte[] chunkData = inflateChunkData(in, compressedsize, uncompressedsize); 89 | 90 | if (chunkData == null) { 91 | LookingGlassPacketManager.bus.sendToServer(PacketRequestChunk.createPacket(xPos, yPos, zPos, dim)); 92 | LoggerUtils.error("Chunk decompression failed: %d\t:\t%d\t\t%d : %d\n", yMSBPos, yPos, compressedsize, uncompressedsize); 93 | return; 94 | } 95 | handle(player, chunkData, dim, xPos, zPos, reqinit, yPos, yMSBPos); 96 | } 97 | 98 | public void handle(EntityPlayer player, byte[] chunkData, int dim, int xPos, int zPos, boolean reqinit, short yPos, short yMSBPos) { 99 | WorldClient proxyworld = ProxyWorldManager.getProxyworld(dim); 100 | if (proxyworld == null) return; 101 | if (proxyworld.provider.dimensionId != dim) return; 102 | 103 | //TODO: Test to see if this first part is even necessary 104 | Chunk chunk = proxyworld.getChunkProvider().provideChunk(xPos, zPos); 105 | if (reqinit && (chunk == null || chunk.isEmpty())) { 106 | if (yPos == 0) { 107 | proxyworld.doPreChunk(xPos, zPos, false); 108 | return; 109 | } 110 | proxyworld.doPreChunk(xPos, zPos, true); 111 | } 112 | // End possible removal section 113 | proxyworld.invalidateBlockReceiveRegion(xPos << 4, 0, zPos << 4, (xPos << 4) + 15, 256, (zPos << 4) + 15); 114 | chunk = proxyworld.getChunkFromChunkCoords(xPos, zPos); 115 | if (reqinit && (chunk == null || chunk.isEmpty())) { 116 | proxyworld.doPreChunk(xPos, zPos, true); 117 | chunk = proxyworld.getChunkFromChunkCoords(xPos, zPos); 118 | } 119 | if (chunk != null) { 120 | chunk.fillChunk(chunkData, yPos, yMSBPos, reqinit); 121 | receivedChunk(proxyworld, xPos, zPos); 122 | if (!reqinit || !(proxyworld.provider instanceof WorldProviderSurface)) { 123 | chunk.resetRelightChecks(); 124 | } 125 | } 126 | } 127 | 128 | public void receivedChunk(WorldClient worldObj, int cx, int cz) { 129 | worldObj.markBlockRangeForRenderUpdate(cx << 4, 0, cz << 4, (cx << 4) + 15, 256, (cz << 4) + 15); 130 | Chunk c = worldObj.getChunkFromChunkCoords(cx, cz); 131 | if (c == null || c.isEmpty()) return; 132 | 133 | for (WorldView activeview : ProxyWorldManager.getWorldViews(worldObj.provider.dimensionId)) { 134 | activeview.onChunkReceived(cx, cz); 135 | } 136 | 137 | int x = (cx << 4); 138 | int z = (cz << 4); 139 | for (int y = 0; y < worldObj.getActualHeight(); y += 16) { 140 | if (c.getAreLevelsEmpty(y, y)) continue; 141 | for (int x2 = 0; x2 < 16; ++x2) { 142 | for (int z2 = 0; z2 < 16; ++z2) { 143 | for (int y2 = 0; y2 < 16; ++y2) { 144 | int lx = x + x2; 145 | int ly = y + y2; 146 | int lz = z + z2; 147 | if (worldObj.getBlock(lx, ly, lz).hasTileEntity(worldObj.getBlockMetadata(lx, ly, lz))) { 148 | LookingGlassPacketManager.bus.sendToServer(PacketRequestTE.createPacket(lx, ly, lz, worldObj.provider.dimensionId)); 149 | } 150 | } 151 | } 152 | } 153 | } 154 | } 155 | 156 | private byte[] inflateChunkData(ByteBuf in, int compressedsize, int uncompressedsize) { 157 | if (inflatearray == null || inflatearray.length < compressedsize) { 158 | inflatearray = new byte[compressedsize]; 159 | } 160 | in.readBytes(inflatearray, 0, compressedsize); 161 | byte[] chunkData = new byte[uncompressedsize]; 162 | Inflater inflater = new Inflater(); 163 | inflater.setInput(inflatearray, 0, compressedsize); 164 | 165 | try { 166 | inflater.inflate(chunkData); 167 | } catch (DataFormatException e) { 168 | return null; 169 | } finally { 170 | inflater.end(); 171 | } 172 | return chunkData; 173 | } 174 | 175 | public static Extracted getMapChunkData(Chunk chunk, boolean includeinit, int subid) { 176 | int j = 0; 177 | ExtendedBlockStorage[] aextendedblockstorage = chunk.getBlockStorageArray(); 178 | int k = 0; 179 | S21PacketChunkData.Extracted extracted = new S21PacketChunkData.Extracted(); 180 | if (dataarray == null || dataarray.length < 196864) { 181 | dataarray = new byte[196864]; 182 | } 183 | byte[] abyte = dataarray; 184 | 185 | if (includeinit) { 186 | chunk.sendUpdates = true; 187 | } 188 | 189 | int l; 190 | 191 | for (l = 0; l < aextendedblockstorage.length; ++l) { 192 | if (aextendedblockstorage[l] != null && (!includeinit || !aextendedblockstorage[l].isEmpty()) && (subid & 1 << l) != 0) { 193 | extracted.field_150280_b |= 1 << l; 194 | 195 | if (aextendedblockstorage[l].getBlockMSBArray() != null) { 196 | extracted.field_150281_c |= 1 << l; 197 | ++k; 198 | } 199 | } 200 | } 201 | 202 | for (l = 0; l < aextendedblockstorage.length; ++l) { 203 | if (aextendedblockstorage[l] != null && (!includeinit || !aextendedblockstorage[l].isEmpty()) && (subid & 1 << l) != 0) { 204 | byte[] abyte1 = aextendedblockstorage[l].getBlockLSBArray(); 205 | System.arraycopy(abyte1, 0, abyte, j, abyte1.length); 206 | j += abyte1.length; 207 | } 208 | } 209 | 210 | NibbleArray nibblearray; 211 | 212 | for (l = 0; l < aextendedblockstorage.length; ++l) { 213 | if (aextendedblockstorage[l] != null && (!includeinit || !aextendedblockstorage[l].isEmpty()) && (subid & 1 << l) != 0) { 214 | nibblearray = aextendedblockstorage[l].getMetadataArray(); 215 | System.arraycopy(nibblearray.data, 0, abyte, j, nibblearray.data.length); 216 | j += nibblearray.data.length; 217 | } 218 | } 219 | 220 | for (l = 0; l < aextendedblockstorage.length; ++l) { 221 | if (aextendedblockstorage[l] != null && (!includeinit || !aextendedblockstorage[l].isEmpty()) && (subid & 1 << l) != 0) { 222 | nibblearray = aextendedblockstorage[l].getBlocklightArray(); 223 | System.arraycopy(nibblearray.data, 0, abyte, j, nibblearray.data.length); 224 | j += nibblearray.data.length; 225 | } 226 | } 227 | 228 | if (!chunk.worldObj.provider.hasNoSky) { 229 | for (l = 0; l < aextendedblockstorage.length; ++l) { 230 | if (aextendedblockstorage[l] != null && (!includeinit || !aextendedblockstorage[l].isEmpty()) && (subid & 1 << l) != 0) { 231 | nibblearray = aextendedblockstorage[l].getSkylightArray(); 232 | System.arraycopy(nibblearray.data, 0, abyte, j, nibblearray.data.length); 233 | j += nibblearray.data.length; 234 | } 235 | } 236 | } 237 | 238 | if (k > 0) { 239 | for (l = 0; l < aextendedblockstorage.length; ++l) { 240 | if (aextendedblockstorage[l] != null && (!includeinit || !aextendedblockstorage[l].isEmpty()) && aextendedblockstorage[l].getBlockMSBArray() != null && (subid & 1 << l) != 0) { 241 | nibblearray = aextendedblockstorage[l].getBlockMSBArray(); 242 | System.arraycopy(nibblearray.data, 0, abyte, j, nibblearray.data.length); 243 | j += nibblearray.data.length; 244 | } 245 | } 246 | } 247 | 248 | if (includeinit) { 249 | byte[] abyte2 = chunk.getBiomeArray(); 250 | System.arraycopy(abyte2, 0, abyte, j, abyte2.length); 251 | j += abyte2.length; 252 | } 253 | 254 | extracted.field_150282_a = new byte[j]; 255 | System.arraycopy(abyte, 0, extracted.field_150282_a, 0, j); 256 | return extracted; 257 | } 258 | } 259 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/network/packet/PacketCloseView.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.network.packet; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import net.minecraft.entity.player.EntityPlayer; 5 | 6 | import com.xcompwiz.lookingglass.client.proxyworld.WorldView; 7 | import com.xcompwiz.lookingglass.proxyworld.ModConfigs; 8 | 9 | import cpw.mods.fml.common.network.internal.FMLProxyPacket; 10 | import cpw.mods.fml.relauncher.Side; 11 | import cpw.mods.fml.relauncher.SideOnly; 12 | 13 | public class PacketCloseView extends PacketHandlerBase { 14 | @SideOnly(Side.CLIENT) 15 | public static FMLProxyPacket createPacket(WorldView worldview) { 16 | // This line may look like black magic (and, well, it is), but it's actually just returning a class reference for this class. Copy-paste safe. 17 | ByteBuf data = PacketHandlerBase.createDataBuffer((Class) new Object() {}.getClass().getEnclosingClass()); 18 | 19 | return buildPacket(data); 20 | } 21 | 22 | @Override 23 | public void handle(ByteBuf data, EntityPlayer player) { 24 | if (ModConfigs.disabled) return; 25 | 26 | //TODO: make closing viewpoint aware. See PacketCreateView 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/network/packet/PacketCreateView.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.network.packet; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import net.minecraft.client.Minecraft; 5 | import net.minecraft.entity.player.EntityPlayer; 6 | import net.minecraft.entity.player.EntityPlayerMP; 7 | import net.minecraft.server.MinecraftServer; 8 | import net.minecraft.util.ChunkCoordinates; 9 | import net.minecraft.world.WorldServer; 10 | import net.minecraftforge.common.DimensionManager; 11 | 12 | import com.xcompwiz.lookingglass.api.event.ClientWorldInfoEvent; 13 | import com.xcompwiz.lookingglass.client.proxyworld.WorldView; 14 | import com.xcompwiz.lookingglass.network.LookingGlassPacketManager; 15 | import com.xcompwiz.lookingglass.proxyworld.ChunkFinder; 16 | import com.xcompwiz.lookingglass.proxyworld.ChunkFinderManager; 17 | import com.xcompwiz.lookingglass.proxyworld.ModConfigs; 18 | 19 | import cpw.mods.fml.common.network.internal.FMLProxyPacket; 20 | import cpw.mods.fml.relauncher.Side; 21 | import cpw.mods.fml.relauncher.SideOnly; 22 | 23 | public class PacketCreateView extends PacketHandlerBase { 24 | @SideOnly(Side.CLIENT) 25 | public static FMLProxyPacket createPacket(WorldView worldview) { 26 | // This line may look like black magic (and, well, it is), but it's actually just returning a class reference for this class. Copy-paste safe. 27 | ByteBuf data = PacketHandlerBase.createDataBuffer((Class) new Object() {}.getClass().getEnclosingClass()); 28 | 29 | int x = 0; 30 | int y = -1; 31 | int z = 0; 32 | if (worldview.coords != null) { 33 | x = worldview.coords.posX >> 4; 34 | y = worldview.coords.posY >> 4; 35 | z = worldview.coords.posZ >> 4; 36 | } 37 | 38 | data.writeInt(worldview.getWorldObj().provider.dimensionId); 39 | data.writeInt(x); 40 | data.writeInt(y); 41 | data.writeInt(z); 42 | data.writeByte(Math.min(ModConfigs.renderDistance, Minecraft.getMinecraft().gameSettings.renderDistanceChunks)); 43 | 44 | return buildPacket(data); 45 | } 46 | 47 | @Override 48 | public void handle(ByteBuf data, EntityPlayer player) { 49 | if (ModConfigs.disabled) return; 50 | int dim = data.readInt(); 51 | int xPos = data.readInt(); 52 | int yPos = data.readInt(); 53 | int zPos = data.readInt(); 54 | byte renderDistance = data.readByte(); 55 | 56 | if (!DimensionManager.isDimensionRegistered(dim)) return; 57 | WorldServer world = MinecraftServer.getServer().worldServerForDimension(dim); 58 | if (world == null) return; 59 | int x; 60 | int y; 61 | int z; 62 | if (yPos < 0) { 63 | ChunkCoordinates c = world.getSpawnPoint(); 64 | x = c.posX >> 4; 65 | y = c.posY >> 4; 66 | z = c.posZ >> 4; 67 | } else { 68 | x = xPos; 69 | y = yPos; 70 | z = zPos; 71 | } 72 | if (renderDistance > ModConfigs.renderDistance) renderDistance = ModConfigs.renderDistance; 73 | ChunkFinderManager.instance.addFinder(new ChunkFinder(new ChunkCoordinates(x, y, z), dim, world.getChunkProvider(), player, renderDistance)); 74 | //TODO: Add to tracking list. Send time/data updates at intervals. Keep in mind to catch player disconnects when tracking clients. 75 | //Register ChunkFinder, and support change of finder location. 76 | //TODO: This is a repeat of the handling of PacketRequestWorldInfo 77 | net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new ClientWorldInfoEvent(dim, (EntityPlayerMP) player)); 78 | LookingGlassPacketManager.bus.sendTo(PacketWorldInfo.createPacket(dim), (EntityPlayerMP) player); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/network/packet/PacketHandlerBase.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.network.packet; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import net.minecraft.entity.player.EntityPlayer; 6 | 7 | import com.xcompwiz.lookingglass.network.LookingGlassPacketManager; 8 | 9 | import cpw.mods.fml.common.network.internal.FMLProxyPacket; 10 | 11 | /** 12 | * This class is the parent of the packet handling classes for our network communication. Mostly contains helper functions. 13 | */ 14 | public abstract class PacketHandlerBase { 15 | 16 | /** 17 | * Called by our packet manager to process packet data 18 | */ 19 | public abstract void handle(ByteBuf data, EntityPlayer player); 20 | 21 | /** 22 | * Used by the progeny of this class in order to produce and prepare the buffer for packet data. Includes writing the correct packet id for the packet. 23 | */ 24 | public static ByteBuf createDataBuffer(Class handlerclass) { 25 | ByteBuf data = Unpooled.buffer(); 26 | data.writeByte(LookingGlassPacketManager.getId(handlerclass)); 27 | return data; 28 | } 29 | 30 | /** 31 | * Used by the progeny of this class in order to produce a packet object from the data buffer. Automatically uses our packet channel so that the manager on 32 | * the other side will receive the packet. 33 | */ 34 | protected static FMLProxyPacket buildPacket(ByteBuf payload) { 35 | return new FMLProxyPacket(payload, LookingGlassPacketManager.CHANNEL); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/network/packet/PacketRequestChunk.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.network.packet; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import net.minecraft.entity.player.EntityPlayer; 5 | import net.minecraft.server.MinecraftServer; 6 | import net.minecraft.world.WorldServer; 7 | import net.minecraft.world.chunk.Chunk; 8 | import net.minecraftforge.common.DimensionManager; 9 | 10 | import com.xcompwiz.lookingglass.network.ServerPacketDispatcher; 11 | import com.xcompwiz.lookingglass.proxyworld.ModConfigs; 12 | 13 | import cpw.mods.fml.common.network.internal.FMLProxyPacket; 14 | 15 | public class PacketRequestChunk extends PacketHandlerBase { 16 | public static FMLProxyPacket createPacket(int xPos, int yPos, int zPos, int dim) { 17 | // This line may look like black magic (and, well, it is), but it's actually just returning a class reference for this class. Copy-paste safe. 18 | ByteBuf data = PacketHandlerBase.createDataBuffer((Class) new Object() {}.getClass().getEnclosingClass()); 19 | 20 | data.writeInt(dim); 21 | data.writeInt(xPos); 22 | data.writeInt(yPos); 23 | data.writeInt(zPos); 24 | 25 | return buildPacket(data); 26 | } 27 | 28 | @Override 29 | public void handle(ByteBuf data, EntityPlayer player) { 30 | if (ModConfigs.disabled) return; 31 | int dim = data.readInt(); 32 | int xPos = data.readInt(); 33 | int yPos = data.readInt(); 34 | int zPos = data.readInt(); 35 | 36 | if (!DimensionManager.isDimensionRegistered(dim)) return; 37 | WorldServer world = MinecraftServer.getServer().worldServerForDimension(dim); 38 | if (world == null) return; 39 | Chunk chunk = world.getChunkFromChunkCoords(xPos, zPos); 40 | if (!chunk.isChunkLoaded) chunk = world.getChunkProvider().loadChunk(xPos, zPos); 41 | ServerPacketDispatcher.getInstance().addPacket(player, PacketChunkInfo.createPacket(chunk, true, yPos, dim)); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/network/packet/PacketRequestTE.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.network.packet; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import net.minecraft.entity.player.EntityPlayer; 5 | import net.minecraft.nbt.NBTTagCompound; 6 | import net.minecraft.server.MinecraftServer; 7 | import net.minecraft.tileentity.TileEntity; 8 | import net.minecraft.world.WorldServer; 9 | import net.minecraftforge.common.DimensionManager; 10 | 11 | import com.xcompwiz.lookingglass.network.ServerPacketDispatcher; 12 | import com.xcompwiz.lookingglass.proxyworld.ModConfigs; 13 | 14 | import cpw.mods.fml.common.network.internal.FMLProxyPacket; 15 | 16 | public class PacketRequestTE extends PacketHandlerBase { 17 | public static FMLProxyPacket createPacket(int xPos, int yPos, int zPos, int dim) { 18 | // This line may look like black magic (and, well, it is), but it's actually just returning a class reference for this class. Copy-paste safe. 19 | ByteBuf data = PacketHandlerBase.createDataBuffer((Class) new Object() {}.getClass().getEnclosingClass()); 20 | 21 | data.writeInt(dim); 22 | data.writeInt(xPos); 23 | data.writeInt(yPos); 24 | data.writeInt(zPos); 25 | 26 | return buildPacket(data); 27 | } 28 | 29 | @Override 30 | public void handle(ByteBuf data, EntityPlayer player) { 31 | if (ModConfigs.disabled) return; 32 | int dim = data.readInt(); 33 | int xPos = data.readInt(); 34 | int yPos = data.readInt(); 35 | int zPos = data.readInt(); 36 | 37 | if (!DimensionManager.isDimensionRegistered(dim)) return; 38 | WorldServer world = MinecraftServer.getServer().worldServerForDimension(dim); 39 | if (world == null) return; 40 | TileEntity tile = world.getTileEntity(xPos, yPos, zPos); 41 | if (tile != null) { 42 | //FIXME: This is currently a very "forceful" method of doing this, and not technically guaranteed to produce correct results 43 | // This would be much better handled by using the getDescriptionPacket method and wrapping that packet in a LookingGlass 44 | // packet to control delivery timing, allowing for processing the packet while the correct target world is the active world 45 | // This idea requires that that system be in place, though, so until then this hack will hopefully hold. 46 | NBTTagCompound tag = new NBTTagCompound(); 47 | tile.writeToNBT(tag); 48 | ServerPacketDispatcher.getInstance().addPacket(player, PacketTileEntityNBT.createPacket(xPos, yPos, zPos, tag, dim)); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/network/packet/PacketRequestWorldInfo.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.network.packet; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import net.minecraft.entity.player.EntityPlayer; 5 | import net.minecraft.entity.player.EntityPlayerMP; 6 | import net.minecraftforge.common.DimensionManager; 7 | 8 | import com.xcompwiz.lookingglass.api.event.ClientWorldInfoEvent; 9 | import com.xcompwiz.lookingglass.network.LookingGlassPacketManager; 10 | import com.xcompwiz.lookingglass.proxyworld.ModConfigs; 11 | 12 | import cpw.mods.fml.common.network.internal.FMLProxyPacket; 13 | import cpw.mods.fml.relauncher.Side; 14 | import cpw.mods.fml.relauncher.SideOnly; 15 | 16 | public class PacketRequestWorldInfo extends PacketHandlerBase { 17 | @SideOnly(Side.CLIENT) 18 | public static FMLProxyPacket createPacket(int xPos, int yPos, int zPos, int dim) { 19 | // This line may look like black magic (and, well, it is), but it's actually just returning a class reference for this class. Copy-paste safe. 20 | ByteBuf data = PacketHandlerBase.createDataBuffer((Class) new Object() {}.getClass().getEnclosingClass()); 21 | 22 | data.writeInt(dim); 23 | 24 | return buildPacket(data); 25 | } 26 | 27 | @Override 28 | public void handle(ByteBuf data, EntityPlayer player) { 29 | if (ModConfigs.disabled) return; 30 | int dim = data.readInt(); 31 | 32 | if (!DimensionManager.isDimensionRegistered(dim)) return; 33 | net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new ClientWorldInfoEvent(dim, (EntityPlayerMP) player)); 34 | LookingGlassPacketManager.bus.sendTo(PacketWorldInfo.createPacket(dim), (EntityPlayerMP) player); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/network/packet/PacketTileEntityNBT.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.network.packet; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import net.minecraft.client.multiplayer.WorldClient; 5 | import net.minecraft.entity.player.EntityPlayer; 6 | import net.minecraft.nbt.NBTTagCompound; 7 | import net.minecraft.tileentity.TileEntity; 8 | 9 | import com.xcompwiz.lookingglass.client.proxyworld.ProxyWorldManager; 10 | 11 | import cpw.mods.fml.common.network.ByteBufUtils; 12 | import cpw.mods.fml.common.network.internal.FMLProxyPacket; 13 | 14 | /** 15 | * Based on code from Ken Butler/shadowking97 16 | */ 17 | public class PacketTileEntityNBT extends PacketHandlerBase { 18 | 19 | public static FMLProxyPacket createPacket(int xPos, int yPos, int zPos, NBTTagCompound nbt, int dim) { 20 | // This line may look like black magic (and, well, it is), but it's actually just returning a class reference for this class. Copy-paste safe. 21 | ByteBuf data = PacketHandlerBase.createDataBuffer((Class) new Object() {}.getClass().getEnclosingClass()); 22 | 23 | data.writeInt(dim); 24 | data.writeInt(xPos); 25 | data.writeInt(yPos); 26 | data.writeInt(zPos); 27 | ByteBufUtils.writeTag(data, nbt); 28 | 29 | return buildPacket(data); 30 | } 31 | 32 | @Override 33 | public void handle(ByteBuf data, EntityPlayer player) { 34 | int dimension = data.readInt(); 35 | int xPos = data.readInt(); 36 | int yPos = data.readInt(); 37 | int zPos = data.readInt(); 38 | NBTTagCompound nbt = ByteBufUtils.readTag(data); 39 | 40 | WorldClient proxyworld = ProxyWorldManager.getProxyworld(dimension); 41 | if (proxyworld == null) return; 42 | if (proxyworld.provider.dimensionId != dimension) return; 43 | if (proxyworld.blockExists(xPos, yPos, zPos)) { 44 | TileEntity tileentity = proxyworld.getTileEntity(xPos, yPos, zPos); 45 | 46 | if (tileentity != null) { 47 | tileentity.readFromNBT(nbt); 48 | } else { 49 | //Create tile entity from data 50 | tileentity = TileEntity.createAndLoadEntity(nbt); 51 | if (tileentity != null) { 52 | proxyworld.addTileEntity(tileentity); 53 | } 54 | } 55 | proxyworld.markTileEntityChunkModified(xPos, yPos, zPos, tileentity); 56 | proxyworld.setTileEntity(xPos, yPos, zPos, tileentity); 57 | proxyworld.markBlockForUpdate(xPos, yPos, zPos); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/network/packet/PacketWorldInfo.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.network.packet; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | 5 | import java.util.Collection; 6 | 7 | import net.minecraft.client.multiplayer.WorldClient; 8 | import net.minecraft.entity.player.EntityPlayer; 9 | import net.minecraft.server.MinecraftServer; 10 | import net.minecraft.util.ChunkCoordinates; 11 | import net.minecraft.world.WorldServer; 12 | 13 | import com.xcompwiz.lookingglass.client.proxyworld.ProxyWorldManager; 14 | import com.xcompwiz.lookingglass.client.proxyworld.WorldView; 15 | import com.xcompwiz.lookingglass.log.LoggerUtils; 16 | 17 | import cpw.mods.fml.common.network.internal.FMLProxyPacket; 18 | 19 | /** 20 | * Based on code from Ken Butler/shadowking97 21 | */ 22 | public class PacketWorldInfo extends PacketHandlerBase { 23 | 24 | public static FMLProxyPacket createPacket(int dimension) { 25 | WorldServer world = MinecraftServer.getServer().worldServerForDimension(dimension); 26 | if (world == null) { 27 | LoggerUtils.warn("Server-side world for dimension %i is null!", dimension); 28 | return null; 29 | } 30 | ChunkCoordinates cc = world.provider.getSpawnPoint(); 31 | int posX = cc.posX; 32 | int posY = cc.posY; 33 | int posZ = cc.posZ; 34 | int skylightSubtracted = world.skylightSubtracted; 35 | float thunderingStrength = world.thunderingStrength; 36 | float rainingStrength = world.rainingStrength; 37 | long worldTime = world.provider.getWorldTime(); 38 | 39 | // This line may look like black magic (and, well, it is), but it's actually just returning a class reference for this class. Copy-paste safe. 40 | ByteBuf data = PacketHandlerBase.createDataBuffer((Class) new Object() {}.getClass().getEnclosingClass()); 41 | 42 | data.writeInt(dimension); 43 | data.writeInt(posX); 44 | data.writeInt(posY); 45 | data.writeInt(posZ); 46 | data.writeInt(skylightSubtracted); 47 | data.writeFloat(thunderingStrength); 48 | data.writeFloat(rainingStrength); 49 | data.writeLong(worldTime); 50 | 51 | return buildPacket(data); 52 | } 53 | 54 | @Override 55 | public void handle(ByteBuf in, EntityPlayer player) { 56 | int dimension = in.readInt(); 57 | int posX = in.readInt(); 58 | int posY = in.readInt(); 59 | int posZ = in.readInt(); 60 | int skylightSubtracted = in.readInt(); 61 | float thunderingStrength = in.readFloat(); 62 | float rainingStrength = in.readFloat(); 63 | long worldTime = in.readLong(); 64 | 65 | WorldClient proxyworld = ProxyWorldManager.getProxyworld(dimension); 66 | 67 | if (proxyworld == null) return; 68 | if (proxyworld.provider.dimensionId != dimension) return; 69 | 70 | ChunkCoordinates cc = new ChunkCoordinates(); 71 | cc.set(posX, posY, posZ); 72 | Collection views = ProxyWorldManager.getWorldViews(dimension); 73 | for (WorldView view : views) { 74 | view.updateWorldSpawn(cc); 75 | } 76 | proxyworld.setSpawnLocation(posX, posY, posZ); 77 | proxyworld.skylightSubtracted = skylightSubtracted; 78 | proxyworld.thunderingStrength = thunderingStrength; 79 | proxyworld.setRainStrength(rainingStrength); 80 | proxyworld.setWorldTime(worldTime); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/proxyworld/ChunkFinder.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.proxyworld; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | import net.minecraft.block.Block; 7 | import net.minecraft.entity.player.EntityPlayer; 8 | import net.minecraft.util.ChunkCoordinates; 9 | import net.minecraft.world.chunk.Chunk; 10 | import net.minecraft.world.chunk.IChunkProvider; 11 | 12 | import com.xcompwiz.lookingglass.log.LoggerUtils; 13 | import com.xcompwiz.lookingglass.network.ServerPacketDispatcher; 14 | import com.xcompwiz.lookingglass.network.packet.PacketChunkInfo; 15 | 16 | /** 17 | * Finds 16x16x16 chunks exposed to the passed chunk location. 18 | * @author Ken Butler/shadowking97 19 | */ 20 | public class ChunkFinder { 21 | 22 | private final IChunkProvider chunkProvider; 23 | private final int rootX; 24 | private final int rootZ; 25 | private final int range; 26 | private final int dimension; 27 | private final EntityPlayer player; 28 | private ChunkData[][] map; 29 | private List cc; 30 | private final int d; 31 | private int step; 32 | private int stepRange; 33 | private long startTime; 34 | 35 | /** 36 | * Finds exposed chunks. Chunks must be loaded. 37 | * @param root The chunk in chunk coordinates. 38 | * @param dimension The target dimension 39 | * @param chunkProvider The world server that contains the chunks 40 | * @param player The player to send the chunks to 41 | * @param range The radius of the chunkfinder. 42 | * @return Sorted Chunk Data, by range. Prioritizes closest chunks. 43 | */ 44 | public ChunkFinder(ChunkCoordinates root, int dimension, IChunkProvider chunkProvider, EntityPlayer player, int range) { 45 | this.chunkProvider = chunkProvider; 46 | this.range = range; 47 | this.dimension = dimension; 48 | this.player = player; 49 | this.d = (range << 1) + 1; 50 | this.map = new ChunkData[d][d]; 51 | this.rootX = root.posX - range; 52 | this.rootZ = root.posZ - range; 53 | this.stepRange = 16 - root.posY; 54 | if (root.posY > stepRange) stepRange = root.posY; 55 | startTime = System.nanoTime(); 56 | LoggerUtils.debug("ChunkFinder scan started at nano: " + startTime); 57 | for (int i = 0; i < d; i++) { 58 | for (int j = 0; j < d; j++) { 59 | map[i][j] = new ChunkData(i + rootX, j + rootZ); 60 | int x1 = i - range; 61 | int z1 = j - range; 62 | map[i][j].distance = x1 * x1 + z1 * z1; 63 | } 64 | } 65 | cc = new LinkedList(); 66 | cc.add(new ChunkCoordinates(range, root.posY, range)); 67 | step = 0; 68 | List cc2 = new LinkedList(); 69 | while (step - 1 < stepRange && !cc.isEmpty()) { 70 | while (!cc.isEmpty()) { 71 | cc2.addAll(scan(chunkProvider, map, cc.get(0), range)); 72 | cc.remove(0); 73 | } 74 | step++; 75 | cc.addAll(cc2); 76 | cc2.clear(); 77 | if (step >= stepRange) { 78 | int range2 = step - stepRange + 1; 79 | range2 *= range2; 80 | int range3 = step - stepRange; 81 | if (range3 < 0) range3 = 0; 82 | range3 *= range3; 83 | int minStep = range - (step - stepRange); 84 | int maxStep = range + (step - stepRange) + 1; 85 | if (minStep < 0) minStep = 0; 86 | if (maxStep > d) maxStep = d; 87 | for (int i = minStep; i < maxStep; i++) { 88 | for (int j = minStep; j < maxStep; j++) { 89 | int dist = map[i][j].distance; 90 | if (map[i][j].doAdd() && dist < range2 && dist >= range3) { 91 | ChunkData data = map[i][j]; 92 | Chunk c2 = chunkProvider.provideChunk(data.x, data.z); 93 | if (!c2.isChunkLoaded) c2 = chunkProvider.loadChunk(data.x, data.z); 94 | 95 | ServerPacketDispatcher.getInstance().addPacket(player, PacketChunkInfo.createPacket(c2, true, data.levels(), dimension)); 96 | } 97 | } 98 | } 99 | } 100 | } 101 | } 102 | 103 | public boolean findChunks() { 104 | if (!cc.isEmpty()) { 105 | int tick = 0; 106 | List cc2 = new LinkedList(); 107 | while (!cc.isEmpty() && tick < 15) { 108 | ChunkCoordinates ch = cc.get(0); 109 | cc2.addAll(scan(chunkProvider, map, ch, range)); 110 | cc.remove(0); 111 | ++tick; 112 | } 113 | if (!cc.isEmpty()) return false; 114 | 115 | step++; 116 | 117 | cc.addAll(cc2); 118 | cc2.clear(); 119 | 120 | if (step >= stepRange) { 121 | int range2 = step - stepRange + 1; 122 | range2 *= range2; 123 | int range3 = step - stepRange; 124 | if (range3 < 0) range3 = 0; 125 | range3 *= range3; 126 | int minStep = range - (step - stepRange); 127 | int maxStep = range + (step - stepRange) + 1; 128 | if (minStep < 0) minStep = 0; 129 | if (maxStep > d) maxStep = d; 130 | for (int i = minStep; i < maxStep; i++) { 131 | for (int j = minStep; j < maxStep; j++) { 132 | int dist = map[i][j].distance; 133 | if (map[i][j].doAdd() && dist < range2 && dist >= range3) { 134 | ChunkData data = map[i][j]; 135 | Chunk c2 = chunkProvider.provideChunk(data.x, data.z); 136 | if (!c2.isChunkLoaded) c2 = chunkProvider.loadChunk(data.x, data.z); 137 | ServerPacketDispatcher.getInstance().addPacket(player, PacketChunkInfo.createPacket(c2, true, data.levels(), dimension)); 138 | } 139 | } 140 | } 141 | } 142 | return false; 143 | } 144 | 145 | if (step >= stepRange) { 146 | int range2 = step - stepRange; 147 | range2 *= range2; 148 | for (int i = 0; i < d; i++) { 149 | for (int j = 0; j < d; j++) { 150 | int dist = map[i][j].distance; 151 | if (map[i][j].doAdd() && dist >= range2) { 152 | ChunkData data = map[i][j]; 153 | Chunk c2 = chunkProvider.provideChunk(data.x, data.z); 154 | if (!c2.isChunkLoaded) c2 = chunkProvider.loadChunk(data.x, data.z); 155 | ServerPacketDispatcher.getInstance().addPacket(player, PacketChunkInfo.createPacket(c2, true, data.levels(), dimension)); 156 | } 157 | } 158 | } 159 | } 160 | LoggerUtils.debug("Scan finished. nanoseconds: " + (System.nanoTime() - startTime)); 161 | return true; 162 | } 163 | 164 | /** 165 | * Recursive function to find all chunk segments attached to the surface. 166 | */ 167 | private static List scan(IChunkProvider chunkProvider, ChunkData[][] map, ChunkCoordinates coord, int range) { 168 | int rangeSqr = range * range; 169 | List cc3 = new LinkedList(); 170 | int x = coord.posX; 171 | int y = coord.posY; 172 | int z = coord.posZ; 173 | ChunkData data = map[x][z]; 174 | if (data.isAdded(y) || data.distance > rangeSqr) return cc3; 175 | data.add(y); 176 | Chunk c = chunkProvider.provideChunk(data.x, data.z); 177 | if (!c.isChunkLoaded) { 178 | c = chunkProvider.loadChunk(data.x, data.z); 179 | } 180 | if (c.getAreLevelsEmpty(y << 4, (y << 4) + 15)) { 181 | data.empty(y); 182 | if (x < (range << 1) && !(map[x + 1][z].isAdded(y) || map[x + 1][z].distance > rangeSqr || map[x + 1][z].distance < map[x][z].distance)) cc3.add(new ChunkCoordinates(x + 1, y, z)); 183 | if (x > 0 && !(map[x - 1][z].isAdded(y) || map[x - 1][z].distance > rangeSqr || map[x - 1][z].distance < map[x][z].distance)) cc3.add(new ChunkCoordinates(x - 1, y, z)); 184 | if (y < 15 && !(map[x][z].isAdded(y + 1) || map[x][z].distance > rangeSqr)) cc3.add(new ChunkCoordinates(x, y + 1, z)); 185 | if (y > 0 && !(map[x][z].isAdded(y - 1) || map[x][z].distance > rangeSqr)) cc3.add(new ChunkCoordinates(x, y - 1, z)); 186 | ; 187 | if (z < (range << 1) && !(map[x][z + 1].isAdded(y) || map[x][z + 1].distance > rangeSqr || map[x][z + 1].distance < map[x][z].distance)) cc3.add(new ChunkCoordinates(x, y, z + 1)); 188 | if (z > 0 && !(map[x][z - 1].isAdded(y) || map[x][z - 1].distance > rangeSqr || map[x][z - 1].distance < map[x][z].distance)) cc3.add(new ChunkCoordinates(x, y, z - 1)); 189 | } else { 190 | boolean ok = false; 191 | if (z > 0 && !(map[x][z - 1].isAdded(y) || map[x][z - 1].distance > rangeSqr || map[x][z - 1].distance < map[x][z].distance)) { 192 | for (int i = 0; i < 16 && !ok; i++) { 193 | for (int l = 0; l < 16 && !ok; l++) { 194 | if (!isBlockNormalCubeDefault(c, l, (y << 4) + i, 0, false)) ok = true; 195 | } 196 | } 197 | if (ok) { 198 | cc3.add(new ChunkCoordinates(x, y, z - 1)); 199 | } 200 | ok = false; 201 | } 202 | if (z < (range << 1) && !(map[x][z + 1].isAdded(y) || map[x][z + 1].distance > rangeSqr || map[x][z + 1].distance < map[x][z].distance)) { 203 | for (int i = 0; i < 16 && !ok; i++) { 204 | for (int l = 0; l < 16 && !ok; l++) { 205 | if (!isBlockNormalCubeDefault(c, l, (y << 4) + i, 15, false)) ok = true; 206 | } 207 | } 208 | if (ok) { 209 | cc3.add(new ChunkCoordinates(x, y, z + 1)); 210 | } 211 | ok = false; 212 | } 213 | if (y > 0 && !(map[x][z].isAdded(y - 1) || map[x][z].distance > rangeSqr)) { 214 | for (int i = 0; i < 16 && !ok; i++) { 215 | for (int l = 0; l < 16 && !ok; l++) { 216 | if (!isBlockNormalCubeDefault(c, l, (y << 4), i, false)) ok = true; 217 | } 218 | } 219 | if (ok) { 220 | cc3.add(new ChunkCoordinates(x, y - 1, z)); 221 | } 222 | ok = false; 223 | } 224 | if (y < 15 && !(map[x][z].isAdded(y + 1) || map[x][z].distance > rangeSqr)) { 225 | for (int i = 0; i < 16 && !ok; i++) { 226 | for (int l = 0; l < 16 && !ok; l++) { 227 | if (!isBlockNormalCubeDefault(c, l, (y << 4) + 15, i, false)) ok = true; 228 | } 229 | } 230 | if (ok) { 231 | cc3.add(new ChunkCoordinates(x, y + 1, z)); 232 | } 233 | ok = false; 234 | } 235 | if (x > 0 && !(map[x - 1][z].isAdded(y) || map[x - 1][z].distance > rangeSqr || map[x - 1][z].distance < map[x][z].distance)) { 236 | for (int i = 0; i < 16 && !ok; i++) { 237 | for (int l = 0; l < 16 && !ok; l++) { 238 | if (!isBlockNormalCubeDefault(c, 0, (y << 4) + l, i, false)) ok = true; 239 | } 240 | } 241 | if (ok) { 242 | cc3.add(new ChunkCoordinates(x - 1, y, z)); 243 | } 244 | ok = false; 245 | } 246 | if (x < (range << 1) && !(map[x + 1][z].isAdded(y) || map[x + 1][z].distance > rangeSqr || map[x + 1][z].distance < map[x][z].distance)) { 247 | for (int i = 0; i < 16 && !ok; i++) { 248 | for (int l = 0; l < 16 && !ok; l++) { 249 | if (!isBlockNormalCubeDefault(c, 15, (y << 4) + l, i, false)) ok = true; 250 | } 251 | } 252 | if (ok) { 253 | cc3.add(new ChunkCoordinates(x + 1, y, z)); 254 | } 255 | } 256 | } 257 | return cc3; 258 | } 259 | 260 | public static boolean isBlockNormalCubeDefault(Chunk chunk, int par1, int par2, int par3, boolean par4) { 261 | if (par1 >= -30000000 && par3 >= -30000000 && par1 < 30000000 && par3 < 30000000) { 262 | if (chunk != null && !chunk.isEmpty()) { 263 | Block block = chunk.getBlock(par1 & 15, par2, par3 & 15); 264 | return block.isNormalCube(); 265 | } 266 | } 267 | return par4; 268 | } 269 | 270 | public class ChunkData implements Comparable { 271 | public int x; 272 | public int z; 273 | public int added; 274 | public int empty; 275 | public int distance; 276 | 277 | public ChunkData(int x, int z) { 278 | this.x = x; 279 | this.z = z; 280 | added = 0; 281 | } 282 | 283 | public boolean isAdded(int level) { 284 | return (added & (1 << level)) != 0; 285 | } 286 | 287 | public boolean doAdd() { 288 | return (added ^ empty) != 0; 289 | } 290 | 291 | public boolean doAdd(int level) { 292 | return isAdded(level) && !isEmpty(level); 293 | } 294 | 295 | public void add(int level) { 296 | added |= 1 << level; 297 | } 298 | 299 | public boolean isEmpty(int level) { 300 | return (empty & (1 << level)) == 0; 301 | } 302 | 303 | public void empty(int level) { 304 | empty |= 1 << level; 305 | } 306 | 307 | public int levels() { 308 | return added ^ empty; 309 | } 310 | 311 | @Override 312 | public int compareTo(ChunkData arg0) { 313 | 314 | return this.distance - arg0.distance; 315 | } 316 | } 317 | } 318 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/proxyworld/ChunkFinderManager.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.proxyworld; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | /** 7 | * @author Ken Butler/shadowking97 8 | */ 9 | public class ChunkFinderManager { 10 | public static ChunkFinderManager instance = new ChunkFinderManager(); 11 | 12 | private List finders; 13 | 14 | public ChunkFinderManager() { 15 | finders = new LinkedList(); 16 | } 17 | 18 | public void addFinder(ChunkFinder f) { 19 | finders.add(f); 20 | } 21 | 22 | public void tick() { 23 | for (int i = 0; i < finders.size(); ++i) { 24 | if (finders.get(i).findChunks()) { 25 | finders.remove(i); 26 | --i; 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/proxyworld/LookingGlassEventHandler.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.proxyworld; 2 | 3 | import java.io.File; 4 | import java.io.FileNotFoundException; 5 | import java.io.PrintStream; 6 | 7 | import net.minecraft.client.Minecraft; 8 | import net.minecraft.client.multiplayer.WorldClient; 9 | 10 | import com.xcompwiz.lookingglass.client.proxyworld.ProxyWorldManager; 11 | import com.xcompwiz.lookingglass.log.LoggerUtils; 12 | import com.xcompwiz.lookingglass.render.PerspectiveRenderManager; 13 | import com.xcompwiz.lookingglass.render.WorldViewRenderManager; 14 | 15 | import cpw.mods.fml.common.eventhandler.SubscribeEvent; 16 | import cpw.mods.fml.common.gameevent.TickEvent; 17 | import cpw.mods.fml.common.network.FMLNetworkEvent.ClientDisconnectionFromServerEvent; 18 | import cpw.mods.fml.relauncher.Side; 19 | import cpw.mods.fml.relauncher.SideOnly; 20 | 21 | /** 22 | * This class handles the FML events. Primarily it is used to listen for tick events. 23 | */ 24 | public class LookingGlassEventHandler { 25 | 26 | /** An output stream we can use for proxy world logging */ 27 | private final PrintStream printstream; 28 | 29 | /** The client world as we last saw it. We use this to check if the client has changed worlds */ 30 | @SideOnly(Side.CLIENT) 31 | private WorldClient previousWorld; 32 | 33 | /** A simple accumulator to handle triggering freeing world views and such */ 34 | @SideOnly(Side.CLIENT) 35 | private int tickcounter; 36 | 37 | public LookingGlassEventHandler(File logfile) { 38 | PrintStream stream = null; 39 | try { 40 | stream = new PrintStream(logfile); 41 | } catch (FileNotFoundException e) { 42 | e.printStackTrace(); 43 | } finally { 44 | printstream = stream; 45 | } 46 | if (printstream == null) throw new RuntimeException("Could not set up debug exception logger file for Proxy World system"); 47 | } 48 | 49 | @SideOnly(Side.CLIENT) 50 | @SubscribeEvent 51 | public void onClientTick(TickEvent.ClientTickEvent event) { 52 | Minecraft mc = Minecraft.getMinecraft(); 53 | // If no client world we're not playing. Abort. 54 | if (mc.theWorld == null) return; 55 | // We don't want to tick twice per tick loop. Just once. We chose to tick at the start of the tick loop. 56 | if (event.phase != TickEvent.Phase.START) return; 57 | 58 | // Every now and then we want to check to see if there are frame buffers we could free 59 | if (++this.tickcounter % 200 == 0) ProxyWorldManager.detectFreedWorldViews(); 60 | 61 | // Handle whenever the client world has changed since we last looked 62 | if (mc.theWorld != previousWorld) { 63 | // We need to handle the removal of the old world. Particularly, the player will still be visible in it. 64 | // We may consider replacing the old client world with a new proxy world. 65 | if (previousWorld != null) previousWorld.removeAllEntities(); //TODO: This is hardly an ideal solution (It also doesn't seem to work well) 66 | previousWorld = mc.theWorld; // At this point we can safely assert that the client world has changed 67 | 68 | // We let our local world manager know that the client world changed. 69 | ProxyWorldManager.handleWorldChange(mc.theWorld); 70 | } 71 | 72 | // Tick loop for our own worlds. 73 | WorldClient worldBackup = mc.theWorld; 74 | for (WorldClient proxyworld : ProxyWorldManager.getProxyworlds()) { 75 | if (proxyworld.lastLightningBolt > 0) --proxyworld.lastLightningBolt; 76 | if (worldBackup == proxyworld) continue; // This prevents us from double ticking the client world. 77 | try { 78 | mc.theWorld = proxyworld; 79 | //TODO: relays for views (renderGlobal and effectRenderer) (See ProxyWorld.makeFireworks ln23) 80 | proxyworld.tick(); 81 | } catch (Exception e) { 82 | LoggerUtils.error("Client Proxy Dim had error while ticking: %s", e.getLocalizedMessage()); 83 | e.printStackTrace(printstream); 84 | } 85 | } 86 | mc.theWorld = worldBackup; 87 | } 88 | 89 | @SideOnly(Side.CLIENT) 90 | @SubscribeEvent 91 | public void onRenderTick(TickEvent.RenderTickEvent event) { 92 | // If no client world we're not playing. Abort. 93 | if (Minecraft.getMinecraft().theWorld == null) return; 94 | if (event.phase == TickEvent.Phase.START) { 95 | // Anything we need to render for the current frame should happen either during or before the main world render 96 | // Here we call the renderer for "live portal" renders. 97 | PerspectiveRenderManager.onRenderTick(printstream); 98 | return; 99 | } 100 | if (event.phase == TickEvent.Phase.END) { 101 | // We render the world views at the end of the render tick. 102 | WorldViewRenderManager.onRenderTick(printstream); 103 | return; 104 | } 105 | } 106 | 107 | @SubscribeEvent 108 | public void onServerTick(TickEvent.ServerTickEvent event) { 109 | if (event.phase != TickEvent.Phase.END) return; 110 | // On server ticks we try to send clients who need chunk data some of that data they need 111 | ChunkFinderManager.instance.tick(); 112 | } 113 | 114 | @SubscribeEvent 115 | public void onClientDisconnect(ClientDisconnectionFromServerEvent event) { 116 | // Abandon ship! 117 | ProxyWorldManager.clearProxyworlds(); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/proxyworld/ModConfigs.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.proxyworld; 2 | 3 | import net.minecraftforge.common.config.Configuration; 4 | import net.minecraftforge.common.config.Property; 5 | 6 | public class ModConfigs { 7 | private static final String CATAGORY_SERVER = "server"; 8 | 9 | public static boolean disabled = false; 10 | 11 | public static int dataRate = 2048; 12 | 13 | public static byte renderDistance = 7; 14 | 15 | public static void loadConfigs(Configuration config) { 16 | Property off = config.get(CATAGORY_SERVER, "disabled", disabled); 17 | off.comment = "On the client this disables other world renders entirely, preventing world requests. On the server this disables sending world info to all clients."; 18 | disabled = off.getBoolean(disabled); 19 | 20 | Property d = config.get(CATAGORY_SERVER, "datarate", dataRate); 21 | d.comment = "The number of bytes to send per tick before the server cuts off sending. Only applies to other-world chunks. Default: " + dataRate; 22 | dataRate = d.getInt(dataRate); 23 | 24 | if (dataRate <= 0) disabled = true; 25 | 26 | if (config.hasChanged()) config.save(); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/proxyworld/SubChunkUtils.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.proxyworld; 2 | 3 | import net.minecraft.util.ChunkCoordinates; 4 | 5 | public class SubChunkUtils { 6 | public static final boolean withinDistance(ChunkCoordinates c1, int x, int y, int z, int distance) { 7 | return distance * distance >= c1.getDistanceSquared(x, y, z); 8 | } 9 | 10 | public static final boolean withinDistance(int x, int y, int z, int x2, int y2, int z2, int distance) { 11 | int x3 = x - x2; 12 | int y3 = y - y2; 13 | int z3 = z - z2; 14 | return distance * distance >= x3 * x3 + y3 * y3 + z3 * z3; 15 | } 16 | 17 | public static final boolean withinRange(ChunkCoordinates c1, int x, int y, int z, int d1, int d2) { 18 | float cDistance = c1.getDistanceSquared(x, y, z); 19 | return d2 * d2 >= cDistance && d1 * d1 <= cDistance; 20 | } 21 | 22 | public static final boolean withinDistance2D(int x, int z, int x2, int z2, int distance) { 23 | int x3 = x - x2; 24 | int z3 = z - z2; 25 | int distance2 = x3 * x3 + z3 * z3; 26 | return distance * distance >= distance2; 27 | } 28 | 29 | public static final boolean withinRange2D(int x, int z, int x2, int z2, int d1, int d2) { 30 | int x3 = x - x2; 31 | int z3 = z - z2; 32 | int distance = x3 * x3 + z3 * z3; 33 | return d2 * d2 >= distance && d1 * d1 <= distance; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/render/PerspectiveRenderManager.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.render; 2 | 3 | import java.io.PrintStream; 4 | 5 | public class PerspectiveRenderManager { 6 | 7 | public static void onRenderTick(PrintStream printstream) { 8 | // TODO: OK, I lied. It doesn't do anything yet. 9 | // I've been testing this in another mod. 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/render/WorldViewRenderManager.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.render; 2 | 3 | import java.io.PrintStream; 4 | import java.util.Collection; 5 | 6 | import net.minecraft.client.Minecraft; 7 | import net.minecraft.client.entity.EntityClientPlayerMP; 8 | import net.minecraft.client.multiplayer.WorldClient; 9 | import net.minecraft.client.particle.EffectRenderer; 10 | import net.minecraft.client.renderer.RenderGlobal; 11 | import net.minecraft.client.renderer.entity.RenderManager; 12 | import net.minecraft.entity.EntityLivingBase; 13 | import net.minecraft.item.ItemStack; 14 | import net.minecraft.util.MathHelper; 15 | 16 | import com.xcompwiz.lookingglass.client.proxyworld.ProxyWorldManager; 17 | import com.xcompwiz.lookingglass.client.proxyworld.WorldView; 18 | import com.xcompwiz.lookingglass.client.render.RenderUtils; 19 | import com.xcompwiz.lookingglass.log.LoggerUtils; 20 | 21 | public class WorldViewRenderManager { 22 | public static void onRenderTick(PrintStream printstream) { 23 | Minecraft mc = Minecraft.getMinecraft(); 24 | Collection worlds = ProxyWorldManager.getProxyworlds(); 25 | if (worlds == null || worlds.isEmpty()) return; 26 | 27 | long renderT = Minecraft.getSystemTime(); 28 | //TODO: This and the renderWorldToTexture need to be remixed 29 | WorldClient worldBackup = mc.theWorld; 30 | RenderGlobal renderBackup = mc.renderGlobal; 31 | EffectRenderer effectBackup = mc.effectRenderer; 32 | EntityClientPlayerMP playerBackup = mc.thePlayer; 33 | EntityLivingBase viewportBackup = mc.renderViewEntity; 34 | 35 | //TODO: This is a hack to work around some of the vanilla rendering hacks... Yay hacks. 36 | float fovmult = playerBackup.getFOVMultiplier(); 37 | ItemStack currentClientItem = playerBackup.inventory.getCurrentItem(); 38 | 39 | for (WorldClient proxyworld : worlds) { 40 | if (proxyworld == null) continue; 41 | mc.theWorld = proxyworld; 42 | RenderManager.instance.set(mc.theWorld); 43 | for (WorldView activeview : ProxyWorldManager.getWorldViews(proxyworld.provider.dimensionId)) { 44 | if (activeview.hasChunks() && activeview.markClean()) { 45 | activeview.startRender(renderT); 46 | 47 | mc.renderGlobal = activeview.getRenderGlobal(); 48 | mc.effectRenderer = activeview.getEffectRenderer(); 49 | mc.renderViewEntity = activeview.camera; 50 | mc.thePlayer = activeview.camera; 51 | //Other half of hack 52 | activeview.camera.setFOVMult(fovmult); //Prevents the FOV from flickering 53 | activeview.camera.inventory.currentItem = playerBackup.inventory.currentItem; 54 | activeview.camera.inventory.mainInventory[playerBackup.inventory.currentItem] = currentClientItem; //Prevents the hand from flickering 55 | 56 | try { 57 | mc.renderGlobal.updateClouds(); 58 | mc.theWorld.doVoidFogParticles(MathHelper.floor_double(activeview.camera.posX), MathHelper.floor_double(activeview.camera.posY), MathHelper.floor_double(activeview.camera.posZ)); 59 | mc.effectRenderer.updateEffects(); 60 | } catch (Exception e) { 61 | LoggerUtils.error("Client Proxy Dim had error while updating render elements: %s", e.getLocalizedMessage()); 62 | e.printStackTrace(printstream); 63 | } 64 | 65 | try { 66 | RenderUtils.renderWorldToTexture(0.1f, activeview.getFramebuffer(), activeview.width, activeview.height); 67 | } catch (Exception e) { 68 | LoggerUtils.error("Client Proxy Dim had error while rendering: %s", e.getLocalizedMessage()); 69 | e.printStackTrace(printstream); 70 | } 71 | } 72 | } 73 | } 74 | mc.renderViewEntity = viewportBackup; 75 | mc.thePlayer = playerBackup; 76 | mc.effectRenderer = effectBackup; 77 | mc.renderGlobal = renderBackup; 78 | mc.theWorld = worldBackup; 79 | RenderManager.instance.set(mc.theWorld); 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/xcompwiz/lookingglass/utils/MathUtils.java: -------------------------------------------------------------------------------- 1 | package com.xcompwiz.lookingglass.utils; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import net.minecraft.util.Vec3; 5 | 6 | public class MathUtils { 7 | 8 | public static Vec3 readCoordinates(ByteBuf data) { 9 | Vec3 coords = Vec3.createVectorHelper(data.readDouble(), data.readDouble(), data.readDouble()); 10 | return coords; 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/resources/assets/lookingglass/lang/en_US.lang: -------------------------------------------------------------------------------- 1 | lookingglass.commands.generic.player.notfound=Could not get Player by name: %s 2 | -------------------------------------------------------------------------------- /src/main/resources/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XCompWiz/LookingGlass/70cb8ad8c2f5854635a58db8c9c443a62a50eb57/src/main/resources/logo.png -------------------------------------------------------------------------------- /src/main/resources/mcmod.info: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "modid": "LookingGlass", 4 | "name": "Looking Glass", 5 | "description": "\"In another moment Alice was through the glass, and had jumped lightly down into the Looking-glass room.\" - Through the Looking-Glass, and What Alice Found There; Lewis Carroll", 6 | "version": "${version}", 7 | "mcversion": "${mcversion}", 8 | "url": "http://xcompwiz.com", 9 | "updateUrl": "", 10 | "authorList": ["XCompWiz"], 11 | "credits": "shadowking97, for following the plan in my head", 12 | "logoFile": "/logo.png", 13 | "screenshots": [], 14 | "dependencies": [] 15 | } 16 | ] 17 | --------------------------------------------------------------------------------