diff --git a/LICENSE b/LICENSE index e69de29..40c8ae6 100644 --- a/LICENSE +++ b/LICENSE @@ -0,0 +1,505 @@ +GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +(This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.) + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + {description} + Copyright (C) {year} {fullname} + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random + Hacker. + + {signature of Ty Coon}, 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + diff --git a/app/Resources/povray_layout/layout.tmpl b/app/Resources/povray_layout/layout.tmpl new file mode 100644 index 0000000..2447337 --- /dev/null +++ b/app/Resources/povray_layout/layout.tmpl @@ -0,0 +1,55 @@ +#declare main_mesh = m_MYSOLID; +#include "math.inc" +#include "finish.inc" +#include "transforms.inc" +#include "colors.inc" + +background {color rgb 1} + +light_source { <-10,-15,15> color White } +light_source { <-11,-4,10> color White } +light_source { <-10,14,20> color White } + + +global_settings { + assumed_gamma 2.1 +} + +#declare Min = min_extent( main_mesh ); +#declare Max = max_extent( main_mesh ); + +#declare MaxLength = max( + Max.x-Min.x, + Max.y-Min.y, + Max.z-Min.z +); + +// Calculate camera distace factor - if object is large on Y axis and Z axis move the camera further +#declare cameraDistance = (((Max.x-Min.x)*(1/MaxLength) > 0.3) & ((Max.y-Min.y)*(1/MaxLength) > 0.95) ? 1: 0.9); + +camera +{ + location <-1.5*cameraDistance, -1*cameraDistance, 1.1*cameraDistance> + angle 45 + sky z + look_at 0 + translate <0,0.05,-0.15> + right -1*x +} + +object +{ + main_mesh + Center_Trans(main_mesh, x+y+z) + +// rotate <-90,0,0> + rotate <0,90,0> + + texture + { + pigment{ color rgb<0, 0.34, 0.6> } + finish { phong .51} + } + scale (1/MaxLength) +} + diff --git a/app/Resources/views/brickset/instructions.html.twig b/app/Resources/views/brickset/instructions.html.twig index 43c983d..5e64733 100644 --- a/app/Resources/views/brickset/instructions.html.twig +++ b/app/Resources/views/brickset/instructions.html.twig @@ -17,7 +17,7 @@ {% for instruction in instructions %} {{ instruction.description }} - {{ utils.bytesToSize( remoteSize(instruction.uRL)) }} + {{ remoteSize(instruction.uRL) | bytesToSize }} {{ remoteFilename(instruction.uRL) }} {% endfor %} diff --git a/app/Resources/views/macros/elements.html.twig b/app/Resources/views/macros/elements.html.twig index 9b9c149..4a28385 100644 --- a/app/Resources/views/macros/elements.html.twig +++ b/app/Resources/views/macros/elements.html.twig @@ -3,7 +3,10 @@
- + + {#
#} + {##} + {#
#}
{{ model.number }}
diff --git a/app/Resources/views/macros/utils.html.twig b/app/Resources/views/macros/utils.html.twig index 36850dd..e69de29 100644 --- a/app/Resources/views/macros/utils.html.twig +++ b/app/Resources/views/macros/utils.html.twig @@ -1,21 +0,0 @@ -{#http://stackoverflow.com/a/15303004#} -{% macro bytesToSize(bytes) %} - {% spaceless %} - {% set kilobyte = 1024 %} - {% set megabyte = kilobyte * 1024 %} - {% set gigabyte = megabyte * 1024 %} - {% set terabyte = gigabyte * 1024 %} - - {% if bytes < kilobyte %} - {{ bytes ~ ' B' }} - {% elseif bytes < megabyte %} - {{ (bytes / kilobyte)|number_format(2, '.') ~ ' KB' }} - {% elseif bytes < gigabyte %} - {{ (bytes / megabyte)|number_format(2, '.') ~ ' MB' }} - {% elseif bytes < terabyte %} - {{ (bytes / gigabyte)|number_format(2, '.') ~ ' GB' }} - {% else %} - {{ (bytes / terabyte)|number_format(2, '.') ~ ' TB' }} - {% endif %} - {% endspaceless %} -{% endmacro %} \ No newline at end of file diff --git a/app/Resources/views/model/detail.html.twig b/app/Resources/views/model/detail.html.twig index a4ea0ac..4600a22 100644 --- a/app/Resources/views/model/detail.html.twig +++ b/app/Resources/views/model/detail.html.twig @@ -11,7 +11,7 @@
- +
diff --git a/app/config/config.yml b/app/config/config.yml index 9bf88c9..ab7ca80 100644 --- a/app/config/config.yml +++ b/app/config/config.yml @@ -8,7 +8,7 @@ imports: parameters: locale: en # rebrickable csv files root URL (http://rebrickable.com/media/downloads/ or local dir containing csv files) - rebrickable_csv_url: 'http://rebrickable.com/media/downloads/' + rebrickable_downloads_url: 'http://rebrickable.com/media/downloads/' framework: #esi: ~ @@ -65,13 +65,13 @@ doctrine: naming_strategy: doctrine.orm.naming_strategy.underscore auto_mapping: true -# Swiftmailer Configuration -swiftmailer: - transport: "%mailer_transport%" - host: "%mailer_host%" - username: "%mailer_user%" - password: "%mailer_password%" - spool: { type: memory } +## Swiftmailer Configuration +#swiftmailer: +# transport: "%mailer_transport%" +# host: "%mailer_host%" +# username: "%mailer_user%" +# password: "%mailer_password%" +# spool: { type: memory } knp_menu: twig: @@ -97,7 +97,7 @@ liip_imagine: filesystem_service: oneup_flysystem.media_filesystem rebrickable: stream: - wrapper: 'http://m.rebrickable.com/media/' + wrapper: 'http://rebrickable.com/media/' resolvers: default: diff --git a/app/config/parameters.yml.dist b/app/config/parameters.yml.dist index be71996..3f3268a 100644 --- a/app/config/parameters.yml.dist +++ b/app/config/parameters.yml.dist @@ -10,11 +10,6 @@ parameters: # You should uncomment this if you want use pdo_sqlite # database_path: "%kernel.root_dir%/data.db3" - mailer_transport: smtp - mailer_host: 127.0.0.1 - mailer_user: ~ - mailer_password: ~ - # A secret key that's used to generate certain security-related tokens secret: ThisTokenIsNotSoSecretChangeIt @@ -24,5 +19,10 @@ parameters: # Rebrickable API key obtainable at http://rebrickable.com/api/ rebrickable_apikey: ~ - # Absolute path to OSMesa port of LDView - ldview_bin: /usr/bin/ldview \ No newline at end of file + # Path to OSMesa port of LDView + ldview_bin: /usr/bin/ldview + + # Path to POV-Ray binary - http://www.povray.org/ + povray_bin: /usr/bin/povray + # Path to stl2pov (version 3.3.0) - https://rsmith.home.xs4all.nl/software/py-stl-stl2pov.html + stl2pov_bin: /usr/bin/stl2pov \ No newline at end of file diff --git a/app/config/service/loader.yml b/app/config/service/loader.yml index 0dbf6f6..9bd585d 100644 --- a/app/config/service/loader.yml +++ b/app/config/service/loader.yml @@ -3,15 +3,11 @@ services: abstract: true class: AppBundle\Service\Loader\BaseLoader calls: - - [setArguments, ['@doctrine.orm.entity_manager', '@monolog.logger.loader']] - - service.ldview: - class: AppBundle\Service\LDViewService - arguments: ['%ldview_bin%', '@oneup_flysystem.media_filesystem'] + - [setArguments, ['@doctrine.orm.entity_manager', '@monolog.logger.loader', '@app.transformer.format']] service.loader.rebrickable: class: AppBundle\Service\Loader\RebrickableLoader - arguments: ['%rebrickable_csv_url%'] + arguments: ['%rebrickable_downloads_url%'] parent: service.loader.base service.loader.model: @@ -22,4 +18,9 @@ services: service.loader.relation: class: AppBundle\Service\Loader\RelationLoader arguments: ['@api.manager.rebrickable', '@app.relation.mapper'] + parent: service.loader.base + + service.loader.image: + class: AppBundle\Service\Loader\ImageLoader + arguments: ['@oneup_flysystem.media_filesystem', '%rebrickable_downloads_url%','@service.renderer.stl'] parent: service.loader.base \ No newline at end of file diff --git a/app/config/service/manager.yml b/app/config/service/manager.yml deleted file mode 100644 index 9e4a3f5..0000000 --- a/app/config/service/manager.yml +++ /dev/null @@ -1 +0,0 @@ -services: \ No newline at end of file diff --git a/app/config/service/service.yml b/app/config/service/service.yml index 88c5c8b..f800491 100644 --- a/app/config/service/service.yml +++ b/app/config/service/service.yml @@ -2,11 +2,14 @@ services: app.twig_extension: class: AppBundle\Twig\AppExtension public: false - arguments: ['@api.manager.rebrickable'] + arguments: ['@api.manager.rebrickable', '@app.transformer.format'] tags: - { name: twig.extension } - app.relation.mapper: - class: AppBundle\Utils\RelationMapper - arguments: - - ['%kernel.root_dir%/Resources/relations'] \ No newline at end of file + service.renderer.stl: + class: AppBundle\Service\StlRendererService + arguments: ['%kernel.root_dir%/Resources/povray_layout/layout.tmpl', '%povray_bin%','%stl2pov_bin%'] + + service.ldview: + class: AppBundle\Service\LDViewService + arguments: ['%ldview_bin%', '@oneup_flysystem.media_filesystem'] diff --git a/app/config/service/util.yml b/app/config/service/util.yml new file mode 100644 index 0000000..b044eed --- /dev/null +++ b/app/config/service/util.yml @@ -0,0 +1,8 @@ +services: + app.transformer.format: + class: AppBundle\Transformer\FormatTransformer + + app.relation.mapper: + class: AppBundle\Util\RelationMapper + arguments: + - ['%kernel.root_dir%/Resources/relations'] diff --git a/app/config/services.yml b/app/config/services.yml index ed103c2..5125d4d 100644 --- a/app/config/services.yml +++ b/app/config/services.yml @@ -2,7 +2,7 @@ imports: - { resource: service/repository.yml } - { resource: service/api.yml } - { resource: service/loader.yml } - - { resource: service/manager.yml } + - { resource: service/util.yml } - { resource: service/service.yml } - { resource: service/form.yml } - { resource: service/menu.yml } \ No newline at end of file diff --git a/bin/ldview b/bin/ldview deleted file mode 100644 index d255b0f..0000000 Binary files a/bin/ldview and /dev/null differ diff --git a/bin/stl2pov-2.5.0/LICENSE b/bin/stl2pov-2.5.0/LICENSE new file mode 100644 index 0000000..423414c --- /dev/null +++ b/bin/stl2pov-2.5.0/LICENSE @@ -0,0 +1,23 @@ +stl2pov is copyright © 2004--2007 R.F.Smith . +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. diff --git a/bin/stl2pov-2.5.0/stl2pov b/bin/stl2pov-2.5.0/stl2pov new file mode 100644 index 0000000..c0aa493 Binary files /dev/null and b/bin/stl2pov-2.5.0/stl2pov differ diff --git a/src/AppBundle/Command/InitDataCommand.php b/src/AppBundle/Command/InitDataCommand.php new file mode 100644 index 0000000..2d2adc5 --- /dev/null +++ b/src/AppBundle/Command/InitDataCommand.php @@ -0,0 +1,67 @@ +setName('app:init') + ->setDescription('Loads relations between LDraw models and Rebrickable parts.') + ->setHelp('This command allows you to load relation between models and parts into database.') + ->setDefinition( + new InputDefinition([ + new InputArgument('ldraw', InputArgument::REQUIRED, 'Path to LDraw library directory'), + ]) + ); + } + + protected function execute(InputInterface $input, OutputInterface $output) + { + $loadModelsCommand = $this->getApplication()->find('app:load:models'); + + $returnCode = $loadModelsCommand->run(new ArrayInput([ + 'command' => 'app:load:models', + 'ldraw' => $input->getArgument('ldraw'), + '--all' => true + ]),$output); + + if($returnCode) { + return 1; + } + + $loadRebrickableCommad = $this->getApplication()->find('app:load:rebrickable'); + $returnCode = $loadRebrickableCommad->run(new ArrayInput([ + 'command' => 'app:load:rebrickable']),$output); + + if($returnCode) { + return 1; + } + + $loadRelationsCommand = $this->getApplication()->find('app:load:relations'); + + $returnCode = $loadRelationsCommand->run(new ArrayInput([ + 'command' => 'app:load:relations']),$output); + + if($returnCode) { + return 1; + } + + $loadImagesCommand = $this->getApplication()->find('app:load:images'); + + $returnCode = $loadImagesCommand->run(new ArrayInput([ + 'command' => 'app:load:images', + '--color' => -1, + '--rebrickable' => true, + '--models' => true + ]),$output); + } +} diff --git a/src/AppBundle/Command/LoadModelImagesCommand.php b/src/AppBundle/Command/LoadModelImagesCommand.php new file mode 100644 index 0000000..d3a2e08 --- /dev/null +++ b/src/AppBundle/Command/LoadModelImagesCommand.php @@ -0,0 +1,48 @@ +setName('app:load:images') + ->setDescription('Loads images of models') + ->setHelp('This command allows you to load rendered images of models from Rebrickable or/and generate rendered images from stl files of models.') + ->setDefinition( + new InputDefinition([ + new InputOption('color', 'c', InputOption::VALUE_REQUIRED, 'Color ID of images to load.'), + new InputOption('url', 'u', InputOption::VALUE_REQUIRED, 'Url of zip file to load'), + new InputOption('rebrickable', 'r', InputOption::VALUE_NONE, 'Download images from Rebicable.com'), + new InputOption('models', 'm', InputOption::VALUE_NONE, 'Load missing images of models'), + ]) + ); + } + + protected function execute(InputInterface $input, OutputInterface $output) + { + $imageLoaderService = $this->getContainer()->get('service.loader.image'); + $imageLoaderService->setOutput($output); + + $color = $input->getOption('color'); + $url = $input->getOption('url'); + + if($color !== null && $input->getOption('rebrickable')) { + $imageLoaderService->loadColorFromRebrickable($color, $url); + } + + if($input->getOption('models')) { + $imageLoaderService->loadMissingModelImages($color); + } + } +} diff --git a/src/AppBundle/Command/LoadModelsCommand.php b/src/AppBundle/Command/LoadModelsCommand.php index c115440..54f925e 100644 --- a/src/AppBundle/Command/LoadModelsCommand.php +++ b/src/AppBundle/Command/LoadModelsCommand.php @@ -23,7 +23,6 @@ class LoadModelsCommand extends ContainerAwareCommand ->setDefinition( new InputDefinition([ new InputArgument('ldraw', InputArgument::REQUIRED, 'Path to LDraw library directory'), -// new InputOption('images', 'i', InputOption::VALUE_NONE, 'Do you want to generate images of models?'), new InputOption('all', 'a', InputOption::VALUE_NONE, 'Load all models from LDraw libary folder (/parts directory)'), new InputOption('file', 'f', InputOption::VALUE_REQUIRED, 'Load single modle into database'), new InputOption('update', 'u', InputOption::VALUE_NONE, 'Overwrite already loaded models'), @@ -35,8 +34,7 @@ class LoadModelsCommand extends ContainerAwareCommand { if (!$this->lock()) { $output->writeln('The command is already running in another process.'); - - return 0; + return 1; } $modelLoader = $this->getContainer()->get('service.loader.model'); @@ -51,12 +49,10 @@ class LoadModelsCommand extends ContainerAwareCommand if (($path = $input->getOption('file')) != null) { if ($file = realpath($path)) { $output->writeln([ - 'Loading model', - 'path: '.$file, - '------------------------------------------------------------------------------', + "Loading model: {$path}", ]); - $modelLoader->loadOneModel($file); + $modelLoader->loadOne($file); $errorCount = $this->getContainer()->get('monolog.logger.loader')->countErrors(); $errors = $errorCount ? ''.$errorCount.'' : '0'; @@ -70,10 +66,12 @@ class LoadModelsCommand extends ContainerAwareCommand // Load all models inside ldraw/parts directory if ($input->getOption('all')) { $output->writeln([ - 'Loading models from LDraw library: '.$ldrawPath.'', + '------------------------------------------------------------------------------', + "Loading models from LDraw library: {$ldrawPath}", + '------------------------------------------------------------------------------', ]); - $modelLoader->loadAllModels(); + $modelLoader->loadAll(); $errorCount = $this->getContainer()->get('monolog.logger.loader')->countErrors(); $errors = $errorCount ? ''.$errorCount.'' : '0'; @@ -81,7 +79,9 @@ class LoadModelsCommand extends ContainerAwareCommand $output->writeln(['Done with "'.$errors.'" errors.']); } } else { - $output->writeln($ldraw.' is not valid path'); + $output->writeln("{$ldraw} is not a valid path!"); + $this->release(); + return 1; } $this->release(); diff --git a/src/AppBundle/Command/LoadRebrickableDataCommand.php b/src/AppBundle/Command/LoadRebrickableDataCommand.php index 71d7135..6ac5cb4 100644 --- a/src/AppBundle/Command/LoadRebrickableDataCommand.php +++ b/src/AppBundle/Command/LoadRebrickableDataCommand.php @@ -2,6 +2,7 @@ namespace AppBundle\Command; +use League\Flysystem\Exception; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -21,7 +22,11 @@ class LoadRebrickableDataCommand extends ContainerAwareCommand $rebrickableLoader = $this->getContainer()->get('service.loader.rebrickable'); $rebrickableLoader->setOutput($output); - //TODO log errors - $rebrickableLoader->loadTables(); + try { + $rebrickableLoader->loadAll(); + } catch (Exception $exception) { + $output->writeln("{$exception->getMessage()}"); + return 1; + } } } diff --git a/src/AppBundle/Command/LoadRelationCommand.php b/src/AppBundle/Command/LoadRelationCommand.php index d90ebeb..1d18ffe 100644 --- a/src/AppBundle/Command/LoadRelationCommand.php +++ b/src/AppBundle/Command/LoadRelationCommand.php @@ -21,7 +21,15 @@ class LoadRelationCommand extends ContainerAwareCommand $relationLoader = $this->getContainer()->get('service.loader.relation'); $relationLoader->setOutput($output); - //TODO log errors - $relationLoader->loadNotPaired(); + + $output->writeln([ + '------------------------------------------------------------------------------', + "Loading relations between parts and models...", + '------------------------------------------------------------------------------', + ]); + + $relationLoader->loadAll(); + + $output->writeln(['Done!']); } } diff --git a/src/AppBundle/Exception/RenderFailedException.php b/src/AppBundle/Exception/RenderFailedException.php new file mode 100644 index 0000000..db52881 --- /dev/null +++ b/src/AppBundle/Exception/RenderFailedException.php @@ -0,0 +1,15 @@ +mediaFilesystem->has('ldraw'.DIRECTORY_SEPARATOR.'models')) { - $this->mediaFilesystem->createDir('ldraw'.DIRECTORY_SEPARATOR.'models'); + if (!$this->mediaFilesystem->has('models')) { + $this->mediaFilesystem->createDir('models'); } - $newFile = 'ldraw'.DIRECTORY_SEPARATOR.'models'.DIRECTORY_SEPARATOR.basename($file, '.dat').'.stl'; + $newFile = 'models'.DIRECTORY_SEPARATOR.basename($file, '.dat').'.stl'; if (!$this->mediaFilesystem->has($newFile) || $rewrite) { $this->runLDView([ @@ -70,7 +70,7 @@ class LDViewService '-LDrawDir='.$this->ldrawLibraryContext->getAdapter()->getPathPrefix(), '-ExportFiles=1', '-ExportSuffix=.stl', - '-ExportsDir='.$this->mediaFilesystem->getAdapter()->getPathPrefix().'ldraw'.DIRECTORY_SEPARATOR.'models', + '-ExportsDir='.$this->mediaFilesystem->getAdapter()->getPathPrefix().'models', ]); // Check if file created successfully @@ -96,11 +96,11 @@ class LDViewService */ public function datToPng($file, $rewrite = false) { - if (!$this->mediaFilesystem->has('ldraw'.DIRECTORY_SEPARATOR.'images')) { - $this->mediaFilesystem->createDir('ldraw'.DIRECTORY_SEPARATOR.'images'); + if (!$this->mediaFilesystem->has('images')) { + $this->mediaFilesystem->createDir('images'); } - $newFile = 'ldraw'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.basename($file, '.dat').'.png'; + $newFile = 'images'.DIRECTORY_SEPARATOR.basename($file, '.dat').'.png'; if (!$this->mediaFilesystem->has($newFile) || $this->rewrite) { $this->runLDView([ @@ -118,7 +118,7 @@ class LDViewService '-SaveWidth=800', '-CurveQuality=12', '-DefaultLatLong=45,40', - '-SaveDir='.$this->mediaFilesystem->getAdapter()->getPathPrefix().'ldraw'.DIRECTORY_SEPARATOR.'images', + '-SaveDir='.$this->mediaFilesystem->getAdapter()->getPathPrefix().'images', '-SaveSnapshots=1', ]); diff --git a/src/AppBundle/Service/Loader/BaseLoader.php b/src/AppBundle/Service/Loader/BaseLoader.php index 07343ee..8e222e2 100644 --- a/src/AppBundle/Service/Loader/BaseLoader.php +++ b/src/AppBundle/Service/Loader/BaseLoader.php @@ -4,6 +4,7 @@ namespace AppBundle\Service\Loader; use AppBundle\Exception\FileNotFoundException; use AppBundle\Exception\WriteErrorException; +use AppBundle\Transformer\FormatTransformer; use Doctrine\ORM\EntityManager; use Monolog\Logger; use Symfony\Bundle\FrameworkBundle\Translation\Translator; @@ -29,21 +30,29 @@ abstract class BaseLoader */ protected $progressBar; - /** @var Logger */ + /** + * @var Logger + */ protected $logger; + /** + * @var FormatTransformer + */ + private $formatTransformer; + /** * Loader constructor. * * @param EntityManager $em * @param Translator $translator */ - public function setArguments(EntityManager $em, $logger) + public function setArguments(EntityManager $em, $logger, $formatTransformer) { $this->em = $em; $this->em->getConnection()->getConfiguration()->setSQLLogger(null); $this->logger = $logger; + $this->formatTransformer = $formatTransformer; } public function setOutput(OutputInterface $output) @@ -57,28 +66,33 @@ abstract class BaseLoader * * @param $total */ - protected function initProgressBar($total) + protected function initProgressBar($total, $format = 'loader') { $this->progressBar = new ProgressBar($this->output, $total); -// $this->progressBar->setFormat('very_verbose'); - $this->progressBar->setFormat('[%current%/%max%] [%bar%] %percent:3s%% (%elapsed:6s%/%estimated:-6s%) (%filename%)'.PHP_EOL); + ProgressBar::setFormatDefinition('loader', '[%current% / %max%] [%bar%] %percent:3s%% (%elapsed:6s%/%estimated:-6s%) (%message%)' . PHP_EOL); + ProgressBar::setFormatDefinition('download', '[%progress% / %size%] [%bar%] %percent:3s%% (%elapsed:6s%/%estimated:-6s%)' . PHP_EOL); + $this->progressBar->setFormat($format); $this->progressBar->setBarWidth(70); + $this->progressBar->start(); } protected function progressCallback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) { + $this->logger->info($notification_code); + switch ($notification_code) { case STREAM_NOTIFY_FILE_SIZE_IS: $this->initProgressBar($bytes_max); - $this->progressBar->setFormat('[%current%/%max%] [%bar%] %percent:3s%% (%elapsed:6s%/%estimated:-6s%)'.PHP_EOL); + $this->progressBar->setFormat('download'); + $this->progressBar->setMessage($this->formatTransformer->bytesToSize($bytes_max),'size'); + $this->progressBar->setRedrawFrequency($bytes_max/20); break; case STREAM_NOTIFY_PROGRESS: $this->progressBar->setProgress($bytes_transferred); + $this->progressBar->setMessage($this->formatTransformer->bytesToSize($bytes_transferred),'progress'); break; case STREAM_NOTIFY_COMPLETED: - $this->progressBar->setMessage('Done'); - $this->progressBar->setProgress($bytes_max); $this->progressBar->finish(); break; } @@ -106,6 +120,7 @@ abstract class BaseLoader if (false === file_put_contents($temp, fopen($url, 'r', 0, $ctx))) { throw new WriteErrorException($temp); } + $this->progressBar->finish(); } catch (ContextErrorException $e) { throw new FileNotFoundException($url); } catch (\Exception $e) { @@ -114,4 +129,9 @@ abstract class BaseLoader return $temp; } + + protected function writeOutput(array $lines) { + if($this->output) + $this->output->writeln($lines); + } } diff --git a/src/AppBundle/Service/Loader/ImageLoader.php b/src/AppBundle/Service/Loader/ImageLoader.php new file mode 100644 index 0000000..fd04794 --- /dev/null +++ b/src/AppBundle/Service/Loader/ImageLoader.php @@ -0,0 +1,68 @@ +mediaFilesystem = $mediaFilesystem; + $this->rebrickableDownloadUrl = $rebrickableDownloadUrl; + $this->stlRendererService = $stlRendererService; + } + + public function loadColorFromRebrickable($color, $path = null) + { + if(!$path) { + $path = $this->rebrickableDownloadUrl."ldraw/parts_{$color}.zip"; + } + + $file = $this->downloadFile($path); + $zip = new \ZipArchive($file); + + if ($zip->open($file) === TRUE) { + $this->output->writeln([ + "Extracting ZIP file into {$this->mediaFilesystem->getAdapter()->getPathPrefix()}images/{$color}" + ]); + $zip->extractTo($this->mediaFilesystem->getAdapter()->getPathPrefix().'images'.DIRECTORY_SEPARATOR.$color); + $zip->close(); + $this->output->writeln(['Done!']); + } else { + $this->output->writeln(['Extraction of file failed!']); + } + } + + public function loadMissingModelImages($color) { + $models = $this->em->getRepository(Model::class)->findAll(); + + $this->initProgressBar(count($models)); + foreach ($models as $model) { + $this->progressBar->setMessage($model->getNumber()); + if(!$this->mediaFilesystem->has('images'.DIRECTORY_SEPARATOR.$color.DIRECTORY_SEPARATOR.$model->getNumber().'.png')) { + try { + $this->stlRendererService->render( + $this->mediaFilesystem->getAdapter()->getPathPrefix().$model->getPath(), + $this->mediaFilesystem->getAdapter()->getPathPrefix().'images'.DIRECTORY_SEPARATOR.$color.DIRECTORY_SEPARATOR + ); + } catch (\Exception $e) { + dump($e->getMessage()); + } + } + $this->progressBar->advance(); + } + } +} \ No newline at end of file diff --git a/src/AppBundle/Service/Loader/ModelLoader.php b/src/AppBundle/Service/Loader/ModelLoader.php index 6e47507..64f08c8 100644 --- a/src/AppBundle/Service/Loader/ModelLoader.php +++ b/src/AppBundle/Service/Loader/ModelLoader.php @@ -12,15 +12,14 @@ use AppBundle\Exception\ConvertingFailedException; use AppBundle\Exception\FileException; use AppBundle\Exception\ParseErrorException; use AppBundle\Service\LDViewService; -use AppBundle\Utils\LDModelParser; -use AppBundle\Utils\RelationMapper; +use AppBundle\Util\LDModelParser; +use AppBundle\Util\RelationMapper; use League\Flysystem\Adapter\Local; use League\Flysystem\Exception; use League\Flysystem\Filesystem; use Symfony\Component\Finder\Finder; use Symfony\Component\Finder\SplFileInfo; -//TODO refactor class ModelLoader extends BaseLoader { /** @@ -80,7 +79,7 @@ class ModelLoader extends BaseLoader } } - public function loadOneModel($file) + public function loadOne($file) { $connection = $this->em->getConnection(); try { @@ -95,7 +94,7 @@ class ModelLoader extends BaseLoader } } - public function loadAllModels() + public function loadAll() { $files = $this->finder->in([ $this->ldrawLibraryContext->getAdapter()->getPathPrefix(), @@ -109,7 +108,7 @@ class ModelLoader extends BaseLoader $connection->beginTransaction(); try { - $this->progressBar->setMessage($file->getFilename(), 'filename'); + $this->progressBar->setMessage($file->getFilename()); $this->loadModel($file->getRealPath()); @@ -127,7 +126,8 @@ class ModelLoader extends BaseLoader } /** - * Load Model entity into database. + * Load model entity and all related submodels into database while generating stl file of model. + * Uses LDView to convert LDraw .dat to .stl * * @param $file * @@ -144,7 +144,8 @@ class ModelLoader extends BaseLoader // Parse model file save data to $modelArray try { - $modelArray = $this->ldModelParser->parse($file); + $content = file_get_contents($file); + $modelArray = $this->ldModelParser->parse($content); } catch (ParseErrorException $e) { $this->logger->error($e->getMessage(), [$file]); @@ -172,8 +173,8 @@ class ModelLoader extends BaseLoader return $parentModel; } - // Load model + // Load model $model = $this->em->getRepository(Model::class)->getOrCreate($modelArray['id']); // Recursively load models of subparts @@ -203,7 +204,7 @@ class ModelLoader extends BaseLoader try { // update model only if newer version if (!$model->getModified() || ($model->getModified() < $modelArray['modified'])) { - $stl = $this->LDViewService->datToStl($file, $rewrite)->getPath(); + $stl = $this->LDViewService->datToStl($file, $this->rewite)->getPath(); $model->setPath($stl); $model @@ -271,12 +272,14 @@ class ModelLoader extends BaseLoader return $context->getAdapter()->getPathPrefix().$filename; } // Try to find model in current LDRAW\PARTS sub-directory - elseif ($this->ldrawLibraryContext->has('parts/'.$filename)) { - return $this->ldrawLibraryContext->getAdapter()->getPathPrefix().'parts'.DIRECTORY_SEPARATOR.$filename; - } - // Try to find model in current LDRAW\P sub-directory - elseif ($this->ldrawLibraryContext->has('p'.DIRECTORY_SEPARATOR.$filename)) { - return $this->ldrawLibraryContext->getAdapter()->getPathPrefix().'p'.DIRECTORY_SEPARATOR.$filename; + elseif($this->ldrawLibraryContext) { + if($this->ldrawLibraryContext->has('parts/'.$filename)) { + return $this->ldrawLibraryContext->getAdapter()->getPathPrefix().'parts'.DIRECTORY_SEPARATOR.$filename; + } + // Try to find model in current LDRAW\P sub-directory + elseif ($this->ldrawLibraryContext->has('p'.DIRECTORY_SEPARATOR.$filename)) { + return $this->ldrawLibraryContext->getAdapter()->getPathPrefix().'p'.DIRECTORY_SEPARATOR.$filename; + } } return null; @@ -297,6 +300,7 @@ class ModelLoader extends BaseLoader return new Filesystem($adapter); } catch (Exception $exception) { $this->logger->error($exception->getMessage()); + return null; } } @@ -322,7 +326,6 @@ class ModelLoader extends BaseLoader // Do not include models without permission to redistribute elseif ($modelArray['license'] != 'Redistributable under CCAL version 2.0') { $this->logger->info('Model skipped.', ['number' => $modelArray['id'], 'license' => $modelArray['license']]); - return false; } diff --git a/src/AppBundle/Service/Loader/RebrickableLoader.php b/src/AppBundle/Service/Loader/RebrickableLoader.php index 7df7f91..ea68a1b 100644 --- a/src/AppBundle/Service/Loader/RebrickableLoader.php +++ b/src/AppBundle/Service/Loader/RebrickableLoader.php @@ -21,7 +21,7 @@ class RebrickableLoader extends BaseLoader $this->rebrickable_url = $rebrickable_url; } - public function loadTables() + public function loadAll() { $connection = $this->em->getConnection(); $connection->beginTransaction(); @@ -33,9 +33,8 @@ class RebrickableLoader extends BaseLoader $this->truncateTables(); $connection->prepare('SET foreign_key_checks = 1;')->execute(); - $this->output->writeln([ + $this->writeOutput([ 'Truncated rebrickable database tables.', - '------------------------------------------------------------------------------', 'Loading CSV files into database...', ]); @@ -54,7 +53,7 @@ class RebrickableLoader extends BaseLoader $connection->commit(); - $this->output->writeln('Rebrickable database loaded successfully!'); + $this->writeOutput(['Rebrickable database loaded successfully!']); } catch (\Exception $e) { $connection->rollBack(); throw $e; @@ -65,19 +64,17 @@ class RebrickableLoader extends BaseLoader { $array = ['inventories', 'inventory_parts', 'inventory_sets', 'sets', 'themes', 'parts', 'part_categories', 'colors']; - $this->output->writeln([ - 'Loading Rebrickable CSV files', - '------------------------------------------------------------------------------', + $this->writeOutput([ + '------------------------------------------------------------------------------', + 'Loading Rebrickable CSV files', + '------------------------------------------------------------------------------', ]); foreach ($array as $item) { $this->csvFile[$item] = $this->downloadFile($this->rebrickable_url.$item.'.csv'); } - $this->output->writeln([ - 'Done', - '------------------------------------------------------------------------------', - ]); + $this->writeOutput(['All CSV files loaded.']); } private function truncateTables() diff --git a/src/AppBundle/Service/Loader/RelationLoader.php b/src/AppBundle/Service/Loader/RelationLoader.php index 7ceaf73..925fec7 100644 --- a/src/AppBundle/Service/Loader/RelationLoader.php +++ b/src/AppBundle/Service/Loader/RelationLoader.php @@ -30,26 +30,21 @@ class RelationLoader extends BaseLoader public function loadAll() { $parts = $this->em->getRepository(Part::class)->findAll(); - - $this->initProgressBar(count($parts)); - /** @var Part $part */ - foreach ($parts as $part) { - $this->load($part); - - $this->progressBar->advance(); - } - $this->progressBar->finish(); + $this->load($parts); } - public function loadNotPaired() + public function loadNotPaired($parts) { $parts = $this->em->getRepository(Part::class)->findAllNotPaired(); + $this->load($parts); + } + private function load($parts) { $this->initProgressBar(count($parts)); /** @var Part $part */ foreach ($parts as $part) { - $this->load($part); - $this->progressBar->setMessage($part->getNumber(), 'filename'); + $this->loadPartRelation($part); + $this->progressBar->setMessage($part->getNumber()); $this->progressBar->advance(); } $this->progressBar->finish(); @@ -62,7 +57,7 @@ class RelationLoader extends BaseLoader * * @return Model $m */ - private function load(Part $part) + private function loadPartRelation(Part $part) { $modelRepository = $this->em->getRepository(Model::class); diff --git a/src/AppBundle/Service/StlRendererService.php b/src/AppBundle/Service/StlRendererService.php new file mode 100644 index 0000000..db49a54 --- /dev/null +++ b/src/AppBundle/Service/StlRendererService.php @@ -0,0 +1,204 @@ +stl2pov = $stl2pov; + $this->povray = $povray; + $this->layout = $layout; + $this->size = 900; + if($tmpDir) { + $this->tmpDir = $tmpDir; + } else { + $this->tmpDir = sys_get_temp_dir(); + } + } + + + /** + * @param $file + * @param $destinationDir + * @param bool $cleanup + * @return string + * @throws \Exception + */ + public function render($file, $destinationDir, $cleanup = true) { + $povFile = $this->convertStlPov($file); + + try { + $image = $this->renderPov($povFile, $destinationDir); + if($cleanup) { + unlink($povFile); + } + return $image; + + } catch (\Exception $exception) { + unlink($povFile); + throw $exception; + } + } + + + /** + * Converts STL file to pov scene by calling stl2pov command line application + * + * Generated file is saved to tmp directory specifed in constructor of this class and path to file is returned + * + * stl2pov (version 3.3.0) - https://rsmith.home.xs4all.nl/software/py-stl-stl2pov.html + * + * @param string $file The full path to stl file + * @return string Return the full path to the generated pov scene + * @throws ConvertingFailedException throws exception if there are problems converting stl file to pov + * @throws FileNotFoundException throws exception if source file not found + */ + private function convertStlPov($file) { + if(!file_exists($file)) { + throw new FileNotFoundException($file); + } + if(pathinfo($file, PATHINFO_EXTENSION) != 'stl') { + throw new ConvertingFailedException($file, 'POV', 'Wrong input filetype'); + } + + // Save the current working directory and change directory to tmp dir + // stl2pov outputs converted file to current directory and destination can not be changed + $cwd = getcwd(); + chdir($this->tmpDir); + + $filename = pathinfo($file)['filename']; + + // Run stl2pov conversion + $processBuilder = new ProcessBuilder(); + $process = $processBuilder->setPrefix($this->stl2pov) + ->setArguments([ + $file + ]) + ->getProcess(); + $process->mustRun(); + + // Check if file created successfully + if (!file_exists($filename.'.inc')) { + throw new ConvertingFailedException($file, 'POV'); + } + + // Load contents of .inc file to variable + $incFile = file_get_contents($filename.'.inc',LOCK_EX); + // Replace mesh name in loaded inc file to match declaration in scene layout + $incFile = preg_replace('/# declare m_(.*) = mesh/','#declare m_MYSOLID = mesh',$incFile); + + // Remove no longer needed inc file + unlink($filename.'.inc'); + chdir($cwd); + + // Get desired filepath of new pov file + $outputFile = $this->tmpDir.DIRECTORY_SEPARATOR.$filename.'.pov'; + + // Load contents of pov-ray layout file + $layout = file_get_contents($this->layout); + + // Try to write contents of converted inc file and concat int with scene definitions + if (!file_put_contents($outputFile, $incFile, LOCK_EX)) { + throw new ConvertingFailedException($file, 'POV'); + } + if(!file_put_contents($outputFile, $layout, FILE_APPEND | LOCK_EX)) { + throw new ConvertingFailedException($file, 'POV'); + } + if (!file_exists($outputFile)) { + throw new ConvertingFailedException($file, 'POV'); + } + + return $outputFile; + } + + + /** + * Renders POV-Ray .pov file by calling povray command line application + * + * http://www.povray.org/ + * + * @param string $file The full path to .pov file to be rendered + * @param $to + * @return string Full path to rendered image file + * @throws RenderFailedException throws exception if there are problems rendering image + * @throws FileNotFoundException throws exception if source file not found + */ + private function renderPov($file, $to) { + if(!file_exists($file)) { + throw new FileNotFoundException($file); + } + + $filename = pathinfo($file)['filename']; + + $outputFile = "{$to}{$filename}.png"; + + $processBuilder = new ProcessBuilder(); + + //+I - input file name + //+FN - PNG file format + //+Wn - Sets screen width to n pixels + //+Hn - Sets screen height to n pixels + //+O - output file + //+Qn - Set quality value to n (0 <= n <= 11) + //+AMn - use non-adaptive (n=1) or adaptive (n=2) supersampling + //+A0.n - perform antialiasing (if color change is above n percent) + //-D - Turns graphic display off + $process = $processBuilder->setPrefix($this->povray) + ->setArguments([ + "+I\"{$file}\"", + "+FN", + "+W{$this->size}", + "+H{$this->size}", + "+O\"$outputFile\"", + "+Q8", + "+AM2", + "+A0.5", + "-D", + ])->getProcess(); + $process->mustRun(); + + if(!file_exists($outputFile)) { + throw new RenderFailedException("{$to}{$filename}.png"); + } + return $outputFile; + } +} \ No newline at end of file diff --git a/src/AppBundle/Transformer/FormatTransformer.php b/src/AppBundle/Transformer/FormatTransformer.php new file mode 100644 index 0000000..0691092 --- /dev/null +++ b/src/AppBundle/Transformer/FormatTransformer.php @@ -0,0 +1,18 @@ +rebrickableAPIManager = $rebrickableAPIManager; + $this->formatTransformer = $formatTransformer; } public function getFilters() @@ -24,6 +29,7 @@ class AppExtension extends \Twig_Extension return [ new \Twig_SimpleFilter('partImage', [$this, 'partImage']), new \Twig_SimpleFilter('setImage', [$this, 'setImage']), + new \Twig_SimpleFilter('bytesToSize', [$this, 'bytesToSize']), ]; } @@ -37,7 +43,7 @@ class AppExtension extends \Twig_Extension public function partImage($number, $color = null) { - return '/parts/ldraw/'.($color ? $color : '-1').'/'.$number.'.png'; + return '/parts/ldraw/'.($color !== null ? $color : '-1').'/'.$number.'.png'; } public function setImage($number) @@ -45,6 +51,10 @@ class AppExtension extends \Twig_Extension return '/sets/'.strtolower($number).'.jpg'; } + public function bytesToSize($bytes, $precision = 2) { + return $this->formatTransformer->bytesToSize($bytes, $precision); + } + public function remoteSize($url) { $ch = curl_init($url); diff --git a/src/AppBundle/Util/LDModelParser.php b/src/AppBundle/Util/LDModelParser.php new file mode 100644 index 0000000..adcddeb --- /dev/null +++ b/src/AppBundle/Util/LDModelParser.php @@ -0,0 +1,206 @@ + string + * 'name' => string + * 'category' => string + * 'keywords' => [] + * 'author' => string + * 'modified' => DateTime + * 'type' => string + * 'subparts' => [], + * 'licence' => string + * ]. + * + * LDraw.org Standards: Official Library Header Specification (http://www.ldraw.org/article/398.html) + * + * @throws ErrorParsingLineException + * + * @return array + */ + public function parse($string) + { + $model = [ + 'id' => null, + 'name' => null, + 'category' => null, + 'keywords' => [], + 'author' => null, + 'modified' => null, + 'type' => null, + 'subparts' => [], + 'parent' => null, + 'license' => null, + ]; + + $firstLine = false; + foreach(explode("\n", $string) as $line) { + $line = trim($line); + + // Comments or META Commands + if (strpos($line, '0 ') === 0) { + $line = preg_replace('/^0 /', '', $line); + + // 0 + if (!$firstLine) { + $array = explode(' ', ltrim(trim($line, 2), '=_~')); + $model['category'] = isset($array[0]) ? $array[0] : ''; + $model['name'] = preg_replace('/ {2,}/', ' ', ltrim($line, '=_')); + + $firstLine = true; + } + // 0 !CATEGORY + elseif (strpos($line, '!CATEGORY ') === 0) { + $model['category'] = trim(preg_replace('/^!CATEGORY /', '', $line)); + } + // 0 !KEYWORDS , , ..., + elseif (strpos($line, '!KEYWORDS ') === 0) { + $model['keywords'] = explode(', ', preg_replace('/^!KEYWORDS /', '', $line)); + } + // 0 Name: .dat + elseif (strpos($line, 'Name: ') === 0 && !isset($header['id'])) { + $model['id'] = preg_replace('/(^Name: )(.*)(.dat)/', '$2', $line); + } + // 0 Author: [] + elseif (strpos($line, 'Author: ') === 0) { + $model['author'] = preg_replace('/^Author: /', '', $line); + } + // 0 !LDRAW_ORG Part|Subpart|Primitive|48_Primitive|Shortcut (optional qualifier(s)) ORIGINAL|UPDATE YYYY-RR + elseif (strpos($line, '!LDRAW_ORG ') === 0) { + $type = preg_replace('/(^!LDRAW_ORG )(.*)( UPDATE| ORIGINAL)(.*)/', '$2', $line); + + $model['type'] = $type; + + // Last modification date in format YYYY-RR + $date = preg_replace('/(^!LDRAW_ORG )(.*)( UPDATE | ORIGINAL )(.*)/', '$4', $line); + if (preg_match('/^[1-2][0-9]{3}-[0-9]{2}$/', $date)) { + $model['modified'] = \DateTime::createFromFormat('Y-m-d H:i:s', $date.'-01 00:00:00'); + } + } + // 0 !LICENSE Redistributable under CCAL version 2.0 : see CAreadme.txt | 0 !LICENSE Not redistributable : see NonCAreadme.txt + elseif (strpos($line, '!LICENSE ') === 0) { + $model['license'] = preg_replace('/(^!LICENSE )(.*) : (.*)$/', '$2', $line); + } + } elseif (strpos($line, '1 ') === 0) { + $id = strtolower($this->getReferencedModelNumber($line)); + + if (isset($model['subparts'][$id])) { + $model['subparts'][$id] = $model['subparts'][$id] + 1; + } else { + $model['subparts'][$id] = 1; + } + } elseif (!empty($line) && !in_array($line[0], ['2', '3', '4', '5'])) { + throw new ErrorParsingLineException($model['id'],$line); + } + } + + if ($this->isSticker($model['name'], $model['id'])) { + $model['type'] = 'Sticker'; + } elseif (count($model['subparts']) == 1 && in_array($model['type'], ['Part Alias', 'Shortcut Physical_Colour', 'Shortcut Alias', 'Part Physical_Colour'])) { + $model['parent'] = array_keys($model['subparts'])[0]; + } elseif (($parent = $this->getPrintedModelParentNumber($model['id'])) && !in_array($model['type'], ['48_Primitive', '8_Primitive', 'Primitive', 'Subpart'])) { + $model['type'] = 'Printed'; + $model['parent'] = $parent; + } elseif ($parent = $this->getObsoleteModelParentNumber($model['name'])) { + $model['parent'] = $parent; + } + + return $model; + } + + /** + * Get file reference from part line. + * + * Line type 1 is a sub-file reference. The generic format is: + * 1 x y z a b c d e f g h i + * + * LDraw.org Standards: File Format 1.0.2 (http://www.ldraw.org/article/218.html) + * + * @param $line + * + * @return string|null Filename of referenced part + */ + public function getReferencedModelNumber($line) + { + $line = ($line); + + if (preg_match('/^1(.*) (.*)\.dat$/', strtolower($line), $matches)) { + return str_replace('\\', DIRECTORY_SEPARATOR, $matches[2]); + } + + return null; + } + + /** + * Get printed part parent id. + * + * part name in format: + * nnnPxx, nnnnPxx, nnnnnPxx, nnnaPxx, nnnnaPxx (a = alpha, n= numeric, x = alphanumeric) + * + * http://www.ldraw.org/library/tracker/ref/numberfaq/ + * + * @param $id + * + * @return string|null LDraw number of printed part parent + */ + public function getPrintedModelParentNumber($id) + { + if (preg_match('/(^.*)(p[0-9a-z]{2,3})$/', $id, $matches)) { + return $matches[1]; + } + + return null; + } + + /** + * Check if part is shortcut part of stricker and part. + * + * part name in format: + * nnnDnn, nnnnDnn, nnnnnDnn (a = alpha, n= numeric, x = alphanumeric) + * + * http://www.ldraw.org/library/tracker/ref/numberfaq/ + * + * @param $name + * @param $number + * + * @return bool + */ + public function isSticker($name, $number) + { + if (strpos($name, 'Sticker') === 0) { + return true; + } + + // Check if in format n*Daa == sticker + return preg_match('/(^.*)(d[0-9]{2})$/', $number); + } + + /** + * Get parent of obsolete part kept for reference. + * + * part description in format: + * ~Moved to {new_number} + * + * http://www.ldraw.org/article/398.html (Appendix II (02-Oct-06)) + * + * @param $name + * + * @return string|null Filename of referenced part + */ + public function getObsoleteModelParentNumber($name) + { + if (preg_match('/^(~Moved to )(.*)$/', $name, $matches)) { + return str_replace('\\', DIRECTORY_SEPARATOR, $matches[2]); + } + + return null; + } +} diff --git a/src/AppBundle/Utils/RelationMapper.php b/src/AppBundle/Util/RelationMapper.php similarity index 98% rename from src/AppBundle/Utils/RelationMapper.php rename to src/AppBundle/Util/RelationMapper.php index 257a8d4..940493a 100644 --- a/src/AppBundle/Utils/RelationMapper.php +++ b/src/AppBundle/Util/RelationMapper.php @@ -1,6 +1,6 @@ string - * 'name' => string - * 'category' => string - * 'keywords' => [] - * 'author' => string - * 'modified' => DateTime - * 'type' => string - * 'subparts' => [], - * 'licence' => string - * ]. - * - * LDraw.org Standards: Official Library Header Specification (http://www.ldraw.org/article/398.html) - * - * @throws FileNotFoundException|ParseErrorException - * - * @return array - */ - public function parse($file) - { - if (file_exists($file)) { - $model = [ - 'id' => null, - 'name' => null, - 'category' => null, - 'keywords' => [], - 'author' => null, - 'modified' => null, - 'type' => null, - 'subparts' => [], - 'parent' => null, - 'license' => null, - ]; - - try { - $handle = fopen($file, 'r'); - - if ($handle) { - $firstLine = false; - - while (($line = fgets($handle)) !== false) { - $line = trim($line); - - // Comments or META Commands - if (strpos($line, '0 ') === 0) { - $line = preg_replace('/^0 /', '', $line); - - // 0 - if (!$firstLine) { - $array = explode(' ', ltrim(trim($line, 2), '=_~')); - $model['category'] = isset($array[0]) ? $array[0] : ''; - $model['name'] = preg_replace('/ {2,}/', ' ', ltrim($line, '=_')); - - $firstLine = true; - } - // 0 !CATEGORY - elseif (strpos($line, '!CATEGORY ') === 0) { - $model['category'] = trim(preg_replace('/^!CATEGORY /', '', $line)); - } - // 0 !KEYWORDS , , ..., - elseif (strpos($line, '!KEYWORDS ') === 0) { - $model['keywords'] = explode(', ', preg_replace('/^!KEYWORDS /', '', $line)); - } - // 0 Name: .dat - elseif (strpos($line, 'Name: ') === 0 && !isset($header['id'])) { - $model['id'] = preg_replace('/(^Name: )(.*)(.dat)/', '$2', $line); - } - // 0 Author: [] - elseif (strpos($line, 'Author: ') === 0) { - $model['author'] = preg_replace('/^Author: /', '', $line); - } - // 0 !LDRAW_ORG Part|Subpart|Primitive|48_Primitive|Shortcut (optional qualifier(s)) ORIGINAL|UPDATE YYYY-RR - elseif (strpos($line, '!LDRAW_ORG ') === 0) { - $type = preg_replace('/(^!LDRAW_ORG )(.*)( UPDATE| ORIGINAL)(.*)/', '$2', $line); - - $model['type'] = $type; - - // Last modification date in format YYYY-RR - $date = preg_replace('/(^!LDRAW_ORG )(.*)( UPDATE | ORIGINAL )(.*)/', '$4', $line); - if (preg_match('/^[1-2][0-9]{3}-[0-9]{2}$/', $date)) { - $model['modified'] = \DateTime::createFromFormat('Y-m-d H:i:s', $date.'-01 00:00:00'); - } - } - // 0 !LICENSE Redistributable under CCAL version 2.0 : see CAreadme.txt | 0 !LICENSE Not redistributable : see NonCAreadme.txt - elseif (strpos($line, '!LICENSE ') === 0) { - $model['license'] = preg_replace('/(^!LICENSE )(.*) : (.*)$/', '$2', $line); - } - } elseif (strpos($line, '1 ') === 0) { - $id = strtolower($this->getReferencedModelNumber($line)); - - if (isset($model['subparts'][$id])) { - $model['subparts'][$id] = $model['subparts'][$id] + 1; - } else { - $model['subparts'][$id] = 1; - } - } elseif (!empty($line) && !in_array($line[0], ['2', '3', '4', '5'])) { - throw new ErrorParsingLineException($file,$line); - } - } - - if ($this->isSticker($model['name'], $model['id'])) { - $model['type'] = 'Sticker'; - } elseif (count($model['subparts']) == 1 && in_array($model['type'], ['Part Alias', 'Shortcut Physical_Colour', 'Shortcut Alias', 'Part Physical_Colour'])) { - $model['parent'] = array_keys($model['subparts'])[0]; - } elseif (($parent = $this->getPrintedModelParentNumber($model['id'])) && !in_array($model['type'], ['48_Primitive', '8_Primitive', 'Primitive', 'Subpart'])) { - $model['type'] = 'Printed'; - $model['parent'] = $parent; - } elseif ($parent = $this->getObsoleteModelParentNumber($model['name'])) { - $model['type'] = 'Alias'; - $model['parent'] = $parent; - } - - fclose($handle); - - return $model; - } - } catch (\Exception $exception) { - throw new ParseErrorException($file); - } - } - throw new FileNotFoundException($file); - } - - /** - * Get file reference from part line. - * - * Line type 1 is a sub-file reference. The generic format is: - * 1 x y z a b c d e f g h i - * - * LDraw.org Standards: File Format 1.0.2 (http://www.ldraw.org/article/218.html) - * - * @param $line - * - * @return string|null Filename of referenced part - */ - public function getReferencedModelNumber($line) - { - $line = ($line); - - if (preg_match('/^1(.*) (.*)\.dat$/', strtolower($line), $matches)) { - return str_replace('\\', DIRECTORY_SEPARATOR, $matches[2]); - } - - return null; - } - - /** - * Get printed part parent id. - * - * part name in format: - * nnnPxx, nnnnPxx, nnnnnPxx, nnnaPxx, nnnnaPxx (a = alpha, n= numeric, x = alphanumeric) - * - * http://www.ldraw.org/library/tracker/ref/numberfaq/ - * - * @param $id - * - * @return string|null LDraw number of printed part parent - */ - public function getPrintedModelParentNumber($id) - { - if (preg_match('/(^.*)(p[0-9a-z]{2,3})$/', $id, $matches)) { - return $matches[1]; - } - - return null; - } - - /** - * Check if part is shortcut part of stricker and part. - * - * part name in format: - * nnnDnn, nnnnDnn, nnnnnDnn (a = alpha, n= numeric, x = alphanumeric) - * - * http://www.ldraw.org/library/tracker/ref/numberfaq/ - * - * @param $name - * @param $number - * - * @return bool - */ - public function isSticker($name, $number) - { - if (strpos($name, 'Sticker') === 0) { - return true; - } - - // Check if in format n*Daa == sticker - return preg_match('/(^.*)(d[0-9]{2})$/', $number); - } - - /** - * Get parent of obsolete part kept for reference. - * - * part description in format: - * ~Moved to {new_number} - * - * http://www.ldraw.org/article/398.html (Appendix II (02-Oct-06)) - * - * @param $name - * - * @return string|null Filename of referenced part - */ - public function getObsoleteModelParentNumber($name) - { - if (preg_match('/^(~Moved to )(.*)$/', $name, $matches)) { - return str_replace('\\', DIRECTORY_SEPARATOR, $matches[2]); - } - - return null; - } -}