[
  {
    "path": ".gitignore",
    "content": "CMakeCache.txt\nCMakeFiles/\ncmake_install.cmake\nMakefile\nsrc/install_manifest.txt\ntrack_targets\nvision_landing.conf\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# vision_landing\n\n_**WARNING: This project is currently discontinued and is of academic interest only. ArduPilot and PX4 autopilots do not yet safely support vision based precision landing.  PLEASE DO NOT USE THIS CODE other than for experimental or learning purposes.  IT WILL behave dangerously.  You have been warned.**_\n\n### Precision landing using visual targets.  \nThis is a project to achieve precision landing on drones using ArduCopter firmware, using (monocular) vision alone.  Fiducial markers are printed and used as landing targets, and these targets provide orientation, location and distance information when combined with accurate size information of the markers and calibrated camera information.  No rangefinder is necessary, as the distance to target is obtained automatically through pose estimation of the markers.  \n\nDemonstrations\n--------------------\n### vision_landing from RTL  \n<a href=\"https://www.youtube.com/watch?v=E5PEEvcGPGc\" target=\"_new_\"><img src=\"https://github.com/goodrobots/vision_landing/blob/master/media/rtl-landing.png\" width=\"400\"></a>  \n### vision_landing using Infrared  \n<a href=\"https://www.youtube.com/watch?v=4ahQUu4kxuk\" target=\"_new_\"><img src=\"https://github.com/goodrobots/vision_landing/blob/master/media/ir-gray.png\" width=\"400\"></a>  \n### vision_landing using multiple video/data streams, colormapped in realtime  \n<a href=\"https://www.youtube.com/watch?v=OnWrUb7D-T4\" target=\"_new_\"><img src=\"https://github.com/goodrobots/vision_landing/blob/master/media/ir-colormap.png\" width=\"400\"></a>\n### Detection altitude using 720p video  \nLanding marker detected and locked on at 23 meters altitude, using very poor quality 720p video.  Much higher altitude can be expected using better quality camera/settings.  \n<img src=\"https://raw.githubusercontent.com/fnoop/vision_landing/master/media/23m-720p.png\" width=\"400\">  \n### Detection altitude using 1080p video  \nLanding marker detected and locked on at 32 meters altitude, using very poor quality 1080p video.  Much higher altitude can be expected using better quality camera/settings.  \n<img src=\"https://raw.githubusercontent.com/fnoop/vision_landing/master/media/32m-1080p.png\" width=\"400\">  \n\nDependencies\n--------------------\n**OpenCV (>3.0 recommended)**  \nIf possible find packages for your OS for version 3.0 or above (or install from source, for the brave), or else install 2.x packages for your OS.  For debian/ubuntu which currently only has opencv2.4, you probably want to install at least these packages:  \n - libopencv-dev  \n - libopencv-calib3d-dev  \n - libopencv-highgui-dev  \n - libopencv-imgproc-dev\nNote that this was developed using OpenCV 3.2, although current dev/testing is under 4.0.1.  SolvePNP which is the underlying function for pose estimation that aruco uses is somewhat broken in 2.4 so aruco includes it's own routines, only using solvepnp in OpenCV >3.0.\n\n**Aruco (>3.0.0)**\nIt is recommended to install 3.1.0 from https://github.com/fnoop/aruco as it has some fixes that haven't been released yet.  \nInstallation is straight forward:  \n ```\n git clone https://github.com/fnoop/aruco\n git checkout 3.1.0\n cd aruco\n cmake . && make && sudo make install\n ```\n\n**Dronekit**\nInstall the latest dronekit:  \n ```\n sudo pip install dronekit\n ```\n\nPrinting Targets/Markers\n--------------------\nThe landing targets used in this project are called 'fiducial markers'.  Fiducial markers are encoded objects (think QR codes or bar codes) that are used by computer vision systems as reference points in a scene.  There are numerous different types of encodings, which are called 'dictionaries'.  The marker library used in this project (Aruco) has its own set of dictionaries, but it also supports other dictionary types such as AprilTags.  \nIn order to perform the recommended calibration (detailed below in the next section), it is necessary to print a specific A4 marker board:  \n https://github.com/goodrobots/vision_landing/blob/master/calibration/aruco_calibration_board_a4.pdf  \nIt is important to print this on A4 size paper in exactly the size and proportions given in the PDF, as there are specific properties of the board that are expected by the calibration process.  \nWhen it comes to the landing markers themselves, the size and format depends on the nature of the craft and landing situations.  The higher the craft normally flies or will start landing from, the larger the target needs to be in order to be detected.  However, larger targets are more difficult to produce, transport and store, and they become unreadable at lower altitudes as they exceed the Field of View of the camera.  If precision landing is acceptable from a lower altitude then a smaller target can be used.  Alternatively, multiple targets can be used with varying sizes, so a larger target can be used for high altitude lock-on, then the vision system can switch to smaller targets at lower altitude for better precision and to keep within the FoV.  \nAruco recommends the 'ARUCO_MIP_36h12' dictionary for the best compromise between marker size and robustness.  \n<img src=\"https://github.com/goodrobots/vision_landing/blob/master/markers/aruco_mip_36h12_00012.png\" width=\"300\">  \nThis is a 36bit (6x6) 250 element dictionary and the intermarker distance is smaller than other aruco dictionaries such as 16h3 (4x4), so it's possible after further testing that these dictionaries with smaller marker size are better for precision landing.  Indeed, practical testing has shown that using a dictionary with a smaller grid size (and hence larger element or 'pixel' size) gives much better results from altitude.  If a larger dictionary with lots of different tags is not required, then it is recommended to use a dictionary such as the AprilTags 16h5 dictionary.  \n<img src=\"https://github.com/goodrobots/vision_landing/blob/master/markers/tag16_05_00011.png\" width=\"300\">  \n\nSo to start with, it is recommended to print a couple of markers (at your choice of size, A4 or A3 are easy to print and a good start):  \n https://github.com/goodrobots/vision_landing/blob/master/markers/aruco_mip_36h12_00012.png  \n https://github.com/goodrobots/vision_landing/blob/master/markers/aruco_mip_36h12_00036.png  \nOnce printed, measure the size of the marker (black edge to black edge) and this is fed as the marker size parameter to vision_landing.  However, note that you should either print the white border or mount the marker on a white background that leaves a white border around the black marker itself - the white border is important for reliable detection.  \nIt is important that the markers do not deform, bend, flap or move, so it's advisable to mount them on something solid like board or perspex.  Cardboard mounting up to A1 size is easy to find in local print, craft or stationary shops.  It is particularly important to make sure the A4 calibration page is rigid when doing the calibration.  \n\nIn order to address the problem of large markers exceeding the camera FoV at lower altitudes, multiple markers of differing sizes can be used.  As the craft descends in altitude locked on to a large marker, at some point a smaller marker will come into view and can be locked on to.  Marker boards can be used for increased robustness and accuracy.  An example of such a multiple marker board is included as an A1 PDF:\nhttps://github.com/goodrobots/vision_landing/blob/master/markers/a1-landing.pdf  \n<img src=\"https://github.com/goodrobots/vision_landing/blob/master/markers/a1-landing.png\" width=\"300\">  \nAfter testing and experimentation, it was found to have less markers as close together as possible in a circular pattern, with small pattern grids and larger intermarker distances gave better results.  An updated marker board as below is preset as default in the config file:  \nhttps://github.com/goodrobots/vision_landing/blob/master/markers/april16h5-landing-a1.pdf  \n<img src=\"https://github.com/goodrobots/vision_landing/blob/master/markers/april16h5-landing-a1.png\" width=\"300\">  \n\nAlso during development and testing, it was found that as the smaller markers come into view, the detection bounces between the two which can cause oscillations or other unexpected (and undesirable!) behaviour of the UAV.  A configurable filter that helps to debounce the detection thresholds has been implemented and can be set in the config:  \n```\n## Marker tracking history - number of frames that each marker is tracked for active marker transition  \nmarkerhistory=30  \n## Marker tracking threshold - percentage of frames in tracking history that marker must be detected to be activated  \nmarkerthreshold=80  \n```\nThe above settings mean that a 30 frame marker buffer is used (equal to 1 second at 30fps), and that of the last 30 frames, the smaller marker must be accurately detected in at least 80% of those 30 frames before vision_landing will lock on to that new smaller marker.  This greatly helps when landing on a pattern of concentric diminishing markers.  \n\nCamera Calibration\n--------------------\nIn order to perform any accurate Computer Vision work, you must first calibrate your camera.  Every camera and lens combination has different focal lengths, field of view, aperture, sensor size, optical center and lens distortions (eg. fisheye also known as positive radial distortion, or barrel distortion).  Even cameras or lenses of the same make/model will have small manufacturing tolerance/mistakes.  All of these must be known and compensated for.  \nOpenCV (which is what the vision code in this project uses) uses optional 'Camera Matrix' and 'Distortion Coefficients'  matrices (collectively called intrinsics) which are used to 'undistort' the raw image for accurate further processing and can also be used to automatically calculate focal length and field of view, necessary in turn to calculate the target angular offsets for precision landing and pose estimation used for accurate distance measurements.  There are numerous calibration methods for opencv, but there is a simple interactive routine included in the Aruco software installed as a dependency, so that process is recommended and documented briefly here:  \n - Print the A4 calibration board detailed above\n - Run aruco_calibration program:  \n   ```aruco_calibration live mycamera_calibration.yml -m <vision_landing_dir>/calibration/aruco_calibration_board_a4.yml -size 0.033```\n - Move the calibration board so it's in every position of the screen, particularly the outer edges (this is very important to capture the distortion of the lens at it's most extreme) and press 's' to capture a calibration snapshot at each position.\n - After taking enough snapshots (more the better, at least 10 is good), press 'c' to produce the calibration.  With the above command, it will produce a 'mycamera_calibration.yml'  \n\nInstallation\n--------------------\nFirst ensure the above dependencies are already installed.  \n\nThere are two main components:  \n - vision_landing, a python script\n - track_targets, a c++ program\n\ntrack_targets must be compiled and installed into the main directory before vision_landing can be run.  vision_landing calls track_targets to do the actual target detection and vector calculations.\n ```\n git clone https://github.com/goodrobots/vision_landing\n cd vision_landing/src\n cmake . && make && make install\n ```\nYou should now have a track_targets file in the same directory as the vision_landing script (the root of the vision_landing project).\n\n### Service Installation  \nIn order to provide startup at system boot and 'graceful' stop, a systemd manifest is provided (vision_landing.service).  To install, either alter the manifest with the full path to where vision_landing has been downloaded to (replace all instances of /usr/local/vision_landing with new path), or perhaps easier is to copy or symlink the directory to /usr/local and the provided manifest can be used without alteration.  The following should be executed from the root of vision_landing project (ie. in the same directory as the vision_landing script and track_targets after install):  \n ```\n sudo ln -s `pwd` /usr/local\n sudo cp vision_landing.service /etc/systemd/system\n sudo systemctl daemon-reload\n ```  \n\n ### Maverick - Automated Installation\n The [Maverick](http://github.com/goodrobots/maverick) project pre-installs everything necessary for vision_landing.  Flash-able OS images are available for multiple platforms.  To start vision_landing, ensure anything else that is using the camera is stopped, and simply use:  \n `maverick start vision_landing`  \n\n\nRunning\n--------------------\nTo run this project, you MUST have accurate calibration data for your camera sensor/lens combination.  This can be quite challenging to accomplish, so sample calibration data for Odroid oCam 5cr and Raspberry Pi cameras (v1 only) are included in the calibration directory.  More will hopefully be added in the future.  Note that even these supplied calibrations will not necessarily be perfect or even be guaranteed to work for your particular camera/lens combination, even if they are the same model.  It is highly recommended to take 10 minutes to perform the calibration.\n\n### Systemd running\nSystemd is the recommended way to run vision_landing, and assumes that the 'Recommended Installation' in the previous section has been completed.  Using systemd, starting vision_landing is as simple as executing:  \n ```sudo systemctl start vision_landing```  \nIt can be stopped by executing:  \n ```sudo systemctl stop vision_landing```  \nNote that when using systemd for control, mandatory and optional parameters are set using vision_landing.conf.  \n\n### Manual running\nvision_landing can also be run without systemd by just calling the main script and relying on the config file for correct configuration, or calling with the necessary mandatory and optional parameters.  It is highly recommended to use the config file for ease of use and minimum confusion.  \n\n**Examples**\n```\n./vision_landing # (uses values in vision_landing.conf)\n./vision_landing --input /dev/ttyS0 --markersize 0.235 --calibration calibration/ocam5cr-calibration-640x480.yml\n./vision_landing --markerid 580 --markerdict TAG36h11 --input /dev/ttyS0 0.235 --calibration calibration/ocam5cr-calibration-640x480.yml\n./vision_landing --simulator --input /dev/video2 --output \"appsrc ! autovideoconvert ! v4l2video11h264enc ! h264parse ! rtph264pay config-interval=1 pt=96 ! udpsink host=192.168.1.70 port=5000 sync=false\" --markerdict TAG36h11 --input tcp:localhost:5777 --markersize 0.235 --calibration calibration/ocam5cr-calibration-640x480.yml\n./vision_landing --input /dev/video2 --output /srv/maverick/data/video/landing.mpg --markerdict TAG36h11 --input tcp:localhost:5777 --markersize 0.235 --width 1280 --height 720 --calibration calibration/ocam5cr-calibration-1280x720.yml\n```\n\n### Mandatory parameters  \n - **connect**: This is the dronekit connection string, eg. /dev/ttyS0 (for serial connection to FC), tcp:localhost:5770 (tcp connection to mavproxy), udp:localhost:14560 (udp connection to mavproxy).\n - **markersize**: This is the size of the fiducial marker in meters.  So a typical april tag printed on A3 will be around 23.5cm from black edge to black edge, so the value here would be 0.235.\n - **calibration**: This is the file containing calibration data, eg. calibration/ocam5cr-calibration-640x480.yml\n\n### Optional parameters  \n** Note that the --fakerangefinder flag is needed unless you have a proper laser rangefinder or running arducopter >3.5-rc2 **  \n - **--input**: This is the video stream 'pipeline' used to look for targets.  It defaults to /dev/video0 which is what most USB cameras show up as (/dev/video2 typically for odroid xu4 with hardware encoding activated).  Video files can be used for testing by just specifying the video file name here.  A gstreamer pipeline can also be used here as long as it ends in appsink (eg. v4l2src device=/dev/video2 ! decodebin ! videoconvert ! appsink)\n - **--output**: This is the output 'pipeline' that can be used to save the video stream with AR data overlaid.  This can either be a video file name (which will be uncompressed and very large), or you can create gstreamer pipelines.  Example pipeline for odroid xu4 with hardware encoding activated to stream h264 compressed video with AR markers in realtime would be (note gstreamer pipeline must start with appsrc):   \n  ```appsrc ! autovideoconvert ! v4l2video11h264enc ! h264parse ! rtph264pay config-interval=1 pt=96 ! udpsink host=192.168.1.x port=5000 sync=false```\n - **--markerid**: Specify a marker ID to detect.  If specified, only a target matching this ID will be used for landing and any other target will be rejected.  If not specified, all targets in the specified or default dictionary will be detected and the closest will be chosen for landing.\n - **--markerdict**: Type of marker dictionary to use.  Only one dictionary can be detected at any one time.  Supported dictionaries are: ARUCO ARUCO_MIP_16h3 ARUCO_MIP_25h7 ARUCO_MIP_36h12 ARTOOLKITPLUS ARTOOLKITPLUSBCH TAG16h5 TAG25h7 TAG25h9 TAG36h11 TAG36h10.  Defaults to ARUCO_MIP_36h12.\n - **--simulator**: If this flag is set, when the dronekit connection is made the script will wait for prearm checks to pass and then take off to preset altitude and then initiate landing.  This is typically used when connecting to SITL simulator to test precision landing.\n - **--width**: Set the width of the incoming video stream.  Note that camera intrinsics are resized but this will only work if the area of camera is sensor is the same as the calibration.  If a different aspect ratio is used then an appropriate calibration should be used, ie. 1280x720 resolution will not work with 640x480 calibration data.\n - **--height**: As width, but for height.\n - **--fps**: This attempts to set frames per second of incoming video but this is often not supported by the camera driver.  It can be used as a 'fudge factor' if saved video files look too fast or slow.\n - **--brightness**: This can be used to increase or decrease gain or brightness in high or low light conditions.\n - **--fakerangefinder**: This flag tells vision_landing to also send fake rangefinder data based on distance detected from a selected target.  This is necessary for arducopter firmware <3.5-rc2.\n - **--verbose**: Turn on some extra info/debug output\n\n## Intel RealSense enhancements\nThe *realsense* branch of this project adds some enhancements when using an Intel RealSense camera.  These units actually have three cameras inside - a color RGB camera, two near-InfraRed cameras, and they also have a laser projector for throwing IR patterns onto flat surfaces that are otherwise hard to map.  From the two infrared cameras, a depth map is calculated.  All of this is done in custom ASIC hardware on the unit so no additional processing is necessary on the host computer.  In addition, the units are factory calibrated and intrinsic calibration data is automatically available for each individual unit through the librealsense library/api.  They are an excellent, cheap option for obtaining stereo depth data.  \nHowever, for the purposes of vision_landing they have advantages and disadvantages.  On the downside, the cameras are very low quality mobile-pinhole type lenses/sensors.  They are configured by default for indoor use, and configuring them for outdoor use is tricky.  In particular, the color RGB camera is very poor and is terrible at high contrasting colours - unfortunately exactly what the landing markers are - the white bleeds onto the black and makes detection difficult and unreliable.  On the upside, the two IR cameras are global shutter and high framerate (up to 90fps).  This makes them actually very good for Computer Vision, and excellent results can be obtained using these cameras.  It seems that the toner of laser printers absorb IR very well, so targets printed on a laser printer have excellent contrast to the IR cameras and are very clear from altitude.  In addition, the streams from the three cameras can be read simultaneously, as well as the synthetic streams for depth, and corrected and synchronised streams between the cameras.  This means we can use the IR camera for the marker detection and estimation, and use either the color stream or depth mapping for visualisation.  \n"
  },
  {
    "path": "calibration/aruco_calibration_board_a4.yml",
    "content": "%YAML:1.0\naruco_bc_dict: ARUCO_MIP_36h12\naruco_bc_nmarkers: 20\naruco_bc_mInfoType: 0\naruco_bc_markers:\n   - { id:161, corners:[ [ -1250., -1450., 0. ], [ -750., -1450., 0. ],\n       [ -750., -1950., 0. ], [ -1250., -1950., 0. ] ] }\n   - { id:227, corners:[ [ -250., -1450., 0. ], [ 250., -1450., 0. ], [\n       250., -1950., 0. ], [ -250., -1950., 0. ] ] }\n   - { id:85, corners:[ [ 750., -1450., 0. ], [ 1250., -1450., 0. ], [\n       1250., -1950., 0. ], [ 750., -1950., 0. ] ] }\n   - { id:166, corners:[ [ -750., -950., 0. ], [ -250., -950., 0. ], [\n       -250., -1450., 0. ], [ -750., -1450., 0. ] ] }\n   - { id:244, corners:[ [ 250., -950., 0. ], [ 750., -950., 0. ], [\n       750., -1450., 0. ], [ 250., -1450., 0. ] ] }\n   - { id:144, corners:[ [ -1250., -450., 0. ], [ -750., -450., 0. ], [\n       -750., -950., 0. ], [ -1250., -950., 0. ] ] }\n   - { id:90, corners:[ [ -250., -450., 0. ], [ 250., -450., 0. ], [\n       250., -950., 0. ], [ -250., -950., 0. ] ] }\n   - { id:214, corners:[ [ 750., -450., 0. ], [ 1250., -450., 0. ], [\n       1250., -950., 0. ], [ 750., -950., 0. ] ] }\n   - { id:153, corners:[ [ -750., 50., 0. ], [ -250., 50., 0. ], [ -250.,\n       -450., 0. ], [ -750., -450., 0. ] ] }\n   - { id:7, corners:[ [ 250., 50., 0. ], [ 750., 50., 0. ], [ 750.,\n       -450., 0. ], [ 250., -450., 0. ] ] }\n   - { id:143, corners:[ [ -1250., 550., 0. ], [ -750., 550., 0. ], [\n       -750., 50., 0. ], [ -1250., 50., 0. ] ] }\n   - { id:219, corners:[ [ -250., 550., 0. ], [ 250., 550., 0. ], [ 250.,\n       50., 0. ], [ -250., 50., 0. ] ] }\n   - { id:78, corners:[ [ 750., 550., 0. ], [ 1250., 550., 0. ], [ 1250.,\n       50., 0. ], [ 750., 50., 0. ] ] }\n   - { id:159, corners:[ [ -750., 1050., 0. ], [ -250., 1050., 0. ], [\n       -250., 550., 0. ], [ -750., 550., 0. ] ] }\n   - { id:209, corners:[ [ 250., 1050., 0. ], [ 750., 1050., 0. ], [\n       750., 550., 0. ], [ 250., 550., 0. ] ] }\n   - { id:13, corners:[ [ -1250., 1550., 0. ], [ -750., 1550., 0. ], [\n       -750., 1050., 0. ], [ -1250., 1050., 0. ] ] }\n   - { id:247, corners:[ [ -250., 1550., 0. ], [ 250., 1550., 0. ], [\n       250., 1050., 0. ], [ -250., 1050., 0. ] ] }\n   - { id:237, corners:[ [ 750., 1550., 0. ], [ 1250., 1550., 0. ], [\n       1250., 1050., 0. ], [ 750., 1050., 0. ] ] }\n   - { id:100, corners:[ [ -750., 2050., 0. ], [ -250., 2050., 0. ], [\n       -250., 1550., 0. ], [ -750., 1550., 0. ] ] }\n   - { id:6, corners:[ [ 250., 2050., 0. ], [ 750., 2050., 0. ], [ 750.,\n       1550., 0. ], [ 250., 1550., 0. ] ] }\n"
  },
  {
    "path": "calibration/d435-1280x720.yml",
    "content": "%YAML:1.0\n---\nimage_width: 1280\nimage_height: 720\ncamera_matrix: !!opencv-matrix\n   rows: 3\n   cols: 3\n   dt: d\n   data: [ 9.5184581361560402e+02, 0., 6.9603166699329518e+02, 0.,\n       8.5119274893929366e+02, 3.5100439081567129e+02, 0., 0., 1. ]\ndistortion_coefficients: !!opencv-matrix\n   rows: 1\n   cols: 5\n   dt: d\n   data: [ 1.3354150548207788e-01, -4.2352076836541502e-03,\n       7.2103047346773974e-02, -6.6299211011281861e-02,\n       -2.0028506424249306e+00 ]\n"
  },
  {
    "path": "calibration/d435-640x480.yml",
    "content": "%YAML:1.0\n---\nimage_width: 640\nimage_height: 480\ncamera_matrix: !!opencv-matrix\n   rows: 3\n   cols: 3\n   dt: f\n   data: [ 2.12665997e+01, 0., 3.91298920e+02, 0., 1.00516953e+02,\n       1.99458557e+02, 0., 0., 1. ]\ndistortion_coefficients: !!opencv-matrix\n   rows: 1\n   cols: 5\n   dt: f\n   data: [ -7.61123234e-03, 8.11523496e-05, -1.29759137e-03,\n       1.34489697e-03, -2.41024395e-07 ]\n"
  },
  {
    "path": "calibration/ocam5cr-calibration-1280x720.yml",
    "content": "%YAML:1.0\n---\nimage_width: 1280\nimage_height: 720\ncamera_matrix: !!opencv-matrix\n   rows: 3\n   cols: 3\n   dt: d\n   data: [ 1.3440884040820424e+03, 0., 6.9905156745199122e+02, 0.,\n       1.3467815094749353e+03, 3.8248170253646941e+02, 0., 0., 1. ]\ndistortion_coefficients: !!opencv-matrix\n   rows: 1\n   cols: 5\n   dt: d\n   data: [ -4.7871621275114645e-01, 5.4981010471419212e-01,\n       -2.5231381980395746e-03, -7.2442090246576209e-04,\n       -6.5971250176164065e-01 ]\n"
  },
  {
    "path": "calibration/ocam5cr-calibration-640x480.alt.yml",
    "content": "%YAML:1.0\n---\nimage_width: 640\nimage_height: 480\ncamera_matrix: !!opencv-matrix\n   rows: 3\n   cols: 3\n   dt: d\n   data: [ 6.6121494917337247e+02, 0., 3.2828841718686101e+02, 0.,\n       6.5618744814267620e+02, 1.9107124426366272e+02, 0., 0., 1. ]\ndistortion_coefficients: !!opencv-matrix\n   rows: 1\n   cols: 5\n   dt: d\n   data: [ -4.2521027321415589e-01, 1.6184870648672697e-01,\n       1.0785595182920660e-02, -4.6897192269970264e-03,\n       8.5242077077199302e-03 ]\n"
  },
  {
    "path": "calibration/ocam5cr-calibration-640x480.yml",
    "content": "%YAML:1.0\n---\nimage_width: 640\nimage_height: 480\ncamera_matrix: !!opencv-matrix\n   rows: 3\n   cols: 3\n   dt: d\n   data: [ 5.9735378164978681e+02, 0., 3.2679919454715503e+02, 0.,\n       6.0372905645583614e+02, 2.8010613705134386e+02, 0., 0., 1. ]\ndistortion_coefficients: !!opencv-matrix\n   rows: 1\n   cols: 5\n   dt: d\n   data: [ -3.9267258438550706e-01, 2.3586462855322002e-01,\n       -1.0512656347201383e-02, -6.8267662796361807e-04,\n       -1.3795994095762154e-01 ]\n"
  },
  {
    "path": "calibration/r200-calibration-1280x720.yml",
    "content": "%YAML:1.0\n---\nimage_width: 1280\nimage_height: 720\ncamera_matrix: !!opencv-matrix\n   rows: 3\n   cols: 3\n   dt: d\n   data: [ 9.2816139520991885e+02, 0., 6.4301704018620785e+02, 0.,\n       9.2778873253260781e+02, 3.7498666412608128e+02, 0., 0., 1. ]\ndistortion_coefficients: !!opencv-matrix\n   rows: 1\n   cols: 5\n   dt: d\n   data: [ 9.5751948597244715e-02, -6.5241365732573608e-01,\n       -2.0828586224311361e-03, -7.0621354398648674e-04,\n       8.7552357956889237e-01 ]\n"
  },
  {
    "path": "calibration/r200-calibration-1920x1080.yml",
    "content": "%YAML:1.0\n---\nimage_width: 1920\nimage_height: 1080\ncamera_matrix: !!opencv-matrix\n   rows: 3\n   cols: 3\n   dt: d\n   data: [ 1.4302707103631117e+03, 0., 9.8298453177709575e+02, 0.,\n       1.4290231496186070e+03, 5.6279173856551881e+02, 0., 0., 1. ]\ndistortion_coefficients: !!opencv-matrix\n   rows: 1\n   cols: 5\n   dt: d\n   data: [ 8.4267570788474924e-02, -6.2358151257688899e-01,\n       8.3815550773588268e-04, 2.1128443195196503e-03,\n       9.3539169816479428e-01 ]\n"
  },
  {
    "path": "calibration/r200-calibration-640x480.yml",
    "content": "%YAML:1.0\n---\nimage_width: 640\nimage_height: 480\ncamera_matrix: !!opencv-matrix\n   rows: 3\n   cols: 3\n   dt: d\n   data: [ 6.0783617044102618e+02, 0., 3.1581780741003723e+02, 0.,\n       6.1120408601302597e+02, 2.5008129529549603e+02, 0., 0., 1. ]\ndistortion_coefficients: !!opencv-matrix\n   rows: 1\n   cols: 5\n   dt: d\n   data: [ 1.4816645713462362e-01, -1.0182391728955875e+00,\n       -1.8143434742778767e-03, -3.6992078893083903e-03,\n       1.4676077663793050e+00 ]\n"
  },
  {
    "path": "calibration/raspicamv1-calibration-1280x720.yml",
    "content": "%YAML:1.0\n---\nimage_width: 1280\nimage_height: 720\ncamera_matrix: !!opencv-matrix\n   rows: 3\n   cols: 3\n   dt: d\n   data: [ 1.0870591972997881e+03, 0., 5.1985156867369221e+02, 0.,\n       1.1095304896744867e+03, 6.5370374660295761e+02, 0., 0., 1. ]\ndistortion_coefficients: !!opencv-matrix\n   rows: 1\n   cols: 5\n   dt: d\n   data: [ 6.7506039599485021e-02, -5.9048530625047245e-02,\n       1.7155220868880776e-03, -5.2020426468591507e-02,\n       2.7634211934173425e-02 ]\n"
  },
  {
    "path": "calibration/raspicamv1-calibration-640x480.yml",
    "content": "%YAML:1.0\n---\nimage_width: 640\nimage_height: 480\ncamera_matrix: !!opencv-matrix\n   rows: 3\n   cols: 3\n   dt: d\n   data: [ 6.5896698580363773e+02, 0., 3.1002321894647190e+02, 0.,\n       6.5682077412787862e+02, 2.3106121559640056e+02, 0., 0., 1. ]\ndistortion_coefficients: !!opencv-matrix\n   rows: 1\n   cols: 5\n   dt: d\n   data: [ 1.1852650267166695e-01, -5.1934013894639219e-01,\n       -3.0733227337306872e-03, -5.5608500948949660e-03,\n       2.6916737484502573e-01 ]\n"
  },
  {
    "path": "calibration/raspicamv2-calibration-640x480.yml",
    "content": "%YAML:1.0\n---\nimage_width: 640\nimage_height: 480\ncamera_matrix: !!opencv-matrix\n   rows: 3\n   cols: 3\n   dt: d\n   data: [ 4.9260281220532505e+02, 0., 3.2983271307718115e+02, 0.,\n       4.9185805133583187e+02, 2.4829905879256435e+02, 0., 0., 1. ]\ndistortion_coefficients: !!opencv-matrix\n   rows: 1\n   cols: 5\n   dt: d\n   data: [ 1.7239420667429373e-01, -5.5553264866253949e-01,\n       2.4128347703893300e-03, 2.7407429940248681e-03,\n       4.9313531402738187e-01 ]\n"
  },
  {
    "path": "calibration/sj4000-calibration-1280x720.yml",
    "content": "%YAML:1.0\n---\nimage_width: 1280\nimage_height: 720\ncamera_matrix: !!opencv-matrix\n   rows: 3\n   cols: 3\n   dt: d\n   data: [ 1.8593258445340257e+03, 0., 6.3832828268340643e+02, 0.,\n       1.7109359494675668e+03, 3.4853591106543831e+02, 0., 0., 1. ]\ndistortion_coefficients: !!opencv-matrix\n   rows: 1\n   cols: 5\n   dt: d\n   data: [ -7.3405019069485866e-01, 7.3735108609330446e-01,\n       2.6216434201067888e-02, 7.1663397680407998e-02,\n       1.2758125148276322e+00 ]\n"
  },
  {
    "path": "calibration/sj4000-calibration-640x480.yml",
    "content": "%YAML:1.0\n---\nimage_width: 640\nimage_height: 480\ncamera_matrix: !!opencv-matrix\n   rows: 3\n   cols: 3\n   dt: d\n   data: [ 3.7037165052172065e+02, 0., 3.1804464317636484e+02, 0.,\n       3.6986507401947409e+02, 2.3433401660781536e+02, 0., 0., 1. ]\ndistortion_coefficients: !!opencv-matrix\n   rows: 1\n   cols: 5\n   dt: d\n   data: [ -3.0928475932553318e-01, 1.1286735280595565e-01,\n       2.7916987103310091e-04, 2.9956904211408351e-04,\n       -1.9893030862940957e-02 ]\n"
  },
  {
    "path": "markers/2x2map.yml",
    "content": "%YAML:1.0\n---\naruco_bc_dict: ARUCO_MIP_36h12\naruco_bc_nmarkers: 4\naruco_bc_mInfoType: 0\naruco_bc_markers:\n   - { id:161, corners:[ [ -550., -50., 0. ], [ -50., -50., 0. ], [ -50.,\n       -550., 0. ], [ -550., -550., 0. ] ] }\n   - { id:227, corners:[ [ 50., -50., 0. ], [ 550., -50., 0. ], [ 550.,\n       -550., 0. ], [ 50., -550., 0. ] ] }\n   - { id:85, corners:[ [ -550., 550., 0. ], [ -50., 550., 0. ], [ -50.,\n       50., 0. ], [ -550., 50., 0. ] ] }\n   - { id:166, corners:[ [ 50., 550., 0. ], [ 550., 550., 0. ], [ 550.,\n       50., 0. ], [ 50., 50., 0. ] ] }\n"
  },
  {
    "path": "src/CMakeLists.txt",
    "content": "cmake_minimum_required (VERSION 2.8)\nproject (track_targets)\nfind_package(aruco REQUIRED )\nfind_package(OpenCV REQUIRED)\n\noption(USE_TIMERS \"Set to OFF to disable timers\" OFF)\niF(USE_TIMERS)\nadd_definitions(-DUSE_TIMERS)\nENDIF()\n\nadd_executable(track_targets track_targets.cpp)\n\nset(EXTRA_C_FLAGS_RELEASE \"${EXTRA_C_FLAGS_RELEASE} -std=c++0x -pthread -march=armv8-a+crc -mfpu=neon-vfpv4 -mtune=cortex-a53 -ftree-vectorize -mfloat-abi=hard -O3 \")\nset(cpp_compile_flags \"-std=gnu++11 -pthread\")\nadd_definitions(${cpp_compile_flags})\n\ninclude_directories(${aruco_INCLUDE_DIRS} ${OpenCV_INCLUDE_DIRS})\ntarget_link_libraries(track_targets aruco ${aruco_LIBS} ${OpenCV_LIBS} pthread)\nlink_directories(${aruco_LIB_DIR} ${OpenCV_INSTALL_PATH}/lib})\nlink_libraries(pthread)\ninstall(PROGRAMS track_targets DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/..)\n\nset(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -latomic\")\n"
  },
  {
    "path": "src/args.hxx",
    "content": "/* Copyright (c) 2016 Taylor C. Richberger <taywee@gmx.com>\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\n// https://github.com/Taywee/args\n\n/** \\file args.hxx\n * \\brief this single-header lets you use all of the args functionality\n *\n * The important stuff is done inside the args namespace\n */\n\n#ifndef ARGS_HXX\n#define ARGS_HXX\n\n#include <algorithm>\n#include <exception>\n#include <functional>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <vector>\n#include <unordered_map>\n#include <unordered_set>\n#include <type_traits>\n\n#ifdef ARGS_TESTNAMESPACE\nnamespace argstest\n{\n#else\n\n/** \\namespace args\n * \\brief contains all the functionality of the args library\n */\nnamespace args\n{\n#endif\n    /** Getter to grab the value from the argument type.\n     *\n     * If the Get() function of the type returns a reference, so does this, and\n     * the value will be modifiable.\n     */\n    template <typename Option>\n    auto get(Option &option_) -> decltype(option_.Get())\n    {\n        return option_.Get();\n    }\n\n    /** (INTERNAL) Count UTF-8 glyphs\n     *\n     * This is not reliable, and will fail for combinatory glyphs, but it's\n     * good enough here for now.\n     *\n     * \\param string The string to count glyphs from\n     * \\return The UTF-8 glyphs in the string\n     */\n    std::string::size_type Glyphs(const std::string &string_)\n    {\n        std::string::size_type length = 0;\n        for (const char c: string_)\n        {\n            if ((c & 0xc0) != 0x80)\n            {\n                ++length;\n            }\n        }\n        return length;\n    }\n\n    /** (INTERNAL) Wrap a string into a vector of lines\n     *\n     * This is quick and hacky, but works well enough.  You can specify a\n     * different width for the first line\n     *\n     * \\param width The width of the body\n     * \\param the widtho f the first line, defaults to the width of the body\n     * \\return the vector of lines\n     */\n    std::vector<std::string> Wrap(const std::string &in, const std::string::size_type width, std::string::size_type firstlinewidth = 0)\n    {\n        // Preserve existing line breaks\n        const auto newlineloc = in.find('\\n');\n        if (newlineloc != in.npos)\n        {\n            auto first = Wrap(std::string(in, 0, newlineloc), width);\n            auto second = Wrap(std::string(in, newlineloc + 1), width);\n            first.insert(\n                std::end(first),\n                std::make_move_iterator(std::begin(second)),\n                std::make_move_iterator(std::end(second)));\n            return first;\n        }\n        if (firstlinewidth == 0)\n        {\n            firstlinewidth = width;\n        }\n        auto currentwidth = firstlinewidth;\n\n        std::istringstream stream(in);\n        std::vector<std::string> output;\n        std::ostringstream line;\n        std::string::size_type linesize = 0;\n        while (stream)\n        {\n            std::string item;\n            stream >> item;\n            auto itemsize = Glyphs(item);\n            if ((linesize + 1 + itemsize) > currentwidth)\n            {\n                if (linesize > 0)\n                {\n                    output.push_back(line.str());\n                    line.str(std::string());\n                    linesize = 0;\n                    currentwidth = width;\n                }\n            }\n            if (itemsize > 0)\n            {\n                if (linesize)\n                {\n                    ++linesize;\n                    line << \" \";\n                }\n                line << item;\n                linesize += itemsize;\n            }\n        }\n        if (linesize > 0)\n        {\n            output.push_back(line.str());\n        }\n        return output;\n    }\n\n#ifdef ARGS_NOEXCEPT\n    /// Error class, for when ARGS_NOEXCEPT is defined\n    enum class Error\n    {\n        None,\n        Usage,\n        Parse,\n        Validation,\n        Map,\n        Extra,\n        Help\n    };\n#else\n    /** Base error class\n     */\n    class Error : public std::runtime_error\n    {\n        public:\n            Error(const std::string &problem) : std::runtime_error(problem) {}\n            virtual ~Error() {};\n    };\n\n    /** Errors that occur during usage\n     */\n    class UsageError : public Error\n    {\n        public:\n            UsageError(const std::string &problem) : Error(problem) {}\n            virtual ~UsageError() {};\n    };\n\n    /** Errors that occur during regular parsing\n     */\n    class ParseError : public Error\n    {\n        public:\n            ParseError(const std::string &problem) : Error(problem) {}\n            virtual ~ParseError() {};\n    };\n\n    /** Errors that are detected from group validation after parsing finishes\n     */\n    class ValidationError : public Error\n    {\n        public:\n            ValidationError(const std::string &problem) : Error(problem) {}\n            virtual ~ValidationError() {};\n    };\n\n    /** Errors in map lookups\n     */\n    class MapError : public ParseError\n    {\n        public:\n            MapError(const std::string &problem) : ParseError(problem) {}\n            virtual ~MapError() {};\n    };\n\n    /** Error that occurs when a singular flag is specified multiple times\n     */\n    class ExtraError : public ParseError\n    {\n        public:\n            ExtraError(const std::string &problem) : ParseError(problem) {}\n            virtual ~ExtraError() {};\n    };\n\n    /** An exception that indicates that the user has requested help\n     */\n    class Help : public Error\n    {\n        public:\n            Help(const std::string &flag) : Error(flag) {}\n            virtual ~Help() {};\n    };\n#endif\n\n    /** A simple unified option type for unified initializer lists for the Matcher class.\n     */\n    struct EitherFlag\n    {\n        const bool isShort;\n        const char shortFlag;\n        const std::string longFlag;\n        EitherFlag(const std::string &flag) : isShort(false), shortFlag(), longFlag(flag) {}\n        EitherFlag(const char *flag) : isShort(false), shortFlag(), longFlag(flag) {}\n        EitherFlag(const char flag) : isShort(true), shortFlag(flag), longFlag() {}\n\n        /** Get just the long flags from an initializer list of EitherFlags\n         */\n        static std::unordered_set<std::string> GetLong(std::initializer_list<EitherFlag> flags)\n        {\n            std::unordered_set<std::string>  longFlags;\n            for (const EitherFlag &flag: flags)\n            {\n                if (!flag.isShort)\n                {\n                    longFlags.insert(flag.longFlag);\n                }\n            }\n            return longFlags;\n        }\n\n        /** Get just the short flags from an initializer list of EitherFlags\n         */\n        static std::unordered_set<char> GetShort(std::initializer_list<EitherFlag> flags)\n        {\n            std::unordered_set<char>  shortFlags;\n            for (const EitherFlag &flag: flags)\n            {\n                if (flag.isShort)\n                {\n                    shortFlags.insert(flag.shortFlag);\n                }\n            }\n            return shortFlags;\n        }\n    };\n\n\n\n    /** A class of \"matchers\", specifying short and flags that can possibly be\n     * matched.\n     *\n     * This is supposed to be constructed and then passed in, not used directly\n     * from user code.\n     */\n    class Matcher\n    {\n        private:\n            const std::unordered_set<char> shortFlags;\n            const std::unordered_set<std::string> longFlags;\n\n        public:\n            /** Specify short and long flags separately as iterators\n             *\n             * ex: `args::Matcher(shortFlags.begin(), shortFlags.end(), longFlags.begin(), longFlags.end())`\n             */\n            template <typename ShortIt, typename LongIt>\n            Matcher(ShortIt shortFlagsStart, ShortIt shortFlagsEnd, LongIt longFlagsStart, LongIt longFlagsEnd) :\n                shortFlags(shortFlagsStart, shortFlagsEnd),\n                longFlags(longFlagsStart, longFlagsEnd)\n            {}\n\n            /** Specify short and long flags separately as iterables\n             *\n             * ex: `args::Matcher(shortFlags, longFlags)`\n             */\n            template <typename Short, typename Long>\n            Matcher(Short &&shortIn, Long &&longIn) :\n                shortFlags(std::begin(shortIn), std::end(shortIn)), longFlags(std::begin(longIn), std::end(longIn))\n            {}\n\n            /** Specify a mixed single initializer-list of both short and long flags\n             *\n             * This is the fancy one.  It takes a single initializer list of\n             * any number of any mixed kinds of flags.  Chars are\n             * automatically interpreted as short flags, and strings are\n             * automatically interpreted as long flags:\n             *\n             *     args::Matcher{'a'}\n             *     args::Matcher{\"foo\"}\n             *     args::Matcher{'h', \"help\"}\n             *     args::Matcher{\"foo\", 'f', 'F', \"FoO\"}\n             */\n            Matcher(std::initializer_list<EitherFlag> in) :\n                shortFlags(EitherFlag::GetShort(in)), longFlags(EitherFlag::GetLong(in)) {}\n\n            Matcher(Matcher &&other) : shortFlags(std::move(other.shortFlags)), longFlags(std::move(other.longFlags))\n            {}\n\n            ~Matcher() {}\n\n            /** (INTERNAL) Check if there is a match of a short flag\n             */\n            bool Match(const char flag) const\n            {\n                return shortFlags.find(flag) != shortFlags.end();\n            }\n\n            /** (INTERNAL) Check if there is a match of a long flag\n             */\n            bool Match(const std::string &flag) const\n            {\n                return longFlags.find(flag) != longFlags.end();\n            }\n\n            /** (INTERNAL) Get all flag strings as a vector, with the prefixes embedded\n             */\n            std::vector<std::string> GetFlagStrings(const std::string &shortPrefix, const std::string &longPrefix) const\n            {\n                std::vector<std::string> flagStrings;\n                flagStrings.reserve(shortFlags.size() + longFlags.size());\n                for (const char flag: shortFlags)\n                {\n                    flagStrings.emplace_back(shortPrefix + std::string(1, flag));\n                }\n                for (const std::string &flag: longFlags)\n                {\n                    flagStrings.emplace_back(longPrefix + flag);\n                }\n                return flagStrings;\n            }\n\n            /** (INTERNAL) Get all flag strings as a vector, with the prefixes and names embedded\n             */\n            std::vector<std::string> GetFlagStrings(const std::string &shortPrefix, const std::string &longPrefix, const std::string &name, const std::string &shortSeparator, const std::string longSeparator) const\n            {\n                const std::string bracedname(std::string(\"[\") + name + \"]\");\n                std::vector<std::string> flagStrings;\n                flagStrings.reserve(shortFlags.size() + longFlags.size());\n                for (const char flag: shortFlags)\n                {\n                    flagStrings.emplace_back(shortPrefix + std::string(1, flag) + shortSeparator + bracedname);\n                }\n                for (const std::string &flag: longFlags)\n                {\n                    flagStrings.emplace_back(longPrefix + flag + longSeparator + bracedname);\n                }\n                return flagStrings;\n            }\n    };\n\n    /** Base class for all match types\n     */\n    class Base\n    {\n        protected:\n            bool matched;\n            const std::string help;\n#ifdef ARGS_NOEXCEPT\n            /// Only for ARGS_NOEXCEPT\n            Error error;\n#endif\n\n        public:\n            Base(const std::string &help_) : matched(false), help(help_) {}\n            virtual ~Base() {}\n\n            virtual bool Matched() const noexcept\n            {\n                return matched;\n            }\n\n            operator bool() const noexcept\n            {\n                return Matched();\n            }\n\n            virtual std::tuple<std::string, std::string> GetDescription(const std::string &shortPrefix, const std::string &longPrefix, const std::string &shortSeparator, const std::string &longSeparator) const\n            {\n                std::tuple<std::string, std::string> description;\n                std::get<1>(description) = help;\n                return description;\n            }\n\n            virtual void Reset() noexcept\n            {\n                matched = false;\n#ifdef ARGS_NOEXCEPT\n                error = Error::None;\n#endif\n            }\n\n#ifdef ARGS_NOEXCEPT\n            /// Only for ARGS_NOEXCEPT\n            virtual Error GetError() const\n            {\n                return error;\n            }\n#endif\n    };\n\n    /** Base class for all match types that have a name\n     */\n    class NamedBase : public Base\n    {\n        protected:\n            const std::string name;\n            bool kickout;\n\n        public:\n            NamedBase(const std::string &name_, const std::string &help_) : Base(help_), name(name_), kickout(false) {}\n            virtual ~NamedBase() {}\n\n            virtual std::tuple<std::string, std::string> GetDescription(const std::string &shortPrefix, const std::string &longPrefi, const std::string &shortSeparator, const std::string &longSeparator) const override\n            {\n                std::tuple<std::string, std::string> description;\n                std::get<0>(description) = Name();\n                std::get<1>(description) = help;\n                return description;\n            }\n            virtual std::string Name() const\n            {\n                return name;\n            }\n\n            /// Sets a kick-out value for building subparsers\n            void KickOut(bool kickout_) noexcept\n            {\n                this->kickout = kickout_;\n            }\n\n            /// Gets the kick-out value for building subparsers\n            bool KickOut() const noexcept\n            {\n                return kickout;\n            }\n    };\n\n    /** Base class for all flag options\n     */\n    class FlagBase : public NamedBase\n    {\n        private:\n            const bool extraError;\n\n        protected:\n            const Matcher matcher;\n\n        public:\n            FlagBase(const std::string &name_, const std::string &help_, Matcher &&matcher_, const bool extraError_ = false) : NamedBase(name_, help_), extraError(extraError_), matcher(std::move(matcher_)) {}\n\n            virtual ~FlagBase() {}\n\n            virtual FlagBase *Match(const std::string &flag)\n            {\n                if (matcher.Match(flag))\n                {\n                    if (extraError && matched)\n                    {\n#ifdef ARGS_NOEXCEPT\n                        error = Error::Extra;\n#else\n                        std::ostringstream problem;\n                        problem << \"Flag '\" << flag << \"' was passed multiple times, but is only allowed to be passed once\";\n                        throw ExtraError(problem.str());\n#endif\n                    }\n                    matched = true;\n                    return this;\n                }\n                return nullptr;\n            }\n\n            virtual FlagBase *Match(const char flag)\n            {\n                if (matcher.Match(flag))\n                {\n                    if (extraError && matched)\n                    {\n#ifdef ARGS_NOEXCEPT\n                        error = Error::Extra;\n#else\n                        std::ostringstream problem;\n                        problem << \"Flag '\" << flag << \"' was passed multiple times, but is only allowed to be passed once\";\n                        throw ExtraError(problem.str());\n#endif\n                    }\n                    matched = true;\n                    return this;\n                }\n                return nullptr;\n            }\n\n            virtual std::tuple<std::string, std::string> GetDescription(const std::string &shortPrefix, const std::string &longPrefix, const std::string &shortSeparator, const std::string &longSeparator) const override\n            {\n                std::tuple<std::string, std::string> description;\n                const auto flagStrings = matcher.GetFlagStrings(shortPrefix, longPrefix);\n                std::ostringstream flagstream;\n                for (auto it = std::begin(flagStrings); it != std::end(flagStrings); ++it)\n                {\n                    if (it != std::begin(flagStrings))\n                    {\n                        flagstream << \", \";\n                    }\n                    flagstream << *it;\n                }\n                std::get<0>(description) = flagstream.str();\n                std::get<1>(description) = help;\n                return description;\n            }\n    };\n\n    /** Base class for value-accepting flag options\n     */\n    class ValueFlagBase : public FlagBase\n    {\n        public:\n            ValueFlagBase(const std::string &name_, const std::string &help_, Matcher &&matcher_, const bool extraError_ = false) : FlagBase(name_, help_, std::move(matcher_), extraError_) {}\n            virtual ~ValueFlagBase() {}\n            virtual void ParseValue(const std::string &value) = 0;\n\n            virtual std::tuple<std::string, std::string> GetDescription(const std::string &shortPrefix, const std::string &longPrefix, const std::string &shortSeparator, const std::string &longSeparator) const override\n            {\n                std::tuple<std::string, std::string> description;\n                const auto flagStrings = matcher.GetFlagStrings(shortPrefix, longPrefix, Name(), shortSeparator, longSeparator);\n                std::ostringstream flagstream;\n                for (auto it = std::begin(flagStrings); it != std::end(flagStrings); ++it)\n                {\n                    if (it != std::begin(flagStrings))\n                    {\n                        flagstream << \", \";\n                    }\n                    flagstream << *it;\n                }\n                std::get<0>(description) = flagstream.str();\n                std::get<1>(description) = help;\n                return description;\n            }\n    };\n\n    /** Base class for positional options\n     */\n    class PositionalBase : public NamedBase\n    {\n        protected:\n            bool ready;\n\n        public:\n            PositionalBase(const std::string &name_, const std::string &help_) : NamedBase(name_, help_), ready(true) {}\n            virtual ~PositionalBase() {}\n\n            bool Ready()\n            {\n                return ready;\n            }\n\n            virtual void ParseValue(const std::string &value_) = 0;\n\n            virtual void Reset() noexcept override\n            {\n                matched = false;\n                ready = true;\n#ifdef ARGS_NOEXCEPT\n                error = Error::None;\n#endif\n            }\n    };\n\n    /** Class for all kinds of validating groups, including ArgumentParser\n     */\n    class Group : public Base\n    {\n        private:\n            std::vector<Base*> children;\n            std::function<bool(const Group &)> validator;\n\n        public:\n            /** Default validators\n             */\n            struct Validators\n            {\n                static bool Xor(const Group &group)\n                {\n                    return group.MatchedChildren() == 1;\n                }\n\n                static bool AtLeastOne(const Group &group)\n                {\n                    return group.MatchedChildren() >= 1;\n                }\n\n                static bool AtMostOne(const Group &group)\n                {\n                    return group.MatchedChildren() <= 1;\n                }\n\n                static bool All(const Group &group)\n                {\n                    return group.Children().size() == group.MatchedChildren();\n                }\n\n                static bool AllOrNone(const Group &group)\n                {\n                    return (All(group) || None(group));\n                }\n\n                static bool AllChildGroups(const Group &group)\n                {\n                    return std::find_if(std::begin(group.Children()), std::end(group.Children()), [](const Base* child) -> bool {\n                            return dynamic_cast<const Group *>(child) && !child->Matched();\n                            }) == std::end(group.Children());\n                }\n\n                static bool DontCare(const Group &group)\n                {\n                    return true;\n                }\n\n                static bool CareTooMuch(const Group &group)\n                {\n                    return false;\n                }\n\n                static bool None(const Group &group)\n                {\n                    return group.MatchedChildren() == 0;\n                }\n            };\n            /// If help is empty, this group will not be printed in help output\n            Group(const std::string &help_ = std::string(), const std::function<bool(const Group &)> &validator_ = Validators::DontCare) : Base(help_), validator(validator_) {}\n            /// If help is empty, this group will not be printed in help output\n            Group(Group &group_, const std::string &help_ = std::string(), const std::function<bool(const Group &)> &validator_ = Validators::DontCare) : Base(help_), validator(validator_)\n            {\n                group_.Add(*this);\n            }\n            virtual ~Group() {}\n\n            /** Return the first FlagBase that matches flag, or nullptr\n             *\n             * \\param flag The flag with prefixes stripped\n             * \\return the first matching FlagBase pointer, or nullptr if there is no match\n             */\n            template <typename T>\n            FlagBase *Match(const T &flag)\n            {\n                for (Base *child: children)\n                {\n                    if (FlagBase *flagBase = dynamic_cast<FlagBase *>(child))\n                    {\n                        if (FlagBase *match = flagBase->Match(flag))\n                        {\n                            return match;\n                        }\n                    } else if (Group *group = dynamic_cast<Group *>(child))\n                    {\n                        if (FlagBase *match = group->Match(flag))\n                        {\n                            return match;\n                        }\n                    }\n                }\n                return nullptr;\n            }\n\n            /** Get the next ready positional, or nullptr if there is none\n             *\n             * \\return the first ready PositionalBase pointer, or nullptr if there is no match\n             */\n            PositionalBase *GetNextPositional()\n            {\n                for (Base *child: children)\n                {\n                    auto next = dynamic_cast<PositionalBase *>(child);\n                    auto group = dynamic_cast<Group *>(child);\n                    if (group)\n                    {\n                        next = group->GetNextPositional();\n                    }\n                    if (next && next->Ready())\n                    {\n                        return next;\n                    }\n                }\n                return nullptr;\n            }\n\n            /** Get whether this has any FlagBase children\n             *\n             * \\return Whether or not there are any FlagBase children\n             */\n            bool HasFlag() const\n            {\n                for (Base *child: children)\n                {\n                    if (dynamic_cast<FlagBase *>(child))\n                    {\n                        return true;\n                    }\n                    if (auto group = dynamic_cast<Group *>(child))\n                    {\n                        if (group->HasFlag())\n                        {\n                            return true;\n                        }\n                    }\n                }\n                return false;\n            }\n\n            /** Append a child to this Group.\n             */\n            void Add(Base &child)\n            {\n                children.emplace_back(&child);\n            }\n\n            /** Get all this group's children\n             */\n            const std::vector<Base *> &Children() const\n            {\n                return children;\n            }\n\n            /** Count the number of matched children this group has\n             */\n            std::vector<Base *>::size_type MatchedChildren() const\n            {\n                return std::count_if(std::begin(children), std::end(children), [](const Base *child){return child->Matched();});\n            }\n\n            /** Whether or not this group matches validation\n             */\n            virtual bool Matched() const noexcept override\n            {\n                return validator(*this);\n            }\n\n            /** Get validation\n             */\n            bool Get() const\n            {\n                return Matched();\n            }\n\n            /** Get all the child descriptions for help generation\n             */\n            std::vector<std::tuple<std::string, std::string, unsigned int>> GetChildDescriptions(const std::string &shortPrefix, const std::string &longPrefix, const std::string &shortSeparator, const std::string &longSeparator, const unsigned int indent = 0) const\n            {\n                std::vector<std::tuple<std::string, std::string, unsigned int>> descriptions;\n                for (const auto &child: children)\n                {\n                    if (const auto group = dynamic_cast<Group *>(child))\n                    {\n                        // Push that group description on the back if not empty\n                        unsigned char addindent = 0;\n                        if (!group->help.empty())\n                        {\n                            descriptions.emplace_back(group->help, \"\", indent);\n                            addindent = 1;\n                        }\n                        auto groupDescriptions = group->GetChildDescriptions(shortPrefix, longPrefix, shortSeparator, longSeparator, indent + addindent);\n                        descriptions.insert(\n                            std::end(descriptions),\n                            std::make_move_iterator(std::begin(groupDescriptions)),\n                            std::make_move_iterator(std::end(groupDescriptions)));\n                    } else if (const auto named = dynamic_cast<NamedBase *>(child))\n                    {\n                        const auto description = named->GetDescription(shortPrefix, longPrefix, shortSeparator, longSeparator);\n                        descriptions.emplace_back(std::get<0>(description), std::get<1>(description), indent);\n                    }\n                }\n                return descriptions;\n            }\n\n            /** Get the names of positional parameters\n             */\n            std::vector<std::string> GetPosNames() const\n            {\n                std::vector <std::string> names;\n                for (const auto &child: children)\n                {\n                    if (const Group *group = dynamic_cast<Group *>(child))\n                    {\n                        auto groupNames = group->GetPosNames();\n                        names.insert(\n                            std::end(names),\n                            std::make_move_iterator(std::begin(groupNames)),\n                            std::make_move_iterator(std::end(groupNames)));\n                    } else if (const PositionalBase *pos = dynamic_cast<PositionalBase *>(child))\n                    {\n                        names.emplace_back(pos->Name());\n                    }\n                }\n                return names;\n            }\n\n            virtual void Reset() noexcept override\n            {\n                for (auto &child: children)\n                {\n                    child->Reset();\n                }\n#ifdef ARGS_NOEXCEPT\n                error = Error::None;\n#endif\n            }\n\n#ifdef ARGS_NOEXCEPT\n            /// Only for ARGS_NOEXCEPT\n            virtual Error GetError() const override\n            {\n                if (error != Error::None)\n                {\n                    return error;\n                }\n\n                auto it = std::find_if(std::begin(children), std::end(children), [](const Base *child){return child->GetError() != Error::None;});\n                if (it == std::end(children))\n                {\n                    return Error::None;\n                } else\n                {\n                    return (*it)->GetError();\n                }\n            }\n#endif\n\n    };\n\n    /** The main user facing command line argument parser class\n     */\n    class ArgumentParser : public Group\n    {\n        private:\n            std::string prog;\n            std::string proglinePostfix;\n            std::string description;\n            std::string epilog;\n\n            std::string longprefix;\n            std::string shortprefix;\n\n            std::string longseparator;\n\n            std::string terminator;\n\n            bool allowJoinedShortValue;\n            bool allowJoinedLongValue;\n            bool allowSeparateShortValue;\n            bool allowSeparateLongValue;\n\n        public:\n            /** A simple structure of parameters for easy user-modifyable help menus\n             */\n            struct HelpParams\n            {\n                /** The width of the help menu\n                 */\n                unsigned int width = 80;\n                /** The indent of the program line\n                 */\n                unsigned int progindent = 2;\n                /** The indent of the program trailing lines for long parameters\n                 */\n                unsigned int progtailindent = 4;\n                /** The indent of the description and epilogs\n                 */\n                unsigned int descriptionindent = 4;\n                /** The indent of the flags\n                 */\n                unsigned int flagindent = 6;\n                /** The indent of the flag descriptions\n                 */\n                unsigned int helpindent = 40;\n                /** The additional indent each group adds\n                 */\n                unsigned int eachgroupindent = 2;\n\n                /** The minimum gutter between each flag and its help\n                 */\n                unsigned int gutter = 1;\n\n                /** Show the terminator when both options and positional parameters are present\n                 */\n                bool showTerminator = true;\n\n                /** Show the {OPTIONS} on the prog line when this is true\n                 */\n                bool showProglineOptions = true;\n\n                /** Show the positionals on the prog line when this is true\n                 */\n                bool showProglinePositionals = true;\n            } helpParams;\n            ArgumentParser(const std::string &description_, const std::string &epilog_ = std::string()) :\n                Group(\"\", Group::Validators::AllChildGroups),\n                description(description_),\n                epilog(epilog_),\n                longprefix(\"--\"),\n                shortprefix(\"-\"),\n                longseparator(\"=\"),\n                terminator(\"--\"),\n                allowJoinedShortValue(true),\n                allowJoinedLongValue(true),\n                allowSeparateShortValue(true),\n                allowSeparateLongValue(true) {}\n\n            /** The program name for help generation\n             */\n            const std::string &Prog() const\n            { return prog; }\n            /** The program name for help generation\n             */\n            void Prog(const std::string &prog_)\n            { this->prog = prog_; }\n\n            /** The description that appears on the prog line after options\n             */\n            const std::string &ProglinePostfix() const\n            { return proglinePostfix; }\n            /** The description that appears on the prog line after options\n             */\n            void ProglinePostfix(const std::string &proglinePostfix_)\n            { this->proglinePostfix = proglinePostfix_; }\n\n            /** The description that appears above options\n             */\n            const std::string &Description() const\n            { return description; }\n            /** The description that appears above options\n             */\n            void Description(const std::string &description_)\n            { this->description = description_; }\n            \n            /** The description that appears below options\n             */\n            const std::string &Epilog() const\n            { return epilog; }\n            /** The description that appears below options\n             */\n            void Epilog(const std::string &epilog_)\n            { this->epilog = epilog_; }\n\n            /** The prefix for long flags\n             */\n            const std::string &LongPrefix() const\n            { return longprefix; }\n            /** The prefix for long flags\n             */\n            void LongPrefix(const std::string &longprefix_)\n            { this->longprefix = longprefix_; }\n\n            /** The prefix for short flags\n             */\n            const std::string &ShortPrefix() const\n            { return shortprefix; }\n            /** The prefix for short flags\n             */\n            void ShortPrefix(const std::string &shortprefix_)\n            { this->shortprefix = shortprefix_; }\n\n            /** The separator for long flags\n             */\n            const std::string &LongSeparator() const\n            { return longseparator; }\n            /** The separator for long flags\n             */\n            void LongSeparator(const std::string &longseparator_)\n            {\n                if (longseparator_.empty())\n                {\n#ifdef ARGS_NOEXCEPT\n                    error = Error::Usage;\n#else\n                    throw UsageError(\"longseparator can not be set to empty\");\n#endif\n                } else\n                {\n                    this->longseparator = longseparator_;\n                }\n            }\n\n            /** The terminator that forcibly separates flags from positionals\n             */\n            const std::string &Terminator() const\n            { return terminator; }\n            /** The terminator that forcibly separates flags from positionals\n             */\n            void Terminator(const std::string &terminator_)\n            { this->terminator = terminator_; }\n\n            /** Get the current argument separation parameters.\n             *\n             * See SetArgumentSeparations for details on what each one means.\n             */\n            void GetArgumentSeparations(\n                bool &allowJoinedShortValue_,\n                bool &allowJoinedLongValue_,\n                bool &allowSeparateShortValue_,\n                bool &allowSeparateLongValue_) const\n            {\n                allowJoinedShortValue_ = this->allowJoinedShortValue;\n                allowJoinedLongValue_ = this->allowJoinedLongValue;\n                allowSeparateShortValue_ = this->allowSeparateShortValue;\n                allowSeparateLongValue_ = this->allowSeparateLongValue;\n            }\n\n            /** Change allowed option separation.\n             *\n             * \\param allowJoinedShortValue Allow a short flag that accepts an argument to be passed its argument immediately next to it (ie. in the same argv field)\n             * \\param allowJoinedLongValue Allow a long flag that accepts an argument to be passed its argument separated by the longseparator (ie. in the same argv field)\n             * \\param allowSeparateShortValue Allow a short flag that accepts an argument to be passed its argument separated by whitespace (ie. in the next argv field)\n             * \\param allowSeparateLongValue Allow a long flag that accepts an argument to be passed its argument separated by whitespace (ie. in the next argv field)\n             */\n            void SetArgumentSeparations(\n                const bool allowJoinedShortValue_,\n                const bool allowJoinedLongValue_,\n                const bool allowSeparateShortValue_,\n                const bool allowSeparateLongValue_)\n            {\n                this->allowJoinedShortValue = allowJoinedShortValue_;\n                this->allowJoinedLongValue = allowJoinedLongValue_;\n                this->allowSeparateShortValue = allowSeparateShortValue_;\n                this->allowSeparateLongValue = allowSeparateLongValue_;\n            }\n\n            /** Pass the help menu into an ostream\n             */\n            void Help(std::ostream &help) const\n            {\n                bool hasoptions = false;\n                bool hasarguments = false;\n\n                const auto description_text = Wrap(this->description, helpParams.width - helpParams.descriptionindent);\n                const auto epilog_text = Wrap(this->epilog, helpParams.width - helpParams.descriptionindent);\n                std::ostringstream prognameline;\n                prognameline << prog;\n                if (HasFlag())\n                {\n                    hasoptions = true;\n                    if (helpParams.showProglineOptions)\n                    {\n                        prognameline << \" {OPTIONS}\";\n                    }\n                }\n                for (const std::string &posname: GetPosNames())\n                {\n                    hasarguments = true;\n                    if (helpParams.showProglinePositionals)\n                    {\n                        prognameline << \" [\" << posname << ']';\n                    }\n                }\n                if (!proglinePostfix.empty())\n                {\n                    prognameline << ' ' << proglinePostfix;\n                }\n                const auto proglines = Wrap(prognameline.str(), helpParams.width - (helpParams.progindent + 4), helpParams.width - helpParams.progindent);\n                auto progit = std::begin(proglines);\n                if (progit != std::end(proglines))\n                {\n                    help << std::string(helpParams.progindent, ' ') << *progit << '\\n';\n                    ++progit;\n                }\n                for (; progit != std::end(proglines); ++progit)\n                {\n                    help << std::string(helpParams.progtailindent, ' ') << *progit << '\\n';\n                }\n\n                help << '\\n';\n\n                for (const auto &line: description_text)\n                {\n                    help << std::string(helpParams.descriptionindent, ' ') << line << \"\\n\";\n                }\n                help << \"\\n\";\n                help << std::string(helpParams.progindent, ' ') << \"OPTIONS:\\n\\n\";\n                for (const auto &desc: GetChildDescriptions(shortprefix, longprefix, allowJoinedShortValue ? \"\" : \" \", allowJoinedLongValue ? longseparator : \" \"))\n                {\n                    const auto groupindent = std::get<2>(desc) * helpParams.eachgroupindent;\n                    const auto flags = Wrap(std::get<0>(desc), helpParams.width - (helpParams.flagindent + helpParams.helpindent + helpParams.gutter));\n                    const auto info = Wrap(std::get<1>(desc), helpParams.width - (helpParams.helpindent + groupindent));\n\n                    std::string::size_type flagssize = 0;\n                    for (auto flagsit = std::begin(flags); flagsit != std::end(flags); ++flagsit)\n                    {\n                        if (flagsit != std::begin(flags))\n                        {\n                            help << '\\n';\n                        }\n                        help << std::string(groupindent + helpParams.flagindent, ' ') << *flagsit;\n                        flagssize = Glyphs(*flagsit);\n                    }\n\n                    auto infoit = std::begin(info);\n                    // groupindent is on both sides of this inequality, and therefore can be removed\n                    if ((helpParams.flagindent + flagssize + helpParams.gutter) > helpParams.helpindent || infoit == std::end(info))\n                    {\n                        help << '\\n';\n                    } else\n                    {\n                        // groupindent is on both sides of the minus sign, and therefore doesn't actually need to be in here\n                        help << std::string(helpParams.helpindent - (helpParams.flagindent + flagssize), ' ') << *infoit << '\\n';\n                        ++infoit;\n                    }\n                    for (; infoit != std::end(info); ++infoit)\n                    {\n                        help << std::string(groupindent + helpParams.helpindent, ' ') << *infoit << '\\n';\n                    }\n                }\n                if (hasoptions && hasarguments && helpParams.showTerminator)\n                {\n                    for (const auto &item: Wrap(std::string(\"\\\"\") + terminator + \"\\\" can be used to terminate flag options and force all following arguments to be treated as positional options\", helpParams.width - helpParams.flagindent))\n                    {\n                        help << std::string(helpParams.flagindent, ' ') << item << '\\n';\n                    }\n                }\n\n                help << \"\\n\";\n                for (const auto &line: epilog_text)\n                {\n                    help << std::string(helpParams.descriptionindent, ' ') << line << \"\\n\";\n                }\n            }\n\n            /** Generate a help menu as a string.\n             *\n             * \\return the help text as a single string\n             */\n            std::string Help() const\n            {\n                std::ostringstream help;\n                Help(help);\n                return help.str();\n            }\n\n            /** Parse all arguments.\n             *\n             * \\param begin an iterator to the beginning of the argument list\n             * \\param end an iterator to the past-the-end element of the argument list\n             * \\return the iterator after the last parsed value.  Only useful for kick-out\n             */\n            template <typename It>\n            It ParseArgs(It begin, It end)\n            {\n                // Reset all Matched statuses and errors\n                Reset();\n                bool terminated = false;\n\n                // Check all arg chunks\n                for (auto it = begin; it != end; ++it)\n                {\n                    const auto &chunk = *it;\n\n                    if (!terminated && chunk == terminator)\n                    {\n                        terminated = true;\n                    // If a long arg was found\n                    } else if (!terminated && chunk.find(longprefix) == 0 && chunk.size() > longprefix.size())\n                    {\n                        const auto argchunk = chunk.substr(longprefix.size());\n                        // Try to separate it, in case of a separator:\n                        const auto separator = longseparator.empty() ? argchunk.npos : argchunk.find(longseparator);\n                        // If the separator is in the argument, separate it.\n                        const auto arg = (separator != argchunk.npos ?\n                            std::string(argchunk, 0, separator)\n                            : argchunk);\n\n                        if (auto base = Match(arg))\n                        {\n                            if (auto argbase = dynamic_cast<ValueFlagBase *>(base))\n                            {\n                                if (separator != argchunk.npos)\n                                {\n                                    if (allowJoinedLongValue)\n                                    {\n                                        argbase->ParseValue(argchunk.substr(separator + longseparator.size()));\n                                    } else\n                                    {\n#ifdef ARGS_NOEXCEPT\n                                        error = Error::Parse;\n                                        return it;\n#else\n                                        std::ostringstream problem;\n                                        problem << \"Flag '\" << arg << \"' was passed a joined argument, but these are disallowed\";\n                                        throw ParseError(problem.str());\n#endif\n                                    }\n                                } else\n                                {\n                                    ++it;\n                                    if (it == end)\n                                    {\n#ifdef ARGS_NOEXCEPT\n                                        error = Error::Parse;\n                                        return it;\n#else\n                                        std::ostringstream problem;\n                                        problem << \"Flag '\" << arg << \"' requires an argument but received none\";\n                                        throw ParseError(problem.str());\n#endif\n                                    }\n\n                                    if (allowSeparateLongValue)\n                                    {\n                                        argbase->ParseValue(*it);\n                                    } else\n                                    {\n#ifdef ARGS_NOEXCEPT\n                                        error = Error::Parse;\n                                        return it;\n#else\n                                        std::ostringstream problem;\n                                        problem << \"Flag '\" << arg << \"' was passed a separate argument, but these are disallowed\";\n                                        throw ParseError(problem.str());\n#endif\n                                    }\n                                }\n                            } else if (separator != argchunk.npos)\n                            {\n#ifdef ARGS_NOEXCEPT\n                                error = Error::Parse;\n                                return it;\n#else\n                                std::ostringstream problem;\n                                problem << \"Passed an argument into a non-argument flag: \" << chunk;\n                                throw ParseError(problem.str());\n#endif\n                            }\n\n                            if (base->KickOut())\n                            {\n                                return ++it;\n                            }\n                        } else\n                        {\n#ifdef ARGS_NOEXCEPT\n                            error = Error::Parse;\n                            return it;\n#else\n                            std::ostringstream problem;\n                            problem << \"Flag could not be matched: \" << arg;\n                            throw ParseError(problem.str());\n#endif\n                        }\n                        // Check short args\n                    } else if (!terminated && chunk.find(shortprefix) == 0 && chunk.size() > shortprefix.size())\n                    {\n                        const auto argchunk = chunk.substr(shortprefix.size());\n                        for (auto argit = std::begin(argchunk); argit != std::end(argchunk); ++argit)\n                        {\n                            const auto arg = *argit;\n\n                            if (auto base = Match(arg))\n                            {\n                                if (auto argbase = dynamic_cast<ValueFlagBase *>(base))\n                                {\n                                    const std::string value(++argit, std::end(argchunk));\n                                    if (!value.empty())\n                                    {\n                                        if (allowJoinedShortValue)\n                                        {\n                                            argbase->ParseValue(value);\n                                        } else\n                                        {\n#ifdef ARGS_NOEXCEPT\n                                            error = Error::Parse;\n                                            return it;\n#else\n                                            std::ostringstream problem;\n                                            problem << \"Flag '\" << arg << \"' was passed a joined argument, but these are disallowed\";\n                                            throw ParseError(problem.str());\n#endif\n                                        }\n                                    } else\n                                    {\n                                        ++it;\n                                        if (it == end)\n                                        {\n#ifdef ARGS_NOEXCEPT\n                                            error = Error::Parse;\n                                            return it;\n#else\n                                            std::ostringstream problem;\n                                            problem << \"Flag '\" << arg << \"' requires an argument but received none\";\n                                            throw ParseError(problem.str());\n#endif\n                                        }\n\n                                        if (allowSeparateShortValue)\n                                        {\n                                            argbase->ParseValue(*it);\n                                        } else\n                                        {\n#ifdef ARGS_NOEXCEPT\n                                            error = Error::Parse;\n                                            return it;\n#else\n                                            std::ostringstream problem;\n                                            problem << \"Flag '\" << arg << \"' was passed a separate argument, but these are disallowed\";\n                                            throw ParseError(problem.str());\n#endif\n                                        }\n                                    }\n                                    // Because this argchunk is done regardless\n                                    break;\n                                }\n\n                                if (base->KickOut())\n                                {\n                                    return ++it;\n                                }\n                            } else\n                            {\n#ifdef ARGS_NOEXCEPT\n                                error = Error::Parse;\n                                return it;\n#else\n                                std::ostringstream problem;\n                                problem << \"Flag could not be matched: '\" << arg << \"'\";\n                                throw ParseError(problem.str());\n#endif\n                            }\n                        }\n                    } else\n                    {\n                        auto pos = GetNextPositional();\n                        if (pos)\n                        {\n                            pos->ParseValue(chunk);\n\n                            if (pos->KickOut())\n                            {\n                                return ++it;\n                            }\n                        } else\n                        {\n#ifdef ARGS_NOEXCEPT\n                            error = Error::Parse;\n                            return it;\n#else\n                            std::ostringstream problem;\n                            problem << \"Passed in argument, but no positional arguments were ready to receive it: \" << chunk;\n                            throw ParseError(problem.str());\n#endif\n                        }\n                    }\n                }\n                if (!Matched())\n                {\n#ifdef ARGS_NOEXCEPT\n                    error = Error::Validation;\n#else\n                    std::ostringstream problem;\n                    problem << \"Group validation failed somewhere!\";\n                    throw ValidationError(problem.str());\n#endif\n                }\n                return end;\n            }\n\n            /** Parse all arguments.\n             *\n             * \\param args an iterable of the arguments\n             * \\return the iterator after the last parsed value.  Only useful for kick-out\n             */\n            template <typename T>\n            auto ParseArgs(const T &args) -> decltype(std::begin(args))\n            {\n                return ParseArgs(std::begin(args), std::end(args));\n            }\n\n            /** Convenience function to parse the CLI from argc and argv\n             *\n             * Just assigns the program name and vectorizes arguments for passing into ParseArgs()\n             *\n             * \\return whether or not all arguments were parsed.  This works for detecting kick-out, but is generally useless as it can't do anything with it.\n             */\n            bool ParseCLI(const int argc, const char * const * argv)\n            {\n                if (prog.empty())\n                {\n                    prog.assign(argv[0]);\n                }\n                const std::vector<std::string> args(argv + 1, argv + argc);\n                return ParseArgs(args) == std::end(args);\n            }\n    };\n\n    std::ostream &operator<<(std::ostream &os, const ArgumentParser &parser)\n    {\n        parser.Help(os);\n        return os;\n    }\n\n    /** Boolean argument matcher\n     */\n    class Flag : public FlagBase\n    {\n        public:\n            Flag(Group &group_, const std::string &name_, const std::string &help_, Matcher &&matcher_, const bool extraError_ = false): FlagBase(name_, help_, std::move(matcher_), extraError_)\n            {\n                group_.Add(*this);\n            }\n\n            virtual ~Flag() {}\n\n            /** Get whether this was matched\n             */\n            bool Get() const\n            {\n                return Matched();\n            }\n    };\n\n    /** Help flag class\n     *\n     * Works like a regular flag, but throws an instance of Help when it is matched\n     */\n    class HelpFlag : public Flag\n    {\n        public:\n            HelpFlag(Group &group_, const std::string &name_, const std::string &help_, Matcher &&matcher_): Flag(group_, name_, help_, std::move(matcher_)) {}\n\n            virtual ~HelpFlag() {}\n\n            virtual FlagBase *Match(const std::string &arg) override\n            {\n                if (FlagBase::Match(arg))\n                {\n#ifdef ARGS_NOEXCEPT\n                    error = Error::Help;\n#else\n                    throw Help(arg);\n#endif\n                    return this;\n                }\n                return nullptr;\n            }\n\n            virtual FlagBase *Match(const char arg) override\n            {\n                if (FlagBase::Match(arg))\n                {\n#ifdef ARGS_NOEXCEPT\n                    error = Error::Help;\n#else\n                    throw Help(std::string(1, arg));\n#endif\n                    return this;\n                }\n                return nullptr;\n            }\n\n            /** Get whether this was matched\n             */\n            bool Get() const noexcept\n            {\n                return Matched();\n            }\n    };\n\n    /** A flag class that simply counts the number of times it's matched\n     */\n    class CounterFlag : public Flag\n    {\n        private:\n            const int startcount;\n            int count;\n\n        public:\n            CounterFlag(Group &group_, const std::string &name_, const std::string &help_, Matcher &&matcher_, const int startcount_ = 0): Flag(group_, name_, help_, std::move(matcher_)), startcount(startcount_), count(startcount_) {}\n\n            virtual ~CounterFlag() {}\n\n            virtual FlagBase *Match(const std::string &arg) override\n            {\n                auto me = FlagBase::Match(arg);\n                if (me)\n                {\n                    ++count;\n                }\n                return me;\n            }\n\n            virtual FlagBase *Match(const char arg) override\n            {\n                auto me = FlagBase::Match(arg);\n                if (me)\n                {\n                    ++count;\n                }\n                return me;\n            }\n\n            /** Get the count\n             */\n            int &Get() noexcept\n            {\n                return count;\n            }\n\n            virtual void Reset() noexcept override\n            {\n                FlagBase::Reset();\n                count = startcount;\n            }\n    };\n\n    /** A default Reader class for argument classes\n     *\n     * Simply uses a std::istringstream to read into the destination type, and\n     * raises a ParseError if there are any characters left.\n     */\n    template <typename T>\n    struct ValueReader\n    {\n        bool operator ()(const std::string &name, const std::string &value, T &destination)\n        {\n            std::istringstream ss(value);\n            ss >> destination;\n\n            if (ss.rdbuf()->in_avail() > 0)\n            {\n#ifdef ARGS_NOEXCEPT\n                return false;\n#else\n                std::ostringstream problem;\n                problem << \"Argument '\" << name << \"' received invalid value type '\" << value << \"'\";\n                throw ParseError(problem.str());\n#endif\n            }\n            return true;\n        }\n    };\n\n    /** std::string specialization for ValueReader\n     *\n     * By default, stream extraction into a string splits on white spaces, and\n     * it is more efficient to ust copy a string into the destination.\n     */\n    template <>\n    struct ValueReader<std::string>\n    {\n        bool operator()(const std::string &name, const std::string &value, std::string &destination)\n        {\n            destination.assign(value);\n            return true;\n        }\n    };\n\n    /** An argument-accepting flag class\n     * \n     * \\tparam T the type to extract the argument as\n     * \\tparam Reader The functor type used to read the argument, taking the name, value, and destination reference with operator(), and returning a bool (if ARGS_NOEXCEPT is defined)\n     */\n    template <\n        typename T,\n        typename Reader = ValueReader<T>>\n    class ValueFlag : public ValueFlagBase\n    {\n        private:\n            T value;\n            Reader reader;\n\n        public:\n\n            ValueFlag(Group &group_, const std::string &name_, const std::string &help_, Matcher &&matcher_, const T &defaultValue_ = T(), const bool extraError_ = false): ValueFlagBase(name_, help_, std::move(matcher_), extraError_), value(defaultValue_)\n            {\n                group_.Add(*this);\n            }\n\n            virtual ~ValueFlag() {}\n\n            virtual void ParseValue(const std::string &value_) override\n            {\n#ifdef ARGS_NOEXCEPT\n                if (!reader(name, value_, this->value))\n                {\n                    error = Error::Parse;\n                }\n#else\n                reader(name, value_, this->value);\n#endif\n            }\n\n            /** Get the value\n             */\n            T &Get() noexcept\n            {\n                return value;\n            }\n    };\n\n    /** An argument-accepting flag class that pushes the found values into a list\n     * \n     * \\tparam T the type to extract the argument as\n     * \\tparam List the list type that houses the values\n     * \\tparam Reader The functor type used to read the argument, taking the name, value, and destination reference with operator(), and returning a bool (if ARGS_NOEXCEPT is defined)\n     */\n    template <\n        typename T,\n        template <typename...> class List = std::vector,\n        typename Reader = ValueReader<T>>\n    class ValueFlagList : public ValueFlagBase\n    {\n        private:\n            List<T> values;\n            Reader reader;\n\n        public:\n\n            ValueFlagList(Group &group_, const std::string &name_, const std::string &help_, Matcher &&matcher_, const List<T> &defaultValues_ = List<T>()): ValueFlagBase(name_, help_, std::move(matcher_)), values(defaultValues_)\n            {\n                group_.Add(*this);\n            }\n\n            virtual ~ValueFlagList() {}\n\n            virtual void ParseValue(const std::string &value_) override\n            {\n                T v;\n#ifdef ARGS_NOEXCEPT\n                if (!reader(name, value_, v))\n                {\n                    error = Error::Parse;\n                }\n#else\n                reader(name, value_, v);\n#endif\n                values.insert(std::end(values), v);\n            }\n\n            /** Get the values\n             */\n            List<T> &Get() noexcept\n            {\n                return values;\n            }\n\n            virtual std::string Name() const override\n            {\n                return name + std::string(\"...\");\n            }\n\n            virtual void Reset() noexcept override\n            {\n                ValueFlagBase::Reset();\n                values.clear();\n            }\n    };\n\n    /** A mapping value flag class\n     * \n     * \\tparam K the type to extract the argument as\n     * \\tparam T the type to store the result as\n     * \\tparam Reader The functor type used to read the argument, taking the name, value, and destination reference with operator(), and returning a bool (if ARGS_NOEXCEPT is defined)\n     * \\tparam Map The Map type.  Should operate like std::map or std::unordered_map\n     */\n    template <\n        typename K,\n        typename T,\n        typename Reader = ValueReader<K>,\n        template <typename...> class Map = std::unordered_map>\n    class MapFlag : public ValueFlagBase\n    {\n        private:\n            const Map<K, T> map;\n            T value;\n            Reader reader;\n\n        public:\n\n            MapFlag(Group &group_, const std::string &name_, const std::string &help_, Matcher &&matcher_, const Map<K, T> &map_, const T &defaultValue_ = T(), const bool extraError_ = false): ValueFlagBase(name_, help_, std::move(matcher_), extraError_), map(map_), value(defaultValue_)\n            {\n                group_.Add(*this);\n            }\n\n            virtual ~MapFlag() {}\n\n            virtual void ParseValue(const std::string &value_) override\n            {\n                K key;\n#ifdef ARGS_NOEXCEPT\n                if (!reader(name, value_, key))\n                {\n                    error = Error::Parse;\n                }\n#else\n                reader(name, value_, key);\n#endif\n                auto it = map.find(key);\n                if (it == std::end(map))\n                {\n#ifdef ARGS_NOEXCEPT\n                    error = Error::Map;\n#else\n                    std::ostringstream problem;\n                    problem << \"Could not find key '\" << key << \"' in map for arg '\" << name << \"'\";\n                    throw MapError(problem.str());\n#endif\n                } else\n                {\n                    this->value = it->second;\n                }\n            }\n\n            /** Get the value\n             */\n            T &Get() noexcept\n            {\n                return value;\n            }\n    };\n\n    /** A mapping value flag list class\n     * \n     * \\tparam K the type to extract the argument as\n     * \\tparam T the type to store the result as\n     * \\tparam List the list type that houses the values\n     * \\tparam Reader The functor type used to read the argument, taking the name, value, and destination reference with operator(), and returning a bool (if ARGS_NOEXCEPT is defined)\n     * \\tparam Map The Map type.  Should operate like std::map or std::unordered_map\n     */\n    template <\n        typename K,\n        typename T,\n        template <typename...> class List = std::vector,\n        typename Reader = ValueReader<K>,\n        template <typename...> class Map = std::unordered_map>\n    class MapFlagList : public ValueFlagBase\n    {\n        private:\n            const Map<K, T> map;\n            List<T> values;\n            Reader reader;\n\n        public:\n\n            MapFlagList(Group &group_, const std::string &name_, const std::string &help_, Matcher &&matcher_, const Map<K, T> &map_, const List<T> &defaultValues_ = List<T>()): ValueFlagBase(name_, help_, std::move(matcher_)), map(map_), values(defaultValues_)\n            {\n                group_.Add(*this);\n            }\n\n            virtual ~MapFlagList() {}\n\n            virtual void ParseValue(const std::string &value) override\n            {\n                K key;\n#ifdef ARGS_NOEXCEPT\n                if (!reader(name, value, key))\n                {\n                    error = Error::Parse;\n                }\n#else\n                reader(name, value, key);\n#endif\n                auto it = map.find(key);\n                if (it == std::end(map))\n                {\n#ifdef ARGS_NOEXCEPT\n                    error = Error::Map;\n#else\n                    std::ostringstream problem;\n                    problem << \"Could not find key '\" << key << \"' in map for arg '\" << name << \"'\";\n                    throw MapError(problem.str());\n#endif\n                } else\n                {\n                    this->values.emplace_back(it->second);\n                }\n            }\n\n            /** Get the value\n             */\n            List<T> &Get() noexcept\n            {\n                return values;\n            }\n\n            virtual std::string Name() const override\n            {\n                return name + std::string(\"...\");\n            }\n\n            virtual void Reset() noexcept override\n            {\n                ValueFlagBase::Reset();\n                values.clear();\n            }\n    };\n\n    /** A positional argument class\n     *\n     * \\tparam T the type to extract the argument as\n     * \\tparam Reader The functor type used to read the argument, taking the name, value, and destination reference with operator(), and returning a bool (if ARGS_NOEXCEPT is defined)\n     */\n    template <\n        typename T,\n        typename Reader = ValueReader<T>>\n    class Positional : public PositionalBase\n    {\n        private:\n            T value;\n            Reader reader;\n        public:\n            Positional(Group &group_, const std::string &name_, const std::string &help_, const T &defaultValue_ = T()): PositionalBase(name_, help_), value(defaultValue_)\n            {\n                group_.Add(*this);\n            }\n\n            virtual ~Positional() {}\n\n            virtual void ParseValue(const std::string &value_) override\n            {\n#ifdef ARGS_NOEXCEPT\n                if (!reader(name, value_, this->value))\n                {\n                    error = Error::Parse;\n                }\n#else\n                reader(name, value_, this->value);\n#endif\n                ready = false;\n                matched = true;\n            }\n\n            /** Get the value\n             */\n            T &Get() noexcept\n            {\n                return value;\n            }\n    };\n\n    /** A positional argument class that pushes the found values into a list\n     * \n     * \\tparam T the type to extract the argument as\n     * \\tparam List the list type that houses the values\n     * \\tparam Reader The functor type used to read the argument, taking the name, value, and destination reference with operator(), and returning a bool (if ARGS_NOEXCEPT is defined)\n     */\n    template <\n        typename T,\n        template <typename...> class List = std::vector,\n        typename Reader = ValueReader<T>>\n    class PositionalList : public PositionalBase\n    {\n        private:\n            List<T> values;\n            Reader reader;\n\n        public:\n            PositionalList(Group &group_, const std::string &name_, const std::string &help_, const List<T> &defaultValues_ = List<T>()): PositionalBase(name_, help_), values(defaultValues_)\n            {\n                group_.Add(*this);\n            }\n\n            virtual ~PositionalList() {}\n\n            virtual void ParseValue(const std::string &value_) override\n            {\n                T v;\n#ifdef ARGS_NOEXCEPT\n                if (!reader(name, value_, v))\n                {\n                    error = Error::Parse;\n                }\n#else\n                reader(name, value_, v);\n#endif\n                values.insert(std::end(values), v);\n                matched = true;\n            }\n\n            virtual std::string Name() const override\n            {\n                return name + std::string(\"...\");\n            }\n\n            /** Get the values\n             */\n            List<T> &Get() noexcept\n            {\n                return values;\n            }\n\n            virtual void Reset() noexcept override\n            {\n                PositionalBase::Reset();\n                values.clear();\n            }\n    };\n\n    /** A positional argument mapping class\n     * \n     * \\tparam K the type to extract the argument as\n     * \\tparam T the type to store the result as\n     * \\tparam Reader The functor type used to read the argument, taking the name, value, and destination reference with operator(), and returning a bool (if ARGS_NOEXCEPT is defined)\n     * \\tparam Map The Map type.  Should operate like std::map or std::unordered_map\n     */\n    template <\n        typename K,\n        typename T,\n        typename Reader = ValueReader<K>,\n        template <typename...> class Map = std::unordered_map>\n    class MapPositional : public PositionalBase\n    {\n        private:\n            const Map<K, T> map;\n            T value;\n            Reader reader;\n\n        public:\n\n            MapPositional(Group &group_, const std::string &name_, const std::string &help_, const Map<K, T> &map_, const T &defaultValue_ = T()): PositionalBase(name_, help_), map(map_), value(defaultValue_)\n            {\n                group_.Add(*this);\n            }\n\n            virtual ~MapPositional() {}\n\n            virtual void ParseValue(const std::string &value_) override\n            {\n                K key;\n#ifdef ARGS_NOEXCEPT\n                if (!reader(name, value_, key))\n                {\n                    error = Error::Parse;\n                }\n#else\n                reader(name, value_, key);\n#endif\n                auto it = map.find(key);\n                if (it == std::end(map))\n                {\n#ifdef ARGS_NOEXCEPT\n                    error = Error::Map;\n#else\n                    std::ostringstream problem;\n                    problem << \"Could not find key '\" << key << \"' in map for arg '\" << name << \"'\";\n                    throw MapError(problem.str());\n#endif\n                } else\n                {\n                    this->value = it->second;\n                    ready = false;\n                    matched = true;\n                }\n            }\n\n            /** Get the value\n             */\n            T &Get() noexcept\n            {\n                return value;\n            }\n    };\n\n    /** A positional argument mapping list class\n     * \n     * \\tparam K the type to extract the argument as\n     * \\tparam T the type to store the result as\n     * \\tparam List the list type that houses the values\n     * \\tparam Reader The functor type used to read the argument, taking the name, value, and destination reference with operator(), and returning a bool (if ARGS_NOEXCEPT is defined)\n     * \\tparam Map The Map type.  Should operate like std::map or std::unordered_map\n     */\n    template <\n        typename K,\n        typename T,\n        template <typename...> class List = std::vector,\n        typename Reader = ValueReader<K>,\n        template <typename...> class Map = std::unordered_map>\n    class MapPositionalList : public PositionalBase\n    {\n        private:\n            const Map<K, T> map;\n            List<T> values;\n            Reader reader;\n\n        public:\n\n            MapPositionalList(Group &group_, const std::string &name_, const std::string &help_, const Map<K, T> &map_, const List<T> &defaultValues_ = List<T>()): PositionalBase(name_, help_), map(map_), values(defaultValues_)\n            {\n                group_.Add(*this);\n            }\n\n            virtual ~MapPositionalList() {}\n\n            virtual void ParseValue(const std::string &value_) override\n            {\n                K key;\n#ifdef ARGS_NOEXCEPT\n                if (!reader(name, value_, key))\n                {\n                    error = Error::Parse;\n                }\n#else\n                reader(name, value_, key);\n#endif\n                auto it = map.find(key);\n                if (it == std::end(map))\n                {\n#ifdef ARGS_NOEXCEPT\n                    error = Error::Map;\n#else\n                    std::ostringstream problem;\n                    problem << \"Could not find key '\" << key << \"' in map for arg '\" << name << \"'\";\n                    throw MapError(problem.str());\n#endif\n                } else\n                {\n                    this->values.emplace_back(it->second);\n                    matched = true;\n                }\n            }\n\n            /** Get the value\n             */\n            List<T> &Get() noexcept\n            {\n                return values;\n            }\n\n            virtual std::string Name() const override\n            {\n                return name + std::string(\"...\");\n            }\n\n            virtual void Reset() noexcept override\n            {\n                PositionalBase::Reset();\n                values.clear();\n            }\n    };\n}\n\n#endif\n"
  },
  {
    "path": "src/pkQueueTS.hpp",
    "content": "/**************************************************************************************\r\n*\r\n* IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\r\n*\r\n* By downloading, copying, installing or using the software you agree to this license.\r\n* If you do not agree to this license, do not download, install,\r\n* copy or use the software.\r\n*\r\n*                           License Agreement\r\n*                           For pkQueueTS\r\n*\r\n*  pkQueueTS - http://pklab.net/index.php?id=395\r\n*  Copyright (C) 2016 PkLab.net all rights reserved.\r\n*\r\n*  Third party copyrights are property of their respective owners.\r\n*\r\n*  Redistribution and use in source and binary forms, with or without modification,\r\n*  are permitted provided that the following conditions are met:\r\n*\r\n*  1. Redistributions of source code must retain the above copyright notice,\r\n*     this list of conditions and the following disclaimer.\r\n*  2. Redistributions in binary form must reproduce the above copyright notice,\r\n*     this list of conditions and the following disclaimer in the documentation\r\n*     and/or other materials provided with the distribution.\r\n*  3. The name of the author may not be used to endorse or promote products\r\n*     derived from this software without specific prior written permission.\r\n*\r\n* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED\r\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\r\n* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\r\n* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\r\n* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\r\n* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\r\n* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\r\n* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n*****************************************************************************************/\r\n\r\n#ifndef PKQUEUETS_H\r\n#define PKQUEUETS_H\r\n\r\n#if __cplusplus < 199711L\r\n#error \"This file requires C++ 11 !\"\r\n#endif\r\n\r\n#include <queue>\r\n#include <thread>\r\n#include <mutex>\r\n#include <condition_variable>\r\n#include <chrono>\r\n\r\n#include <opencv2/core.hpp>\r\n#include <opencv2/opencv.hpp>\r\n\r\n\r\nusing namespace std;\r\nusing namespace  cv;\r\n\r\n//! \\defgroup  pkQueueTS A Thread safe queue by PkLab\r\n//! @{\r\n\r\n/** \\brief Thread Safe Queue result codes\r\n */\r\nenum pkQueueResults\r\n{\r\n    PK_QTS_OK,          //!< The result is correct\r\n    PK_QTS_TIMEOUT,     //!< A time-out has reached while push or pop\r\n    PK_QTS_EMPTY,       //!< The queue is empty and we wont wait\r\n};\r\n\r\n/** \\brief Simple structure for an OpenCV Mat with deep copy constructor and assignment operator.\r\n*\r\n* This class encapsulates a `cv::Mat` and provides custom assignment operator and\r\n* copy constructor to perform deep copy of matrix data too.\r\n*\r\n* This is because the `cv::Mat` assignment operator and the copy constructor\r\n* just copy the Mat header but not the matrix data.\r\n*\r\n* This class is useful for Mats buffering. For example:\r\n* - `std::queue::push(cv::Mat)` just creates a copy of `cv::Mat` header in the queue.\r\n* - `std::queue::push(MatCapsule)` creates a deep copy of `cv::Mat` in the queue.\r\n*\r\n* \\tparam TAdditionalStorage Here you can attach your own data type to hold any kind of information.\r\n* In case your data type contains simple types, like a structure, you can forget about copying.\r\n* If your data type holds any pointers or complex data type, you have to take care\r\n* its copy constructor and assignment operator.\r\n*\r\n* \\see\r\n* - Assignment operator [cv::Mat::operator=](http://docs.opencv.org/master/d3/d63/classcv_1_1Mat.html#aed1f81fe7efaacc2bd95149cdfa34302)\r\n* - Copy constructor [cv::Mat::Mat(const Mat &m)](http://docs.opencv.org/master/d3/d63/classcv_1_1Mat.html#a294eaf8a95d2f9c7be19ff594d06278e)\r\n*\r\n*/\r\ntemplate <class TAdditionalStorage = int>\r\nclass MatCapsule_\r\n{\r\npublic:\r\n    //! The OpenCV Mat\r\n    Mat mat;\r\n\r\n    /** \\brief Storage for additional information (Template)\r\n    *\r\n    * You can define you own data type to hold any kind of information.\r\n    * - In case your `TAdditionalStorage` holds just simple types you can forget about copying.\r\n    * - In case `TAdditionalStorage` holds any pointers or complex data type, you have to take care\r\n    *   of copy constructor and assignment operator.\r\n    */\r\n    TAdditionalStorage vars;\r\n\r\n    /** \\brief Default constructor\r\n    */\r\n    MatCapsule_() { }\r\n\r\n    /** \\brief Class destructor. Called by queue::pop\r\n    */\r\n    ~MatCapsule_() { }\r\n\r\n    /** \\brief The copy constructor. Called by queue::push\r\n    *\r\n    * Performs a deep copy of the `mat` member and its data.\r\n    * Calls the `TAdditionalStorage` copy constructor if any.\r\n    */\r\n    MatCapsule_(const MatCapsule_& src)\r\n    {\r\n        vars = TAdditionalStorage(src.vars); //Calls the copy constructor for the data type\r\n        src.mat.copyTo(mat);\r\n    }\r\n\r\n    /** \\brief The assignment operator. Called BY queue::front\r\n     * \\warning In case you have any member pointers you need to clone them.\r\n     * This is because, next calls to queue::pop calls the class destructor destroying all data.\r\n     * With `cv::Mat` the matrix data is still valid thanks to its internal memory counter.\r\n     */\r\n    MatCapsule_& operator=(const MatCapsule_& src)\r\n    {\r\n        //Sanity check\r\n        if (this == &src) return *this;\r\n\r\n        vars = src.vars;    // Calls assignment operator for the data type\r\n        mat = src.mat;      // Just copy the Mat header\r\n\r\n        return *this;\r\n    }\r\n};\r\n\r\n/** \\brief For your convenience, If you don't need any additional storage */\r\ntypedef MatCapsule_<int> MatCapsule;\r\n\r\n/** \\brief Abstract base class for handling custom pkQueueTS::Push event.\r\n *\r\n * It provides an abstract interface to create custom OnPush event handler.\r\n * The OnPush event could be used to perform any custom actions like memory analysis on the pkQueueTS.\r\n *\r\n * ### How to use the OnPush event\r\n * Because this class is pure virtual, you have to derive your own class and write your own OnPush().\r\n * The \"OnPush\" constructor pkQueueTS::pkQueueTS(pkQueueOnPushBase* onPushHandler) should\r\n * be used\r\n *\r\n * In this case, pkQueueTS::Push() calls `YourDerivedClass::OnPush()` within its own lock.\r\n */\r\nclass pkQueueOnPushBase\r\n{\r\npublic:\r\n    /** \\brief OnPush event handler interface\r\n     *\r\n     *  User has to defines its own class and implements the method to take needed actions.\r\n     *\r\n     * \\param queueSize Queue size after current push.\r\n     * \\param elementPtr Pointer to the last pushed element in the queue <`&m_queue.back()`>\r\n     * \\note This is called by pkQueueTS::Push() within a proper lock on the queue.\r\n     * Therefore the OnPush() method is thread safe vs those threads that are writing /reading\r\n     * the queue, also in case of multiple producer/consumer.\r\n     * \\warning Do not use `elementPtr` out of here because pointed to object will be destroyed\r\n     * on next pkQueueTS::Pop().\r\n     */\r\n    virtual void OnPush(size_t queueSize, const void *elementPtr) = 0;\r\n};\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n/** \\brief Thread Safe Queue\r\n*\r\n* \\author\r\n* pkQueueTS - http://pklab.net/index.php?id=395\r\n* Copyright (C) 2016 PkLab.net all rights reserved.\r\n*\r\n* This is a thread safe queue, multiple producer multiple consumer.\r\n* It's based on [std::queue](http://en.cppreference.com/w/cpp/container/queue) with single lock.\r\n* A [condition_variable](http://en.cppreference.com/w/cpp/thread/condition_variable)\r\n* with time-out is used to wait for new data.\r\n*\r\n* ## A thread safe queue for OpenCV Mats\r\n*\r\n* This class can be used to manage queue of [OpenCV Mats](http://docs.opencv.org/master/d3/d63/classcv_1_1Mat.html).\r\n* Thanks to [Automatic Memory Management](http://docs.opencv.org/master/d1/dfb/intro.html) of `cv::Mat`\r\n* and C++/STL memory recycling, use of `std::queue` with `cv::Mat` is memory effective.\r\n*\r\n* Unfortunately `cv::Mat` can't be used directly as element because its assignment operator and copy constructor\r\n* just copy the Mat header but not the matrix data. A simple solution is to encapsulates `cv::Mat`\r\n* into a structure or class and to write adequate assignment and constructor. The template class\r\n* MatCapsule_ (or its simple alias `MatCapsule` ) is provided here to this purpose.\r\n*\r\n* Definitely you can write:\r\n*\r\n* \\snippet pkQueueTS_TestSimple.cpp pkQueueTS_BasicUsage\r\n*\r\n* ## Additional storage\r\n*\r\n* The template class MatCapsule_ allows to attach any kind of additional storage to the capsule.\r\n* For example you can have:\r\n*\r\n* \\snippet pkQueueTS_TestSimple.cpp pkQueueTS_Additional_storage\r\n*\r\n* ## Memory statistics\r\n*\r\n* You can easily measure memory usage and allocations performed while using this class.\r\n* Just write your own `OnPush` event handler and collect wanted measurement (see pkQueueOnPushBase).\r\n*\r\n* For example you can collect all addresses of pushed elements using a simple `std::map` as below:\r\n*\r\n* \\snippet pkQueueTS_TestSimple.cpp pkQueueTS_Stats\r\n*\r\n* Please see http://pklab.net/?&id=396 for a detailed example and analysis\r\n*/\r\ntemplate <class TElement>\r\nclass pkQueueTS\r\n{\r\npublic:\r\n\r\n    /** \\brief Default constructor\r\n    */\r\n    pkQueueTS():m_onPushHandler(nullptr) {  }\r\n\r\n    /** \\overload\r\n     *  \\brief \"OnPush\" Constructor\r\n     *\r\n     * If the \"OnPush\" constructor is used, a custom object will be invoked each time\r\n     * pkQueueTS::Push() is called. In other words you have an OnPush event handler\r\n     * that can be used to perform any custom actions on the queue.\r\n     *\r\n     * \\param onPushHandler A pointer to custom object be derived from\r\n     *                      the abstract class pkQueueOnPushBase\r\n     */\r\n    pkQueueTS(pkQueueOnPushBase* onPushHandler)\r\n    {\r\n        m_onPushHandler = onPushHandler;\r\n    }\r\n\r\n    /** \\brief Default destructor\r\n    *\r\n    * Calls element destructor for all elements in the queue (if any).\r\n    * \\warning If element is a pointer, the pointed to objects are not destroyed.\r\n    */\r\n    ~pkQueueTS()\r\n    {\r\n        lock_guard<mutex> lock(m_mutex);\r\n        while (!m_queue.empty())\r\n            m_queue.pop();  //if you are here than you are discarding some elements\r\n    }\r\n\r\n    /** \\brief Retrieves the oldest element in the queue, if any or if wait.\r\n    *\r\n    * Blocks the caller thread until a new element is available or after the specified\r\n    * time-out duration. When/If the element has been retrieved correctly is it's removed\r\n    * from the queue.\r\n    *\r\n    * \\param [out] element If PK_QTS_OK is returned, contains the oldest element in the queue.\r\n    * \\param timeoutMs You can specify a time (milliseconds) to wait for a valid elements\r\n    *        - `timeoutMs = 0` [default] means no wait at all\r\n    *        - `timeoutMs > 0` means wait for given time out\r\n    * \\return pkQueueResults One of the following:\r\n    *         - PK_QTS_OK The element has been retrieved correctly\r\n    *         - PK_QTS_TIMEOUT  The queue is empty but we wont wait\r\n    *         - PK_QTS_EMPTY Time out has reached waiting a valid element\r\n    */\r\n    pkQueueResults Pop(TElement &element, unsigned timeoutMs = 0)\r\n    {\r\n        unique_lock<mutex> lock(m_mutex);\r\n        // wait for a data (ignoring spurious awakenings)\r\n        while (m_queue.empty())\r\n        {\r\n            // if no data and won't wait;\r\n            if (timeoutMs == 0)\r\n            {\r\n                return PK_QTS_EMPTY;\r\n            }\r\n            // else wait data with time-out\r\n            else if (cv_status::timeout == m_dataReady.wait_for(lock, chrono::milliseconds(timeoutMs)))\r\n            {\r\n                // Time out while waiting a valid element\r\n                return PK_QTS_TIMEOUT;\r\n            }\r\n        } // data available\r\n        element = m_queue.front(); //calls TElement::=operator\r\n        m_queue.pop();\r\n        return PK_QTS_OK;\r\n    }\r\n\r\n    /** \\brief Inserts an element at the end of the queue\r\n    *\r\n    * \\param element The element to add.\r\n    * \\return The queue size after that the element has been added\r\n    */\r\n    size_t Push(const TElement &element)\r\n    {\r\n        unique_lock<mutex> lock(m_mutex);\r\n        m_queue.push(element);  //calls TElement::copy_constructor\r\n\r\n        size_t N = m_queue.size();\r\n        if (m_onPushHandler)\r\n        {\r\n            void * ptr = &(m_queue.back());\r\n            m_onPushHandler->OnPush(N, ptr);\r\n        }\r\n\r\n        // The notifying thread does not need to hold the lock on the\r\n        // same mutex as the one held by the waiting thread(s);\r\n        // in fact doing so is a pessimization\r\n        lock.unlock();\r\n        m_dataReady.notify_one();\r\n        return N;\r\n    }\r\n\r\n    /** \\brief Returns the size of the queue\r\n    */\r\n    size_t Size()\r\n    {\r\n        lock_guard<mutex> lock(m_mutex);\r\n        return m_queue.size();\r\n    }\r\n\r\n    /** \\brief Test whether queue is empty\r\n    */\r\n    bool Empty() const\r\n    {\r\n        lock_guard<mutex> lock(m_mutex);\r\n        return m_queue.empty();\r\n    }\r\n\r\nprivate:\r\n    std::queue<TElement>    m_queue;\r\n    std::condition_variable m_dataReady;\r\n    mutable std::mutex      m_mutex;\r\n    pkQueueOnPushBase*      m_onPushHandler;\r\n\r\n};\r\n\r\n//! @}\r\n#endif //PKQUEUETS_H\r\n"
  },
  {
    "path": "src/track_targets.cpp",
    "content": "/**\ntrack_targets\nhttps://github.com/fnoop/vision_landing\n\nThis program uses opencv and aruco to detect fiducial markers in a stream.\nIt uses tracking across images in order to avoid ambiguity problem with a single marker.\nFor each target detected, it performs pose estimation and outputs the marker ID and translation vectors.\nThese vectors are used by vision_landing mavlink messages to enable precision landing by vision alone.\n\nCompile with cmake: cmake . && make\n or manually: g++ src/track_targets.cpp -o track_targets -std=gnu++11 `pkg-config --cflags --libs aruco`\n\nRun separately with: ./track_targets -d TAG36h11 /dev/video0 calibration.yml 0.235\n./track_targets -w 1280 -g 720 -d TAG36h11 -o 'appsrc ! autovideoconvert ! v4l2video11h264enc extra-controls=\"encode,h264_level=10,h264_profile=4,frame_level_rate_control_enable=1,video_bitrate=2097152\" ! h264parse ! rtph264pay config-interval=1 pt=96 ! udpsink host=192.168.1.70 port=5000 sync=false' /dev/video2 calibration/ocam5cr-calibration-1280x720.yml 0.235\n./track_targets -w 1280 -g 720 -d TAG36h11 -o /srv/maverick/data/videos/landing.avi /dev/video2 calibration/ocam5cr-calibration-1280x720.yml 0.235\n./track_targets -b 0.8 -d TAG36h11 -o 'appsrc ! autovideoconvert ! v4l2video11h264enc extra-contros=\"encode,h264_level=10,h264_profile=4,frame_level_rate_control_enable=1,video_bitrate=2097152\" ! h264parse ! rtph264pay config-interval=1 pt=96 ! udpsink host=192.168.1.70 port=5000 sync=false' -i 1 -v /dev/video2 calibration/ocam5cr-calibration-640x480.yml 0.235\n**/\n\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <thread>\n#include <atomic>\n#include <queue>\n#include <signal.h>\n#include <poll.h>\n#include <ctime>\n#include <sys/select.h>\n\n#include \"args.hxx\"\n#include \"pkQueueTS.hpp\"\n\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\n#include \"aruco/aruco.h\"\n#include \"aruco/timers.h\"\n\nusing namespace cv;\nusing namespace aruco;\n\n// Setup sig handling\nstatic volatile sig_atomic_t sigflag = 0;\nstatic volatile sig_atomic_t stateflag = 0; // 0 = stopped, 1 = started\nvoid handle_sig(int sig)\n{\n    std::cout << \"info:SIGNAL:\" << sig << \":Received\" << std::endl;\n    sigflag = 1;\n}\nvoid handle_sigusr1(int sig)\n{\n    std::cout << \"info:SIGNAL:SIGUSR1:Received:\" << sig << \":Switching on Vision Processing\" << std::endl;\n    stateflag = 1;\n}\nvoid handle_sigusr2(int sig)\n{\n    std::cout << \"info:SIGNAL:SIGUSR2:Received:\" << sig << \":Switching off Vision Processing\" << std::endl;\n    stateflag = 0;\n}\n\n// Setup fps tracker\ndouble CLOCK()\n{\n    struct timespec t;\n    clock_gettime(CLOCK_MONOTONIC, &t);\n    return (t.tv_sec * 1000) + (t.tv_nsec * 1e-6);\n}\ndouble _avgdur = 0;\ndouble _fpsstart = 0;\ndouble _avgfps = 0;\ndouble _fps1sec = 0;\ndouble avgdur(double newdur)\n{\n    _avgdur = 0.98 * _avgdur + 0.02 * newdur;\n    return _avgdur;\n}\ndouble avgfps()\n{\n    if (CLOCK() - _fpsstart > 1000)\n    {\n        _fpsstart = CLOCK();\n        _avgfps = 0.7 * _avgfps + 0.3 * _fps1sec;\n        _fps1sec = 0;\n    }\n    _fps1sec++;\n    return _avgfps;\n}\n\n// Define function to draw AR landing marker\nvoid drawARLandingCube(cv::Mat &Image, Marker &m, const CameraParameters &CP)\n{\n    Mat objectPoints(8, 3, CV_32FC1);\n    double halfSize = m.ssize / 2;\n\n    objectPoints.at<float>(0, 0) = -halfSize;\n    objectPoints.at<float>(0, 1) = -halfSize;\n    objectPoints.at<float>(0, 2) = 0;\n    objectPoints.at<float>(1, 0) = halfSize;\n    objectPoints.at<float>(1, 1) = -halfSize;\n    objectPoints.at<float>(1, 2) = 0;\n    objectPoints.at<float>(2, 0) = halfSize;\n    objectPoints.at<float>(2, 1) = halfSize;\n    objectPoints.at<float>(2, 2) = 0;\n    objectPoints.at<float>(3, 0) = -halfSize;\n    objectPoints.at<float>(3, 1) = halfSize;\n    objectPoints.at<float>(3, 2) = 0;\n\n    objectPoints.at<float>(4, 0) = -halfSize;\n    objectPoints.at<float>(4, 1) = -halfSize;\n    objectPoints.at<float>(4, 2) = m.ssize;\n    objectPoints.at<float>(5, 0) = halfSize;\n    objectPoints.at<float>(5, 1) = -halfSize;\n    objectPoints.at<float>(5, 2) = m.ssize;\n    objectPoints.at<float>(6, 0) = halfSize;\n    objectPoints.at<float>(6, 1) = halfSize;\n    objectPoints.at<float>(6, 2) = m.ssize;\n    objectPoints.at<float>(7, 0) = -halfSize;\n    objectPoints.at<float>(7, 1) = halfSize;\n    objectPoints.at<float>(7, 2) = m.ssize;\n\n    std::vector<Point2f> imagePoints;\n    cv::projectPoints(objectPoints, m.Rvec, m.Tvec, CP.CameraMatrix, CP.Distorsion, imagePoints);\n    // draw lines of different colours\n    for (int i = 0; i < 4; i++)\n        cv::line(Image, imagePoints[i], imagePoints[(i + 1) % 4], Scalar(0, 255, 0, 255), 1, cv::LINE_AA);\n\n    for (int i = 0; i < 4; i++)\n        cv::line(Image, imagePoints[i + 4], imagePoints[4 + (i + 1) % 4], Scalar(0, 255, 0, 255), 1, cv::LINE_AA);\n\n    for (int i = 0; i < 4; i++)\n        cv::line(Image, imagePoints[i], imagePoints[i + 4], Scalar(0, 255, 0, 255), 1, cv::LINE_AA);\n}\n\n// Print the calculated distance at bottom of image\nvoid drawVectors(Mat &in, Scalar color, int lineWidth, int vOffset, int MarkerId, double X, double Y, double Distance, double cX, double cY)\n{\n    char cad[100];\n    sprintf(cad, \"ID:%i, Distance:%0.3fm, X:%0.3f, Y:%0.3f, cX:%0.3f, cY:%0.3f\", MarkerId, Distance, X, Y, cX, cY);\n    Point cent(10, vOffset);\n    cv::putText(in, cad, cent, FONT_HERSHEY_SIMPLEX, std::max(0.5f, float(lineWidth) * 0.3f), color, lineWidth);\n}\n\n// Summarise a marker history over the past 10 frames\nint markerHistory(std::map<uint32_t, std::queue<int>> &marker_history_queue, uint32_t thisId, uint32_t marker_history)\n{\n    // Work out current history for this marker\n    uint32_t histsum = 0;\n    for (unsigned int j = 0; j < marker_history; j++)\n    {\n        uint32_t _val = marker_history_queue[thisId].front(); // fetch value off front of queue\n        histsum += _val;                                      // add value to history sum\n        marker_history_queue[thisId].pop();                   // pop value off front of queue\n        marker_history_queue[thisId].push(_val);              // push value back onto end of queue\n    }\n    return histsum;\n}\n\n// Change active marker and reset all marker histories\nvoid changeActiveMarker(std::map<uint32_t, std::queue<int>> &marker_history_queue, uint32_t &active_marker, uint32_t newId, uint32_t marker_history)\n{\n    // Set the new marker as active\n    active_marker = newId;\n\n    // Reset all marker histories.  This ensures that another marker change can't happen for at least x frames where x is history size\n    for (auto &markerhist : marker_history_queue)\n    {\n        for (unsigned int j = 0; j < marker_history; j++)\n        {\n            marker_history_queue[markerhist.first].push(0);\n            marker_history_queue[markerhist.first].pop();\n        }\n    }\n}\n\n// Setup our incoming threaded camera feed\nstruct TimeCapsuleVars\n{\n    uint64_t timeStamp = 0;\n    uint64_t frameNum = 0;\n};\ntypedef MatCapsule_<TimeCapsuleVars> MatTimeCapsule;\npkQueueTS<MatTimeCapsule> incomingQueue;\natomic<bool> grabState;\n\n// Initiate camera\ncv::VideoCapture vreader;\n\n// Thread to control capture device and push frames onto the threadsafe queue\nvoid incomingThread()\n{\n    // Enable capture input\n    grabState = true;\n    // Incoming frame\n    MatTimeCapsule iframe;\n    uint64_t frameNum = 0;\n    std::cout << \"Starting incomingThread()\" << std::endl;\n\n    while (grabState)\n    {\n        // Read the next frame in from the camera and push it to back of queue\n        // std::cout << \"debug:Pushing camera frame to queue\" << std::endl;\n        vreader.grab();\n        // Lodge clock for start of frame, after grabbing the frame but before decompressing/converting it.\n        // This is as close as we can get to the shutter time, for a better match to inertial frame.\n        frameNum++;\n        iframe.vars.frameNum = frameNum;\n        iframe.vars.timeStamp = CLOCK() * 1e+6;\n        // Now process the grabbed frame\n        vreader.retrieve(iframe.mat);\n        // Push the timeframe capsule onto the queue, ready for collection and processing\n        incomingQueue.Push(iframe);\n        \n        // If there is more than 1 frame in the queue, pop the rest to prevent buildup\n        while (incomingQueue.Size() > 1)\n            incomingQueue.Pop(iframe);\n\n    }\n}\n\n// Setup our outgoing threaded video stream\npkQueueTS< MatCapsule > outgoingQueue;\natomic<bool> pushState;\n// Initiate stream\ncv::VideoWriter vwriter;\n// Thread to control writer device, read frames from the threadsafe queue and push into the video stream\nvoid outgoingThread()\n{\n    // Enable stream output\n    pushState = true;\n    // Outgoing frame\n    MatCapsule oframe;\n    std::cout << \"Starting outgoingThread()\" << std::endl;\n\n    while (pushState)\n    {\n        int qsize = outgoingQueue.Size();\n        // Read frame in from the queue and push it to stream\n        if (qsize > 0) \n        {\n            std::cout << \"debug:Pushing output frame to stream:\" << qsize << std::endl;\n            // If the queue already has more than 1 frame then pop it, to prevent buildup\n            // We only want to send the latest frame\n            while (qsize > 1)\n            {\n                outgoingQueue.Pop(oframe);\n                qsize--;\n            }\n            // Pop the frame off the queue and push to stream\n            outgoingQueue.Pop(oframe);\n            vwriter.write(oframe.mat);\n        }\n    }\n}\n\n// main..\nint main(int argc, char **argv)\n{\n    // Unbuffer stdout and stdin\n    std::cout.setf(std::ios::unitbuf);\n    std::ios_base::sync_with_stdio(false);\n\n    // Make sure std::cout does not show scientific notation\n    std::cout.setf(ios::fixed);\n\n    // Setup arguments for parser\n    args::ArgumentParser parser(\"Track fiducial markers and estimate pose, output translation vectors for vision_landing\");\n    args::HelpFlag help(parser, \"help\", \"Display this help menu\", {'h', \"help\"});\n    args::Flag verbose(parser, \"verbose\", \"Verbose\", {'v', \"verbose\"});\n    args::ValueFlag<int> markerid(parser, \"markerid\", \"Marker ID\", {'i', \"id\"});\n    args::ValueFlag<std::string> dict(parser, \"dict\", \"Marker Dictionary\", {'d', \"dict\"});\n    args::ValueFlag<std::string> output(parser, \"output\", \"Output Stream\", {'o', \"output\"});\n    args::ValueFlag<int> width(parser, \"width\", \"Video Input Resolution - Width\", {'w', \"width\"});\n    args::ValueFlag<int> height(parser, \"height\", \"Video Input Resolution - Height\", {'g', \"height\"});\n    args::ValueFlag<int> fps(parser, \"fps\", \"Video Output FPS - Kludge factor\", {'f', \"fps\"});\n    args::ValueFlag<double> brightness(parser, \"brightness\", \"Camera Brightness/Gain\", {'b', \"brightness\"});\n    args::ValueFlag<std::string> sizemapping(parser, \"sizemapping\", \"Marker Size Mappings, in marker_id:size format, comma separated\", {'z', \"sizemapping\"});\n    args::ValueFlag<int> markerhistory(parser, \"markerhistory\", \"Marker tracking history, in frames\", {\"markerhistory\"});\n    args::ValueFlag<int> markerthreshold(parser, \"markerthreshold\", \"Marker tracking threshold, percentage\", {\"markerthreshold\"});\n    args::ValueFlag<std::string> fourcc(parser, \"fourcc\", \"FourCC CoDec code\", {'c', \"fourcc\"});\n    args::Positional<std::string> input(parser, \"input\", \"Input Stream\");\n    args::Positional<std::string> calibration(parser, \"calibration\", \"Calibration Data\");\n    args::Positional<double> markersize(parser, \"markersize\", \"Marker Size\");\n\n    // Parse arguments\n    try\n    {\n        parser.ParseCLI(argc, argv);\n    }\n    catch (args::Help)\n    {\n        std::cout << parser;\n        return 0;\n    }\n    catch (args::ParseError e)\n    {\n        std::cerr << e.what() << std::endl;\n        std::cerr << parser;\n        return 1;\n    }\n    catch (args::ValidationError e)\n    {\n        std::cerr << e.what() << std::endl;\n        std::cerr << parser;\n        return 1;\n    }\n\n    if (!input || !calibration || !markersize)\n    {\n        std::cout << parser;\n        return 1;\n    }\n\n    // Open camera\n    vreader.open( args::get(input) );\n\n    // Bail if camera can't be opened\n    if (!vreader.isOpened())\n    {\n        std::cerr << \"Error: Input stream can't be opened\" << std::endl;\n        return 1;\n    }\n\n    // Register signals\n    signal(SIGINT, handle_sig);\n    signal(SIGTERM, handle_sig);\n    signal(SIGUSR1, handle_sigusr1);\n    signal(SIGUSR2, handle_sigusr2);\n\n    // If resolution is specified then use, otherwise use default\n    int inputwidth = 640;\n    int inputheight = 480;\n    if (width)\n        inputwidth = args::get(width);\n    if (height)\n        inputheight = args::get(height);\n\n    // If fps is specified then use, otherwise use default\n    int inputfps = 30;\n    if (fps)\n        inputfps = args::get(fps);\n\n    // If brightness is specified then use, otherwise use default\n    if (brightness)\n        vreader.set(CAP_PROP_BRIGHTNESS, args::get(brightness));\n\n    // Set camera properties\n    vreader.set(cv::CAP_PROP_FRAME_WIDTH, inputwidth);\n    vreader.set(cv::CAP_PROP_FRAME_HEIGHT, inputheight);\n    vreader.set(cv::CAP_PROP_FPS, inputfps);\n    // vreader.set(CAP_PROP_BUFFERSIZE, 0); // Doesn't work yet with V4L2\n\n    // Read and parse camera calibration data\n    aruco::CameraParameters CamParam;\n    CamParam.readFromXMLFile(args::get(calibration));\n    if (!CamParam.isValid())\n    {\n        std::cerr << \"Calibration Parameters not valid\" << std::endl;\n        return -1;\n    }\n\n    // Take a single image and resize calibration parameters based on input stream dimensions\n    // Note we read directly from vreader here because we haven't turned the reader thread on yet\n    Mat rawimage;\n    vreader >> rawimage;\n    CamParam.resize(rawimage.size());\n\n    // Calculate the fov from the calibration intrinsics\n    const double pi = std::atan(1) * 4;\n    const double fovx = 2 * atan(inputwidth / (2 * CamParam.CameraMatrix.at<float>(0, 0))) * (180.0 / pi);\n    const double fovy = 2 * atan(inputheight / (2 * CamParam.CameraMatrix.at<float>(1, 1))) * (180.0 / pi);\n    std::cout << \"info:FoVx~\" << fovx << \":FoVy~\" << fovy << \":vWidth~\" << inputwidth << \":vHeight~\" << inputheight << std::endl;\n\n    // Turn on incoming thread\n    std::thread inThread(incomingThread);\n    MatTimeCapsule iframe;\n\n    // If output specified then setup the pipeline unless output is set to 'window'\n    if (output && args::get(output) != \"window\")\n    {\n        if (fourcc)\n        {\n            std::string _fourcc = args::get(fourcc);\n            vwriter.open(args::get(output), VideoWriter::fourcc(_fourcc[0], _fourcc[1], _fourcc[2], _fourcc[3]), inputfps, cv::Size(inputwidth, inputheight), true);\n        }\n        else\n        {\n            vwriter.open(args::get(output), 0, inputfps, cv::Size(inputwidth, inputheight), true);\n        }\n        if (!vwriter.isOpened())\n        {\n            std::cerr << \"Error can't create video writer\" << std::endl;\n            return 1;\n        }\n    }\n    // Turn on writer thread\n    std::thread outThread(outgoingThread);\n    MatCapsule oframe;\n\n    // Setup the marker detection\n    double MarkerSize = args::get(markersize);\n    MarkerDetector MDetector;\n    MarkerDetector::Params &MParams = MDetector.getParameters();\n    MDetector.setDetectionMode(aruco::DM_VIDEO_FAST, 0.02);\n    MParams.setAutoSizeSpeedUp(true,0.3);\n    MParams.maxThreads = 1; // -1 = all\n    MParams.setCornerRefinementMethod(aruco::CORNER_SUBPIX);\n    MParams.NAttemptsAutoThresFix = 3; // This is the number of random threshold iterations when no markers found\n\n    // Tracking variables\n    float Ti = MParams.minSize;\n    int ThresHold = MParams.ThresHold;\n\n    std::map<uint32_t, MarkerPoseTracker> MTracker; // use a map so that for each id, we use a different pose tracker\n    if (dict)\n        MDetector.setDictionary(args::get(dict), 0.f);\n\n    // Start framecounter at 0 for fps tracking\n    int frameno = 0;\n\n    // Create a map of marker sizes from 'sizemapping' config setting\n    std::map<uint32_t, float> markerSizes;\n    std::stringstream ss(args::get(sizemapping));\n    // First split each mapping into a vector\n    std::vector<std::string> _size_mappings;\n    std::string _size_mapping;\n    while (std::getline(ss, _size_mapping, ','))\n    {\n        _size_mappings.push_back(_size_mapping);\n    }\n    // Next tokenize each vector element into the markerSizes map\n    for (std::string const &_s : _size_mappings)\n    {\n        auto _i = _s.find(':');\n        markerSizes[atoi(_s.substr(0, _i).data())] = atof(_s.substr(_i + 1).data());\n    }\n    // Debug print the constructed map\n    std::cout << \"info:Size Mappings:\";\n    for (const auto &p : markerSizes)\n    {\n        std::cout << p.first << \"=\" << p.second << \", \";\n    }\n    std::cout << std::endl;\n\n    // Setup marker thresholding\n    uint32_t active_marker;\n    // Use a map of queues to track state of each marker in the last x frames\n    std::map<uint32_t, std::queue<int>> marker_history_queue;\n\n    // If marker history or threshold is set in parameters use them, otherwise set defaults\n    uint32_t marker_history;\n    if (args::get(markerhistory))\n    {\n        marker_history = args::get(markerhistory);\n    }\n    else\n    {\n        marker_history = 15;\n    }\n    std::cout << \"debug:Marker History:\" << marker_history << std::endl;\n    uint32_t marker_threshold;\n    marker_threshold = args::get(markerthreshold);\n    std::cout << \"debug:Marker Threshold:\" << marker_threshold << std::endl;\n\n    // Print a specific info message to signify end of initialisation\n    std::cout << \"info:initcomp:Initialisation Complete\" << std::endl;\n\n    // Main loop\n    while (true)\n    {\n        // If signal for interrupt/termination was received, break out of main loop and exit\n        if (sigflag)\n        {\n            std::cout << \"info:Signal Detected:Exiting track_targets\" << std::endl;\n            break;\n        }\n\n        // If tracking not active, skip\n        if (!stateflag)\n        {\n            // Add a 1ms sleep to slow down the loop if nothing else is being done\n            nanosleep((const struct timespec[]){{0, 10000000L}}, NULL);\n            continue;\n        }\n\n        // Start Timers\n        double framestart = CLOCK();\n        ScopedTimerEvents Timer(\"detectloop\");\n\n        // Read a camera frame from the incoming thread, with 1 second timeout\n        // std::cout << \"debug:Incoming queue size:\" << incomingQueue.Size() << std::endl;\n        pkQueueResults res = incomingQueue.Pop(iframe, 1000);\n        if (res != PK_QTS_OK)\n        {\n            if (verbose && res == PK_QTS_TIMEOUT)\n                std::cout << \"debug:Time out reading from the camera thread\" << std::endl;\n            if (verbose && res == PK_QTS_EMPTY)\n                std::cout << \"debug:Camera thread is empty\" << std::endl;\n            this_thread::yield();\n            continue;\n        }\n        Timer.add(\"PopImage\");\n\n        // Skip this loop iteration if the frame was empty\n        if (iframe.mat.empty())\n            continue;\n\n        // Detect markers\n        std::vector<Marker> Markers = MDetector.detect(iframe.mat);\n        Timer.add(\"MarkerDetect\");\n\n        // Order the markers in ascending size - we want to start with the smallest.\n        std::map<float, uint32_t> markerAreas;\n        std::map<uint32_t, bool> markerIds;\n        for (auto &marker : Markers)\n        {\n            markerAreas[marker.getArea()] = marker.id;\n            markerIds[marker.id] = true;\n            // If the marker doesn't already exist in the threshold tracking, add and populate with full set of zeros\n            if (marker_history_queue.count(marker.id) == 0)\n            {\n                for (unsigned int i = 0; i < marker_history; i++)\n                    marker_history_queue[marker.id].push(0);\n            }\n        }\n\n        // Iterate through marker history and update for this frame\n        for (auto &markerhist : marker_history_queue)\n        {\n            // If marker was detected in this frame, push a 1\n            (markerIds.count(markerhist.first)) ? markerhist.second.push(1) : markerhist.second.push(0);\n            // If the marker history has reached history limit, pop the oldest element\n            if (markerhist.second.size() > marker_history)\n            {\n                markerhist.second.pop();\n            }\n        }\n\n        // If marker is set in config, use that to lock on\n        if (markerid)\n        {\n            active_marker = args::get(markerid);\n            // Otherwise find the smallest marker that has a size mapping\n        }\n        else\n        {\n            for (auto &markerArea : markerAreas)\n            {\n                uint32_t thisId = markerArea.second;\n                if (markerSizes[thisId])\n                {\n                    // If the current history for this marker is >threshold, then set as the active marker and clear marker histories.  Otherwise, skip to the next sized marker.\n                    uint32_t _histsum = markerHistory(marker_history_queue, thisId, marker_history);\n                    float _histthresh = marker_history * ((float)marker_threshold / (float)100);\n                    if (_histsum > _histthresh)\n                    {\n                        if (active_marker == thisId)\n                            break; // Don't change to the same thing\n                        changeActiveMarker(marker_history_queue, active_marker, thisId, marker_history);\n                        if (verbose)\n                        {\n                            std::cout << \"debug:changing active_marker:\" << thisId << \":\" << _histsum << \":\" << _histthresh << \":\" << std::endl;\n                            std::cout << \"debug:marker history:\";\n                            for (auto &markerhist : marker_history_queue)\n                            {\n                                std::cout << markerhist.first << \":\" << markerHistory(marker_history_queue, markerhist.first, marker_history) << \":\";\n                            }\n                            std::cout << std::endl;\n                        }\n                        break;\n                    }\n                }\n            }\n        }\n        // If a marker lock hasn't been found by this point, use the smallest found marker with the default marker size\n        if (!active_marker)\n        {\n            for (auto &markerArea : markerAreas)\n            {\n                uint32_t thisId = markerArea.second;\n                // If the history threshold for this marker is >50%, then set as the active marker and clear marker histories.  Otherwise, skip to the next sized marker.\n                uint32_t _histsum = markerHistory(marker_history_queue, thisId, marker_history);\n                float _histthresh = marker_history * ((float)marker_threshold / (float)100);\n                if (_histsum > _histthresh)\n                {\n                    if (verbose)\n                        std::cout << \"debug:changing active_marker:\" << thisId << std::endl;\n                    changeActiveMarker(marker_history_queue, active_marker, thisId, marker_history);\n                    break;\n                }\n            }\n        }\n        Timer.add(\"MarkerLock\");\n\n        // Iterate through the markers, in order of size, and do pose estimation\n        for (auto &markerArea : markerAreas)\n        {\n            if (markerArea.second != active_marker)\n                continue; // Don't do pose estimation if not active marker, save cpu cycles\n            float _size;\n            // If marker size mapping exists for this marker, use it for pose estimation\n            if (markerSizes[markerArea.second])\n            {\n                _size = markerSizes[markerArea.second];\n                // Otherwise use generic marker size\n            }\n            else if (MarkerSize)\n            {\n                _size = MarkerSize;\n                if (verbose)\n                    std::cout << \"debug:defaulting to generic marker size: \" << markerArea.second << std::endl;\n            }\n            // Find the Marker in the Markers map and do pose estimation.  I'm sure there's a better way of iterating through the map..\n            for (unsigned int i = 0; i < Markers.size(); i++)\n            {\n                if (Markers[i].id == markerArea.second)\n                {\n                    MTracker[markerArea.second].estimatePose(Markers[i], CamParam, _size);\n                }\n            }\n        }\n        Timer.add(\"PoseEstimation\");\n\n        // Iterate through each detected marker and send data for active marker and draw green AR cube, otherwise draw red AR square\n        for (unsigned int i = 0; i < Markers.size(); i++)\n        {\n            double processtime = CLOCK() - framestart;\n            // If marker id matches current active marker, draw a green AR cube\n            if (Markers[i].id == active_marker)\n            {\n                if (output)\n                {\n                    Markers[i].draw(iframe.mat, Scalar(0, 255, 0), 2, false);\n                }\n                // If pose estimation was successful, calculate data and output to anyone listening.\n                if (Markers[i].Tvec.at<float>(0, 2) > 0)\n                {\n                    // Calculate vector norm for distance\n                    double distance = sqrt(pow(Markers[i].Tvec.at<float>(0, 0), 2) + pow(Markers[i].Tvec.at<float>(0, 1), 2) + pow(Markers[i].Tvec.at<float>(0, 2), 2));\n                    // Calculate angular offsets in radians of center of detected marker\n                    double xoffset = (Markers[i].getCenter().x - inputwidth / 2.0) * (fovx * (pi / 180)) / inputwidth;\n                    double yoffset = (Markers[i].getCenter().y - inputheight / 2.0) * (fovy * (pi / 180)) / inputheight;\n                    if (verbose)\n                    {\n                        Ti = MParams.minSize;\n                        ThresHold = MParams.ThresHold;\n                        std::cout << \"debug:active_marker:\" << active_marker << \":center~\" << Markers[i].getCenter() << \":area~\" << Markers[i].getArea() << \":marker~\" << Markers[i] << \":vectornorm~\" << distance << \":Ti~\" << Ti << \":ThresHold~\" << ThresHold << \":Markers~\" << Markers.size() << \":processtime~\" << processtime << \":timestamp~\" << iframe.vars.timeStamp << std::endl;\n                    }\n                    // This is the main message that track_targets outputs, containing the active target data\n                    std::cout << \"target:\" << Markers[i].id << \":\" << xoffset << \":\" << yoffset << \":\" << distance << \":\" << processtime << \":\" << iframe.vars.timeStamp << \":\" << CLOCK() * 1e+6 << std::endl << std::flush;\n                    // std::cout << \"target:\" << Markers[i].id << \":\" << xoffset << \":\" << yoffset << \":\" << distance << \":\" << processtime << \":\" << CLOCK() * 1e+6 << std::endl << std::flush;\n                    std::fflush(stdout); // explicitly flush stdout buffer\n                    Timer.add(\"SendMessage\");\n                    // Draw AR cube and distance\n                    if (output)\n                    { // don't burn cpu cycles if no output\n                        drawARLandingCube(iframe.mat, Markers[i], CamParam);\n                        CvDrawingUtils::draw3dAxis(iframe.mat, Markers[i], CamParam);\n                        drawVectors(iframe.mat, Scalar(0, 255, 0), 1, (i + 1) * 20, Markers[i].id, xoffset, yoffset, distance, Markers[i].getCenter().x, Markers[i].getCenter().y);\n                        Timer.add(\"DrawGreenAR\");\n                    }\n                }\n                // Otherwise draw a red square\n            }\n            else\n            {\n                if (verbose)\n                    std::cout << \"debug:inactive_marker:center~\" << Markers[i].getCenter() << \":area~\" << Markers[i].getArea() << \":marker~\" << Markers[i] << \":Ti~\" << Ti << \":ThresHold~\" << ThresHold << \":Markers~\" << Markers.size() << \":processtime~\" << processtime << std::endl;\n                if (output)\n                { // don't burn cpu cycles if no output\n                    Markers[i].draw(iframe.mat, Scalar(0, 0, 255), 2, false);\n                    drawVectors(iframe.mat, Scalar(0, 0, 255), 1, (i + 1) * 20, Markers[i].id, 0, 0, Markers[i].Tvec.at<float>(0, 2), Markers[i].getCenter().x, Markers[i].getCenter().y);\n                    Timer.add(\"DrawRedAR\");\n                }\n            }\n        }\n        Timer.add(\"UseMarkers\");\n\n        if (output && args::get(output) != \"window\")\n        {\n            oframe.mat = iframe.mat.clone();\n            // iframe.mat.copyTo(oframe.mat);\n            Timer.add(\"Out-CloneMat\");\n            outgoingQueue.Push(oframe);\n            Timer.add(\"Out-PushImage\");\n        }\n        else if (output && args::get(output) == \"window\")\n        {\n            imshow(\"vision_landing\", iframe.mat);\n            Timer.add(\"OutputImage\");\n        }\n\n        // Lodge clock for end of frame\n        double framedur = CLOCK() - framestart;\n\n        // Print fps info every 100 frames\n        char framestr[100];\n        sprintf(framestr, \"info:avgframedur~%fms:fps~%f:frameno~%d:\", avgdur(framedur), avgfps(), frameno++);\n        if (verbose && (frameno % 100 == 1))\n        {\n            std::cout << framestr << std::endl;\n        }\n        Timer.add(\"EndofLoop\");\n    }\n\n    // Stop incoming thread and flush queue\n    std::cout << \"info:track_targets complete, exiting\" << std::endl;\n    grabState = false;\n    pushState = false;\n    while (PK_QTS_EMPTY != incomingQueue.Pop(iframe, 0));\n    inThread.join();\n    while (PK_QTS_EMPTY != outgoingQueue.Pop(oframe, 0));\n    outThread.join();\n    vreader.release();\n    vwriter.release();\n    std::cout.flush();\n    return 0;\n}\n"
  },
  {
    "path": "vision_landing",
    "content": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\n# vision_landing\n# https://github.com/fnoop/vision_landing\n#\n# This python script connects to arducopter using dronekit, to control precision landing.\n# The control is purely visual using pose estimation from fiducial markers (eg. aruco or april tags), no additional rangefinder is needed.\n# It launches a separate program track_targets which does the actual cv work and captures the resulting vectors from non-blocking thread handler.\n\nfrom threading import Thread, Event\nfrom Queue import LifoQueue, Queue, Empty\nfrom subprocess import Popen, PIPE\nfrom dronekit import connect, VehicleMode, LocationGlobal, LocationGlobalRelative\nfrom pymavlink import mavutil\nfrom time import sleep, time\nfrom datetime import datetime, timedelta\nfrom sys import exit, stdout, stderr\nfrom os import path, makedirs, symlink, remove\nfrom math import pi\nfrom re import sub, search\nfrom collections import deque\nfrom math import sqrt\nimport signal\nimport logging\nimport ctypes\n\n\n### ================================\n### Define Functions\n### ================================\n\n# Return correctly typed config parser option\ndef get_config_value(parser, section, option):\n    \"\"\"Parses config value as python type\"\"\"\n    try:\n        return parser.getint(section, option)\n    except ValueError:\n        pass\n    try:\n        return parser.getfloat(section, option)\n    except ValueError:\n        pass\n    try:\n        return parser.getboolean(section, option)\n    except ValueError:\n        pass\n    return parser.get(section, option)\n\n# Setup monotonic clock\nCLOCK_MONOTONIC_RAW = 4\nclass timespec(ctypes.Structure):\n    _fields_ = [\n        ('tv_sec', ctypes.c_long),\n        ('tv_nsec', ctypes.c_long)\n    ]\nlibrt = ctypes.CDLL('librt.so.1', use_errno=True)\nclock_gettime = librt.clock_gettime\nclock_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(timespec)]\n\ndef monotonic_time():\n    t = timespec()\n    if clock_gettime(CLOCK_MONOTONIC_RAW , ctypes.pointer(t)) != 0:\n        errno_ = ctypes.get_errno()\n        raise OSError(errno_, os.strerror(errno_))\n    return (t.tv_sec * 1e+9) + t.tv_nsec\n\n### ================================\n### End Define Functions\n### ================================\n\n\n### ================================\n### Define Classes\n### ================================\n\n# Threaded Reader class connects the output from the track_targets process to a non-blocking reader, and adds any messages to a queue.\n# The queue is then read by the main loop and if anything is waiting it calls a method to process from the track_targets object.\nclass ThreadedReader:\n    def __init__(self, stdout, stderr):\n        self.stdout = stdout\n        self.stderr = stderr\n        self.queue = LifoQueue()\n        self._stop = Event()\n        def insertQueue(pipe, queue, qtype=\"stdout\"):\n            while not self.stopped():\n                self.clear() # Clear the queue before adding anything - we only want the latest data\n                line = pipe.readline().rstrip() + \":{:.0f}\".format(monotonic_time())\n                if args.verbose:\n                    log.debug(\"Adding line: {} : {}\".format(qtype, line))\n                if line and qtype == \"stdout\":\n                    queue.put(line)\n                elif line and qtype == \"stderr\":\n                    queue.put(\"error:\"+line)\n        self.threadout = Thread(target = insertQueue, args = (self.stdout, self.queue))\n        self.threadout.daemon = True\n        self.threadout.start()\n        self.threaderr = Thread(target = insertQueue, args = (self.stderr, self.queue, \"stderr\"))\n        self.threaderr.daemon = True\n        self.threaderr.start()\n    def size(self):\n        return self.queue.qsize()\n    def readline(self, timeout = None):\n        try:\n            line = self.queue.get(block = timeout is not None, timeout = timeout)\n            self.queue.task_done()\n            return line\n        except Empty:\n            log.debug(\"empty queue\")\n            return None\n    def clear(self):\n        #with self.queue.mutex:\n        #    self.queue.clear()\n        while self.size() > 10:\n            # self.readline()\n            tmpline = self.queue.get(False)\n            log.debug(\"clearing queue: {} : {}\".format(self.size(), tmpline))\n            self.queue.task_done()\n        return\n    def stop(self):\n        self._stop.set()\n    def stopped(self):\n        return self._stop.isSet()\n\n# TrackTime class is used to synchronise time between the companion computer and the flight controller.\n# This is necessary to ensure that the vision frames are matched as closely as possible with the inertial frames.\n# Note: This requires a Craft object to be passed, in order to perform the actual sync. \nclass TrackTime:\n    def __init__(self, craft):\n        self.fctime_nanos = 0\n        self.mytime_nanos = 0\n        self.local_tracker = {}\n        self.delta = None\n        self.difference = None\n        self.delta_buffer = deque(maxlen=50) # Circular buffer to track timesync deltas\n        self.difference_buffer = deque(maxlen=50) # Circular buffer to track difference between two systems\n        self.debug = False\n        self.vehicle = craft.vehicle\n        # Setup time struct to hold local monotonic clock queries\n        self.t = timespec()\n        # Setup listener decorator\n        @self.vehicle.on_message(\"TIMESYNC\")\n        def listener_timesync(subself, name, message):\n            try:\n                if message.ts1 < self.mytime_nanos:\n                    #log.info(\"Newer timesync message already received, ignoring\")\n                    return False\n                self.mytime_nanos = message.ts1 # Set the time that the message was sent\n                _cts = self.current_timestamp()\n                _avg_ts = (self.local_tracker[message.ts1] + _cts)/2\n                self._delta = _cts - _avg_ts # Calculuate the time delta\n                self.delta_buffer.append(self._delta) # Push the delta into the circular buffer\n                # If the averaged delta has been reached, use that, and update the delta from the latest buffer\n                if self.delta:\n                    self.delta = sum(list(self.delta_buffer)) / len(list(self.delta_buffer))\n                    self.fctime_nanos = message.tc1 - self.delta\n                # Otherwise use the spot delta from the incoming message\n                else:\n                    self.fctime_nanos = message.tc1 - self._delta\n                self.difference_buffer.append(self.mytime_nanos - self.fctime_nanos)\n                self.difference = sum(list(self.difference_buffer)) / len(list(self.difference_buffer))\n                if self.debug:\n                    log.debug(\"Timesync message received:\"+\", \".join([str(message), str(self._delta), str(self.fctime_nanos)]))\n            except:\n                if self.debug:\n                    log.debug(\"Error, unexpected timesync timestamp received:\"+str(message.ts1))\n    # Blocking method to call once during startup, to calculate delta\n    def initial_sync(self):\n        # Keep sending timesync requests until the delta buffer is full, or a timeout is reached\n        start_timesync = self.current_timestamp()\n        while len(list(self.delta_buffer)) < 50 and self.current_timestamp() - start_timesync < (15 * 1000000000):\n            self.update()\n            sleep(0.1) # Ardupilot can't cope with too many timesync messages being sent in a short time period, the results are nonsense\n        # When full, average the delta buffer and then set that to use as the ongoing delta\n        if len(self.delta_buffer) == 50:\n            self.delta = sum(list(self.delta_buffer)) / len(list(self.delta_buffer))\n        else:\n            log.warning(\"Error creating timesync delta buffer - unpredictable results will follow\")\n    # Method to return monotonic clock time\n    def current_timestamp(self):\n        return monotonic_time()\n    # Request a timesync update from the flight controller\n    def update(self, ts=0, tc=0):\n        if ts == 0:\n            ts = self.current_timestamp()\n        self.local_tracker[ts] = self.current_timestamp() # Create entry to correlate sending timestamp with actual localtime\n        msg = self.vehicle.message_factory.timesync_encode(\n            tc,     # tc1\n            ts      # ts1\n        )\n        self.vehicle.send_mavlink(msg)\n        self.vehicle.flush()\n    # Note: This returns the 'actual' time of the FC with the delay compensated from the last sync event\n    def actual(self):\n        return self.fctime_nanos\n    # Return actual + time elapsed since actual set\n    def estimate(self):\n        estmynanos = self.current_timestamp() - self.difference\n        estfcnanos = self.actual() + (self.current_timestamp() - self.mytime_nanos)\n        #log.debug(\"Estimate time: current-difference:\"+str(estmynanos/1000000)+\", fctime_nanos+elapsed:\"+str(estfcnanos/1000000)+\", difference:\"+str((estmynanos - estfcnanos) / 1000000))\n        return estmynanos\n    def toFcTime(self, inTime):\n        return inTime - self.difference\n\n# TrackTargets class launches, controls and handles the separate track_targets process that does the actual vision processing.\nclass TrackTargets:\n    def __init__(self, args, calibration):\n        self.state = None\n        self.shutdown = False\n        # Setup timing containers\n        self.frame_times = []\n        self.start_t = time()\n        # Work out starting parameters\n        self.setup(args, calibration)\n        # Launch tracking process and process output\n        log.info(\"Launching track_targets with arguments:\" + \" \".join(self.track_arguments))\n        self.launch()\n    def setup(self, args, calibration):\n        # Define the basic arguments to track_targets\n        self.track_arguments = [cwd+'/track_targets']\n        # If marker dictionary is set, pass it through\n        if args.markerdict:\n            self.track_arguments.extend(['-d', args.markerdict])\n        # If output is set, pass it through\n        if args.output:\n            now = datetime.now()\n            nowtime = now.strftime(\"%Y-%m-%d-%H-%M-%S\")\n            args_output = sub(\"-xxx\", \"-\"+str(nowtime), args.output)\n            self.track_arguments.extend(['-o', args_output])\n        # If marker id is set, pass it through\n        if args.markerid:\n            self.track_arguments.extend(['-i', args.markerid])\n        # If width is set, pass it through\n        if args.width:\n            self.track_arguments.extend(['-w', str(args.width)])\n        # If height is set, pass it through\n        if args.height:\n            self.track_arguments.extend(['-g', str(args.height)])\n        # If fps is set, pass it through\n        if args.fps:\n            self.track_arguments.extend(['-f', str(args.fps)])\n        # If verbose is set, pass it through\n        if args.verbose:\n            self.track_arguments.extend(['-v'])\n        # If brightness is set, pass it through\n        if args.brightness:\n            self.track_arguments.extend(['-b', str(args.brightness)])\n        # If fourcc codec is set, pass it through\n        if args.fourcc:\n            self.track_arguments.extend(['-c', args.fourcc])\n        # If sizemapping is set, pass it through\n        if args.sizemapping:\n            self.track_arguments.extend(['-z', args.sizemapping])\n        # If markerhistory is set, pass it through\n        if args.markerhistory:\n            self.track_arguments.extend(['--markerhistory', str(args.markerhistory)])\n        # If markerthreshold is set, pass it through\n        if args.markerthreshold:\n            self.track_arguments.extend(['--markerthreshold', str(args.markerthreshold)])\n        # Add positional arguments\n        self.track_arguments.extend([args.input, calibration, str(args.markersize)])\n    def launch(self):\n        self.process = Popen(self.track_arguments, stdin = PIPE, stdout = PIPE, stderr = PIPE, shell = False, bufsize=1)\n        self.reader = ThreadedReader(self.process.stdout, self.process.stderr)\n        self.state = \"initialising\"\n    def processline(self, line):\n        # Unpack data from track_targets data\n        trackdata = line.rstrip().split(\":\")\n        # If not target data, log and skip to next data\n        if trackdata[0] != \"target\":\n            datatype = trackdata[0]\n            if trackdata[0] == \"error\":\n                log.error(\"track_targets: \" +str(trackdata[1:]))\n            elif trackdata[0] == \"debug\" and args.verbose:\n                log.debug(\"track_targets: \" + datatype[0].upper() + datatype[1:] + str(trackdata[1:]))\n            elif trackdata[0] == \"info\":\n                log.info(\"track_targets: \" + str(trackdata[1:]))\n                if trackdata[1] == \"initcomp\":\n                    self.state = \"initialised\"\n            return\n        # Unpack and cast target data to correct types\n        try:\n            [id,x,y,z,processtime,sensorTimestamp,sendTimestamp,receiveTimestamp] = trackdata[1:]\n            [id,x,y,z,processtime,sensorTimestamp,sendTimestamp,receiveTimestamp] = [int(id),float(x),float(y),float(z),float(processtime),float(sensorTimestamp),float(sendTimestamp),float(receiveTimestamp)]\n        except:\n            log.debug(\"track_targets: error in data: \" + str(line.rstrip()))\n            return\n        # If fake rangefinder distance is required, send it\n        if args.fakerangefinder:\n            craft.send_distance_message(int(z*100))\n        # Send the landing_target message to arducopter\n        # NOTE: This sends the current estimated fctime, NOT the time the frame was actually captured.\n        # So this does not allow for the CV processing time. This should be sending when the frame is actually captured, before processing.\n        nowTime = monotonic_time()\n        # If data is less than 250ms since the image shuttr, send the message.\n        if nowTime - sensorTimestamp < 250 * 1e+6:\n            craft.send_land_message(x, y, z, tracktime.toFcTime(sensorTimestamp) / 1000, id) # Send sensor timestamp adjusted to timesync, in micros\n        # Track frame timing to calculate fps, running average over last 10 frames\n        end_t = time()\n        time_taken = end_t - self.start_t\n        self.start_t = end_t\n        self.frame_times.append(time_taken)\n        self.frame_times = self.frame_times[-10:]\n        fps = len(self.frame_times) / sum(self.frame_times)\n        log.info(\"Fctime:{:.0f}:{:.0f}, Fps:{:.2f}, Alt:{}, Rng:{}, Marker:{}, Distance:{}, xOffset:{}, yOffset:{}, processTime:{:.0f}, sensorTime:{:.0f}, sendTime:{:.0f}, receiveTime:{:.0f}, currentTime:{:.0f}, sensorDiff:{}, sendDiff:{}, receiveDiff:{}\".format(tracktime.actual(), tracktime.estimate(), fps, craft.vehicle.location.global_relative_frame.alt, craft.vehicle.rangefinder.distance, id, z, x, y, processtime, sensorTimestamp, sendTimestamp, receiveTimestamp, nowTime, nowTime - sensorTimestamp, nowTime - sendTimestamp, nowTime - receiveTimestamp))\n    def start(self):\n        if self.state == \"initialised\":\n            log.info(\"Requesting track_targets to start tracking:\"+str(craft.vehicle.mode))\n            self.process.send_signal(signal.SIGUSR1)\n            self.state = \"started\"\n        else:\n            log.info(\"Request to start track_targets tracking failed, state is not 'initialised'\")\n    def stop(self):\n        log.info(\"Requesting track_targets to stop tracking:\"+str(craft.vehicle.mode))\n        self.state = \"initialised\"\n        self.process.send_signal(signal.SIGUSR2)\n    def end(self):\n        log.info(\"Shutting down track_targets\")\n        # Stop threaded reader\n        self.reader.stop()\n        # track_targets should always be stopped by now, but be sure\n        self.process.poll()\n        if self.process.returncode == None:\n            self.process.terminate()\n        self.shutdown = True\n\n# The Craft class connects to the flight controller and sends controlling messages\nclass Craft:\n    def __init__(self, connectstr):\n        self.debug = False\n        self.mode = None\n        self.connected = None\n        self.vehicle = None\n        self.connect(connectstr)\n        self.precloiter_opt = self.find_precloiter_opt()\n        if self.precloiter_opt:\n            log.info(\"Precision loiter switch found: Channel \"+str(self.precloiter_opt))\n    def connect(self, connectstr):\n        try:\n            # self.vehicle = connect(connectstr, wait_ready=True, rate=1)\n            # self.vehicle = connect(connectstr, wait_ready=True)\n            # self.vehicle = connect(connectstr, wait_ready=['system_status','mode'], baud=921600)\n            self.vehicle = connect(connectstr, wait_ready=['system_status','mode'])\n            self.connected = True\n        except Exception,e:\n            log.critical(\"Error connecting to vehicle:\"+str(repr(e)))\n            self.connected = False\n    # Define function to send distance_message mavlink message for mavlink based rangefinder, must be >10hz\n    # http://mavlink.org/messages/common#DISTANCE_SENSOR\n    def send_distance_message(self, dist):\n        msg = self.vehicle.message_factory.distance_sensor_encode(\n            0,          # time since system boot, not used\n            1,          # min distance cm\n            10000,      # max distance cm\n            dist,       # current distance, must be int\n            0,          # type = laser?\n            0,          # onboard id, not used\n            mavutil.mavlink.MAV_SENSOR_ROTATION_PITCH_270, # must be set to MAV_SENSOR_ROTATION_PITCH_270 for mavlink rangefinder, represents downward facing\n            0           # covariance, not used\n        )\n        self.vehicle.send_mavlink(msg)\n        self.vehicle.flush()\n        if args.verbose:\n            log.debug(\"Sending mavlink distance_message:\" +str(dist))\n    # Define function to send landing_target mavlink message for mavlink based precision landing\n    # http://mavlink.org/messages/common#LANDING_TARGET\n    def send_land_message(self, x,y,z, time_usec=0, target_num=0):\n        msg = self.vehicle.message_factory.landing_target_encode(\n            time_usec,          # time target data was processed, as close to sensor capture as possible\n            target_num,          # target num, not used\n            mavutil.mavlink.MAV_FRAME_BODY_NED, # frame, not used\n            x,          # X-axis angular offset, in radians\n            y,          # Y-axis angular offset, in radians\n            z,          # distance, in meters\n            0,          # Target x-axis size, in radians\n            0,          # Target y-axis size, in radians\n            0,          # x\tfloat\tX Position of the landing target on MAV_FRAME\n            0,          # y\tfloat\tY Position of the landing target on MAV_FRAME\n            0,          # z\tfloat\tZ Position of the landing target on MAV_FRAME\n            (1,0,0,0),  # q\tfloat[4]\tQuaternion of landing target orientation (w, x, y, z order, zero-rotation is 1, 0, 0, 0)\n            2,          # type of landing target: 2 = Fiducial marker\n            1,          # position_valid boolean\n        )\n        self.vehicle.send_mavlink(msg)\n        self.vehicle.flush()\n        if args.verbose:\n            log.debug(\"Sending mavlink landing_target - time_usec:{:.0f}, x:{}, y:{}, z:{}\".format(time_usec, str(x), str(y), str(z)))\n    # Define function that arms and takes off, used for testing in SITL\n    # Lifted from dronekit-python examples\n    def arm_and_takeoff(self, targetAltitude):\n        log.info(\"Basic pre-arm checks\")\n        # Don't let the user try to arm until autopilot is ready\n        while not self.vehicle.is_armable:\n            log.info(\" Waiting for vehicle to initialise...\")\n            sleep(1)\n        log.info(\"Arming motors\")\n        # Copter should arm in GUIDED mode\n        self.vehicle.mode = VehicleMode(\"GUIDED\")\n        self.vehicle.armed = True\n        while not self.vehicle.armed:      \n            log.info(\" Waiting for arming...\")\n            sleep(1)\n        log.info(\"Taking off!\")\n        self.vehicle.simple_takeoff(targetAltitude) # Take off to target altitude\n        # Wait until the vehicle reaches a safe height before processing the goto (otherwise the command \n        #  after Vehicle.simple_takeoff will execute immediately).\n        while True:\n            log.info(\" Altitude: \" + str(self.vehicle.location.global_relative_frame.alt))\n            if self.vehicle.location.global_relative_frame.alt>=targetAltitude*0.95: #Trigger just below target alt.\n                log.info(\"Reached target altitude\")\n                break\n            sleep(1)\n    # Scan through option channels for one set to 39 (precision loiter)\n    def find_precloiter_opt(self):\n        _optch = None\n        for ch in range(7,16):\n            try:\n                if self.vehicle.parameters['CH'+str(ch)+'_OPT'] == 39:\n                    _optch = ch\n            except:\n                pass\n        return _optch\n\n# Class for signal tracking and handling.  This is used to accept Ctrl-C or SIGHUP/SIGKILL type events.\nclass SigTrack:\n    def __init__(self):\n        self.counter = 0\n    def add(self):\n        self.counter += 1\n    def count(self):\n        return self.counter\n    def handle_sig(self, signal, frame):\n        log.info(\"Signal handler called, calling shutdown and cleanup logic\")\n        track_targets.end()\n        sigtracker.add()\n        log.debug(\"Sigtracker count:\"+str(sigtracker.count()))\n        if sigtracker.count() >= 3:\n            log.warning(\"Signal handler called three times, exiting immediately\")\n            exit(1)\n\n### ================================\n### End Define Classes\n### ================================\n\n\n### --------------------------------\n### Parse arguments, setup logging\n### --------------------------------\n\n# Find full directory path of this script, used for loading config and other files\ncwd = path.dirname(path.abspath(__file__))\n\n# Find current time, used for dating files\nnow = datetime.now()\nnowtime = now.strftime(\"%Y-%m-%d-%H-%M-%S\")\n\n# Configure argument parsing\nimport argparse\nimport ConfigParser\nparser = argparse.ArgumentParser(description='Vision based precision landing')\nparser.add_argument('--config', '-c', default=cwd+\"/vision_landing.conf\", help=\"config file location, defaults to same directory as vision_landing\")\nparser.add_argument('--connect', help=\"dronekit vehicle connection target string, eg. /dev/ttyS0, tcp:localhost:5770, udp:localhost:14560\")\nparser.add_argument('--markersize', help=\"Target marker size, in meters, required\")\nparser.add_argument('--sizemapping', '-z', help=\"Marker Size Mappings, in marker_id:size format, comma separated\")\nparser.add_argument('--markerhistory', help=\"Marker tracking history, in frames, defaults to 15\")\nparser.add_argument('--markerthreshold', help=\"Marker tracking threshold, in percentage, defaults to 50\")\nparser.add_argument('--calibration', help=\"camera calibration data, required\")\nparser.add_argument('--input', '-i', default=\"/dev/video0\", help=\"camera input, defaults to /dev/video0\")\nparser.add_argument('--output', '-o', help=\"gstreamer output pipeline, defaults to none\")\nparser.add_argument('--markerdict', '-d', default=\"ARUCO_MIP_36h12\", help=\"Target marker dictionary, defaults to ARUCO_MIP_36h12\")\nparser.add_argument('--markerid', '-id', help=\"Target ID (optional, if not specified will use closest target)\")\nparser.add_argument('--simulator', '-s', action='store_true', help=\"Perform initial simulator actions for testing, takeoff and initiate land\")\nparser.add_argument('--width', '-w', help=\"Video Input Resolution - Width\")\nparser.add_argument('--height', '-g', help=\"Video Input Resolution - Height\")\nparser.add_argument('--fps', '-f', help=\"Video Output FPS - Kludge factor\")\nparser.add_argument('--verbose', '-v', action='store_true', help=\"Verbose/Debug output\")\nparser.add_argument('--brightness', '-b', help=\"Camera Brightness/Gain\")\nparser.add_argument('--fourcc', '-u', help=\"Specify FourCC codec\")\nparser.add_argument('--fakerangefinder', '-r', action='store_true', help=\"Fake RangeFinder Data\")\nparser.add_argument('--logdir', '-l', help=\"Log directory, if not specified will log to stdout\")\nparser.add_argument('--controlprocessing', '-p', action='store_true', help=\"Control Vision Processing - enable/disable based on arming status and landing/precloiter mode\")\nparser.add_argument('--estimator', '-e', help=\"ACPrecLand estimator, 0=Raw, 1=EKF.  Defaults to 0 (Raw)\")\nargs = parser.parse_args()\n# First parse config file, and set defaults\ndefaults = {}\nif path.isfile(args.config):\n    config = ConfigParser.SafeConfigParser()\n    config.read([args.config])\n    for key, value in config.items(\"Defaults\"):\n        defaults[key] = get_config_value(config, \"Defaults\", key)\n    parser.set_defaults(**defaults)\n    args = parser.parse_args()\nelse:\n    print\n    print \"Error: Config file \"+str(args.config)+\" does not exist\"\n    print\n    exit(1)\n    \n# If we don't have the mandatory arguments, exit\nif not args.calibration or not args.markersize or not args.connect:\n    print\n    if not args.calibration:\n        print \"Error: missing required argument 'calibration'\"\n    if not args.markersize:\n        print \"Error: missing required argument 'markersize'\"\n    if not args.connect:\n        print \"Error: missing required argument 'connect'\"\n    print\n    parser.print_usage()\n    exit(1)\n\n# Setup logging\nconsole = logging.StreamHandler()\nif args.logdir:\n    # If logdir specified, create if it doesn't exist\n    if not path.exists(args.logdir):\n        makedirs(args.logdir)\n    # Add timestamped logfile out\n    logging.basicConfig(filename=args.logdir+'/vision_landing.'+nowtime+'.log', format='%(asctime)s %(levelname)s %(message)s', level=logging.DEBUG)\n    # Create handly symlink to current logfile\n    if path.exists(args.logdir+'/last.log'):\n        remove(args.logdir+'/last.log')\n    symlink(args.logdir+'/vision_landing.'+nowtime+'.log', args.logdir+'/last.log')\nelse:\n    logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.DEBUG)\nlog = logging.getLogger(__name__)\n\n# Check if calibration data exists\nif path.isfile(cwd+\"/calibration/\"+args.calibration):\n    calibration = cwd+\"/calibration/\"+args.calibration\nelif path.isfile(args.calibration):\n    calibration = args.calibration\nelse:\n    log.critical(\"Error: specified calibration does not exist.\")\n    exit(1)\n\n### --------------------------------\n### Start track_targets CV process\n###  and attach threaded reader\n### --------------------------------\n\n# Check track_targets exists\nif not path.isfile(cwd+\"/track_targets\"):\n    log.critical(\"Error: track_targets does not exist.  Please run 'make install' in src/ directory\")\n    exit(1)\n\n# Run the vision tracker as a thread\ntry:\n    track_targets = TrackTargets(args, calibration)\n    sleep(1)\nexcept Exception as error:\n    log.critical(\"Error starting track_targets:\"+ str(error))\n    exit(1)\ntrack_targets.process.poll()\nif track_targets.process.returncode != None:\n    log.critical(\"Error starting track_targets: \".format(track_targets.process.returncode))\n    exit(1)\n\n# Define a function that stops and clears up cv process\ndef cleanup():\n    # Do a final check to see if tracker process still running, try to shut down if so\n    track_targets.process.poll()\n    if track_targets.process.returncode == None:\n        track_targets.end()\n    # Close connection to the drone\n    try:\n        craft.vehicle.close()\n    except:\n        pass\n\n### --------------------------------\n### Start up procedure - setup signal handlers,\n###  connect to drone, start syncing time with drone,\n###  setup drone parameters\n### --------------------------------\n\n# Setup signal handlers\nsigtracker = SigTrack()\nsignal.signal(signal.SIGINT, sigtracker.handle_sig)\nsignal.signal(signal.SIGTERM, sigtracker.handle_sig)\n\n# Connect to the Vehicle\nlog.info(\"Connecting to drone on: %s\" % args.connect)\ncraft = Craft(args.connect)\nif not craft.connected:\n    log.critical(\"Error: Could not connect to drone\")\n    cleanup()\n    exit(1)\nelse:\n    log.info(\"Connected to drone\")\n\n# Create a new TrackTime object to try and keep sync with the flight controller\nlog.info(\"Starting time synchronisation with flight controller\")\ntracktime = TrackTime(craft)\ntracktime.debug = False\n\n# Perform the initial sync with the flight controller.  This blocks until the sync is complete and good enough.\nwhile True:\n    tracktime.initial_sync()\n    if not tracktime.delta:\n        log.warning(\"Timesync not supported by flight controller. THIS CAN LEAD TO DANGEROUS AND UNPREDICTABLE BEHAVIOUR.\")\n        break\n    log.info(\"Initial timesync complete, offset is {} ms\".format(tracktime.delta/1000000))\n    log.info(\"Initial timesync difference is {} ms\".format(tracktime.difference/1000000))\n    log.info(\"Initial timesync delta buffer: {}\".format(list(tracktime.delta_buffer)))\n    _dvariance = map(lambda x: (x - tracktime.delta)**2, tracktime.delta_buffer)\n    _variance = sum(_dvariance) * 1.0 / len(_dvariance)\n    # Calculate standard deviation of delta (latency) variance\n    # A median standard deviation would probably be better here to represent jitter\n    stddev = round((_variance ** 0.5 / 1000000), 2)\n    jitterpercent = round((stddev / (tracktime.delta/1000000)) * 100, 2)\n    log.info(\"Initial timesync jitter (standard deviation of delta buffer): {} ms, {}% of average latency\".format(stddev, jitterpercent))\n    if tracktime.delta/1000000 >= 40:\n        log.warning(\"Error: Timesync not good enough, trying again\")\n        tracktime.delta_buffer.clear() # Clear the buffer to force a fresh resync\n        continue\n    else:\n        break\n    if jitterpercent > 25:\n        log.info(\"WARNING: Timesync jitter is very high. This will signficantly affect video frame -> inertial frame correlation.\")\n\n# Set some parameters important to precision landing\nlog.info(\"Setting flight controller parameters\")\ncraft.vehicle.parameters['PLND_ENABLED'] = 1\ncraft.vehicle.parameters['PLND_TYPE'] = 1 # Mavlink landing backend\n# Set estimator type to 'raw', as ekf estimator can be very erratic\ntry:\n    if 'PLND_EST_TYPE' in craft.vehicle.parameters:\n        try:\n            craft.vehicle.parameters['PLND_EST_TYPE'] = int(args.estimator)\n            log.info(\"plnd estimator: {}, {}\".format(craft.vehicle.parameters['PLND_EST_TYPE'], args.estimator))\n        except Exception as e:\n            log.info(\"plnd estimator error: {} - setting estimator to type 0\".format(repr(e)))\n            craft.vehicle.parameters['PLND_EST_TYPE'] = 0\nexcept:\n    pass\n# Set the precland buffer to 250ms.  This should give enough buffer space for even very slow computers\ntry:\n    if 'PLND_BUFFER' in craft.vehicle.parameters:\n        craft.vehicle.parameters['PLND_BUFFER'] = 250\nexcept:\n    pass\n\nif args.fakerangefinder:\n    # Following are for mavlink based rangefinder (not needed for 3.5-rc2+)\n    craft.vehicle.parameters['RNGFND_TYPE'] = 10\n    craft.vehicle.parameters['RNGFND_MIN_CM'] = 1\n    craft.vehicle.parameters['RNGFND_MAX_CM'] = 10000\n    craft.vehicle.parameters['RNGFND_GNDCLEAR'] = 5\n    log.info(\"Faking RangeFinder data with distance_sensor messages\")\n\n# If simulator option set, perform initial takeoff and initiate land\nif args.simulator:\n    if args.fakerangefinder:\n        # Following are for SITL rangefinder\n        craft.vehicle.parameters['RNGFND_TYPE'] = 1 \n        craft.vehicle.parameters['RNGFND_MIN_CM'] = 0\n        craft.vehicle.parameters['RNGFND_MAX_CM'] = 4000\n        craft.vehicle.parameters['RNGFND_PIN'] = 0\n        craft.vehicle.parameters['RNGFND_SCALING'] = 12.12\n    # Take off to 25m altitude and start landing if not already armed\n    if not craft.vehicle.armed:\n        craft.arm_and_takeoff(100)\n        # Start landing\n        log.info(\"Starting landing...\")\n        craft.vehicle.mode = VehicleMode(\"LAND\")\n\n# Clear the vision tracking queue, we don't want to blast mavlink messages for everything stacked up\nwhile True:\n    line = track_targets.reader.readline()\n    if not line:\n        break\n    elif not search(\"^target:\", line):\n        if search(\"^error:\", line):\n            log.error(\"track_targets: \"+sub(\"^error:\",\"\",line))\n        # Make sure to catch and process initcomp if it's in this initial queue\n        elif search(\"initcomp\", line):\n            track_targets.processline(line)\n        else:\n            log.info(\"track_targets: \"+line)\n\n### --------------------------------\n### Main Loop\n### Monitor for landing/precloiter mode\n### Listen for incoming cv tracking results\n### --------------------------------\nlog.info(\"Entering main tracking loop\")\nloop_counter = 0\nwhile True:\n    # Update timesync\n    tracktime.update()\n\n    # If craft mode has changed, take action\n    if (args.controlprocessing and (craft.vehicle.armed and (craft.vehicle.mode == \"LAND\" or (craft.vehicle.mode == \"LOITER\" and (craft.precloiter_opt and craft.vehicle.channels[str(craft.precloiter_opt)] > 1800))))) and track_targets.state == \"initialised\":\n        track_targets.start()\n    elif (args.controlprocessing and (not craft.vehicle.armed or (craft.vehicle.mode != \"LAND\" and (craft.vehicle.mode != \"LOITER\" and (craft.precloiter_opt and craft.vehicle.channels[str(craft.precloiter_opt)] <= 1800))))) and track_targets.state == \"started\":\n        track_targets.stop()\n    elif not args.controlprocessing and track_targets.state == \"initialised\":\n        track_targets.start()\n\n    # See if there are any tracking results in the queue\n    #log.debug(\"Main loop: Before readline: {:.0f}\".format(monotonic_time()))\n    line = track_targets.reader.readline(1)\n    #log.debug(\"Main loop: After readline: {:.0f}\".format(monotonic_time()))\n    if line:\n        if args.verbose:\n            log.debug(\"queue size:{}, ourtime:{:.0f}, line:{}\".format(track_targets.reader.size(), monotonic_time(), line))\n        track_targets.processline(line)\n        #log.debug(\"Main loop: After processline: {:.0f}\".format(monotonic_time()))\n    else:\n        # Add a short 100ms sleep to slow down the loop, otherwise it consumes 100% cpu.\n        log.debug(\"Main loop queue read empty, sleeping for a few ms\")\n        sleep(0.1)\n\n    if args.simulator and not craft.vehicle.armed and not track_targets.shutdown:\n        log.info(\"Landed\")\n        track_targets.end()\n\n    track_targets.process.poll() # Poll the track_targets process and populate returncode, exit main loop when track_targets shut down\n    if track_targets.process.returncode != None and track_targets.shutdown:\n        log.info(\"Tracking process return code:\"+str(track_targets.process.returncode)+\", exiting main loop\")\n        break\n    elif track_targets.process.returncode != None and not track_targets.shutdown and track_targets.state == \"started\":\n        log.error(\"Error: Tracking process shut down unexpectedly (\"+str(track_targets.process.returncode)+\"), restarting\")\n        track_targets = TrackTargets(args, calibration)\n\n    loop_counter += 1\n    \ncleanup()\nlog.info(\"Vision_landing shutdown complete, exiting\")\nexit(track_targets.process.returncode)\n"
  },
  {
    "path": "vision_landing.service",
    "content": "[Unit]\nDescription=Vision Landing System\n\n[Service]\nExecStart=/usr/local/vision_landing/vision_landing\nTimeoutStartSec=0\n\n[Install]\nWantedBy=multi-user.target\n"
  }
]