code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
--TEST-- Indented Standalone Tag --DESCRIPTION-- Indented standalone lines should be removed from the template. --SKIPIF-- <?php if(!extension_loaded('mustache')) die('skip '); ?> --FILE-- <?php $test = array ( 'name' => 'Indented Standalone Tag', 'desc' => 'Indented standalone lines should be removed from the template.', 'data' => array ( ), 'template' => 'Begin. {{=@ @=}} End. ', 'expected' => 'Begin. End. ', ); $mustache = new Mustache(); echo $mustache->render($test["template"], $test["data"]); ?> --EXPECTREGEX-- Begin\.\s*End\.\s*
cgvarela/php-mustache
tests/mustache-spec-delimiters-indented-standalone-tag.phpt
PHP
mit
558
#include "nth_prime.h" #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <stdexcept> BOOST_AUTO_TEST_CASE(first) { BOOST_REQUIRE_EQUAL(2, prime::nth(1)); } #if defined(EXERCISM_RUN_ALL_TESTS) BOOST_AUTO_TEST_CASE(second) { BOOST_REQUIRE_EQUAL(3, prime::nth(2)); } BOOST_AUTO_TEST_CASE(sixth) { BOOST_REQUIRE_EQUAL(13, prime::nth(6)); } BOOST_AUTO_TEST_CASE(big_prime) { BOOST_REQUIRE_EQUAL(104743, prime::nth(10001)); } BOOST_AUTO_TEST_CASE(weird_case) { BOOST_REQUIRE_THROW(prime::nth(0), std::domain_error); } #endif
lukasz-m-maciejewski/xcpp
nth-prime/nth_prime_test.cpp
C++
mit
563
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Release Notes</title> <link rel="stylesheet" href="../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../boost_units.html" title="Chapter&#160;35.&#160;Boost.Units 1.1.0"> <link rel="prev" href="version_id.html" title="Version Info"> <link rel="next" href="TODO.html" title="TODO"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../boost.png"></td> <td align="center"><a href="../../../index.html">Home</a></td> <td align="center"><a href="../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="version_id.html"><img src="../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../boost_units.html"><img src="../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="TODO.html"><img src="../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h2 class="title" style="clear: both"> <a name="boost_units.ReleaseNotes"></a><a class="link" href="ReleaseNotes.html" title="Release Notes">Release Notes</a> </h2></div></div></div> <p> 1.2 (March 2010) </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"> Added autoprefix ready for Boost 1.43 </li></ul></div> <p> 1.0.0 (August 1, 2008) : </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"> Initial release with Boost 1.36 </li></ul></div> <p> 0.7.1 (March 14, 2007) : </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> Boost.Typeof emulation support. </li> <li class="listitem"> attempting to rebind a heterogeneous_system to a different set of dimensions now fails. </li> <li class="listitem"> cmath.hpp now works with como-win32. </li> <li class="listitem"> minor changes to the tests and examples to make msvc 7.1 happy. </li> </ul></div> <p> 0.7.0 (March 13, 2007) : </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> heterogeneous and mixed system functionality added. </li> <li class="listitem"> added fine-grained implicit unit conversion on a per fundamental dimension basis. </li> <li class="listitem"> added a number of utility metafunction classes and predicates. </li> <li class="listitem"> <code class="computeroutput"><a class="link" href="Reference.html#header.boost.units.operators_hpp" title="Header &lt;boost/units/operators.hpp&gt;">boost/units/operators.hpp</a></code> now uses <code class="computeroutput"><span class="identifier">BOOST_TYPEOF</span></code> when possible. </li> <li class="listitem"> angular units added in <code class="computeroutput"><a class="link" href="Reference.html#header.boost.units.systems.angle.gradians_hpp" title="Header &lt;boost/units/systems/angle/gradians.hpp&gt;">boost/units/systems/angle/gradians.hpp</a></code> and <code class="computeroutput"><a class="link" href="Reference.html#header.boost.units.systems.angle.gradians_hpp" title="Header &lt;boost/units/systems/angle/gradians.hpp&gt;">boost/units/systems/angle/gradians.hpp</a></code>. Implicit conversion of radians between trigonometric, SI, and CGS systems is allowed. </li> <li class="listitem"> a variety of <span class="underline"><code class="computeroutput"><a class="link" href="../boost/units/unit.html" title="Class template unit">unit</a></code></span> and <span class="underline"><code class="computeroutput"><a class="link" href="../boost/units/quantity.html" title="Class template quantity">quantity</a></code></span> tests added. </li> <li class="listitem"> examples now provide self-tests. </li> </ul></div> <p> 0.6.2 (February 22, 2007) : </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> changed template order in <code class="computeroutput"><span class="identifier">unit</span></code> so dimension precedes unit system </li> <li class="listitem"> added <code class="computeroutput"><span class="identifier">homogeneous_system</span><span class="special">&lt;</span><span class="identifier">S</span><span class="special">&gt;</span></code> for unit systems </li> <li class="listitem"> incorporated changes to <code class="computeroutput"><a class="link" href="Reference.html#header.boost.units.dimension_hpp" title="Header &lt;boost/units/dimension.hpp&gt;">boost/units/dimension.hpp</a></code> (compile-time sorting by predicate), <code class="computeroutput"><a class="link" href="Reference.html#header.boost.units.conversion_hpp" title="Header &lt;boost/units/conversion.hpp&gt;">boost/units/conversion.hpp</a></code> (thread-safe implementation of quantity conversions), and <code class="computeroutput"><a class="link" href="Reference.html#header.boost.units.io_hpp" title="Header &lt;boost/units/io.hpp&gt;">boost/units/io.hpp</a></code> (now works with any <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_ostream</span></code>) by SW </li> <li class="listitem"> added abstract units in <code class="computeroutput"><a class="link" href="Reference.html#header.boost.units.systems.abstract_hpp" title="Header &lt;boost/units/systems/abstract.hpp&gt;">boost/units/systems/abstract.hpp</a></code> to allow abstract dimensional analysis </li> <li class="listitem"> new example demonstrating implementation of code based on requirements from Michael Fawcett (<a href="../../../libs/units/example/radar_beam_height.cpp" target="_top">radar_beam_height.cpp</a>) </li> </ul></div> <p> 0.6.1 (February 13, 2007) : </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> added metafunctions to test if a type is <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "> <li class="listitem"> a valid dimension list (<code class="computeroutput"><span class="identifier">is_dimension_list</span><span class="special">&lt;</span><span class="identifier">D</span><span class="special">&gt;</span></code>) </li> <li class="listitem"> a unit (<code class="computeroutput"><span class="identifier">is_unit</span><span class="special">&lt;</span><span class="identifier">T</span><span class="special">&gt;</span></code> and <code class="computeroutput"><span class="identifier">is_unit_of_system</span><span class="special">&lt;</span><span class="identifier">U</span><span class="special">,</span><span class="identifier">System</span><span class="special">&gt;</span></code>) </li> <li class="listitem"> a quantity (<code class="computeroutput"><span class="identifier">is_quantity</span><span class="special">&lt;</span><span class="identifier">T</span><span class="special">&gt;</span></code> and <code class="computeroutput"><span class="identifier">is_quantity_of_system</span><span class="special">&lt;</span><span class="identifier">Q</span><span class="special">,</span><span class="identifier">System</span><span class="special">&gt;</span></code>) </li> </ul></div> </li> <li class="listitem"> quantity conversion factor is now computed at compile time </li> <li class="listitem"> static constants now avoid ODR problems </li> <li class="listitem"> unit_example_14.cpp now uses Boost.Timer </li> <li class="listitem"> numerous minor fixes suggested by SW </li> </ul></div> <p> 0.6.0 (February 8, 2007) : </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"> incorporated Steven Watanabe's optimized code for dimension.hpp, leading to <span class="bold"><strong>dramatic</strong></span> decreases in compilation time (nearly a factor of 10 for unit_example_4.cpp in my tests). </li></ul></div> <p> 0.5.8 (February 7, 2007) : </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> fixed <code class="computeroutput"><span class="preprocessor">#include</span></code> in <code class="computeroutput"><a class="link" href="Reference.html#header.boost.units.systems.si.base_hpp" title="Header &lt;boost/units/systems/si/base.hpp&gt;">boost/units/systems/si/base.hpp</a></code> (thanks to Michael Fawcett and Steven Watanabe) </li> <li class="listitem"> removed references to obsolete <code class="computeroutput"><span class="identifier">base_type</span></code> in <span class="underline">__unit_info</span> (thanks to Michael Fawcett) </li> <li class="listitem"> moved functions in <code class="computeroutput"><a class="link" href="Reference.html#header.boost.units.cmath_hpp" title="Header &lt;boost/units/cmath.hpp&gt;">boost/units/cmath.hpp</a></code> into <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">units</span></code> namespace (thanks to Steven Watanabe) </li> <li class="listitem"> fixed <code class="computeroutput"><span class="preprocessor">#include</span></code> guards to be consistently named <code class="computeroutput"><span class="identifier">BOOST_UNITS_XXX</span></code> (thanks to Steven Watanabe) </li> </ul></div> <p> 0.5.7 (February 5, 2007) : </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> changed quantity conversion helper to increase flexibility </li> <li class="listitem"> minor documentation changes </li> <li class="listitem"> submitted for formal review as a Boost library </li> </ul></div> <p> 0.5.6 (January 22, 2007) : </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> added IEEE 1541 standard binary prefixes along with SI prefixes to and extended algebra of <code class="computeroutput"><span class="identifier">scale</span></code> and <code class="computeroutput"><span class="identifier">scaled_value</span></code> classes (thanks to Kevin Lynch) </li> <li class="listitem"> split SI units into separate header files to minimize the "kitchen sink" include problem (thanks to Janek Kozicki) </li> <li class="listitem"> added convenience classes for declaring fundamental dimensions and composite dimensions with integral powers (<code class="computeroutput"><span class="identifier">fundamental_dimension</span></code> and <code class="computeroutput"><span class="identifier">composite_dimension</span></code> respectively) </li> </ul></div> <p> 0.5.5 (January 18, 2007) : </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> template parameter order in <code class="computeroutput"><span class="identifier">quantity</span></code> switched and default <code class="computeroutput"><span class="identifier">value_type</span></code> of <code class="computeroutput"><span class="keyword">double</span></code> added (thanks to Andrey Semashev and Paul Bristow) </li> <li class="listitem"> added implicit <code class="computeroutput"><span class="identifier">value_type</span></code> conversion where allowed (thanks to Andrey Semashev) </li> <li class="listitem"> added <code class="computeroutput"><span class="identifier">quantity_cast</span></code> for three cases (thanks to Andrey Semashev): <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "> <li class="listitem"> constructing <code class="computeroutput"><span class="identifier">quantity</span></code> from raw <code class="computeroutput"><span class="identifier">value_type</span></code> </li> <li class="listitem"> casting from one <code class="computeroutput"><span class="identifier">value_type</span></code> to another </li> <li class="listitem"> casting from one <code class="computeroutput"><span class="identifier">unit</span></code> to another (where conversion is allowed) </li> </ul></div> </li> <li class="listitem"> added<code class="computeroutput"> <span class="identifier">metre</span></code> and <code class="computeroutput"><span class="identifier">metres</span></code> and related constants to the SI system for the convenience of our Commonwealth friends... </li> </ul></div> <p> 0.5.4 (January 12, 2007) : </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> completely reimplemented unit conversion to allow for arbitrary unit conversions between systems </li> <li class="listitem"> strict quantity construction is default; quantities can be constructed from bare values by using static member <code class="computeroutput"><span class="identifier">from_value</span></code> </li> </ul></div> <p> 0.5.3 (December 12, 2006) : </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> added Boost.Serialization support to <code class="computeroutput"><span class="identifier">unit</span></code> and <code class="computeroutput"><span class="identifier">quantity</span></code> classes </li> <li class="listitem"> added option to enforce strict construction of quantities (only constructible by multiplication of scalar by unit or quantity by unit) by preprocessor <code class="computeroutput"><span class="identifier">MCS_STRICT_QUANTITY_CONSTRUCTION</span></code> switch </li> </ul></div> <p> 0.5.2 (December 4, 2006) : </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"> added <code class="computeroutput"><span class="special">&lt;</span><span class="identifier">cmath</span><span class="special">&gt;</span></code> wrappers in the <code class="computeroutput"><span class="identifier">std</span></code> namespace for functions that can support quantities </li></ul></div> <p> 0.5.1 (November 3, 2006) : </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> converted to Boost Software License </li> <li class="listitem"> boostified directory structure and file paths </li> </ul></div> <p> 0.5 (November 2, 2006) : </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> completely reimplemented SI and CGS unit systems and changed syntax for quantities </li> <li class="listitem"> significantly streamlined <code class="computeroutput"><span class="identifier">pow</span></code> and <code class="computeroutput"><span class="identifier">root</span></code> so for most applications it is only necessary to define <code class="computeroutput"><span class="identifier">power_typeof_helper</span></code> and <code class="computeroutput"><span class="identifier">root_typeof_helper</span></code> to gain this functionality </li> <li class="listitem"> added a selection of physical constants from the CODATA tables </li> <li class="listitem"> added a skeleton <code class="computeroutput"><span class="identifier">complex</span></code> class that correctly supports both <code class="computeroutput"><span class="identifier">complex</span><span class="special">&lt;</span><span class="identifier">quantity</span><span class="special">&lt;</span><span class="identifier">Y</span><span class="special">,</span><span class="identifier">Unit</span><span class="special">&gt;</span> <span class="special">&gt;</span></code> and <code class="computeroutput"><span class="identifier">quantity</span><span class="special">&lt;</span><span class="identifier">complex</span><span class="special">&lt;</span><span class="identifier">Y</span><span class="special">&gt;,</span><span class="identifier">Unit</span><span class="special">&gt;</span></code> as an example </li> <li class="listitem"> investigate using Boost.Typeof for compilers that do not support <code class="computeroutput"><span class="identifier">typeof</span></code> </li> </ul></div> <p> 0.4 (October 13, 2006) : </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> <code class="computeroutput"><span class="identifier">pow</span><span class="special">&lt;</span><span class="identifier">R</span><span class="special">&gt;</span></code> and <code class="computeroutput"><span class="identifier">root</span><span class="special">&lt;</span><span class="identifier">R</span><span class="special">&gt;</span></code> improved for user-defined types </li> <li class="listitem"> added unary + and unary - operators </li> <li class="listitem"> added new example of interfacing with <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">math</span><span class="special">::</span><span class="identifier">quaternion</span></code> </li> <li class="listitem"> added optional preprocessor switch to enable implicit unit conversions (<code class="computeroutput"><span class="identifier">BOOST_UNITS_ENABLE_IMPLICIT_UNIT_CONVERSIONS</span></code>) </li> </ul></div> <p> 0.3 (September 6, 2006) : </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"> Support for <code class="computeroutput"><span class="identifier">op</span><span class="special">(</span><span class="identifier">X</span> <span class="identifier">x</span><span class="special">,</span><span class="identifier">Y</span> <span class="identifier">y</span><span class="special">)</span></code> for g++ added. This is automatically active when compiling with gcc and can be optionally enabled by defining the preprocessor constant <code class="computeroutput"><span class="identifier">BOOST_UNITS_HAS_TYPEOF</span></code> </li></ul></div> <p> 0.2 (September 4, 2006) : Second alpha release based on slightly modified code from 0.1 release </p> <p> 0.1 (December 13, 2003) : written as a Boost demonstration of MPL-based dimensional analysis in 2003. </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2008 Matthias Christian Schabel<br>Copyright &#169; 2007-2010 Steven Watanabe<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="version_id.html"><img src="../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../boost_units.html"><img src="../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="TODO.html"><img src="../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
laborautonomo/poedit
deps/boost/doc/html/boost_units/ReleaseNotes.html
HTML
mit
21,512
package nl.conspect.eventboot.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * Created by marten on 11-12-14. */ @Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("forward:/index.html"); } }
Conspect/spring-boot-lab
Opdracht 6/src/main/java/nl/conspect/eventboot/config/WebConfig.java
Java
mit
547
module Cms::Addon::OpendataRef::Site extend SS::Addon extend ActiveSupport::Concern included do embeds_ids :opendata_sites, class_name: "Cms::Site", metadata: { on_copy: :clear, branch: false } permit_params opendata_site_ids: [] end end
tany/ss
app/models/concerns/cms/addon/opendata_ref/site.rb
Ruby
mit
255
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>lxml.tests</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="lxml-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" ><a class="navbar" target="_top" href="/">lxml API</a></th> </tr></table></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="lxml-module.html">Package&nbsp;lxml</a> :: Package&nbsp;tests </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="lxml.tests-pysrc.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <h1 class="epydoc">Source Code for <a href="lxml.tests-module.html">Package lxml.tests</a></h1> <pre class="py-src"> <a name="L1"></a><tt class="py-lineno">1</tt> <tt class="py-line"><tt class="py-docstring">"""</tt> </tt> <a name="L2"></a><tt class="py-lineno">2</tt> <tt class="py-line"><tt class="py-docstring">The lxml test suite for lxml, ElementTree and cElementTree.</tt> </tt> <a name="L3"></a><tt class="py-lineno">3</tt> <tt class="py-line"><tt class="py-docstring">"""</tt> </tt> <a name="L4"></a><tt class="py-lineno">4</tt> <tt class="py-line"> </tt><script type="text/javascript"> <!-- expandto(location.href); // --> </script> </pre> <br /> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="lxml-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" ><a class="navbar" target="_top" href="/">lxml API</a></th> </tr></table></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Sat Apr 25 16:24:38 2015 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
bertucho/epic-movie-quotes-quiz
dialogos/build/lxml/doc/html/api/lxml.tests-pysrc.html
HTML
mit
4,515
// dear imgui, v1.50 WIP // (headers) // See imgui.cpp file for documentation. // See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code. // Read 'Programmer guide' in imgui.cpp for notes on how to setup ImGui in your codebase. // Get latest version at https://github.com/ocornut/imgui #pragma once #if !defined(IMGUI_DISABLE_INCLUDE_IMCONFIG_H) || defined(IMGUI_INCLUDE_IMCONFIG_H) #include "imconfig.h" // User-editable configuration file #endif #include <float.h> // FLT_MAX #include <stdarg.h> // va_list #include <stddef.h> // ptrdiff_t, NULL #include <string.h> // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp #define IMGUI_VERSION "1.50 WIP" // Define attributes of all API symbols declarations, e.g. for DLL under Windows. #ifndef IMGUI_API #define IMGUI_API #endif // Define assertion handler. #ifndef IM_ASSERT #include <assert.h> #define IM_ASSERT(_EXPR) assert(_EXPR) #endif // Some compilers support applying printf-style warnings to user functions. #if defined(__clang__) || defined(__GNUC__) #define IM_PRINTFARGS(FMT) __attribute__((format(printf, FMT, (FMT+1)))) #else #define IM_PRINTFARGS(FMT) #endif #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wold-style-cast" #endif // Forward declarations struct ImDrawChannel; // Temporary storage for outputting drawing commands out of order, used by ImDrawList::ChannelsSplit() struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call) struct ImDrawData; // All draw command lists required to render the frame struct ImDrawList; // A single draw command list (generally one per window) struct ImDrawVert; // A single vertex (20 bytes by default, override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) struct ImFont; // Runtime data for a single font within a parent ImFontAtlas struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF font loader struct ImFontConfig; // Configuration data when adding a font or merging fonts struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 struct ImGuiIO; // Main configuration and I/O between your application and ImGui struct ImGuiOnceUponAFrame; // Simple helper for running a block of code not more than once a frame, used by IMGUI_ONCE_UPON_A_FRAME macro struct ImGuiStorage; // Simple custom key value storage struct ImGuiStyle; // Runtime data for styling/colors struct ImGuiTextFilter; // Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" struct ImGuiTextBuffer; // Text buffer for logging/accumulating text struct ImGuiTextEditCallbackData; // Shared state of ImGui::InputText() when using custom ImGuiTextEditCallback (rare/advanced use) struct ImGuiSizeConstraintCallbackData;// Structure used to constraint window size in custom ways when using custom ImGuiSizeConstraintCallback (rare/advanced use) struct ImGuiListClipper; // Helper to manually clip large list of items struct ImGuiContext; // ImGui context (opaque) // Typedefs and Enumerations (declared as int for compatibility and to not pollute the top of this file) typedef unsigned int ImU32; // 32-bit unsigned integer (typically used to store packed colors) typedef unsigned int ImGuiID; // unique ID used by widgets (typically hashed from a stack of string) typedef unsigned short ImWchar; // character for keyboard input/display typedef void* ImTextureID; // user data to identify a texture (this is whatever to you want it to be! read the FAQ about ImTextureID in imgui.cpp) typedef int ImGuiCol; // a color identifier for styling // enum ImGuiCol_ typedef int ImGuiStyleVar; // a variable identifier for styling // enum ImGuiStyleVar_ typedef int ImGuiKey; // a key identifier (ImGui-side enum) // enum ImGuiKey_ typedef int ImGuiAlign; // alignment // enum ImGuiAlign_ typedef int ImGuiColorEditMode; // color edit mode for ColorEdit*() // enum ImGuiColorEditMode_ typedef int ImGuiMouseCursor; // a mouse cursor identifier // enum ImGuiMouseCursor_ typedef int ImGuiWindowFlags; // window flags for Begin*() // enum ImGuiWindowFlags_ typedef int ImGuiSetCond; // condition flags for Set*() // enum ImGuiSetCond_ typedef int ImGuiInputTextFlags; // flags for InputText*() // enum ImGuiInputTextFlags_ typedef int ImGuiSelectableFlags; // flags for Selectable() // enum ImGuiSelectableFlags_ typedef int ImGuiTreeNodeFlags; // flags for TreeNode*(), Collapsing*() // enum ImGuiTreeNodeFlags_ typedef int (*ImGuiTextEditCallback)(ImGuiTextEditCallbackData *data); typedef void (*ImGuiSizeConstraintCallback)(ImGuiSizeConstraintCallbackData* data); // Others helpers at bottom of the file: // class ImVector<> // Lightweight std::vector like class. // IMGUI_ONCE_UPON_A_FRAME // Execute a block of code once per frame only (convenient for creating UI within deep-nested code that runs multiple times) struct ImVec2 { float x, y; ImVec2() { x = y = 0.0f; } ImVec2(float _x, float _y) { x = _x; y = _y; } #ifdef IM_VEC2_CLASS_EXTRA // Define constructor and implicit cast operators in imconfig.h to convert back<>forth from your math types and ImVec2. IM_VEC2_CLASS_EXTRA #endif }; struct ImVec4 { float x, y, z, w; ImVec4() { x = y = z = w = 0.0f; } ImVec4(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; } #ifdef IM_VEC4_CLASS_EXTRA // Define constructor and implicit cast operators in imconfig.h to convert back<>forth from your math types and ImVec4. IM_VEC4_CLASS_EXTRA #endif }; // ImGui end-user API // In a namespace so that user can add extra functions in a separate file (e.g. Value() helpers for your vector or common types) namespace ImGui { // Main IMGUI_API ImGuiIO& GetIO(); IMGUI_API ImGuiStyle& GetStyle(); IMGUI_API ImDrawData* GetDrawData(); // same value as passed to your io.RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame() IMGUI_API void NewFrame(); // start a new ImGui frame, you can submit any command from this point until NewFrame()/Render(). IMGUI_API void Render(); // ends the ImGui frame, finalize rendering data, then call your io.RenderDrawListsFn() function if set. IMGUI_API void Shutdown(); IMGUI_API void ShowUserGuide(); // help block IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // style editor block. you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style) IMGUI_API void ShowTestWindow(bool* p_open = NULL); // test window demonstrating ImGui features IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // metrics window for debugging ImGui // Window IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // push window to the stack and start appending to it. see .cpp for details. return false when window is collapsed, so you can early out in your code. 'bool* p_open' creates a widget on the upper-right to close the window (which sets your bool to false). IMGUI_API bool Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha = -1.0f, ImGuiWindowFlags flags = 0); // OBSOLETE. this is the older/longer API. the extra parameters aren't very relevant. call SetNextWindowSize() instead if you want to set a window size. For regular windows, 'size_on_first_use' only applies to the first time EVER the window is created and probably not what you want! might obsolete this API eventually. IMGUI_API void End(); // finish appending to current window, pop it off the window stack. IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // begin a scrolling region. size==0.0f: use remaining window size, size<0.0f: use remaining window size minus abs(size). size>0.0f: fixed size. each axis can use a different mode, e.g. ImVec2(0,400). IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // " IMGUI_API void EndChild(); IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos() IMGUI_API float GetContentRegionAvailWidth(); // IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min (roughly (0,0)-Scroll), in window coordinates IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates IMGUI_API float GetWindowContentRegionWidth(); // IMGUI_API ImDrawList* GetWindowDrawList(); // get rendering command-list if you want to append your own draw primitives IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList api) IMGUI_API ImVec2 GetWindowSize(); // get current window size IMGUI_API float GetWindowWidth(); IMGUI_API float GetWindowHeight(); IMGUI_API bool IsWindowCollapsed(); IMGUI_API void SetWindowFontScale(float scale); // per-window font scale. Adjust IO.FontGlobalScale if you want to scale all windows IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond = 0); // set next window position. call before Begin() IMGUI_API void SetNextWindowPosCenter(ImGuiSetCond cond = 0); // set next window position to be centered on screen. call before Begin() IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin() IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Use callback to apply non-trivial programmatic constraints. IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (enforce the range of scrollbars). set axis to 0.0f to leave it automatic. call before Begin() IMGUI_API void SetNextWindowContentWidth(float width); // set next window content width (enforce the range of horizontal scrollbar). call before Begin() IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond = 0); // set next window collapsed state. call before Begin() IMGUI_API void SetNextWindowFocus(); // set next window to be focused / front-most. call before Begin() IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiSetCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects. IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiSetCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0,0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiSetCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / front-most. prefer using SetNextWindowFocus(). IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond = 0); // set named window position. IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond = 0); // set named window collapsed state IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / front-most. use NULL to remove focus. IMGUI_API float GetScrollX(); // get scrolling amount [0..GetScrollMaxX()] IMGUI_API float GetScrollY(); // get scrolling amount [0..GetScrollMaxY()] IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.X - WindowSize.X IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.Y - WindowSize.Y IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0..GetScrollMaxX()] IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0..GetScrollMaxY()] IMGUI_API void SetScrollHere(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. IMGUI_API void SetScrollFromPosY(float pos_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position valid. use GetCursorPos() or GetCursorStartPos()+offset to get valid positions. IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use negative 'offset' to access previous widgets. IMGUI_API void SetStateStorage(ImGuiStorage* tree); // replace tree state storage with our own (if you want to manipulate it yourself, typically clear subsection of it) IMGUI_API ImGuiStorage* GetStateStorage(); // Parameters stacks (shared) IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font IMGUI_API void PopFont(); IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col); IMGUI_API void PopStyleColor(int count = 1); IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); IMGUI_API void PopStyleVar(int count = 1); IMGUI_API ImFont* GetFont(); // get current font IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied // Parameters stacks (current window) IMGUI_API void PushItemWidth(float item_width); // width of items for the common item+label case, pixels. 0.0f = default to ~2/3 of windows width, >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side) IMGUI_API void PopItemWidth(); IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position IMGUI_API void PushTextWrapPos(float wrap_pos_x = 0.0f); // word-wrapping for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space IMGUI_API void PopTextWrapPos(); IMGUI_API void PushAllowKeyboardFocus(bool v); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets IMGUI_API void PopAllowKeyboardFocus(); IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (uses io.KeyRepeatDelay/io.KeyRepeatRate for now). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame. IMGUI_API void PopButtonRepeat(); // Cursor / Layout IMGUI_API void Separator(); // horizontal line IMGUI_API void SameLine(float pos_x = 0.0f, float spacing_w = -1.0f); // call between widgets or groups to layout them horizontally IMGUI_API void NewLine(); // undo a SameLine() IMGUI_API void Spacing(); // add vertical spacing IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by style.IndentSpacing or indent_w if >0 IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by style.IndentSpacing or indent_w if >0 IMGUI_API void BeginGroup(); // lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) IMGUI_API void EndGroup(); IMGUI_API ImVec2 GetCursorPos(); // cursor position is relative to window position IMGUI_API float GetCursorPosX(); // " IMGUI_API float GetCursorPosY(); // " IMGUI_API void SetCursorPos(const ImVec2& local_pos); // " IMGUI_API void SetCursorPosX(float x); // " IMGUI_API void SetCursorPosY(float y); // " IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API) IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute screen coordinates [0..io.DisplaySize] IMGUI_API void AlignFirstTextHeightToWidgets(); // call once if the first item on the line is a Text() item and you want to vertically lower it to match subsequent (bigger) widgets IMGUI_API float GetTextLineHeight(); // height of font == GetWindowFontSize() IMGUI_API float GetTextLineHeightWithSpacing(); // distance (in pixels) between 2 consecutive lines of text == GetWindowFontSize() + GetStyle().ItemSpacing.y IMGUI_API float GetItemsLineHeightWithSpacing(); // distance (in pixels) between 2 consecutive lines of standard height widgets == GetWindowFontSize() + GetStyle().FramePadding.y*2 + GetStyle().ItemSpacing.y // Columns // You can also use SameLine(pos_x) for simplified columning. The columns API is still work-in-progress and rather lacking. IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true); // setup number of columns. use an identifier to distinguish multiple column sets. close with Columns(1). IMGUI_API void NextColumn(); // next column IMGUI_API int GetColumnIndex(); // get current column index IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetcolumnsCount() inclusive. column 0 is usually 0.0f and not resizable unless you call this IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column IMGUI_API float GetColumnWidth(int column_index = -1); // column width (== GetColumnOffset(GetColumnIndex()+1) - GetColumnOffset(GetColumnOffset()) IMGUI_API int GetColumnsCount(); // number of columns (what was passed to Columns()) // ID scopes // If you are creating widgets in a loop you most likely want to push a unique identifier so ImGui can differentiate them. // You can also use the "##foobar" syntax within widget label to distinguish them from each others. Read "A primer on the use of labels/IDs" in the FAQ for more details. IMGUI_API void PushID(const char* str_id); // push identifier into the ID stack. IDs are hash of the *entire* stack! IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end); IMGUI_API void PushID(const void* ptr_id); IMGUI_API void PushID(int int_id); IMGUI_API void PopID(); IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). useful if you want to query into ImGuiStorage yourself. otherwise rarely needed IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end); IMGUI_API ImGuiID GetID(const void* ptr_id); // Widgets IMGUI_API void Text(const char* fmt, ...) IM_PRINTFARGS(1); IMGUI_API void TextV(const char* fmt, va_list args); IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_PRINTFARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor(); IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args); IMGUI_API void TextDisabled(const char* fmt, ...) IM_PRINTFARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor(); IMGUI_API void TextDisabledV(const char* fmt, va_list args); IMGUI_API void TextWrapped(const char* fmt, ...) IM_PRINTFARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize(). IMGUI_API void TextWrappedV(const char* fmt, va_list args); IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // doesn't require null terminated string if 'text_end' is specified. no copy done to any bounded stack buffer, recommended for long chunks of text IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_PRINTFARGS(2); // display text+label aligned the same way as value+label widgets IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args); IMGUI_API void Bullet(); // draw a small circle and keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses IMGUI_API void BulletText(const char* fmt, ...) IM_PRINTFARGS(1); // shortcut for Bullet()+Text() IMGUI_API void BulletTextV(const char* fmt, va_list args); IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0)); // button IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size); IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0)); IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,0), const ImVec4& tint_col = ImVec4(1,1,1,1)); // <0 frame_padding uses default frame padding settings. 0 for no padding IMGUI_API bool Checkbox(const char* label, bool* v); IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); IMGUI_API bool RadioButton(const char* label, bool active); IMGUI_API bool RadioButton(const char* label, int* v, int v_button); IMGUI_API bool Combo(const char* label, int* current_item, const char** items, int items_count, int height_in_items = -1); IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items = -1); // separate items with \0, end item-list with \0\0 IMGUI_API bool Combo(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); IMGUI_API bool ColorButton(const ImVec4& col, bool small_height = false, bool outline_border = true); IMGUI_API bool ColorEdit3(const char* label, float col[3]); // Hint: 'float col[3]' function argument is same as 'float* col'. You can pass address of first element out of a contiguous set, e.g. &myvector.x IMGUI_API bool ColorEdit4(const char* label, float col[4], bool show_alpha = true); // " IMGUI_API void ColorEditMode(ImGuiColorEditMode mode); // FIXME-OBSOLETE: This is inconsistent with most of the API and will be obsoleted/replaced. IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), int stride = sizeof(float)); IMGUI_API void PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), int stride = sizeof(float)); IMGUI_API void PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1,0), const char* overlay = NULL); // Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can go off-bounds) // For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, remember than a 'float v[3]' function argument is the same as 'float* v'. You can pass address of your first element out of a contiguous set, e.g. &myvector.x IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); // If v_min >= v_max we have no bound IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", const char* display_format_max = NULL, float power = 1.0f); IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); // If v_min >= v_max we have no bound IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f", const char* display_format_max = NULL); // Widgets: Input with Keyboard IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiTextEditCallback callback = NULL, void* user_data = NULL); IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0,0), ImGuiInputTextFlags flags = 0, ImGuiTextEditCallback callback = NULL, void* user_data = NULL); IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputFloat2(const char* label, float v[2], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputFloat3(const char* label, float v[3], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputFloat4(const char* label, float v[4], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags = 0); // Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can go off-bounds) IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); // adjust display_format to decorate the value with a prefix or a suffix. Use power!=1.0 for logarithmic sliders IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f); IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format = "%.0f"); IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format = "%.0f"); IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format = "%.0f"); IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format = "%.0f"); IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format = "%.0f"); // Widgets: Trees IMGUI_API bool TreeNode(const char* label); // if returning 'true' the node is open and the tree id is pushed into the id stack. user is responsible for calling TreePop(). IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_PRINTFARGS(2); // read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet(). IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_PRINTFARGS(2); // " IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args); // " IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args); // " IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0); IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_PRINTFARGS(3); IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_PRINTFARGS(3); IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args); IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args); IMGUI_API void TreePush(const char* str_id = NULL); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call Push/Pop yourself for layout purpose IMGUI_API void TreePush(const void* ptr_id = NULL); // " IMGUI_API void TreePop(); // ~ Unindent()+PopId() IMGUI_API void TreeAdvanceToLabelPos(); // advance cursor x position by GetTreeNodeToLabelSpacing() IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceeding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode IMGUI_API void SetNextTreeNodeOpen(bool is_open, ImGuiSetCond cond = 0); // set next TreeNode/CollapsingHeader open state. IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). IMGUI_API bool CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags = 0); // when 'p_open' isn't NULL, display an additional small close button on upper right of the header // Widgets: Selectable / Lists IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); IMGUI_API bool ListBox(const char* label, int* current_item, const char** items, int items_count, int height_in_items = -1); IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0,0)); // use if you want to reimplement ListBox() will custom data or interactions. make sure to call ListBoxFooter() afterwards. IMGUI_API bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // " IMGUI_API void ListBoxFooter(); // terminate the scrolling region // Widgets: Value() Helpers. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace) IMGUI_API void Value(const char* prefix, bool b); IMGUI_API void Value(const char* prefix, int v); IMGUI_API void Value(const char* prefix, unsigned int v); IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL); IMGUI_API void ValueColor(const char* prefix, const ImVec4& v); IMGUI_API void ValueColor(const char* prefix, ImU32 v); // Tooltips IMGUI_API void SetTooltip(const char* fmt, ...) IM_PRINTFARGS(1); // set tooltip under mouse-cursor, typically use with ImGui::IsHovered(). last call wins IMGUI_API void SetTooltipV(const char* fmt, va_list args); IMGUI_API void BeginTooltip(); // use to create full-featured tooltip windows that aren't just text IMGUI_API void EndTooltip(); // Menus IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar. only call EndMainMenuBar() if this returns true! IMGUI_API void EndMainMenuBar(); IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set). only call EndMenuBar() if this returns true! IMGUI_API void EndMenuBar(); IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true! IMGUI_API void EndMenu(); IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. shortcuts are displayed for convenience but not processed by ImGui at the moment IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL // Popups IMGUI_API void OpenPopup(const char* str_id); // mark popup as open. popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). IMGUI_API bool BeginPopup(const char* str_id); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returned true! IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags extra_flags = 0); // modal dialog (can't close them by clicking outside) IMGUI_API bool BeginPopupContextItem(const char* str_id, int mouse_button = 1); // helper to open and begin popup when clicked on last item. read comments in .cpp! IMGUI_API bool BeginPopupContextWindow(bool also_over_items = true, const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked on current window. IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked in void (no window). IMGUI_API void EndPopup(); IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup. // Logging: all text output from interface is redirected to tty/file/clipboard. By default, tree nodes are automatically opened during logging. IMGUI_API void LogToTTY(int max_depth = -1); // start logging to tty IMGUI_API void LogToFile(int max_depth = -1, const char* filename = NULL); // start logging to file IMGUI_API void LogToClipboard(int max_depth = -1); // start logging to OS clipboard IMGUI_API void LogFinish(); // stop logging (close file, etc.) IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard IMGUI_API void LogText(const char* fmt, ...) IM_PRINTFARGS(1); // pass text data straight to log (without being displayed) // Clipping IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect); IMGUI_API void PopClipRect(); // Utilities IMGUI_API bool IsItemHovered(); // was the last item hovered by mouse? IMGUI_API bool IsItemHoveredRect(); // was the last item hovered by mouse? even if another item is active or window is blocked by popup while we are hovering this IMGUI_API bool IsItemActive(); // was the last item active? (e.g. button being held, text field being edited- items that don't interact will always return false) IMGUI_API bool IsItemClicked(int mouse_button = 0); // was the last item clicked? (e.g. button/node just clicked on) IMGUI_API bool IsItemVisible(); // was the last item visible? (aka not out of sight due to clipping/scrolling.) IMGUI_API bool IsAnyItemHovered(); IMGUI_API bool IsAnyItemActive(); IMGUI_API ImVec2 GetItemRectMin(); // get bounding rect of last item in screen space IMGUI_API ImVec2 GetItemRectMax(); // " IMGUI_API ImVec2 GetItemRectSize(); // " IMGUI_API void SetItemAllowOverlap(); // allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area. IMGUI_API bool IsWindowHovered(); // is current window hovered and hoverable (not blocked by a popup) (differentiate child windows from each others) IMGUI_API bool IsWindowFocused(); // is current window focused IMGUI_API bool IsRootWindowFocused(); // is current root window focused (root = top-most parent of a child, otherwise self) IMGUI_API bool IsRootWindowOrAnyChildFocused(); // is current root window or any of its child (including current window) focused IMGUI_API bool IsRootWindowOrAnyChildHovered(); // is current root window or any of its child (including current window) hovered and hoverable (not blocked by a popup) IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle of given size starting from cursor pos is visible (not clipped). to perform coarse clipping on user's side (as an optimization) IMGUI_API bool IsPosHoveringAnyWindow(const ImVec2& pos); // is given position hovering any active imgui window IMGUI_API float GetTime(); IMGUI_API int GetFrameCount(); IMGUI_API const char* GetStyleColName(ImGuiCol idx); IMGUI_API ImVec2 CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge = false, float outward = +0.0f); // utility to find the closest point the last item bounding rectangle edge. useful to visually link items IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f); IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // calculate coarse clipping for large list of evenly sized items. Prefer using the ImGuiListClipper higher-level helper if you can. IMGUI_API bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame IMGUI_API void EndChildFrame(); IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in); IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in); IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v); IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b); // Inputs IMGUI_API int GetKeyIndex(ImGuiKey key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key] IMGUI_API bool IsKeyDown(int key_index); // key_index into the keys_down[] array, imgui doesn't know the semantic of each entry, uses your own indices! IMGUI_API bool IsKeyPressed(int key_index, bool repeat = true); // uses user's key indices as stored in the keys_down[] array. if repeat=true. uses io.KeyRepeatDelay / KeyRepeatRate IMGUI_API bool IsKeyReleased(int key_index); // " IMGUI_API bool IsMouseDown(int button); // is mouse button held IMGUI_API bool IsMouseClicked(int button, bool repeat = false); // did mouse button clicked (went from !Down to Down) IMGUI_API bool IsMouseDoubleClicked(int button); // did mouse button double-clicked. a double-click returns false in IsMouseClicked(). uses io.MouseDoubleClickTime. IMGUI_API bool IsMouseReleased(int button); // did mouse button released (went from Down to !Down) IMGUI_API bool IsMouseHoveringWindow(); // is mouse hovering current window ("window" in API names always refer to current window). disregarding of any consideration of being blocked by a popup. (unlike IsWindowHovered() this will return true even if the window is blocked because of a popup) IMGUI_API bool IsMouseHoveringAnyWindow(); // is mouse hovering any visible window IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true); // is mouse hovering given bounding rect (in screen space). clipped by current clipping settings. disregarding of consideration of focus/window ordering/blocked by a popup. IMGUI_API bool IsMouseDragging(int button = 0, float lock_threshold = -1.0f); // is mouse dragging. if lock_threshold < -1.0f uses io.MouseDraggingThreshold IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve backup of mouse positioning at the time of opening popup we have BeginPopup() into IMGUI_API ImVec2 GetMouseDragDelta(int button = 0, float lock_threshold = -1.0f); // dragging amount since clicking. if lock_threshold < -1.0f uses io.MouseDraggingThreshold IMGUI_API void ResetMouseDragDelta(int button = 0); // IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you IMGUI_API void SetMouseCursor(ImGuiMouseCursor type); // set desired cursor type IMGUI_API void CaptureKeyboardFromApp(bool capture = true); // manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application handle). e.g. force capture keyboard when your widget is being hovered. IMGUI_API void CaptureMouseFromApp(bool capture = true); // manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application handle). // Helpers functions to access functions pointers in ImGui::GetIO() IMGUI_API void* MemAlloc(size_t sz); IMGUI_API void MemFree(void* ptr); IMGUI_API const char* GetClipboardText(); IMGUI_API void SetClipboardText(const char* text); // Internal context access - if you want to use multiple context, share context between modules (e.g. DLL). There is a default context created and active by default. // All contexts share a same ImFontAtlas by default. If you want different font atlas, you can new() them and overwrite the GetIO().Fonts variable of an ImGui context. IMGUI_API const char* GetVersion(); IMGUI_API ImGuiContext* CreateContext(void* (*malloc_fn)(size_t) = NULL, void (*free_fn)(void*) = NULL); IMGUI_API void DestroyContext(ImGuiContext* ctx); IMGUI_API ImGuiContext* GetCurrentContext(); IMGUI_API void SetCurrentContext(ImGuiContext* ctx); // Obsolete (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS static inline bool CollapsingHeader(const char* label, const char* str_id, bool framed = true, bool default_open = false) { (void)str_id; (void)framed; ImGuiTreeNodeFlags default_open_flags = 1<<5; return CollapsingHeader(label, (default_open ? default_open_flags : 0)); } // OBSOLETE 1.49+ static inline ImFont* GetWindowFont() { return GetFont(); } // OBSOLETE 1.48+ static inline float GetWindowFontSize() { return GetFontSize(); } // OBSOLETE 1.48+ static inline void OpenNextNode(bool open) { ImGui::SetNextTreeNodeOpen(open, 0); } // OBSOLETE 1.34+ static inline bool GetWindowIsFocused() { return ImGui::IsWindowFocused(); } // OBSOLETE 1.36+ static inline bool GetWindowCollapsed() { return ImGui::IsWindowCollapsed(); } // OBSOLETE 1.39+ static inline ImVec2 GetItemBoxMin() { return GetItemRectMin(); } // OBSOLETE 1.36+ static inline ImVec2 GetItemBoxMax() { return GetItemRectMax(); } // OBSOLETE 1.36+ static inline bool IsClipped(const ImVec2& size) { return !IsRectVisible(size); } // OBSOLETE 1.38+ static inline bool IsRectClipped(const ImVec2& size) { return !IsRectVisible(size); } // OBSOLETE 1.39+ static inline bool IsMouseHoveringBox(const ImVec2& rect_min, const ImVec2& rect_max) { return IsMouseHoveringRect(rect_min, rect_max); } // OBSOLETE 1.36+ static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETE 1.42+ #endif } // namespace ImGui // Flags for ImGui::Begin() enum ImGuiWindowFlags_ { // Default: 0 ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programatically) ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame ImGuiWindowFlags_ShowBorders = 1 << 7, // Show borders around windows and items ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file ImGuiWindowFlags_NoInputs = 1 << 9, // Disable catching mouse or keyboard inputs ImGuiWindowFlags_MenuBar = 1 << 10, // Has a menu-bar ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programatically giving it focus) ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y) ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x) ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16, // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient) // [Internal] ImGuiWindowFlags_ChildWindow = 1 << 20, // Don't use! For internal use by BeginChild() ImGuiWindowFlags_ChildWindowAutoFitX = 1 << 21, // Don't use! For internal use by BeginChild() ImGuiWindowFlags_ChildWindowAutoFitY = 1 << 22, // Don't use! For internal use by BeginChild() ImGuiWindowFlags_ComboBox = 1 << 23, // Don't use! For internal use by ComboBox() ImGuiWindowFlags_Tooltip = 1 << 24, // Don't use! For internal use by BeginTooltip() ImGuiWindowFlags_Popup = 1 << 25, // Don't use! For internal use by BeginPopup() ImGuiWindowFlags_Modal = 1 << 26, // Don't use! For internal use by BeginPopupModal() ImGuiWindowFlags_ChildMenu = 1 << 27 // Don't use! For internal use by BeginMenu() }; // Flags for ImGui::InputText() enum ImGuiInputTextFlags_ { // Default: 0 ImGuiInputTextFlags_CharsDecimal = 1 << 0, // Allow 0123456789.+-*/ ImGuiInputTextFlags_CharsHexadecimal = 1 << 1, // Allow 0123456789ABCDEFabcdef ImGuiInputTextFlags_CharsUppercase = 1 << 2, // Turn a..z into A..Z ImGuiInputTextFlags_CharsNoBlank = 1 << 3, // Filter out spaces, tabs ImGuiInputTextFlags_AutoSelectAll = 1 << 4, // Select entire text when first taking mouse focus ImGuiInputTextFlags_EnterReturnsTrue = 1 << 5, // Return 'true' when Enter is pressed (as opposed to when the value was modified) ImGuiInputTextFlags_CallbackCompletion = 1 << 6, // Call user function on pressing TAB (for completion handling) ImGuiInputTextFlags_CallbackHistory = 1 << 7, // Call user function on pressing Up/Down arrows (for history handling) ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Call user function every time. User code may query cursor position, modify text buffer. ImGuiInputTextFlags_CallbackCharFilter = 1 << 9, // Call user function to filter character. Modify data->EventChar to replace/filter input, or return 1 to discard character. ImGuiInputTextFlags_AllowTabInput = 1 << 10, // Pressing TAB input a '\t' character into the text field ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11, // In multi-line mode, allow exiting edition by pressing Enter. Ctrl+Enter to add new line (by default adds new lines with Enter). ImGuiInputTextFlags_NoHorizontalScroll = 1 << 12, // Disable following the cursor horizontally ImGuiInputTextFlags_AlwaysInsertMode = 1 << 13, // Insert mode ImGuiInputTextFlags_ReadOnly = 1 << 14, // Read-only mode ImGuiInputTextFlags_Password = 1 << 15, // Password mode, display all characters as '*' // [Internal] ImGuiInputTextFlags_Multiline = 1 << 20 // For internal use by InputTextMultiline() }; // Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*() enum ImGuiTreeNodeFlags_ { ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected ImGuiTreeNodeFlags_Framed = 1 << 1, // Full colored frame (e.g. for CollapsingHeader) ImGuiTreeNodeFlags_AllowOverlapMode = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Need double-click to open node ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Only open when clicking on the arrow part. If ImGuiTreeNodeFlags_OpenOnDoubleClick is also set, single-click arrow or double-click all box to open. ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes). ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow //ImGuITreeNodeFlags_SpanAllAvailWidth = 1 << 10, // FIXME: TODO: Extend hit box horizontally even if not framed //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 11, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoAutoOpenOnLog }; // Flags for ImGui::Selectable() enum ImGuiSelectableFlags_ { // Default: 0 ImGuiSelectableFlags_DontClosePopups = 1 << 0, // Clicking this don't close parent popup window ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Selectable frame can span all columns (text will still fit in current column) ImGuiSelectableFlags_AllowDoubleClick = 1 << 2 // Generate press events on double clicks too }; // User fill ImGuiIO.KeyMap[] array with indices into the ImGuiIO.KeysDown[512] array enum ImGuiKey_ { ImGuiKey_Tab, // for tabbing through fields ImGuiKey_LeftArrow, // for text edit ImGuiKey_RightArrow,// for text edit ImGuiKey_UpArrow, // for text edit ImGuiKey_DownArrow, // for text edit ImGuiKey_PageUp, ImGuiKey_PageDown, ImGuiKey_Home, // for text edit ImGuiKey_End, // for text edit ImGuiKey_Delete, // for text edit ImGuiKey_Backspace, // for text edit ImGuiKey_Enter, // for text edit ImGuiKey_Escape, // for text edit ImGuiKey_A, // for text edit CTRL+A: select all ImGuiKey_C, // for text edit CTRL+C: copy ImGuiKey_V, // for text edit CTRL+V: paste ImGuiKey_X, // for text edit CTRL+X: cut ImGuiKey_Y, // for text edit CTRL+Y: redo ImGuiKey_Z, // for text edit CTRL+Z: undo ImGuiKey_COUNT }; // Enumeration for PushStyleColor() / PopStyleColor() enum ImGuiCol_ { ImGuiCol_Text, ImGuiCol_TextDisabled, ImGuiCol_WindowBg, // Background of normal windows ImGuiCol_ChildWindowBg, // Background of child windows ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows ImGuiCol_Border, ImGuiCol_BorderShadow, ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive, ImGuiCol_TitleBg, ImGuiCol_TitleBgCollapsed, ImGuiCol_TitleBgActive, ImGuiCol_MenuBarBg, ImGuiCol_ScrollbarBg, ImGuiCol_ScrollbarGrab, ImGuiCol_ScrollbarGrabHovered, ImGuiCol_ScrollbarGrabActive, ImGuiCol_ComboBg, ImGuiCol_CheckMark, ImGuiCol_SliderGrab, ImGuiCol_SliderGrabActive, ImGuiCol_Button, ImGuiCol_ButtonHovered, ImGuiCol_ButtonActive, ImGuiCol_Header, ImGuiCol_HeaderHovered, ImGuiCol_HeaderActive, ImGuiCol_Column, ImGuiCol_ColumnHovered, ImGuiCol_ColumnActive, ImGuiCol_ResizeGrip, ImGuiCol_ResizeGripHovered, ImGuiCol_ResizeGripActive, ImGuiCol_CloseButton, ImGuiCol_CloseButtonHovered, ImGuiCol_CloseButtonActive, ImGuiCol_PlotLines, ImGuiCol_PlotLinesHovered, ImGuiCol_PlotHistogram, ImGuiCol_PlotHistogramHovered, ImGuiCol_TextSelectedBg, ImGuiCol_ModalWindowDarkening, // darken entire screen when a modal window is active ImGuiCol_COUNT }; // Enumeration for PushStyleVar() / PopStyleVar() // NB: the enum only refers to fields of ImGuiStyle() which makes sense to be pushed/poped in UI code. Feel free to add others. enum ImGuiStyleVar_ { ImGuiStyleVar_Alpha, // float ImGuiStyleVar_WindowPadding, // ImVec2 ImGuiStyleVar_WindowRounding, // float ImGuiStyleVar_WindowMinSize, // ImVec2 ImGuiStyleVar_ChildWindowRounding, // float ImGuiStyleVar_FramePadding, // ImVec2 ImGuiStyleVar_FrameRounding, // float ImGuiStyleVar_ItemSpacing, // ImVec2 ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ImGuiStyleVar_IndentSpacing, // float ImGuiStyleVar_GrabMinSize // float }; enum ImGuiAlign_ { ImGuiAlign_Left = 1 << 0, ImGuiAlign_Center = 1 << 1, ImGuiAlign_Right = 1 << 2, ImGuiAlign_Top = 1 << 3, ImGuiAlign_VCenter = 1 << 4, ImGuiAlign_Default = ImGuiAlign_Left | ImGuiAlign_Top }; // Enumeration for ColorEditMode() // FIXME-OBSOLETE: Will be replaced by future color/picker api enum ImGuiColorEditMode_ { ImGuiColorEditMode_UserSelect = -2, ImGuiColorEditMode_UserSelectShowButton = -1, ImGuiColorEditMode_RGB = 0, ImGuiColorEditMode_HSV = 1, ImGuiColorEditMode_HEX = 2 }; // Enumeration for GetMouseCursor() enum ImGuiMouseCursor_ { ImGuiMouseCursor_Arrow = 0, ImGuiMouseCursor_TextInput, // When hovering over InputText, etc. ImGuiMouseCursor_Move, // Unused ImGuiMouseCursor_ResizeNS, // Unused ImGuiMouseCursor_ResizeEW, // When hovering over a column ImGuiMouseCursor_ResizeNESW, // Unused ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window ImGuiMouseCursor_Count_ }; // Condition flags for ImGui::SetWindow***(), SetNextWindow***(), SetNextTreeNode***() functions // All those functions treat 0 as a shortcut to ImGuiSetCond_Always enum ImGuiSetCond_ { ImGuiSetCond_Always = 1 << 0, // Set the variable ImGuiSetCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call with succeed) ImGuiSetCond_FirstUseEver = 1 << 2, // Set the variable if the window has no saved data (if doesn't exist in the .ini file) ImGuiSetCond_Appearing = 1 << 3 // Set the variable if the window is appearing after being hidden/inactive (or the first time) }; struct ImGuiStyle { float Alpha; // Global alpha applies to everything in ImGui ImVec2 WindowPadding; // Padding within a window ImVec2 WindowMinSize; // Minimum window size float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows ImGuiAlign WindowTitleAlign; // Alignment for title bar text float ChildWindowRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets) float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets). ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). float ColumnsMinSpacing; // Minimum horizontal spacing between two columns float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar float ScrollbarRounding; // Radius of grab corners for scrollbar float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. ImVec2 DisplayWindowPadding; // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows. ImVec2 DisplaySafeAreaPadding; // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. bool AntiAliasedLines; // Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU. bool AntiAliasedShapes; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) float CurveTessellationTol; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. ImVec4 Colors[ImGuiCol_COUNT]; IMGUI_API ImGuiStyle(); }; // This is where your app communicate with ImGui. Access via ImGui::GetIO(). // Read 'Programmer guide' section in .cpp file for general usage. struct ImGuiIO { //------------------------------------------------------------------ // Settings (fill once) // Default value: //------------------------------------------------------------------ ImVec2 DisplaySize; // <unset> // Display size, in pixels. For clamping windows positions. float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. float IniSavingRate; // = 5.0f // Maximum time between saving positions/sizes to .ini file, in seconds. const char* IniFilename; // = "imgui.ini" // Path to .ini file. NULL to disable .ini saving. const char* LogFilename; // = "imgui_log.txt" // Path to .log file (default parameter to ImGui::LogToFile when no file is specified). float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds. float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels. float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging int KeyMap[ImGuiKey_COUNT]; // <unset> // Map of indices into the KeysDown[512] entries array float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.). float KeyRepeatRate; // = 0.020f // When holding a key/button, rate at which it repeats, in seconds. void* UserData; // = NULL // Store your own data for retrieval by callbacks. ImFontAtlas* Fonts; // <auto> // Load and assemble one or more fonts into a single tightly packed texture. Output to Fonts array. float FontGlobalScale; // = 1.0f // Global scale all fonts bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. ImVec2 DisplayFramebufferScale; // = (1.0f,1.0f) // For retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui. ImVec2 DisplayVisibleMin; // <unset> (0.0f,0.0f) // If you use DisplaySize as a virtual space larger than your screen, set DisplayVisibleMin/Max to the visible area. ImVec2 DisplayVisibleMax; // <unset> (0.0f,0.0f) // If the values are the same, we defaults to Min=(0.0f) and Max=DisplaySize // Advanced/subtle behaviors bool OSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl //------------------------------------------------------------------ // User Functions //------------------------------------------------------------------ // Rendering function, will be called in Render(). // Alternatively you can keep this to NULL and call GetDrawData() after Render() to get the same pointer. // See example applications if you are unsure of how to implement this. void (*RenderDrawListsFn)(ImDrawData* data); // Optional: access OS clipboard // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) const char* (*GetClipboardTextFn)(); void (*SetClipboardTextFn)(const char* text); // Optional: override memory allocations. MemFreeFn() may be called with a NULL pointer. // (default to posix malloc/free) void* (*MemAllocFn)(size_t sz); void (*MemFreeFn)(void* ptr); // Optional: notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME in Windows) // (default to use native imm32 api on Windows) void (*ImeSetInputScreenPosFn)(int x, int y); void* ImeWindowHandle; // (Windows) Set this to your HWND to get automatic IME cursor positioning. //------------------------------------------------------------------ // Input - Fill before calling NewFrame() //------------------------------------------------------------------ ImVec2 MousePos; // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) bool MouseDown[5]; // Mouse buttons: left, right, middle + extras. ImGui itself mostly only uses left button (BeginPopupContext** are using right button). Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. float MouseWheel; // Mouse wheel: 1 unit scrolls about 5 lines text. bool MouseDrawCursor; // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). bool KeyCtrl; // Keyboard modifier pressed: Control bool KeyShift; // Keyboard modifier pressed: Shift bool KeyAlt; // Keyboard modifier pressed: Alt bool KeySuper; // Keyboard modifier pressed: Cmd/Super/Windows bool KeysDown[512]; // Keyboard keys that are pressed (in whatever storage order you naturally have access to keyboard data) ImWchar InputCharacters[16+1]; // List of characters input (translated by user from keypress+keyboard state). Fill using AddInputCharacter() helper. // Functions IMGUI_API void AddInputCharacter(ImWchar c); // Helper to add a new character into InputCharacters[] IMGUI_API void AddInputCharactersUTF8(const char* utf8_chars); // Helper to add new characters into InputCharacters[] from an UTF-8 string inline void ClearInputCharacters() { InputCharacters[0] = 0; } // Helper to clear the text input buffer //------------------------------------------------------------------ // Output - Retrieve after calling NewFrame(), you can use them to discard inputs or hide them from the rest of your application //------------------------------------------------------------------ bool WantCaptureMouse; // Mouse is hovering a window or widget is active (= ImGui will use your mouse input) bool WantCaptureKeyboard; // Widget is active (= ImGui will use your keyboard input) bool WantTextInput; // Some text input widget is active, which will read input characters from the InputCharacters array. float Framerate; // Framerate estimation, in frame per second. Rolling average estimation based on IO.DeltaTime over 120 frames int MetricsAllocs; // Number of active memory allocations int MetricsRenderVertices; // Vertices output during last call to Render() int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3 int MetricsActiveWindows; // Number of visible windows (exclude child windows) //------------------------------------------------------------------ // [Internal] ImGui will maintain those fields for you //------------------------------------------------------------------ ImVec2 MousePosPrev; // Previous mouse position ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are negative to allow mouse enabling/disabling. bool MouseClicked[5]; // Mouse button went from !Down to Down ImVec2 MouseClickedPos[5]; // Position at time of clicking float MouseClickedTime[5]; // Time of last click (used to figure out double-click) bool MouseDoubleClicked[5]; // Has mouse button been double-clicked? bool MouseReleased[5]; // Mouse button went from Down to !Down bool MouseDownOwned[5]; // Track if button was clicked inside a window. We don't request mouse capture from the application if click started outside ImGui bounds. float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked) float MouseDownDurationPrev[5]; // Previous time the mouse button has been down float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the click point float KeysDownDuration[512]; // Duration the keyboard key has been down (0.0f == just pressed) float KeysDownDurationPrev[512]; // Previous duration the key has been down IMGUI_API ImGuiIO(); }; //----------------------------------------------------------------------------- // Helpers //----------------------------------------------------------------------------- // Lightweight std::vector<> like class to avoid dragging dependencies (also: windows implementation of STL with debug enabled is absurdly slow, so let's bypass it so our code runs fast in debug). // Our implementation does NOT call c++ constructors because we don't use them in ImGui. Don't use this class as a straight std::vector replacement in your code! template<typename T> class ImVector { public: int Size; int Capacity; T* Data; typedef T value_type; typedef value_type* iterator; typedef const value_type* const_iterator; ImVector() { Size = Capacity = 0; Data = NULL; } ~ImVector() { if (Data) ImGui::MemFree(Data); } inline bool empty() const { return Size == 0; } inline int size() const { return Size; } inline int capacity() const { return Capacity; } inline value_type& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; } inline const value_type& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; } inline void clear() { if (Data) { Size = Capacity = 0; ImGui::MemFree(Data); Data = NULL; } } inline iterator begin() { return Data; } inline const_iterator begin() const { return Data; } inline iterator end() { return Data + Size; } inline const_iterator end() const { return Data + Size; } inline value_type& front() { IM_ASSERT(Size > 0); return Data[0]; } inline const value_type& front() const { IM_ASSERT(Size > 0); return Data[0]; } inline value_type& back() { IM_ASSERT(Size > 0); return Data[Size-1]; } inline const value_type& back() const { IM_ASSERT(Size > 0); return Data[Size-1]; } inline void swap(ImVector<T>& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; value_type* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } inline int _grow_capacity(int new_size) { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > new_size ? new_capacity : new_size; } inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; } inline void reserve(int new_capacity) { if (new_capacity <= Capacity) return; T* new_data = (value_type*)ImGui::MemAlloc((size_t)new_capacity * sizeof(value_type)); if (Data) memcpy(new_data, Data, (size_t)Size * sizeof(value_type)); ImGui::MemFree(Data); Data = new_data; Capacity = new_capacity; } inline void push_back(const value_type& v) { if (Size == Capacity) reserve(_grow_capacity(Size+1)); Data[Size++] = v; } inline void pop_back() { IM_ASSERT(Size > 0); Size--; } inline iterator erase(const_iterator it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(value_type)); Size--; return Data + off; } inline iterator insert(const_iterator it, const value_type& v) { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(Capacity ? Capacity * 2 : 4); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(value_type)); Data[off] = v; Size++; return Data + off; } }; // Helper: execute a block of code at maximum once a frame // Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame. // Usage: // IMGUI_ONCE_UPON_A_FRAME // { // // code block will be executed one per frame // } // Attention! the macro expands into 2 statement so make sure you don't use it within e.g. an if() statement without curly braces. #define IMGUI_ONCE_UPON_A_FRAME static ImGuiOnceUponAFrame imgui_oaf##__LINE__; if (imgui_oaf##__LINE__) struct ImGuiOnceUponAFrame { ImGuiOnceUponAFrame() { RefFrame = -1; } mutable int RefFrame; operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } }; // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" struct ImGuiTextFilter { struct TextRange { const char* b; const char* e; TextRange() { b = e = NULL; } TextRange(const char* _b, const char* _e) { b = _b; e = _e; } const char* begin() const { return b; } const char* end() const { return e; } bool empty() const { return b == e; } char front() const { return *b; } static bool is_blank(char c) { return c == ' ' || c == '\t'; } void trim_blanks() { while (b < e && is_blank(*b)) b++; while (e > b && is_blank(*(e-1))) e--; } IMGUI_API void split(char separator, ImVector<TextRange>& out); }; char InputBuf[256]; ImVector<TextRange> Filters; int CountGrep; ImGuiTextFilter(const char* default_filter = ""); ~ImGuiTextFilter() {} void Clear() { InputBuf[0] = 0; Build(); } bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build bool PassFilter(const char* text, const char* text_end = NULL) const; bool IsActive() const { return !Filters.empty(); } IMGUI_API void Build(); }; // Helper: Text buffer for logging/accumulating text struct ImGuiTextBuffer { ImVector<char> Buf; ImGuiTextBuffer() { Buf.push_back(0); } inline char operator[](int i) { return Buf.Data[i]; } const char* begin() const { return &Buf.front(); } const char* end() const { return &Buf.back(); } // Buf is zero-terminated, so end() will point on the zero-terminator int size() const { return Buf.Size - 1; } bool empty() { return Buf.Size <= 1; } void clear() { Buf.clear(); Buf.push_back(0); } const char* c_str() const { return Buf.Data; } IMGUI_API void append(const char* fmt, ...) IM_PRINTFARGS(2); IMGUI_API void appendv(const char* fmt, va_list args); }; // Helper: Simple Key->value storage // - Store collapse state for a tree (Int 0/1) // - Store color edit options (Int using values in ImGuiColorEditMode enum). // - Custom user storage for temporary values. // Typically you don't have to worry about this since a storage is held within each Window. // Declare your own storage if: // - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state). // - You want to store custom debug data easily without adding or editing structures in your code. // Types are NOT stored, so it is up to you to make sure your Key don't collide with different types. struct ImGuiStorage { struct Pair { ImGuiID key; union { int val_i; float val_f; void* val_p; }; Pair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; } Pair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; } Pair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; } }; ImVector<Pair> Data; // - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N) // - Set***() functions find pair, insertion on demand if missing. // - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair. IMGUI_API void Clear(); IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const; IMGUI_API void SetInt(ImGuiID key, int val); IMGUI_API bool GetBool(ImGuiID key, bool default_val = false) const; IMGUI_API void SetBool(ImGuiID key, bool val); IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const; IMGUI_API void SetFloat(ImGuiID key, float val); IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL IMGUI_API void SetVoidPtr(ImGuiID key, void* val); // - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set. // - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. // - A typical use case where this is convenient: // float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar; // - You can also use this to quickly create temporary editable values during a session of using Edit&Continue, without restarting your application. IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0); IMGUI_API bool* GetBoolRef(ImGuiID key, bool default_val = false); IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0.0f); IMGUI_API void** GetVoidPtrRef(ImGuiID key, void* default_val = NULL); // Use on your own storage if you know only integer are being stored (open/close all tree nodes) IMGUI_API void SetAllInt(int val); }; // Shared state of InputText(), passed to callback when a ImGuiInputTextFlags_Callback* flag is used and the corresponding callback is triggered. struct ImGuiTextEditCallbackData { ImGuiInputTextFlags EventFlag; // One of ImGuiInputTextFlags_Callback* // Read-only ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only void* UserData; // What user passed to InputText() // Read-only bool ReadOnly; // Read-only mode // Read-only // CharFilter event: ImWchar EventChar; // Character input // Read-write (replace character or set to zero) // Completion,History,Always events: // If you modify the buffer contents make sure you update 'BufTextLen' and set 'BufDirty' to true. ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only char* Buf; // Current text buffer // Read-write (pointed data only, can't replace the actual pointer) int BufTextLen; // Current text length in bytes // Read-write int BufSize; // Maximum text length in bytes // Read-only bool BufDirty; // Set if you modify Buf/BufTextLen!! // Write int CursorPos; // // Read-write int SelectionStart; // // Read-write (== to SelectionEnd when no selection) int SelectionEnd; // // Read-write // NB: Helper functions for text manipulation. Calling those function loses selection. void DeleteChars(int pos, int bytes_count); void InsertChars(int pos, const char* text, const char* text_end = NULL); bool HasSelection() const { return SelectionStart != SelectionEnd; } }; // Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin(). // NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough. struct ImGuiSizeConstraintCallbackData { void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints() ImVec2 Pos; // Read-only. Window position, for reference. ImVec2 CurrentSize; // Read-only. Current window size. ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing. }; // ImColor() helper to implicity converts colors to either ImU32 (packed 4x1 byte) or ImVec4 (4x1 float) // Prefer using IM_COL32() macros if you want a guaranteed compile-time ImU32 for usage with ImDrawList API. // Avoid storing ImColor! Store either u32 of ImVec4. This is not a full-featured color class. // None of the ImGui API are using ImColor directly but you can use it as a convenience to pass colors in either ImU32 or ImVec4 formats. struct ImColor { ImVec4 Value; ImColor() { Value.x = Value.y = Value.z = Value.w = 0.0f; } ImColor(int r, int g, int b, int a = 255) { float sc = 1.0f/255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; } ImColor(ImU32 rgba) { float sc = 1.0f/255.0f; Value.x = (float)(rgba&0xFF) * sc; Value.y = (float)((rgba>>8)&0xFF) * sc; Value.z = (float)((rgba>>16)&0xFF) * sc; Value.w = (float)(rgba >> 24) * sc; } ImColor(float r, float g, float b, float a = 1.0f) { Value.x = r; Value.y = g; Value.z = b; Value.w = a; } ImColor(const ImVec4& col) { Value = col; } inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } inline operator ImVec4() const { return Value; } inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; } static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r,g,b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r,g,b,a); } }; // Helper: Manually clip large list of items. // If you are submitting lots of evenly spaced items and you have a random access to the list, you can perform coarse clipping based on visibility to save yourself from processing those items at all. // The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped. // ImGui already clip items based on their bounds but it needs to measure text size to do so. Coarse clipping before submission makes this cost and your own data fetching/submission cost null. // Usage: // ImGuiListClipper clipper(1000); // we have 1000 elements, evenly spaced. // while (clipper.Step()) // for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) // ImGui::Text("line number %d", i); // - Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height (step skipped if we passed a known height as second arg to constructor). // - Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. // - (Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user call Step(). Does nothing and switch to Step 3.) // - Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. struct ImGuiListClipper { float StartPosY; float ItemsHeight; int ItemsCount, StepNo, DisplayStart, DisplayEnd; // items_count: Use -1 to ignore (you can call Begin later). Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step). // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetItemsLineHeightWithSpacing(). // If you don't specify an items_height, you NEED to call Step(). If you specify items_height you may call the old Begin()/End() api directly, but prefer calling Step(). ImGuiListClipper(int items_count = -1, float items_height = -1.0f) { Begin(items_count, items_height); } // NB: Begin() initialize every fields (as we allow user to call Begin/End multiple times on a same instance if they want). ~ImGuiListClipper() { IM_ASSERT(ItemsCount == -1); } // Assert if user forgot to call End() or Step() until false. IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items. IMGUI_API void Begin(int items_count, float items_height = -1.0f); // Automatically called by constructor if you passed 'items_count' or by Step() in Step 1. IMGUI_API void End(); // Automatically called on the last call of Step() that returns false. }; //----------------------------------------------------------------------------- // Draw List // Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. //----------------------------------------------------------------------------- // Helpers macros to generate 32-bits encoded colors #define IM_COL32(R,G,B,A) (((ImU32)(A)<<24) | ((ImU32)(B)<<16) | ((ImU32)(G)<<8) | ((ImU32)(R))) #define IM_COL32_WHITE (0xFFFFFFFF) #define IM_COL32_BLACK (0xFF000000) #define IM_COL32_BLACK_TRANS (0x00000000) // Transparent black // Draw callbacks for advanced uses. // NB- You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering (you can poke into the draw list for that) // Draw callback may be useful for example, A) Change your GPU render state, B) render a complex 3D scene inside a UI element (without an intermediate texture/render target), etc. // The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) cmd.UserCallback(parent_list, cmd); else RenderTriangles()' typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); // Typically, 1 command = 1 gpu draw call (unless command is a callback) struct ImDrawCmd { unsigned int ElemCount; // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. ImVec4 ClipRect; // Clipping rectangle (x1, y1, x2, y2) ImTextureID TextureId; // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. ImDrawCallback UserCallback; // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. void* UserCallbackData; // The draw callback code can access this. ImDrawCmd() { ElemCount = 0; ClipRect.x = ClipRect.y = -8192.0f; ClipRect.z = ClipRect.w = +8192.0f; TextureId = NULL; UserCallback = NULL; UserCallbackData = NULL; } }; // Vertex index (override with '#define ImDrawIdx unsigned int' inside in imconfig.h) #ifndef ImDrawIdx typedef unsigned short ImDrawIdx; #endif // Vertex layout #ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; ImVec2 uv; ImU32 col; }; #else // You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h // The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine. // The type has to be described within the macro (you can either declare the struct or use a typedef) IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; #endif // Draw channels are used by the Columns API to "split" the render list into different channels while building, so items of each column can be batched together. // You can also use them to simulate drawing layers and submit primitives in a different order than how they will be rendered. struct ImDrawChannel { ImVector<ImDrawCmd> CmdBuffer; ImVector<ImDrawIdx> IdxBuffer; }; // Draw command list // This is the low-level list of polygons that ImGui functions are filling. At the end of the frame, all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering. // At the moment, each ImGui window contains its own ImDrawList but they could potentially be merged in the future. // If you want to add custom rendering within a window, you can use ImGui::GetWindowDrawList() to access the current draw list and add your own primitives. // You can interleave normal ImGui:: calls and adding primitives to the current draw list. // All positions are in screen coordinates (0,0=top-left, 1 pixel per unit). Primitives are always added to the list and not culled (culling is done at render time and at a higher-level by ImGui:: functions). struct ImDrawList { // This is what you have to render ImVector<ImDrawCmd> CmdBuffer; // Commands. Typically 1 command = 1 gpu draw call. ImVector<ImDrawIdx> IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those ImVector<ImDrawVert> VtxBuffer; // Vertex buffer. // [Internal, used while building lists] const char* _OwnerName; // Pointer to owner window's name (if any) for debugging unsigned int _VtxCurrentIdx; // [Internal] == VtxBuffer.Size ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) ImVector<ImVec4> _ClipRectStack; // [Internal] ImVector<ImTextureID> _TextureIdStack; // [Internal] ImVector<ImVec2> _Path; // [Internal] current path building int _ChannelsCurrent; // [Internal] current channel number (0) int _ChannelsCount; // [Internal] number of active channels (1+) ImVector<ImDrawChannel> _Channels; // [Internal] draw channels for columns API (not resized down so _ChannelsCount may be smaller than _Channels.Size) ImDrawList() { _OwnerName = NULL; Clear(); } ~ImDrawList() { ClearFreeMemory(); } IMGUI_API void PushClipRect(ImVec2 clip_rect_min, ImVec2 clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) IMGUI_API void PushClipRectFullScreen(); IMGUI_API void PopClipRect(); IMGUI_API void PushTextureID(const ImTextureID& texture_id); IMGUI_API void PopTextureID(); // Primitives IMGUI_API void AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness = 1.0f); IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners = 0x0F, float thickness = 1.0f); // a: upper-left, b: lower-right IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners = 0x0F); // a: upper-left, b: lower-right IMGUI_API void AddRectFilledMultiColor(const ImVec2& a, const ImVec2& b, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); IMGUI_API void AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness = 1.0f); IMGUI_API void AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col); IMGUI_API void AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness = 1.0f); IMGUI_API void AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col); IMGUI_API void AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12, float thickness = 1.0f); IMGUI_API void AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12); IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL); IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), ImU32 col = 0xFFFFFFFF); IMGUI_API void AddPolyline(const ImVec2* points, const int num_points, ImU32 col, bool closed, float thickness, bool anti_aliased); IMGUI_API void AddConvexPolyFilled(const ImVec2* points, const int num_points, ImU32 col, bool anti_aliased); IMGUI_API void AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments = 0); // Stateful path API, add points then finish with PathFill() or PathStroke() inline void PathClear() { _Path.resize(0); } inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); } inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path[_Path.Size-1], &pos, 8) != 0) _Path.push_back(pos); } inline void PathFill(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col, true); PathClear(); } inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness, true); PathClear(); } IMGUI_API void PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments = 10); IMGUI_API void PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle IMGUI_API void PathBezierCurveTo(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, int num_segments = 0); IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, int rounding_corners = 0x0F); // Channels // - Use to simulate layers. By switching channels to can render out-of-order (e.g. submit foreground primitives before background primitives) // - Use to minimize draw calls (e.g. if going back-and-forth between multiple non-overlapping clipping rectangles, prefer to append into separate channels then merge at the end) IMGUI_API void ChannelsSplit(int channels_count); IMGUI_API void ChannelsMerge(); IMGUI_API void ChannelsSetCurrent(int channel_index); // Advanced IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles. IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible // Internal helpers // NB: all primitives needs to be reserved via PrimReserve() beforehand! IMGUI_API void Clear(); IMGUI_API void ClearFreeMemory(); IMGUI_API void PrimReserve(int idx_count, int vtx_count); IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles) IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col); IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col); inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col){ _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; } inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; } inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } IMGUI_API void UpdateClipRect(); IMGUI_API void UpdateTextureID(); }; // All draw data to render an ImGui frame struct ImDrawData { bool Valid; // Only valid after Render() is called and before the next NewFrame() is called. ImDrawList** CmdLists; int CmdListsCount; int TotalVtxCount; // For convenience, sum of all cmd_lists vtx_buffer.Size int TotalIdxCount; // For convenience, sum of all cmd_lists idx_buffer.Size // Functions ImDrawData() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; } IMGUI_API void DeIndexAllBuffers(); // For backward compatibility: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! IMGUI_API void ScaleClipRects(const ImVec2& sc); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. }; struct ImFontConfig { void* FontData; // // TTF data int FontDataSize; // // TTF data size bool FontDataOwnedByAtlas; // true // TTF data ownership taken by the container ImFontAtlas (will delete memory itself). Set to true int FontNo; // 0 // Index of font within TTF file float SizePixels; // // Size in pixels for rasterizer int OversampleH, OversampleV; // 3, 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis. bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs const ImWchar* GlyphRanges; // // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). bool MergeGlyphCenterV; // false // When merging (multiple ImFontInput for one ImFont), vertically center new glyphs instead of aligning their baseline // [Internal] char Name[32]; // Name (strictly for debugging) ImFont* DstFont; IMGUI_API ImFontConfig(); }; // Load and rasterize multiple TTF fonts into a same texture. // Sharing a texture for multiple fonts allows us to reduce the number of draw calls during rendering. // We also add custom graphic data into the texture that serves for ImGui. // 1. (Optional) Call AddFont*** functions. If you don't call any, the default font will be loaded for you. // 2. Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data. // 3. Upload the pixels data into a texture within your graphics system. // 4. Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture. This value will be passed back to you during rendering to identify the texture. // 5. Call ClearTexData() to free textures memory on the heap. // NB: If you use a 'glyph_ranges' array you need to make sure that your array persist up until the ImFont is cleared. We only copy the pointer, not the data. struct ImFontAtlas { IMGUI_API ImFontAtlas(); IMGUI_API ~ImFontAtlas(); IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg); IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL); IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); IMGUI_API ImFont* AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Transfer ownership of 'ttf_data' to ImFontAtlas, will be deleted after Build() IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_ttf_data' still owned by caller. Compress with binary_to_compressed_c.cpp IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_ttf_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 paramaeter IMGUI_API void ClearTexData(); // Clear the CPU-side texture data. Saves RAM once the texture has been copied to graphics memory. IMGUI_API void ClearInputData(); // Clear the input TTF data (inc sizes, glyph ranges) IMGUI_API void ClearFonts(); // Clear the ImGui-side font data (glyphs storage, UV coordinates) IMGUI_API void Clear(); // Clear all // Retrieve texture data // User is in charge of copying the pixels into graphics memory, then call SetTextureUserID() // After loading the texture into your graphic system, store your texture handle in 'TexID' (ignore if you aren't using multiple fonts nor images) // RGBA32 format is provided for convenience and high compatibility, but note that all RGB pixels are white, so 75% of the memory is wasted. // Pitch = Width * BytesPerPixels IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel void SetTexID(void* id) { TexID = id; } // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list) // NB: Make sure that your string are UTF-8 and NOT in your local code page. See FAQ for details. IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs IMGUI_API const ImWchar* GetGlyphRangesChinese(); // Japanese + full set of about 21000 CJK Unified Ideographs IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters // Members // (Access texture data via GetTexData*() calls which will setup a default font for you.) void* TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It ia passed back to you during rendering. unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 int TexWidth; // Texture width calculated during Build(). int TexHeight; // Texture height calculated during Build(). int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel ImVector<ImFont*> Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. // Private ImVector<ImFontConfig> ConfigData; // Internal data IMGUI_API bool Build(); // Build pixels data. This is automatically for you by the GetTexData*** functions. IMGUI_API void RenderCustomTexData(int pass, void* rects); }; // Font runtime data and rendering // ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32(). struct ImFont { struct Glyph { ImWchar Codepoint; float XAdvance; float X0, Y0, X1, Y1; float U0, V0, U1, V1; // Texture coordinates }; // Members: Hot ~62/78 bytes float FontSize; // <user set> // Height of characters, set during loading (don't change after loading) float Scale; // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetFontScale() ImVec2 DisplayOffset; // = (0.f,1.f) // Offset font rendering by xx pixels ImVector<Glyph> Glyphs; // // All glyphs. ImVector<float> IndexXAdvance; // // Sparse. Glyphs->XAdvance in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI). ImVector<unsigned short> IndexLookup; // // Sparse. Index glyphs by Unicode code-point. const Glyph* FallbackGlyph; // == FindGlyph(FontFallbackChar) float FallbackXAdvance; // == FallbackGlyph->XAdvance ImWchar FallbackChar; // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar() // Members: Cold ~18/26 bytes short ConfigDataCount; // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. ImFontConfig* ConfigData; // // Pointer within ContainerAtlas->ConfigData ImFontAtlas* ContainerAtlas; // // What we has been loaded into float Ascent, Descent; // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] // Methods IMGUI_API ImFont(); IMGUI_API ~ImFont(); IMGUI_API void Clear(); IMGUI_API void BuildLookupTable(); IMGUI_API const Glyph* FindGlyph(ImWchar c) const; IMGUI_API void SetFallbackChar(ImWchar c); float GetCharAdvance(ImWchar c) const { return ((int)c < IndexXAdvance.Size) ? IndexXAdvance[(int)c] : FallbackXAdvance; } bool IsLoaded() const { return ContainerAtlas != NULL; } // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable. IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8 IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const; IMGUI_API void RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, unsigned short c) const; IMGUI_API void RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const; // Private IMGUI_API void GrowIndex(int new_size); IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. }; #if defined(__clang__) #pragma clang diagnostic pop #endif //---- Include imgui_user.h at the end of imgui.h //---- So you can include code that extends ImGui using any of the types declared above. //---- (also convenient for user to only explicitly include vanilla imgui.h) #ifdef IMGUI_INCLUDE_IMGUI_USER_H #include "imgui_user.h" #endif
RogerOlasz/ROF_Engine
ROF_Engine/ImGui/imgui.h
C
mit
123,446
'use strict'; module.exports = { authCheck: require('./authcheck'), injectScripts: require('./injectscripts'), debounceName: require('./debounce-name') };
nodecg/nodecg
lib/util/index.js
JavaScript
mit
159
/* * This is a part of the BugTrap package. * Copyright (c) 2005-2009 IntelleSoft. * All rights reserved. * * Description: Text format analyzer. * Author: Maksim Pyatkovskiy. * * This source code is only intended as a supplement to the * BugTrap package reference and related electronic documentation * provided with the product. See these sources for detailed * information regarding the BugTrap package. */ #include "StdAfx.h" #include "TextFormat.h" #include "BugTrapUtils.h" #ifdef _DEBUG #define new DEBUG_NEW #endif /** * @brief Detect file format and encoding. * @param pszFileName - file name. * @param hFile - file handle. * @param bTextFile - true if file contains text and false for binary files. * @param eEncoding - text encoding. * @return sizeof of encoding signature. */ DWORD DetectFileFormat(PCTSTR pszFileName, HANDLE hFile, BOOL& bTextFile, TEXT_ENCODING& eEncoding) { _ASSERTE(hFile != INVALID_HANDLE_VALUE); BYTE arrBuffer[100]; DWORD dwNumRead = 0; if (! ReadFile(hFile, arrBuffer, sizeof(arrBuffer), &dwNumRead, NULL)) { bTextFile = FALSE; eEncoding = TXTENC_ANSI; SetFilePointer(hFile, 0, NULL, FILE_BEGIN); return 0; } static const TCHAR szXmlFileExt[] = _T(".xml"); const size_t nXmlFileExtLength = countof(szXmlFileExt) - 1; size_t nFileNameLength = _tcslen(pszFileName); BOOL bIsXmlFile = nFileNameLength >= nXmlFileExtLength && _tcsicmp(pszFileName + nFileNameLength - nXmlFileExtLength, szXmlFileExt) == 0; bTextFile = TRUE; DWORD dwStartPos, dwCharSize, dwOffsetFromStart; if (dwNumRead >= sizeof(g_arrUTF16LEPreamble) && memcmp(arrBuffer, g_arrUTF16LEPreamble, sizeof(g_arrUTF16LEPreamble)) == 0) { eEncoding = TXTENC_UTF16LE; dwStartPos = sizeof(g_arrUTF16LEPreamble); dwCharSize = sizeof(WCHAR); dwOffsetFromStart = 0; } else if (dwNumRead >= sizeof(g_arrUTF16BEPreamble) && memcmp(arrBuffer, g_arrUTF16BEPreamble, sizeof(g_arrUTF16BEPreamble)) == 0) { eEncoding = TXTENC_UTF16BE; dwStartPos = sizeof(g_arrUTF16BEPreamble); dwCharSize = sizeof(WCHAR); dwOffsetFromStart = 1; } else if (dwNumRead >= sizeof(g_arrUTF8Preamble) && memcmp(arrBuffer, g_arrUTF8Preamble, sizeof(g_arrUTF8Preamble)) == 0) { eEncoding = TXTENC_UTF8; dwStartPos = sizeof(g_arrUTF8Preamble); dwCharSize = sizeof(CHAR); dwOffsetFromStart = 0; } else if (bIsXmlFile) { static const CHAR szXmlProcessingInstruction[] = "<?xml "; const DWORD dwXmlProcessingInstructionLength = sizeof(szXmlProcessingInstruction) - 1; static const CHAR szEncodingAttribute[] = "encoding"; const DWORD dwEncodingAttributeLength = sizeof(szEncodingAttribute) - 1; static const CHAR szUTF8Encoding[] = "UTF-8"; const DWORD dwUTF8EncodingLength = sizeof(szUTF8Encoding) - 1; eEncoding = TXTENC_UTF8; // default XML encoding dwStartPos = dwOffsetFromStart = 0; dwCharSize = sizeof(CHAR); if (dwNumRead >= dwXmlProcessingInstructionLength && _memicmp(arrBuffer, szXmlProcessingInstruction, dwXmlProcessingInstructionLength) == 0) { DWORD dwBytePos = dwXmlProcessingInstructionLength; while (dwBytePos < dwNumRead) { while (dwBytePos < dwNumRead && IsSpace(arrBuffer[dwBytePos])) ++dwBytePos; if (dwBytePos >= dwNumRead || arrBuffer[dwBytePos] == '?') break; DWORD dwWordStart = dwBytePos; while (dwBytePos < dwNumRead && IsAlpha(arrBuffer[dwBytePos])) ++dwBytePos; DWORD dwWordLength = dwBytePos - dwWordStart; if (dwWordLength == 0) break; while (dwBytePos < dwNumRead && IsSpace(arrBuffer[dwBytePos])) ++dwBytePos; if (dwBytePos < dwNumRead && arrBuffer[dwBytePos] == '=') ++dwBytePos; else break; while (dwBytePos < dwNumRead && IsSpace(arrBuffer[dwBytePos])) ++dwBytePos; if (dwBytePos < dwNumRead && IsQuotation(arrBuffer[dwBytePos])) ++dwBytePos; else break; if (dwBytePos < dwNumRead) { DWORD dwValueStart = dwBytePos; while (dwBytePos < dwNumRead && ! IsQuotation(arrBuffer[dwBytePos])) ++dwBytePos; DWORD dwValueLength = dwBytePos - dwValueStart; if (dwBytePos < dwNumRead) ++dwBytePos; if (dwWordLength == dwEncodingAttributeLength && _memicmp(arrBuffer + dwWordStart, szEncodingAttribute, dwWordLength) == 0) { if (dwValueLength != dwUTF8EncodingLength || _memicmp(arrBuffer + dwValueStart, szUTF8Encoding, dwUTF8EncodingLength) != 0) eEncoding = TXTENC_ANSI; break; } } } } } else { eEncoding = TXTENC_ANSI; dwStartPos = dwOffsetFromStart = 0; dwCharSize = sizeof(CHAR); } for (DWORD dwBytePos = dwStartPos + dwOffsetFromStart; dwBytePos < dwNumRead; dwBytePos += dwCharSize) { if (arrBuffer[dwBytePos] == 0) { bTextFile = FALSE; eEncoding = TXTENC_ANSI; dwStartPos = 0; break; } } return dwStartPos; }
sesom42/BugTrap
source/Client/TextFormat.cpp
C++
mit
4,817
require 'puppet/provider/package' require 'uri' Puppet::Type.type(:package).provide :pacman, :parent => Puppet::Provider::Package do desc "Support for the Package Manager Utility (pacman) used in Archlinux." commands :pacman => "/usr/bin/pacman" # Yaourt is a common AUR helper which, if installed, we can use to query the AUR commands :yaourt => "/usr/bin/yaourt" if File.exists? '/usr/bin/yaourt' confine :operatingsystem => :archlinux defaultfor :operatingsystem => :archlinux has_feature :upgradeable # If yaourt is installed, we can make use of it def yaourt? return File.exists? '/usr/bin/yaourt' end # Install a package using 'pacman', or 'yaourt' if available. # Installs quietly, without confirmation or progressbar, updates package # list from servers defined in pacman.conf. def install if @resource[:source] install_from_file else install_from_repo end unless self.query raise Puppet::ExecutionFailure.new("Could not find package %s" % self.name) end end def install_from_repo if yaourt? yaourt "--noconfirm", "-S", @resource[:name] else pacman "--noconfirm", "--noprogressbar", "-Sy", @resource[:name] end end private :install_from_repo def install_from_file source = @resource[:source] begin source_uri = URI.parse source rescue => detail fail "Invalid source '#{source}': #{detail}" end source = case source_uri.scheme when nil then source when /https?/i then source when /ftp/i then source when /file/i then source_uri.path when /puppet/i fail "puppet:// URL is not supported by pacman" else fail "Source #{source} is not supported by pacman" end pacman "--noconfirm", "--noprogressbar", "-Sy" pacman "--noconfirm", "--noprogressbar", "-U", source end private :install_from_file def self.listcmd [command(:pacman), "-Q"] end # Fetch the list of packages currently installed on the system. def self.instances packages = [] begin execpipe(listcmd()) do |process| # pacman -Q output is 'packagename version-rel' regex = %r{^(\S+)\s(\S+)} fields = [:name, :ensure] hash = {} process.each_line { |line| if match = regex.match(line) fields.zip(match.captures) { |field,value| hash[field] = value } name = hash[:name] hash[:provider] = self.name packages << new(hash) hash = {} else warning("Failed to match line %s" % line) end } end rescue Puppet::ExecutionFailure return nil end packages end # Because Archlinux is a rolling release based distro, installing a package # should always result in the newest release. def update # Install in pacman can be used for update, too self.install end # We rescue the main check from Pacman with a check on the AUR using yaourt, if installed def latest pacman "-Sy" pacman_check = true # Query the main repos first begin if pacman_check output = pacman "-Sp", "--print-format", "%v", @resource[:name] return output.chomp else output = yaourt "-Qma", @resource[:name] output.split("\n").each do |line| return line.split[1].chomp if line =~ /^aur/ end end rescue Puppet::ExecutionFailure if pacman_check and self.yaourt? pacman_check = false # now try the AUR retry else raise end end end # Querys the pacman master list for information about the package. def query begin output = pacman("-Qi", @resource[:name]) if output =~ /Version.*:\s(.+)/ return { :ensure => $1 } end rescue Puppet::ExecutionFailure return { :ensure => :purged, :status => 'missing', :name => @resource[:name], :error => 'ok', } end nil end # Removes a package from the system. def uninstall pacman "--noconfirm", "--noprogressbar", "-R", @resource[:name] end end
phatpenguin/boxen-belgarion
.bundle/ruby/1.9.1/gems/puppet-3.1.0/lib/puppet/provider/package/pacman.rb
Ruby
mit
4,186
/* Script: Language.it.js MooTools Filemanager - Language Strings in English Translation: Moreno Monga */ Filemanager.Language.it = { more: 'Dettagli', width: 'Larghezza:', height: 'Altezza:', ok: 'Ok', open: 'Seleziona file', upload: 'Upload', create: 'Crea cartella', createdir: 'Specifica il nome della cartella:', cancel: 'Annulla', error: 'Errore', information: 'Informazioni', type: 'Tipo:', size: 'Dimensione:', dir: 'Percorso:', modified: 'Ultima modifica:', preview: 'Anteprima', close: 'Chiudi', destroy: 'Cancella', destroyfile: 'Sei sicuro di voler cancellare questo file?', rename: 'Rinomina', renamefile: 'Scrivi un nuovo nome per il file:', rn_mv_cp: 'Rename/Move/Copy', download: 'Download', nopreview: '<i>Non sono disponibili anteprime</i>', title: 'Titolo:', artist: 'Artista:', album: 'Album:', length: 'Lunghezza:', bitrate: 'Bitrate:', deselect: 'Deseleziona', nodestroy: 'La cancellazioni dei file è disabilitata.', toggle_side_boxes: 'Thumbnail view', toggle_side_list: 'List view', show_dir_thumb_gallery: 'Show thumbnails of the files in the preview pane', drag_n_drop: 'Drag & drop has been enabled for this directory', drag_n_drop_disabled: 'Drag & drop has been temporarily disabled for this directory', goto_page: 'Go to page', 'backend.disabled': 'L Upload dei file è disabilitato.', 'backend.authorized': 'Non sei autorizzato a fare l upload dei file.', 'backend.path': 'La cartella degli upload non esiste. Contattare il webmaster.', 'backend.exists': 'La cartella specificata per gli upload esiste già. Contattare il webmaster.', 'backend.mime': 'Il tipo del file specificato non è consentito.', 'backend.extension': 'Il tipo di file che si vuole caricare non è consentito o è sconosciuto.', 'backend.size': 'La dimensione del file è troppo grande per essere processato. Ricarica un file con dimensioni ridotte.', 'backend.partial': 'Il file è stato parzialmente caricato. Per favore, prova a ricaricarlo.', 'backend.nofile': 'Non è stato specificato alcun file da caricare.', 'backend.default': 'Mi spiace, l operazione non è andata a buon fine.', 'backend.path_not_writable': 'You do not have write/upload permissions for this directory.', 'backend.filename_maybe_too_large': 'The filename/path is probably too long for the server filesystem. Please retry with a shorter file name.', 'backend.fmt_not_allowed': 'You are not allowed to upload this file format/name.', 'backend.read_error': 'Cannot read / download the specified file.', 'backend.unidentified_error': 'An unindentified error occurred while communicating with the backend (web server).', 'backend.nonewfile': 'A new name for the file to be moved / copied is missing.', 'backend.corrupt_img': 'This file is a not a image or a corrupt file: ', // path 'backend.resize_inerr': 'This file could not be resized due to an internal error.', 'backend.copy_failed': 'An error occurred while copying the file / directory: ', // oldlocalpath : newlocalpath 'backend.delete_cache_entries_failed': 'An error occurred when attempting to delete the item cache (thumbnails, metadata)', 'backend.mkdir_failed': 'An error occurred when attempting to create the directory: ', // path 'backend.move_failed': 'An error occurred while moving / renaming the file / directory: ', // oldlocalpath : newlocalpath 'backend.path_tampering': 'Path tampering detected.', 'backend.realpath_failed': 'Cannot translate the given file specification to a valid storage location: ', // $path 'backend.unlink_failed': 'An error occurred when attempting to delete the file / directory: ', // path // Image.class.php: 'backend.process_nofile': 'The image processing unit did not receive a valid file location to work on.', 'backend.imagecreatetruecolor_failed': 'The image processing unit failed: GD imagecreatetruecolor() failed.', 'backend.imagealphablending_failed': 'The image processing unit failed: cannot perform the required image alpha blending.', 'backend.imageallocalpha50pctgrey_failed': 'The image processing unit failed: cannot allocate space for the alpha channel and the 50% background.', 'backend.imagecolorallocatealpha_failed': 'The image processing unit failed: cannot allocate space for the alpha channel for this color image.', 'backend.imagerotate_failed': 'The image processing unit failed: GD imagerotate() failed.', 'backend.imagecopyresampled_failed': 'The image processing unit failed: GD imagecopyresampled() failed. Image resolution: ', /* x * y */ 'backend.imagecopy_failed': 'The image processing unit failed: GD imagecopy() failed.', 'backend.imageflip_failed': 'The image processing unit failed: cannot flip the image.', 'backend.imagejpeg_failed': 'The image processing unit failed: GD imagejpeg() failed.', 'backend.imagepng_failed': 'The image processing unit failed: GD imagepng() failed.', 'backend.imagegif_failed': 'The image processing unit failed: GD imagegif() failed.', 'backend.imagecreate_failed': 'The image processing unit failed: GD imagecreate() failed.', 'backend.cvt2truecolor_failed': 'conversion to True Color failed. Image resolution: ', /* x * y */ 'backend.no_imageinfo': 'Corrupt image or not an image file at all.', 'backend.img_will_not_fit': 'Server error: image does not fit in available RAM; minimum required (estimate): ', /* XXX MBytes */ 'backend.unsupported_imgfmt': 'unsupported image format: ', /* jpeg/png/gif/... */ /* FU */ uploader: { unknown: 'Errore sconosciuto', sizeLimitMin: 'Non puoi caricare "<em>${name}</em>" (${size}), la dimensione minima del file è <strong>${size_min}</strong>!', sizeLimitMax: 'Non puoi caricare "<em>${name}</em>" (${size}), la dimensione massima del file è <strong>${size_max}</strong>!', mod_security: 'No response was given from the uploader, this may mean that "mod_security" is active on the server and one of the rules in mod_security has cancelled this request. If you can not disable mod_security, you may need to use the NoFlash Uploader.' }, flash: { hidden: 'To enable the embedded uploader, unblock it in your browser and refresh (see Adblock).', disabled: 'To enable the embedded uploader, enable the blocked Flash movie and refresh (see Flashblock).', flash: 'In order to upload files you need to install <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash">Adobe Flash</a>.' }, resizeImages: 'Ridimensiona immagini grandi', serialize: 'Salva galleria', gallery: { text: 'Titolo immagine', save: 'Salva', remove: 'Rimuovi dalla galleria', drag: 'Sposta gli oggetti qui per creare una galleria...' } };
a7medelgendy/learn-git
themes/admin/javascript/filemanager/language/Language.it.js
JavaScript
mit
6,669
'use strict'; // Setting up route angular.module('usuarios-mobile').config(['$stateProvider', 'RouteHelpersProvider', function($stateProvider, helper) { // Articles state routing $stateProvider. state('app.listUsuariosMobile', { url: '/usuarios-mobile', title: 'Listar Usuários Mobile', templateUrl: 'modules/usuarios-mobile/views/list-usuarios-mobile.client.view.html', resolve: helper.resolveFor('datatables', 'xeditable') }); } ]);
marcostomazini/unicesumar-marketing
public/modules/usuarios-mobile/config/usuarios-mobile.client.routes.js
JavaScript
mit
458
var searchData= [ ['defaultgaussianmixture',['DefaultGaussianMixture',['../namespaceedda_1_1dist.html#a7ac563ae69a0db2921a59877f32c2846',1,'edda::dist']]], ['devicegmmarray',['DeviceGMMArray',['../namespaceedda.html#adf57cb048134c8ba9b3560698eb45a61',1,'edda']]], ['dword',['DWORD',['../bmp__image_8h.html#af483253b2143078cede883fc3c111ad2',1,'bmp_image.h']]] ];
GRAVITYLab/edda
html/search/typedefs_2.js
JavaScript
mit
369
require 'spec_helper' require Rails.root.join('lib/migrations/ss/20150619114301_fix_ss_files_url') RSpec.describe SS::Migration20150619114301, dbscope: :example do let(:before_html_path) { Rails.root.join("spec/fixtures/ss/migration/fix_ss_files_url/before.html") } let(:before_layout_html_path) { Rails.root.join("spec/fixtures/ss/migration/fix_ss_files_url/before_layout.html") } let(:after_html_path) { Rails.root.join("spec/fixtures/ss/migration/fix_ss_files_url/after.html") } let(:after_layout_html_path) { Rails.root.join("spec/fixtures/ss/migration/fix_ss_files_url/after_layout.html") } before do @save_multibyte_filename = SS.config.env.multibyte_filename @save_file_url_with = SS.config.ss.file_url_with SS.config.replace_value_at(:env, :multibyte_filename, "underscore") SS.config.replace_value_at(:ss, :file_url_with, "filename") end after do SS.config.replace_value_at(:ss, :file_url_with, @save_file_url_with) SS.config.replace_value_at(:env, :multibyte_filename, @save_multibyte_filename) end before do @before_html = ::File.open(before_html_path).read @before_layout_html = ::File.open(before_layout_html_path).read @after_html = ::File.open(after_html_path).read @after_layout_html = ::File.open(after_layout_html_path).read create_once :cms_page, name: "cms_page", html: @before_html create_once :article_page, name: "article_page", html: @before_html create_once :cms_part_free, name: "free_part", html: @before_html create_once :article_part_page, name: "list_part", upper_html: @before_html, lower_html: @before_html create_once :cms_layout, name: "layout", html: @before_layout_html SS.config.replace_value_at(:env, :multibyte_filename, "underscore") SS::File.destroy_all @file = SS::File.new @file.in_file = Fs::UploadedFile.create_from_file("spec/fixtures/ss/logo.png") @file.model = "ss/file" @file.id = 1000 @file.save! @file.set(filename: "ロゴ.png") @file.set(name: nil) end it do described_class.new.change @file.reload expect(@file.filename).to eq "__.png" expect(@file.name).to eq "ロゴ.png" Cms::Page.all.each do |item| expect(item.html).to eq(@after_html.strip) end Cms::Part.all.each do |item| expect(item.html).to eq(@after_html.strip) if item.respond_to?(:html) expect(item.upper_html).to eq(@after_html.strip) if item.respond_to?(:upper_html) expect(item.lower_html).to eq(@after_html.strip) if item.respond_to?(:lower_html) end Cms::Layout.all.each do |item| expect(item.html).to eq(@after_layout_html.strip) end end end
tany/ss
spec/lib/ss/migrations/20150619114301_fix_ss_files_url_spec.rb
Ruby
mit
2,665
# -*- coding: utf-8 -*- # -- ==alkane_monolayer== -- import mbuild as mb from mbuild.lib.surfaces import Betacristobalite from mbuild.lib.atoms import H from mbuild.examples.alkane_monolayer.alkylsilane import AlkylSilane class AlkaneMonolayer(mb.Monolayer): """An akylsilane monolayer on beta-cristobalite. """ def __init__(self, pattern, tile_x=1, tile_y=1, chain_length=10): """Create an alkylsilane monolayer on beta-cristobalite. Parameters ---------- pattern : np.ndarray, shape=(n, 3), optional, default=None An array of planar binding locations. If not provided, the entire surface will be filled with `chain`. tile_x : int, optional, default=1 Number of times to replicate substrate in x-direction. tile_y : int, optional, default=1 Number of times to replicate substrate in y-direction. chain_length : int, optional, default=10 Number of carbon atoms per chain. """ surface = Betacristobalite() alkylsilane = AlkylSilane(chain_length) hydrogen = H() super(AlkaneMonolayer, self).__init__(surface, alkylsilane, backfill=hydrogen, pattern=pattern, tile_x=tile_x, tile_y=tile_y) # -- ==alkane_monolayer== --
ctk3b/mbuild
mbuild/examples/alkane_monolayer/alkane_monolayer.py
Python
mit
1,378
<?php // users.php :: Handles user account functions. /*$controlquery = doquery("SELECT * FROM {{table}} WHERE id='1' LIMIT 1", "control"); $controlrow = mysql_fetch_array($controlquery);*/ include('lib.php'); $link = opendb(); include('cookies.php'); $userrow = checkcookies(); if (isset($_GET["do"])) { $do = $_GET["do"]; if ($do == "register") { register(); } elseif ($do == "verify") { verify(); } elseif ($do == "lostpassword") { lostpassword(); } elseif ($do == "changepassword") { changepassword(); } elseif ($do == "doardinheiro") { doardinheiro(); } elseif ($do == "banco") { banco(); } elseif ($do == "doaritem") { doaritem(); } elseif ($do == "troca1") { troca1(); } elseif ($do == "troca2") { troca2(); } elseif ($do == "troca3") { troca3(); } elseif ($do == "troca4") { troca4(); } elseif ($do == "batalha1") { batalha1(); } elseif ($do == "resetarduelo") { resetarduelo(); } elseif ($do == "duelo") { duelo(); } elseif ($do == "procurarjogador") { procurarjogador(); } } function register() { // Register a new account. $controlquery = doquery("SELECT * FROM {{table}} WHERE id='1' LIMIT 1", "control"); $controlrow = mysql_fetch_array($controlquery); if (isset($_POST["submit"])) { extract($_POST); $errors = 0; $errorlist = ""; if (strlen($password1) > 10){ $errors++; $errorlist .= "Senha não pode conter mais que 10 caracteres.<br />"; } if (strlen($username) > 30){ $errors++; $errorlist .= "Nome da Conta não pode conter mais que 30 caracteres.<br />"; } // Process username. if ($username == "") { $errors++; $errorlist .= "Nome da conta é necessário.<br />"; } if (preg_match("/[^A-z0-9_\-]/", $username)==1) { $errors++; $errorlist .= "Nome da sua conta deve ser alfanumérico(não pode conter espaços).<br />"; } // Thanks to "Carlos Pires" from php.net! $usernamequery = doquery("SELECT username FROM {{table}} WHERE username='$username' LIMIT 1","users"); if (mysql_num_rows($usernamequery) > 0) { $errors++; $errorlist .= "Essa conta já existe.<br />"; } // Process charname. if ($charname == "") { $errors++; $errorlist .= "Campo de Nome do Personagem é necessário.<br />"; } if (preg_match("/[^A-z0-9_\-]/", $charname)==1) { $errors++; $errorlist .= "Nome do personagem deve ser alfanumérico(não pode conter espaços).<br />"; } // Thanks to "Carlos Pires" from php.net! $characternamequery = doquery("SELECT charname FROM {{table}} WHERE charname='$charname' LIMIT 1","users"); if (mysql_num_rows($characternamequery) > 0) { $errors++; $errorlist .= "Esse nome de personagem já está em uso.<br />"; } // Process email address. if ($email1 == "" || $email2 == "") { $errors++; $errorlist .= "Campo de e-mail é necessário.<br />"; } if ($email1 != $email2) { $errors++; $errorlist .= "Os e-mails não coincidem.<br />"; } if (! is_email($email1)) { $errors++; $errorlist .= "O e-mail não é válido.<br />"; } $emailquery = doquery("SELECT email FROM {{table}} WHERE email='$email1' LIMIT 1","users"); if (mysql_num_rows($emailquery) > 0) { $errors++; $errorlist .= "Esse e-mail já está em uso.<br />"; } // Process password. if (trim($password1) == "") { $errors++; $errorlist .= "Campo de senha é necessário.<br />"; } if (preg_match("/[^A-z0-9_\-]/", $password1)==1) { $errors++; $errorlist .= "Sua senha deve ser alfanumérica.<br />"; } // Thanks to "Carlos Pires" from php.net! if ($password1 != $password2) { $errors++; $errorlist .= "Os campos de senha não coincidem.<br />"; } $password = md5($password1); if ($errors == 0) { if ($controlrow["verifyemail"] == 1) { $verifycode = ""; for ($i=0; $i<8; $i++) { $verifycode .= chr(rand(65,90)); } } else { $verifycode='1'; } $query = doquery("INSERT INTO {{table}} SET id='',regdate=NOW(),verify='$verifycode',username='$username',password='$password',email='$email1',charname='$charname',charclass='$charclass',difficulty='$difficulty'", "users") or die(mysql_error()); if ($controlrow["verifyemail"] == 1) { if (sendregmail($email1, $verifycode) == true) { $page = "<table width=\"100%\"><tr><td width=\"100%\" align=\"center\"><center><img src=\"images/criarconta.gif\" /></center></td></tr></table>Sua conta foi criada com sucesso.<br /><br />Você deve receber um e-mail de confirmação logo. É preciso verificar o código que está presente no seu e-mail para ativar a sua conta. Uma vez recebido o e-mail, por favor visite a <a href=\"users.php?do=verify\">Página de Verificação</a> para ativar sua conta e começar a jogar."; } else { $page = "<table width=\"100%\"><tr><td width=\"100%\" align=\"center\"><center><img src=\"images/criarconta.gif\" /></center></td></tr></table>Sua conta foi criada com sucesso.<br /><br />De qualquer forma, houve um erro durante o envio do seu e-mail de confirmação. Por favor cheque com o Administrador do jogo para resolver seu problema. Você também pode ativar sua conta pelo site clicando <a href=\"http://www.nigeru.com/narutorpg/ativarconta.php\">aqui</a>."; } } else { $page = "<table width=\"100%\"><tr><td width=\"100%\" align=\"center\"><center><img src=\"images/criarconta.gif\" /></center></td></tr></table>Sua conta foi criada com sucesso.<br /><br />Você pode agora acessar a <a href=\"login.php?do=login\">Página de Login</a> e continuar jogando ".$controlrow["gamename"]."!"; } } else { $page = "<table width=\"100%\"><tr><td width=\"100%\" align=\"center\"><center><img src=\"images/criarconta.gif\" /></center></td></tr></table><form id=\"formback\"><fieldset id=\"field2\"><legend>Dados da Conta</legend>O(s) seguinte(s) erro(s) ocorreram enquanto sua conta estava sendo feita:<br /><span style=\"color:red;\">$errorlist</span><br />Por favor <a href=\"javascript: history.back();\">volte</a> e tente novamente.</fieldset></form>"; } } else { $page = gettemplate("register"); if ($controlrow["verifyemail"] == 1) { $controlrow["verifytext"] = "<br /><span class=\"small\">Um código de verificação será enviado para seu e-mail, você não está habilitado a jogar antes de ativar sua conta com o código presente em seu e-mail. Esteja ciente de que é preciso preencher o campo e-mail com um e-mail válido.</span>"; } else { $controlrow["verifytext"] = ""; } $page = parsetemplate($page, $controlrow); } $topnav = "<a href=\"login.php?do=login\"><img src=\"images/button_login.gif\" alt=\"Log In\" border=\"0\" /></a><a href=\"users.php?do=register\"><img src=\"images/button_register.gif\" alt=\"Register\" border=\"0\" /></a><a href=\"help.php\"><img src=\"images/button_help.gif\" alt=\"Help\" border=\"0\" /></a>"; display($page, "Registrar", false, false, false); } function verify() { if (isset($_POST["submit"])) { extract($_POST); $userquery = doquery("SELECT username,email,verify FROM {{table}} WHERE username='$username' LIMIT 1","users"); if (mysql_num_rows($userquery) != 1) { die("Nenhuma conta com esse nome."); } $userrow = mysql_fetch_array($userquery); if ($userrow["verify"] == 1) { die("Sua conta já está verificada."); } if ($userrow["email"] != $email) { die("E-mail incorreto."); } if ($userrow["verify"] != $verify) { die("Código de verificação incorreto."); } // If we've made it this far, should be safe to update their account. $updatequery = doquery("UPDATE {{table}} SET verify='1' WHERE username='$username' LIMIT 1","users"); display("<table width=\"100%\"><tr><td width=\"100%\" align=\"center\"><center><img src=\"images/minhaconta.gif\" /></center></td></tr></table>Sua conta foi ativada com sucesso..<br /><br />Você pode acessar a <a href=\"login.php?do=login\">Página de Login</a> e começar a jogar agora mesmo.<br /><br />Obrigado por jogar!","Verificar Email",false,false,false); } $page = gettemplate("verify"); $topnav = "<a href=\"login.php?do=login\"><img src=\"images/button_login.gif\" alt=\"Log In\" border=\"0\" /></a><a href=\"users.php?do=register\"><img src=\"images/button_register.gif\" alt=\"Register\" border=\"0\" /></a><a href=\"help.php\"><img src=\"images/button_help.gif\" alt=\"Help\" border=\"0\" /></a>"; display($page, "Verify Email", false, false, false); } function lostpassword() { if (isset($_POST["submit"])) { extract($_POST); $userquery = doquery("SELECT email FROM {{table}} WHERE email='$email' LIMIT 1","users"); if (mysql_num_rows($userquery) != 1) { header("Location: users.php?do=lostpassword&conteudo=Não há uma conta com esse e-mail."); die();} $newpass = ""; for ($i=0; $i<8; $i++) { $newpass .= chr(rand(65,90)); } $md5newpass = md5($newpass); $updatequery = doquery("UPDATE {{table}} SET password='$md5newpass' WHERE email='$email' LIMIT 1","users"); if (sendpassemail($email,$newpass) == true) { display("<table width=\"100%\"><tr><td width=\"100%\" align=\"center\"><center><img src=\"images/minhaconta.gif\" /></center></td></tr></table><fieldset id=\"field2\"><legend>Recuperar Senha</legend>Sua nova senha foi enviada para seu e-mail.<br /><br />Quando recebê-la, você pode fazer o <a href=\"login.php?do=login\">Log In</a> e continuar jogando.<br /><br />Obrigado.</fieldset>","Senha Perdida",false,false,false); } else { header("Location: users.php?do=lostpassword&conteudo=Houve um erro no envio da sua nova senha. Por favor cheque com o Administrador ou alguém da equipe para mais informações. Pedimos desculpas pelo transtorno."); die(); } die(); } global $conteudouser; $conteudouser = $_GET['conteudo']; $conteudouser = "<font color=brown><center>".strip_tags($conteudouser)."</font></center>"; $page = gettemplate("lostpassword"); $topnav = "<a href=\"login.php?do=login\"><img src=\"images/button_login.gif\" alt=\"Log In\" border=\"0\" /></a><a href=\"users.php?do=register\"><img src=\"images/button_register.gif\" alt=\"Register\" border=\"0\" /></a><a href=\"help.php\"><img src=\"images/button_help.gif\" alt=\"Help\" border=\"0\" /></a>"; display($page, "Senha Perdida", false, false, false); } function changepassword() { if (isset($_POST["submit"])) { extract($_POST); $userquery = doquery("SELECT * FROM {{table}} WHERE username='$username' LIMIT 1","users"); if (mysql_num_rows($userquery) != 1) {header("Location: users.php?do=changepassword&conteudo=Não há uma conta com esse nome."); die(); } $userrow = mysql_fetch_array($userquery); if ($userrow["password"] != md5($oldpass)) {header("Location: users.php?do=changepassword&conteudo=A senha antiga está incorreta."); die();} if (preg_match("/[^A-z0-9_\-]/", $newpass1)==1) {header("Location: users.php?do=changepassword&conteudo=A nova senha precisa ser alfanumérica."); die();} // Thanks to "Carlos Pires" from php.net! if ($newpass1 != $newpass2) { header("Location: users.php?do=changepassword&conteudo=Novas senhas não coincidem.");die();} $realnewpass = md5($newpass1); $updatequery = doquery("UPDATE {{table}} SET password='$realnewpass' WHERE username='$username' LIMIT 1","users"); if (isset($_COOKIE["dkgame"])) { setcookie("dkgame", "", time()-100000, "/", "", 0); } display("<table width=\"100%\"><tr><td width=\"100%\" align=\"center\"><center><img src=\"images/minhaconta.gif\" /></center></td></tr></table><fieldset id=\"field2\"><legend>Mudar Senha</legend>Sua senha foi modificada com sucesso.<br /><br />Você foi desconectado do jogo para evitar erros.<br /><br />Por favor, <a href=\"login.php?do=login\">faça o login novamente</a> para continuar jogando.<br></fieldset>","Mudar Senha",false,false,false); die(); } global $conteudouser; $conteudouser = $_GET['conteudo']; $conteudouser = "<font color=brown><center>".strip_tags($conteudouser)."</font></center>"; $page = gettemplate("changepassword"); $topnav = "<a href=\"login.php?do=login\"><img src=\"images/button_login.gif\" alt=\"Log In\" border=\"0\" /></a><a href=\"users.php?do=register\"><img src=\"images/button_register.gif\" alt=\"Register\" border=\"0\" /></a><a href=\"help.php\"><img src=\"images/button_help.gif\" alt=\"Help\" border=\"0\" /></a>"; display($page, "Mudar Senha", false, false, false); } function sendpassemail($emailaddress, $password) { $controlquery = doquery("SELECT * FROM {{table}} WHERE id='1' LIMIT 1", "control"); $controlrow = mysql_fetch_array($controlquery); extract($controlrow); $email = <<<END Você ou alguém usando a sua conta de e-mail, utilizou a função de Senha Perdida do jogo $gamename, localizado em $gameurl. Nós estamos te enviando uma nova senha, então você poderá entrar novamente no jogo. Sua nova senha é: $password Obrigado por jogar. Nigeru Animes. END; $status = mymail($emailaddress, "$gamename Senha Perdida", $email); return $status; } function sendregmail($emailaddress, $vercode) { $controlquery = doquery("SELECT * FROM {{table}} WHERE id='1' LIMIT 1", "control"); $controlrow = mysql_fetch_array($controlquery); extract($controlrow); $verurl = $gameurl . "?do=verify"; $email = <<<END Você ou alguém usando sua conta de e-mail, recentemente se registrou no jogo $gamename, localizado em $gameurl. Esse e-mail é enviado para verificar seu e-mail de registro. Para começar a utilizar a sua conta, você deve verificar o seu e-mail. Por favor visite a Página de Verificação: ($verurl) e preencha com o código de ativação abaixo: Código de Ativação: $vercode Se você não é a pessoa que se registrou no jogo, por favor ignore essa mensagem. Você não receberá outro e-mail. END; $status = mymail($emailaddress, "$gamename Verificação da Conta", $email); return $status; } function mymail($to, $title, $body, $from = '') { // thanks to arto dot PLEASE dot DO dot NOT dot SPAM at artoaaltonen dot fi. $controlquery = doquery("SELECT * FROM {{table}} WHERE id='1' LIMIT 1", "control"); $controlrow = mysql_fetch_array($controlquery); extract($controlrow); $from = trim($from); if (!$from) { $from = '<'.$controlrow["adminemail"].'>'; } $rp = $controlrow["adminemail"]; $org = '$gameurl'; $mailer = 'PHP'; $head = ''; $head .= "Content-Type: text/plain \r\n"; $head .= "Date: ". date('r'). " \r\n"; $head .= "Return-Path: $rp \r\n"; $head .= "From: $from \r\n"; $head .= "Sender: $from \r\n"; $head .= "Reply-To: $from \r\n"; $head .= "Organization: $org \r\n"; $head .= "X-Sender: $from \r\n"; $head .= "X-Priority: 3 \r\n"; $head .= "X-Mailer: $mailer \r\n"; $body = str_replace("\r\n", "\n", $body); $body = str_replace("\n", "\r\n", $body); return mail($to, $title, $body, $head); } function doardinheiro() { global $topvar; $topvar = true; /* testando se está logado */ //include('cookies.php'); //$userrow = checkcookies(); global $userrow; if ($userrow == false) { display("Por favor faça o <a href=\"login.php?do=login\">log in</a> no jogo antes de executar essa ação.","Erro",false,false,false); die(); } if ($userrow["currentaction"] != "In Town") {if ($userrow["currentaction"] == "Fighting"){header('Location: ./index.php?do=fight&conteudo=Você só pode acessar essa função dentro de uma cidade!');die();}else{header('Location: ./index.php?conteudo=Você só pode acessar essa função dentro de uma cidade!');die();} } if ($userrow["currentaction"] == "Fighting") {header('Location: ./index.php?do=fight&conteudo=Você não pode acessar essa função no meio de uma batalha!');die(); } if ($userrow["level"] < 5) {display("Você não pode acessar essa função se seu level for menor que 5!","Erro",false,false,false);die(); } $usuariologadoid = $userrow["id"]; $usuariologadonome = $userrow["charname"]; $usuriologadodinaheiro = $userrow["gold"]; /*fim do teste */ /* OLDPASS É A QUANTIDADE DE DINHEIRO DOADO */ if (isset($_POST["submit"])) { extract($_POST); $userquery = doquery("SELECT * FROM {{table}} WHERE charname='$username' LIMIT 1","users"); if (mysql_num_rows($userquery) != 1) { display("<table width=\"100%\"><tr><td width=\"100%\" align=\"center\"><center><img src=\"images/minhaconta.gif\" /></center></td></tr></table>Não existe nenhuma conta com esse Nome.","Erro",false,false,false);die(); } $userrow = mysql_fetch_array($userquery); if ($usuariologadoid == $userrow["id"]) { display("Você não pode doar Ryou para si mesmo.","Erro",false,false,false);die();} if (!is_numeric($oldpass)) { display("A quantidade de Ryou deve ser um número.","Erro",false,false,false);die(); } $oldpass = floor($oldpass); /*if ($userrow["password"] != md5($oldpass)) { die("The old password you provided was incorrect."); } /*$realnewpass = md5($newpass1); */ if ($oldpass > $usuriologadodinaheiro) { display("Você não pode doar mais do que a sua quantidade de Ryou.","Erro",false,false,false);die(); } if ($oldpass < 1) { display("Você não pode doar menos que 1 Ryou.","Erro",false,false,false);die(); } $dinheirototal = $userrow["gold"] + $oldpass; $dinheirousuariologadodepois = $usuriologadodinaheiro - $oldpass; $updatequery = doquery("UPDATE {{table}} SET gold='$dinheirototal' WHERE charname='$username' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET gold='$dinheirousuariologadodepois' WHERE charname='$usuariologadonome' LIMIT 1","users"); display("O dinheiro foi retirado da sua conta e doado com sucesso.<br /><br />Você pode <a href=\"index.php\">clicar aqui</a> para continuar jogando ou <a href=\"users.php?do=doardinheiro\">doar mais Ryou</a>.","Doar Ryou",false,false,false); die(); } $page = "<table width=\"100%\"><tr><td width=\"100%\" align=\"center\"><center><img src=\"images/doaryou.gif\" /></center></td></tr></table> <b>Seu Ryou</b>: $usuriologadodinaheiro<br><br>".gettemplate("doardinheiro"); $topnav = "<a href=\"index.php\"><img src=\"images/jogar.gif\" alt=\"Voltar a Jogar\" border=\"0\" /></a><a href=\"help.php\"><img src=\"images/button_help.gif\" alt=\"Ajuda\" border=\"0\" /></a>"; display($page, "Doar Ryou", false, false, false); } function banco() { global $topvar; $topvar = true; /* testando se está logado */ //include('cookies.php'); // $userrow = checkcookies(); global $userrow; if ($userrow == false) { display("Por favor faça o <a href=\"login.php?do=login\">log in</a> no jogo antes de executar essa ação.","Erro",false,false,false);die(); } if ($userrow["currentaction"] != "In Town") {if ($userrow["currentaction"] == "Fighting"){header('Location: ./index.php?do=fight&conteudo=Você só pode acessar essa função dentro de uma cidade!');die();}else{header('Location: ./index.php?conteudo=Você só pode acessar essa função dentro de uma cidade!');die();} } if ($userrow["currentaction"] == "Fighting") {header('Location: ./index.php?do=fight&conteudo=Você não pode acessar essa função no meio de uma batalha!');die(); } $usuariologadoid = $userrow["id"]; $usuariologadonome = $userrow["charname"]; $usuriologadodinheiro = $userrow["gold"]; $armaid = $userrow["weaponid"]; $armaduraid = $userrow["armorid"]; $escudoid = $userrow["shieldid"]; $arma = $userrow["weaponname"]; $armadura = $userrow["armorname"]; $escudo = $userrow["shieldname"]; $idslot1 = $userrow["slot1id"]; $idslot2 = $userrow["slot2id"]; $idslot3 = $userrow["slot3id"]; $nomeslot1 = $userrow["slot1name"]; $nomeslot2 = $userrow["slot2name"]; $nomeslot3 = $userrow["slot3name"]; /* BANCO DE TROCAS */ $banco1 = $userrow["banconome1"]; $banco2 = $userrow["banconome2"]; $banco3 = $userrow["banconome3"]; $banco4 = $userrow["banconome4"]; $banco5 = $userrow["banconome5"]; $banco6 = $userrow["banconome6"]; $banco1id = $userrow["bancoid1"]; $banco2id = $userrow["bancoid2"]; $banco3id = $userrow["bancoid3"]; $banco4id = $userrow["bancoid4"]; $banco5id = $userrow["bancoid5"]; $banco6id = $userrow["bancoid6"]; /* ARMAZENAMENTO */ $b2banco1id = $userrow["b2_bancoid1"]; $b2banco2id = $userrow["b2_bancoid2"]; $b2banco3id = $userrow["b2_bancoid3"]; $b2banco4id = $userrow["b2_bancoid4"]; $b2banco5id = $userrow["b2_bancoid5"]; $b2banco6id = $userrow["b2_bancoid6"]; $b2banco1 = $userrow["b2_banconome1"]; $b2banco2 = $userrow["b2_banconome2"]; $b2banco3 = $userrow["b2_banconome3"]; $b2banco4 = $userrow["b2_banconome4"]; $b2banco5 = $userrow["b2_banconome5"]; $b2banco6 = $userrow["b2_banconome6"]; $ryoudepositado = $userrow["banco_grana"]; $dinheirototal = $usuriologadodinheiro + $ryoudepositado; /*fim do teste */ /* OLDPASS É A QUANTIDADE DE DINHEIRO DOADO */ if (isset($_POST["submit"])) { extract($_POST); //DEPOSITAR GRANA if ($deposito != "") { if (!is_numeric($deposito)) { display("A quantidade de Ryou à repositar deve ser um número.","Erro",false,false,false);die(); } $deposito = floor($deposito); if ($deposito < 1) { display("Você não pode depositar menos que 1 Ryou.","Erro",false,false,false);die(); } $porcentagemconta = floor(90*$dinheirototal/100); $dinheirosuposto = $deposito + $ryoudepositado; if ($dinheirosuposto > 90*$dinheirototal/100) { display("Você não pode ter uma quantia maior que $porcentagemconta Ryou no Banco, que representa 90% do seu Ryou total, o que está depositado e o que está no seu personagem.","Erro",false,false,false);die(); } if ($deposito > $usuriologadodinheiro) { display("Você não pode depositar mais que a sua quantidade de Ryou.","Erro",false,false,false);die(); } $ryoudepositado += floor($deposito); $usuriologadodinheiro -= floor($deposito); $updatequery = doquery("UPDATE {{table}} SET banco_grana='$ryoudepositado' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET gold='$usuriologadodinheiro' WHERE charname='$usuariologadonome' LIMIT 1","users"); } //RETIRAR GRANA if ($retirar != "") { if (!is_numeric($retirar)) { display("A quantidade de Ryou à retirar deve ser um número.","Erro",false,false,false);die(); } $retirar = floor($retirar); if ($retirar < 1) { display("Você não pode retirar menos que 1 Ryou.","Erro",false,false,false);die(); } if ($retirar > 99999) { display("Você não pode retirar mais que 99999 Ryou.","Erro",false,false,false);die(); } if ($retirar > $ryoudepositado) { display("Você não pode retirar mais que seu dinheiro no banco.","Erro",false,false,false);die(); } $ryoudepositado -= floor($retirar); $usuriologadodinheiro += floor($retirar); $updatequery = doquery("UPDATE {{table}} SET banco_grana='$ryoudepositado' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET gold='$usuriologadodinheiro' WHERE charname='$usuariologadonome' LIMIT 1","users"); } /* BANCO DE TROCAS */ //ARMAS if ($Combobox1 == 1) { // STATUS DOS ITENS global $userrow; // Special item fields. $specialchange1 = ""; $specialchange2 = ""; //esse é o q tira if ($armaid != 0) { $itemsquery2 = doquery("SELECT * FROM {{table}} WHERE id='$armaid' LIMIT 1", "items"); $itemsrow2 = mysql_fetch_array($itemsquery2); if ($itemsrow2["special"] != "X") { $special2 = explode(",",$itemsrow2["special"]); $tochange2 = $special2[0]; $userrow[$tochange2] = $userrow[$tochange2] - $special2[1]; $specialchange2 = "$tochange2='".$userrow[$tochange2]."',"; if ($tochange2 == "strength") { $userrow["attackpower"] -= $special2[1]; } if ($tochange2 == "dexterity") { $userrow["defensepower"] -= $special2[1]; } }else{ $itemsrow["special"] = "X";} } else {$itemsrow2["attribute"] = 0; } //esse é o que poe o item equipado if ($banco1id != 0) { $itemsquery = doquery("SELECT * FROM {{table}} WHERE id='$banco1id' LIMIT 1","items"); $itemsrow = mysql_fetch_array($itemsquery); if ($itemsrow["special"] != "X") { $special = explode(",",$itemsrow["special"]); $tochange = $special[0]; $userrow[$tochange] = $userrow[$tochange] + $special[1]; $specialchange1 = "$tochange='".$userrow[$tochange]."',"; if ($tochange == "strength") { $userrow["attackpower"] += $special[1]; } if ($tochange == "dexterity") { $userrow["defensepower"] += $special[1]; } }else{ $itemsrow["special"] = "X";} } else {$itemsrow["attribute"] = 0;} //checar itens $newattack = $userrow["attackpower"] + $itemsrow["attribute"] - $itemsrow2["attribute"]; if ($userrow["currenthp"] > $userrow["maxhp"]) { $newhp = $userrow["maxhp"]; } else { $newhp = $userrow["currenthp"]; } if ($userrow["currentmp"] > $userrow["maxmp"]) { $newmp = $userrow["maxmp"]; } else { $newmp = $userrow["currentmp"]; } if ($userrow["currenttp"] > $userrow["maxtp"]) { $newtp = $userrow["maxtp"]; } else { $newtp = $userrow["currenttp"]; } //upload stats $updatequery = doquery("UPDATE {{table}} SET $specialchange1 $specialchange2 attackpower='$newattack', currenthp='$newhp', currentmp='$newmp', currenttp='$newtp' WHERE charname='$usuariologadonome' LIMIT 1", "users"); //fim $updatequery = doquery("UPDATE {{table}} SET weaponid='$banco1id' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET weaponname='$banco1' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid1='$armaid' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome1='$arma' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox2 == 1) { // STATUS DOS ITENS global $userrow; // Special item fields. $specialchange1 = ""; $specialchange2 = ""; //esse é o q tira if ($armaduraid != 0) { $itemsquery2 = doquery("SELECT * FROM {{table}} WHERE id='$armaduraid' LIMIT 1", "items"); $itemsrow2 = mysql_fetch_array($itemsquery2); if ($itemsrow2["special"] != "X") { $special2 = explode(",",$itemsrow2["special"]); $tochange2 = $special2[0]; $userrow[$tochange2] = $userrow[$tochange2] - $special2[1]; $specialchange2 = "$tochange2='".$userrow[$tochange2]."',"; if ($tochange2 == "strength") { $userrow["attackpower"] -= $special2[1]; } if ($tochange2 == "dexterity") { $userrow["defensepower"] -= $special2[1]; } }else{ $itemsrow["special"] = "X";} } else {$itemsrow2["attribute"] = 0; } //esse é o que poe o item equipado if ($banco2id != 0) { $itemsquery = doquery("SELECT * FROM {{table}} WHERE id='$banco2id' LIMIT 1","items"); $itemsrow = mysql_fetch_array($itemsquery); if ($itemsrow["special"] != "X") { $special = explode(",",$itemsrow["special"]); $tochange = $special[0]; $userrow[$tochange] = $userrow[$tochange] + $special[1]; $specialchange1 = "$tochange='".$userrow[$tochange]."',"; if ($tochange == "strength") { $userrow["attackpower"] += $special[1]; } if ($tochange == "dexterity") { $userrow["defensepower"] += $special[1]; } }else{ $itemsrow["special"] = "X";} } else {$itemsrow["attribute"] = 0;} //checar itens $newdefense = $userrow["defensepower"] + $itemsrow["attribute"] - $itemsrow2["attribute"]; if ($userrow["currenthp"] > $userrow["maxhp"]) { $newhp = $userrow["maxhp"]; } else { $newhp = $userrow["currenthp"]; } if ($userrow["currentmp"] > $userrow["maxmp"]) { $newmp = $userrow["maxmp"]; } else { $newmp = $userrow["currentmp"]; } if ($userrow["currenttp"] > $userrow["maxtp"]) { $newtp = $userrow["maxtp"]; } else { $newtp = $userrow["currenttp"]; } //upload stats $updatequery = doquery("UPDATE {{table}} SET $specialchange1 $specialchange2 defensepower='$newdefense', currenthp='$newhp', currentmp='$newmp', currenttp='$newtp' WHERE charname='$usuariologadonome' LIMIT 1", "users"); //fim $updatequery = doquery("UPDATE {{table}} SET armorid='$banco2id' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET armorname='$banco2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid2='$armaduraid' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome2='$armadura' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox3 == 1) { // STATUS DOS ITENS global $userrow; // Special item fields. $specialchange1 = ""; $specialchange2 = ""; //esse é o q tira if ($escudoid != 0) { $itemsquery2 = doquery("SELECT * FROM {{table}} WHERE id='$escudoid' LIMIT 1", "items"); $itemsrow2 = mysql_fetch_array($itemsquery2); if ($itemsrow2["special"] != "X") { $special2 = explode(",",$itemsrow2["special"]); $tochange2 = $special2[0]; $userrow[$tochange2] = $userrow[$tochange2] - $special2[1]; $specialchange2 = "$tochange2='".$userrow[$tochange2]."',"; if ($tochange2 == "strength") { $userrow["attackpower"] -= $special2[1]; } if ($tochange2 == "dexterity") { $userrow["defensepower"] -= $special2[1]; } }else{ $itemsrow["special"] = "X";} } else {$itemsrow2["attribute"] = 0; } //esse é o que poe o item equipado if ($banco3id != 0) { $itemsquery = doquery("SELECT * FROM {{table}} WHERE id='$banco3id' LIMIT 1","items"); $itemsrow = mysql_fetch_array($itemsquery); if ($itemsrow["special"] != "X") { $special = explode(",",$itemsrow["special"]); $tochange = $special[0]; $userrow[$tochange] = $userrow[$tochange] + $special[1]; $specialchange1 = "$tochange='".$userrow[$tochange]."',"; if ($tochange == "strength") { $userrow["attackpower"] += $special[1]; } if ($tochange == "dexterity") { $userrow["defensepower"] += $special[1]; } }else{ $itemsrow["special"] = "X";} } else {$itemsrow["attribute"] = 0;} //checar itens $newdefense = $userrow["defensepower"] + $itemsrow["attribute"] - $itemsrow2["attribute"]; if ($userrow["currenthp"] > $userrow["maxhp"]) { $newhp = $userrow["maxhp"]; } else { $newhp = $userrow["currenthp"]; } if ($userrow["currentmp"] > $userrow["maxmp"]) { $newmp = $userrow["maxmp"]; } else { $newmp = $userrow["currentmp"]; } if ($userrow["currenttp"] > $userrow["maxtp"]) { $newtp = $userrow["maxtp"]; } else { $newtp = $userrow["currenttp"]; } //upload stats $updatequery = doquery("UPDATE {{table}} SET $specialchange1 $specialchange2 defensepower='$newdefense', currenthp='$newhp', currentmp='$newmp', currenttp='$newtp' WHERE charname='$usuariologadonome' LIMIT 1", "users"); //fim $updatequery = doquery("UPDATE {{table}} SET shieldid='$banco3id' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET shieldname='$banco3' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid3='$escudoid' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome3='$escudo' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox4 == 1) { //AJEITAR SLOTS global $userrow; $dropquery = doquery("SELECT * FROM {{table}} WHERE id='$banco4id' LIMIT 1", "drops"); $slotquery = doquery("SELECT * FROM {{table}} WHERE id='$idslot1' LIMIT 1", "drops"); $slotrow = mysql_fetch_array($slotquery); $droprow = mysql_fetch_array($dropquery); $variavel = 0; if ($banco4id != 0) { $variavel += 1;} if ($idslot1 != 0) { $variavel += 1; } if ($variavel == 2) { //se tem item nos 2 slots $old1 = explode(",",$slotrow["attribute1"]); if ($slotrow["attribute2"] != "X") { $old2 = explode(",",$slotrow["attribute2"]); } else { $old2 = array(0=>"maxhp",1=>0); } $new1 = explode(",",$droprow["attribute1"]); if ($droprow["attribute2"] != "X") { $new2 = explode(",",$droprow["attribute2"]); } else { $new2 = array(0=>"maxhp",1=>0); } $userrow[$old1[0]] -= $old1[1]; $userrow[$old2[0]] -= $old2[1]; if ($old1[0] == "strength") { $userrow["attackpower"] -= $old1[1]; } if ($old1[0] == "dexterity") { $userrow["defensepower"] -= $old1[1]; } if ($old2[0] == "strength") { $userrow["attackpower"] -= $old2[1]; } if ($old2[0] == "dexterity") { $userrow["defensepower"] -= $old2[1]; } $userrow[$new1[0]] += $new1[1]; $userrow[$new2[0]] += $new2[1]; if ($new1[0] == "strength") { $userrow["attackpower"] += $new1[1]; } if ($new1[0] == "dexterity") { $userrow["defensepower"] += $new1[1]; } if ($new2[0] == "strength") { $userrow["attackpower"] += $new2[1]; } if ($new2[0] == "dexterity") { $userrow["defensepower"] += $new2[1]; } if ($userrow["currenthp"] > $userrow["maxhp"]) { $userrow["currenthp"] = $userrow["maxhp"]; } if ($userrow["currentmp"] > $userrow["maxmp"]) { $userrow["currentmp"] = $userrow["maxmp"]; } if ($userrow["currenttp"] > $userrow["maxtp"]) { $userrow["currenttp"] = $userrow["maxtp"]; } $query = doquery("UPDATE {{table}} SET $old1[0]='".$userrow[$old1[0]]."',$old2[0]='".$userrow[$old2[0]]."',$new1[0]='".$userrow[$new1[0]]."',$new2[0]='".$userrow[$new2[0]]."',attackpower='".$userrow["attackpower"]."',defensepower='".$userrow["defensepower"]."',currenthp='".$userrow["currenthp"]."',currentmp='".$userrow["currentmp"]."',currenttp='".$userrow["currenttp"]."' WHERE charname='$usuariologadonome' LIMIT 1", "users"); } if ($variavel == 1) {//se não tem item no slot $new1 = explode(",",$droprow["attribute1"]); if ($droprow["attribute2"] != "X") { $new2 = explode(",",$droprow["attribute2"]); } else { $new2 = array(0=>"maxhp",1=>0); } $old1 = explode(",",$slotrow["attribute1"]); if ($slotrow["attribute2"] != "X") { $old2 = explode(",",$slotrow["attribute2"]); } else { $old2 = array(0=>"maxhp",1=>0);} $userrow[$new1[0]] += $new1[1]; $userrow[$new2[0]] += $new2[1]; if ($new1[0] == "strength") { $userrow["attackpower"] += $new1[1]; } if ($new1[0] == "dexterity") { $userrow["defensepower"] += $new1[1]; } if ($new2[0] == "strength") { $userrow["attackpower"] += $new2[1]; } if ($new2[0] == "dexterity") { $userrow["defensepower"] += $new2[1]; } $userrow[$old1[0]] -= $old1[1]; $userrow[$old2[0]] -= $old2[1]; if ($old1[0] == "strength") { $userrow["attackpower"] -= $old1[1]; } if ($old1[0] == "dexterity") { $userrow["defensepower"] -= $old1[1]; } if ($old2[0] == "strength") { $userrow["attackpower"] -= $old2[1]; } if ($old2[0] == "dexterity") { $userrow["defensepower"] -= $old2[1]; } if($banco4id != 0) { $query = doquery("UPDATE {{table}} SET $new1[0]='".$userrow[$new1[0]]."',$new2[0]='".$userrow[$new2[0]]."',attackpower='".$userrow["attackpower"]."',defensepower='".$userrow["defensepower"]."' WHERE charname='$usuariologadonome' LIMIT 1", "users");} if($idslot1 != 0) { $query = doquery("UPDATE {{table}} SET $old1[0]='".$userrow[$old1[0]]."',$old2[0]='".$userrow[$old2[0]]."',attackpower='".$userrow["attackpower"]."',defensepower='".$userrow["defensepower"]."' WHERE charname='$usuariologadonome' LIMIT 1", "users");} } //termina aqui $updatequery = doquery("UPDATE {{table}} SET slot1id='$banco4id' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot1name='$banco4' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid4='$idslot1' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome4='$nomeslot1' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox4 == 3) { $updatequery = doquery("UPDATE {{table}} SET slot1id='$idslot2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot1name='$nomeslot2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot2id='$idslot1' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot2name='$nomeslot1' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox4 == 4) { $updatequery = doquery("UPDATE {{table}} SET slot1id='$idslot3' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot1name='$nomeslot3' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot3id='$idslot1' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot3name='$nomeslot1' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox5 == 3) { $updatequery = doquery("UPDATE {{table}} SET slot2id='$idslot1' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot2name='$nomeslot1' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot1id='$idslot2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot1name='$nomeslot2' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox5 == 4) { $updatequery = doquery("UPDATE {{table}} SET slot2id='$idslot3' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot2name='$nomeslot3' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot3id='$idslot2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot3name='$nomeslot2' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox6 == 3) { $updatequery = doquery("UPDATE {{table}} SET slot3id='$idslot1' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot3name='$nomeslot1' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot1id='$idslot3' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot1name='$nomeslot3' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox6 == 4) { $updatequery = doquery("UPDATE {{table}} SET slot2id='$idslot3' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot2name='$nomeslot3' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot3id='$idslot2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot3name='$nomeslot2' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox5 == 1) { //AJEITAR SLOTS global $userrow; $dropquery = doquery("SELECT * FROM {{table}} WHERE id='$banco5id' LIMIT 1", "drops"); $slotquery = doquery("SELECT * FROM {{table}} WHERE id='$idslot2' LIMIT 1", "drops"); $slotrow = mysql_fetch_array($slotquery); $droprow = mysql_fetch_array($dropquery); $variavel = 0; if ($banco5id != 0) { $variavel += 1;} if ($idslot2 != 0) { $variavel += 1; } if ($variavel == 2) { //se tem item nos 2 slots $old1 = explode(",",$slotrow["attribute1"]); if ($slotrow["attribute2"] != "X") { $old2 = explode(",",$slotrow["attribute2"]); } else { $old2 = array(0=>"maxhp",1=>0); } $new1 = explode(",",$droprow["attribute1"]); if ($droprow["attribute2"] != "X") { $new2 = explode(",",$droprow["attribute2"]); } else { $new2 = array(0=>"maxhp",1=>0); } $userrow[$old1[0]] -= $old1[1]; $userrow[$old2[0]] -= $old2[1]; if ($old1[0] == "strength") { $userrow["attackpower"] -= $old1[1]; } if ($old1[0] == "dexterity") { $userrow["defensepower"] -= $old1[1]; } if ($old2[0] == "strength") { $userrow["attackpower"] -= $old2[1]; } if ($old2[0] == "dexterity") { $userrow["defensepower"] -= $old2[1]; } $userrow[$new1[0]] += $new1[1]; $userrow[$new2[0]] += $new2[1]; if ($new1[0] == "strength") { $userrow["attackpower"] += $new1[1]; } if ($new1[0] == "dexterity") { $userrow["defensepower"] += $new1[1]; } if ($new2[0] == "strength") { $userrow["attackpower"] += $new2[1]; } if ($new2[0] == "dexterity") { $userrow["defensepower"] += $new2[1]; } if ($userrow["currenthp"] > $userrow["maxhp"]) { $userrow["currenthp"] = $userrow["maxhp"]; } if ($userrow["currentmp"] > $userrow["maxmp"]) { $userrow["currentmp"] = $userrow["maxmp"]; } if ($userrow["currenttp"] > $userrow["maxtp"]) { $userrow["currenttp"] = $userrow["maxtp"]; } $query = doquery("UPDATE {{table}} SET $old1[0]='".$userrow[$old1[0]]."',$old2[0]='".$userrow[$old2[0]]."',$new1[0]='".$userrow[$new1[0]]."',$new2[0]='".$userrow[$new2[0]]."',attackpower='".$userrow["attackpower"]."',defensepower='".$userrow["defensepower"]."',currenthp='".$userrow["currenthp"]."',currentmp='".$userrow["currentmp"]."',currenttp='".$userrow["currenttp"]."' WHERE charname='$usuariologadonome' LIMIT 1", "users"); } if ($variavel == 1) {//se não tem item no slot $new1 = explode(",",$droprow["attribute1"]); if ($droprow["attribute2"] != "X") { $new2 = explode(",",$droprow["attribute2"]); } else { $new2 = array(0=>"maxhp",1=>0); } $old1 = explode(",",$slotrow["attribute1"]); if ($slotrow["attribute2"] != "X") { $old2 = explode(",",$slotrow["attribute2"]); } else { $old2 = array(0=>"maxhp",1=>0);} $userrow[$new1[0]] += $new1[1]; $userrow[$new2[0]] += $new2[1]; if ($new1[0] == "strength") { $userrow["attackpower"] += $new1[1]; } if ($new1[0] == "dexterity") { $userrow["defensepower"] += $new1[1]; } if ($new2[0] == "strength") { $userrow["attackpower"] += $new2[1]; } if ($new2[0] == "dexterity") { $userrow["defensepower"] += $new2[1]; } $userrow[$old1[0]] -= $old1[1]; $userrow[$old2[0]] -= $old2[1]; if ($old1[0] == "strength") { $userrow["attackpower"] -= $old1[1]; } if ($old1[0] == "dexterity") { $userrow["defensepower"] -= $old1[1]; } if ($old2[0] == "strength") { $userrow["attackpower"] -= $old2[1]; } if ($old2[0] == "dexterity") { $userrow["defensepower"] -= $old2[1]; } if($banco5id != 0) { $query = doquery("UPDATE {{table}} SET $new1[0]='".$userrow[$new1[0]]."',$new2[0]='".$userrow[$new2[0]]."',attackpower='".$userrow["attackpower"]."',defensepower='".$userrow["defensepower"]."' WHERE charname='$usuariologadonome' LIMIT 1", "users");} if($idslot2 != 0) { $query = doquery("UPDATE {{table}} SET $old1[0]='".$userrow[$old1[0]]."',$old2[0]='".$userrow[$old2[0]]."',attackpower='".$userrow["attackpower"]."',defensepower='".$userrow["defensepower"]."' WHERE charname='$usuariologadonome' LIMIT 1", "users");} } //termina aqui $updatequery = doquery("UPDATE {{table}} SET slot2id='$banco5id' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot2name='$banco5' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid5='$idslot2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome5='$nomeslot2' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox6 == 1) { //AJEITAR SLOTS global $userrow; $dropquery = doquery("SELECT * FROM {{table}} WHERE id='$banco6id' LIMIT 1", "drops"); $slotquery = doquery("SELECT * FROM {{table}} WHERE id='$idslot3' LIMIT 1", "drops"); $slotrow = mysql_fetch_array($slotquery); $droprow = mysql_fetch_array($dropquery); $variavel = 0; if ($banco6id != 0) { $variavel += 1;} if ($idslot3 != 0) { $variavel += 1; } if ($variavel == 2) { //se tem item nos 2 slots $old1 = explode(",",$slotrow["attribute1"]); if ($slotrow["attribute2"] != "X") { $old2 = explode(",",$slotrow["attribute2"]); } else { $old2 = array(0=>"maxhp",1=>0); } $new1 = explode(",",$droprow["attribute1"]); if ($droprow["attribute2"] != "X") { $new2 = explode(",",$droprow["attribute2"]); } else { $new2 = array(0=>"maxhp",1=>0); } $userrow[$old1[0]] -= $old1[1]; $userrow[$old2[0]] -= $old2[1]; if ($old1[0] == "strength") { $userrow["attackpower"] -= $old1[1]; } if ($old1[0] == "dexterity") { $userrow["defensepower"] -= $old1[1]; } if ($old2[0] == "strength") { $userrow["attackpower"] -= $old2[1]; } if ($old2[0] == "dexterity") { $userrow["defensepower"] -= $old2[1]; } $userrow[$new1[0]] += $new1[1]; $userrow[$new2[0]] += $new2[1]; if ($new1[0] == "strength") { $userrow["attackpower"] += $new1[1]; } if ($new1[0] == "dexterity") { $userrow["defensepower"] += $new1[1]; } if ($new2[0] == "strength") { $userrow["attackpower"] += $new2[1]; } if ($new2[0] == "dexterity") { $userrow["defensepower"] += $new2[1]; } if ($userrow["currenthp"] > $userrow["maxhp"]) { $userrow["currenthp"] = $userrow["maxhp"]; } if ($userrow["currentmp"] > $userrow["maxmp"]) { $userrow["currentmp"] = $userrow["maxmp"]; } if ($userrow["currenttp"] > $userrow["maxtp"]) { $userrow["currenttp"] = $userrow["maxtp"]; } $query = doquery("UPDATE {{table}} SET $old1[0]='".$userrow[$old1[0]]."',$old2[0]='".$userrow[$old2[0]]."',$new1[0]='".$userrow[$new1[0]]."',$new2[0]='".$userrow[$new2[0]]."',attackpower='".$userrow["attackpower"]."',defensepower='".$userrow["defensepower"]."',currenthp='".$userrow["currenthp"]."',currentmp='".$userrow["currentmp"]."',currenttp='".$userrow["currenttp"]."' WHERE charname='$usuariologadonome' LIMIT 1", "users"); } if ($variavel == 1) {//se não tem item no slot $new1 = explode(",",$droprow["attribute1"]); if ($droprow["attribute2"] != "X") { $new2 = explode(",",$droprow["attribute2"]); } else { $new2 = array(0=>"maxhp",1=>0); } $old1 = explode(",",$slotrow["attribute1"]); if ($slotrow["attribute2"] != "X") { $old2 = explode(",",$slotrow["attribute2"]); } else { $old2 = array(0=>"maxhp",1=>0);} $userrow[$new1[0]] += $new1[1]; $userrow[$new2[0]] += $new2[1]; if ($new1[0] == "strength") { $userrow["attackpower"] += $new1[1]; } if ($new1[0] == "dexterity") { $userrow["defensepower"] += $new1[1]; } if ($new2[0] == "strength") { $userrow["attackpower"] += $new2[1]; } if ($new2[0] == "dexterity") { $userrow["defensepower"] += $new2[1]; } $userrow[$old1[0]] -= $old1[1]; $userrow[$old2[0]] -= $old2[1]; if ($old1[0] == "strength") { $userrow["attackpower"] -= $old1[1]; } if ($old1[0] == "dexterity") { $userrow["defensepower"] -= $old1[1]; } if ($old2[0] == "strength") { $userrow["attackpower"] -= $old2[1]; } if ($old2[0] == "dexterity") { $userrow["defensepower"] -= $old2[1]; } if($banco6id != 0) { $query = doquery("UPDATE {{table}} SET $new1[0]='".$userrow[$new1[0]]."',$new2[0]='".$userrow[$new2[0]]."',attackpower='".$userrow["attackpower"]."',defensepower='".$userrow["defensepower"]."' WHERE charname='$usuariologadonome' LIMIT 1", "users");} if($idslot3 != 0) { $query = doquery("UPDATE {{table}} SET $old1[0]='".$userrow[$old1[0]]."',$old2[0]='".$userrow[$old2[0]]."',attackpower='".$userrow["attackpower"]."',defensepower='".$userrow["defensepower"]."' WHERE charname='$usuariologadonome' LIMIT 1", "users");} } //termina aqui $updatequery = doquery("UPDATE {{table}} SET slot3id='$banco6id' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET slot3name='$banco6' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid6='$idslot3' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome6='$nomeslot3' WHERE charname='$usuariologadonome' LIMIT 1","users"); } /*DELETAR ARMA DO BANCO */ if ($Combobox1 == 2) { $updatequery = doquery("UPDATE {{table}} SET bancoid1='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome1='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox2 == 2) { $updatequery = doquery("UPDATE {{table}} SET bancoid2='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome2='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox3 == 2) { $updatequery = doquery("UPDATE {{table}} SET bancoid3='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome3='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox4 == 2) { $updatequery = doquery("UPDATE {{table}} SET bancoid4='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome4='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox5 == 2) { $updatequery = doquery("UPDATE {{table}} SET bancoid5='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome5='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox6 == 2) { $updatequery = doquery("UPDATE {{table}} SET bancoid6='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome6='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); } /* BANCO DE ARMAZENAMENTO */ if ($Combobox1 == 5) { $updatequery = doquery("UPDATE {{table}} SET bancoid1='$b2banco1id' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome1='$b2banco1' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET b2_bancoid1='$banco1id' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET b2_banconome1='$banco1' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox2 == 5) { $updatequery = doquery("UPDATE {{table}} SET bancoid2='$b2banco2id' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome2='$b2banco2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET b2_bancoid2='$banco2id' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET b2_banconome2='$banco2' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox3 == 5) { $updatequery = doquery("UPDATE {{table}} SET bancoid3='$b2banco3id' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome3='$b2banco3' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET b2_bancoid3='$banco3id' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET b2_banconome3='$banco3' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox4 == 5) { $updatequery = doquery("UPDATE {{table}} SET bancoid4='$b2banco4id' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome4='$b2banco4' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET b2_bancoid4='$banco4id' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET b2_banconome4='$banco4' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox5 == 5) { $updatequery = doquery("UPDATE {{table}} SET bancoid5='$b2banco5id' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome5='$b2banco5' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET b2_bancoid5='$banco5id' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET b2_banconome5='$banco5' WHERE charname='$usuariologadonome' LIMIT 1","users"); } if ($Combobox6 == 5) { $updatequery = doquery("UPDATE {{table}} SET bancoid6='$b2banco6id' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome6='$b2banco6' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET b2_bancoid6='$banco6id' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET b2_banconome6='$banco6' WHERE charname='$usuariologadonome' LIMIT 1","users"); } $usuriologadodinheiro = $usuriologadodinheiro - 0; $updatequery = doquery("UPDATE {{table}} SET gold='$usuriologadodinheiro' WHERE charname='$usuariologadonome' LIMIT 1","users"); display("O processo bancário foi completado com sucesso.<br /><br />Você pode <a href=\"index.php\">clicar aqui</a> para continuar jogando ou <a href=\"users.php?do=banco\">voltar ao banco</a>.","Banco",false,false,false); die(); } $page = "<table width=\"100%\"><tr><td width=\"100%\" align=\"center\"><center><img src=\"images/banco.gif\" /></center></td></tr></table> <b>Seu Ryou</b>: $usuriologadodinheiro / <b>Ryou no Banco</b>: $ryoudepositado<br><br><table border=0 cellspacing=0 cellpadding=0><tr><td> <b><font color=brown>Equipado:</font></b><br> <b>Arma</b>: $arma<br><b>Colete</b>: $armadura<br><b>Bandana</b>: $escudo<br><b>Slot 1</b>: $nomeslot1<br><b>Slot 2</b>: $nomeslot2<br><b>Slot 3</b>: $nomeslot3<br><br> </td><td width=20></td><td> <b><font color=brown>Banco de Trocas:</font></b><br> <b>Arma</b>: $banco1<br><b>Colete</b>: $banco2<br><b>Bandana</b>: $banco3<br><b>Slot 1</b>: $banco4<br><b>Slot 2</b>: $banco5<br><b>Slot 3</b>: $banco6<br><br><td width=20></td> <td> <b><font color=brown>Banco de Armazenamento:</font></b><br> <b>Arma</b>: $b2banco1<br><b>Colete</b>: $b2banco2<br><b>Bandana</b>: $b2banco3<br><b>Slot 1</b>: $b2banco4<br><b>Slot 2</b>: $b2banco5<br><b>Slot 3</b>: $b2banco6<br><br></td> </td> </tr></table>" .gettemplate("banco"); $topnav = "<a href=\"index.php\"><img src=\"images/jogar.gif\" alt=\"Voltar a Jogar\" border=\"0\" /></a><a href=\"help.php\"><img src=\"images/button_help.gif\" alt=\"Ajuda\" border=\"0\" /></a>"; display($page, "Banco", false, false, false); } function doaritem() { global $topvar; $topvar = true; /* testando se está logado */ //include('cookies.php'); //$userrow = checkcookies(); global $userrow; if ($userrow == false) { display("Por favor faça o <a href=\"login.php?do=login\">log in</a> no jogo antes de executar essa ação.","Erro",false,false,false);die(); } if ($userrow["currentaction"] == "Fighting") {header('Location: ./index.php?do=fight&conteudo=Você não pode acessar essa função no meio de uma batalha!');die(); } if ($userrow["level"] < 5) {display("Você não pode acessar essa função se seu level for menor que 5!","Erro",false,false,false);die(); } $usuariologadoid = $userrow["id"]; $usuariologadonome = $userrow["charname"]; $usuriologadodinheiro = $userrow["gold"]; $banco1 = $userrow["banconome1"]; $banco2 = $userrow["banconome2"]; $banco3 = $userrow["banconome3"]; $banco4 = $userrow["banconome4"]; $banco5 = $userrow["banconome5"]; $banco6 = $userrow["banconome6"]; $banco1id = $userrow["bancoid1"]; $banco2id = $userrow["bancoid2"]; $banco3id = $userrow["bancoid3"]; $banco4id = $userrow["bancoid4"]; $banco5id = $userrow["bancoid5"]; $banco6id = $userrow["bancoid6"]; /*fim do teste */ /* OLDPASS É A QUANTIDADE DE DINHEIRO DOADO */ if (isset($_POST["submit"])) { extract($_POST); $userquery = doquery("SELECT * FROM {{table}} WHERE charname='$username' LIMIT 1","users"); if (mysql_num_rows($userquery) != 1) { display("Não existe nenhuma conta com esse Nome.","Erro",false,false,false);die(); } $userrow = mysql_fetch_array($userquery); if ($usuariologadoid == $userrow["id"]) { display("Você não pode doar Item para si mesmo.","Erro",false,false,false);die();} /*if ($userrow["password"] != md5($oldpass)) { die("The old password you provided was incorrect."); } /*$realnewpass = md5($newpass1); */ if ($usuriologadodinheiro < 40) { display("Você não pode doar um Item com menos de 40 Ryou.","Erro",false,false,false);die();} if ($Combobox1 == 1) { if ($userrow["bancoid1"] != 0) { display("O jogador o qual você quer doar o Item, já possui uma Arma no Banco de Trocas.","Erro",false,false,false);die();} else{ $updatequery = doquery("UPDATE {{table}} SET bancoid1='$banco1id' WHERE charname='$username' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome1='$banco1' WHERE charname='$username' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid1='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome1='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); } } if ($Combobox1 == 2) { if ($userrow["bancoid2"] != 0) { display("O jogador o qual você quer doar o Item, já possui um Colete no Banco de Trocas.","Erro",false,false,false);die();} else{ $updatequery = doquery("UPDATE {{table}} SET bancoid2='$banco2id' WHERE charname'$username' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome2='$banco2' WHERE charname='$username' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid2='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome2='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); } } if ($Combobox1 == 3) { if ($userrow["bancoid3"] != 0) { display("O jogador o qual você quer doar o Item, já possui uma Bandana no Banco de Trocas.","Erro",false,false,false);die();} else{ $updatequery = doquery("UPDATE {{table}} SET bancoid3='$banco3id' WHERE charname='$username' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome3='$banco3' WHERE charname='$username' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid3='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome3='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); } } if ($Combobox1 == 4) { if ($userrow["bancoid4"] != 0) { display("O jogador o qual você quer doar o Item, já possui um Item no Slot 1 no Banco de Trocas.","Erro",false,false,false);die();} else{ $updatequery = doquery("UPDATE {{table}} SET bancoid4='$banco4id' WHERE charname='$username' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome4='$banco4' WHERE charname='$username' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid4='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome4='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); } } if ($Combobox1 == 5) { if ($userrow["bancoid5"] != 0) { display("O jogador o qual você quer doar o Item, já possui um Item no Slot 2 no Banco de Trocas.","Erro",false,false,false);die();} else{ $updatequery = doquery("UPDATE {{table}} SET bancoid5='$banco5id' WHERE charname='$username' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome5='$banco5' WHERE charname='$username' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid5='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome5='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); } } if ($Combobox1 == 6) { if ($userrow["bancoid6"] != 0) { display("O jogador o qual você quer doar o Item, já possui um Item no Slot 3 no Banco de Trocas.","Erro",false,false,false);die();} else{ $updatequery = doquery("UPDATE {{table}} SET bancoid6='$banco6id' WHERE charname='$username' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome6='$banco6' WHERE charname='$username' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid6='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome6='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); } } if ($Combobox1 == 0) {display("Primeiro selecione uma ação.","Erro",false,false,false);die();} $usuriologadodinheiro = $usuriologadodinheiro - 40; $updatequery = doquery("UPDATE {{table}} SET gold='$usuriologadodinheiro' WHERE charname='$usuariologadonome' LIMIT 1","users"); display("O Item foi retirado da sua conta e doado com sucesso. Foram retirados da sua conta, 40 Ryou.<br /><br />Você pode <a href=\"index.php\">clicar aqui</a> para continuar jogando ou <a href=\"users.php?do=doaritem\">doar mais Item</a>.","Doar Item",false,false,false); die(); } $page = "<table width=\"100%\"><tr><td width=\"100%\" align=\"center\"><center><img src=\"images/doaritem.gif\" /></center></td></tr></table> <b>Seu Ryou</b>: $usuriologadodinheiro<br><br><b><font color=brown>Seu Banco de Trocas:</font></b><br><b>Arma</b>: $banco1<br><b>Colete</b>: $banco2<br><b>Bandana</b>: $banco3<br><b>Slot 1</b>: $banco4<br><b>Slot2</b>: $banco5<br><b>Slot3</b>: $banco6<br><br>".gettemplate("doaritem"); $topnav = "<a href=\"index.php\"><img src=\"images/jogar.gif\" alt=\"Voltar a Jogar\" border=\"0\" /></a><a href=\"help.php\"><img src=\"images/button_help.gif\" alt=\"Ajuda\" border=\"0\" /></a>"; display($page, "Doar Item", false, false, false); } function troca1() { global $topvar; $topvar = true; /* testando se está logado */ //include('cookies.php'); //$userrow = checkcookies(); global $userrow; if ($userrow == false) { display("Por favor faça o <a href=\"login.php?do=login\">log in</a> no jogo antes de executar essa ação.","Erro",false,false,false);die(); } if ($userrow["currentaction"] == "Fighting") {header('Location: ./index.php?do=fight&conteudo=Você não pode acessar essa função no meio de uma batalha!');die(); } $usuariologadoid = $userrow["id"]; $usuariologadonome = $userrow["charname"]; $usuriologadodinaheiro = $userrow["gold"]; /*fim do teste */ /* BANCO DE TROCAS */ $banco1 = $userrow["banconome1"]; $banco2 = $userrow["banconome2"]; $banco3 = $userrow["banconome3"]; $banco4 = $userrow["banconome4"]; $banco5 = $userrow["banconome5"]; $banco6 = $userrow["banconome6"]; $banco1id = $userrow["bancoid1"]; $banco2id = $userrow["bancoid2"]; $banco3id = $userrow["bancoid3"]; $banco4id = $userrow["bancoid4"]; $banco5id = $userrow["bancoid5"]; $banco6id = $userrow["bancoid6"]; /* OLDPASS É A QUANTIDADE DE DINHEIRO DOADO */ if (isset($_POST["submit"])) { extract($_POST); $userquery = doquery("SELECT * FROM {{table}} WHERE charname='$username' LIMIT 1","users"); if (mysql_num_rows($userquery) != 1) { display("Não existe nenhuma conta com esse Nome.","Erro",false,false,false);die(); } $userrow = mysql_fetch_array($userquery); //testando se os dois jogadores estão no mesmo mapa $monsterquery = doquery("SELECT * FROM {{table}} WHERE charname='$username' LIMIT 1", "users"); $jogador2row = mysql_fetch_array($monsterquery); if ($userrow["longitude"] != $jogador2row["longitude"]) {display("Você só pode trocar com um jogador que está no mesmo mapa que o seu! Clique <a href=\"index.php\">aqui</a> para voltar ao jogo.","Erro",false,false,false);die(); } if ($userrow["latitude"] != $jogador2row["latitude"]) {display("Você só pode trocar com um jogador que está no mesmo mapa que o seu! Clique <a href=\"index.php\">aqui</a> para voltar ao jogo.","Erro",false,false,false);die(); } //acaba aqui if ($Combobox1 == 0) { display("Primeiro selecione um Item.","Erro",false,false,false);die(); } $updatequery = doquery("UPDATE {{table}} SET trocanomeitem='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocaiditem='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocanomejogador='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocanumero='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocaposicaoitem='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); //colocando a posição do item, qual item é. $updatequery = doquery("UPDATE {{table}} SET trocaposicaoitem='$Combobox1' WHERE charname='$usuariologadonome' LIMIT 1","users"); if ($Combobox1 == 1) {$nomeitempronto = $banco1; $iditempronto = $banco1id;} if ($Combobox1 == 2) {$nomeitempronto = $banco2;$iditempronto = $banco2id;} if ($Combobox1 == 3) {$nomeitempronto = $banco3;$iditempronto = $banco3id;} if ($Combobox1 == 4) {$nomeitempronto = $banco4;$iditempronto = $banco4id;} if ($Combobox1 == 5) {$nomeitempronto = $banco5;$iditempronto = $banco5id;} if ($Combobox1 == 6) {$nomeitempronto = $banco6;$iditempronto = $banco6id;} //confere se o item se a casa do jogador a ser doado está vazia $nomedoslot = bancoid.$Combobox1; if ($userrow["$nomedoslot"] != 0) { display("O Jogador o qual você realizar a troca, já possui um Item no Banco de Trocas referente ao item que você quer trocar.","Erro",false,false,false);die(); } $updatequery = doquery("UPDATE {{table}} SET trocanomeitem='$nomeitempronto' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocaiditem='$iditempronto' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocanomejogador='$username' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocanumero='1' WHERE charname='$username' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocanomejogador='$usuariologadonome' WHERE charname='$username' LIMIT 1","users"); display("A primeira etapa da troca foi realizada. Envie esse link: <font color=red>http://nigeru.com/narutorpg/users.php?do=troca2</font> para o Jogador o qual você deseja realizar a Troca.<br /><br />Você pode <a href=\"index.php\">clicar aqui</a> para continuar jogando, caso não queira mais realizar uma troca, ou ainda <a href=\"users.php?do=troca1\">iniciar uma nova Troca</a>.","Realizar Troca",false,false,false); die(); } $page = " <table width=\"100%\"><tr><td width=\"100%\" align=\"center\"><center><img src=\"images/troca.gif\" /></center></td></tr></table> <b>Seu Ryou</b>: $usuriologadodinaheiro<br><br> <b><font color=brown>Seu Banco de Trocas:</font></b><br> <b>Arma</b>: $banco1<br><b>Colete</b>: $banco2<br><b>Bandana</b>: $banco3<br><b>Slot 1</b>: $banco4<br><b>Slot 2</b>: $banco5<br><b>Slot 3</b>: $banco6<br><br> ".gettemplate("troca1"); $topnav = "<a href=\"index.php\"><img src=\"images/jogar.gif\" alt=\"Voltar a Jogar\" border=\"0\" /></a><a href=\"help.php\"><img src=\"images/button_help.gif\" alt=\"Ajuda\" border=\"0\" /></a>"; display($page, "Realizar Troca", false, false, false); } function troca2() { global $topvar; $topvar = true; /* testando se está logado */ //include('cookies.php'); //$userrow = checkcookies(); global $userrow; if ($userrow == false) { display("Por favor faça o <a href=\"login.php?do=login\">log in</a> no jogo antes de executar essa ação.","Erro",false,false,false);die(); } if ($userrow["currentaction"] == "Fighting") {header('Location: ./index.php?do=fight&conteudo=Você não pode acessar essa função no meio de uma batalha!');die(); } $usuariologadoid = $userrow["id"]; $usuariologadonome = $userrow["charname"]; $usuriologadodinheiro = $userrow["gold"]; /*fim do teste */ /* BANCO DE TROCAS */ $banco1 = $userrow["banconome1"]; $banco2 = $userrow["banconome2"]; $banco3 = $userrow["banconome3"]; $banco4 = $userrow["banconome4"]; $banco5 = $userrow["banconome5"]; $banco6 = $userrow["banconome6"]; $banco1id = $userrow["bancoid1"]; $banco2id = $userrow["bancoid2"]; $banco3id = $userrow["bancoid3"]; $banco4id = $userrow["bancoid4"]; $banco5id = $userrow["bancoid5"]; $banco6id = $userrow["bancoid6"]; $numerodatroca = $userrow["trocanumero"]; $username = $userrow["trocanomejogador"]; if ($numerodatroca != 1) { display("Respeite a ordem da troca, envie esse link para o outro jogador.","Erro",false,false,false);die(); } /* OLDPASS É A QUANTIDADE DE DINHEIRO DOADO */ if (isset($_POST["submit"])) { extract($_POST); $userquery = doquery("SELECT * FROM {{table}} WHERE charname='$username' LIMIT 1","users"); if (mysql_num_rows($userquery) != 1) { display("Não existe nenhuma conta com esse Nome.","Erro",false,false,false);die(); } $userrow = mysql_fetch_array($userquery); if (!is_numeric($oldpass)) { display("A quantidade de Ryou deve ser um número.","Erro",false,false,false);die(); } $oldpass = floor($oldpass); //testando se os dois jogadores estão no mesmo mapa $monsterquery = doquery("SELECT * FROM {{table}} WHERE charname='$username' LIMIT 1", "users"); $jogador2row = mysql_fetch_array($monsterquery); if ($userrow["longitude"] != $jogador2row["longitude"]) {display("Você só pode trocar com um jogador que está no mesmo mapa que o seu! Clique <a href=\"index.php\">aqui</a> para voltar ao jogo.","Erro",false,false,false);die(); } if ($userrow["latitude"] != $jogador2row["latitude"]) {display("Você só pode trocar com um jogador que está no mesmo mapa que o seu! Clique <a href=\"index.php\">aqui</a> para voltar ao jogo.","Erro",false,false,false);die(); } //acaba aqui if ($oldpass > $usuriologadodinheiro) {display("Você não pode trocar mais Ryou que a sua quantidade.","Erro",false,false,false); die(); } if ($oldpass < 1) {display("Você não pode trocar menos que 1 Ryou.","Erro",false,false,false); die(); } if ($oldpass > 999999999) {display("Você não pode utilizar um número com 10 algarismos.","Erro",false,false,false); die(); } $nomedoitemprontop = $oldpass." Ryou"; $updatequery = doquery("UPDATE {{table}} SET trocanomeitem='$nomedoitemprontop' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocaiditem='$oldpass' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocanomejogador='$username' WHERE charname='$usuariologadonome' LIMIT 1","users"); //número da troca $updatequery = doquery("UPDATE {{table}} SET trocanumero='2' WHERE charname='$username' LIMIT 1","users"); display("A segunda etapa da troca foi realizada. Envie esse link: <font color=red>http://nigeru.com/narutorpg/users.php?do=troca3</font> para o Jogador o qual você deseja realizar a Troca.<br /><br />Você pode <a href=\"index.php\">clicar aqui</a> para continuar jogando, caso não queira mais realizar uma troca, ou ainda <a href=\"users.php?do=troca1\">iniciar uma nova Troca</a>.","Realizar Troca",false,false,false); die(); } $page = "<table width=\"100%\"><tr><td width=\"100%\" align=\"center\"><center><img src=\"images/troca.gif\" /></center></td></tr></table> <b>Seu Ryou</b>: $usuriologadodinheiro<br><br><b>Trocar com</b>: $username<br><br>".gettemplate("troca2"); $topnav = "<a href=\"index.php\"><img src=\"images/jogar.gif\" alt=\"Voltar a Jogar\" border=\"0\" /></a><a href=\"help.php\"><img src=\"images/button_help.gif\" alt=\"Ajuda\" border=\"0\" /></a>"; display($page, "Realizar Troca", false, false, false); } function troca3() { global $topvar; $topvar = true; /* testando se está logado */ //include('cookies.php'); //$userrow = checkcookies(); global $userrow; if ($userrow == false) { display("Por favor faça o <a href=\"login.php?do=login\">log in</a> no jogo antes de executar essa ação.","Erro",false,false,false);die(); } if ($userrow["currentaction"] == "Fighting") {header('Location: ./index.php?do=fight&conteudo=Você não pode acessar essa função no meio de uma batalha!');die(); } $usuariologadoid = $userrow["id"]; $usuariologadonome = $userrow["charname"]; $usuriologadodinheiro = $userrow["gold"]; /*fim do teste */ /* BANCO DE TROCAS */ $banco1 = $userrow["banconome1"]; $banco2 = $userrow["banconome2"]; $banco3 = $userrow["banconome3"]; $banco4 = $userrow["banconome4"]; $banco5 = $userrow["banconome5"]; $banco6 = $userrow["banconome6"]; $banco1id = $userrow["bancoid1"]; $banco2id = $userrow["bancoid2"]; $banco3id = $userrow["bancoid3"]; $banco4id = $userrow["bancoid4"]; $banco5id = $userrow["bancoid5"]; $banco6id = $userrow["bancoid6"]; $trocanomeitemjogador = $userrow["trocanomeitem"]; $nomedojogadordatroca = $userrow["trocanomejogador"]; $numerodatrocadurante = $userrow["trocanumero"]; $userquery = doquery("SELECT * FROM {{table}} WHERE charname='$nomedojogadordatroca' LIMIT 1","users"); if (mysql_num_rows($userquery) != 1) { display("Não existe nenhuma conta com o nome do Jogador.","Erro",false,false,false);die(); } $userrow = mysql_fetch_array($userquery); $itemdetrocajogador2 = $userrow["trocanomeitem"]; $nomedojogadordatroca2 = $userrow["trocanomejogador"]; if ($nomedojogadordatroca2 != $usuariologadonome) {$fim = true;} if ($fim){ display("Você não pode comandar uma Troca que não é pra você. <a href=\"users.php?do=troca1\">Clique aqui</a> para realizar uma nova troca.","Erro",false,false,false);die(); } if ($numerodatrocadurante != 2) { display("Respeite a ordem da troca, envie esse link para o outro jogador.","Erro",false,false,false);die(); } //testando se os dois jogadores estão no mesmo mapa $monsterquery = doquery("SELECT * FROM {{table}} WHERE charname='$nomedojogadordatroca2' LIMIT 1", "users"); $jogador2row = mysql_fetch_array($monsterquery); if ($userrow["longitude"] != $jogador2row["longitude"]) {display("Você só pode trocar com um jogador que está no mesmo mapa que o seu! Clique <a href=\"index.php\">aqui</a> para voltar ao jogo.","Erro",false,false,false);die(); } if ($userrow["latitude"] != $jogador2row["latitude"]) {display("Você só pode trocar com um jogador que está no mesmo mapa que o seu! Clique <a href=\"index.php\">aqui</a> para voltar ao jogo.","Erro",false,false,false);die(); } //acaba aqui /* OLDPASS É A QUANTIDADE DE DINHEIRO DOADO */ if (isset($_POST["submit"])) { extract($_POST); if ($numerodatrocadurante != 2){ display("Não foi possível realizar uma troca, recomece uma nova troca <a href=\"users.php?do=troca1\">clicando aqui</a>.","Erro",false,false,false);die(); } //número da troca $updatequery = doquery("UPDATE {{table}} SET trocanumero='3' WHERE charname='$nomedojogadordatroca' LIMIT 1","users"); display("A terceira etapa da troca foi realizada. Envie esse link: <font color=red>http://nigeru.com/narutorpg/users.php?do=troca4</font> para o Jogador o qual você deseja realizar a Troca.<br /><br />Você pode <a href=\"index.php\">clicar aqui</a> para continuar jogando, caso não queira mais realizar uma troca, ou ainda <a href=\"users.php?do=troca1\">iniciar uma nova Troca</a>.","Realizar Troca",false,false,false); die(); } $page = "<table width=\"100%\"><tr><td width=\"100%\" align=\"center\"><center><img src=\"images/troca.gif\" /></center></td></tr></table> <b>Troca atual:</b><br>$trocanomeitemjogador por $itemdetrocajogador2.".gettemplate("troca3"); $topnav = "<a href=\"index.php\"><img src=\"images/jogar.gif\" alt=\"Voltar a Jogar\" border=\"0\" /></a><a href=\"help.php\"><img src=\"images/button_help.gif\" alt=\"Ajuda\" border=\"0\" /></a>"; display($page, "Realizar Troca", false, false, false); } function troca4() { global $topvar; $topvar = true; /* testando se está logado */ //include('cookies.php'); // $userrow = checkcookies(); global $userrow; if ($userrow == false) { display("Por favor faça o <a href=\"login.php?do=login\">log in</a> no jogo antes de executar essa ação.","Erro",false,false,false);die(); } if ($userrow["currentaction"] == "Fighting") {header('Location: ./index.php?do=fight&conteudo=Você não pode acessar essa função no meio de uma batalha!');die(); } $usuariologadoid = $userrow["id"]; $usuariologadonome = $userrow["charname"]; $usuriologadodinheiro = $userrow["gold"]; /*fim do teste */ /* BANCO DE TROCAS */ $banco1 = $userrow["banconome1"]; $banco2 = $userrow["banconome2"]; $banco3 = $userrow["banconome3"]; $banco4 = $userrow["banconome4"]; $banco5 = $userrow["banconome5"]; $banco6 = $userrow["banconome6"]; $banco1id = $userrow["bancoid1"]; $banco2id = $userrow["bancoid2"]; $banco3id = $userrow["bancoid3"]; $banco4id = $userrow["bancoid4"]; $banco5id = $userrow["bancoid5"]; $banco6id = $userrow["bancoid6"]; $trocanomeitemjogador = $userrow["trocanomeitem"]; $nomedojogadordatroca = $userrow["trocanomejogador"]; $iddojogadordatroca = $userrow["trocaiditem"]; $posicaoitem = $userrow["trocaposicaoitem"]; $numerodatrocadurante = $userrow["trocanumero"]; $userquery = doquery("SELECT * FROM {{table}} WHERE charname='$nomedojogadordatroca' LIMIT 1","users"); if (mysql_num_rows($userquery) != 1) { display("Não existe nenhuma conta com o nome do Jogador.","Erro",false,false,false);die(); } $userrow = mysql_fetch_array($userquery); $itemdetrocajogador2 = $userrow["trocanomeitem"]; $nomedojogadordatroca2 = $userrow["trocanomejogador"]; $iddojogadordatroca2 = $userrow["trocaiditem"]; $posicaoitem2 = $userrow["trocaposicaoitem"]; $dinheirodojogador2 = $userrow["gold"]; if ($nomedojogadordatroca2 != $usuariologadonome) {$fim = true;} if ($fim){ display("Você não pode comandar uma Troca que não é pra você. <a href=\"users.php?do=troca1\">Clique aqui</a> para realizar uma nova troca.","Erro",false,false,false);die(); } if ($numerodatrocadurante != 3) { display("Respeite a ordem da troca, envie esse link para o outro jogador.","Erro",false,false,false);die(); } /* OLDPASS É A QUANTIDADE DE DINHEIRO DOADO */ //testando se os dois jogadores estão no mesmo mapa $monsterquery = doquery("SELECT * FROM {{table}} WHERE charname='$nomedojogadordatroca2' LIMIT 1", "users"); $jogador2row = mysql_fetch_array($monsterquery); if ($userrow["longitude"] != $jogador2row["longitude"]) {display("Você só pode trocar com um jogador que está no mesmo mapa que o seu! Clique <a href=\"index.php\">aqui</a> para voltar ao jogo.","Erro",false,false,false);die(); } if ($userrow["latitude"] != $jogador2row["latitude"]) {display("Você só pode trocar com um jogador que está no mesmo mapa que o seu! Clique <a href=\"index.php\">aqui</a> para voltar ao jogo.","Erro",false,false,false);die(); } //acaba aqui if (isset($_POST["submit"])) { extract($_POST); //if ($numerodatrocadurante != 3){ die("Não foi possível realizar uma troca, recomece uma nova troca <a href=\"users.php?do=troca1\">clicando aqui</a>."); } //trocando if ($posicaoitem2 == 1) { $updatequery = doquery("UPDATE {{table}} SET banconome1='$itemdetrocajogador2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid1='$iddojogadordatroca2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome1='None' WHERE charname='$nomedojogadordatroca' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid1='0' WHERE charname='$nomedojogadordatroca' LIMIT 1","users");} if ($posicaoitem2 == 2) { $updatequery = doquery("UPDATE {{table}} SET banconome2='$itemdetrocajogador2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid2='$iddojogadordatroca2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome2='None' WHERE charname='$nomedojogadordatroca' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid2='0' WHERE charname='$nomedojogadordatroca' LIMIT 1","users");} if ($posicaoitem2 == 3) { $updatequery = doquery("UPDATE {{table}} SET banconome3='$itemdetrocajogador2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid3='$iddojogadordatroca2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome3='None' WHERE charname='$nomedojogadordatroca' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid3='0' WHERE charname='$nomedojogadordatroca' LIMIT 1","users");} if ($posicaoitem2 == 4) { $updatequery = doquery("UPDATE {{table}} SET banconome4='$itemdetrocajogador2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid4='$iddojogadordatroca2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome4='None' WHERE charname='$nomedojogadordatroca' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid4='0' WHERE charname='$nomedojogadordatroca' LIMIT 1","users");} if ($posicaoitem2 == 5) { $updatequery = doquery("UPDATE {{table}} SET banconome5='$itemdetrocajogador2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid5='$iddojogadordatroca2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome5='None' WHERE charname='$nomedojogadordatroca' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid5='0' WHERE charname='$nomedojogadordatroca' LIMIT 1","users");} if ($posicaoitem2 == 6) { $updatequery = doquery("UPDATE {{table}} SET banconome6='$itemdetrocajogador2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid6='$iddojogadordatroca2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET banconome6='None' WHERE charname='$nomedojogadordatroca' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET bancoid6='0' WHERE charname='$nomedojogadordatroca' LIMIT 1","users");} //trocandojogador2 $dinheirofinalpronto = $dinheirodojogador2 + $iddojogadordatroca; $dinheirofinalpronto2 = $usuriologadodinheiro - $iddojogadordatroca; $updatequery = doquery("UPDATE {{table}} SET gold='$dinheirofinalpronto' WHERE charname='$nomedojogadordatroca' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET gold='$dinheirofinalpronto2' WHERE charname='$usuariologadonome' LIMIT 1","users"); //resetando os itens da troca $updatequery = doquery("UPDATE {{table}} SET trocanomeitem='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocaiditem='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocanomejogador='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocanumero='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocaposicaoitem='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocanomeitem='None' WHERE charname='$nomedojogadordatroca' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocaiditem='0' WHERE charname='$nomedojogadordatroca' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocanomejogador='None' WHERE charname='$nomedojogadordatroca' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocanumero='0' WHERE charname='$nomedojogadordatroca' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET trocaposicaoitem='0' WHERE charname='$nomedojogadordatroca' LIMIT 1","users"); display("A troca foi realizada com sucesso e seu Item foi enviado para o Banco de Trocas.<br /><br />Você pode <a href=\"index.php\">clicar aqui</a> para continuar jogando, caso não queira mais realizar uma troca, ou ainda <a href=\"users.php?do=troca1\">iniciar uma nova Troca</a>.","Realizar Troca",false,false,false); die(); } $page = "<table width=\"100%\"><tr><td width=\"100%\" align=\"center\"><center><img src=\"images/troca.gif\" /></center></td></tr></table> <b>Troca atual:</b><br>$trocanomeitemjogador por $itemdetrocajogador2.".gettemplate("troca4"); $topnav = "<a href=\"index.php\"><img src=\"images/jogar.gif\" alt=\"Voltar a Jogar\" border=\"0\" /></a><a href=\"help.php\"><img src=\"images/button_help.gif\" alt=\"Ajuda\" border=\"0\" /></a>"; display($page, "Realizar Troca", false, false, false); } function batalha1() { global $topvar; $topvar = true; /* testando se está logado */ //include('cookies.php'); //$userrow = checkcookies(); global $userrow; if ($userrow == false) { display("Por favor faça o <a href=\"login.php?do=login\">log in</a> no jogo antes de executar essa ação.","Erro",false,false,false);die(); } if ($userrow["currentaction"] == "Fighting") {header('Location: ./index.php?do=fight&conteudo=Você não pode acessar essa função no meio de uma batalha!');die(); } $usuariologadoid = $userrow["id"]; $usuariologadonome = $userrow["charname"]; $usuriologadodinheiro = $userrow["gold"]; /*fim do teste */ //dados de batalha $batalhanome = $userrow["batalha_nome"]; $batalhaid = $userrow["batalha_id"]; $batalhahp = $userrow["batalha_hp"]; //fim $hpjogador = $userrow["currenthp"]; $mpjogador = $userrow["currentmp"]; if (isset($_POST["submit"])) { extract($_POST); //DADOS JOGADOR 2 $userquery = doquery("SELECT * FROM {{table}} WHERE charname='$jogador' LIMIT 1","users"); if (mysql_num_rows($userquery) != 1) { display("Não existe nenhuma conta com esse nome.","Erro",false,false,false);die(); } $userrow = mysql_fetch_array($userquery); if ($usuariologadonome == $jogador) { display("Você não pode batalhar com você mesmo.","Erro",false,false,false);die();} $nomedojogador2 = $userrow["charname"]; $batalhanome2 = $userrow["batalha_nome"]; $batalhaid2 = $userrow["batalha_id"]; $batalhahp2 = $userrow["batalha_hp"]; $hpjogador2 = $userrow["currenthp"]; $mpjogador2 = $usarrow["currentmp"]; //testando se os dois jogadores estão no mesmo mapa $monsterquery = doquery("SELECT * FROM {{table}} WHERE charname='$jogador' LIMIT 1", "users"); $jogador2row = mysql_fetch_array($monsterquery); if ($userrow["longitude"] != $jogador2row["longitude"]) {display("Você só pode duelar com um jogador que está no mesmo mapa que o seu! Clique <a href=\"index.php\">aqui</a> para voltar ao jogo.","Erro",false,false,false);die(); } if ($userrow["latitude"] != $jogador2row["latitude"]) {display("Você só pode duelar com um jogador que está no mesmo mapa que o seu! Clique <a href=\"index.php\">aqui</a> para voltar ao jogo.","Erro",false,false,false);die(); } //acaba aqui $updatequery = doquery("UPDATE {{table}} SET currentmonstersleep='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentuberdamage='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentuberdefense='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_nome='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_hp='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentmonsterhp='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentmonsterimmune='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentmonster='' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_timer='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_timer2='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_id='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_acao='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_nome='$jogador' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_hp='$hpjogador' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentmonsterhp='$hpjogador2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentmonsterimmune='$mpjogador2' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_timer='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_timer2='5' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_id='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_id='1' WHERE charname='$jogador' LIMIT 1","users"); display("<table width=\"100%\"><tr><td width=\"100%\" align=\"center\"><center><img src=\"images/duelo.gif\" /></center></td></tr></table>A primeira etapa para começar um duelo foi realizada. Envie esse link: <font color=red>http://nigeru.com/narutorpg/users.php?do=batalha1</font> para o Jogador o qual você deseja realizar o Duelo.<br><br>Se os dois jogadores já preencheram a página, acessem esse link: <font color=red><a href=\"http://nigeru.com/narutorpg/users.php?do=duelo\"> http://nigeru.com/narutorpg/users.php?do=duelo</a></font> ao mesmo tempo.<br /><br />Você pode <a href=\"index.php\">clicar aqui</a> para continuar jogando, caso não queira mais realizar um duelo, ou ainda <a href=\"users.php?do=batalha1\">iniciar um novo Duelo</a>.","Realizar Duelo",false,false,false); die(); } $page = "<table width=\"100%\"><tr><td width=\"100%\" align=\"center\"><center><img src=\"images/duelo.gif\" /></center></td></tr></table>".gettemplate("batalha1"); $topnav = "<a href=\"index.php\"><img src=\"images/jogar.gif\" alt=\"Voltar a Jogar\" border=\"0\" /></a><a href=\"help.php\"><img src=\"images/button_help.gif\" alt=\"Ajuda\" border=\"0\" /></a>"; display($page, "Realizar Duelo", false, false, false); } function resetarduelo() { global $topvar; $topvar = true; /* testando se está logado */ //include('cookies.php'); //$userrow = checkcookies(); global $userrow; if ($userrow == false) { display("Por favor faça o <a href=\"login.php?do=login\">log in</a> no jogo antes de executar essa ação.","Erro",false,false,false);die(); } if ($userrow["currentaction"] == "Fighting") {header('Location: ./index.php?do=fight&conteudo=Você não pode acessar essa função no meio de uma batalha!');die(); } $usuariologadoid = $userrow["id"]; $usuariologadonome = $userrow["charname"]; $usuriologadodinheiro = $userrow["gold"]; /*fim do teste */ //dados de batalha $batalhanome = $userrow["batalha_nome"]; $batalhaid = $userrow["batalha_id"]; $batalhahp = $userrow["batalha_hp"]; //fim $hpjogador = $userrow["currenthp"]; $mpjogador = $userrow["currentmp"]; $updatequery = doquery("UPDATE {{table}} SET currentmonstersleep='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentuberdamage='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentuberdefense='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_nome='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_hp='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentmonsterhp='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentmonsterimmune='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentmonster='' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_timer='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_timer2='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_id='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_acao='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); $page = "<table width=\"100%\"><tr><td width=\"100%\" align=\"center\"><center><img src=\"images/duelo.gif\" /></center></td></tr></table>Seu duelo atual foi resetado com sucesso. Clique <a href=\"index.php\">aqui</a> para voltar ao jogo."; $topnav = "<a href=\"index.php\"><img src=\"images/jogar.gif\" alt=\"Voltar a Jogar\" border=\"0\" /></a><a href=\"help.php\"><img src=\"images/button_help.gif\" alt=\"Ajuda\" border=\"0\" /></a>"; display($page, "Realizar Duelo", false, false, false); } function duelo() { global $topvar; $topvar = true; /* testando se está logado */ //include('cookies.php'); //$userrow = checkcookies(); global $userrow; if ($userrow == false) { display("Por favor faça o <a href=\"login.php?do=login\">log in</a> no jogo antes de executar essa ação.","Erro",false,false,false);die(); } if ($userrow["currentaction"] == "Fighting") {header('Location: ./index.php?do=fight&conteudo=Você não pode acessar essa função no meio de uma batalha!');die(); } $usuariologadoid = $userrow["id"]; $usuariologadonome = $userrow["charname"]; $usuriologadodinheiro = $userrow["gold"]; /*fim do teste */ //dados de batalha $batalhanome = $userrow["batalha_nome"]; $batalhaid = $userrow["batalha_id"]; $batalhahp = $userrow["batalha_hp"]; //fim $hpjogador = $userrow["currenthp"]; $hpdosegundojogador = $userrow["currentmonsterhp"]; $mpjogador = $userrow["currentmp"]; $mpjogador2 = $userrow["currentmonsterimmune"]; //fim $timer = $userrow["batalha_timer"]; $timeraux = $userrow["batalha_timer2"]; $mosternofim = $userrow["batalha_acao"]; if ($mosternofim == $usuariologadonome.": ") {$mosternofim = "Não houve uma ação na rodada passada.";} if ($mosternofim == "None") {$mosternofim = "Não houve uma ação na rodada passada.";} //colocando pra duelar somente no mesmo mapa $monsterquery = doquery("SELECT * FROM {{table}} WHERE charname='$batalhanome' LIMIT 1", "users"); $jogador2row = mysql_fetch_array($monsterquery); if ($userrow["longitude"] != $jogador2row["longitude"]) {display("Você só pode duelar com um jogador que está no mesmo mapa que o seu! Clique <a href=\"index.php\">aqui</a> para voltar ao jogo.","Erro",false,false,false);die(); } if ($userrow["latitude"] != $jogador2row["latitude"]) {display("Você só pode duelar com um jogador que está no mesmo mapa que o seu! Clique <a href=\"index.php\">aqui</a> para voltar ao jogo.","Erro",false,false,false);die(); } /*//fazer o timer 2 $userquery = doquery("SELECT * FROM {{table}} WHERE charname='$batalhanome' LIMIT 1","users"); if (mysql_num_rows($userquery) != 1) { die("Não existe nenhuma conta com esse nome."); } $userrow = mysql_fetch_array($userquery); $timer2 = $userrow["batalha_timer"]; $userquery = doquery("SELECT * FROM {{table}} WHERE charname='$usuariologadonome' LIMIT 1","users"); if (mysql_num_rows($userquery) != 1) { die("Não existe nenhuma conta com esse nome."); } $userrow = mysql_fetch_array($userquery); //fim //if ($batalhaid != 1) {die("Respeite a ordem de Duelo, envie esse link para o outro Jogador."); } if ($timer < 2) {if ($timer2 > 1){ $timer2 = $timer2 - 1; $updatequery = doquery("UPDATE {{table}} SET batalha_timer='$timer2' WHERE charname='$batalhanome' LIMIT 1","users"); die("Aguarde...$timer segundos. Turno do segundo jogador.<meta HTTP-EQUIV='refresh' CONTENT='1;URL=users.php?do=duelo'>"); } else{ $updatequery = doquery("UPDATE {{table}} SET batalha_timer='6' WHERE charname='$usuariologadonome' LIMIT 1","users");} } */ //TIMER ANTIGO FALHO /*$timer -= 5; $updatequery = doquery("UPDATE {{table}} SET batalha_timer='$timer' WHERE charname='$usuariologadonome' LIMIT 1","users"); if ($timer < 1) { if ($timeraux > 5) { $updatequery = doquery("UPDATE {{table}} SET batalha_timer='6' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_timer2='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); } else{ $timeraux += 1; $updatequery = doquery("UPDATE {{table}} SET batalha_timer='6' WHERE charname='$batalhanome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_timer2='$timeraux' WHERE charname='$usuariologadonome' LIMIT 1","users"); die("Aguarde o seu turno novamente.<meta HTTP-EQUIV='refresh' CONTENT='1;URL=users.php?do=duelo'>"); } }*/ //fazer duelo primeiro if($batalhanome == None) { display("Primeiro você deve escolher alguém para Duelar. Clique <a href=\"users.php?do=batalha1\">aqui</a>, para fazer isso.","Realizar Duelo",false,false,false); die(); } //VITORIA E DERROTA. if($hpjogador == 0) { display(" <table width=\"100%\"> <tr><td align=\"center\"><center><img src=\"images/duelo.gif\" alt=\"Duelo\" /></center></td></tr></table> <table><tr><td width=\"310\" valign=\"middle\"><center> <br><br>Ação do último turno:<br>".$mosternofim."<br><br>Você perdeu a batalha!<br>O seu HP é 0!<br><br><b>Vencedor:</b> $batalhanome<br><b>Perdedor:</b> $usuariologadonome </center> </td><td> <table width=\"165\" height=\"175\" background=\"layoutnovo/graficos/fundo.png\" style=\"background-repeat:no-repeat;;background-position:left top\"><tr height=\"50%\"><td></td></tr><tr><td><center><img src=\"layoutnovo/graficos/".$userrow["avatar"]."_morto.gif\"></center> </td></tr><tr height=\"15\"><td></td></tr></table> </td></tr></table> ","Realizar Duelo",false,false,false); $updatequery = doquery("UPDATE {{table}} SET currentmonstersleep='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentuberdamage='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentuberdefense='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_nome='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_hp='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentmonsterhp='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentmonsterimmune='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentmonster='' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_timer='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_acao='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_id='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); die(); } if($hpdosegundojogador == 0){ display(" <table width=\"100%\"> <tr><td align=\"center\"><center><img src=\"images/duelo.gif\" alt=\"Duelo\" /></center></td></tr></table> <table><tr><td width=\"310\" valign=\"middle\"><center> <br><br>Ação do último turno:<br>".$mosternofim."<br><br>Você ganhou a batalha!<br>O HP do seu Oponente é 0!<br><br><br><b>Vencedor:</b> $usuariologadonome<br><b>Perdedor:</b> $batalhanome </center> </td><td> <table width=\"165\" height=\"175\" background=\"layoutnovo/graficos/fundo.png\" style=\"background-repeat:no-repeat;;background-position:left top\"><tr height=\"30%\"><td></td></tr><tr><td><center><img src=\"layoutnovo/graficos/".$userrow["avatar"]."_ganhou.gif\"></center> </td></tr><tr height=\"15\"><td></td></tr></table> </td></tr></table> ","Realizar Duelo",false,false,false); $updatequery = doquery("UPDATE {{table}} SET currentmonstersleep='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentuberdamage='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentuberdefense='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_nome='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_hp='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentmonsterhp='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentmonsterimmune='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET currentmonster='' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_timer='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_acao='None' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_id='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); die(); } //VEZ DE QUAL JOGADOR if($batalhaid == 0) { display("Aguarde o seu turno novamente. O outro Jogador precisa fazer seu movimento.<meta HTTP-EQUIV='refresh' CONTENT='1;URL=users.php?do=duelo'>","Realizar Duelo",false,false,false); die(); } //JOGADOR SPELLS $pagearray = array(); $playerisdead = 0; //Graficos $pagearray["grafico"] = $userrow["avatar"]."_stance.gif"; $pagearray["magiclist"] = ""; $userspells = explode(",",$userrow["spells"]); $spellquery = doquery("SELECT id,name FROM {{table}}", "spells"); while ($spellrow = mysql_fetch_array($spellquery)) { $spell = false; foreach ($userspells as $a => $b) { if ($b == $spellrow["id"]) { $spell = true; } } if ($spell == true) { //if ($spellrow["type"] != 3) {//menos spell de sleep $pagearray["magiclist"] .= "<option value=\"".$spellrow["id"]."\">".$spellrow["name"]."</option>\n"; //}//termina aqui o spell } unset($spell); } if ($pagearray["magiclist"] == "") { $pagearray["magiclist"] = "<option value=\"0\">None</option>\n"; } $magiclist = $pagearray["magiclist"]; $chancetoswingfirst = 1; //FIM JOGADOR SPELLS if (isset($_POST["duelo"])) { extract($_POST); //Graficos $pagearray["grafico"] = $userrow["avatar"]."_ataque.gif"; //DADOS JOGADOR 1 $userquery = doquery("SELECT * FROM {{table}} WHERE charname='$usuariologadonome' LIMIT 1","users"); if (mysql_num_rows($userquery) != 1) { display("Não existe nenhuma conta com esse nome.","Erro",false,false,false);die(); } $userrow = mysql_fetch_array($userquery); // DADOS JOGADOR 2. $monsterquery = doquery("SELECT * FROM {{table}} WHERE charname='$batalhanome' LIMIT 1", "users"); $jogador2row = mysql_fetch_array($monsterquery); $pagearray["monstername"] = $jogador2row["charname"]; $batalhahp2 = $jogador2row["batalha_hp"]; // Your turn. $pagearray["yourturn"] = ""; $tohit = ceil(rand($userrow["attackpower"]*.75,$userrow["attackpower"])/3); $toexcellent = rand(1,150); //atributo determinacao // antes $toexcellent <= sqrt($userrow["strength"]) $determinacao = sqrt($userrow["strength"]) + ($userrow["determinacao"]*2/100); if ($toexcellent <= $determinacao) { $tohit *= 2; $pagearray["yourturn"] .= "Hit Excelente!<br />"; } $toblock = ceil(rand(($jogador2row["defensepower"]/10)*.75,($jogador2row["defensepower"]/10))/3); $tododge = rand(1,200); //atributo precisao // antes $tododge <= sqrt($monsterrow["armor"]) $tododge = $tododge + floor($userrow["precisao"]*3/100); //agilidade $tododgejogador2agilidade = sqrt($jogador2row["dexterity"]/6) + floor($jogador2row["agilidade"]*2/100); if ($tododge <= $tododgejogador2agilidade) { $tohit = 0; $pagearray["yourturn"] .= "O jogador está desviando. Nenhum dano foi recebido por ele.<br />"; $monsterdamage = 0; } else { $monsterdamage = $tohit - $toblock; if ($monsterdamage < 1) { $monsterdamage = 1; } if ($userrow["currentuberdamage"] != 0) { $monsterdamage += ceil($monsterdamage * ($userrow["currentuberdamage"]/100)); } //parte teste, timer: /* $updatequery = doquery("UPDATE {{table}} SET batalha_timer='1' WHERE charname='$usuariologadonome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_timer='6' WHERE charname='$batalhanome' LIMIT 1","users"); //fim timer */ $pagearray["yourturn"] .= "Você atacou o jogador provocando $monsterdamage de dano.<br /><br />"; $userrow["currentmonsterhp"] -= $monsterdamage; $pagearray["monsterhp"] = "HP do Jogador: " . $userrow["currentmonsterhp"] . "<br /><br />"; //atualizando os dados de batalha, hp etc $updatequery = doquery("UPDATE {{table}} SET currentmonsterhp='".$userrow["currentmonsterhp"]."', currenthp='$hpjogador' WHERE id='".$userrow["id"]."' LIMIT 1", "users"); $updatequery = doquery("UPDATE {{table}} SET batalha_hp='".$userrow["currentmonsterhp"]."', currenthp='".$userrow["currentmonsterhp"]."', currentmonsterimmune='".$userrow["currentmp"]."', currentmonsterhp='$hpjogador' WHERE charname='$batalhanome' LIMIT 1", "users"); }//fim da parte duelo // JOGADOR ESTA MORTO. $variaveldapagina = "<b>".$usuariologadonome."</b>: ".$pagearray["yourturn"]; $updatequery = doquery("UPDATE {{table}} SET batalha_acao='$variaveldapagina' WHERE charname='$batalhanome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_id='1' WHERE charname='$batalhanome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_id='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); display("<b>Ações</b>:<br>$variaveldapagina<br><br>Aguarde o seu turno novamente.<meta HTTP-EQUIV='refresh' CONTENT='5;URL=users.php?do=duelo'>","Realizar Duelo",false,false,false); die(); } if (isset($_POST["spell"])) { //Graficos $pagearray["grafico"] = $userrow["avatar"]."_jutsu.gif"; $healaravida = 0; // Your turn. $pickedspell = $_POST["userspell"]; if ($pickedspell == 0) { display("Você deve selecionar um Jutsu primeiro. Por favor volte e tente novamente.", "Error"); die(); } $newspellquery = doquery("SELECT * FROM {{table}} WHERE id='$pickedspell' LIMIT 1", "spells"); $newspellrow = mysql_fetch_array($newspellquery); $spell = false; foreach($userspells as $a => $b) { if ($b == $pickedspell) { $spell = true; } } if ($spell != true) { display("Você ainda não aprendeu esse Jutsu. Por favor volte e tente novamente.", "Error"); die(); } if ($userrow["currentmp"] < $newspellrow["mp"]) { display("Você não tem Chakra suficiente para usar esse Jutsu. Por favor volte e tente novamente.", "Error"); die(); } if ($newspellrow["type"] == 1) { // Heal spell. $newhp = $userrow["currenthp"] + $newspellrow["attribute"]; if ($userrow["maxhp"] < $newhp) { $newspellrow["attribute"] = $userrow["maxhp"] - $userrow["currenthp"]; $newhp = $userrow["currenthp"] + $newspellrow["attribute"]; } $userrow["currenthp"] = $newhp; $userrow["currentmp"] -= $newspellrow["mp"]; $pagearray["yourturn"] = "Você usou o Jutsu: ".$newspellrow["name"]." e ganhou ".$newspellrow["attribute"]." Pontos de Vida.<br /><br />"; //adicionando pontos de vida $hpjogador += $newspellrow["attribute"]; if ($userrow["maxhp"] < $hpjogador) {$hpjogador = $userrow["maxhp"];} $healaravida = 1; } elseif ($newspellrow["type"] == 2) { // Hurt spell. $variaveltb = 0; if ($variaveltb == 0) { $monsterdamage = rand((($newspellrow["attribute"]/6)*5), $newspellrow["attribute"]); $userrow["currentmonsterhp"] -= $monsterdamage; $pagearray["yourturn"] = "Você usou o Jutsu: ".$newspellrow["name"]." e causou $monsterdamage de dano.<br /><br />"; } else { $pagearray["yourturn"] = "Você usou o Jutsu: ".$newspellrow["name"].", mas o jogador é imune à seu Jutsu.<br /><br />"; } //monstro imune ao sleep, eu adicionei $variavel = 2; $userrow["currentmp"] -= $newspellrow["mp"]; } /*elseif ($newspellrow["type"] == 3) { // Sleep spell. if ($variavel != 2) { $userrow["currentmonstersleep"] = $newspellrow["attribute"]; $pagearray["yourturn"] = "Você usou o Jutsu: ".$newspellrow["name"].". O inimigo está dormindo.<br /><br />"; } else { $pagearray["yourturn"] = "Você usou o Jutsu: ".$newspellrow["name"].", mas o jogador é imune à ele.<br /><br />"; }*/ elseif ($newspellrow["type"] == 3) { // Sleep spell. $pagearray["yourturn"] = "Você usou o Jutsu: ".$newspellrow["name"].", mas os jogadores são imunes à ele.<br /><br />"; $userrow["currentmp"] -= $newspellrow["mp"]; } elseif ($newspellrow["type"] == 4) { // +Damage spell. $userrow["currentuberdamage"] = $newspellrow["attribute"]; $userrow["currentmp"] -= $newspellrow["mp"]; $pagearray["yourturn"] = "Você usou o Jutsu: ".$newspellrow["name"]." e ganhou ".$newspellrow["attribute"]."% de dano até o fim da batalha.<br /><br />"; } elseif ($newspellrow["type"] == 5) { // +Defense spell. $userrow["currentuberdefense"] = $newspellrow["attribute"]; $userrow["currentmp"] -= $newspellrow["mp"]; $pagearray["yourturn"] = "Você usou o Jutsu: ".$newspellrow["name"]." e ganhou ".$newspellrow["attribute"]."% de defesa até o fim da batalha.<br /><br />"; } //atualizando os dados de batalha, hp etc $updatequery = doquery("UPDATE {{table}} SET currentmonsterhp='".$userrow["currentmonsterhp"]."', currentuberdefense='".$userrow["currentuberdefense"]."', currentmp='".$userrow["currentmp"]."', currentuberdamage='".$userrow["currentuberdamage"]."', currentuberdamage='".$userrow["currentuberdamage"]."', currenthp='$hpjogador' WHERE id='".$userrow["id"]."' LIMIT 1", "users"); $updatequery = doquery("UPDATE {{table}} SET batalha_hp='".$userrow["currentmonsterhp"]."', currenthp='".$userrow["currentmonsterhp"]."', currentmonsterimmune='$hpjogador', currentmonsterhp='$hpjogador' WHERE charname='$batalhanome' LIMIT 1", "users"); /* if ($healarvida != 0){ $updatequery = doquery("UPDATE {{table}} SET currentmonsterhp='$healaravida' WHERE charname='$batalhanome' LIMIT 1","users");}*/ //terminando $variaveldapagina = "<b>".$usuariologadonome."</b>: ".$pagearray["yourturn"]; $updatequery = doquery("UPDATE {{table}} SET batalha_acao='$variaveldapagina' WHERE charname='$batalhanome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_id='1' WHERE charname='$batalhanome' LIMIT 1","users"); $updatequery = doquery("UPDATE {{table}} SET batalha_id='0' WHERE charname='$usuariologadonome' LIMIT 1","users"); display("<b>Ações</b>:<br>$variaveldapagina<br><br>Aguarde o seu turno novamente.<meta HTTP-EQUIV='refresh' CONTENT='5;URL=users.php?do=duelo'>","Realizar Duelo",false,false,false); die(); } //CONTEUDO DA PAGINA AQUI !!! if ($pagearray["grafico"] == ""){$pagearray["grafico"] = $userrow["avatar"]."_stance.gif";} $page = "<table width=\"100%\"><tr><td width=\"100%\"align=\"center\"><center><img src=\"images/duelo.gif\" /></center></td></tr></table> <table><tr><td width=\"310\" valign=\"middle\"> Ação do último turno:<br>$mosternofim<br><br> <table><tr><td><b>Seus Dados:</b><br><b>Nome</b>: $usuariologadonome<br><b>HP</b>: $hpjogador<br><b>CH</b>: $mpjogador</td> <td width=20></td><td><b>Desafiante</b><br><b>Nome</b>: $batalhanome<br><b>HP</b>: ".$userrow["currentmonsterhp"]."<br><b>CH</b>: $mpjogador2</td></tr></table> <br><br>Comando?<br /><br /> <form action=\"users.php?do=duelo\" method=\"post\"> <input type=\"submit\" name=\"duelo\" value=\"Atacar\" /><br /><br /> <select name=\"userspell\"><option value=\"0\">Escolha um Jutsu</option>$magiclist</select> <input type=\"submit\" name=\"spell\" value=\"Usar\" /><br /><br /> </td><td> <table width=\"165\" height=\"175\" background=\"layoutnovo/graficos/fundo.png\" style=\"background-repeat:no-repeat;;background-position:left top\"><tr height=\"30%\"><td></td></tr><tr><td><center><img src=\"layoutnovo/graficos/".$pagearray["grafico"]."\"></center> </td></tr><tr height=\"15\"><td></td></tr></table> </td></tr></table> </form><br><h2><a href=\"users.php?do=resetarduelo\">Cancelar Duelo</a></h2>" ; $topnav = "<a href=\"index.php\"><img src=\"images/jogar.gif\" alt=\"Voltar a Jogar\" border=\"0\" /></a><a href=\"help.php\"><img src=\"images/button_help.gif\" alt=\"Ajuda\" border=\"0\" /></a>"; display($page, "Realizar Duelo", false, false, false); } function procurarjogador() { global $topvar; $topvar = true; /* testando se está logado */ //include('cookies.php'); //$userrow = checkcookies(); global $userrow; if ($userrow == false) { display("Por favor faça o <a href=\"login.php?do=login\">log in</a> no jogo antes de executar essa ação.","Erro",false,false,false); die(); } if ($userrow["currentaction"] == "Fighting") {header('Location: ./index.php?do=fight&conteudo=Você não pode acessar essa função no meio de uma batalha!');die(); } $usuariologadoid = $userrow["id"]; $usuariologadonome = $userrow["charname"]; $usuriologadodinaheiro = $userrow["gold"]; /*fim do teste */ /* OLDPASS É A QUANTIDADE DE DINHEIRO DOADO */ if (isset($_POST["submit"])) { extract($_POST); $userquery = doquery("SELECT * FROM {{table}} WHERE charname='$username' LIMIT 1","users"); if (mysql_num_rows($userquery) != 1) { display("Não existe nenhuma conta com esse Nome.","Erro",false,false,false);die(); } $userrow = mysql_fetch_array($userquery); /*if ($userrow["password"] != md5($oldpass)) { die("The old password you provided was incorrect."); } /*$realnewpass = md5($newpass1); */ $localiz = $userrow["id"]; header("Location: index.php?do=onlinechar:$localiz"); } $page = gettemplate("procurarjogador"); $topnav = "<a href=\"index.php\"><img src=\"images/jogar.gif\" alt=\"Voltar a Jogar\" border=\"0\" /></a><a href=\"help.php\"><img src=\"images/button_help.gif\" alt=\"Ajuda\" border=\"0\" /></a>"; display($page, "Procurar Jogador", false, false, false); } ?>
OyatsumiD/NarutoBrowserMmorpg
src/3-Feb-2011/users.php
PHP
mit
120,455
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace MyWebApp.ViewModels.Manage { public class VerifyPhoneNumberViewModel { [Required] public string Code { get; set; } [Required] [Phone] [Display(Name = "Phone number")] public string PhoneNumber { get; set; } } }
Microsoft-Build-2016/CodeLabs-WebDev
Module2-AspNetCore/Source/Ex4/End/src/MyWebApp/ViewModels/Manage/VerifyPhoneNumberViewModel.cs
C#
mit
428
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; function plural(n: number): number { return 5; } export default [ 'nds-NL', [['AM', 'PM'], u, u], u, [['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], u, u], u, [ ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], ['M01', 'M02', 'M03', 'M04', 'M05', 'M06', 'M07', 'M08', 'M09', 'M10', 'M11', 'M12'], u ], u, [['BCE', 'CE'], u, u], 1, [6, 0], ['y-MM-dd', 'y MMM d', 'y MMMM d', 'y MMMM d, EEEE'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1} {0}', u, u, u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'], 'EUR', '€', 'EUR', {'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, 'ltr', plural ];
Toxicable/angular
packages/common/locales/nds-NL.ts
TypeScript
mit
1,098
/** * @file tv_text.c * TV_Text native device driver interface. * * Copyright (c) 2008-2011, Steve Denson * See end of file for terms of use. */ #include <propeller.h> #include "TvText.h" #define TV_TEXT_OUT /** * tvText mailbox and any data shared with PASM must be in hub memory. */ HUBDATA static TvText_t tvText; HUBDATA static uint32_t colorTable[TV_TEXT_COLORTABLE_SIZE]; HUBDATA static uint16_t screen[TV_TEXT_SCREENSIZE]; /** * This is the main global tv text control/status structure. */ HUBDATA volatile TvText_t *tvPtr; /* * In the case of __PROPELLER_XMM__ we must copy the PASM to * a temporary HUB buffer for cog start. Define buffer here. */ #if defined(__PROPELLER_XMM__) #define PASMLEN 496 HUBDATA uint32_t pasm[PASMLEN]; #endif /** * These are variables to keep up with display; */ static int col, row, flag; static uint16_t blank = 0x220; /** * This is the TV palette. */ static char gpalette[TV_TEXT_COLORTABLE_SIZE] = {// fgRGB bgRGB 0x07, 0x0a, // 0 white / dark blue 0x07, 0xbb, // 1 yellow / brown 0x9e, 0x9b, // 2 magenta / black 0x04, 0x07, // 3 grey / white 0x3d, 0x3b, // 4 cyan / dark cyan 0x6b, 0x6e, // 5 green / gray-green 0xbb, 0xce, // 6 red / pink 0x3e, 0x0a // 7 cyan / blue }; /* * This should set the character foreground and screen background. * API are available to get/set this. */ static int color = 0; /* * global var to keep cogid so we don't have to pass parm to stop */ static int gTvTextCog = 0; HUBTEXT static void wordfill(uint16_t *dst, uint16_t val, int len) { while(--len > -1) { *dst = val; dst++; } } HUBTEXT static void wordmove(uint16_t *dst, uint16_t *src, int len) { while(--len > -1) { *dst = *src; dst++; src++; } } /* * TV_Text start function starts TV on a cog * See header file for more details. */ int tvText_start(int basepin) { extern uint32_t binary_TV_dat_start[]; col = 0; row = 0; flag = 0; tvPtr = &tvText; tvPtr->status = 0; tvPtr->enable = 1; tvPtr->pins = ((basepin & 0x38) << 1) | (((basepin & 4) == 4) ? 0x5 : 0); tvPtr->mode = 0x12; tvPtr->colors = colorTable; tvPtr->screen = screen; tvPtr->ht = TV_TEXT_COLS; tvPtr->vt = TV_TEXT_ROWS; tvPtr->hx = 4; tvPtr->vx = 1; tvPtr->ho = 0; tvPtr->vo = -2; tvPtr->broadcast = 0; tvPtr->auralcog = 0; // set main fg/bg color tvText_setColorPalette(&gpalette[TV_TEXT_PAL_WHITE_BLUE]); // blank the screen wordfill(tvPtr->screen, blank, TV_TEXT_SCREENSIZE); #if defined(__PROPELLER_XMM__) // start new cog from external memory using pasm and tvPtr memcpy((char*)pasm,(char*)binary_TV_dat_start,PASMLEN<<2); gTvTextCog = cognew(pasm, (uint32_t)tvPtr) + 1; #else gTvTextCog = cognew((uint32_t)binary_TV_dat_start, (uint32_t)tvPtr) + 1; #endif waitcnt((CLKFREQ>>4)+CNT); // 100us is all we need really // clear screen wordfill(tvPtr->screen, color << 11 | blank, TV_TEXT_SCREENSIZE); col = 0; row = 0; return gTvTextCog; } /** * stop stops the cog running the native assembly driver */ void tvText_stop(void) { int id = gTvTextCog - 1; if(gTvTextCog > 0) { cogstop(id); } } /* * TV_Text setcolors function sets the palette to that defined by pointer. * See header file for more details. */ void tvText_setColorPalette(char* ptr) { int ii = 0; uint8_t fg = 0; uint8_t bg = 0; uint32_t* colors = tvPtr->colors; for(ii = 0; ii < TV_TEXT_COLORTABLE_SIZE; ii += 2) { fg = (uint8_t) ptr[ii]; bg = (uint8_t) ptr[ii+1]; colors[ii] = fg << 24 | bg << 16 | fg << 8 | bg; colors[ii+1] = fg << 24 | fg << 16 | bg << 8 | bg; } } /* * print a new line */ static void newline(void) { uint16_t* sp = (uint16_t*)tvPtr->screen; col = 0; if (++row == TV_TEXT_ROWS) { row--; wordmove(sp, &sp[TV_TEXT_COLS], TV_TEXT_LASTROW); // scroll wordfill(&sp[TV_TEXT_LASTROW], blank, TV_TEXT_COLS); // clear new line } } /* * print a character */ static void printc(int c) { int ndx = row * TV_TEXT_COLS + col; uint32_t val = 0; val = ((color << 1) | (c & 1)) << 10; val += 0x200 + (c & 0xFE); // Driver updates during invisible. Need some delay so screen updates right. // For flicker-free once per scan update, you can wait for status != invisible. // while(*tvPtr->status != TV_TEXT_STAT_INVISIBLE) ; tvPtr->screen[ndx] = val; if (++col == TV_TEXT_COLS) newline(); } /* * TV_Text outchar print char to screen with normal stdio definitions * See header file for more details. */ int tvText_outchar(char c) { switch(c) { case '\b': if (col) col--; break; case '\t': do { printc(' '); } while(col & 7); break; case '\n': newline(); break; case '\r': col = 0; break; default: printc(c); break; } return (int)c; } /* * tvText_ClearScreen function clears the screen. * See header file for more details. */ void tvText_ClearScreen(void) { wordfill(screen, blank, TV_TEXT_SCREENSIZE); } /* * tvText_GetWidth function gets screen width. * See header file for more details. */ int tvText_GetWidth(void) { return TV_TEXT_COLS; } /* * tvText_GetHeight function gets screen height. * See header file for more details. */ int tvText_GetHeight(void) { return TV_TEXT_ROWS; } /* * tvText_SetCursor function sets position to x,y. * See header file for more details. */ void tvText_SetCursor(int c, int r) { col = c; row = r; } /* * tvText_GetCursor function gets the cursor position. * See header file for more details. */ void tvText_GetCursor(int *pc, int *pr) { *pc = col; *pr = row; } /* * tvText_Print null terminated char* to screen * See header file for more details. */ void tvText_Print(const char* s) { while(*s) { printc(*(s++)); } } /* +-------------------------------------------------------------------- | TERMS OF USE: MIT License +-------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------ */
dbetz/propgcc-demos
tvedit/TvText.c
C
mit
7,518
// // IXCollection.h // Ignite Engine // // Created by Robert Walsh on 12/31/13. // /**************************************************************************** The MIT License (MIT) Copyright (c) 2015 Apigee Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ // #import "IXCellBasedControl.h" @interface IXCollection : IXCellBasedControl @end
arjunmantri/IgniteEngine-iOS
IgniteEngine/Controls/IXCollection.h
C
mit
1,429
# How borschik resolves technologies `borschik` resolves a technology path in the following order 1. If the path starts with `/` or `.`, `borschik` uses the given path. For example, `borschik -t ./my-tech/tech.js -i my-file.ext`. 2. Tries to load the technology from `borschik/lib/techs/<given technology>`. For example, `borschik -t css -i my-file.css`. 3. If no, tries to load `borschik-tech-<given technology>` npm package. The example loads `borschik-tech-js-coffee` npm package: `borschik -t js-coffee -i my-file.coffee`.
insane-developer/borschik
docs/where-is-my-tech/where-is-my-tech.en.md
Markdown
mit
529
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Config\Definition\Builder; use Symfony\Component\Config\Definition\NodeInterface; use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException; /** * This class provides a fluent interface for defining a node. * * @author Johannes M. Schmitt <schmittjoh@gmail.com> */ abstract class NodeDefinition implements NodeParentInterface { protected $name; protected $normalization; protected $validation; protected $defaultValue; protected $default = false; protected $required = false; protected $deprecationMessage = null; protected $merge; protected $allowEmptyValue = true; protected $nullEquivalent; protected $trueEquivalent = true; protected $falseEquivalent = false; protected $parent; protected $attributes = array(); public function __construct(?string $name, NodeParentInterface $parent = null) { $this->parent = $parent; $this->name = $name; } /** * Sets the parent node. * * @return $this */ public function setParent(NodeParentInterface $parent) { $this->parent = $parent; return $this; } /** * Sets info message. * * @param string $info The info text * * @return $this */ public function info($info) { return $this->attribute('info', $info); } /** * Sets example configuration. * * @param string|array $example * * @return $this */ public function example($example) { return $this->attribute('example', $example); } /** * Sets an attribute on the node. * * @param string $key * @param mixed $value * * @return $this */ public function attribute($key, $value) { $this->attributes[$key] = $value; return $this; } /** * Returns the parent node. * * @return NodeParentInterface|NodeBuilder|NodeDefinition|ArrayNodeDefinition|VariableNodeDefinition|null The builder of the parent node */ public function end() { return $this->parent; } /** * Creates the node. * * @param bool $forceRootNode Whether to force this node as the root node * * @return NodeInterface */ public function getNode($forceRootNode = false) { if ($forceRootNode) { $this->parent = null; } if (null !== $this->normalization) { $this->normalization->before = ExprBuilder::buildExpressions($this->normalization->before); } if (null !== $this->validation) { $this->validation->rules = ExprBuilder::buildExpressions($this->validation->rules); } $node = $this->createNode(); $node->setAttributes($this->attributes); return $node; } /** * Sets the default value. * * @param mixed $value The default value * * @return $this */ public function defaultValue($value) { $this->default = true; $this->defaultValue = $value; return $this; } /** * Sets the node as required. * * @return $this */ public function isRequired() { $this->required = true; return $this; } /** * Sets the node as deprecated. * * You can use %node% and %path% placeholders in your message to display, * respectively, the node name and its complete path. * * @param string $message Deprecation message * * @return $this */ public function setDeprecated($message = 'The child node "%node%" at path "%path%" is deprecated.') { $this->deprecationMessage = $message; return $this; } /** * Sets the equivalent value used when the node contains null. * * @param mixed $value * * @return $this */ public function treatNullLike($value) { $this->nullEquivalent = $value; return $this; } /** * Sets the equivalent value used when the node contains true. * * @param mixed $value * * @return $this */ public function treatTrueLike($value) { $this->trueEquivalent = $value; return $this; } /** * Sets the equivalent value used when the node contains false. * * @param mixed $value * * @return $this */ public function treatFalseLike($value) { $this->falseEquivalent = $value; return $this; } /** * Sets null as the default value. * * @return $this */ public function defaultNull() { return $this->defaultValue(null); } /** * Sets true as the default value. * * @return $this */ public function defaultTrue() { return $this->defaultValue(true); } /** * Sets false as the default value. * * @return $this */ public function defaultFalse() { return $this->defaultValue(false); } /** * Sets an expression to run before the normalization. * * @return ExprBuilder */ public function beforeNormalization() { return $this->normalization()->before(); } /** * Denies the node value being empty. * * @return $this */ public function cannotBeEmpty() { $this->allowEmptyValue = false; return $this; } /** * Sets an expression to run for the validation. * * The expression receives the value of the node and must return it. It can * modify it. * An exception should be thrown when the node is not valid. * * @return ExprBuilder */ public function validate() { return $this->validation()->rule(); } /** * Sets whether the node can be overwritten. * * @param bool $deny Whether the overwriting is forbidden or not * * @return $this */ public function cannotBeOverwritten($deny = true) { $this->merge()->denyOverwrite($deny); return $this; } /** * Gets the builder for validation rules. * * @return ValidationBuilder */ protected function validation() { if (null === $this->validation) { $this->validation = new ValidationBuilder($this); } return $this->validation; } /** * Gets the builder for merging rules. * * @return MergeBuilder */ protected function merge() { if (null === $this->merge) { $this->merge = new MergeBuilder($this); } return $this->merge; } /** * Gets the builder for normalization rules. * * @return NormalizationBuilder */ protected function normalization() { if (null === $this->normalization) { $this->normalization = new NormalizationBuilder($this); } return $this->normalization; } /** * Instantiate and configure the node according to this definition. * * @return NodeInterface $node The node instance * * @throws InvalidDefinitionException When the definition is invalid */ abstract protected function createNode(); }
gencer/symfony
src/Symfony/Component/Config/Definition/Builder/NodeDefinition.php
PHP
mit
7,581
const config = require('../../../server/config'), Manager = require('./manager'), manager = new Manager(); // Responsible for handling requests for sitemap files module.exports = function handler(siteApp) { const verifyResourceType = function verifyResourceType(req, res, next) { if (!Object.prototype.hasOwnProperty.call(manager, req.params.resource)) { return res.sendStatus(404); } next(); }; siteApp.get('/sitemap.xml', function sitemapXML(req, res) { res.set({ 'Cache-Control': 'public, max-age=' + config.get('caching:sitemap:maxAge'), 'Content-Type': 'text/xml' }); res.send(manager.getIndexXml()); }); siteApp.get('/sitemap-:resource.xml', verifyResourceType, function sitemapResourceXML(req, res) { var type = req.params.resource, page = 1; res.set({ 'Cache-Control': 'public, max-age=' + config.get('caching:sitemap:maxAge'), 'Content-Type': 'text/xml' }); res.send(manager.getSiteMapXml(type, page)); }); };
dingotiles/ghost-for-cloudfoundry
versions/3.3.0/core/frontend/services/sitemap/handler.js
JavaScript
mit
1,110
CREATE TABLE country (id VARCHAR(2) NOT NULL, name VARCHAR(64) NOT NULL, PRIMARY KEY(id)); INSERT INTO "country" ("id", "name") VALUES ('fan', 'ஃபங்க்'); INSERT INTO "country" ("id", "name") VALUES ('fo', 'ஃபரிஸ்த்'); INSERT INTO "country" ("id", "name") VALUES ('fon', 'ஃபான்'); INSERT INTO "country" ("id", "name") VALUES ('fat', 'ஃபான்டி'); INSERT INTO "country" ("id", "name") VALUES ('fj', 'ஃபிஜி'); INSERT INTO "country" ("id", "name") VALUES ('fiu', 'ஃபினோ-உக்ரைன் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('fil', 'ஃபிலிபினோ'); INSERT INTO "country" ("id", "name") VALUES ('ff', 'ஃபுலா'); INSERT INTO "country" ("id", "name") VALUES ('phn', 'ஃபொனிஷியன்'); INSERT INTO "country" ("id", "name") VALUES ('pon', 'ஃபோன்பெயென்'); INSERT INTO "country" ("id", "name") VALUES ('fur', 'ஃப்ரியூலியன்'); INSERT INTO "country" ("id", "name") VALUES ('cpf', 'ஃப்ரென்ச் அடைப்படையிலான கிரியோல் மற்றும் பிஜின்'); INSERT INTO "country" ("id", "name") VALUES ('aa', 'அஃபார்'); INSERT INTO "country" ("id", "name") VALUES ('afh', 'அஃப்ரிஹிலி'); INSERT INTO "country" ("id", "name") VALUES ('afa', 'அஃப்ரோ-ஏசியாடிக் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('ak', 'அகான்'); INSERT INTO "country" ("id", "name") VALUES ('ach', 'அகோலி'); INSERT INTO "country" ("id", "name") VALUES ('akk', 'அக்கேதியன்'); INSERT INTO "country" ("id", "name") VALUES ('anp', 'அங்கிகா'); INSERT INTO "country" ("id", "name") VALUES ('az', 'அசர்பாய்ஜானி'); INSERT INTO "country" ("id", "name") VALUES ('ady', 'அதகே'); INSERT INTO "country" ("id", "name") VALUES ('ada', 'அதாங்மே'); INSERT INTO "country" ("id", "name") VALUES ('ath', 'அதாபஸ்கான் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('apa', 'அபாச்சி மொழி'); INSERT INTO "country" ("id", "name") VALUES ('ab', 'அப்காஜியான்'); INSERT INTO "country" ("id", "name") VALUES ('hsb', 'அப்பர் சோர்பியான்'); INSERT INTO "country" ("id", "name") VALUES ('umb', 'அம்பொண்டு'); INSERT INTO "country" ("id", "name") VALUES ('am', 'அம்ஹாரிக்'); INSERT INTO "country" ("id", "name") VALUES ('ay', 'அய்மரா'); INSERT INTO "country" ("id", "name") VALUES ('arp', 'அரபஹோ'); INSERT INTO "country" ("id", "name") VALUES ('ar', 'அரபு'); INSERT INTO "country" ("id", "name") VALUES ('arc', 'அராமைக்'); INSERT INTO "country" ("id", "name") VALUES ('arw', 'அராவாக்'); INSERT INTO "country" ("id", "name") VALUES ('rup', 'அரோமானியன்'); INSERT INTO "country" ("id", "name") VALUES ('arn', 'அரௌகேனியன்'); INSERT INTO "country" ("id", "name") VALUES ('ale', 'அலூட்'); INSERT INTO "country" ("id", "name") VALUES ('alg', 'அல்கான்கியன் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('tut', 'அல்தேய்க் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('sq', 'அல்பெனியன்'); INSERT INTO "country" ("id", "name") VALUES ('awa', 'அவதி'); INSERT INTO "country" ("id", "name") VALUES ('ae', 'அவெஸ்தான்'); INSERT INTO "country" ("id", "name") VALUES ('av', 'அவேரிக்'); INSERT INTO "country" ("id", "name") VALUES ('ast', 'அஸ்துரியன்'); INSERT INTO "country" ("id", "name") VALUES ('as', 'அஸ்ஸாமி'); INSERT INTO "country" ("id", "name") VALUES ('af', 'ஆஃப்ரிகான்ஸ்'); INSERT INTO "country" ("id", "name") VALUES ('oc', 'ஆகிடியன்'); INSERT INTO "country" ("id", "name") VALUES ('cpe', 'ஆங்கில அடைப்படையிலான கிரியோல் மற்றும் பிஜின்'); INSERT INTO "country" ("id", "name") VALUES ('en', 'ஆங்கிலம்'); INSERT INTO "country" ("id", "name") VALUES ('ace', 'ஆச்சினீஸ்'); INSERT INTO "country" ("id", "name") VALUES ('cch', 'ஆட்சம்'); INSERT INTO "country" ("id", "name") VALUES ('an', 'ஆர்கோனீஸ்'); INSERT INTO "country" ("id", "name") VALUES ('hy', 'ஆர்மேனியன்'); INSERT INTO "country" ("id", "name") VALUES ('map', 'ஆஸ்ட்ரோனேஷியன்'); INSERT INTO "country" ("id", "name") VALUES ('aus', 'ஆஸ்த்ரேலிய மொழி'); INSERT INTO "country" ("id", "name") VALUES ('ig', 'இக்போ'); INSERT INTO "country" ("id", "name") VALUES ('inh', 'இங்குஷ்'); INSERT INTO "country" ("id", "name") VALUES ('ijo', 'இஜோ'); INSERT INTO "country" ("id", "name") VALUES ('io', 'இடோ'); INSERT INTO "country" ("id", "name") VALUES ('it', 'இத்தாலியன்'); INSERT INTO "country" ("id", "name") VALUES ('hi', 'இந்தி'); INSERT INTO "country" ("id", "name") VALUES ('inc', 'இந்திய மொழி'); INSERT INTO "country" ("id", "name") VALUES ('id', 'இந்தோனேஷியன்'); INSERT INTO "country" ("id", "name") VALUES ('smn', 'இனாரி சாமி'); INSERT INTO "country" ("id", "name") VALUES ('iu', 'இனுகிடூட்'); INSERT INTO "country" ("id", "name") VALUES ('ik', 'இனுபியாக்'); INSERT INTO "country" ("id", "name") VALUES ('ie', 'இன்டர்லிங்'); INSERT INTO "country" ("id", "name") VALUES ('ia', 'இன்டர்லிங்குவா'); INSERT INTO "country" ("id", "name") VALUES ('ine', 'இன்டோ-ஐரோப்பியன் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('iba', 'இபான்'); INSERT INTO "country" ("id", "name") VALUES ('ira', 'இரானியன் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('iro', 'இரோகோயியன் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('ilo', 'இலோகோ'); INSERT INTO "country" ("id", "name") VALUES ('ee', 'ஈஓயே'); INSERT INTO "country" ("id", "name") VALUES ('eka', 'ஈகாஜுக்'); INSERT INTO "country" ("id", "name") VALUES ('yi', 'ஈத்திஷ'); INSERT INTO "country" ("id", "name") VALUES ('uga', 'உகாரிட்க்'); INSERT INTO "country" ("id", "name") VALUES ('uk', 'உக்ரேனியன்'); INSERT INTO "country" ("id", "name") VALUES ('udm', 'உட்முர்ட்'); INSERT INTO "country" ("id", "name") VALUES ('ur', 'உருது'); INSERT INTO "country" ("id", "name") VALUES ('uz', 'உஸ்பெக்'); INSERT INTO "country" ("id", "name") VALUES ('efi', 'எஃபிக்'); INSERT INTO "country" ("id", "name") VALUES ('nqo', 'என்\'கோ'); INSERT INTO "country" ("id", "name") VALUES ('elx', 'எலமைட்'); INSERT INTO "country" ("id", "name") VALUES ('zh_Hans', 'எளிய சீனம்'); INSERT INTO "country" ("id", "name") VALUES ('ewo', 'எவோன்டோ'); INSERT INTO "country" ("id", "name") VALUES ('et', 'எஸ்டோனியன்'); INSERT INTO "country" ("id", "name") VALUES ('eo', 'எஸ்பரேன்டோ'); INSERT INTO "country" ("id", "name") VALUES ('myv', 'ஏர்ஜியா'); INSERT INTO "country" ("id", "name") VALUES ('ain', 'ஐனு'); INSERT INTO "country" ("id", "name") VALUES ('pt_PT', 'ஐபேரியன் போர்ச்சுகீசியம்'); INSERT INTO "country" ("id", "name") VALUES ('ga', 'ஐரிஷ்'); INSERT INTO "country" ("id", "name") VALUES ('is', 'ஐஸ்லென்டிக்'); INSERT INTO "country" ("id", "name") VALUES ('os', 'ஒசெட்டிக்'); INSERT INTO "country" ("id", "name") VALUES ('ota', 'ஒட்டோமன் துர்க்கி'); INSERT INTO "country" ("id", "name") VALUES ('oto', 'ஒட்டோமன் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('or', 'ஒரியா'); INSERT INTO "country" ("id", "name") VALUES ('om', 'ஒரோமோ'); INSERT INTO "country" ("id", "name") VALUES ('vo', 'ஒலாபூக்'); INSERT INTO "country" ("id", "name") VALUES ('wo', 'ஒலூஃப்'); INSERT INTO "country" ("id", "name") VALUES ('wa', 'ஒவாலூன்'); INSERT INTO "country" ("id", "name") VALUES ('osa', 'ஓசேஜ்'); INSERT INTO "country" ("id", "name") VALUES ('oj', 'ஓஜிபவா'); INSERT INTO "country" ("id", "name") VALUES ('kk', 'கசாக்'); INSERT INTO "country" ("id", "name") VALUES ('kr', 'கனுரி'); INSERT INTO "country" ("id", "name") VALUES ('kn', 'கன்னடம்'); INSERT INTO "country" ("id", "name") VALUES ('kab', 'கபாய்ல்'); INSERT INTO "country" ("id", "name") VALUES ('kbd', 'கபார்டியன்'); INSERT INTO "country" ("id", "name") VALUES ('kam', 'கம்பா'); INSERT INTO "country" ("id", "name") VALUES ('gay', 'கயோ'); INSERT INTO "country" ("id", "name") VALUES ('krc', 'கராசே-பல்கார்'); INSERT INTO "country" ("id", "name") VALUES ('car', 'கரீப்'); INSERT INTO "country" ("id", "name") VALUES ('kar', 'கரேன்'); INSERT INTO "country" ("id", "name") VALUES ('krl', 'கரேலியன்'); INSERT INTO "country" ("id", "name") VALUES ('hr', 'கரோஷியன்'); INSERT INTO "country" ("id", "name") VALUES ('kl', 'கலாலிசூட்'); INSERT INTO "country" ("id", "name") VALUES ('xal', 'கல்மிக்'); INSERT INTO "country" ("id", "name") VALUES ('csb', 'கஷுபியன்'); INSERT INTO "country" ("id", "name") VALUES ('gaa', 'கா'); INSERT INTO "country" ("id", "name") VALUES ('cau', 'காகேஷியன் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('kg', 'காங்கோ'); INSERT INTO "country" ("id", "name") VALUES ('kac', 'காசின்'); INSERT INTO "country" ("id", "name") VALUES ('ca', 'காடலான்'); INSERT INTO "country" ("id", "name") VALUES ('lg', 'கான்டா'); INSERT INTO "country" ("id", "name") VALUES ('cop', 'காப்டிக்'); INSERT INTO "country" ("id", "name") VALUES ('kaa', 'காரா-கல்பாக்'); INSERT INTO "country" ("id", "name") VALUES ('co', 'கார்சியன்'); INSERT INTO "country" ("id", "name") VALUES ('kw', 'கார்னிஷ்'); INSERT INTO "country" ("id", "name") VALUES ('gl', 'காலிஸியன்'); INSERT INTO "country" ("id", "name") VALUES ('kaw', 'காவி'); INSERT INTO "country" ("id", "name") VALUES ('ks', 'காஷ்மிரி'); INSERT INTO "country" ("id", "name") VALUES ('kha', 'காஸி'); INSERT INTO "country" ("id", "name") VALUES ('ki', 'கிகுயூ'); INSERT INTO "country" ("id", "name") VALUES ('rw', 'கின்யாருவான்டா'); INSERT INTO "country" ("id", "name") VALUES ('kmb', 'கிம்புன்து'); INSERT INTO "country" ("id", "name") VALUES ('crh', 'கிரிமியன் துர்க்கி'); INSERT INTO "country" ("id", "name") VALUES ('crp', 'கிரியோல் மற்றும் பிஜின்'); INSERT INTO "country" ("id", "name") VALUES ('el', 'கிரேக்கம்'); INSERT INTO "country" ("id", "name") VALUES ('ky', 'கிர்கிஷ்'); INSERT INTO "country" ("id", "name") VALUES ('gil', 'கில்பெர்டீஸ்'); INSERT INTO "country" ("id", "name") VALUES ('tlh', 'கிளிங்கன்'); INSERT INTO "country" ("id", "name") VALUES ('frs', 'கிழக்கு ஃப்ரிஸியான்'); INSERT INTO "country" ("id", "name") VALUES ('qu', 'கிவேசுவா'); INSERT INTO "country" ("id", "name") VALUES ('gez', 'கீஜ்'); INSERT INTO "country" ("id", "name") VALUES ('gu', 'குஜராத்தி'); INSERT INTO "country" ("id", "name") VALUES ('kut', 'குடேனை'); INSERT INTO "country" ("id", "name") VALUES ('kum', 'கும்இக்'); INSERT INTO "country" ("id", "name") VALUES ('gn', 'குரானி'); INSERT INTO "country" ("id", "name") VALUES ('kru', 'குருக்'); INSERT INTO "country" ("id", "name") VALUES ('ku', 'குர்திஷ்'); INSERT INTO "country" ("id", "name") VALUES ('kj', 'குவான்யாமா'); INSERT INTO "country" ("id", "name") VALUES ('gwi', 'குவிசின்'); INSERT INTO "country" ("id", "name") VALUES ('cus', 'குஷிடிக் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('km', 'கெமெர்'); INSERT INTO "country" ("id", "name") VALUES ('cel', 'கெல்டிக் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('cad', 'கேடோ'); INSERT INTO "country" ("id", "name") VALUES ('kok', 'கொங்கனி'); INSERT INTO "country" ("id", "name") VALUES ('khi', 'கொய்ஸன் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('ko', 'கொரியன்'); INSERT INTO "country" ("id", "name") VALUES ('kho', 'கோதானீஸ்'); INSERT INTO "country" ("id", "name") VALUES ('got', 'கோதிக்'); INSERT INTO "country" ("id", "name") VALUES ('gon', 'கோன்டி'); INSERT INTO "country" ("id", "name") VALUES ('kv', 'கோமி'); INSERT INTO "country" ("id", "name") VALUES ('kfo', 'கோரோ'); INSERT INTO "country" ("id", "name") VALUES ('gor', 'கோரோன்டலோ'); INSERT INTO "country" ("id", "name") VALUES ('kos', 'கோஸ்ரைன்'); INSERT INTO "country" ("id", "name") VALUES ('kpe', 'க்பெல்லே'); INSERT INTO "country" ("id", "name") VALUES ('cr', 'க்ரீ'); INSERT INTO "country" ("id", "name") VALUES ('mus', 'க்ரீக்'); INSERT INTO "country" ("id", "name") VALUES ('kro', 'க்ரு'); INSERT INTO "country" ("id", "name") VALUES ('grb', 'க்ரேபோ'); INSERT INTO "country" ("id", "name") VALUES ('sgn', 'சங்கேத மொழி'); INSERT INTO "country" ("id", "name") VALUES ('sa', 'சமஸ்கிருதம்'); INSERT INTO "country" ("id", "name") VALUES ('sam', 'சமாரிடன் அராமைக்'); INSERT INTO "country" ("id", "name") VALUES ('cu', 'சர்ச் ஸ்லாவிக்'); INSERT INTO "country" ("id", "name") VALUES ('sr', 'சர்பியன்'); INSERT INTO "country" ("id", "name") VALUES ('sg', 'சாங்கோ'); INSERT INTO "country" ("id", "name") VALUES ('sas', 'சாசாக்'); INSERT INTO "country" ("id", "name") VALUES ('sc', 'சாடினியன்'); INSERT INTO "country" ("id", "name") VALUES ('sat', 'சான்டாலி'); INSERT INTO "country" ("id", "name") VALUES ('sad', 'சான்டாவே'); INSERT INTO "country" ("id", "name") VALUES ('smi', 'சாமி மொழி'); INSERT INTO "country" ("id", "name") VALUES ('cmc', 'சாமிக் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('ch', 'சாமோரோ'); INSERT INTO "country" ("id", "name") VALUES ('sal', 'சாலிஷன் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('bla', 'சிக்சிகா'); INSERT INTO "country" ("id", "name") VALUES ('si', 'சிங்களம்'); INSERT INTO "country" ("id", "name") VALUES ('scn', 'சிசிலியன்'); INSERT INTO "country" ("id", "name") VALUES ('ii', 'சிசுவான் ஈ'); INSERT INTO "country" ("id", "name") VALUES ('sid', 'சிடாமோ'); INSERT INTO "country" ("id", "name") VALUES ('sd', 'சிந்தி'); INSERT INTO "country" ("id", "name") VALUES ('chn', 'சினூக் ஜார்கான்'); INSERT INTO "country" ("id", "name") VALUES ('sit', 'சினோ-திபேத்தியன் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('chp', 'சிபெவ்யான்'); INSERT INTO "country" ("id", "name") VALUES ('chb', 'சிப்சா'); INSERT INTO "country" ("id", "name") VALUES ('sio', 'சியோயுவான் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('syr', 'சிரியாக்'); INSERT INTO "country" ("id", "name") VALUES ('zh', 'சீனம்'); INSERT INTO "country" ("id", "name") VALUES ('suk', 'சுகுமா'); INSERT INTO "country" ("id", "name") VALUES ('sus', 'சுசு'); INSERT INTO "country" ("id", "name") VALUES ('su', 'சுடானீஸ்'); INSERT INTO "country" ("id", "name") VALUES ('sux', 'சுமேரியன்'); INSERT INTO "country" ("id", "name") VALUES ('cv', 'சுவாஷ்'); INSERT INTO "country" ("id", "name") VALUES ('sw', 'சுவாஹிலி'); INSERT INTO "country" ("id", "name") VALUES ('chk', 'சூகிசே'); INSERT INTO "country" ("id", "name") VALUES ('cs', 'செக்'); INSERT INTO "country" ("id", "name") VALUES ('ce', 'செசென்'); INSERT INTO "country" ("id", "name") VALUES ('ceb', 'செபுவானோ'); INSERT INTO "country" ("id", "name") VALUES ('sem', 'செமிடிக் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('art', 'செயற்கையான மொழி'); INSERT INTO "country" ("id", "name") VALUES ('chy', 'செயேனி'); INSERT INTO "country" ("id", "name") VALUES ('chr', 'செரூக்கி'); INSERT INTO "country" ("id", "name") VALUES ('srr', 'செரெர்'); INSERT INTO "country" ("id", "name") VALUES ('sh', 'செர்போ-க்ரோஷியன்'); INSERT INTO "country" ("id", "name") VALUES ('sel', 'செல்குப்'); INSERT INTO "country" ("id", "name") VALUES ('wen', 'சொர்பியன் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('sog', 'சோக்தியன்'); INSERT INTO "country" ("id", "name") VALUES ('cho', 'சோக்தௌ'); INSERT INTO "country" ("id", "name") VALUES ('son', 'சோங்காய்'); INSERT INTO "country" ("id", "name") VALUES ('snk', 'சோனின்கே'); INSERT INTO "country" ("id", "name") VALUES ('so', 'சோமாலி'); INSERT INTO "country" ("id", "name") VALUES ('ja', 'ஜப்பானீஸ்'); INSERT INTO "country" ("id", "name") VALUES ('zza', 'ஜாஜா'); INSERT INTO "country" ("id", "name") VALUES ('znd', 'ஜான்டே'); INSERT INTO "country" ("id", "name") VALUES ('zap', 'ஜாபோடெக்'); INSERT INTO "country" ("id", "name") VALUES ('jv', 'ஜாவானீஸ்'); INSERT INTO "country" ("id", "name") VALUES ('ka', 'ஜியோர்ஜியன்'); INSERT INTO "country" ("id", "name") VALUES ('za', 'ஜுவாங்'); INSERT INTO "country" ("id", "name") VALUES ('jrb', 'ஜூதேயோ-அராபிக்'); INSERT INTO "country" ("id", "name") VALUES ('jpr', 'ஜூதேயோ-பெர்ஷியன்'); INSERT INTO "country" ("id", "name") VALUES ('zun', 'ஜூனி'); INSERT INTO "country" ("id", "name") VALUES ('zu', 'ஜூலூ'); INSERT INTO "country" ("id", "name") VALUES ('zen', 'ஜெனகா'); INSERT INTO "country" ("id", "name") VALUES ('de', 'ஜெர்மன்'); INSERT INTO "country" ("id", "name") VALUES ('gem', 'ஜெர்மானிய மொழி'); INSERT INTO "country" ("id", "name") VALUES ('kaj', 'ஜ்ஜூ'); INSERT INTO "country" ("id", "name") VALUES ('nl', 'டச்சு'); INSERT INTO "country" ("id", "name") VALUES ('tr', 'டர்கிஷ்'); INSERT INTO "country" ("id", "name") VALUES ('tk', 'டர்க்மென்'); INSERT INTO "country" ("id", "name") VALUES ('ty', 'டஹிதியான்'); INSERT INTO "country" ("id", "name") VALUES ('tl', 'டாகாலோக்'); INSERT INTO "country" ("id", "name") VALUES ('tt', 'டாடர்'); INSERT INTO "country" ("id", "name") VALUES ('da', 'டானிஷ்'); INSERT INTO "country" ("id", "name") VALUES ('tmh', 'டாமாஷேக்'); INSERT INTO "country" ("id", "name") VALUES ('ti', 'டிக்ரின்யா'); INSERT INTO "country" ("id", "name") VALUES ('din', 'டின்கா'); INSERT INTO "country" ("id", "name") VALUES ('tem', 'டிம்னே'); INSERT INTO "country" ("id", "name") VALUES ('tli', 'டிலிங்கிட்'); INSERT INTO "country" ("id", "name") VALUES ('tiv', 'டிவ்'); INSERT INTO "country" ("id", "name") VALUES ('tum', 'டும்புகா'); INSERT INTO "country" ("id", "name") VALUES ('tvl', 'டுவாலு'); INSERT INTO "country" ("id", "name") VALUES ('tyv', 'டுவினியன்'); INSERT INTO "country" ("id", "name") VALUES ('tet', 'டெடும்'); INSERT INTO "country" ("id", "name") VALUES ('ter', 'டெரெனோ'); INSERT INTO "country" ("id", "name") VALUES ('tig', 'டைக்ரே'); INSERT INTO "country" ("id", "name") VALUES ('tkl', 'டோகேலௌ'); INSERT INTO "country" ("id", "name") VALUES ('tpi', 'டோக் பிஸின்'); INSERT INTO "country" ("id", "name") VALUES ('doi', 'டோக்ரி'); INSERT INTO "country" ("id", "name") VALUES ('dgr', 'டோக்ரிப்'); INSERT INTO "country" ("id", "name") VALUES ('to', 'டோங்கா'); INSERT INTO "country" ("id", "name") VALUES ('dyu', 'ட்யூலா'); INSERT INTO "country" ("id", "name") VALUES ('tw', 'ட்வி'); INSERT INTO "country" ("id", "name") VALUES ('tsi', 'ட்ஸிம்ஷியன்'); INSERT INTO "country" ("id", "name") VALUES ('dak', 'தகோடா'); INSERT INTO "country" ("id", "name") VALUES ('ta', 'தமிழ்'); INSERT INTO "country" ("id", "name") VALUES ('day', 'தயாக்'); INSERT INTO "country" ("id", "name") VALUES ('tg', 'தாஜிக்'); INSERT INTO "country" ("id", "name") VALUES ('th', 'தாய்'); INSERT INTO "country" ("id", "name") VALUES ('tai', 'தாய் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('dar', 'தார்குவா'); INSERT INTO "country" ("id", "name") VALUES ('bo', 'திபெத்து'); INSERT INTO "country" ("id", "name") VALUES ('dra', 'திராவிட மொழி'); INSERT INTO "country" ("id", "name") VALUES ('dv', 'திவேஹி'); INSERT INTO "country" ("id", "name") VALUES ('tup', 'துபி மொழி'); INSERT INTO "country" ("id", "name") VALUES ('dua', 'துவாலா'); INSERT INTO "country" ("id", "name") VALUES ('sai', 'தென் அமெரிக்க இன்டியன் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('und', 'தெரியாத அல்லது செல்லாத பிரதேசம்'); INSERT INTO "country" ("id", "name") VALUES ('alt', 'தெற்கு அல்தை'); INSERT INTO "country" ("id", "name") VALUES ('sma', 'தெற்கு சாமி'); INSERT INTO "country" ("id", "name") VALUES ('nr', 'தெற்கு தெபெலே'); INSERT INTO "country" ("id", "name") VALUES ('st', 'தெற்கு ஸோதோ'); INSERT INTO "country" ("id", "name") VALUES ('del', 'தெலாவேர்'); INSERT INTO "country" ("id", "name") VALUES ('te', 'தெலுங்கு'); INSERT INTO "country" ("id", "name") VALUES ('kcg', 'தையாப்'); INSERT INTO "country" ("id", "name") VALUES ('ng', 'தோங்கா'); INSERT INTO "country" ("id", "name") VALUES ('ny', 'நயன்ஜா'); INSERT INTO "country" ("id", "name") VALUES ('tog', 'நயாசா டோங்கா'); INSERT INTO "country" ("id", "name") VALUES ('nv', 'நவாஜோ'); INSERT INTO "country" ("id", "name") VALUES ('na', 'நவ்ரூ'); INSERT INTO "country" ("id", "name") VALUES ('nah', 'நஹுவால்'); INSERT INTO "country" ("id", "name") VALUES ('no', 'நார்வே'); INSERT INTO "country" ("id", "name") VALUES ('nb', 'நார்வே பொக்மால்'); INSERT INTO "country" ("id", "name") VALUES ('nn', 'நார்வேஜியன் நியூநார்ஸ்க்'); INSERT INTO "country" ("id", "name") VALUES ('nzi', 'நிஜ்மா'); INSERT INTO "country" ("id", "name") VALUES ('nyn', 'நியான்கோலே'); INSERT INTO "country" ("id", "name") VALUES ('nym', 'நியாம்வேஜி'); INSERT INTO "country" ("id", "name") VALUES ('nia', 'நியாஸ்'); INSERT INTO "country" ("id", "name") VALUES ('nub', 'நியூபியன் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('niu', 'நியூவான்'); INSERT INTO "country" ("id", "name") VALUES ('nap', 'நியோபோலிடன்'); INSERT INTO "country" ("id", "name") VALUES ('nyo', 'நியோரோ'); INSERT INTO "country" ("id", "name") VALUES ('ssa', 'நிலோ-சஹாரன் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('new', 'நெவாரி'); INSERT INTO "country" ("id", "name") VALUES ('ne', 'நேபாளி'); INSERT INTO "country" ("id", "name") VALUES ('nic', 'நைஜர்-கோரடோஃபனியன் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('nog', 'நோகை'); INSERT INTO "country" ("id", "name") VALUES ('pa', 'பஞ்சாபி'); INSERT INTO "country" ("id", "name") VALUES ('egy', 'பண்டைய எகிப்தியன்'); INSERT INTO "country" ("id", "name") VALUES ('grc', 'பண்டைய கிரேக்கம்'); INSERT INTO "country" ("id", "name") VALUES ('pag', 'பன்காசினன்'); INSERT INTO "country" ("id", "name") VALUES ('pap', 'பபியேமென்டோ'); INSERT INTO "country" ("id", "name") VALUES ('paa', 'பபுவான் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('bai', 'பமிலெகே மொழி'); INSERT INTO "country" ("id", "name") VALUES ('pam', 'பம்பாங்கா'); INSERT INTO "country" ("id", "name") VALUES ('bm', 'பம்பாரா'); INSERT INTO "country" ("id", "name") VALUES ('gba', 'பயா'); INSERT INTO "country" ("id", "name") VALUES ('pra', 'பராக்ரித் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('my', 'பர்மிஸ்'); INSERT INTO "country" ("id", "name") VALUES ('fa', 'பர்ஸியன்'); INSERT INTO "country" ("id", "name") VALUES ('mul', 'பல மொழிகள்'); INSERT INTO "country" ("id", "name") VALUES ('mis', 'பலதரப்பட்ட மொழிகள்'); INSERT INTO "country" ("id", "name") VALUES ('ban', 'பலினீஸ்'); INSERT INTO "country" ("id", "name") VALUES ('pau', 'பலௌவ்ன்'); INSERT INTO "country" ("id", "name") VALUES ('bg', 'பல்கேரியன்'); INSERT INTO "country" ("id", "name") VALUES ('fro', 'பழைய ஃப்ரென்ச்'); INSERT INTO "country" ("id", "name") VALUES ('ang', 'பழைய ஆங்கிலம்'); INSERT INTO "country" ("id", "name") VALUES ('sga', 'பழைய ஐரிஷ்'); INSERT INTO "country" ("id", "name") VALUES ('non', 'பழைய நோர்ஸ்'); INSERT INTO "country" ("id", "name") VALUES ('peo', 'பழைய பெர்ஷியன்'); INSERT INTO "country" ("id", "name") VALUES ('pro', 'பழைய ப்ரோவென்சால்'); INSERT INTO "country" ("id", "name") VALUES ('goh', 'பழைய ஹை ஜெர்மன்'); INSERT INTO "country" ("id", "name") VALUES ('eu', 'பஸ்க்'); INSERT INTO "country" ("id", "name") VALUES ('btk', 'பாடாக்'); INSERT INTO "country" ("id", "name") VALUES ('bad', 'பாண்டா'); INSERT INTO "country" ("id", "name") VALUES ('bnt', 'பான்டு'); INSERT INTO "country" ("id", "name") VALUES ('syc', 'பாரம்பரிய சிரியாக்'); INSERT INTO "country" ("id", "name") VALUES ('nwc', 'பாரம்பரிய நேவாரி'); INSERT INTO "country" ("id", "name") VALUES ('pi', 'பாலி'); INSERT INTO "country" ("id", "name") VALUES ('bat', 'பால்டிக் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('ba', 'பாஷ்கிர்'); INSERT INTO "country" ("id", "name") VALUES ('ps', 'பாஷ்டோ'); INSERT INTO "country" ("id", "name") VALUES ('bas', 'பாஸா'); INSERT INTO "country" ("id", "name") VALUES ('pal', 'பாஹ்லவி'); INSERT INTO "country" ("id", "name") VALUES ('bik', 'பிகோல்'); INSERT INTO "country" ("id", "name") VALUES ('bin', 'பினி'); INSERT INTO "country" ("id", "name") VALUES ('fi', 'பின்னிஷ்'); INSERT INTO "country" ("id", "name") VALUES ('br', 'பிரிடன்'); INSERT INTO "country" ("id", "name") VALUES ('fr', 'பிரெஞ்சு'); INSERT INTO "country" ("id", "name") VALUES ('pt_BR', 'பிரேசிலியன் போர்ச்சுகீசியம்'); INSERT INTO "country" ("id", "name") VALUES ('phi', 'பிலிபைன் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('bi', 'பிஸ்லாமா'); INSERT INTO "country" ("id", "name") VALUES ('bh', 'பிஹாரி'); INSERT INTO "country" ("id", "name") VALUES ('bug', 'புகினீஸ்'); INSERT INTO "country" ("id", "name") VALUES ('bua', 'புரியாத்'); INSERT INTO "country" ("id", "name") VALUES ('dz', 'பூடானி'); INSERT INTO "country" ("id", "name") VALUES ('bem', 'பெம்பா'); INSERT INTO "country" ("id", "name") VALUES ('ber', 'பெர்பெர்'); INSERT INTO "country" ("id", "name") VALUES ('bal', 'பெலுசி'); INSERT INTO "country" ("id", "name") VALUES ('bej', 'பேஜா'); INSERT INTO "country" ("id", "name") VALUES ('be', 'பைலோருஷ்ன்'); INSERT INTO "country" ("id", "name") VALUES ('bho', 'போஜ்பூரி'); INSERT INTO "country" ("id", "name") VALUES ('cpp', 'போர்சுக்கீஸ் அடைப்படையிலான கிரியோல் மற்றும் பிஜின்'); INSERT INTO "country" ("id", "name") VALUES ('pt', 'போர்ச்சுக்கீஸ்'); INSERT INTO "country" ("id", "name") VALUES ('pl', 'போலிஷ்'); INSERT INTO "country" ("id", "name") VALUES ('bs', 'போஸ்னியன்'); INSERT INTO "country" ("id", "name") VALUES ('bra', 'ப்ராஜ்'); INSERT INTO "country" ("id", "name") VALUES ('byn', 'ப்லின்'); INSERT INTO "country" ("id", "name") VALUES ('zbl', 'ப்லிஸ்ஸிம்பால்ஸ்'); INSERT INTO "country" ("id", "name") VALUES ('mak', 'மகாசார்'); INSERT INTO "country" ("id", "name") VALUES ('mag', 'மகாஹி'); INSERT INTO "country" ("id", "name") VALUES ('mn', 'மங்கோலியன்'); INSERT INTO "country" ("id", "name") VALUES ('mad', 'மதுரீஸ்'); INSERT INTO "country" ("id", "name") VALUES ('frm', 'மத்திய ஃப்ரென்ச்'); INSERT INTO "country" ("id", "name") VALUES ('cai', 'மத்திய அமெரிக்கன் இன்டியன் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('enm', 'மத்திய ஆங்கிலம்'); INSERT INTO "country" ("id", "name") VALUES ('mga', 'மத்திய ஐரிஷ்'); INSERT INTO "country" ("id", "name") VALUES ('dum', 'மத்திய டச்சு'); INSERT INTO "country" ("id", "name") VALUES ('gmh', 'மத்திய ஹை ஜெர்மன்'); INSERT INTO "country" ("id", "name") VALUES ('mni', 'மனிபூரி'); INSERT INTO "country" ("id", "name") VALUES ('mno', 'மனோபோ மொழி'); INSERT INTO "country" ("id", "name") VALUES ('mnc', 'மன்சு'); INSERT INTO "country" ("id", "name") VALUES ('zh_Hant', 'மரபு சீனம்'); INSERT INTO "country" ("id", "name") VALUES ('mr', 'மராத்தி'); INSERT INTO "country" ("id", "name") VALUES ('mg', 'மலகாஸி'); INSERT INTO "country" ("id", "name") VALUES ('ms', 'மலாய்'); INSERT INTO "country" ("id", "name") VALUES ('ml', 'மலையாளம்'); INSERT INTO "country" ("id", "name") VALUES ('hmn', 'மாங்க்'); INSERT INTO "country" ("id", "name") VALUES ('mas', 'மாசாய்'); INSERT INTO "country" ("id", "name") VALUES ('mkh', 'மான்-க்மெர் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('mdr', 'மான்டார்'); INSERT INTO "country" ("id", "name") VALUES ('man', 'மான்டிங்கோ'); INSERT INTO "country" ("id", "name") VALUES ('myn', 'மாயான் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('chm', 'மாரி'); INSERT INTO "country" ("id", "name") VALUES ('mwr', 'மார்வாரி'); INSERT INTO "country" ("id", "name") VALUES ('mh', 'மார்ஷெலிஷ்'); INSERT INTO "country" ("id", "name") VALUES ('mt', 'மால்டிஸ்'); INSERT INTO "country" ("id", "name") VALUES ('mk', 'மாஸிடோனியன்'); INSERT INTO "country" ("id", "name") VALUES ('mic', 'மிக்மாக்'); INSERT INTO "country" ("id", "name") VALUES ('min', 'மின்னாங்கபௌ'); INSERT INTO "country" ("id", "name") VALUES ('mwl', 'மிரான்டீஸ்'); INSERT INTO "country" ("id", "name") VALUES ('mun', 'முண்டா மொழி'); INSERT INTO "country" ("id", "name") VALUES ('men', 'மென்டீ'); INSERT INTO "country" ("id", "name") VALUES ('gv', 'மேங்க்ஸ்'); INSERT INTO "country" ("id", "name") VALUES ('fy', 'மேற்கத்திய பிரிஷிய'); INSERT INTO "country" ("id", "name") VALUES ('mai', 'மைதிலி'); INSERT INTO "country" ("id", "name") VALUES ('zxx', 'மொழிக்கிணங்க உள்ளடக்கம் இல்லை'); INSERT INTO "country" ("id", "name") VALUES ('mdf', 'மோக்க்ஷா'); INSERT INTO "country" ("id", "name") VALUES ('lol', 'மோங்கோ'); INSERT INTO "country" ("id", "name") VALUES ('mo', 'மோல்டாவியன்'); INSERT INTO "country" ("id", "name") VALUES ('mos', 'மோஸ்ஸி'); INSERT INTO "country" ("id", "name") VALUES ('moh', 'மோஹாவ்க்'); INSERT INTO "country" ("id", "name") VALUES ('mi', 'மௌரி'); INSERT INTO "country" ("id", "name") VALUES ('sah', 'யாகுட்'); INSERT INTO "country" ("id", "name") VALUES ('yap', 'யாபேசி'); INSERT INTO "country" ("id", "name") VALUES ('yao', 'யாவ்'); INSERT INTO "country" ("id", "name") VALUES ('ug', 'யுகுர்'); INSERT INTO "country" ("id", "name") VALUES ('ypk', 'யுபிக் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('yo', 'யோருப்பா'); INSERT INTO "country" ("id", "name") VALUES ('rap', 'ரபனுய்'); INSERT INTO "country" ("id", "name") VALUES ('rar', 'ரரோடோங்கன்'); INSERT INTO "country" ("id", "name") VALUES ('ru', 'ரஷியன்'); INSERT INTO "country" ("id", "name") VALUES ('raj', 'ராஜஸ்தானி'); INSERT INTO "country" ("id", "name") VALUES ('rn', 'ருண்டி'); INSERT INTO "country" ("id", "name") VALUES ('root', 'ரூட்'); INSERT INTO "country" ("id", "name") VALUES ('rm', 'ரைட்டோ-ரோமென்ஸ்'); INSERT INTO "country" ("id", "name") VALUES ('roa', 'ரோமன்ஸ் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('rom', 'ரோமானி'); INSERT INTO "country" ("id", "name") VALUES ('ro', 'ரோமேனியன்'); INSERT INTO "country" ("id", "name") VALUES ('lb', 'லக்க்ஷெம்பர்கிஷ்'); INSERT INTO "country" ("id", "name") VALUES ('lad', 'லடினோ'); INSERT INTO "country" ("id", "name") VALUES ('la', 'லத்தின்'); INSERT INTO "country" ("id", "name") VALUES ('lam', 'லம்பா'); INSERT INTO "country" ("id", "name") VALUES ('lah', 'லஹன்டா'); INSERT INTO "country" ("id", "name") VALUES ('ln', 'லிங்காலா'); INSERT INTO "country" ("id", "name") VALUES ('lt', 'லிதுவேனியன்'); INSERT INTO "country" ("id", "name") VALUES ('li', 'லிம்பர்கிஷ்'); INSERT INTO "country" ("id", "name") VALUES ('lu', 'லுபா-கடாங்கா'); INSERT INTO "country" ("id", "name") VALUES ('lua', 'லுபா-லுலௌ'); INSERT INTO "country" ("id", "name") VALUES ('luo', 'லுயோ'); INSERT INTO "country" ("id", "name") VALUES ('lui', 'லுய்சேனோ'); INSERT INTO "country" ("id", "name") VALUES ('smj', 'லுலே சாமி'); INSERT INTO "country" ("id", "name") VALUES ('lus', 'லுஷய்'); INSERT INTO "country" ("id", "name") VALUES ('lun', 'லூன்டா'); INSERT INTO "country" ("id", "name") VALUES ('lez', 'லெஜ்ஜியன்'); INSERT INTO "country" ("id", "name") VALUES ('lv', 'லேட்வியன்'); INSERT INTO "country" ("id", "name") VALUES ('nds', 'லோ ஜெர்மன்'); INSERT INTO "country" ("id", "name") VALUES ('loz', 'லோஜி'); INSERT INTO "country" ("id", "name") VALUES ('jbo', 'லோஜ்பன்'); INSERT INTO "country" ("id", "name") VALUES ('lo', 'லோத்தியன்'); INSERT INTO "country" ("id", "name") VALUES ('dsb', 'லோவர் சோர்பியன்'); INSERT INTO "country" ("id", "name") VALUES ('wak', 'வகாஷான் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('bn', 'வங்காளம்'); INSERT INTO "country" ("id", "name") VALUES ('frr', 'வடக்கு ஃப்ரிஸியான்'); INSERT INTO "country" ("id", "name") VALUES ('nai', 'வடக்கு அமெரிக்கன் இன்டியன் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('se', 'வடக்கு சாமி'); INSERT INTO "country" ("id", "name") VALUES ('nso', 'வடக்கு சோதோ'); INSERT INTO "country" ("id", "name") VALUES ('nd', 'வடக்கு தெபெலே'); INSERT INTO "country" ("id", "name") VALUES ('war', 'வாரே'); INSERT INTO "country" ("id", "name") VALUES ('wal', 'வாலாமோ'); INSERT INTO "country" ("id", "name") VALUES ('was', 'வாஷோ'); INSERT INTO "country" ("id", "name") VALUES ('vi', 'வியட்நாமிஸ்'); INSERT INTO "country" ("id", "name") VALUES ('ve', 'வென்டா'); INSERT INTO "country" ("id", "name") VALUES ('cy', 'வெல்ஷ்'); INSERT INTO "country" ("id", "name") VALUES ('vai', 'வை'); INSERT INTO "country" ("id", "name") VALUES ('vot', 'வோட்க்'); INSERT INTO "country" ("id", "name") VALUES ('chg', 'ஷகதை'); INSERT INTO "country" ("id", "name") VALUES ('shn', 'ஷான்'); INSERT INTO "country" ("id", "name") VALUES ('sv', 'ஷீவிடிஸ்'); INSERT INTO "country" ("id", "name") VALUES ('sn', 'ஷோனா'); INSERT INTO "country" ("id", "name") VALUES ('sm', 'ஸாமோவான்'); INSERT INTO "country" ("id", "name") VALUES ('ts', 'ஸோங்கா'); INSERT INTO "country" ("id", "name") VALUES ('sco', 'ஸ்காட்ஸ்'); INSERT INTO "country" ("id", "name") VALUES ('gd', 'ஸ்காட்ஸ் கேலிக்'); INSERT INTO "country" ("id", "name") VALUES ('sms', 'ஸ்கோல்ட் சாமி'); INSERT INTO "country" ("id", "name") VALUES ('es', 'ஸ்பேனிஷ்'); INSERT INTO "country" ("id", "name") VALUES ('srn', 'ஸ்ரானன் டோங்கோ'); INSERT INTO "country" ("id", "name") VALUES ('sla', 'ஸ்லாவிக் மொழி'); INSERT INTO "country" ("id", "name") VALUES ('den', 'ஸ்லாவ்'); INSERT INTO "country" ("id", "name") VALUES ('sk', 'ஸ்லோவாக்'); INSERT INTO "country" ("id", "name") VALUES ('sl', 'ஸ்லோவினேயின்'); INSERT INTO "country" ("id", "name") VALUES ('ss', 'ஸ்வாடீ'); INSERT INTO "country" ("id", "name") VALUES ('tn', 'ஸ்வானா'); INSERT INTO "country" ("id", "name") VALUES ('gsw', 'ஸ்விஸ் ஜெர்மன்'); INSERT INTO "country" ("id", "name") VALUES ('hu', 'ஹங்கேரியன்'); INSERT INTO "country" ("id", "name") VALUES ('haw', 'ஹவாய்யான்'); INSERT INTO "country" ("id", "name") VALUES ('hit', 'ஹிட்டைட்'); INSERT INTO "country" ("id", "name") VALUES ('him', 'ஹிமாச்சலி'); INSERT INTO "country" ("id", "name") VALUES ('ho', 'ஹிரி மோட்டு'); INSERT INTO "country" ("id", "name") VALUES ('hil', 'ஹிலிகாய்னான்'); INSERT INTO "country" ("id", "name") VALUES ('hup', 'ஹுபா'); INSERT INTO "country" ("id", "name") VALUES ('he', 'ஹுப்ரு'); INSERT INTO "country" ("id", "name") VALUES ('hz', 'ஹெரேரோ'); INSERT INTO "country" ("id", "name") VALUES ('hai', 'ஹைடா'); INSERT INTO "country" ("id", "name") VALUES ('ht', 'ஹைத்தியன்'); INSERT INTO "country" ("id", "name") VALUES ('xh', 'ஹோஷா'); INSERT INTO "country" ("id", "name") VALUES ('ha', 'ஹௌஸா');
JumpLink/country-list
country/cldr/ta_IN/language.sqlite.sql
SQL
mit
41,322
import Koa from 'koa'; import convert from 'koa-convert'; import webpack from 'webpack'; import webpackConfig from '../build/webpack.config'; import historyApiFallback from 'koa-connect-history-api-fallback'; import serve from 'koa-static'; import _debug from 'debug'; import config from '../config'; import webpackProxyMiddleware from './middleware/webpack-proxy'; import webpackDevMiddleware from './middleware/webpack-dev'; import webpackHMRMiddleware from './middleware/webpack-hmr'; const debug = _debug('app:server'); const paths = config.utils_paths; const app = new Koa(); // This rewrites all routes requests to the root /index.html file // (ignoring file requests). If you want to implement isomorphic // rendering, you'll want to remove this middleware. app.use(convert(historyApiFallback({ verbose: false }))); // ------------------------------------ // Apply Webpack HMR Middleware // ------------------------------------ if (config.env === 'development') { const compiler = webpack(webpackConfig); // Enable webpack-dev and webpack-hot middleware const { publicPath } = webpackConfig.output; if (config.proxy && config.proxy.enabled) { const options = config.proxy.options; app.use(convert(webpackProxyMiddleware(options))); } app.use(webpackDevMiddleware(compiler, publicPath)); app.use(webpackHMRMiddleware(compiler)); // Serve static assets from ~/src/static since Webpack is unaware of // these files. This middleware doesn't need to be enabled outside // of development since this directory will be copied into ~/dist // when the application is compiled. app.use(convert(serve(paths.client('static')))); } else { debug( 'Server is being run outside of live development mode. This starter kit ' + 'does not provide any production-ready server functionality. To learn ' + 'more about deployment strategies, check out the "deployment" section ' + 'in the README.' ); // Serving ~/dist by default. Ideally these files should be served by // the web server and not the app server, but this helps to demo the // server in production. app.use(convert(serve(paths.base(config.dir_dist)))); } export default app;
magnusbae/laughing-octo-eureka
server/main.js
JavaScript
mit
2,194
module.exports = require("core-js/library/fn/string/trim");
Skillupco/babel
packages/babel-runtime/core-js/string/trim.js
JavaScript
mit
59
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Microsoft.Data.OData.Query { #region Namespaces using System.Collections.Generic; using System.Diagnostics; #endregion Namespaces /// <summary> /// Helper methods for working with query options. /// </summary> internal static class QueryOptionUtils { /// <summary> /// Returns a query option value by its name and removes the query option from the <paramref name="queryOptions"/> collection. /// </summary> /// <param name="queryOptions">The collection of query options.</param> /// <param name="queryOptionName">The name of the query option to get.</param> /// <returns>The value of the query option or null if no such query option exists.</returns> internal static string GetQueryOptionValueAndRemove(this List<QueryOptionQueryToken> queryOptions, string queryOptionName) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(queryOptions != null, "queryOptions != null"); Debug.Assert(queryOptionName == null || queryOptionName.Length > 0, "queryOptionName == null || queryOptionName.Length > 0"); QueryOptionQueryToken option = null; for (int i = 0; i < queryOptions.Count; ++i) { if (queryOptions[i].Name == queryOptionName) { if (option == null) { option = queryOptions[i]; } else { throw new ODataException(Strings.QueryOptionUtils_QueryParameterMustBeSpecifiedOnce(queryOptionName)); } queryOptions.RemoveAt(i); i--; } } return option == null ? null : option.Value; } } }
BrightstarDB/odata-sparql
ODataLib/ODataContrib/Silverlight/Microsoft/Data/OData/Query/QueryOptionUtils.cs
C#
mit
2,476
<!DOCTYPE html> <html> <head> {% include _head.html %} </head> <body> {% include _navigation.html %} {{ content }} <footer class="site-footer"> <div class="container"> {% include _footer.html %} </div> </footer> {% include _scripts.html %} </body> </html>
Materials-Informatics-Class-Fall2014/MIC-Machining-Gradients
_layouts/base.html
HTML
mit
286
/* * Copyright 2013 Google Inc. * Copyright 2014-2016 the libsecp256k1 contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoin; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.math.BigInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import static org.bitcoin.NativeSecp256k1Util.*; /** * <p>This class holds native methods to handle ECDSA verification.</p> * * <p>You can find an example library that can be used for this at https://github.com/bitcoin/secp256k1</p> * * <p>To build secp256k1 for use with bitcoinj, run * `./configure --enable-jni --enable-experimental --enable-module-ecdh` * and `make` then copy `.libs/libsecp256k1.so` to your system library path * or point the JVM to the folder containing it with -Djava.library.path * </p> */ public class NativeSecp256k1 { private static final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); private static final Lock r = rwl.readLock(); private static final Lock w = rwl.writeLock(); private static ThreadLocal<ByteBuffer> nativeByteBuffer = new ThreadLocal<ByteBuffer>(); /** * Verifies the given secp256k1 signature in native code. * Calling when enabled == false is undefined (probably library not loaded) * * @param data The data which was signed, must be exactly 32 bytes * @param signature The signature * @param pub The public key which did the signing */ public static boolean verify(byte[] data, byte[] signature, byte[] pub) { checkArgument(data.length == 32 && signature.length <= 520 && pub.length <= 520); ByteBuffer byteBuff = nativeByteBuffer.get(); if (byteBuff == null || byteBuff.capacity() < 520) { byteBuff = ByteBuffer.allocateDirect(520); byteBuff.order(ByteOrder.nativeOrder()); nativeByteBuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(data); byteBuff.put(signature); byteBuff.put(pub); r.lock(); try { return secp256k1_ecdsa_verify(byteBuff, Secp256k1Context.getContext(), signature.length, pub.length) == 1; } finally { r.unlock(); } } /** * libsecp256k1 Create an ECDSA signature. * * @param data Message hash, 32 bytes * @param key Secret key, 32 bytes * * Return values * @param sig byte array of signature */ public static byte[] sign(byte[] data, byte[] sec) throws AssertFailException{ checkArgument(data.length == 32 && sec.length <= 32); ByteBuffer byteBuff = nativeByteBuffer.get(); if (byteBuff == null || byteBuff.capacity() < 32 + 32) { byteBuff = ByteBuffer.allocateDirect(32 + 32); byteBuff.order(ByteOrder.nativeOrder()); nativeByteBuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(data); byteBuff.put(sec); byte[][] retByteArray; r.lock(); try { retByteArray = secp256k1_ecdsa_sign(byteBuff, Secp256k1Context.getContext()); } finally { r.unlock(); } byte[] sigArr = retByteArray[0]; int sigLen = new BigInteger(new byte[] { retByteArray[1][0] }).intValue(); int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue(); assertEquals(sigArr.length, sigLen, "Got bad signature length."); return retVal == 0 ? new byte[0] : sigArr; } /** * libsecp256k1 Seckey Verify - returns 1 if valid, 0 if invalid * * @param seckey ECDSA Secret key, 32 bytes */ public static boolean secKeyVerify(byte[] seckey) { checkArgument(seckey.length == 32); ByteBuffer byteBuff = nativeByteBuffer.get(); if (byteBuff == null || byteBuff.capacity() < seckey.length) { byteBuff = ByteBuffer.allocateDirect(seckey.length); byteBuff.order(ByteOrder.nativeOrder()); nativeByteBuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(seckey); r.lock(); try { return secp256k1_ec_seckey_verify(byteBuff,Secp256k1Context.getContext()) == 1; } finally { r.unlock(); } } /** * libsecp256k1 Compute Pubkey - computes public key from secret key * * @param seckey ECDSA Secret key, 32 bytes * * Return values * @param pubkey ECDSA Public key, 33 or 65 bytes */ //TODO add a 'compressed' arg public static byte[] computePubkey(byte[] seckey) throws AssertFailException{ checkArgument(seckey.length == 32); ByteBuffer byteBuff = nativeByteBuffer.get(); if (byteBuff == null || byteBuff.capacity() < seckey.length) { byteBuff = ByteBuffer.allocateDirect(seckey.length); byteBuff.order(ByteOrder.nativeOrder()); nativeByteBuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(seckey); byte[][] retByteArray; r.lock(); try { retByteArray = secp256k1_ec_pubkey_create(byteBuff, Secp256k1Context.getContext()); } finally { r.unlock(); } byte[] pubArr = retByteArray[0]; int pubLen = new BigInteger(new byte[] { retByteArray[1][0] }).intValue(); int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue(); assertEquals(pubArr.length, pubLen, "Got bad pubkey length."); return retVal == 0 ? new byte[0]: pubArr; } /** * libsecp256k1 Cleanup - This destroys the secp256k1 context object * This should be called at the end of the program for proper cleanup of the context. */ public static synchronized void cleanup() { w.lock(); try { secp256k1_destroy_context(Secp256k1Context.getContext()); } finally { w.unlock(); } } public static long cloneContext() { r.lock(); try { return secp256k1_ctx_clone(Secp256k1Context.getContext()); } finally { r.unlock(); } } /** * libsecp256k1 PrivKey Tweak-Mul - Tweak privkey by multiplying to it * * @param tweak some bytes to tweak with * @param seckey 32-byte seckey */ public static byte[] privKeyTweakMul(byte[] privkey, byte[] tweak) throws AssertFailException{ checkArgument(privkey.length == 32); ByteBuffer byteBuff = nativeByteBuffer.get(); if (byteBuff == null || byteBuff.capacity() < privkey.length + tweak.length) { byteBuff = ByteBuffer.allocateDirect(privkey.length + tweak.length); byteBuff.order(ByteOrder.nativeOrder()); nativeByteBuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(privkey); byteBuff.put(tweak); byte[][] retByteArray; r.lock(); try { retByteArray = secp256k1_privkey_tweak_mul(byteBuff,Secp256k1Context.getContext()); } finally { r.unlock(); } byte[] privArr = retByteArray[0]; int privLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF; int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue(); assertEquals(privArr.length, privLen, "Got bad pubkey length."); assertEquals(retVal, 1, "Failed return value check."); return privArr; } /** * libsecp256k1 PrivKey Tweak-Add - Tweak privkey by adding to it * * @param tweak some bytes to tweak with * @param seckey 32-byte seckey */ public static byte[] privKeyTweakAdd(byte[] privkey, byte[] tweak) throws AssertFailException{ checkArgument(privkey.length == 32); ByteBuffer byteBuff = nativeByteBuffer.get(); if (byteBuff == null || byteBuff.capacity() < privkey.length + tweak.length) { byteBuff = ByteBuffer.allocateDirect(privkey.length + tweak.length); byteBuff.order(ByteOrder.nativeOrder()); nativeByteBuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(privkey); byteBuff.put(tweak); byte[][] retByteArray; r.lock(); try { retByteArray = secp256k1_privkey_tweak_add(byteBuff,Secp256k1Context.getContext()); } finally { r.unlock(); } byte[] privArr = retByteArray[0]; int privLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF; int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue(); assertEquals(privArr.length, privLen, "Got bad pubkey length."); assertEquals(retVal, 1, "Failed return value check."); return privArr; } /** * libsecp256k1 PubKey Tweak-Add - Tweak pubkey by adding to it * * @param tweak some bytes to tweak with * @param pubkey 32-byte seckey */ public static byte[] pubKeyTweakAdd(byte[] pubkey, byte[] tweak) throws AssertFailException{ checkArgument(pubkey.length == 33 || pubkey.length == 65); ByteBuffer byteBuff = nativeByteBuffer.get(); if (byteBuff == null || byteBuff.capacity() < pubkey.length + tweak.length) { byteBuff = ByteBuffer.allocateDirect(pubkey.length + tweak.length); byteBuff.order(ByteOrder.nativeOrder()); nativeByteBuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(pubkey); byteBuff.put(tweak); byte[][] retByteArray; r.lock(); try { retByteArray = secp256k1_pubkey_tweak_add(byteBuff,Secp256k1Context.getContext(), pubkey.length); } finally { r.unlock(); } byte[] pubArr = retByteArray[0]; int pubLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF; int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue(); assertEquals(pubArr.length, pubLen, "Got bad pubkey length."); assertEquals(retVal, 1, "Failed return value check."); return pubArr; } /** * libsecp256k1 PubKey Tweak-Mul - Tweak pubkey by multiplying to it * * @param tweak some bytes to tweak with * @param pubkey 32-byte seckey */ public static byte[] pubKeyTweakMul(byte[] pubkey, byte[] tweak) throws AssertFailException{ checkArgument(pubkey.length == 33 || pubkey.length == 65); ByteBuffer byteBuff = nativeByteBuffer.get(); if (byteBuff == null || byteBuff.capacity() < pubkey.length + tweak.length) { byteBuff = ByteBuffer.allocateDirect(pubkey.length + tweak.length); byteBuff.order(ByteOrder.nativeOrder()); nativeByteBuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(pubkey); byteBuff.put(tweak); byte[][] retByteArray; r.lock(); try { retByteArray = secp256k1_pubkey_tweak_mul(byteBuff,Secp256k1Context.getContext(), pubkey.length); } finally { r.unlock(); } byte[] pubArr = retByteArray[0]; int pubLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF; int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue(); assertEquals(pubArr.length, pubLen, "Got bad pubkey length."); assertEquals(retVal, 1, "Failed return value check."); return pubArr; } /** * libsecp256k1 create ECDH secret - constant time ECDH calculation * * @param seckey byte array of secret key used in exponentiaion * @param pubkey byte array of public key used in exponentiaion */ public static byte[] createECDHSecret(byte[] seckey, byte[] pubkey) throws AssertFailException{ checkArgument(seckey.length <= 32 && pubkey.length <= 65); ByteBuffer byteBuff = nativeByteBuffer.get(); if (byteBuff == null || byteBuff.capacity() < 32 + pubkey.length) { byteBuff = ByteBuffer.allocateDirect(32 + pubkey.length); byteBuff.order(ByteOrder.nativeOrder()); nativeByteBuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(seckey); byteBuff.put(pubkey); byte[][] retByteArray; r.lock(); try { retByteArray = secp256k1_ecdh(byteBuff, Secp256k1Context.getContext(), pubkey.length); } finally { r.unlock(); } byte[] resArr = retByteArray[0]; int retVal = new BigInteger(new byte[] { retByteArray[1][0] }).intValue(); assertEquals(resArr.length, 32, "Got bad result length."); assertEquals(retVal, 1, "Failed return value check."); return resArr; } /** * libsecp256k1 randomize - updates the context randomization * * @param seed 32-byte random seed */ public static synchronized boolean randomize(byte[] seed) throws AssertFailException{ checkArgument(seed.length == 32 || seed == null); ByteBuffer byteBuff = nativeByteBuffer.get(); if (byteBuff == null || byteBuff.capacity() < seed.length) { byteBuff = ByteBuffer.allocateDirect(seed.length); byteBuff.order(ByteOrder.nativeOrder()); nativeByteBuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(seed); w.lock(); try { return secp256k1_context_randomize(byteBuff, Secp256k1Context.getContext()) == 1; } finally { w.unlock(); } } /** * libsecp256k1 Create a Schnorr signature. * * @param data Message hash, 32 bytes * @param seckey Secret key, 32 bytes * @return sig byte array of signature */ public static byte[] schnorrSign(byte[] data, byte[] seckey) throws AssertFailException { checkArgument(data.length == 32 && seckey.length <= 32); ByteBuffer byteBuff = nativeByteBuffer.get(); if (byteBuff == null || byteBuff.capacity() < data.length + seckey.length) { byteBuff = ByteBuffer.allocateDirect(32 + 32); byteBuff.order(ByteOrder.nativeOrder()); nativeByteBuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(data); byteBuff.put(seckey); byte[][] retByteArray; r.lock(); try { retByteArray = secp256k1_schnorr_sign(byteBuff, Secp256k1Context.getContext()); } finally { r.unlock(); } byte[] sigArr = retByteArray[0]; int retVal = new BigInteger(new byte[] { retByteArray[1][0] }).intValue(); assertEquals(sigArr.length, 64, "Got bad signature length."); return retVal == 0 ? new byte[0] : sigArr; } /** * Verifies the given Schnorr signature in native code. * Calling when enabled == false is undefined (probably library not loaded) * * @param data The data which was signed, must be exactly 32 bytes * @param signature The signature is exactly 64 bytes * @param pub The public key which did the signing which is the same ECDSA */ public static boolean schnorrVerify(byte[] data, byte[] signature, byte[] pub) { checkArgument(data.length == 32 && signature.length == 64 && (pub.length == 33 || pub.length == 65)); ByteBuffer byteBuff = nativeByteBuffer.get(); if (byteBuff == null || byteBuff.capacity() < 32 + 64 + pub.length) { byteBuff = ByteBuffer.allocateDirect(32 + 64 + pub.length); byteBuff.order(ByteOrder.nativeOrder()); nativeByteBuffer.set(byteBuff); } byteBuff.rewind(); byteBuff.put(data); byteBuff.put(signature); byteBuff.put(pub); r.lock(); try { return secp256k1_schnorr_verify(byteBuff, Secp256k1Context.getContext(), pub.length) == 1; } finally { r.unlock(); } } private static native long secp256k1_ctx_clone(long context); private static native int secp256k1_context_randomize(ByteBuffer byteBuff, long context); private static native byte[][] secp256k1_privkey_tweak_add(ByteBuffer byteBuff, long context); private static native byte[][] secp256k1_privkey_tweak_mul(ByteBuffer byteBuff, long context); private static native byte[][] secp256k1_pubkey_tweak_add(ByteBuffer byteBuff, long context, int pubLen); private static native byte[][] secp256k1_pubkey_tweak_mul(ByteBuffer byteBuff, long context, int pubLen); private static native void secp256k1_destroy_context(long context); private static native int secp256k1_ecdsa_verify(ByteBuffer byteBuff, long context, int sigLen, int pubLen); private static native byte[][] secp256k1_ecdsa_sign(ByteBuffer byteBuff, long context); private static native int secp256k1_ec_seckey_verify(ByteBuffer byteBuff, long context); private static native byte[][] secp256k1_ec_pubkey_create(ByteBuffer byteBuff, long context); private static native byte[][] secp256k1_ec_pubkey_parse(ByteBuffer byteBuff, long context, int inputLen); private static native int secp256k1_schnorr_verify(ByteBuffer byteBuff, long context, int pubLen); private static native byte[][] secp256k1_schnorr_sign(ByteBuffer byteBuff, long context); private static native byte[][] secp256k1_ecdh(ByteBuffer byteBuff, long context, int inputLen); }
ftrader-bitcoinabc/bitcoin-abc
src/secp256k1/src/java/org/bitcoin/NativeSecp256k1.java
Java
mit
18,095
// // RootViewController.h // Sample // // Created by Kirby Turner on 2/8/10. // Copyright 2010 White Peak Software Inc. All rights reserved. // #import <UIKit/UIKit.h> #import "KTThumbsViewController.h" #import "PhotoPickerController.h" #import "Photos.h" @class Photos; @interface LocalImageRootViewController : KTThumbsViewController <PhotoPickerControllerDelegate, PhotosDelegate> { PhotoPickerController *photoPicker_; Photos *myPhotos_; UIActivityIndicatorView *activityIndicatorView_; UIWindow *window_; } - (id)initWithWindow:(UIWindow *)window; @end
0359xiaodong/KTPhotoBrowser
src/TabBarSample/Classes/LocalImageSample/LocalImageRootViewController.h
C
mit
581
<!doctype html> <html> <head> <title>LycheeJS Discovery Suite</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <!-- required for build process --> <script src="../../lychee/core.js"></script> <script src="../../lychee/Builder.js"></script> <script src="../../lychee/Preloader.js"></script> <!-- platform-specific bootstrapping --> <script src="../../lychee/platform/html/bootstrap.js"></script> <script src="../../lychee/platform/html/bootstrap.progress.js"></script> <link rel="stylesheet" href="../../lychee/platform/html/bootstrap.progress.css"> <!-- build start --> <script src="./source/Main.js"></script> <link rel="stylesheet" href="./source/Main.css"> </head> <body> <script src="init.js"></script> </body> </html>
nspforever/lycheeJS
game/discovery/index.html
HTML
mit
1,026
from app import celery from flask import current_app as app from datetime import timedelta from celery.decorators import periodic_task from flask import jsonify, request, abort import requests import json @periodic_task(run_every=(timedelta(seconds=1))) def ping(): print "ping!" headers = {'content-type': 'application/json'} response = requests.post("http://localhost:9000" + "/send_ping", headers=headers, data=json.dumps({})) r = json.loads(response.text) if r['success'] is True: print r['server_views']
darksigma/traceless
slave/app/async/routes.py
Python
mit
537
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Validate * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @namespace */ namespace Zend\Validator\Barcode; /** * @uses \Zend\Validator\Barcode\AbstractAdapter * @category Zend * @package Zend_Validate * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Ean5 extends AbstractAdapter { /** * Constructor * * Sets check flag to false. * * @return void */ public function __construct() { $this->setLength(5); $this->setCharacters('0123456789'); $this->useChecksum(false); } }
buzzengine/buzzengine
vendor/zend-framework/library/Zend/Validator/Barcode/Ean5.php
PHP
mit
1,311
import { CRUD_GET_LIST_SUCCESS } from '../../../actions/dataActions'; export default resource => (previousState = 0, { type, payload, meta }) => { if (!meta || meta.resource !== resource) { return previousState; } if (type === CRUD_GET_LIST_SUCCESS) { return payload.total; } return previousState; };
RestUI/rest-ui
src/redux/reducer/resource/list/total.js
JavaScript
mit
338
require 'rails_helper' if Rails::VERSION::MAJOR >= 5 field_name = field_name_from __FILE__ type = type_from __FILE__ describe field_name do it_behaves_like \ "#{type} partial", field_name, value: '((1,2),(3,4))', input_selector: '.form-group input' end end
reinteractive-open/wallaby
spec/views/wallaby/resources/form/_polygon.html.erb_spec.rb
Ruby
mit
288
<!DOCTYPE html> <html lang="en"> <head> <title>Protocols Reference</title> <link rel="stylesheet" type="text/css" href="css/jazzy.css" /> <link rel="stylesheet" type="text/css" href="css/highlight.css" /> <meta charset='utf-8'> <script src="js/jquery.min.js" defer></script> <script src="js/jazzy.js" defer></script> </head> <body> <a title="Protocols Reference"></a> <header> <div class="content-wrapper"> <p><a href="index.html">StravaKit Docs</a> (32% documented)</p> <p class="header-right"><a href="https://github.com/StravaKit/StravaKit"><img src="img/gh.png"/>View on GitHub</a></p> <p class="header-right"><a href="dash-feed://http%3A%2F%2Fcocoadocs%2Eorg%2Fdocsets%2FStravaKit%2F0%2E8%2E0%2Fdocsets%2FStravaKit%2Exml"><img src="img/dash.png"/>Install in Dash</a></p> </div> </header> <div class="content-wrapper"> <p id="breadcrumbs"> <a href="index.html">StravaKit Reference</a> <img id="carat" src="img/carat.png" /> Protocols Reference </p> </div> <div class="content-wrapper"> <nav class="sidebar"> <ul class="nav-groups"> <li class="nav-group-name"> <a href="Classes.html">Classes</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="Classes/DefaultRequestor.html">DefaultRequestor</a> </li> <li class="nav-group-task"> <a href="Classes/Strava.html">Strava</a> </li> </ul> </li> <li class="nav-group-name"> <a href="Global Variables.html">Global Variables</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="Global Variables.html#/s:v9StravaKit7PageKeySS">PageKey</a> </li> <li class="nav-group-task"> <a href="Global Variables.html#/s:v9StravaKit10PerPageKeySS">PerPageKey</a> </li> <li class="nav-group-task"> <a href="Global Variables.html#/s:v9StravaKit23RateLimitLimitHeaderKeySS">RateLimitLimitHeaderKey</a> </li> <li class="nav-group-task"> <a href="Global Variables.html#/s:v9StravaKit17RateLimitLimitKeySS">RateLimitLimitKey</a> </li> <li class="nav-group-task"> <a href="Global Variables.html#/s:v9StravaKit23RateLimitUsageHeaderKeySS">RateLimitUsageHeaderKey</a> </li> <li class="nav-group-task"> <a href="Global Variables.html#/s:v9StravaKit17RateLimitUsageKeySS">RateLimitUsageKey</a> </li> <li class="nav-group-task"> <a href="Global Variables.html#/s:v9StravaKit40StravaAuthorizationCompletedNotificationSS">StravaAuthorizationCompletedNotification</a> </li> <li class="nav-group-task"> <a href="Global Variables.html#/s:v9StravaKit13StravaBaseURLSS">StravaBaseURL</a> </li> <li class="nav-group-task"> <a href="Global Variables.html#/s:v9StravaKit17StravaErrorDomainSS">StravaErrorDomain</a> </li> <li class="nav-group-task"> <a href="Global Variables.html#/s:v9StravaKit14StravaErrorKeySS">StravaErrorKey</a> </li> <li class="nav-group-task"> <a href="Global Variables.html#/s:v9StravaKit24StravaStatusFailureValueSS">StravaStatusFailureValue</a> </li> <li class="nav-group-task"> <a href="Global Variables.html#/s:v9StravaKit15StravaStatusKeySS">StravaStatusKey</a> </li> <li class="nav-group-task"> <a href="Global Variables.html#/s:v9StravaKit24StravaStatusSuccessValueSS">StravaStatusSuccessValue</a> </li> </ul> </li> <li class="nav-group-name"> <a href="Enums.html">Enums</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="Enums/HTTPMethod.html">HTTPMethod</a> </li> <li class="nav-group-task"> <a href="Enums/OAuthScope.html">OAuthScope</a> </li> <li class="nav-group-task"> <a href="Enums/StravaErrorCode.html">StravaErrorCode</a> </li> </ul> </li> <li class="nav-group-name"> <a href="Functions.html">Functions</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="Functions.html#/s:F9StravaKit12decodeLevelsFSSGSqGSaVs6UInt32__">decodeLevels(_:)</a> </li> <li class="nav-group-task"> <a href="Functions.html#/s:F9StravaKit14decodePolylineFTSS9precisionSd_GSqGSaCSo10CLLocation__">decodePolyline(_:precision:)</a> </li> <li class="nav-group-task"> <a href="Functions.html#/s:F9StravaKit14decodePolylineFTSS9precisionSd_GSqGSaVSC22CLLocationCoordinate2D__">decodePolyline(_:precision:)</a> </li> <li class="nav-group-task"> <a href="Functions.html#/s:F9StravaKit17encodeCoordinatesFTGSaVSC22CLLocationCoordinate2D_9precisionSd_SS">encodeCoordinates(_:precision:)</a> </li> <li class="nav-group-task"> <a href="Functions.html#/s:F9StravaKit12encodeLevelsFGSaVs6UInt32_SS">encodeLevels(_:)</a> </li> <li class="nav-group-task"> <a href="Functions.html#/s:F9StravaKit15encodeLocationsFTGSaCSo10CLLocation_9precisionSd_SS">encodeLocations(_:precision:)</a> </li> </ul> </li> <li class="nav-group-name"> <a href="Protocols.html">Protocols</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="Protocols/Requestor.html">Requestor</a> </li> </ul> </li> <li class="nav-group-name"> <a href="Structs.html">Structs</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="Structs/Activity.html">Activity</a> </li> <li class="nav-group-task"> <a href="Structs/Athlete.html">Athlete</a> </li> <li class="nav-group-task"> <a href="Structs/Club.html">Club</a> </li> <li class="nav-group-task"> <a href="Structs/Leaderboard.html">Leaderboard</a> </li> <li class="nav-group-task"> <a href="Structs/LeaderboardEntry.html">LeaderboardEntry</a> </li> <li class="nav-group-task"> <a href="Structs/Map.html">Map</a> </li> <li class="nav-group-task"> <a href="Structs/MapBounds.html">MapBounds</a> </li> <li class="nav-group-task"> <a href="Structs.html#/s:V9StravaKit4Page">Page</a> </li> <li class="nav-group-task"> <a href="Structs/Photo.html">Photo</a> </li> <li class="nav-group-task"> <a href="Structs.html#/s:V9StravaKit8PhotoURL">PhotoURL</a> </li> <li class="nav-group-task"> <a href="Structs/Polyline.html">Polyline</a> </li> <li class="nav-group-task"> <a href="Structs/ResourceSummary.html">ResourceSummary</a> </li> <li class="nav-group-task"> <a href="Structs/Route.html">Route</a> </li> <li class="nav-group-task"> <a href="Structs/Segment.html">Segment</a> </li> <li class="nav-group-task"> <a href="Structs/SegmentEffort.html">SegmentEffort</a> </li> <li class="nav-group-task"> <a href="Structs/SegmentStats.html">SegmentStats</a> </li> <li class="nav-group-task"> <a href="Structs/Stats.html">Stats</a> </li> <li class="nav-group-task"> <a href="Structs/StatsDetail.html">StatsDetail</a> </li> <li class="nav-group-task"> <a href="Structs/Zone.html">Zone</a> </li> <li class="nav-group-task"> <a href="Structs/ZoneCollection.html">ZoneCollection</a> </li> <li class="nav-group-task"> <a href="Structs/Zones.html">Zones</a> </li> </ul> </li> <li class="nav-group-name"> <a href="Typealiases.html">Typealiases</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="Typealiases.html#/s:9StravaKit9JSONArray">JSONArray</a> </li> <li class="nav-group-task"> <a href="Typealiases.html#/s:9StravaKit14JSONDictionary">JSONDictionary</a> </li> <li class="nav-group-task"> <a href="Typealiases.html#/s:9StravaKit16ParamsDictionary">ParamsDictionary</a> </li> </ul> </li> </ul> </nav> <article class="main-content"> <section> <section class="section"> <h1>Protocols</h1> <p>The following protocols are available globally.</p> </section> <section class="section task-group-section"> <div class="task-group"> <ul> <li class="item"> <div> <code> <a name="/s:P9StravaKit9Requestor"></a> <a name="//apple_ref/swift/Protocol/Requestor" class="dashAnchor"></a> <a class="token" href="#/s:P9StravaKit9Requestor">Requestor</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Requestor protocol used to allow for default and custom requestor instances.</p> <a href="Protocols/Requestor.html" class="slightly-smaller">See more</a> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">protocol</span> <span class="kt">Requestor</span></code></pre> </div> </div> </section> </div> </li> </ul> </div> </section> </section> <section id="footer"> <p>&copy; 2017 <a class="link" href="https://github.com/StravaKit/StravaKit" target="_blank" rel="external">StravaKit</a>. All rights reserved. (Last updated: 2017-02-16)</p> <p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.7.2</a>, a <a class="link" href="http://realm.io" target="_blank" rel="external">Realm</a> project.</p> </section> </article> </div> </body> </div> </html>
StravaKit/StravaKit
Documentation/docsets/StravaKit.docset/Contents/Resources/Documents/Protocols.html
HTML
mit
11,913
from django.conf.urls import patterns, url urlpatterns = patterns( '', url(r'^$', 'whatify.views.index'), url(r'^search/(.+)$', 'whatify.views.search'), url(r'^torrent_groups/(\d+)$', 'whatify.views.get_torrent_group'), url(r'^torrent_groups/(\d+)/download$', 'whatify.views.download_torrent_group'), url(r'^torrent_groups/random$', 'whatify.views.random_torrent_groups'), url(r'^torrent_groups/top10$', 'whatify.views.top10_torrent_groups'), url(r'^artists/(\d+)$', 'whatify.views.get_artist'), )
grandmasterchef/WhatManager2
whatify/urls.py
Python
mit
531
import { newE2EPage } from '@stencil/core/testing'; test('select: standalone', async () => { const page = await newE2EPage({ url: '/src/components/select/test/standalone?ionic:_testing=true' }); const compare = await page.compareScreenshot(); expect(compare).toMatchScreenshot(); });
driftyco/ionic
core/src/components/select/test/standalone/e2e.ts
TypeScript
mit
298
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Code generated by gapic-generator. DO NOT EDIT. package scheduler import ( "context" "flag" "fmt" "io" "log" "net" "os" "strings" "testing" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes" emptypb "github.com/golang/protobuf/ptypes/empty" "google.golang.org/api/option" schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1" field_maskpb "google.golang.org/genproto/protobuf/field_mask" status "google.golang.org/genproto/googleapis/rpc/status" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" gstatus "google.golang.org/grpc/status" ) var _ = io.EOF var _ = ptypes.MarshalAny var _ status.Status type mockCloudSchedulerServer struct { // Embed for forward compatibility. // Tests will keep working if more methods are added // in the future. schedulerpb.CloudSchedulerServer reqs []proto.Message // If set, all calls return this error. err error // responses to return if err == nil resps []proto.Message } func (s *mockCloudSchedulerServer) ListJobs(ctx context.Context, req *schedulerpb.ListJobsRequest) (*schedulerpb.ListJobsResponse, error) { md, _ := metadata.FromIncomingContext(ctx) if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) } s.reqs = append(s.reqs, req) if s.err != nil { return nil, s.err } return s.resps[0].(*schedulerpb.ListJobsResponse), nil } func (s *mockCloudSchedulerServer) GetJob(ctx context.Context, req *schedulerpb.GetJobRequest) (*schedulerpb.Job, error) { md, _ := metadata.FromIncomingContext(ctx) if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) } s.reqs = append(s.reqs, req) if s.err != nil { return nil, s.err } return s.resps[0].(*schedulerpb.Job), nil } func (s *mockCloudSchedulerServer) CreateJob(ctx context.Context, req *schedulerpb.CreateJobRequest) (*schedulerpb.Job, error) { md, _ := metadata.FromIncomingContext(ctx) if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) } s.reqs = append(s.reqs, req) if s.err != nil { return nil, s.err } return s.resps[0].(*schedulerpb.Job), nil } func (s *mockCloudSchedulerServer) UpdateJob(ctx context.Context, req *schedulerpb.UpdateJobRequest) (*schedulerpb.Job, error) { md, _ := metadata.FromIncomingContext(ctx) if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) } s.reqs = append(s.reqs, req) if s.err != nil { return nil, s.err } return s.resps[0].(*schedulerpb.Job), nil } func (s *mockCloudSchedulerServer) DeleteJob(ctx context.Context, req *schedulerpb.DeleteJobRequest) (*emptypb.Empty, error) { md, _ := metadata.FromIncomingContext(ctx) if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) } s.reqs = append(s.reqs, req) if s.err != nil { return nil, s.err } return s.resps[0].(*emptypb.Empty), nil } func (s *mockCloudSchedulerServer) PauseJob(ctx context.Context, req *schedulerpb.PauseJobRequest) (*schedulerpb.Job, error) { md, _ := metadata.FromIncomingContext(ctx) if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) } s.reqs = append(s.reqs, req) if s.err != nil { return nil, s.err } return s.resps[0].(*schedulerpb.Job), nil } func (s *mockCloudSchedulerServer) ResumeJob(ctx context.Context, req *schedulerpb.ResumeJobRequest) (*schedulerpb.Job, error) { md, _ := metadata.FromIncomingContext(ctx) if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) } s.reqs = append(s.reqs, req) if s.err != nil { return nil, s.err } return s.resps[0].(*schedulerpb.Job), nil } func (s *mockCloudSchedulerServer) RunJob(ctx context.Context, req *schedulerpb.RunJobRequest) (*schedulerpb.Job, error) { md, _ := metadata.FromIncomingContext(ctx) if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) } s.reqs = append(s.reqs, req) if s.err != nil { return nil, s.err } return s.resps[0].(*schedulerpb.Job), nil } // clientOpt is the option tests should use to connect to the test server. // It is initialized by TestMain. var clientOpt option.ClientOption var ( mockCloudScheduler mockCloudSchedulerServer ) func TestMain(m *testing.M) { flag.Parse() serv := grpc.NewServer() schedulerpb.RegisterCloudSchedulerServer(serv, &mockCloudScheduler) lis, err := net.Listen("tcp", "localhost:0") if err != nil { log.Fatal(err) } go serv.Serve(lis) conn, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure()) if err != nil { log.Fatal(err) } clientOpt = option.WithGRPCConn(conn) os.Exit(m.Run()) } func TestCloudSchedulerListJobs(t *testing.T) { var nextPageToken string = "" var jobsElement *schedulerpb.Job = &schedulerpb.Job{} var jobs = []*schedulerpb.Job{jobsElement} var expectedResponse = &schedulerpb.ListJobsResponse{ NextPageToken: nextPageToken, Jobs: jobs, } mockCloudScheduler.err = nil mockCloudScheduler.reqs = nil mockCloudScheduler.resps = append(mockCloudScheduler.resps[:0], expectedResponse) var formattedParent string = fmt.Sprintf("projects/%s/locations/%s", "[PROJECT]", "[LOCATION]") var request = &schedulerpb.ListJobsRequest{ Parent: formattedParent, } c, err := NewCloudSchedulerClient(context.Background(), clientOpt) if err != nil { t.Fatal(err) } resp, err := c.ListJobs(context.Background(), request).Next() if err != nil { t.Fatal(err) } if want, got := request, mockCloudScheduler.reqs[0]; !proto.Equal(want, got) { t.Errorf("wrong request %q, want %q", got, want) } want := (interface{})(expectedResponse.Jobs[0]) got := (interface{})(resp) var ok bool switch want := (want).(type) { case proto.Message: ok = proto.Equal(want, got.(proto.Message)) default: ok = want == got } if !ok { t.Errorf("wrong response %q, want %q)", got, want) } } func TestCloudSchedulerListJobsError(t *testing.T) { errCode := codes.PermissionDenied mockCloudScheduler.err = gstatus.Error(errCode, "test error") var formattedParent string = fmt.Sprintf("projects/%s/locations/%s", "[PROJECT]", "[LOCATION]") var request = &schedulerpb.ListJobsRequest{ Parent: formattedParent, } c, err := NewCloudSchedulerClient(context.Background(), clientOpt) if err != nil { t.Fatal(err) } resp, err := c.ListJobs(context.Background(), request).Next() if st, ok := gstatus.FromError(err); !ok { t.Errorf("got error %v, expected grpc error", err) } else if c := st.Code(); c != errCode { t.Errorf("got error code %q, want %q", c, errCode) } _ = resp } func TestCloudSchedulerGetJob(t *testing.T) { var name2 string = "name2-1052831874" var description string = "description-1724546052" var schedule string = "schedule-697920873" var timeZone string = "timeZone36848094" var expectedResponse = &schedulerpb.Job{ Name: name2, Description: description, Schedule: schedule, TimeZone: timeZone, } mockCloudScheduler.err = nil mockCloudScheduler.reqs = nil mockCloudScheduler.resps = append(mockCloudScheduler.resps[:0], expectedResponse) var formattedName string = fmt.Sprintf("projects/%s/locations/%s/jobs/%s", "[PROJECT]", "[LOCATION]", "[JOB]") var request = &schedulerpb.GetJobRequest{ Name: formattedName, } c, err := NewCloudSchedulerClient(context.Background(), clientOpt) if err != nil { t.Fatal(err) } resp, err := c.GetJob(context.Background(), request) if err != nil { t.Fatal(err) } if want, got := request, mockCloudScheduler.reqs[0]; !proto.Equal(want, got) { t.Errorf("wrong request %q, want %q", got, want) } if want, got := expectedResponse, resp; !proto.Equal(want, got) { t.Errorf("wrong response %q, want %q)", got, want) } } func TestCloudSchedulerGetJobError(t *testing.T) { errCode := codes.PermissionDenied mockCloudScheduler.err = gstatus.Error(errCode, "test error") var formattedName string = fmt.Sprintf("projects/%s/locations/%s/jobs/%s", "[PROJECT]", "[LOCATION]", "[JOB]") var request = &schedulerpb.GetJobRequest{ Name: formattedName, } c, err := NewCloudSchedulerClient(context.Background(), clientOpt) if err != nil { t.Fatal(err) } resp, err := c.GetJob(context.Background(), request) if st, ok := gstatus.FromError(err); !ok { t.Errorf("got error %v, expected grpc error", err) } else if c := st.Code(); c != errCode { t.Errorf("got error code %q, want %q", c, errCode) } _ = resp } func TestCloudSchedulerCreateJob(t *testing.T) { var name string = "name3373707" var description string = "description-1724546052" var schedule string = "schedule-697920873" var timeZone string = "timeZone36848094" var expectedResponse = &schedulerpb.Job{ Name: name, Description: description, Schedule: schedule, TimeZone: timeZone, } mockCloudScheduler.err = nil mockCloudScheduler.reqs = nil mockCloudScheduler.resps = append(mockCloudScheduler.resps[:0], expectedResponse) var formattedParent string = fmt.Sprintf("projects/%s/locations/%s", "[PROJECT]", "[LOCATION]") var job *schedulerpb.Job = &schedulerpb.Job{} var request = &schedulerpb.CreateJobRequest{ Parent: formattedParent, Job: job, } c, err := NewCloudSchedulerClient(context.Background(), clientOpt) if err != nil { t.Fatal(err) } resp, err := c.CreateJob(context.Background(), request) if err != nil { t.Fatal(err) } if want, got := request, mockCloudScheduler.reqs[0]; !proto.Equal(want, got) { t.Errorf("wrong request %q, want %q", got, want) } if want, got := expectedResponse, resp; !proto.Equal(want, got) { t.Errorf("wrong response %q, want %q)", got, want) } } func TestCloudSchedulerCreateJobError(t *testing.T) { errCode := codes.PermissionDenied mockCloudScheduler.err = gstatus.Error(errCode, "test error") var formattedParent string = fmt.Sprintf("projects/%s/locations/%s", "[PROJECT]", "[LOCATION]") var job *schedulerpb.Job = &schedulerpb.Job{} var request = &schedulerpb.CreateJobRequest{ Parent: formattedParent, Job: job, } c, err := NewCloudSchedulerClient(context.Background(), clientOpt) if err != nil { t.Fatal(err) } resp, err := c.CreateJob(context.Background(), request) if st, ok := gstatus.FromError(err); !ok { t.Errorf("got error %v, expected grpc error", err) } else if c := st.Code(); c != errCode { t.Errorf("got error code %q, want %q", c, errCode) } _ = resp } func TestCloudSchedulerUpdateJob(t *testing.T) { var name string = "name3373707" var description string = "description-1724546052" var schedule string = "schedule-697920873" var timeZone string = "timeZone36848094" var expectedResponse = &schedulerpb.Job{ Name: name, Description: description, Schedule: schedule, TimeZone: timeZone, } mockCloudScheduler.err = nil mockCloudScheduler.reqs = nil mockCloudScheduler.resps = append(mockCloudScheduler.resps[:0], expectedResponse) var job *schedulerpb.Job = &schedulerpb.Job{} var updateMask *field_maskpb.FieldMask = &field_maskpb.FieldMask{} var request = &schedulerpb.UpdateJobRequest{ Job: job, UpdateMask: updateMask, } c, err := NewCloudSchedulerClient(context.Background(), clientOpt) if err != nil { t.Fatal(err) } resp, err := c.UpdateJob(context.Background(), request) if err != nil { t.Fatal(err) } if want, got := request, mockCloudScheduler.reqs[0]; !proto.Equal(want, got) { t.Errorf("wrong request %q, want %q", got, want) } if want, got := expectedResponse, resp; !proto.Equal(want, got) { t.Errorf("wrong response %q, want %q)", got, want) } } func TestCloudSchedulerUpdateJobError(t *testing.T) { errCode := codes.PermissionDenied mockCloudScheduler.err = gstatus.Error(errCode, "test error") var job *schedulerpb.Job = &schedulerpb.Job{} var updateMask *field_maskpb.FieldMask = &field_maskpb.FieldMask{} var request = &schedulerpb.UpdateJobRequest{ Job: job, UpdateMask: updateMask, } c, err := NewCloudSchedulerClient(context.Background(), clientOpt) if err != nil { t.Fatal(err) } resp, err := c.UpdateJob(context.Background(), request) if st, ok := gstatus.FromError(err); !ok { t.Errorf("got error %v, expected grpc error", err) } else if c := st.Code(); c != errCode { t.Errorf("got error code %q, want %q", c, errCode) } _ = resp } func TestCloudSchedulerDeleteJob(t *testing.T) { var expectedResponse *emptypb.Empty = &emptypb.Empty{} mockCloudScheduler.err = nil mockCloudScheduler.reqs = nil mockCloudScheduler.resps = append(mockCloudScheduler.resps[:0], expectedResponse) var formattedName string = fmt.Sprintf("projects/%s/locations/%s/jobs/%s", "[PROJECT]", "[LOCATION]", "[JOB]") var request = &schedulerpb.DeleteJobRequest{ Name: formattedName, } c, err := NewCloudSchedulerClient(context.Background(), clientOpt) if err != nil { t.Fatal(err) } err = c.DeleteJob(context.Background(), request) if err != nil { t.Fatal(err) } if want, got := request, mockCloudScheduler.reqs[0]; !proto.Equal(want, got) { t.Errorf("wrong request %q, want %q", got, want) } } func TestCloudSchedulerDeleteJobError(t *testing.T) { errCode := codes.PermissionDenied mockCloudScheduler.err = gstatus.Error(errCode, "test error") var formattedName string = fmt.Sprintf("projects/%s/locations/%s/jobs/%s", "[PROJECT]", "[LOCATION]", "[JOB]") var request = &schedulerpb.DeleteJobRequest{ Name: formattedName, } c, err := NewCloudSchedulerClient(context.Background(), clientOpt) if err != nil { t.Fatal(err) } err = c.DeleteJob(context.Background(), request) if st, ok := gstatus.FromError(err); !ok { t.Errorf("got error %v, expected grpc error", err) } else if c := st.Code(); c != errCode { t.Errorf("got error code %q, want %q", c, errCode) } } func TestCloudSchedulerPauseJob(t *testing.T) { var name2 string = "name2-1052831874" var description string = "description-1724546052" var schedule string = "schedule-697920873" var timeZone string = "timeZone36848094" var expectedResponse = &schedulerpb.Job{ Name: name2, Description: description, Schedule: schedule, TimeZone: timeZone, } mockCloudScheduler.err = nil mockCloudScheduler.reqs = nil mockCloudScheduler.resps = append(mockCloudScheduler.resps[:0], expectedResponse) var formattedName string = fmt.Sprintf("projects/%s/locations/%s/jobs/%s", "[PROJECT]", "[LOCATION]", "[JOB]") var request = &schedulerpb.PauseJobRequest{ Name: formattedName, } c, err := NewCloudSchedulerClient(context.Background(), clientOpt) if err != nil { t.Fatal(err) } resp, err := c.PauseJob(context.Background(), request) if err != nil { t.Fatal(err) } if want, got := request, mockCloudScheduler.reqs[0]; !proto.Equal(want, got) { t.Errorf("wrong request %q, want %q", got, want) } if want, got := expectedResponse, resp; !proto.Equal(want, got) { t.Errorf("wrong response %q, want %q)", got, want) } } func TestCloudSchedulerPauseJobError(t *testing.T) { errCode := codes.PermissionDenied mockCloudScheduler.err = gstatus.Error(errCode, "test error") var formattedName string = fmt.Sprintf("projects/%s/locations/%s/jobs/%s", "[PROJECT]", "[LOCATION]", "[JOB]") var request = &schedulerpb.PauseJobRequest{ Name: formattedName, } c, err := NewCloudSchedulerClient(context.Background(), clientOpt) if err != nil { t.Fatal(err) } resp, err := c.PauseJob(context.Background(), request) if st, ok := gstatus.FromError(err); !ok { t.Errorf("got error %v, expected grpc error", err) } else if c := st.Code(); c != errCode { t.Errorf("got error code %q, want %q", c, errCode) } _ = resp } func TestCloudSchedulerResumeJob(t *testing.T) { var name2 string = "name2-1052831874" var description string = "description-1724546052" var schedule string = "schedule-697920873" var timeZone string = "timeZone36848094" var expectedResponse = &schedulerpb.Job{ Name: name2, Description: description, Schedule: schedule, TimeZone: timeZone, } mockCloudScheduler.err = nil mockCloudScheduler.reqs = nil mockCloudScheduler.resps = append(mockCloudScheduler.resps[:0], expectedResponse) var formattedName string = fmt.Sprintf("projects/%s/locations/%s/jobs/%s", "[PROJECT]", "[LOCATION]", "[JOB]") var request = &schedulerpb.ResumeJobRequest{ Name: formattedName, } c, err := NewCloudSchedulerClient(context.Background(), clientOpt) if err != nil { t.Fatal(err) } resp, err := c.ResumeJob(context.Background(), request) if err != nil { t.Fatal(err) } if want, got := request, mockCloudScheduler.reqs[0]; !proto.Equal(want, got) { t.Errorf("wrong request %q, want %q", got, want) } if want, got := expectedResponse, resp; !proto.Equal(want, got) { t.Errorf("wrong response %q, want %q)", got, want) } } func TestCloudSchedulerResumeJobError(t *testing.T) { errCode := codes.PermissionDenied mockCloudScheduler.err = gstatus.Error(errCode, "test error") var formattedName string = fmt.Sprintf("projects/%s/locations/%s/jobs/%s", "[PROJECT]", "[LOCATION]", "[JOB]") var request = &schedulerpb.ResumeJobRequest{ Name: formattedName, } c, err := NewCloudSchedulerClient(context.Background(), clientOpt) if err != nil { t.Fatal(err) } resp, err := c.ResumeJob(context.Background(), request) if st, ok := gstatus.FromError(err); !ok { t.Errorf("got error %v, expected grpc error", err) } else if c := st.Code(); c != errCode { t.Errorf("got error code %q, want %q", c, errCode) } _ = resp } func TestCloudSchedulerRunJob(t *testing.T) { var name2 string = "name2-1052831874" var description string = "description-1724546052" var schedule string = "schedule-697920873" var timeZone string = "timeZone36848094" var expectedResponse = &schedulerpb.Job{ Name: name2, Description: description, Schedule: schedule, TimeZone: timeZone, } mockCloudScheduler.err = nil mockCloudScheduler.reqs = nil mockCloudScheduler.resps = append(mockCloudScheduler.resps[:0], expectedResponse) var formattedName string = fmt.Sprintf("projects/%s/locations/%s/jobs/%s", "[PROJECT]", "[LOCATION]", "[JOB]") var request = &schedulerpb.RunJobRequest{ Name: formattedName, } c, err := NewCloudSchedulerClient(context.Background(), clientOpt) if err != nil { t.Fatal(err) } resp, err := c.RunJob(context.Background(), request) if err != nil { t.Fatal(err) } if want, got := request, mockCloudScheduler.reqs[0]; !proto.Equal(want, got) { t.Errorf("wrong request %q, want %q", got, want) } if want, got := expectedResponse, resp; !proto.Equal(want, got) { t.Errorf("wrong response %q, want %q)", got, want) } } func TestCloudSchedulerRunJobError(t *testing.T) { errCode := codes.PermissionDenied mockCloudScheduler.err = gstatus.Error(errCode, "test error") var formattedName string = fmt.Sprintf("projects/%s/locations/%s/jobs/%s", "[PROJECT]", "[LOCATION]", "[JOB]") var request = &schedulerpb.RunJobRequest{ Name: formattedName, } c, err := NewCloudSchedulerClient(context.Background(), clientOpt) if err != nil { t.Fatal(err) } resp, err := c.RunJob(context.Background(), request) if st, ok := gstatus.FromError(err); !ok { t.Errorf("got error %v, expected grpc error", err) } else if c := st.Code(); c != errCode { t.Errorf("got error code %q, want %q", c, errCode) } _ = resp }
pushbullet/engineer
vendor/cloud.google.com/go/scheduler/apiv1/mock_test.go
GO
mit
20,589
'use strict'; var grunt = require('grunt'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports.deployments = { setUp: function(done) { // setup here if necessary done(); }, default_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/default_options'); var expected = grunt.file.read('test/expected/default_options'); test.equal(actual, expected, 'should describe what the default behavior is.'); test.done(); }, custom_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/custom_options'); var expected = grunt.file.read('test/expected/custom_options'); test.equal(actual, expected, 'should describe what the custom option(s) behavior is.'); test.done(); }, };
getdave/grunt-deployments
test/deployments_test.js
JavaScript
mit
1,351
package us.codecraft.learning.automata; /** * @author code4crafter@gmail.com */ public class StringReader { class EOFException extends Exception { } private String string; private int index; public StringReader(String string) { this.string = string; } public char read() throws EOFException { if (index < string.length() - 1) { return string.charAt(index++); } else { throw new EOFException(); } } public void unread() { index--; if (index < 0) { index = 0; } } }
amikey/jsoup-learning
src/main/java/us/codecraft/learning/automata/StringReader.java
Java
mit
606
<base href="http://example.com"> <div class="vcard"> <div class="fn n"><span class="given-name">John</span> <span class="family-name">Doe</span></div> <a class="sound" href="http://www.madgex.com/johndoe.mpeg">Pronunciation of my name</a> <div><img class="photo" src="images/photo.gif" alt="Photo of John Doe" /></div> <p>Nicknames:</p> <ul> <li class="nickname">Man with no name</li> <li class="nickname">Lost boy</li> </ul> <p>About:</p> <p class="note">John Doe is one of those names you always have issues with.</p> <p class="note">It can be a real problem booking a hotel room with the name John Doe.</p> <p>Companies:</p> <div> <img class="logo" src="images/logo.gif" alt="Madgex company logo" /> <img class="logo" src="images/logo.gif" alt="Web Feet Media company logo" /> </div> <ul> <li><a class="url org" href="http://www.madgex.com/">Madgex</a> <span class="title">Creative Director</span></li> <li><a class="url org" href="http://www.webfeetmedia.com/">Web Feet Media Ltd</a> <span class="title">Owner</span></li> </ul> <p>Tags: <a rel="tag" class="category" href="http://en.wikipedia.org/wiki/design">design</a>, <a rel="tag" class="category" href="http://en.wikipedia.org/wiki/development">development</a> and <a rel="tag" class="category" href="http://en.wikipedia.org/wiki/web">web</a> </p> <p>Phone numbers:</p> <ul> <li class="tel"> <span class="type">Work</span> (<span class="type">pref</span>erred): <span class="value">+1 415 555 100</span> </li> <li class="tel"><span class="type">Home</span>: <span class="value">+1 415 555 200</span></li> <li class="tel"><span class="type">Postal</span>: <span class="value">+1 415 555 300</span></li> </ul> <p>Emails:</p> <ul> <li><a class="email" href="mailto:john.doe@madgex.com">John Doe at Madgex</a></li> <li><a class="email" href="mailto:john.doe@webfeetmedia.com">John Doe at Web Feet Media</a></li> </ul> <p>John Doe uses <span class="mailer">PigeonMail 2.1</span> or <span class="mailer">Outlook 2007</span> for email.</p> <p>Addresses:</p> <ul> <li class="label"> <span class="adr"> <span class="type">Work</span>: <span class="street-address">North Street</span>, <span class="locality">Brighton</span>, <span class="country-name">United Kingdom</span> </span> </li> <li class="label"> <span class="adr"> <span class="type">Home</span>: <span class="street-address">West Street</span>, <span class="locality">Brighton</span>, <span class="country-name">United Kingdom</span> </span> </li> </ul> <p>In emergency contact: <span class="agent">Jane Doe</span> or <span class="agent vcard"><span class="fn">Dave Doe</span></span>.</p> <p>Key: <span class="key">hd02$Gfu*d%dh87KTa2=23934532479</span></p> </div>
G5/microformats2
vendor/tests/tests/microformats-v1/hcard/multiple.html
HTML
mit
3,182
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.WebJobs.Host.Bindings; using Microsoft.Azure.WebJobs.Host.Indexers; using Microsoft.Azure.WebJobs.Host.Protocols; using Microsoft.Azure.WebJobs.Host.Triggers; using Moq; using Xunit; using Xunit.Extensions; namespace Microsoft.Azure.WebJobs.Host.UnitTests.Indexers { public class FunctionIndexerTests { [Fact] public void IndexMethod_Throws_IfMethodHasUnboundOutParameterWithJobsAttribute() { // Arrange Mock<IFunctionIndexCollector> indexMock = new Mock<IFunctionIndexCollector>(MockBehavior.Strict); int calls = 0; indexMock .Setup(i => i.Add(It.IsAny<IFunctionDefinition>(), It.IsAny<FunctionDescriptor>(), It.IsAny<MethodInfo>())) .Callback(() => calls++); IFunctionIndexCollector index = indexMock.Object; FunctionIndexer product = CreateProductUnderTest(); // Act & Assert FunctionIndexingException exception = Assert.Throws<FunctionIndexingException>( () => product.IndexMethodAsync(typeof(FunctionIndexerTests).GetMethod("FailIndexing"), index, CancellationToken.None).GetAwaiter().GetResult()); InvalidOperationException innerException = exception.InnerException as InvalidOperationException; Assert.NotNull(innerException); Assert.Equal("Cannot bind parameter 'parsed' to type Foo&.", innerException.Message); } [Theory] [InlineData("MethodWithUnboundOutParameterAndNoJobAttribute")] [InlineData("MethodWithGenericParameter")] [InlineData("MethodWithNoParameters")] public void IndexMethod_IgnoresMethod_IfNonJobMethod(string method) { // Arrange Mock<IFunctionIndexCollector> indexMock = new Mock<IFunctionIndexCollector>(); FunctionIndexer product = CreateProductUnderTest(); // Act product.IndexMethodAsync(typeof(FunctionIndexerTests).GetMethod(method), indexMock.Object, CancellationToken.None).GetAwaiter().GetResult(); // Verify indexMock.Verify(i => i.Add(It.IsAny<IFunctionDefinition>(), It.IsAny<FunctionDescriptor>(), It.IsAny<MethodInfo>()), Times.Never); } [Fact] public void IndexMethod_IfMethodReturnsNonTask_Throws() { // Arrange IFunctionIndexCollector index = CreateDummyFunctionIndex(); FunctionIndexer product = CreateProductUnderTest(); // Act & Assert FunctionIndexingException exception = Assert.Throws<FunctionIndexingException>( () => product.IndexMethodAsync(typeof(FunctionIndexerTests).GetMethod("ReturnNonTask"), index, CancellationToken.None).GetAwaiter().GetResult()); InvalidOperationException innerException = exception.InnerException as InvalidOperationException; Assert.NotNull(innerException); Assert.Equal("Functions must return Task or void.", innerException.Message); } [Fact] public void IndexMethod_IfMethodReturnsTaskOfTResult_Throws() { // Arrange IFunctionIndexCollector index = CreateDummyFunctionIndex(); FunctionIndexer product = CreateProductUnderTest(); // Act & Assert FunctionIndexingException exception = Assert.Throws<FunctionIndexingException>( () => product.IndexMethodAsync(typeof(FunctionIndexerTests).GetMethod("ReturnGenericTask"), index, CancellationToken.None).GetAwaiter().GetResult()); InvalidOperationException innerException = exception.InnerException as InvalidOperationException; Assert.NotNull(innerException); Assert.Equal("Functions must return Task or void.", innerException.Message); } [Fact] public void IndexMethod_IfMethodReturnsVoid_DoesNotThrow() { // Arrange IFunctionIndexCollector index = CreateStubFunctionIndex(); FunctionIndexer product = CreateProductUnderTest(); // Act & Assert product.IndexMethodAsync(typeof(FunctionIndexerTests).GetMethod("ReturnVoid"), index, CancellationToken.None).GetAwaiter().GetResult(); } [Fact] public void IndexMethod_IfMethodReturnsTask_DoesNotThrow() { // Arrange IFunctionIndexCollector index = CreateStubFunctionIndex(); FunctionIndexer product = CreateProductUnderTest(); // Act & Assert product.IndexMethodAsync(typeof(FunctionIndexerTests).GetMethod("ReturnTask"), index, CancellationToken.None).GetAwaiter().GetResult(); } [Fact] public void IsJobMethod_ReturnsFalse_IfMethodHasUnresolvedGenericParameter() { // Arrange Mock<IFunctionIndex> indexMock = new Mock<IFunctionIndex>(); FunctionIndexer product = CreateProductUnderTest(); // Act bool actual = product.IsJobMethod(typeof(FunctionIndexerTests).GetMethod("MethodWithGenericParameter")); // Verify Assert.Equal(false, actual); } [Fact] public void IsJobMethod_ReturnsFalse_IfMethodHasNoParameters() { // Arrange Mock<IFunctionIndex> indexMock = new Mock<IFunctionIndex>(); FunctionIndexer product = CreateProductUnderTest(); // Act bool actual = product.IsJobMethod(typeof(FunctionIndexerTests).GetMethod("MethodWithNoParameters")); // Verify Assert.Equal(false, actual); } [Fact] public void IsJobMethod_ReturnsTrue_IfMethodHasJobAttribute() { // Arrange Mock<IFunctionIndex> indexMock = new Mock<IFunctionIndex>(); FunctionIndexer product = CreateProductUnderTest(); // Act bool actual = product.IsJobMethod(typeof(FunctionIndexerTests).GetMethod("MethodWithJobAttribute")); // Verify Assert.Equal(true, actual); } [Fact] public void IsJobMethod_ReturnsTrue_IfMethodHasJobAttributeButNoParameters() { // Arrange Mock<IFunctionIndex> indexMock = new Mock<IFunctionIndex>(); FunctionIndexer product = CreateProductUnderTest(); // Act bool actual = product.IsJobMethod(typeof(FunctionIndexerTests).GetMethod("MethodWithJobAttributeButNoParameters")); // Verify Assert.Equal(true, actual); } [Fact] public void IsJobMethod_ReturnsTrue_IfMethodHasJobParameterAttributes() { // Arrange Mock<IFunctionIndex> indexMock = new Mock<IFunctionIndex>(); FunctionIndexer product = CreateProductUnderTest(); // Act bool actual = product.IsJobMethod(typeof(FunctionIndexerTests).GetMethod("MethodWithJobParameterAttributes")); // Verify Assert.Equal(true, actual); } [Fact] public void IsJobMethod_ReturnsTrue_IfMethodHasJobParameterAttributes_FromExtensionAssemblies() { // Arrange Mock<IFunctionIndex> indexMock = new Mock<IFunctionIndex>(); IExtensionRegistry extensions = new DefaultExtensionRegistry(); extensions.RegisterExtension<ITriggerBindingProvider>(new TestExtensionTriggerBindingProvider()); extensions.RegisterExtension<IBindingProvider>(new TestExtensionBindingProvider()); FunctionIndexer product = FunctionIndexerFactory.Create(extensionRegistry: extensions); // Act bool actual = product.IsJobMethod(typeof(FunctionIndexerTests).GetMethod("MethodWithExtensionJobParameterAttributes")); // Verify Assert.Equal(true, actual); } [Fact] public void IsJobMethod_ReturnsFalse_IfMethodHasNoSdkAttributes() { // Arrange Mock<IFunctionIndex> indexMock = new Mock<IFunctionIndex>(); FunctionIndexer product = CreateProductUnderTest(); // Act bool actual = product.IsJobMethod(typeof(FunctionIndexerTests).GetMethod("MethodWithUnboundOutParameterAndNoJobAttribute")); // Verify Assert.Equal(false, actual); } private class TestExtensionBindingProvider : IBindingProvider { public Task<IBinding> TryCreateAsync(BindingProviderContext context) { throw new NotImplementedException(); } } private class TestExtensionTriggerBindingProvider : ITriggerBindingProvider { public Task<ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext context) { throw new NotImplementedException(); } } [AttributeUsage(AttributeTargets.Parameter)] public class ExtensionTrigger : Attribute { private string _path; public ExtensionTrigger(string path) { _path = path; } public string Path { get { return _path; } } } [AttributeUsage(AttributeTargets.Parameter)] public class Extension : Attribute { private string _path; public Extension(string path) { _path = path; } public string Path { get { return _path; } } } private static IFunctionIndexCollector CreateDummyFunctionIndex() { return new Mock<IFunctionIndexCollector>(MockBehavior.Strict).Object; } private static FunctionIndexer CreateProductUnderTest() { return FunctionIndexerFactory.Create(); } private static IFunctionIndexCollector CreateStubFunctionIndex() { return new Mock<IFunctionIndexCollector>().Object; } [NoAutomaticTrigger] public static void FailIndexing(string input, out Foo parsed) { throw new NotImplementedException(); } public static void MethodWithUnboundOutParameterAndNoJobAttribute(string input, out Foo parsed) { throw new NotImplementedException(); } public class Foo { } public static IEnumerable<IEnumerable<T>> MethodWithGenericParameter<T>(IEnumerable<T> source) { throw new NotImplementedException(); } public static void MethodWithNoParameters() { throw new NotImplementedException(); } [NoAutomaticTrigger] public static void MethodWithJobAttribute(string input, out string output) { throw new NotImplementedException(); } [NoAutomaticTrigger] public static void MethodWithJobAttributeButNoParameters() { throw new NotImplementedException(); } public static void MethodWithJobParameterAttributes([QueueTrigger("queue")] string input, [Blob("container/output")] TextWriter writer) { throw new NotImplementedException(); } public static void MethodWithExtensionJobParameterAttributes([ExtensionTrigger("path")] string input, [Extension("path")] TextWriter writer) { throw new NotImplementedException(); } [NoAutomaticTrigger] public static int ReturnNonTask() { throw new NotImplementedException(); } [NoAutomaticTrigger] public static Task<int> ReturnGenericTask() { throw new NotImplementedException(); } [NoAutomaticTrigger] public static void ReturnVoid() { throw new NotImplementedException(); } [NoAutomaticTrigger] public static Task ReturnTask() { throw new NotImplementedException(); } } }
brendankowitz/azure-webjobs-sdk
test/Microsoft.Azure.WebJobs.Host.UnitTests/Indexers/FunctionIndexerTests.cs
C#
mit
12,582
<?php /*PLEASE DO NOT EDIT THIS CODE*/ /*This code was generated using the UMPLE 1.10.2.2921 modeling language!*/ class StateMachine { //------------------------ // MEMBER VARIABLES //------------------------ //StateMachine Attributes private $name; private $events; //StateMachine Associations private $classOverview; //------------------------ // CONSTRUCTOR //------------------------ public function __construct($aName, $aClassOverview) { $this->name = $aName; $this->events = array(); $didAddClassOverview = $this->setClassOverview($aClassOverview); if (!$didAddClassOverview) { throw new Exception("Unable to create stateMachine due to classOverview"); } } //------------------------ // INTERFACE //------------------------ public function setName($aName) { $wasSet = false; $this->name = $aName; $wasSet = true; return $wasSet; } public function addEvent($aEvent) { $wasAdded = false; $this->events[] = $aEvent; $wasAdded = true; return $wasAdded; } public function removeEvent($aEvent) { $wasRemoved = false; unset($this->events[$this->indexOfEvent($aEvent)]); $this->events = array_values($this->events); $wasRemoved = true; return $wasRemoved; } public function getName() { return $this->name; } public function getEvent($index) { $aEvent = $this->events[$index]; return $aEvent; } public function getEvents() { $newEvents = $this->events; return $newEvents; } public function numberOfEvents() { $number = count($this->events); return $number; } public function hasEvents() { $has = events.size() > 0; return $has; } public function indexOfEvent($aEvent) { $rawAnswer = array_search($aEvent,$this->events); $index = $rawAnswer == null && $rawAnswer !== 0 ? -1 : $rawAnswer; return $index; } public function getClassOverview() { return $this->classOverview; } public function setClassOverview($aClassOverview) { $wasSet = false; if ($aClassOverview == null) { return $wasSet; } $existingClassOverview = $this->classOverview; $this->classOverview = $aClassOverview; if ($existingClassOverview != null && $existingClassOverview != $aClassOverview) { $existingClassOverview->removeStateMachine($this); } $this->classOverview->addStateMachine($this); $wasSet = true; return $wasSet; } public function equals($compareTo) { return $this == $compareTo; } public function delete() { $this->classOverview->removeStateMachine($this); } //------------------------ // DEVELOPER CODE - PROVIDED AS-IS //------------------------ function getCurrentState($obj) { $stateName = call_user_func(array($obj,"get{$this->getName()}")); $size = strlen($this->getName()); $startOfName = substr($stateName,0,$size); if ($startOfName == $this->getName()) { $stateName = substr($stateName,$size); } return $stateName; } } ?>
runqingz/umple
umpleonline/scripts/StateMachine.php
PHP
mit
3,215
--- layout: post title: 五中常见的开源协议整理(BSD,Apache,GPL,LGPL,MIT) category: 技术 tags: 开源,BSD,Apache,GPL,LGPL,MIT description: 最近做一个项目用了很多开源的组建,项目有可能会发布,所以提前整理整理各个开源协议,有助于项目发展 --- ## 简介 [开源软件][0](Open source software)对我们来说越来越不陌生,开源软件一方面让我们免费享用到了“免费的午餐”,另一方面有效的利用和学习开源软件,也能促进我们开发软件时的效率、提升软件质量。但是在使用和借鉴开源软件的时候,我们不得不关心一下它对使用者的诸多限制,比较常见的方式即协议授权(licence),这些协议中明确说明了使用者应该遵循的原则。 现在开源协议众多,通过[Open Source Initiative][1]组织批准的开源协议有50多种,本文提到的五种常见协议也在其中,而且出现频率非常频繁,我们在使用开源代码或者开放自己源代码的时候,也应该尽量选择这些协议。 ## 五种常见开源协议 ### [BSD协议][2] BSD开源协议是一个给予使用者很大自由的协议。开发者可以自由使用和修改源代码,也可以讲修改后的源代码作为开源或者专有软件再发布。但是有一下几个要求: - 如果再发布的产品中含有源代码,则在源代码中必须带有原来代码中的BSD协议。 - 如果再发布的只是二进制类库/软件,则需要再类库/软件的文档和版权申明中包含原有代码中的BSD协议。 - 不可以用开源代码的作者/机构名字和原来产品的名字做市场推广。 BSD 代码鼓励代码共享,但需要尊重代码作者的著作权。BSD由于允许使用者修改和重新发布代码,也允许使用或在BSD代码上开发商业软件发布和销售,因此是对商业集成很友好的协议。而很多的公司企业在选用开源产品的时候都首选BSD协议,因为可以完全控制这些第三方的代码,在必要的时候可以修改或者二次开发。 ### [Apache Licence 2.0][3] Apache Licence是著名的非盈利开源组织Apache采用的协议。该协议和BSD类似,同样鼓励代码共享和最终原作者的著作权,同样允许源代码修改和再发布。但是也需要遵循以下条件: - 需要给代码的用户一份Apache Licence。 - 如果修改了代码,需要再被修改的文件中说明。 - 在衍生的代码中(修改和有源代码衍生的代码中)需要带有原来代码中的协议,商标,专利声明和其他原来作者规定需要包含的说明。 - 如果再发布的产品中包含一个Notice文件,则在Notice文件中需要带有Apache Licence。你可以再Notice中增加自己的许可,但是不可以表现为对Apache Licence构成更改。 Apache Licence也是对商业应用又好的许可。使用者也可以再需要的时候修改代码来满足并作为开源或商业产品发布/销售。 ### [GPL][4] 我们很熟悉的Linux就是采用了GPL。GPL协议和BSD, Apache Licence等鼓励代码重用的许可很不一样。GPL的出发点是代码的开源/免费使用和引用/修改/衍生代码的开源/免费使用,但不允许修改后和衍生的代码做为闭源的商业软件发布和销售。这也就是为什么我们能用免费的各种linux,包括商业公司的linux和linux上各种各样的由个人,组织,以及商业软件公司开发的免费软件了。 GPL协议的主要内容是只要在一个软件中使用(“使用”指类库引用,修改后的代码或者衍生代码)GPL 协议的产品,则该软件产品必须也采用GPL协议,既必须也是开源和免费。这就是所谓的”传染性”。GPL协议的产品作为一个单独的产品使用没有任何问题,还可以享受免费的优势。 由于GPL严格要求使用了GPL类库的软件产品必须使用GPL协议,对于使用GPL协议的开源代码,商业软件或者对代码有保密要求的部门就不适合集成/采用作为类库和二次开发的基础。 其它细节如再发布的时候需要伴随GPL协议等和BSD/Apache等类似。 ### [LGPL][5] LGPL是GPL的一个为主要为类库使用设计的开源协议。和GPL要求任何使用/修改/衍生之GPL类库的的软件必须采用GPL协议不同。LGPL允许商业软件通过类库引用(link)方式使用LGPL类库而不需要开源商业软件的代码。这使得采用LGPL协议的开源代码可以被商业软件作为类库引用并发布和销售。 但是如果修改LGPL协议的代码或者衍生,则所有修改的代码,涉及修改部分的额外代码和衍生的代码都必须采用LGPL协议。因此LGPL协议的开源代码很适合作为第三方类库被商业软件引用,但不适合希望以LGPL协议代码为基础,通过修改和衍生的方式做二次开发的商业软件采用。 GPL/LGPL都保障原作者的知识产权,避免有人利用开源代码复制并开发类似的产品 ### [MIT][6] MIT是和BSD一样宽范的许可协议,作者只想保留版权,而无任何其他了限制。也就是说,你必须在你的发行版里包含原许可协议的声明,无论你是以二进制发布的还是以源代码发布的. ## 各协议分析图 乌克兰程序员Paul Bagwell,画了一张分析图,说明应该怎么选择。[阮一峰][7]对图进行了汉化,如下图: ![协议分析图][8] ## 参考 - <http://www.awflasher.com/blog/archives/939> - <http://www.ruanyifeng.com/blog/2011/05/how_to_choose_free_software_licenses.html> [0]: https://zh.wikipedia.org/wiki/%E5%BC%80%E6%BA%90%E8%BD%AF%E4%BB%B6 [1]: http://opensource.org/licenses/category [2]: http://zh.wikipedia.org/wiki/BSD%E8%AE%B8%E5%8F%AF%E8%AF%81 [3]: http://www.apache.org/licenses/LICENSE-2.0 [4]: http://en.wikipedia.org/wiki/GNU_General_Public_License [5]: http://www.gnu.org/copyleft/lesser.html [6]: http://opensource.org/licenses/mit-license.php [7]: http://www.ruanyifeng.com [8]: http://7u2ho6.com1.z0.glb.clouddn.com/tech-licence-different.png
hugo-/coolnameismy.github.io
_posts/tech/2013-04-23-opensource-licenses.md
Markdown
mit
6,127
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ /****************************************************************** iLBC Speech Coder ANSI-C Source Code iLBC_test.c ******************************************************************/ #include <math.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include "ilbc.h" //#define JUNK_DATA #ifdef JUNK_DATA #define SEED_FILE "randseed.txt" #endif /*----------------------------------------------------------------* * Main program to test iLBC encoding and decoding * * Usage: * exefile_name.exe <infile> <bytefile> <outfile> * *---------------------------------------------------------------*/ int main(int argc, char* argv[]) { FILE *ifileid,*efileid,*ofileid, *chfileid; short encoded_data[55], data[240], speechType; int len_int, mode; short pli; size_t len, readlen; int blockcount = 0; IlbcEncoderInstance *Enc_Inst; IlbcDecoderInstance *Dec_Inst; #ifdef JUNK_DATA size_t i; FILE *seedfile; unsigned int random_seed = (unsigned int) time(NULL);//1196764538 #endif /* Create structs */ WebRtcIlbcfix_EncoderCreate(&Enc_Inst); WebRtcIlbcfix_DecoderCreate(&Dec_Inst); /* get arguments and open files */ if (argc != 6 ) { fprintf(stderr, "%s mode inputfile bytefile outputfile channelfile\n", argv[0]); fprintf(stderr, "Example:\n"); fprintf(stderr, "%s <30,20> in.pcm byte.dat out.pcm T30.0.dat\n", argv[0]); exit(1); } mode=atoi(argv[1]); if (mode != 20 && mode != 30) { fprintf(stderr,"Wrong mode %s, must be 20, or 30\n", argv[1]); exit(2); } if ( (ifileid=fopen(argv[2],"rb")) == NULL) { fprintf(stderr,"Cannot open input file %s\n", argv[2]); exit(2);} if ( (efileid=fopen(argv[3],"wb")) == NULL) { fprintf(stderr, "Cannot open channelfile file %s\n", argv[3]); exit(3);} if( (ofileid=fopen(argv[4],"wb")) == NULL) { fprintf(stderr, "Cannot open output file %s\n", argv[4]); exit(3);} if ( (chfileid=fopen(argv[5],"rb")) == NULL) { fprintf(stderr,"Cannot open channel file file %s\n", argv[5]); exit(2); } /* print info */ fprintf(stderr, "\n"); fprintf(stderr, "*---------------------------------------------------*\n"); fprintf(stderr, "* *\n"); fprintf(stderr, "* iLBCtest *\n"); fprintf(stderr, "* *\n"); fprintf(stderr, "* *\n"); fprintf(stderr, "*---------------------------------------------------*\n"); #ifdef SPLIT_10MS fprintf(stderr,"\n10ms split with raw mode: %2d ms\n", mode); #else fprintf(stderr,"\nMode : %2d ms\n", mode); #endif fprintf(stderr,"\nInput file : %s\n", argv[2]); fprintf(stderr,"Coded file : %s\n", argv[3]); fprintf(stderr,"Output file : %s\n\n", argv[4]); fprintf(stderr,"Channel file : %s\n\n", argv[5]); #ifdef JUNK_DATA srand(random_seed); if ( (seedfile = fopen(SEED_FILE, "a+t") ) == NULL ) { fprintf(stderr, "Error: Could not open file %s\n", SEED_FILE); } else { fprintf(seedfile, "%u\n", random_seed); fclose(seedfile); } #endif /* Initialization */ WebRtcIlbcfix_EncoderInit(Enc_Inst, mode); WebRtcIlbcfix_DecoderInit(Dec_Inst, mode); /* loop over input blocks */ #ifdef SPLIT_10MS readlen = 80; #else readlen = (size_t)(mode << 3); #endif while(fread(data, sizeof(short), readlen, ifileid) == readlen) { blockcount++; /* encoding */ fprintf(stderr, "--- Encoding block %i --- ",blockcount); len_int=WebRtcIlbcfix_Encode(Enc_Inst, data, readlen, encoded_data); if (len_int < 0) { fprintf(stderr, "Error encoding\n"); exit(0); } len = (size_t)len_int; fprintf(stderr, "\r"); #ifdef JUNK_DATA for ( i = 0; i < len; i++) { encoded_data[i] = (short) (encoded_data[i] + (short) rand()); } #endif /* write byte file */ if(len != 0){ //len may be 0 in 10ms split case fwrite(encoded_data,1,len,efileid); /* get channel data if provided */ if (argc==6) { if (fread(&pli, sizeof(int16_t), 1, chfileid)) { if ((pli!=0)&&(pli!=1)) { fprintf(stderr, "Error in channel file\n"); exit(0); } if (pli==0) { /* Packet loss -> remove info from frame */ memset(encoded_data, 0, sizeof(int16_t)*25); } } else { fprintf(stderr, "Error. Channel file too short\n"); exit(0); } } else { pli=1; } /* decoding */ fprintf(stderr, "--- Decoding block %i --- ",blockcount); if (pli==1) { len_int = WebRtcIlbcfix_Decode(Dec_Inst, encoded_data, len, data, &speechType); if (len_int < 0) { fprintf(stderr, "Error decoding\n"); exit(0); } len = (size_t)len_int; } else { len=WebRtcIlbcfix_DecodePlc(Dec_Inst, data, 1); } fprintf(stderr, "\r"); /* write output file */ fwrite(data,sizeof(short),len,ofileid); } } #ifdef JUNK_DATA if ( (seedfile = fopen(SEED_FILE, "a+t") ) == NULL ) { fprintf(stderr, "Error: Could not open file %s\n", SEED_FILE); } else { fprintf(seedfile, "ok\n\n"); fclose(seedfile); } #endif /* free structs */ WebRtcIlbcfix_EncoderFree(Enc_Inst); WebRtcIlbcfix_DecoderFree(Dec_Inst); /* close files */ fclose(ifileid); fclose(efileid); fclose(ofileid); return 0; }
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/webrtc/modules/audio_coding/codecs/ilbc/test/iLBC_testLib.c
C
mit
6,057
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Boost.Geometry (aka GGL, Generic Geometry Library)</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> <link href="tabs.css" rel="stylesheet" type="text/css"> </head> <table cellpadding="2" width="100%"> <tbody> <tr> <td valign="top"> <img alt="Boost.Geometry" src="images/ggl-logo-big.png" height="80" width="200"> &nbsp;&nbsp; </td> <td valign="top" align="right"> <a href="http://www.boost.org"> <img alt="Boost C++ Libraries" src="images/accepted_by_boost.png" height="80" width="230" border="0"> </a> </td> </tr> </tbody> </table> <!-- Generated by Doxygen 1.7.6.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li class="current"><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li><a href="functions.html"><span>All</span></a></li> <li class="current"><a href="functions_func.html"><span>Functions</span></a></li> <li><a href="functions_vars.html"><span>Variables</span></a></li> <li><a href="functions_type.html"><span>Typedefs</span></a></li> <li><a href="functions_rela.html"><span>Related&#160;Functions</span></a></li> </ul> </div> <div id="navrow4" class="tabs3"> <ul class="tablist"> <li><a href="functions_func.html#index_a"><span>a</span></a></li> <li><a href="functions_func_0x62.html#index_b"><span>b</span></a></li> <li><a href="functions_func_0x63.html#index_c"><span>c</span></a></li> <li><a href="functions_func_0x64.html#index_d"><span>d</span></a></li> <li><a href="functions_func_0x65.html#index_e"><span>e</span></a></li> <li><a href="functions_func_0x66.html#index_f"><span>f</span></a></li> <li><a href="functions_func_0x67.html#index_g"><span>g</span></a></li> <li><a href="functions_func_0x68.html#index_h"><span>h</span></a></li> <li><a href="functions_func_0x69.html#index_i"><span>i</span></a></li> <li><a href="functions_func_0x6a.html#index_j"><span>j</span></a></li> <li><a href="functions_func_0x6c.html#index_l"><span>l</span></a></li> <li><a href="functions_func_0x6d.html#index_m"><span>m</span></a></li> <li><a href="functions_func_0x6f.html#index_o"><span>o</span></a></li> <li><a href="functions_func_0x70.html#index_p"><span>p</span></a></li> <li><a href="functions_func_0x72.html#index_r"><span>r</span></a></li> <li><a href="functions_func_0x73.html#index_s"><span>s</span></a></li> <li class="current"><a href="functions_func_0x74.html#index_t"><span>t</span></a></li> <li><a href="functions_func_0x75.html#index_u"><span>u</span></a></li> <li><a href="functions_func_0x76.html#index_v"><span>v</span></a></li> <li><a href="functions_func_0x77.html#index_w"><span>w</span></a></li> <li><a href="functions_func_0x78.html#index_x"><span>x</span></a></li> <li><a href="functions_func_0x79.html#index_y"><span>y</span></a></li> <li><a href="functions_func_0x7a.html#index_z"><span>z</span></a></li> <li><a href="functions_func_0x7e.html#index_0x7e"><span>~</span></a></li> </ul> </div> </div> <div class="contents"> &#160; <h3><a class="anchor" id="index_t"></a>- t -</h3><ul> <li>text() : <a class="el" href="classboost_1_1geometry_1_1svg__mapper.html#a20890c91dcb47bef38356d81b8abcef9">boost::geometry::svg_mapper&lt; Point, SameScale &gt;</a> </li> <li>touching() : <a class="el" href="classboost_1_1geometry_1_1side__info.html#a63d69eefab159b0911e322758f259506">boost::geometry::side_info</a> </li> <li>translate_transformer() : <a class="el" href="classboost_1_1geometry_1_1strategy_1_1transform_1_1translate__transformer_3_01_calculation_type_00_013_00_013_01_4.html#ad5220c7d064a6a7765fe4abbb5e1d345">boost::geometry::strategy::transform::translate_transformer&lt; CalculationType, 3, 3 &gt;</a> , <a class="el" href="classboost_1_1geometry_1_1strategy_1_1transform_1_1translate__transformer_3_01_calculation_type_00_012_00_012_01_4.html#af527f210267b42095320a119a839f175">boost::geometry::strategy::transform::translate_transformer&lt; CalculationType, 2, 2 &gt;</a> </li> <li>turn_info_exception() : <a class="el" href="classboost_1_1geometry_1_1turn__info__exception.html#a7468366434e478e13af3e53fb4831b1e">boost::geometry::turn_info_exception</a> </li> <li>turn_printer() : <a class="el" href="structboost_1_1geometry_1_1detail_1_1turns_1_1turn__printer.html#ab07f163b9bacb940e04e29527537d015">boost::geometry::detail::turns::turn_printer</a> </li> </ul> </div><!-- contents --> <hr size="1"> <table width="100%"> <tbody> <tr> <td align="left"><small> <p>April 2, 2011</p> </small></td> <td align="right"> <small> Copyright &copy; 2007-2011 Barend Gehrels, Amsterdam, the Netherlands<br> Copyright &copy; 2008-2011 Bruno Lalande, Paris, France<br> Copyright &copy; 2009-2010 Mateusz Loskot, London, UK<br> </small> </td> </tr> </tbody> </table> <address style="text-align: right;"><small> Documentation is generated by&nbsp;<a href="http://www.doxygen.org/index.html">Doxygen</a> </small></address> </body> </html>
yinchunlong/abelkhan-1
ext/c++/thirdpart/c++/boost/libs/geometry/doc/doxy/doxygen_output/html_by_doxygen/functions_func_0x74.html
HTML
mit
6,036
require 'pygments' require 'fileutils' require 'digest/md5' PYGMENTS_CACHE_DIR = File.expand_path('../../_code_cache', __FILE__) FileUtils.mkdir_p(PYGMENTS_CACHE_DIR) module HighlightCode def highlight(str, lang) str = pygments(str, lang).match(/<pre>(.+)<\/pre>/m)[1].to_s.gsub(/ *$/, '') #strip out divs <div class="highlight"> table = '<div class="highlight"><table cellpadding="0" cellspacing="0"><tr><td class="gutter"><pre class="line-numbers">' code = '' str.lines.each_with_index do |line,index| table += "<span class='line'>#{index+1}</span>\n" code += "<div class='line'>#{line}</div>" end table += "</pre></td><td class='code' width='100%'><pre><code class='#{lang}'>#{code}</code></pre></td></tr></table></div>" end def pygments(code, lang) if defined?(PYGMENTS_CACHE_DIR) path = File.join(PYGMENTS_CACHE_DIR, "#{lang}-#{Digest::MD5.hexdigest(code)}.html") if File.exist?(path) highlighted_code = File.read(path) else highlighted_code = Pygments.highlight(code, :lexer => lang, :formatter => 'html') File.open(path, 'w') {|f| f.print(highlighted_code) } end else highlighted_code = Pygments.highlight(code, :lexer => lang, :formatter => 'html') end highlighted_code end end
chikamichi/ruby-lang.org
rubylang/plugins/pygments_code.rb
Ruby
mit
1,304
package com.jakduk.api.restcontroller; import com.jakduk.api.common.Constants; import com.jakduk.api.common.board.category.BoardCategory; import com.jakduk.api.common.board.category.BoardCategoryGenerator; import com.jakduk.api.common.rabbitmq.RabbitMQPublisher; import com.jakduk.api.common.util.AuthUtils; import com.jakduk.api.common.util.DateUtils; import com.jakduk.api.common.util.JakdukUtils; import com.jakduk.api.exception.ServiceError; import com.jakduk.api.exception.ServiceException; import com.jakduk.api.model.aggregate.BoardTop; import com.jakduk.api.model.db.Article; import com.jakduk.api.model.db.ArticleComment; import com.jakduk.api.model.db.Gallery; import com.jakduk.api.model.embedded.CommonFeelingUser; import com.jakduk.api.model.embedded.CommonWriter; import com.jakduk.api.restcontroller.vo.EmptyJsonResponse; import com.jakduk.api.restcontroller.vo.UserFeelingResponse; import com.jakduk.api.restcontroller.vo.board.*; import com.jakduk.api.service.ArticleService; import com.jakduk.api.service.GalleryService; import org.apache.commons.lang3.StringUtils; import org.bson.types.ObjectId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.beans.PropertyEditorSupport; import java.time.LocalDate; import java.util.List; import java.util.stream.Collectors; /** * 게시판 API * * @author pyohwan * 16. 3. 26 오후 11:05 */ @RestController @RequestMapping("/api/board") public class BoardRestController { private final Logger log = LoggerFactory.getLogger(this.getClass()); @Autowired private ArticleService articleService; @Autowired private GalleryService galleryService; @Autowired private RabbitMQPublisher rabbitMQPublisher; // 게시판 글 목록 @GetMapping("/{board}/articles") public GetArticlesResponse getArticles( @PathVariable Constants.BOARD_TYPE board, // 게시판 @RequestParam(required = false, defaultValue = "1") Integer page, // 페이지 번호(1부터 시작) @RequestParam(required = false, defaultValue = "20") Integer size, // 페이지 사이즈 @RequestParam(required = false, defaultValue = "ALL") String categoryCode // 말머리 ) { return articleService.getArticles(board, categoryCode, page, size); } // 게시판 주간 선두 글 @GetMapping("/{board}/tops") public GetArticlesTopsResponse getArticlesTops( @PathVariable Constants.BOARD_TYPE board // 게시판 ) { LocalDate localDate = LocalDate.now().minusWeeks(1); ObjectId objectId = new ObjectId(DateUtils.localDateToDate(localDate)); List<BoardTop> topLikes = articleService.getArticlesTopLikes(board, objectId); List<BoardTop> topComments = articleService.getArticlesTopComments(board, objectId); return new GetArticlesTopsResponse(topLikes, topComments); } // 게시판 글 상세 @GetMapping("/{board}/{seq}") public ResponseEntity<GetArticleDetailResponse> getArticleDetail( @PathVariable Constants.BOARD_TYPE board, // 게시판 @PathVariable Integer seq, // 글 seq HttpServletRequest request, HttpServletResponse response) { Boolean isAddCookie = JakdukUtils.addViewsCookie(request, response, Constants.VIEWS_COOKIE_TYPE.ARTICLE, String.valueOf(seq)); CommonWriter commonWriter = AuthUtils.getCommonWriterFromSession(); return articleService.getArticleDetail(commonWriter, board, seq, isAddCookie); } // 게시판 말머리 목록 @GetMapping("/{board}/categories") public GetBoardCategoriesResponse getBoardCategories( @PathVariable Constants.BOARD_TYPE board // 게시판 ) { List<BoardCategory> categories = BoardCategoryGenerator.getCategories(board, JakdukUtils.getLocale()); return new GetBoardCategoriesResponse(categories); } // 게시판 글쓰기 @PostMapping("/{board}") public WriteArticleResponse writeArticle( @PathVariable Constants.BOARD_TYPE board, @Valid @RequestBody WriteArticle form) { log.info("request board : {}, body : {}", board, form); List<GalleryOnBoard> formGalleries = form.getGalleries(); CommonWriter commonWriter = AuthUtils.getCommonWriterFromSession(); // 연관된 사진 id 배열 (검증 전) List<String> unverifiableGalleryIds = null; if (! CollectionUtils.isEmpty(formGalleries)) { unverifiableGalleryIds = formGalleries.stream() .map(GalleryOnBoard::getId) .distinct() .collect(Collectors.toList()); } List<Gallery> galleries = galleryService.findByIdIn(unverifiableGalleryIds); // 연관된 사진 id 배열 (검증 후) List<String> galleryIds = galleries.stream() .map(Gallery::getId) .collect(Collectors.toList()); Article article = articleService.insertArticle(commonWriter, board, form.getSubject().trim(), form.getContent().trim(), StringUtils.trim(form.getCategoryCode()), ! galleries.isEmpty()); galleryService.processLinkedGalleries(commonWriter.getUserId(), galleries, formGalleries, null, Constants.GALLERY_FROM_TYPE.ARTICLE, article.getId()); // 엘라스틱서치 색인 요청 rabbitMQPublisher.indexDocumentArticle(article.getId(), article.getSeq(), article.getBoard(), article.getCategory(), article.getWriter(), article.getSubject(), article.getContent(), galleryIds); return new WriteArticleResponse(article.getBoard(), article.getSeq()); } // 게시판 글 고치기 @PutMapping("/{board}/{seq}") public WriteArticleResponse editArticle( @PathVariable Constants.BOARD_TYPE board, @PathVariable Integer seq, @Valid @RequestBody WriteArticle form, HttpServletRequest request) { CommonWriter commonWriter = AuthUtils.getCommonWriterFromSession(); // 연관된 사진 id 배열 (검증 전) List<String> unverifiableGalleryIds = null; if (! CollectionUtils.isEmpty(form.getGalleries())) { unverifiableGalleryIds = form.getGalleries().stream() .map(GalleryOnBoard::getId) .distinct() .collect(Collectors.toList()); } List<Gallery> galleries = galleryService.findByIdIn(unverifiableGalleryIds); // 연관된 사진 id 배열 (검증 후) List<String> galleryIds = galleries.stream() .map(Gallery::getId) .collect(Collectors.toList()); Article article = articleService.updateArticle(commonWriter, board, seq, form.getSubject().trim(), form.getContent().trim(), form.getCategoryCode(), ! galleries.isEmpty()); List<String> galleryIdsForRemoval = JakdukUtils.getSessionOfGalleryIdsForRemoval(request, Constants.GALLERY_FROM_TYPE.ARTICLE, article.getId()); galleryService.processLinkedGalleries(commonWriter.getUserId(), galleries, form.getGalleries(), galleryIdsForRemoval, Constants.GALLERY_FROM_TYPE.ARTICLE, article.getId()); JakdukUtils.removeSessionOfGalleryIdsForRemoval(request, Constants.GALLERY_FROM_TYPE.ARTICLE, article.getId()); // 엘라스틱서치 색인 요청 rabbitMQPublisher.indexDocumentArticle(article.getId(), article.getSeq(), article.getBoard(), article.getCategory(), article.getWriter(), article.getSubject(), article.getContent(), galleryIds); return new WriteArticleResponse(article.getBoard(), article.getSeq()); } // 게시판 글 지움 @DeleteMapping("/{board}/{seq}") public DeleteArticleResponse deleteArticle( @PathVariable Constants.BOARD_TYPE board, @PathVariable Integer seq) { CommonWriter commonWriter = AuthUtils.getCommonWriterFromSession(); Constants.ARTICLE_DELETE_TYPE deleteType = articleService.deleteArticle(commonWriter, board, seq); return new DeleteArticleResponse(deleteType); } // 게시판 글의 댓글 목록 @GetMapping("/{board}/{seq}/comments") public GetArticleDetailCommentsResponse getArticleDetailComments( @PathVariable Constants.BOARD_TYPE board, @PathVariable Integer seq, @RequestParam(required = false) String commentId // 이 CommentId 이후부터 목록 가져옴 ) { CommonWriter commonWriter = AuthUtils.getCommonWriterFromSession(); return articleService.getArticleDetailComments(commonWriter, board, seq, commentId); } // 게시판 글의 댓글 달기 @PostMapping("/{board}/{seq}/comment") public ArticleComment writeArticleComment( @PathVariable Constants.BOARD_TYPE board, @PathVariable Integer seq, @Valid @RequestBody WriteArticleComment form) { log.info("request board : {}, seq : {}, body : {}", board, seq, form); log.info("content length : {}", form.getContent().length()); CommonWriter commonWriter = AuthUtils.getCommonWriterFromSession(); // 연관된 사진 id 배열 (검증 전) List<String> unverifiableGalleryIds = null; if (! CollectionUtils.isEmpty(form.getGalleries())) { unverifiableGalleryIds = form.getGalleries().stream() .map(GalleryOnBoard::getId) .collect(Collectors.toList()); } List<Gallery> galleries = galleryService.findByIdIn(unverifiableGalleryIds); ArticleComment articleComment = articleService.insertArticleComment(commonWriter, board, seq, form.getContent().trim(), galleries); galleryService.processLinkedGalleries(commonWriter.getUserId(), galleries, form.getGalleries(), null, Constants.GALLERY_FROM_TYPE.ARTICLE_COMMENT, articleComment.getId()); return articleComment; } // 게시판 글의 댓글 고치기 @PutMapping("/{board}/comment/{id}") public ArticleComment editArticleComment( @PathVariable Constants.BOARD_TYPE board, @PathVariable String id, @Valid @RequestBody WriteArticleComment form, HttpServletRequest request) { CommonWriter commonWriter = AuthUtils.getCommonWriterFromSession(); // 연관된 사진 id 배열 (검증 전) List<String> unverifiableGalleryIds = null; if (! CollectionUtils.isEmpty(form.getGalleries())) { unverifiableGalleryIds = form.getGalleries().stream() .map(GalleryOnBoard::getId) .distinct() .collect(Collectors.toList()); } List<Gallery> galleries = galleryService.findByIdIn(unverifiableGalleryIds); // 연관된 사진 id 배열 (검증 후) List<String> galleryIds = galleries.stream() .map(Gallery::getId) .collect(Collectors.toList()); ArticleComment articleComment = articleService.updateArticleComment(commonWriter, board, id, form.getContent().trim(), galleryIds); List<String> galleryIdsForRemoval = JakdukUtils.getSessionOfGalleryIdsForRemoval(request, Constants.GALLERY_FROM_TYPE.ARTICLE_COMMENT, articleComment.getId()); galleryService.processLinkedGalleries(commonWriter.getUserId(), galleries, form.getGalleries(), galleryIdsForRemoval, Constants.GALLERY_FROM_TYPE.ARTICLE_COMMENT, articleComment.getId()); JakdukUtils.removeSessionOfGalleryIdsForRemoval(request, Constants.GALLERY_FROM_TYPE.ARTICLE_COMMENT, articleComment.getId()); return articleComment; } // 게시판 글의 댓글 지우기 @DeleteMapping("/{board}/comment/{id}") public EmptyJsonResponse deleteFreeComment( @PathVariable Constants.BOARD_TYPE board, @PathVariable String id // 댓글 ID ) { CommonWriter commonWriter = AuthUtils.getCommonWriterFromSession(); articleService.deleteArticleComment(commonWriter, board, id); return EmptyJsonResponse.newInstance(); } // 게시판 글 감정 표현 @PostMapping("/{board}/{seq}/{feeling}") public UserFeelingResponse setArticleFeeling( @PathVariable Constants.BOARD_TYPE board, @PathVariable Integer seq, @PathVariable Constants.FEELING_TYPE feeling) { CommonWriter commonWriter = AuthUtils.getCommonWriterFromSession(); Article article = articleService.setArticleFeelings(commonWriter, board, seq, feeling); List<CommonFeelingUser> usersLiking = article.getUsersLiking(); List<CommonFeelingUser> usersDisliking = article.getUsersDisliking(); return new UserFeelingResponse() {{ setMyFeeling(JakdukUtils.getMyFeeling(commonWriter, usersLiking, usersDisliking)); setNumberOfLike(CollectionUtils.isEmpty(usersLiking) ? 0 : usersLiking.size()); setNumberOfDislike(CollectionUtils.isEmpty(usersDisliking) ? 0 : usersDisliking.size()); }}; } // 자유게시판 글의 감정 표현 회원 목록 @GetMapping("/{board}/{seq}/feeling/users") public GetArticleFeelingUsersResponse getArticleFeelingUsers ( @PathVariable Constants.BOARD_TYPE board, @PathVariable Integer seq) { Article article = articleService.findOneBySeq(board, seq); return new GetArticleFeelingUsersResponse(seq, article.getUsersLiking(), article.getUsersDisliking()); } // 자유게시판 댓글 감정 표현 @PostMapping("/{board}/comment/{commentId}/{feeling}") public UserFeelingResponse addFreeCommentFeeling( @PathVariable Constants.BOARD_TYPE board, @PathVariable String commentId, @PathVariable Constants.FEELING_TYPE feeling) { CommonWriter commonWriter = AuthUtils.getCommonWriterFromSession(); ArticleComment boardComment = articleService.setArticleCommentFeeling(commonWriter, commentId, feeling); List<CommonFeelingUser> usersLiking = boardComment.getUsersLiking(); List<CommonFeelingUser> usersDisliking = boardComment.getUsersDisliking(); return new UserFeelingResponse() {{ setMyFeeling(JakdukUtils.getMyFeeling(commonWriter, usersLiking, usersDisliking)); setNumberOfLike(CollectionUtils.isEmpty(usersLiking) ? 0 : usersLiking.size()); setNumberOfDislike(CollectionUtils.isEmpty(usersDisliking) ? 0 : usersDisliking.size()); }}; } // 게시판 글의 공지 활성화 @PostMapping("/{board}/{seq}/notice") public EmptyJsonResponse enableArticleNotice( @PathVariable Constants.BOARD_TYPE board, @PathVariable Integer seq) { CommonWriter commonWriter = AuthUtils.getCommonWriterFromSession(); articleService.enableArticleNotice(commonWriter, board, seq); return EmptyJsonResponse.newInstance(); } // 게시판 글의 공지 비활성화 @DeleteMapping("/{board}/{seq}/notice") public EmptyJsonResponse disableArticleNotice( @PathVariable Constants.BOARD_TYPE board, @PathVariable Integer seq) { CommonWriter commonWriter = AuthUtils.getCommonWriterFromSession(); articleService.disableArticleNotice(commonWriter, board, seq); return EmptyJsonResponse.newInstance(); } @InitBinder public void initBoardTypeEnumBinder(WebDataBinder dataBinder) { dataBinder.registerCustomEditor(Constants.BOARD_TYPE.class, new BoardTypeEnumConverter()); dataBinder.registerCustomEditor(Constants.FEELING_TYPE.class, new FeelingTypeEnumConverter()); } private class BoardTypeEnumConverter extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { if (StringUtils.isAllLowerCase(text)) { setValue(text.toUpperCase()); } else { throw new ServiceException(ServiceError.INVALID_PARAMETER); } } } private class FeelingTypeEnumConverter extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { if (StringUtils.isAllLowerCase(text)) { setValue(text.toUpperCase()); } else { throw new ServiceException(ServiceError.INVALID_PARAMETER); } } } }
Pyohwan/JakduK
src/main/java/com/jakduk/api/restcontroller/BoardRestController.java
Java
mit
17,007
compassOptions ============== An optional parameter to customize the retrieval of the compass. Options ------- - __frequency:__ How often to retrieve the compass heading in milliseconds. _(Number)_ (Default: 100) - __filter:__ The change in degrees required to initiate a watchHeadingFilter success callback. _(Number)_ Android Quirks ______________ - filter is not supported. Windows Phone 7 Quirks -------------- - filter is not supported.
macdonst/callback-docs
docs/en/edge/phonegap/compass/parameters/compassOptions.md
Markdown
mit
447
require 'spec_helper' require 'cucumber/formatter/spec_helper' require 'cucumber/formatter/junit' require 'nokogiri' module Cucumber::Formatter describe Junit do extend SpecHelperDsl include SpecHelper class TestDoubleJunitFormatter < Junit attr_reader :written_files def write_file(feature_filename, data) @written_files ||= {} @written_files[feature_filename] = data end end before(:each) do allow(File).to receive(:directory?) { true } @formatter = TestDoubleJunitFormatter.new(runtime, '', {}) end after(:each) do $stdout = STDOUT end describe "is able to strip control chars from cdata" do before(:each) do run_defined_feature @doc = Nokogiri.XML(@formatter.written_files.values.first) end define_feature " Feature: One passing scenario, one failing scenario Scenario: Passing Given a passing ctrl scenario " class Junit def before_step(step) if step.name.match("a passing ctrl scenario") Interceptor::Pipe.unwrap! :stdout @fake_io = $stdout = StringIO.new $stdout.sync = true @interceptedout = Interceptor::Pipe.wrap(:stdout) end end def after_step(step) if step.name.match("a passing ctrl scenario") @interceptedout.write("boo\b\cx\e\a\f boo ") $stdout = STDOUT @fake_io.close end end end it { expect(@doc.xpath('//testsuite/system-out').first.content).to match(/\s+boo boo\s+/) } end describe "a feature with no name" do define_feature <<-FEATURE Feature: Scenario: Passing Given a passing scenario FEATURE it "raises an exception" do expect(-> { run_defined_feature }).to raise_error(Junit::UnNamedFeatureError) end end describe "given a single feature" do before(:each) do run_defined_feature @doc = Nokogiri.XML(@formatter.written_files.values.first) end describe "with a single scenario" do define_feature <<-FEATURE Feature: One passing scenario, one failing scenario Scenario: Passing Given a passing scenario FEATURE it { expect(@doc.to_s).to match /One passing scenario, one failing scenario/ } it 'has a root system-out node' do expect(@doc.xpath('//testsuite/system-out').size).to eq 1 end it 'has a root system-err node' do expect(@doc.xpath('//testsuite/system-err').size).to eq 1 end it 'has a system-out node under <testcase/>' do expect(@doc.xpath('//testcase/system-out').size).to eq 1 end it 'has a system-err node under <testcase/>' do expect(@doc.xpath('//testcase/system-err').size).to eq 1 end end describe "with a scenario in a subdirectory" do define_feature %{ Feature: One passing scenario, one failing scenario Scenario: Passing Given a passing scenario }, File.join('features', 'some', 'path', 'spec.feature') it 'writes the filename including the subdirectory' do expect(@formatter.written_files.keys.first).to eq File.join('', 'TEST-features-some-path-spec.xml') end end describe "with a scenario outline table" do define_steps do Given(/.*/) { } end define_feature <<-FEATURE Feature: Eat things when hungry Scenario Outline: Eat things Given <Things> And stuff: | foo | | bar | Examples: Good | Things | | Cucumber | | Whisky | Examples: Evil | Things | | Big Mac | FEATURE it { expect(@doc.to_s).to match /Eat things when hungry/ } it { expect(@doc.to_s).to match /Cucumber/ } it { expect(@doc.to_s).to match /Whisky/ } it { expect(@doc.to_s).to match /Big Mac/ } it { expect(@doc.to_s).not_to match /Things/ } it { expect(@doc.to_s).not_to match /Good|Evil/ } it { expect(@doc.to_s).not_to match /type="skipped"/} end describe "scenario with skipped test in junit report" do define_feature <<-FEATURE Feature: junit report with skipped test Scenario Outline: skip a test and junit report of the same Given a <skip> scenario Examples: | skip | | undefined | | still undefined | FEATURE it { expect(@doc.to_s).to match /skipped="2"/} end describe "with a regular data table scenario" do define_steps do Given(/the following items on a shortlist/) { |table| } When(/I go.*/) { } Then(/I should have visited at least/) { |table| } end define_feature <<-FEATURE Feature: Shortlist Scenario: Procure items Given the following items on a shortlist: | item | | milk | | cookies | When I get some.. Then I'll eat 'em FEATURE # these type of tables shouldn't crash (or generate test cases) it { expect(@doc.to_s).not_to match /milk/ } it { expect(@doc.to_s).not_to match /cookies/ } end end end end
CW5000/CWFDerpy
spec/cucumber/formatter/junit_spec.rb
Ruby
mit
5,644
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>basic_socket_acceptor::operator= (2 of 2 overloads)</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../operator_eq_.html" title="basic_socket_acceptor::operator="> <link rel="prev" href="overload1.html" title="basic_socket_acceptor::operator= (1 of 2 overloads)"> <link rel="next" href="../protocol_type.html" title="basic_socket_acceptor::protocol_type"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="overload1.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../operator_eq_.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../protocol_type.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h5 class="title"> <a name="boost_asio.reference.basic_socket_acceptor.operator_eq_.overload2"></a><a class="link" href="overload2.html" title="basic_socket_acceptor::operator= (2 of 2 overloads)">basic_socket_acceptor::operator= (2 of 2 overloads)</a> </h5></div></div></div> <p> Move-assign a <a class="link" href="../../basic_socket_acceptor.html" title="basic_socket_acceptor"><code class="computeroutput"><span class="identifier">basic_socket_acceptor</span></code></a> from an acceptor of another protocol type. </p> <pre class="programlisting"><span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="../../Protocol.html" title="Protocol requirements">Protocol1</a><span class="special">,</span> <span class="keyword">typename</span> <a class="link" href="../../SocketAcceptorService.html" title="Socket acceptor service requirements">SocketAcceptorService1</a><span class="special">&gt;</span> <span class="identifier">enable_if</span><span class="special">&lt;</span> <span class="identifier">is_convertible</span><span class="special">&lt;</span> <span class="identifier">Protocol1</span><span class="special">,</span> <span class="identifier">Protocol</span> <span class="special">&gt;::</span><span class="identifier">value</span><span class="special">,</span> <span class="identifier">basic_socket_acceptor</span> <span class="special">&gt;::</span><span class="identifier">type</span> <span class="special">&amp;</span> <span class="keyword">operator</span><span class="special">=(</span> <span class="identifier">basic_socket_acceptor</span><span class="special">&lt;</span> <span class="identifier">Protocol1</span><span class="special">,</span> <span class="identifier">SocketAcceptorService1</span> <span class="special">&gt;</span> <span class="special">&amp;&amp;</span> <span class="identifier">other</span><span class="special">);</span> </pre> <p> This assignment operator moves an acceptor from one object to another. </p> <h6> <a name="boost_asio.reference.basic_socket_acceptor.operator_eq_.overload2.h0"></a> <span><a name="boost_asio.reference.basic_socket_acceptor.operator_eq_.overload2.parameters"></a></span><a class="link" href="overload2.html#boost_asio.reference.basic_socket_acceptor.operator_eq_.overload2.parameters">Parameters</a> </h6> <div class="variablelist"> <p class="title"><b></b></p> <dl> <dt><span class="term">other</span></dt> <dd><p> The other <a class="link" href="../../basic_socket_acceptor.html" title="basic_socket_acceptor"><code class="computeroutput"><span class="identifier">basic_socket_acceptor</span></code></a> object from which the move will occur. </p></dd> </dl> </div> <h6> <a name="boost_asio.reference.basic_socket_acceptor.operator_eq_.overload2.h1"></a> <span><a name="boost_asio.reference.basic_socket_acceptor.operator_eq_.overload2.remarks"></a></span><a class="link" href="overload2.html#boost_asio.reference.basic_socket_acceptor.operator_eq_.overload2.remarks">Remarks</a> </h6> <p> Following the move, the moved-from object is in the same state as if constructed using the <code class="computeroutput"><span class="identifier">basic_socket</span><span class="special">(</span><span class="identifier">io_service</span><span class="special">&amp;)</span> <span class="identifier">constructor</span></code>. </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2015 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="overload1.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../operator_eq_.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../protocol_type.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
yinchunlong/abelkhan-1
ext/c++/thirdpart/c++/boost/libs/asio/doc/html/boost_asio/reference/basic_socket_acceptor/operator_eq_/overload2.html
HTML
mit
6,422
<!DOCTYPE html> <html class='nb_fullscreen'> <head> <meta charset="utf-8"/> <!-- Author: cf AUTHORS.txt License: Copyright (c) 2010-2012 Massachusetts Institute of Technology. MIT License (cf. MIT-LICENSE.txt or http://www.opensource.org/licenses/mit-license.php) --> <title>Page unavailable</title> <link type="text/css" href="/content/compiled/add_navbar.css" rel="stylesheet" /> <link type="text/css" href="/content/lib/font-awesome/font-awesome-4.6.1/css/font-awesome.min.css" rel="stylesheet" /> <script type="text/javascript" src="/content/compiled/add_navbar_NB.js"></script> </head> <body> <h1>Page unavailable</h1> <p>Sorry, but the requested page is unavailable due to a server hiccup.</p> <p>Our engineers have been notified, so check back later.</p> </body> </html>
kesiena115/nbproject
templates/500.html
HTML
mit
844
//----------------------------------------------------------------------- // <copyright file="<file>.cs" company="The Outercurve Foundation"> // Copyright (c) 2011, The Outercurve Foundation. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.opensource.org/licenses/mit-license.php // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <author>Nathan Totten (ntotten.com), Jim Zimmerman (jimzimmerman.com) and Prabir Shrestha (prabir.me)</author> // <website>https://github.com/facebook-csharp-sdk/simple-json</website> //----------------------------------------------------------------------- namespace SimpleJsonTests.DataContractTests { #if NUNIT using TestClass = NUnit.Framework.TestFixtureAttribute; using TestMethod = NUnit.Framework.TestAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; using ClassCleanup = NUnit.Framework.TestFixtureTearDownAttribute; using ClassInitialize = NUnit.Framework.TestFixtureSetUpAttribute; using NUnit.Framework; #else #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; #else using Microsoft.VisualStudio.TestTools.UnitTesting; #endif #endif using SimpleJson; [TestClass] public class PrivateReadonlySerializeTests { private DataContractPrivateReadOnlyFields _dataContractPrivateReadOnlyFields; public PrivateReadonlySerializeTests() { _dataContractPrivateReadOnlyFields = new DataContractPrivateReadOnlyFields(); } [TestMethod] public void SerializesCorrectly() { var result = SimpleJson.SerializeObject(_dataContractPrivateReadOnlyFields, SimpleJson.DataContractJsonSerializerStrategy); Assert.AreEqual("{\"DataMemberWithoutName\":\"dmv\",\"name\":\"dmnv\"}", result); } } }
facebook-csharp-sdk/simple-json
src/SimpleJson.Tests/DataContractTests/PrivateReadonlySerializeTests.cs
C#
mit
2,437
var MusicView = React.createClass({ getInitialState: function() { return {album: null} }, render: function() { if (this.state.album){ return ( <div className="musicView" > <h2 className="musicName"> {this.state.album.name} </h2> <h3 className="musicAuthor"> {this.state.album.author} </h3> <img src={this.state.album.thumbnail} width="60"></img> <br/> {this.state.album.summary} <br/> <b>Release date:</b> {this.state.album.rlsdate} <br/> <b>Genre:</b> {this.state.album.genre} <br/> <b>Score:</b> {this.state.album.score} <br/> <b>Link:</b> <a href={this.state.album.url}>{this.state.album.url}</a> <br/> </div> ) }else{ return ( <h2>Click an item to see details</h2> ) } } })
melissabica/metacritic-react
contents/js/music/view.js
JavaScript
mit
1,088
// Windows implementation of system_error_category // // Copyright Beman Dawes 2002, 2006 // Copyright (c) Microsoft Corporation 2014 // Copyright 2018 Peter Dimov // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See library home page at http://www.boost.org/libs/system #include <boost/winapi/error_codes.hpp> #include <boost/winapi/error_handling.hpp> #include <boost/winapi/character_code_conversion.hpp> #include <boost/winapi/local_memory.hpp> #include <cstdio> // namespace boost { namespace system { namespace detail { #if ( defined(_MSC_VER) && _MSC_VER < 1900 ) || ( defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR) ) inline char const * unknown_message_win32( int ev, char * buffer, std::size_t len ) { # if defined( BOOST_MSVC ) # pragma warning( push ) # pragma warning( disable: 4996 ) # endif _snprintf( buffer, len - 1, "Unknown error (%d)", ev ); buffer[ len - 1 ] = 0; return buffer; # if defined( BOOST_MSVC ) # pragma warning( pop ) # endif } #else inline char const * unknown_message_win32( int ev, char * buffer, std::size_t len ) { std::snprintf( buffer, len, "Unknown error (%d)", ev ); return buffer; } #endif inline boost::winapi::UINT_ message_cp_win32() { #if defined(BOOST_SYSTEM_USE_UTF8) return boost::winapi::CP_UTF8_; #else return boost::winapi::CP_ACP_; #endif } inline char const * system_category_message_win32( int ev, char * buffer, std::size_t len ) BOOST_NOEXCEPT { if( len == 0 ) { return buffer; } if( len == 1 ) { buffer[0] = 0; return buffer; } boost::winapi::UINT_ const code_page = message_cp_win32(); int r = 0; #if !defined(BOOST_NO_ANSI_APIS) if( code_page == boost::winapi::CP_ACP_ ) { using namespace boost::winapi; DWORD_ retval = boost::winapi::FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM_ | FORMAT_MESSAGE_IGNORE_INSERTS_, NULL, ev, MAKELANGID_( LANG_NEUTRAL_, SUBLANG_DEFAULT_ ), // Default language buffer, static_cast<DWORD_>( len ), NULL ); r = static_cast<int>( retval ); } else #endif { using namespace boost::winapi; wchar_t * lpMsgBuf = 0; DWORD_ retval = boost::winapi::FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER_ | FORMAT_MESSAGE_FROM_SYSTEM_ | FORMAT_MESSAGE_IGNORE_INSERTS_, NULL, ev, MAKELANGID_( LANG_NEUTRAL_, SUBLANG_DEFAULT_ ), // Default language (LPWSTR_) &lpMsgBuf, 0, NULL ); if( retval != 0 ) { r = boost::winapi::WideCharToMultiByte( code_page, 0, lpMsgBuf, -1, buffer, static_cast<int>( len ), NULL, NULL ); boost::winapi::LocalFree( lpMsgBuf ); if ( r != 0 ) --r; // exclude null terminator } } if( r == 0 ) { return unknown_message_win32( ev, buffer, len ); } while( r > 0 && ( buffer[ r-1 ] == '\n' || buffer[ r-1 ] == '\r' ) ) { buffer[ --r ] = 0; } if( r > 0 && buffer[ r-1 ] == '.' ) { buffer[ --r ] = 0; } return buffer; } struct local_free { void * p_; ~local_free() { boost::winapi::LocalFree( p_ ); } }; inline std::string unknown_message_win32( int ev ) { char buffer[ 38 ]; return unknown_message_win32( ev, buffer, sizeof( buffer ) ); } inline std::string system_category_message_win32( int ev ) { using namespace boost::winapi; wchar_t * lpMsgBuf = 0; DWORD_ retval = boost::winapi::FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER_ | FORMAT_MESSAGE_FROM_SYSTEM_ | FORMAT_MESSAGE_IGNORE_INSERTS_, NULL, ev, MAKELANGID_( LANG_NEUTRAL_, SUBLANG_DEFAULT_ ), // Default language (LPWSTR_) &lpMsgBuf, 0, NULL ); if( retval == 0 ) { return unknown_message_win32( ev ); } local_free lf_ = { lpMsgBuf }; (void)lf_; UINT_ const code_page = message_cp_win32(); int r = boost::winapi::WideCharToMultiByte( code_page, 0, lpMsgBuf, -1, 0, 0, NULL, NULL ); if( r == 0 ) { return unknown_message_win32( ev ); } std::string buffer( r, char() ); r = boost::winapi::WideCharToMultiByte( code_page, 0, lpMsgBuf, -1, &buffer[0], r, NULL, NULL ); if( r == 0 ) { return unknown_message_win32( ev ); } --r; // exclude null terminator while( r > 0 && ( buffer[ r-1 ] == '\n' || buffer[ r-1 ] == '\r' ) ) { --r; } if( r > 0 && buffer[ r-1 ] == '.' ) { --r; } buffer.resize( r ); return buffer; } inline error_condition system_category_default_error_condition_win32( int ev ) BOOST_NOEXCEPT { // When using the Windows Runtime, most system errors are reported as HRESULTs. // We want to map the common Win32 errors to their equivalent error condition, // whether or not they are reported via an HRESULT. #define BOOST_SYSTEM_FAILED(hr) ((hr) < 0) #define BOOST_SYSTEM_HRESULT_FACILITY(hr) (((hr) >> 16) & 0x1fff) #define BOOST_SYSTEM_HRESULT_CODE(hr) ((hr) & 0xFFFF) #define BOOST_SYSTEM_FACILITY_WIN32 7 if( BOOST_SYSTEM_FAILED( ev ) && BOOST_SYSTEM_HRESULT_FACILITY( ev ) == BOOST_SYSTEM_FACILITY_WIN32 ) { ev = BOOST_SYSTEM_HRESULT_CODE( ev ); } #undef BOOST_SYSTEM_FAILED #undef BOOST_SYSTEM_HRESULT_FACILITY #undef BOOST_SYSTEM_HRESULT_CODE #undef BOOST_SYSTEM_FACILITY_WIN32 using namespace boost::winapi; using namespace errc; // Windows system -> posix_errno decode table // see WinError.h comments for descriptions of errors switch ( ev ) { case 0: return make_error_condition( success ); case ERROR_ACCESS_DENIED_: return make_error_condition( permission_denied ); case ERROR_ALREADY_EXISTS_: return make_error_condition( file_exists ); case ERROR_BAD_UNIT_: return make_error_condition( no_such_device ); case ERROR_BUFFER_OVERFLOW_: return make_error_condition( filename_too_long ); case ERROR_BUSY_: return make_error_condition( device_or_resource_busy ); case ERROR_BUSY_DRIVE_: return make_error_condition( device_or_resource_busy ); case ERROR_CANNOT_MAKE_: return make_error_condition( permission_denied ); case ERROR_CANTOPEN_: return make_error_condition( io_error ); case ERROR_CANTREAD_: return make_error_condition( io_error ); case ERROR_CANTWRITE_: return make_error_condition( io_error ); case ERROR_CURRENT_DIRECTORY_: return make_error_condition( permission_denied ); case ERROR_DEV_NOT_EXIST_: return make_error_condition( no_such_device ); case ERROR_DEVICE_IN_USE_: return make_error_condition( device_or_resource_busy ); case ERROR_DIR_NOT_EMPTY_: return make_error_condition( directory_not_empty ); case ERROR_DIRECTORY_: return make_error_condition( invalid_argument ); // WinError.h: "The directory name is invalid" case ERROR_DISK_FULL_: return make_error_condition( no_space_on_device ); case ERROR_FILE_EXISTS_: return make_error_condition( file_exists ); case ERROR_FILE_NOT_FOUND_: return make_error_condition( no_such_file_or_directory ); case ERROR_HANDLE_DISK_FULL_: return make_error_condition( no_space_on_device ); case ERROR_INVALID_ACCESS_: return make_error_condition( permission_denied ); case ERROR_INVALID_DRIVE_: return make_error_condition( no_such_device ); case ERROR_INVALID_FUNCTION_: return make_error_condition( function_not_supported ); case ERROR_INVALID_HANDLE_: return make_error_condition( invalid_argument ); case ERROR_INVALID_NAME_: return make_error_condition( invalid_argument ); case ERROR_LOCK_VIOLATION_: return make_error_condition( no_lock_available ); case ERROR_LOCKED_: return make_error_condition( no_lock_available ); case ERROR_NEGATIVE_SEEK_: return make_error_condition( invalid_argument ); case ERROR_NOACCESS_: return make_error_condition( permission_denied ); case ERROR_NOT_ENOUGH_MEMORY_: return make_error_condition( not_enough_memory ); case ERROR_NOT_READY_: return make_error_condition( resource_unavailable_try_again ); case ERROR_NOT_SAME_DEVICE_: return make_error_condition( cross_device_link ); case ERROR_OPEN_FAILED_: return make_error_condition( io_error ); case ERROR_OPEN_FILES_: return make_error_condition( device_or_resource_busy ); case ERROR_OPERATION_ABORTED_: return make_error_condition( operation_canceled ); case ERROR_OUTOFMEMORY_: return make_error_condition( not_enough_memory ); case ERROR_PATH_NOT_FOUND_: return make_error_condition( no_such_file_or_directory ); case ERROR_READ_FAULT_: return make_error_condition( io_error ); case ERROR_RETRY_: return make_error_condition( resource_unavailable_try_again ); case ERROR_SEEK_: return make_error_condition( io_error ); case ERROR_SHARING_VIOLATION_: return make_error_condition( permission_denied ); case ERROR_TOO_MANY_OPEN_FILES_: return make_error_condition( too_many_files_open ); case ERROR_WRITE_FAULT_: return make_error_condition( io_error ); case ERROR_WRITE_PROTECT_: return make_error_condition( permission_denied ); case WSAEACCES_: return make_error_condition( permission_denied ); case WSAEADDRINUSE_: return make_error_condition( address_in_use ); case WSAEADDRNOTAVAIL_: return make_error_condition( address_not_available ); case WSAEAFNOSUPPORT_: return make_error_condition( address_family_not_supported ); case WSAEALREADY_: return make_error_condition( connection_already_in_progress ); case WSAEBADF_: return make_error_condition( bad_file_descriptor ); case WSAECONNABORTED_: return make_error_condition( connection_aborted ); case WSAECONNREFUSED_: return make_error_condition( connection_refused ); case WSAECONNRESET_: return make_error_condition( connection_reset ); case WSAEDESTADDRREQ_: return make_error_condition( destination_address_required ); case WSAEFAULT_: return make_error_condition( bad_address ); case WSAEHOSTUNREACH_: return make_error_condition( host_unreachable ); case WSAEINPROGRESS_: return make_error_condition( operation_in_progress ); case WSAEINTR_: return make_error_condition( interrupted ); case WSAEINVAL_: return make_error_condition( invalid_argument ); case WSAEISCONN_: return make_error_condition( already_connected ); case WSAEMFILE_: return make_error_condition( too_many_files_open ); case WSAEMSGSIZE_: return make_error_condition( message_size ); case WSAENAMETOOLONG_: return make_error_condition( filename_too_long ); case WSAENETDOWN_: return make_error_condition( network_down ); case WSAENETRESET_: return make_error_condition( network_reset ); case WSAENETUNREACH_: return make_error_condition( network_unreachable ); case WSAENOBUFS_: return make_error_condition( no_buffer_space ); case WSAENOPROTOOPT_: return make_error_condition( no_protocol_option ); case WSAENOTCONN_: return make_error_condition( not_connected ); case WSAENOTSOCK_: return make_error_condition( not_a_socket ); case WSAEOPNOTSUPP_: return make_error_condition( operation_not_supported ); case WSAEPROTONOSUPPORT_: return make_error_condition( protocol_not_supported ); case WSAEPROTOTYPE_: return make_error_condition( wrong_protocol_type ); case WSAETIMEDOUT_: return make_error_condition( timed_out ); case WSAEWOULDBLOCK_: return make_error_condition( operation_would_block ); default: return error_condition( ev, system_category() ); } } } // namespace detail } // namespace system } // namespace boost
PopcornTimeTV/PopcornTorrent
include/boost/system/detail/system_category_win32.hpp
C++
mit
11,866
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtPositioning module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QGEOSHAPE_P_H #define QGEOSHAPE_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include <QtCore/QSharedData> #include "qgeoshape.h" QT_BEGIN_NAMESPACE class QGeoShapePrivate : public QSharedData { public: explicit QGeoShapePrivate(QGeoShape::ShapeType type); virtual ~QGeoShapePrivate(); virtual bool isValid() const = 0; virtual bool isEmpty() const = 0; virtual bool contains(const QGeoCoordinate &coordinate) const = 0; virtual void extendShape(const QGeoCoordinate &coordinate) = 0; virtual QGeoShapePrivate *clone() const = 0; virtual bool operator==(const QGeoShapePrivate &other) const; QGeoShape::ShapeType type; }; // don't use the copy constructor when detaching from a QSharedDataPointer, use virtual clone() // call instead. template <> Q_INLINE_TEMPLATE QGeoShapePrivate *QSharedDataPointer<QGeoShapePrivate>::clone() { return d->clone(); } QT_END_NAMESPACE #endif
imzcy/JavaScriptExecutable
thirdparty/qt53/include/QtPositioning/5.3.0/QtPositioning/private/qgeoshape_p.h
C
mit
3,118
(function($) { $(document).ready(function() { $('.styleswitch').click(function() { switchStylestyle(this.getAttribute("rel")); return false; }); var c = readCookie('style'); if (c) switchStylestyle(c); }); function switchStylestyle(styleName) { $('link[rel*=style][title]').each(function(i) { this.disabled = true; if (this.getAttribute('title') == styleName) this.disabled = false; }); createCookie('style', styleName, 365); } })(jQuery); // Cookie functions function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); } // Switcher jQuery('.demo_changer .demo-icon').click(function(){ if(jQuery('.demo_changer').hasClass("active")){ jQuery('.demo_changer').animate({"left":"-140px"},function(){ jQuery('.demo_changer').toggleClass("active"); }); }else{ jQuery('.demo_changer').animate({"left":"0px"},function(){ jQuery('.demo_changer').toggleClass("active"); }); } });
myunimol/website
public/js/fswit.js
JavaScript
mit
1,502
const express = require('express') const app = express() const formidable = require('formidable') const path = require('path') const rimraf = require('rimraf') const fs = require('fs') const throttle = require('express-throttle-bandwidth') const port = process.env.PORT || 4444, folder = path.join(__dirname, 'files') if (!fs.existsSync(folder)) { fs.mkdirSync(folder) } else { rimraf.sync(path.join(folder, '*')) } process.on('exit', () => { rimraf.sync(path.join(folder)) }) app.set('port', port) app.use(throttle(1024 * 128)) app.use((_, res, next) => { res.header('Access-Control-Allow-Origin', '*') res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') next() }) app.post('/upload', (req, res) => { rimraf.sync(path.join(folder, '*')) const form = new formidable.IncomingForm() form.uploadDir = folder form.parse(req, (_, fields, files) => { console.log('\n-----------') console.log('Fields', fields) console.log('Received:', Object.keys(files)) console.log() }) res.send('Thank you') }) app.listen(port, () => { console.log('\nUpload server running on http://localhost:' + port + '/upload') console.log('You can now upload from main dev server using QUploader') })
rstoenescu/quasar-framework
ui/dev/upload-server/server.js
JavaScript
mit
1,266
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > If the argument len is a Number and ToUint32(len) is equal to len, then the length property of the newly constructed object is set to ToUint32(len) es5id: 15.4.2.2_A2.1_T1 description: Array constructor is given one argument ---*/ //CHECK#1 var x = new Array(0); if (x.length !== 0) { $ERROR('#1: var x = new Array(0); x.length === 0. Actual: ' + (x.length)); } //CHECK#2 var x = new Array(1); if (x.length !== 1) { $ERROR('#2: var x = new Array(1); x.length === 1. Actual: ' + (x.length)); } //CHECK#3 var x = new Array(4294967295); if (x.length !== 4294967295) { $ERROR('#3: var x = new Array(4294967295); x.length === 4294967295. Actual: ' + (x.length)); }
PiotrDabkowski/Js2Py
tests/test_cases/built-ins/Array/length/S15.4.2.2_A2.1_T1.js
JavaScript
mit
830
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { PropTypes } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Content.css'; function Content({ path, title, content }) { return ( <div className={s.root}> <div className={s.container}> {title && path !== '/' && <h1>{title}</h1>} <div dangerouslySetInnerHTML={{ __html: content }} /> </div> </div> ); } Content.propTypes = { path: PropTypes.string.isRequired, content: PropTypes.string.isRequired, title: PropTypes.string, }; export default withStyles(s)(Content);
rowinf/robertirwin.me-v2
src/routes/content/Content.js
JavaScript
mit
838
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Logz.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Linq; public partial class PlanData { /// <summary> /// Initializes a new instance of the PlanData class. /// </summary> public PlanData() { CustomInit(); } /// <summary> /// Initializes a new instance of the PlanData class. /// </summary> /// <param name="usageType">different usage type like PAYG/COMMITTED. /// this could be enum</param> /// <param name="billingCycle">different billing cycles like /// MONTHLY/WEEKLY. this could be enum</param> /// <param name="planDetails">plan id as published by Logz</param> /// <param name="effectiveDate">date when plan was applied</param> public PlanData(string usageType = default(string), string billingCycle = default(string), string planDetails = default(string), System.DateTime? effectiveDate = default(System.DateTime?)) { UsageType = usageType; BillingCycle = billingCycle; PlanDetails = planDetails; EffectiveDate = effectiveDate; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets different usage type like PAYG/COMMITTED. this could /// be enum /// </summary> [JsonProperty(PropertyName = "usageType")] public string UsageType { get; set; } /// <summary> /// Gets or sets different billing cycles like MONTHLY/WEEKLY. this /// could be enum /// </summary> [JsonProperty(PropertyName = "billingCycle")] public string BillingCycle { get; set; } /// <summary> /// Gets or sets plan id as published by Logz /// </summary> [JsonProperty(PropertyName = "planDetails")] public string PlanDetails { get; set; } /// <summary> /// Gets or sets date when plan was applied /// </summary> [JsonProperty(PropertyName = "effectiveDate")] public System.DateTime? EffectiveDate { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (UsageType != null) { if (UsageType.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "UsageType", 50); } } if (BillingCycle != null) { if (BillingCycle.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "BillingCycle", 50); } } if (PlanDetails != null) { if (PlanDetails.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "PlanDetails", 50); } } } } }
ayeletshpigelman/azure-sdk-for-net
sdk/logz/Microsoft.Azure.Management.Logz/src/Generated/Models/PlanData.cs
C#
mit
3,665
using System.Collections.Generic; using System.Linq; using NuGet; namespace APIComparer.VersionComparisons { class CompareAgainstNextReleaseStrategy : ICompareStrategy { public IEnumerable<VersionPair> GetVersionsToCompare(List<SemanticVersion> semverCompliantVersions) { var majorGroups = semverCompliantVersions.GroupBy(v => v.Version.Major); foreach (var major in majorGroups) { var left = major.First(); foreach (var right in major) { if (right == left) { continue; } yield return new VersionPair(left.Version.ToString(), right.Version.ToString()); left = right; } } } } }
modernist/APIComparer
APIComparer/VersionComparisons/CompareAgainstNextReleaseStrategy.cs
C#
mit
854
package gocaptcha import ( "bytes" "crypto/md5" "encoding/gob" "encoding/hex" "fmt" "log" "strconv" "strings" "time" "gopkg.in/redis.v2" ) func init() { RegisterStore(storeName, CreateCaptchaRedisStore) } const ( captchaKeyFormat = "captcha:text:%s;rand:%s;time:%x;" storeName = "redis" ) type CaptchaRedisStore struct { lifeTime time.Duration stg *redis.Client } func CreateCaptchaRedisStore(config *StoreConfig) (StoreInterface, error) { lifeTime := config.LifeTime if config.Servers == nil || len(config.Servers) == 0 { return nil, fmt.Errorf("servers must not be empty") } fullAddr := strings.TrimPrefix(config.Servers[0], "redis://") pieces := strings.SplitN(fullAddr, "/", 2) db := 0 addr := pieces[0] if len(pieces) == 2 { db, _ = strconv.Atoi(pieces[1]) } opt := redis.Options{} opt.Addr = addr opt.DB = int64(db) opt.PoolSize = 0 stg := redis.NewTCPClient(&opt) return &CaptchaRedisStore{lifeTime, stg}, nil } func (this *CaptchaRedisStore) Get(key string) *CaptchaInfo { s, err := this.stg.Get(key).Result() if err != nil { log.Printf("get key in redis error:%s", err) return nil } captcha := CaptchaInfo{} this.decodeCaptachInfo([]byte(s), &captcha) return &captcha } func (this *CaptchaRedisStore) Add(captcha *CaptchaInfo) string { key := fmt.Sprintf(captchaKeyFormat, captcha.Text, randStr(20), captcha.CreateTime.Unix()) key = hex.EncodeToString(md5.New().Sum([]byte(key))) key = key[:32] val, err := this.encodeCaptchaInfo(captcha) if err == nil { if seterr := this.stg.SetEx(key, this.lifeTime, string(val)); seterr != nil { log.Printf("add key in redis error:%s", seterr) } } return key } func (this *CaptchaRedisStore) Del(key string) { this.stg.Del(key) } func (this *CaptchaRedisStore) Destroy() { } func (this *CaptchaRedisStore) OnConstruct() { } func (this *CaptchaRedisStore) OnDestruct() { } func (this *CaptchaRedisStore) encodeCaptchaInfo(captcha *CaptchaInfo) ([]byte, error) { buf := new(bytes.Buffer) encoder := gob.NewEncoder(buf) err := encoder.Encode(captcha) if err != nil { log.Printf("encode captcha info error:%s", err) return nil, err } return buf.Bytes(), nil } func (this *CaptchaRedisStore) decodeCaptachInfo(b []byte, ret *CaptchaInfo) { buf := bytes.NewBuffer(b) decoder := gob.NewDecoder(buf) if err := decoder.Decode(ret); err != nil { log.Printf("decode captcha info error:%s", err) } return }
piaoxj/gocaptcha
redisstore.go
GO
mit
2,452
import asposebarcodecloud from asposebarcodecloud.BarcodeApi import BarcodeApi from asposebarcodecloud.BarcodeApi import ApiException import asposestoragecloud from asposestoragecloud.StorageApi import StorageApi from asposestoragecloud.StorageApi import ResponseMessage import ConfigParser config = ConfigParser.ConfigParser() config.readfp(open(r'../../data/config.properties')) apiKey = config.get('AppConfig', 'api_key') appSid = config.get('AppConfig', 'app_sid') out_folder = config.get('AppConfig', 'out_folder') data_folder = "../../data/" #resouece data folder #ExStart:1 #Instantiate Aspose Storage API SDK storage_apiClient = asposestoragecloud.ApiClient.ApiClient(apiKey, appSid, True) storageApi = StorageApi(storage_apiClient) #Instantiate Aspose Barcode API SDK api_client = asposebarcodecloud.ApiClient.ApiClient(apiKey, appSid, True) barcodeApi = BarcodeApi(api_client); #Set the barcode file name created on server name = "sample-barcode" #Set Text to encode inside barcode. text = "Aspose.BarCode" #Set Barcode Symbology type = "Code128" #Set Generated Barcode Image Format format = "PNG" #Set height, Width and quality of the image imageHeight = 1.0; imageWidth = 1.0; imageQuality = "default"; try: #invoke Aspose.BarCode Cloud SDK API to generate image with specific height, width, and quality along with auto size option response = barcodeApi.PutBarcodeGenerateFile(name, file= None, text=text, type=type, format=format, imageHeight=imageHeight, imageWidth=imageWidth, imageQuality=imageQuality) if response.Status == "OK": #download generated barcode from cloud storage response = storageApi.GetDownload(Path=name) outfilename = out_folder + name + "." + format with open(outfilename, 'wb') as f: for chunk in response.InputStream: f.write(chunk) except ApiException as ex: print "ApiException:" print "Code:" + str(ex.code) print "Message:" + ex.message #ExEnd:1
farooqsheikhpk/Aspose.BarCode-for-Cloud
Examples/Python/generating-saving/cloud-storage/set-barcode-image-height-width-quality-settings.py
Python
mit
2,140
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> <link href="other/help.css" type="text/css" rel="stylesheet" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="other/help.js"></script> </head> <body> <h1> Barra de Estado</h1> <p> La "Barra de Estado" es un peque&ntilde;o espacio usado para desplegar informaci&oacute;n relevante al archivo seleccionado, el n&uacute;mero total de archivos en la carpeta, etc. Se puede encontrar al final de la interface de CKFinder</p> <p> Si <strong>un archivo es seleccionado </strong> en CKFinder, la barra de estado desplegar&aacute; informaci&oacute;n detallada acerca de ese archivo en particular, contendr&aacute; el nombre del archivo, su tama&ntilde;o y la fecha de su &uacute;ltima modificaci&oacute;n, por ejemplo: </p> <p style="text-align: center"> <img src="images/018.png" width="257" height="16" alt="adivina.xls (2444Kb 21/03/2010)"/>&nbsp;</p> <p>Si<strong> ning&uacute;n archivo est&aacute; seleccionado</strong> por el contrario, el n&uacute;mero total de archivos en la carpeta actual ser&aacute; mostrado. Por ejemplo: </p> <p style="text-align: center"> <img src="images/019.png" width="145" height="15" alt="2 ficheros"/>&nbsp;</p> </body> </html>
nlkhagva/educenter.mn
web/js/ckfinder/help/es-mx/files/010.html
HTML
mit
1,409
/* Copyright (c) 2013-2022 Mahmoud Fayed <msfclipper@yahoo.com> */ #include "ring.h" /* Jump Functions */ void ring_vm_jump ( VM *pVM ) { RING_VM_JUMP ; } void ring_vm_jumpzero ( VM *pVM ) { List *pList ; Item *pItem ; if ( RING_VM_STACK_ISNUMBER ) { if ( RING_VM_STACK_READN == 0 ) { ring_vm_jump(pVM); } } else if ( RING_VM_STACK_ISSTRING ) { if ( strcmp(RING_VM_STACK_READC,"") == 0 ) { ring_vm_jump(pVM); } } else if ( RING_VM_STACK_ISPOINTER ) { if ( RING_VM_STACK_OBJTYPE == RING_OBJTYPE_VARIABLE ) { pList = (List *) RING_VM_STACK_READP ; pList = ring_list_getlist(pList,RING_VAR_VALUE) ; if ( ring_list_getsize(pList) == 0 ) { ring_vm_jump(pVM); } } else if ( RING_VM_STACK_OBJTYPE == RING_OBJTYPE_LISTITEM ) { pItem = (Item *) RING_VM_STACK_READP ; pList = ring_item_getlist(pItem) ; if ( ring_list_getsize(pList) == 0 ) { ring_vm_jump(pVM); } } } RING_VM_STACK_POP ; } void ring_vm_jumpfor ( VM *pVM ) { double nNum1,nNum2,nNum3 ; /* Check Data */ if ( RING_VM_STACK_ISNUMBER ) { nNum1 = RING_VM_STACK_READN ; RING_VM_STACK_POP ; } else if ( RING_VM_STACK_ISSTRING ) { nNum1 = ring_vm_stringtonum(pVM,RING_VM_STACK_READC); RING_VM_STACK_POP ; } else { ring_vm_error(pVM,RING_VM_ERROR_FORLOOPDATATYPE); return ; } nNum2 = ring_list_getdouble(pVM->aForStep,ring_list_getsize(pVM->aForStep)); /* Check Data */ if ( RING_VM_STACK_ISNUMBER ) { nNum3 = RING_VM_STACK_READN ; RING_VM_STACK_POP ; } else if ( RING_VM_STACK_ISSTRING ) { nNum3 = ring_vm_stringtonum(pVM,RING_VM_STACK_READC); RING_VM_STACK_POP ; } else { ring_vm_error(pVM,RING_VM_ERROR_FORLOOPDATATYPE); return ; } /* ** nNum2 = Step value that can be positive or negative ** nNum1 = Items Count , nNum3 = Index */ if ( nNum2 < 0 ) { if ( ! ( nNum3 >= nNum1 ) ) { ring_vm_jump(pVM); } } else { if ( ! ( nNum3 <= nNum1 ) ) { ring_vm_jump(pVM); } } } void ring_vm_jumpone ( VM *pVM ) { List *pList ; Item *pItem ; if ( RING_VM_STACK_ISNUMBER ) { if ( RING_VM_STACK_READN != 0 ) { ring_vm_jump(pVM); } } else if ( RING_VM_STACK_ISSTRING ) { if ( strcmp(RING_VM_STACK_READC,"") != 0 ) { ring_vm_jump(pVM); } } else if ( RING_VM_STACK_ISPOINTER ) { if ( RING_VM_STACK_OBJTYPE == RING_OBJTYPE_VARIABLE ) { pList = (List *) RING_VM_STACK_READP ; pList = ring_list_getlist(pList,RING_VAR_VALUE) ; if ( ring_list_getsize(pList) != 0 ) { ring_vm_jump(pVM); } } else if ( RING_VM_STACK_OBJTYPE == RING_OBJTYPE_LISTITEM ) { pItem = (Item *) RING_VM_STACK_READP ; pList = ring_item_getlist(pItem) ; if ( ring_list_getsize(pList) != 0 ) { ring_vm_jump(pVM); } } } RING_VM_STACK_POP ; } void ring_vm_jumpone2 ( VM *pVM ) { List *pList ; Item *pItem ; /* Add 1, required for jump in many 'OR' in conditions */ if ( RING_VM_STACK_ISNUMBER ) { if ( RING_VM_STACK_READN != 0 ) { ring_vm_jump(pVM); return ; } } else if ( RING_VM_STACK_ISSTRING ) { if ( strcmp(RING_VM_STACK_READC,"") != 0 ) { ring_vm_jump(pVM); return ; } } else if ( RING_VM_STACK_ISPOINTER ) { if ( RING_VM_STACK_OBJTYPE == RING_OBJTYPE_VARIABLE ) { pList = (List *) RING_VM_STACK_READP ; pList = ring_list_getlist(pList,RING_VAR_VALUE) ; if ( ring_list_getsize(pList) != 0 ) { ring_vm_jump(pVM); return ; } } else if ( RING_VM_STACK_OBJTYPE == RING_OBJTYPE_LISTITEM ) { pItem = (Item *) RING_VM_STACK_READP ; pList = ring_item_getlist(pItem) ; if ( ring_list_getsize(pList) != 0 ) { ring_vm_jump(pVM); return ; } } } RING_VM_STACK_POP ; RING_VM_STACK_PUSHNVALUE(0); } void ring_vm_jumpzero2 ( VM *pVM ) { List *pList ; Item *pItem ; /* Add 1, required for jump in many 'AND' in conditions */ if ( RING_VM_STACK_ISNUMBER ) { if ( RING_VM_STACK_READN == 0 ) { ring_vm_jump(pVM); return ; } } else if ( RING_VM_STACK_ISSTRING ) { if ( strcmp(RING_VM_STACK_READC,"") == 0 ) { ring_vm_jump(pVM); return ; } } else if ( RING_VM_STACK_ISPOINTER ) { if ( RING_VM_STACK_OBJTYPE == RING_OBJTYPE_VARIABLE ) { pList = (List *) RING_VM_STACK_READP ; pList = ring_list_getlist(pList,RING_VAR_VALUE) ; if ( ring_list_getsize(pList) == 0 ) { ring_vm_jump(pVM); return ; } } else if ( RING_VM_STACK_OBJTYPE == RING_OBJTYPE_LISTITEM ) { pItem = (Item *) RING_VM_STACK_READP ; pList = ring_item_getlist(pItem) ; if ( ring_list_getsize(pList) == 0 ) { ring_vm_jump(pVM); return ; } } } RING_VM_STACK_POP ; RING_VM_STACK_PUSHNVALUE(1); }
ring-lang/ring
language/src/ring_vmjump.c
C
mit
5,646
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.authenticator; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Assert; import org.junit.Test; import org.apache.catalina.Context; import org.apache.catalina.LifecycleException; import org.apache.catalina.connector.Request; import org.apache.catalina.core.TesterContext; import org.apache.catalina.startup.TesterMapRealm; import org.apache.catalina.startup.TesterServlet; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.descriptor.web.LoginConfig; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.apache.tomcat.util.security.ConcurrentMessageDigest; import org.apache.tomcat.util.security.MD5Encoder; public class TestDigestAuthenticator extends TomcatBaseTest { private static String USER = "user"; private static String PWD = "pwd"; private static String ROLE = "role"; private static String URI = "/protected"; private static String QUERY = "?foo=bar"; private static String CONTEXT_PATH = "/foo"; private static String CLIENT_AUTH_HEADER = "authorization"; private static String REALM = "TestRealm"; private static String CNONCE = "cnonce"; private static String NC1 = "00000001"; private static String NC2 = "00000002"; private static String QOP = "auth"; @Test public void bug54521() throws LifecycleException { DigestAuthenticator digestAuthenticator = new DigestAuthenticator(); digestAuthenticator.setContainer(new TesterContext()); digestAuthenticator.start(); Request request = new TesterRequest(); final int count = 1000; Set<String> nonces = new HashSet<>(); for (int i = 0; i < count; i++) { nonces.add(digestAuthenticator.generateNonce(request)); } Assert.assertEquals(count, nonces.size()); } @Test public void testAllValid() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, NC1, NC2, CNONCE, QOP, true, true); } @Test public void testValidNoQop() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, null, null, null, null, true, true); } @Test public void testValidQuery() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI + QUERY, false, true, REALM, true, true, NC1, NC2, CNONCE, QOP, true, true); } @Test public void testInvalidUriFail() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, true, true, REALM, true, true, NC1, NC2, CNONCE, QOP, false, false); } @Test public void testInvalidUriPass() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, true, false, REALM, true, true, NC1, NC2, CNONCE, QOP, true, true); } @Test public void testInvalidRealm() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, "null", true, true, NC1, NC2, CNONCE, QOP, false, false); } @Test public void testInvalidNonce() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, false, true, NC1, NC2, CNONCE, QOP, false, true); } @Test public void testInvalidOpaque() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, false, NC1, NC2, CNONCE, QOP, false, true); } @Test public void testInvalidNc1() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, "null", null, CNONCE, QOP, false, false); } @Test public void testInvalidQop() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, NC1, NC2, CNONCE, "null", false, false); } @Test public void testInvalidQopCombo1() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, NC1, NC2, CNONCE, null, false, false); } @Test public void testInvalidQopCombo2() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, NC1, NC2, null, QOP, false, false); } @Test public void testInvalidQopCombo3() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, NC1, NC2, null, null, false, false); } @Test public void testInvalidQopCombo4() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, null, null, CNONCE, QOP, false, false); } @Test public void testInvalidQopCombo5() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, null, null, CNONCE, null, false, false); } @Test public void testInvalidQopCombo6() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, null, null, null, QOP, false, false); } @Test public void testReplay() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, NC1, NC1, CNONCE, QOP, true, false); } public void doTest(String user, String pwd, String uri, boolean breakUri, boolean validateUri, String realm, boolean useServerNonce, boolean useServerOpaque, String nc1, String nc2, String cnonce, String qop, boolean req2expect200, boolean req3expect200) throws Exception { if (!validateUri) { DigestAuthenticator auth = (DigestAuthenticator) getTomcatInstance().getHost().findChild( CONTEXT_PATH).getPipeline().getFirst(); auth.setValidateUri(false); } getTomcatInstance().start(); String digestUri; if (breakUri) { digestUri = "/broken" + uri; } else { digestUri = uri; } List<String> auth = new ArrayList<>(); auth.add(buildDigestResponse(user, pwd, digestUri, realm, "null", "null", nc1, cnonce, qop)); Map<String,List<String>> reqHeaders = new HashMap<>(); reqHeaders.put(CLIENT_AUTH_HEADER, auth); Map<String,List<String>> respHeaders = new HashMap<>(); // The first request will fail - but we need to extract the nonce ByteChunk bc = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort() + uri, bc, reqHeaders, respHeaders); assertEquals(401, rc); assertTrue(bc.getLength() > 0); bc.recycle(); // Second request should succeed (if we use the server nonce) auth.clear(); if (useServerNonce) { if (useServerOpaque) { auth.add(buildDigestResponse(user, pwd, digestUri, realm, getNonce(respHeaders), getOpaque(respHeaders), nc1, cnonce, qop)); } else { auth.add(buildDigestResponse(user, pwd, digestUri, realm, getNonce(respHeaders), "null", nc1, cnonce, qop)); } } else { auth.add(buildDigestResponse(user, pwd, digestUri, realm, "null", getOpaque(respHeaders), nc1, cnonce, QOP)); } rc = getUrl("http://localhost:" + getPort() + uri, bc, reqHeaders, null); if (req2expect200) { assertEquals(200, rc); assertEquals("OK", bc.toString()); } else { assertEquals(401, rc); assertTrue(bc.getLength() > 0); } // Third request should succeed if we increment nc auth.clear(); bc.recycle(); bc.reset(); auth.add(buildDigestResponse(user, pwd, digestUri, realm, getNonce(respHeaders), getOpaque(respHeaders), nc2, cnonce, qop)); rc = getUrl("http://localhost:" + getPort() + uri, bc, reqHeaders, null); if (req3expect200) { assertEquals(200, rc); assertEquals("OK", bc.toString()); } else { assertEquals(401, rc); assertTrue(bc.getLength() > 0); } } @Override public void setUp() throws Exception { super.setUp(); // Configure a context with digest auth and a single protected resource Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctxt = tomcat.addContext(CONTEXT_PATH, null); // Add protected servlet Tomcat.addServlet(ctxt, "TesterServlet", new TesterServlet()); ctxt.addServletMapping(URI, "TesterServlet"); SecurityCollection collection = new SecurityCollection(); collection.addPattern(URI); SecurityConstraint sc = new SecurityConstraint(); sc.addAuthRole(ROLE); sc.addCollection(collection); ctxt.addConstraint(sc); // Configure the Realm TesterMapRealm realm = new TesterMapRealm(); realm.addUser(USER, PWD); realm.addUserRole(USER, ROLE); ctxt.setRealm(realm); // Configure the authenticator LoginConfig lc = new LoginConfig(); lc.setAuthMethod("DIGEST"); lc.setRealmName(REALM); ctxt.setLoginConfig(lc); ctxt.getPipeline().addValve(new DigestAuthenticator()); } protected static String getNonce(Map<String,List<String>> respHeaders) { List<String> authHeaders = respHeaders.get(AuthenticatorBase.AUTH_HEADER_NAME); // Assume there is only one String authHeader = authHeaders.iterator().next(); int start = authHeader.indexOf("nonce=\"") + 7; int end = authHeader.indexOf("\"", start); return authHeader.substring(start, end); } protected static String getOpaque(Map<String,List<String>> respHeaders) { List<String> authHeaders = respHeaders.get(AuthenticatorBase.AUTH_HEADER_NAME); // Assume there is only one String authHeader = authHeaders.iterator().next(); int start = authHeader.indexOf("opaque=\"") + 8; int end = authHeader.indexOf("\"", start); return authHeader.substring(start, end); } /* * Notes from RFC2617 * H(data) = MD5(data) * KD(secret, data) = H(concat(secret, ":", data)) * A1 = unq(username-value) ":" unq(realm-value) ":" passwd * A2 = Method ":" digest-uri-value * request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" nc-value ":" unq(cnonce-value) ":" unq(qop-value) ":" H(A2) ) <"> */ private static String buildDigestResponse(String user, String pwd, String uri, String realm, String nonce, String opaque, String nc, String cnonce, String qop) { String a1 = user + ":" + realm + ":" + pwd; String a2 = "GET:" + uri; String md5a1 = digest(a1); String md5a2 = digest(a2); String response; if (qop == null) { response = md5a1 + ":" + nonce + ":" + md5a2; } else { response = md5a1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + md5a2; } String md5response = digest(response); StringBuilder auth = new StringBuilder(); auth.append("Digest username=\""); auth.append(user); auth.append("\", realm=\""); auth.append(realm); auth.append("\", nonce=\""); auth.append(nonce); auth.append("\", uri=\""); auth.append(uri); auth.append("\", opaque=\""); auth.append(opaque); auth.append("\", response=\""); auth.append(md5response); auth.append("\""); if (qop != null) { auth.append(", qop="); auth.append(qop); auth.append(""); } if (nc != null) { auth.append(", nc="); auth.append(nc); } if (cnonce != null) { auth.append(", cnonce=\""); auth.append(cnonce); auth.append("\""); } return auth.toString(); } private static String digest(String input) { return MD5Encoder.encode( ConcurrentMessageDigest.digestMD5(input.getBytes())); } private static class TesterRequest extends Request { @Override public String getRemoteAddr() { return "127.0.0.1"; } } }
plumer/codana
tomcat_files/8.0.22/TestDigestAuthenticator.java
Java
mit
14,017
<?php /** * Copyright (C) 2012 Derek J. Lambert * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ namespace CrEOF\Spatial\Tests\DBAL\Types; use CrEOF\Spatial\DBAL\Types\StringLexer; /** * StringLexer tests * * @author Derek J. Lambert <dlambert@dereklambert.com> * @license http://dlambert.mit-license.org MIT * * @group result_processing */ class StringLexerTest extends \PHPUnit_Framework_TestCase { public function testScannerRecognizesPointType() { $lexer = new StringLexer('POINT'); $lexer->moveNext(); $token = $lexer->lookahead; $this->assertEquals(StringLexer::T_POINT, $token['type']); $this->assertEquals('POINT', $token['value']); } public function testScannerRecognizesLineStringType() { $lexer = new StringLexer('LINESTRING'); $lexer->moveNext(); $token = $lexer->lookahead; $this->assertEquals(StringLexer::T_LINESTRING, $token['type']); $this->assertEquals('LINESTRING', $token['value']); } public function testScannerRecognizesPolygonType() { $lexer = new StringLexer('POLYGON'); $lexer->moveNext(); $token = $lexer->lookahead; $this->assertEquals(StringLexer::T_POLYGON, $token['type']); $this->assertEquals('POLYGON', $token['value']); } public function testScannerRecognizesMultiPointType() { $lexer = new StringLexer('MULTIPOINT'); $lexer->moveNext(); $token = $lexer->lookahead; $this->assertEquals(StringLexer::T_MULTIPOINT, $token['type']); $this->assertEquals('MULTIPOINT', $token['value']); } public function testScannerRecognizesMultiLineStringType() { $lexer = new StringLexer('MULTILINESTRING'); $lexer->moveNext(); $token = $lexer->lookahead; $this->assertEquals(StringLexer::T_MULTILINESTRING, $token['type']); $this->assertEquals('MULTILINESTRING', $token['value']); } public function testScannerRecognizesMultiPolygonType() { $lexer = new StringLexer('MULTIPOLYGON'); $lexer->moveNext(); $token = $lexer->lookahead; $this->assertEquals(StringLexer::T_MULTIPOLYGON, $token['type']); $this->assertEquals('MULTIPOLYGON', $token['value']); } public function testScannerRecognizesGeometryCollectionType() { $lexer = new StringLexer('GEOMETRYCOLLECTION'); $lexer->moveNext(); $token = $lexer->lookahead; $this->assertEquals(StringLexer::T_GEOMETRYCOLLECTION, $token['type']); $this->assertEquals('GEOMETRYCOLLECTION', $token['value']); } public function testScannerRecognizesPositiveInteger() { $lexer = new StringLexer('35'); $lexer->moveNext(); $token = $lexer->lookahead; $this->assertEquals(StringLexer::T_INTEGER, $token['type']); $this->assertEquals(35, $token['value']); } public function testScannerRecognizesNegativeInteger() { $lexer = new StringLexer('-25'); $lexer->moveNext(); $token = $lexer->lookahead; $this->assertEquals(StringLexer::T_INTEGER, $token['type']); $this->assertEquals(-25, $token['value']); } public function testScannerRecognizesPositiveFloat() { $lexer = new StringLexer('35.635'); $lexer->moveNext(); $token = $lexer->lookahead; $this->assertEquals(StringLexer::T_FLOAT, $token['type']); $this->assertEquals(35.635, $token['value']); } public function testScannerRecognizesNegativeFloat() { $lexer = new StringLexer('-120.33'); $lexer->moveNext(); $token = $lexer->lookahead; $this->assertEquals(StringLexer::T_FLOAT, $token['type']); $this->assertEquals(-120.33, $token['value']); } public function testScannerRecognizesSrid() { $lexer = new StringLexer('SRID'); $lexer->moveNext(); $token = $lexer->lookahead; $this->assertEquals(StringLexer::T_SRID, $token['type']); $this->assertEquals('SRID', $token['value']); } public function testScannerTokenizesGeometryValueCorrectly() { $value = 'SRID=4326;LINESTRING(0 0.0, 10.1 -10.025, 20.5 25.9, 50 60)'; $tokens = array( array( 'value' => 'SRID', 'type' => StringLexer::T_SRID, 'position' => 0 ), array( 'value' => '=', 'type' => StringLexer::T_EQUALS, 'position' => 4 ), array( 'value' => '4326', 'type' => StringLexer::T_INTEGER, 'position' => 5 ), array( 'value' => ';', 'type' => StringLexer::T_SEMICOLON, 'position' => 9 ), array( 'value' => 'LINESTRING', 'type' => StringLexer::T_LINESTRING, 'position' => 10 ), array( 'value' => '(', 'type' => StringLexer::T_OPEN_PARENTHESIS, 'position' => 20 ), array( 'value' => 0, 'type' => StringLexer::T_INTEGER, 'position' => 21 ), array( 'value' => 0, 'type' => StringLexer::T_FLOAT, 'position' => 23 ), array( 'value' => ',', 'type' => StringLexer::T_COMMA, 'position' => 26 ), array( 'value' => 10.1, 'type' => StringLexer::T_FLOAT, 'position' => 28 ), array( 'value' => -10.025, 'type' => StringLexer::T_FLOAT, 'position' => 33 ), array( 'value' => ',', 'type' => StringLexer::T_COMMA, 'position' => 40 ), array( 'value' => 20.5, 'type' => StringLexer::T_FLOAT, 'position' => 42 ), array( 'value' => 25.9, 'type' => StringLexer::T_FLOAT, 'position' => 47 ), array( 'value' => ',', 'type' => StringLexer::T_COMMA, 'position' => 51 ), array( 'value' => 50, 'type' => StringLexer::T_INTEGER, 'position' => 53 ), array( 'value' => 60, 'type' => StringLexer::T_INTEGER, 'position' => 56 ), array( 'value' => ')', 'type' => StringLexer::T_CLOSE_PARENTHESIS, 'position' => 58 ) ); $lexer = new StringLexer($value); foreach ($tokens as $expected) { $lexer->moveNext(); $actual = $lexer->lookahead; $this->assertEquals($expected, $actual); } $this->assertFalse($lexer->moveNext()); } }
articque/doctrine2-spatial
tests/CrEOF/Spatial/Tests/DBAL/Types/StringLexerTest.php
PHP
mit
8,482
# Create, Run and Cancel Synapse Spark jobs This sample demonstrates basic operations with two core classes in this library: `SparkBatchClient` and `SparkBatchJob`. `SparkBatchClient` is used to interact with Spark jobs running on Azure Synapse - each method call sends a request to the service's REST API. `SparkBatchJob` is an entity that represents a batched Spark job within Synapse. The sample walks through the basics of creating, running, and canceling job requests. To get started, you'll need a connection endpoint to Azure Synapse. See the [README](https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/synapse/Azure.Analytics.Synapse.Spark/README.md) for links and instructions. ## Create Spark batch client To interact with Spark jobs running on Azure Synapse, you need to instantiate a `SparkBatchClient`. It requires an endpoint URL and a `TokenCredential`. ```C# Snippet:CreateSparkBatchClient // Replace the strings below with the spark, endpoint, and file system information string sparkPoolName = "<my-spark-pool-name>"; string endpoint = "<my-endpoint-url>"; string storageAccount = "<my-storage-account-name>"; string fileSystem = "<my-storage-filesystem-name>"; SparkBatchClient client = new SparkBatchClient(new Uri(endpoint), sparkPoolName, new DefaultAzureCredential()); ``` ## Submitting Spark jobs To submit a Spark job, first create a `SparkBatchJob`, passing in an instance of `SparkBatchJobOptions` describing the job's parameters. Calling `StartCreateSparkBatchJob` with that job will submit it to Synapse. ```C# Snippet:SubmitSparkBatchJob string name = $"batch-{Guid.NewGuid()}"; string file = string.Format("abfss://{0}@{1}.dfs.core.windows.net/samples/net/wordcount/wordcount.zip", fileSystem, storageAccount); SparkBatchJobOptions request = new SparkBatchJobOptions(name, file) { ClassName = "WordCount", Arguments = { string.Format("abfss://{0}@{1}.dfs.core.windows.net/samples/net/wordcount/shakespeare.txt", fileSystem, storageAccount), string.Format("abfss://{0}@{1}.dfs.core.windows.net/samples/net/wordcount/result/", fileSystem, storageAccount), }, DriverMemory = "28g", DriverCores = 4, ExecutorMemory = "28g", ExecutorCores = 4, ExecutorCount = 2 }; SparkBatchOperation createOperation = client.StartCreateSparkBatchJob(request); while (!createOperation.HasCompleted) { System.Threading.Thread.Sleep(2000); createOperation.UpdateStatus(); } SparkBatchJob jobCreated = createOperation.Value; ``` ## Retrieve a Spark job To retrieve the details of a Spark job call `StartGetSparkBatchJob`, passing in the Spark job ID. ```C# Snippet:GetSparkBatchJob SparkBatchJob retrievedJob = client.GetSparkBatchJob (jobCreated.Id); Debug.WriteLine($"Job is returned with name {retrievedJob.Name} and state {retrievedJob.State}"); ``` ## List Spark jobs To enumerate all Spark jobs in the Synapse workspace call `GetSparkBatchJobs`. ```C# Snippet:ListSparkBatchJobs Response<SparkBatchJobCollection> jobs = client.GetSparkBatchJobs(); foreach (SparkBatchJob job in jobs.Value.Sessions) { Console.WriteLine(job.Name); } ``` ## Canceling a Spark job To cancel a submitted Spark job call `CancelSparkBatchJob`, passing in the Spark job ID. ```C# Snippet:CancelSparkBatchJob Response operation = client.CancelSparkBatchJob(jobCreated.Id); ```
jackmagic313/azure-sdk-for-net
sdk/synapse/Azure.Analytics.Synapse.Spark/samples/Sample1_SubmitSparkJob.md
Markdown
mit
3,358
/* Template Name: Color Admin - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.5 Version: 1.9.0 Author: Sean Ngu Website: http://www.seantheme.com/color-admin-v1.9/admin/ */ var handleDataTableResponsive = function() { "use strict"; if ($('#data-table').length !== 0) { $('#data-table').DataTable({ responsive: true }); } }; var TableManageResponsive = function () { "use strict"; return { //main function init: function () { handleDataTableResponsive(); } }; }();
DirectDev/wds-V2
www/admin/js/table-manage-responsive.demo.js
JavaScript
mit
578
module Pronto module Formatter describe CheckstyleFormatter do let(:formatter) { described_class.new } describe '#format' do subject { formatter.format(messages, nil, nil) } let(:line) { double(new_lineno: 1, commit_sha: '123') } let(:error) { Message.new('path/to', line, :error, 'Line Error') } let(:warning) { Message.new('path/to', line, :warning, 'Line Warning') } let(:messages) { [error, warning] } it { should eq load_fixture('message_with_path.xml') } context 'message without path' do let(:error) { Message.new(nil, line, :error, 'Line Error') } it { should eq load_fixture('message_without_path.xml') } end context 'message without line' do let(:error) { Message.new('path/to', nil, :error, 'Line Error') } it { should eq load_fixture('message_without_line.xml') } end end end end end
mvz/pronto
spec/pronto/formatter/checkstyle_formatter_spec.rb
Ruby
mit
952
@extends('core::admin.master') @section('title', $model->present()->title) @section('main') @include('core::admin._button-back', ['module' => 'pages']) <h1 class="@if(!$model->present()->title)text-muted @endif"> {{ $model->present()->title ?: trans('core::global.Untitled') }} </h1> {!! BootForm::open()->put()->action(route('admin::update-page', $model->id))->multipart()->role('form') !!} {!! BootForm::bind($model) !!} @include('pages::admin._form') {!! BootForm::close() !!} @endsection
laravelproject2016/mkproject
vendor/typicms/pages/src/resources/views/admin/edit.blade.php
PHP
mit
537
#!/bin/sh #This script ensures that OneTimeSecret is automatically restarting after an error happens #Handling Errors # 0 silent # 1 email ERROR_HANDLING=0 # Your email address which should recieve the error messages EMAIL_ADDRESS="no-reply@example.com" # Sets the minimun amount of time betweens the sending of error emails. # This ensures you not get spamed while a endless reboot loop # It's the time in seconds TIME_BETWEEN_EMAILS=600 # 10 minutes # DON'T EDIT AFTER THIS LINE LAST_EMAIL_SEND=0 LOG="$1" #Move to the folder where OneTimeSecret is installed cd `dirname $0` #Was this script started in the bin folder? if yes move out if [ -d "../bin" ]; then cd "../" fi #check if a logfile parameter is set if [ -z "${LOG}" ]; then echo "Set a logfile as the first parameter" exit 1 fi shift while [ 1 ] do #try to touch the file if it doesn't exist if [ ! -f ${LOG} ]; then touch ${LOG} || ( echo "Logfile '${LOG}' is not writeable" && exit 1 ) fi #check if the file is writeable if [ ! -w ${LOG} ]; then echo "Logfile '${LOG}' is not writeable" exit 1 fi #start the application bin/run.sh $@ >>${LOG} 2>>${LOG} #Send email if [ $ERROR_HANDLIjNG = 1 ]; then TIME_NOW=$(date +%s) TIME_SINCE_LAST_SEND=$(($TIME_NOW - $LAST_EMAIL_SEND)) if [ $TIME_SINCE_LAST_SEND -gt $TIME_BETWEEN_EMAILS ]; then printf "Server was restarted at: $(date)\nThe last 50 lines of the log before the error happens:\n $(tail -n 50 ${LOG})" | mail -s "OneTimeSecret Server was restarted" $EMAIL_ADDRESS LAST_EMAIL_SEND=$TIME_NOW fi fi echo "RESTART!" >>${LOG} #Sleep 10 seconds before restart sleep 10 done
10xEngineer/onetimesecret
bin/safeRun.sh
Shell
mit
1,695
// @flow import { createPopper, popperGenerator, detectOverflow } from './createPopper'; export type * from './types'; // eslint-disable-next-line import/no-unused-modules export { createPopper, popperGenerator, detectOverflow };
FezVrasta/popper.js
src/popper-base.js
JavaScript
mit
232
/** The MIT License (MIT) Copyright (c) 2013-2015, Joe Bain Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ ;(function(name, context, definition) { if (typeof module !== 'undefined' && module.exports) { module.exports = definition(); } else if (typeof define === 'function' && define.amd) { define(definition); } else { context[name] = definition(); } })('Args', this, function argsDefinition() { "use strict"; if (!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === "[object Array]"; }; } var _extractSchemeEl = function(rawSchemeEl) { var schemeEl = {}; schemeEl.defValue = undefined; schemeEl.typeValue = undefined; schemeEl.customCheck = undefined; for (var name in rawSchemeEl) { if (!rawSchemeEl.hasOwnProperty(name)) continue; if (name === "_default") { schemeEl.defValue = rawSchemeEl[name]; } else if (name === "_type") { schemeEl.typeValue = rawSchemeEl[name]; } else if (name === "_check") { schemeEl.customCheck = rawSchemeEl[name]; } else { schemeEl.sname = name; } } schemeEl.sarg = rawSchemeEl[schemeEl.sname]; if(typeof schemeEl.customCheck === "object" && schemeEl.customCheck instanceof RegExp) { var schemeRegexp = schemeEl.customCheck; schemeEl.customCheck = function(arg) { return !!arg.toString().match(schemeRegexp); }; } return schemeEl; }; var _typeMatches = function(arg, schemeEl) { var ok = false; if ((schemeEl.sarg & Args.ANY) !== 0) { ok = true; } else if ((schemeEl.sarg & Args.STRING) !== 0 && typeof arg === "string") { ok = true; } else if ((schemeEl.sarg & Args.FUNCTION) !== 0 && typeof arg === "function") { ok = true; } else if ((schemeEl.sarg & Args.INT) !== 0 && (typeof arg === "number" && Math.floor(arg) === arg)) { ok = true; } else if ((schemeEl.sarg & Args.FLOAT) !== 0 && typeof arg === "number") { ok = true; } else if ((schemeEl.sarg & Args.ARRAY) !== 0 && (Array.isArray(arg))) { ok = true; } else if (((schemeEl.sarg & Args.OBJECT) !== 0 || schemeEl.typeValue !== undefined) && ( typeof arg === "object" && (schemeEl.typeValue === undefined || (arg instanceof schemeEl.typeValue)) )) { ok = true; } else if ((schemeEl.sarg & Args.ARRAY_BUFFER) !== 0 && arg.toString().match(/ArrayBuffer/)) { ok = true; } else if ((schemeEl.sarg & Args.DATE) !== 0 && arg instanceof Date) { ok = true; } else if ((schemeEl.sarg & Args.BOOL) !== 0 && typeof arg === "boolean") { ok = true; } else if ((schemeEl.sarg & Args.DOM_EL) !== 0 && ( (arg instanceof HTMLElement) || (window.$ !== undefined && arg instanceof window.$) ) ) { ok = true; } if (schemeEl.customCheck !== undefined && typeof schemeEl.customCheck === "function") { if (schemeEl.customCheck(arg)) { ok = true; } else { ok = false; } } return ok; }; var _isTypeSpecified = function(schemeEl) { return (schemeEl.sarg & (Args.ANY | Args.STRING | Args.FUNCTION | Args.INT | Args.FLOAT | Args.OBJECT | Args.ARRAY_BUFFER | Args.DATE | Args.BOOL | Args.DOM_EL | Args.ARRAY)) != 0 || schemeEl.typeValue !== undefined; }; var _getTypeString = function(schemeEl) { var sarg = schemeEl.sarg; var typeValue = schemeEl.typeValue; var customCheck = schemeEl.customCheck; if ((sarg & Args.STRING) !== 0 ) { return "String"; } if ((sarg & Args.FUNCTION) !== 0 ) { return "Function"; } if ((sarg & Args.INT) !== 0 ) { return "Int"; } if ((sarg & Args.FLOAT) !== 0 ) { return "Float"; } if ((sarg & Args.ARRAY) !== 0 ) { return "Array"; } if ((sarg & Args.OBJECT) !== 0) { if (typeValue !== undefined) { return "Object (" + typeValue.toString() + ")"; } else { return "Object"; } } if ((sarg & Args.ARRAY_BUFFER) !== 0 ) { return "Arry Buffer"; } if ((sarg & Args.DATE) !== 0 ) { return "Date"; } if ((sarg & Args.BOOL) !== 0 ) { return "Bool"; } if ((sarg & Args.DOM_EL) !== 0 ) { return "DOM Element"; } if (customCheck !== undefined) { return "[Custom checker]"; } return "unknown"; }; var _checkNamedArgs = function(namedArgs, scheme, returns) { var foundOne = false; for (var s = 0 ; s < scheme.length ; s++) { var found = (function(schemeEl) { var argFound = false; for (var name in namedArgs) { var namedArg = namedArgs[name]; if (name === schemeEl.sname) { if (_typeMatches(namedArg, schemeEl)) { returns[name] = namedArg; argFound = true; break; } } } return argFound; })(_extractSchemeEl(scheme[s])); if (found) { scheme.splice(s--, 1); } foundOne |= found; } return foundOne; }; var _schemesMatch = function(schemeA, schemeB) { if (!schemeA || !schemeB) { return false; } return (schemeA.sarg & ~(Args.Optional | Args.Required)) === (schemeB.sarg & ~(Args.Optional | Args.Required)) && schemeA.typeValue === schemeB.typeValue; }; var _isRequired = function(sarg) { return !_isOptional(sarg); }; var _isOptional = function(sarg) { return (sarg & Args.Optional) !== 0; }; var _reasonForFailure = function(schemeEl, a, arg) { var err = ""; if (_isTypeSpecified(schemeEl)) { err = "Argument " + a + " ("+schemeEl.sname+") should be type "+_getTypeString(schemeEl)+", but it was type " + (typeof arg) + " with value " + arg + "."; } else if (schemeEl.customCheck !== undefined) { var funcString = schemeEl.customCheck.toString(); if (funcString.length > 50) { funcString = funcString.substr(0, 40) + "..." + funcString.substr(funcString.length-10); } err = "Argument " + a + " ("+schemeEl.sname+") does not pass the custom check ("+funcString+")."; } else { err = "Argument " + a + " ("+schemeEl.sname+") has no valid type specified."; } return err; }; /** * Last argument may be a named argument object. This is decided in a non-greedy way, if * there are any unmatched arguments after the normal process and the last argument is an * object it is inspected for matching names. * * If the last argument is a named argument object and it could potentially be matched to * a normal object in the schema the object is first used to try to match any remaining * required args (including the object that it would match against). Only if there are no * remaining required args or none of the remaining required args are matched will the * last object arg match against a normal schema object. * * Runs of objects with the same type are matched greedily but if a required object is * encountered in the schema after all objects of that type have been matched the previous * matches are shifted right to cover the new required arg. Shifts can only happen from * immediately preceding required args or optional args. If a previous required arg is * matched but an optional arg seprates the new required arg from the old one only the * optional arg in between can be shifted. The required arg and any preceding optional * args are not shifted. */ var Args = function(scheme, args) { if (scheme === undefined) throw new Error("The scheme has not been passed."); if (args === undefined) throw new Error("The arguments have not been passed."); args = Array.prototype.slice.call(args,0); var returns = {}; var err = undefined; var runType = undefined; var run = []; var _addToRun = function(schemeEl) { if ( !runType || !_schemesMatch(runType, schemeEl) || (_isRequired(runType.sarg) && _isOptional(schemeEl.sarg)) ) { run = []; } if (run.length > 0 || _isOptional(schemeEl.sarg)) { runType = schemeEl; run.push(schemeEl); } }; var _shiftRun = function(schemeEl, a, r) { if (r === undefined) r = run.length-1; if (r < 0) return; var lastMatch = run[r]; var arg = returns[lastMatch.sname]; if (_typeMatches(arg, schemeEl)) { returns[schemeEl.sname] = arg; returns[lastMatch.sname] = lastMatch.defValue || undefined; if ((lastMatch.sarg & Args.Optional) === 0) { // if the last in the run was not optional _shiftRun(lastMatch, a, r-1); } } else { return _reasonForFailure(schemeEl, a, arg); } }; var a, s; // first let's extract any named args // we need to see if the last arg is an object and if it's constructor was Object (i.e. it is simple) var lastArg = args[args.length-1]; if (lastArg !== null && typeof lastArg === "object" && lastArg.constructor === Object) { // we should also exit if the object arg matches a rule itself // that is more tricky though... if (_checkNamedArgs(args[args.length-1], scheme, returns)) { args.splice(args.length-1,1); } } for (a = 0, s = 0; s < scheme.length ; s++) { a = (function(a,s) { var arg = args[a]; // argument group if (scheme[s] instanceof Array) { var group = scheme[s]; var retName = undefined; var groupIsOptional = false; for (var g = 0 ; g < group.length ; g++) { var groupEl = group[g]; if (groupEl === Args.Optional) { groupIsOptional = true; } else { var schemeEl = _extractSchemeEl(groupEl); if (_typeMatches(arg, schemeEl)) { retName = schemeEl.sname; } } } if (retName === undefined && !groupIsOptional) { if (arg === null || arg === undefined) { err = "Argument " + a + " is null or undefined but it must be not null."; return a; } err = "Argument " + a + " should be one of: "; for (var g = 0 ; g < group.length ; g++) { var schemeEl = _extractSchemeEl(group[g]); err += _getTypeString(schemeEl) + ", "; } err += "but it was type " + (typeof arg) + " with value " + arg + "."; return a; } else if (retName !== undefined) { returns[retName] = arg; return a+1; } } else { var schemeEl = _extractSchemeEl(scheme[s]); // optional arg if ((schemeEl.sarg & Args.Optional) !== 0) { // check if this arg matches the next schema slot if ( arg === null || arg === undefined) { if (schemeEl.defValue !== undefined) { returns[schemeEl.sname] = schemeEl.defValue; } else { returns[schemeEl.sname] = arg; } return a+1; // if the arg is null or undefined it will fill a slot, but may be replace by the default value } else if (_typeMatches(arg, schemeEl)) { returns[schemeEl.sname] = arg; _addToRun(schemeEl); return a+1; } else if (schemeEl.defValue !== undefined) { returns[schemeEl.sname] = schemeEl.defValue; return a; } } // manadatory arg else { //if ((schemeEl.sarg & Args.NotNull) !== 0) { if (arg === null || arg === undefined) { if (_isTypeSpecified(schemeEl) && _schemesMatch(schemeEl, runType)) { err = _shiftRun(schemeEl, a); if (err === "") { _addToRun(schemeEl); } return a; } else { err = "Argument " + a + " ("+schemeEl.sname+") is null or undefined but it must be not null."; return a; } } else if (!_typeMatches(arg, schemeEl)) { if (_isTypeSpecified(schemeEl) && _schemesMatch(schemeEl, runType)) { err = _shiftRun(schemeEl, a); if (err === "") { _addToRun(schemeEl); return a+1; } } else { err = _reasonForFailure(schemeEl, a, arg); } return a; } else { returns[schemeEl.sname] = arg; _addToRun(schemeEl); return a+1; } } } return a; })(a,s); if (err) { break; } } if (err) { throw new Error(err); } return returns; }; Args.ANY = 0x1; Args.STRING = 0x1 << 1; Args.FUNCTION = 0x1 << 2; Args.INT = 0x1 << 3; Args.FLOAT = 0x1 << 4; Args.ARRAY_BUFFER = 0x1 << 5; Args.OBJECT = 0x1 << 6; Args.DATE = 0x1 << 7; Args.BOOL = 0x1 << 8; Args.DOM_EL = 0x1 << 9; Args.ARRAY = 0x1 << 10; Args.Optional = 0x1 << 11; Args.NotNull = Args.Required = 0x1 << 12; return Args; });
abyoussef/SmartFlow
node_modules/args-js/dist/Args.js
JavaScript
mit
14,146
namespace OmniXaml.Tests.Classes { public class IntExtension : MarkupExtension { public IntExtension() { } public IntExtension(int number) { Number = number; } public int Number { get; set; } public override object ProvideValue(MarkupExtensionContext markupExtensionContext) { return Number; } } }
jrodrigv/OmniXAML
Tests/OmniXaml.Tests.Classes/IntExtension.cs
C#
mit
438
using System.Collections.Generic; using NuGet; namespace APIComparer.VersionComparisons { public interface ICompareStrategy { IEnumerable<VersionPair> GetVersionsToCompare(List<SemanticVersion> semVerCompliantVersions); } }
modernist/APIComparer
APIComparer/VersionComparisons/ICompareStrategy.cs
C#
mit
244
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Sql { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// ServerKeysOperations operations. /// </summary> public partial interface IServerKeysOperations { /// <summary> /// Gets a list of server keys. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ServerKey>>> ListByServerWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a server key. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='keyName'> /// The name of the server key to be retrieved. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ServerKey>> GetWithHttpMessagesAsync(string resourceGroupName, string serverName, string keyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a server key. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='keyName'> /// The name of the server key to be operated on (updated or created). /// The key name is required to be in the format of /// 'vault_key_version'. For example, if the keyId is /// https://YourVaultName.vault.azure.net/keys/YourKeyName/01234567890123456789012345678901, /// then the server key name should be formatted as: /// YourVaultName_YourKeyName_01234567890123456789012345678901 /// </param> /// <param name='parameters'> /// The requested server key resource state. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ServerKey>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string keyName, ServerKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the server key with the given name. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='keyName'> /// The name of the server key to be deleted. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serverName, string keyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a server key. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='keyName'> /// The name of the server key to be operated on (updated or created). /// The key name is required to be in the format of /// 'vault_key_version'. For example, if the keyId is /// https://YourVaultName.vault.azure.net/keys/YourKeyName/01234567890123456789012345678901, /// then the server key name should be formatted as: /// YourVaultName_YourKeyName_01234567890123456789012345678901 /// </param> /// <param name='parameters'> /// The requested server key resource state. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ServerKey>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string keyName, ServerKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the server key with the given name. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='keyName'> /// The name of the server key to be deleted. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string serverName, string keyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of server keys. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ServerKey>>> ListByServerNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
atpham256/azure-sdk-for-net
src/SDKs/SqlManagement/Management.Sql/Generated/IServerKeysOperations.cs
C#
mit
11,343
namespace Glass.Mapper.Sc.IoC { public class GlassHtmlFactory : IGlassHtmlFactory { public IGlassHtml GetGlassHtml(ISitecoreContext sitecoreContext) { return new GlassHtml(sitecoreContext); } } }
rmwatson5/Glass-Factory
packages/Glass.Mapper.Sc.Core.4.2.0.184/src/Source/Glass.Mapper.Sc/IoC/GlassHtmlFactory.cs
C#
mit
247
<a href="http://github.com/angular/angular.js/tree/v1.2.12/src/ng/directive/input.js#L95" class="view-source btn btn-action"><i class="icon-zoom-in"> </i> View source</a><a href="http://github.com/angular/angular.js/edit/master/src/ng/directive/input.js" class="improve-docs btn btn-primary"><i class="icon-edit"> </i> Improve this doc</a><h1><code ng:non-bindable="">input [number]</code> <div><span class="hint">directive in module <code ng:non-bindable="">ng</code> </span> </div> </h1> <div><h2 id="description">Description</h2> <div class="description"><div class="ng-directive-page ng-directive-input-number-page"><p>Text input with number validation and transformation. Sets the <code>number</code> validation error if not a valid number.</p> </div></div> <h2 id="usage">Usage</h2> <div class="usage"><pre class="prettyprint linenums">&lt;input type="number" ng-model="{string}" [name="{string}"] [min="{string}"] [max="{string}"] [required] [ng-required="{string}"] [ng-minlength="{number}"] [ng-maxlength="{number}"] [ng-pattern="{string}"] [ng-change="{string}"]&gt;</pre> <h4 id="usage_parameters">Parameters</h4><table class="variables-matrix table table-bordered table-striped"><thead><tr><th>Param</th><th>Type</th><th>Details</th></tr></thead><tbody><tr><td>ngModel</td><td><a href="" class="label type-hint type-hint-string">string</a></td><td><div class="ng-directive-page ng-directive-input-number-page"><p>Assignable angular expression to data-bind to.</p> </div></td></tr><tr><td>name <div><em>(optional)</em></div></td><td><a href="" class="label type-hint type-hint-string">string</a></td><td><div class="ng-directive-page ng-directive-input-number-page"><p>Property name of the form under which the control is published.</p> </div></td></tr><tr><td>min <div><em>(optional)</em></div></td><td><a href="" class="label type-hint type-hint-string">string</a></td><td><div class="ng-directive-page ng-directive-input-number-page"><p>Sets the <code>min</code> validation error key if the value entered is less than <code>min</code>.</p> </div></td></tr><tr><td>max <div><em>(optional)</em></div></td><td><a href="" class="label type-hint type-hint-string">string</a></td><td><div class="ng-directive-page ng-directive-input-number-page"><p>Sets the <code>max</code> validation error key if the value entered is greater than <code>max</code>.</p> </div></td></tr><tr><td>required <div><em>(optional)</em></div></td><td><a href="" class="label type-hint type-hint-string">string</a></td><td><div class="ng-directive-page ng-directive-input-number-page"><p>Sets <code>required</code> validation error key if the value is not entered.</p> </div></td></tr><tr><td>ngRequired <div><em>(optional)</em></div></td><td><a href="" class="label type-hint type-hint-string">string</a></td><td><div class="ng-directive-page ng-directive-input-number-page"><p>Adds <code>required</code> attribute and <code>required</code> validation constraint to the element when the ngRequired expression evaluates to true. Use <code>ngRequired</code> instead of <code>required</code> when you want to data-bind to the <code>required</code> attribute.</p> </div></td></tr><tr><td>ngMinlength <div><em>(optional)</em></div></td><td><a href="" class="label type-hint type-hint-number">number</a></td><td><div class="ng-directive-page ng-directive-input-number-page"><p>Sets <code>minlength</code> validation error key if the value is shorter than minlength.</p> </div></td></tr><tr><td>ngMaxlength <div><em>(optional)</em></div></td><td><a href="" class="label type-hint type-hint-number">number</a></td><td><div class="ng-directive-page ng-directive-input-number-page"><p>Sets <code>maxlength</code> validation error key if the value is longer than maxlength.</p> </div></td></tr><tr><td>ngPattern <div><em>(optional)</em></div></td><td><a href="" class="label type-hint type-hint-string">string</a></td><td><div class="ng-directive-page ng-directive-input-number-page"><p>Sets <code>pattern</code> validation error key if the value does not match the RegExp pattern expression. Expected value is <code>/regexp/</code> for inline patterns or <code>regexp</code> for patterns defined as scope expressions.</p> </div></td></tr><tr><td>ngChange <div><em>(optional)</em></div></td><td><a href="" class="label type-hint type-hint-string">string</a></td><td><div class="ng-directive-page ng-directive-input-number-page"><p>Angular expression to be executed when input changes due to user interaction with the input element.</p> </div></td></tr></tbody></table></div> <h2 id="example">Example</h2> <div class="example"><div class="ng-directive-page ng-directive-input-number-page"><h4 id="example_source">Source</h4> <div source-edit="" source-edit-deps="angular.js script.js protractorTest.js" source-edit-html="index.html-31" source-edit-css="" source-edit-js="script.js-30" source-edit-json="" source-edit-unit="" source-edit-scenario="" source-edit-protractor="protractorTest.js-32"></div> <div class="tabbable"><div class="tab-pane" title="index.html"> <pre class="prettyprint linenums" ng-set-text="index.html-31" ng-html-wrap=" angular.js script.js protractorTest.js"></pre> <script type="text/ng-template" id="index.html-31"> <form name="myForm" ng-controller="Ctrl"> Number: <input type="number" name="input" ng-model="value" min="0" max="99" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.number"> Not valid number!</span> <tt>value = {{value}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </script> </div> <div class="tab-pane" title="script.js"> <pre class="prettyprint linenums" ng-set-text="script.js-30"></pre> <script type="text/ng-template" id="script.js-30"> function Ctrl($scope) { $scope.value = 12; } </script> </div> <div class="tab-pane" title="Protractor e2e test"> <pre class="prettyprint linenums" ng-set-text="protractorTest.js-32"></pre> <script type="text/ng-template" id="protractorTest.js-32"> var value = element(by.binding('value')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('value')); it('should initialize to model', function() { expect(value.getText()).toContain('12'); expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { input.clear(); input.sendKeys(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('false'); }); it('should be invalid if over max', function() { input.clear(); input.sendKeys('123'); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('false'); }); </script> </div> </div><h4 id="example_demo">Demo</h4> <div class="well doc-example-live animate-container" ng-embed-app="" ng-set-html="index.html-31" ng-eval-javascript="script.js-30"></div> </div></div> </div>
nagyist/PlanIT
src/Flyers/DashboardBundle/Resources/public/vendors/angular-1.2.12/docs/partials/api/ng.directive:input.number.html
HTML
mit
7,240
--- layout: page weight: 0 title: Scheduling Parameters navigation: show: true --- With scheduling you can send large volumes of email in queued batches or target individual recipients by specifying custom UNIX timestamp parameter. Using the parameters defined below, you can queue batches of emails targeting individual recipients. This parameter allows SendGrid to begin processing a customer’s email requests before sending. SendGrid will then queue those messages and release them when the timestamp is exceeded. This technique allows for a more efficient way to distribute large email requests and can **improve overall mail delivery time** performance. This functionality: * Improves efficiency of processing and distributing large volumes of email. * Reduces email pre-processing time. * Enables you to time email arrival to increase open rates. * Is available for free to all SendGrid customers. {% info %} Once you send SendGrid a request with a scheduling parameter, that email request cannot be cancelled and we currently only accept time stamps no greater than 72 hours in advance. {% endinfo %} {% warning %} Using both `send_at` and `send_each_at` is not valid and will cause your request to be dropped. {% endwarning %} {% anchor h2 %} Send At {% endanchor %} To schedule a send request for a large batch of emails use the `send_at` parameter which will send all emails at approximately the same time. `send_at` is a [UNIX timestamp](https://en.wikipedia.org/wiki/Unix_time). <h4>Example of send_at email header</h4> {% codeblock lang:json %} { "send_at": 1409348513 } {% endcodeblock %} {% anchor h2 %} Send Each At {% endanchor %} To schedule a send request for individual recipients; use `send_each_at` to send emails to each recipient at the specified time. `send_each_at` is a sequence of UNIX timestamps, provided as an array. There must be one timestamp per email you wish to send. <h4>Example of send_each_at email header</h4> {% codeblock lang:json %} { "to": [ "<ben@example.com>", "john@example.com", "mike@example.com" ], "send_each_at": [ 1409348513, 1409348514, 1409348515 ] } {% endcodeblock %}
L2G/docs
source/API_Reference/SMTP_API/scheduling_parameters.md
Markdown
mit
2,184
<!DOCTYPE html> <html lang="en"> <head> <title>CacheType Enum Reference</title> <link rel="stylesheet" type="text/css" href="../css/jazzy.css" /> <link rel="stylesheet" type="text/css" href="../css/highlight.css" /> <meta charset='utf-8'> <script src="../js/jquery.min.js" defer></script> <script src="../js/jazzy.js" defer></script> </head> <body> <a name="//apple_ref/swift/Enum/CacheType" class="dashAnchor"></a> <a title="CacheType Enum Reference"></a> <header> <div class="content-wrapper"> <p><a href="../index.html">Kingfisher Docs</a> (80% documented)</p> <p class="header-right"><a href="https://github.com/onevcat/Kingfisher"><img src="../img/gh.png"/>View on GitHub</a></p> <p class="header-right"><a href="dash-feed://http%3A%2F%2Fonevcat%2Egithub%2Eio%2FKingfisher%2Fdocsets%2FKingfisher%2Exml"><img src="../img/dash.png"/>Install in Dash</a></p> </div> </header> <div class="content-wrapper"> <p id="breadcrumbs"> <a href="../index.html">Kingfisher Reference</a> <img id="carat" src="../img/carat.png" /> CacheType Enum Reference </p> </div> <div class="content-wrapper"> <nav class="sidebar"> <ul class="nav-groups"> <li class="nav-group-name"> <a href="../Classes.html">Classes</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Classes/AnimatedImageView.html">AnimatedImageView</a> </li> <li class="nav-group-task"> <a href="../Classes/ImageCache.html">ImageCache</a> </li> <li class="nav-group-task"> <a href="../Classes/ImageCache/CacheCheckResult.html">– CacheCheckResult</a> </li> <li class="nav-group-task"> <a href="../Classes/ImageDownloader.html">ImageDownloader</a> </li> <li class="nav-group-task"> <a href="../Classes/ImagePrefetcher.html">ImagePrefetcher</a> </li> <li class="nav-group-task"> <a href="../Classes/Kingfisher.html">Kingfisher</a> </li> <li class="nav-group-task"> <a href="../Classes/KingfisherManager.html">KingfisherManager</a> </li> <li class="nav-group-task"> <a href="../Classes/RetrieveImageTask.html">RetrieveImageTask</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Global Variables.html">Global Variables</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Global Variables.html#/s:v10Kingfisher33KingfisherDiskCacheCleanedHashKeySS">KingfisherDiskCacheCleanedHashKey</a> </li> <li class="nav-group-task"> <a href="../Global Variables.html#/s:v10Kingfisher21KingfisherErrorDomainSS">KingfisherErrorDomain</a> </li> <li class="nav-group-task"> <a href="../Global Variables.html#/s:v10Kingfisher28KingfisherErrorStatusCodeKeySS">KingfisherErrorStatusCodeKey</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Enums.html">Enums</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Enums/CacheType.html">CacheType</a> </li> <li class="nav-group-task"> <a href="../Enums/ContentMode.html">ContentMode</a> </li> <li class="nav-group-task"> <a href="../Enums/ImageProcessItem.html">ImageProcessItem</a> </li> <li class="nav-group-task"> <a href="../Enums/ImageTransition.html">ImageTransition</a> </li> <li class="nav-group-task"> <a href="../Enums/ImageTransition.html">ImageTransition</a> </li> <li class="nav-group-task"> <a href="../Enums/IndicatorType.html">IndicatorType</a> </li> <li class="nav-group-task"> <a href="../Enums/KingfisherError.html">KingfisherError</a> </li> <li class="nav-group-task"> <a href="../Enums/KingfisherOptionsInfoItem.html">KingfisherOptionsInfoItem</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Extensions.html">Extensions</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Extensions/CGSize.html">CGSize</a> </li> <li class="nav-group-task"> <a href="../Extensions/Collection.html">Collection</a> </li> <li class="nav-group-task"> <a href="../Extensions/Data.html">Data</a> </li> <li class="nav-group-task"> <a href="../Extensions/Image.html">Image</a> </li> <li class="nav-group-task"> <a href="../Extensions/ImageView.html">ImageView</a> </li> <li class="nav-group-task"> <a href="../Extensions/Notification.html">Notification</a> </li> <li class="nav-group-task"> <a href="../Extensions/String.html">String</a> </li> <li class="nav-group-task"> <a href="../Extensions/UIButton.html">UIButton</a> </li> <li class="nav-group-task"> <a href="../Extensions/URL.html">URL</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Functions.html">Functions</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Functions.html#/s:F10Kingfisheroi2ggFTPS_14ImageProcessor_PS0___PS0__">&gt;&gt;(_:_:)</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Protocols.html">Protocols</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Protocols/AuthenticationChallengeResponsable.html">AuthenticationChallengeResponsable</a> </li> <li class="nav-group-task"> <a href="../Protocols/CIImageProcessor.html">CIImageProcessor</a> </li> <li class="nav-group-task"> <a href="../Protocols/CacheSerializer.html">CacheSerializer</a> </li> <li class="nav-group-task"> <a href="../Protocols/ImageDownloadRequestModifier.html">ImageDownloadRequestModifier</a> </li> <li class="nav-group-task"> <a href="../Protocols/ImageDownloaderDelegate.html">ImageDownloaderDelegate</a> </li> <li class="nav-group-task"> <a href="../Protocols/ImageProcessor.html">ImageProcessor</a> </li> <li class="nav-group-task"> <a href="../Protocols/Indicator.html">Indicator</a> </li> <li class="nav-group-task"> <a href="../Protocols/KingfisherCompatible.html">KingfisherCompatible</a> </li> <li class="nav-group-task"> <a href="../Protocols/Resource.html">Resource</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Structs.html">Structs</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Structs/AnyModifier.html">AnyModifier</a> </li> <li class="nav-group-task"> <a href="../Structs/BlackWhiteProcessor.html">BlackWhiteProcessor</a> </li> <li class="nav-group-task"> <a href="../Structs/BlurImageProcessor.html">BlurImageProcessor</a> </li> <li class="nav-group-task"> <a href="../Structs.html#/s:V10Kingfisher11CGSizeProxy">CGSizeProxy</a> </li> <li class="nav-group-task"> <a href="../Structs/ColorControlsProcessor.html">ColorControlsProcessor</a> </li> <li class="nav-group-task"> <a href="../Structs/CroppingImageProcessor.html">CroppingImageProcessor</a> </li> <li class="nav-group-task"> <a href="../Structs.html#/s:V10Kingfisher9DataProxy">DataProxy</a> </li> <li class="nav-group-task"> <a href="../Structs/DefaultCacheSerializer.html">DefaultCacheSerializer</a> </li> <li class="nav-group-task"> <a href="../Structs/DefaultImageProcessor.html">DefaultImageProcessor</a> </li> <li class="nav-group-task"> <a href="../Structs/Filter.html">Filter</a> </li> <li class="nav-group-task"> <a href="../Structs/ImageResource.html">ImageResource</a> </li> <li class="nav-group-task"> <a href="../Structs/OverlayImageProcessor.html">OverlayImageProcessor</a> </li> <li class="nav-group-task"> <a href="../Structs/ResizingImageProcessor.html">ResizingImageProcessor</a> </li> <li class="nav-group-task"> <a href="../Structs/RetrieveImageDownloadTask.html">RetrieveImageDownloadTask</a> </li> <li class="nav-group-task"> <a href="../Structs/RoundCornerImageProcessor.html">RoundCornerImageProcessor</a> </li> <li class="nav-group-task"> <a href="../Structs.html#/s:V10Kingfisher11StringProxy">StringProxy</a> </li> <li class="nav-group-task"> <a href="../Structs/TintImageProcessor.html">TintImageProcessor</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Typealiases.html">Typealiases</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher32ImageDownloaderCompletionHandler">ImageDownloaderCompletionHandler</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher28ImageDownloaderProgressBlock">ImageDownloaderProgressBlock</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher21KingfisherOptionsInfo">KingfisherOptionsInfo</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher27PrefetcherCompletionHandler">PrefetcherCompletionHandler</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher23PrefetcherProgressBlock">PrefetcherProgressBlock</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher21RetrieveImageDiskTask">RetrieveImageDiskTask</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher11Transformer">Transformer</a> </li> </ul> </li> </ul> </nav> <article class="main-content"> <section> <section class="section"> <h1>CacheType</h1> <div class="declaration"> <div class="language"> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">enum</span> <span class="kt">CacheType</span></code></pre> </div> </div> <p>Cache type of a cached image.</p> <ul> <li>None: The image is not cached yet when retrieving it.</li> <li>Memory: The image is cached in memory.</li> <li>Disk: The image is cached in disk.</li> </ul> </section> <section class="section task-group-section"> <div class="task-group"> <ul> <li class="item"> <div> <code> <a name="/s:FO10Kingfisher9CacheType4noneFMS0_S0_"></a> <a name="//apple_ref/swift/Element/none" class="dashAnchor"></a> <a class="token" href="#/s:FO10Kingfisher9CacheType4noneFMS0_S0_">none</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Undocumented</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">enum</span> <span class="kt">CacheType</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/onevcat/Kingfisher/tree/3.6.2/Sources/ImageCache.swift#L">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:FO10Kingfisher9CacheType6memoryFMS0_S0_"></a> <a name="//apple_ref/swift/Element/memory" class="dashAnchor"></a> <a class="token" href="#/s:FO10Kingfisher9CacheType6memoryFMS0_S0_">memory</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Undocumented</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">enum</span> <span class="kt">CacheType</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/onevcat/Kingfisher/tree/3.6.2/Sources/ImageCache.swift#L">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:FO10Kingfisher9CacheType4diskFMS0_S0_"></a> <a name="//apple_ref/swift/Element/disk" class="dashAnchor"></a> <a class="token" href="#/s:FO10Kingfisher9CacheType4diskFMS0_S0_">disk</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Undocumented</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">enum</span> <span class="kt">CacheType</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/onevcat/Kingfisher/tree/3.6.2/Sources/ImageCache.swift#L">Show on GitHub</a> </div> </section> </div> </li> </ul> </div> </section> </section> <section id="footer"> <p>&copy; 2017 <a class="link" href="https://onevcat.com" target="_blank" rel="external">Wei Wang</a>. All rights reserved. (Last updated: 2017-04-11)</p> <p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.7.5</a>, a <a class="link" href="http://realm.io" target="_blank" rel="external">Realm</a> project.</p> </section> </article> </div> </body> </div> </html>
visenze/visearch-widget-swift
Carthage/Checkouts/Kingfisher/docs/docsets/Kingfisher.docset/Contents/Resources/Documents/Enums/CacheType.html
HTML
mit
17,502
import { moduleFor, RenderingTestCase, runTask } from 'internal-test-helpers'; import { Object as EmberObject } from '@ember/-internals/runtime'; import { set, setProperties, computed } from '@ember/-internals/metal'; import { setComponentManager, capabilities } from '@ember/-internals/glimmer'; const BasicComponentManager = EmberObject.extend({ capabilities: capabilities('3.4'), createComponent(factory, args) { return factory.create({ args }); }, updateComponent(component, args) { set(component, 'args', args); }, getContext(component) { return component; }, }); /* eslint-disable */ function createBasicManager(owner) { return BasicComponentManager.create({ owner }); } function createInstrumentedManager(owner) { return InstrumentedComponentManager.create({ owner }); } /* eslint-enable */ let InstrumentedComponentManager; class ComponentManagerTest extends RenderingTestCase { constructor(assert) { super(...arguments); InstrumentedComponentManager = EmberObject.extend({ capabilities: capabilities('3.4', { destructor: true, asyncLifecycleCallbacks: true, }), createComponent(factory, args) { assert.step('createComponent'); return factory.create({ args }); }, updateComponent(component, args) { assert.step('updateComponent'); set(component, 'args', args); }, destroyComponent(component) { assert.step('destroyComponent'); component.destroy(); }, getContext(component) { assert.step('getContext'); return component; }, didCreateComponent(component) { assert.step('didCreateComponent'); component.didRender(); }, didUpdateComponent(component) { assert.step('didUpdateComponent'); component.didUpdate(); }, }); } } moduleFor( 'Component Manager - Curly Invocation', class extends ComponentManagerTest { ['@test the string based version of setComponentManager is deprecated']() { expectDeprecation(() => { setComponentManager( 'basic', EmberObject.extend({ greeting: 'hello', }) ); }, 'Passing the name of the component manager to "setupComponentManager" is deprecated. Please pass a function that produces an instance of the manager.'); } ['@test it can render a basic component with custom component manager']() { let ComponentClass = setComponentManager( createBasicManager, EmberObject.extend({ greeting: 'hello', }) ); this.registerComponent('foo-bar', { template: `<p>{{greeting}} world</p>`, ComponentClass, }); this.render('{{foo-bar}}'); this.assertHTML(`<p>hello world</p>`); } ['@test it can render a basic component with custom component manager with a factory']() { let ComponentClass = setComponentManager( () => BasicComponentManager.create(), EmberObject.extend({ greeting: 'hello', }) ); this.registerComponent('foo-bar', { template: `<p>{{greeting}} world</p>`, ComponentClass, }); this.render('{{foo-bar}}'); this.assertHTML(`<p>hello world</p>`); } ['@test it can have no template context']() { let ComponentClass = setComponentManager(() => { return EmberObject.create({ capabilities: capabilities('3.4'), createComponent() { return null; }, updateComponent() {}, getContext() { return null; }, }); }, {}); this.registerComponent('foo-bar', { template: `<p>{{@greeting}} world</p>`, ComponentClass, }); this.render('{{foo-bar greeting="hello"}}'); this.assertHTML(`<p>hello world</p>`); } ['@test it can discover component manager through inheritance - ES Classes']() { class Base {} setComponentManager(() => { return EmberObject.create({ capabilities: capabilities('3.4'), createComponent(Factory, args) { return new Factory(args); }, updateComponent() {}, getContext(component) { return component; }, }); }, Base); class Child extends Base {} class Grandchild extends Child { constructor() { super(); this.name = 'grandchild'; } } this.registerComponent('foo-bar', { template: `{{this.name}}`, ComponentClass: Grandchild, }); this.render('{{foo-bar}}'); this.assertHTML(`grandchild`); } ['@test it can discover component manager through inheritance - Ember Object']() { let Parent = setComponentManager(createBasicManager, EmberObject.extend()); let Child = Parent.extend(); let Grandchild = Child.extend({ init() { this._super(...arguments); this.name = 'grandchild'; }, }); this.registerComponent('foo-bar', { template: `{{this.name}}`, ComponentClass: Grandchild, }); this.render('{{foo-bar}}'); this.assertHTML(`grandchild`); } ['@test it can customize the template context']() { let customContext = { greeting: 'goodbye', }; let ComponentClass = setComponentManager( () => { return EmberObject.create({ capabilities: capabilities('3.4'), createComponent(factory) { return factory.create(); }, getContext() { return customContext; }, updateComponent() {}, }); }, EmberObject.extend({ greeting: 'hello', count: 1234, }) ); this.registerComponent('foo-bar', { template: `<p>{{greeting}} world {{count}}</p>`, ComponentClass, }); this.render('{{foo-bar}}'); this.assertHTML(`<p>goodbye world </p>`); runTask(() => set(customContext, 'greeting', 'sayonara')); this.assertHTML(`<p>sayonara world </p>`); } ['@test it can set arguments on the component instance']() { let ComponentClass = setComponentManager( createBasicManager, EmberObject.extend({ salutation: computed('args.named.firstName', 'args.named.lastName', function() { return this.args.named.firstName + ' ' + this.args.named.lastName; }), }) ); this.registerComponent('foo-bar', { template: `<p>{{salutation}}</p>`, ComponentClass, }); this.render('{{foo-bar firstName="Yehuda" lastName="Katz"}}'); this.assertHTML(`<p>Yehuda Katz</p>`); } ['@test arguments are updated if they change']() { let ComponentClass = setComponentManager( createBasicManager, EmberObject.extend({ salutation: computed('args.named.firstName', 'args.named.lastName', function() { return this.args.named.firstName + ' ' + this.args.named.lastName; }), }) ); this.registerComponent('foo-bar', { template: `<p>{{salutation}}</p>`, ComponentClass, }); this.render('{{foo-bar firstName=firstName lastName=lastName}}', { firstName: 'Yehuda', lastName: 'Katz', }); this.assertHTML(`<p>Yehuda Katz</p>`); runTask(() => setProperties(this.context, { firstName: 'Chad', lastName: 'Hietala', }) ); this.assertHTML(`<p>Chad Hietala</p>`); } ['@test it can set positional params on the component instance']() { let ComponentClass = setComponentManager( createBasicManager, EmberObject.extend({ salutation: computed('args.positional', function() { return this.args.positional[0] + ' ' + this.args.positional[1]; }), }) ); this.registerComponent('foo-bar', { template: `<p>{{salutation}}</p>`, ComponentClass, }); this.render('{{foo-bar "Yehuda" "Katz"}}'); this.assertHTML(`<p>Yehuda Katz</p>`); } ['@test positional params are updated if they change']() { let ComponentClass = setComponentManager( createBasicManager, EmberObject.extend({ salutation: computed('args.positional', function() { return this.args.positional[0] + ' ' + this.args.positional[1]; }), }) ); this.registerComponent('foo-bar', { template: `<p>{{salutation}}</p>`, ComponentClass, }); this.render('{{foo-bar firstName lastName}}', { firstName: 'Yehuda', lastName: 'Katz', }); this.assertHTML(`<p>Yehuda Katz</p>`); runTask(() => setProperties(this.context, { firstName: 'Chad', lastName: 'Hietala', }) ); this.assertHTML(`<p>Chad Hietala</p>`); } ['@test it can opt-in to running destructor'](assert) { let ComponentClass = setComponentManager( () => { return EmberObject.create({ capabilities: capabilities('3.4', { destructor: true, }), createComponent(factory) { assert.step('createComponent'); return factory.create(); }, getContext(component) { return component; }, updateComponent() {}, destroyComponent(component) { assert.step('destroyComponent'); component.destroy(); }, }); }, EmberObject.extend({ greeting: 'hello', destroy() { assert.step('component.destroy()'); this._super(...arguments); }, }) ); this.registerComponent('foo-bar', { template: `<p>{{greeting}} world</p>`, ComponentClass, }); this.render('{{#if show}}{{foo-bar}}{{/if}}', { show: true }); this.assertHTML(`<p>hello world</p>`); runTask(() => this.context.set('show', false)); this.assertText(''); assert.verifySteps(['createComponent', 'destroyComponent', 'component.destroy()']); } ['@test it can opt-in to running async lifecycle hooks'](assert) { let ComponentClass = setComponentManager( () => { return EmberObject.create({ capabilities: capabilities('3.4', { asyncLifecycleCallbacks: true, }), createComponent(factory, args) { assert.step('createComponent'); return factory.create({ args }); }, updateComponent(component, args) { assert.step('updateComponent'); set(component, 'args', args); }, destroyComponent(component) { assert.step('destroyComponent'); component.destroy(); }, getContext(component) { assert.step('getContext'); return component; }, didCreateComponent() { assert.step('didCreateComponent'); }, didUpdateComponent() { assert.step('didUpdateComponent'); }, }); }, EmberObject.extend({ greeting: 'hello', }) ); this.registerComponent('foo-bar', { template: `<p>{{greeting}} {{@name}}</p>`, ComponentClass, }); this.render('{{foo-bar name=name}}', { name: 'world' }); this.assertHTML(`<p>hello world</p>`); assert.verifySteps(['createComponent', 'getContext', 'didCreateComponent']); runTask(() => this.context.set('name', 'max')); this.assertHTML(`<p>hello max</p>`); assert.verifySteps(['updateComponent', 'didUpdateComponent']); } } ); moduleFor( 'Component Manager - Angle Invocation', class extends ComponentManagerTest { ['@test it can render a basic component with custom component manager']() { let ComponentClass = setComponentManager( createBasicManager, EmberObject.extend({ greeting: 'hello', }) ); this.registerComponent('foo-bar', { template: `<p>{{greeting}} world</p>`, ComponentClass, }); this.render('<FooBar />'); this.assertHTML(`<p>hello world</p>`); } ['@test it can set arguments on the component instance']() { let ComponentClass = setComponentManager( createBasicManager, EmberObject.extend({ salutation: computed('args.named.firstName', 'args.named.lastName', function() { return this.args.named.firstName + ' ' + this.args.named.lastName; }), }) ); this.registerComponent('foo-bar', { template: `<p>{{salutation}}</p>`, ComponentClass, }); this.render('<FooBar @firstName="Yehuda" @lastName="Katz" />'); this.assertHTML(`<p>Yehuda Katz</p>`); } ['@test it can pass attributes']() { let ComponentClass = setComponentManager(createBasicManager, EmberObject.extend()); this.registerComponent('foo-bar', { template: `<p ...attributes>Hello world!</p>`, ComponentClass, }); this.render('<FooBar data-test="foo" />'); this.assertHTML(`<p data-test="foo">Hello world!</p>`); } ['@test arguments are updated if they change']() { let ComponentClass = setComponentManager( createBasicManager, EmberObject.extend({ salutation: computed('args.named.firstName', 'args.named.lastName', function() { return this.args.named.firstName + ' ' + this.args.named.lastName; }), }) ); this.registerComponent('foo-bar', { template: `<p>{{salutation}}</p>`, ComponentClass, }); this.render('<FooBar @firstName={{firstName}} @lastName={{lastName}} />', { firstName: 'Yehuda', lastName: 'Katz', }); this.assertHTML(`<p>Yehuda Katz</p>`); runTask(() => setProperties(this.context, { firstName: 'Chad', lastName: 'Hietala', }) ); this.assertHTML(`<p>Chad Hietala</p>`); } ['@test updating attributes triggers didUpdateComponent'](assert) { let TestManager = EmberObject.extend({ capabilities: capabilities('3.4', { destructor: true, asyncLifecycleCallbacks: true, }), createComponent(factory, args) { assert.step('createComponent'); return factory.create({ args }); }, updateComponent(component, args) { assert.step('updateComponent'); set(component, 'args', args); }, destroyComponent(component) { component.destroy(); }, getContext(component) { assert.step('getContext'); return component; }, didCreateComponent(component) { assert.step('didCreateComponent'); component.didRender(); }, didUpdateComponent(component) { assert.step('didUpdateComponent'); component.didUpdate(); }, }); let ComponentClass = setComponentManager( () => { return TestManager.create(); }, EmberObject.extend({ didRender() {}, didUpdate() {}, }) ); this.registerComponent('foo-bar', { template: `<p ...attributes>Hello world!</p>`, ComponentClass, }); this.render('<FooBar data-test={{value}} />', { value: 'foo' }); this.assertHTML(`<p data-test="foo">Hello world!</p>`); assert.verifySteps(['createComponent', 'getContext', 'didCreateComponent']); runTask(() => this.context.set('value', 'bar')); assert.verifySteps(['didUpdateComponent']); } } );
kellyselden/ember.js
packages/@ember/-internals/glimmer/tests/integration/custom-component-manager-test.js
JavaScript
mit
16,163
// <copyright file="TestData.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2015 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using MathNet.Numerics.LinearAlgebra; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex32 { using Numerics; public static class TestData { static readonly MatrixBuilder<Complex32> M = Matrix<Complex32>.Build; static readonly VectorBuilder<Complex32> V = Vector<Complex32>.Build; public static Matrix<Complex32> Matrix(TestMatrix matrix) { switch (matrix) { case TestMatrix.DenseSquare3x3: return M.DenseOfArray(new[,] { { 1f, new Complex32(1.1f, -4f), 2f }, { 1f, 1f, 2f }, { 1f, new Complex32(1f, 2f), 2f } }); case TestMatrix.DenseSquare3x3b: return M.DenseOfArray(new[,] { { -1.1f, -2.2f, -3.3f }, { 0f, 1.1f, new Complex32(2.2f, -1.2f) }, { -4.4f, 5.5f, 6.6f } }); case TestMatrix.DenseSquare3x3c: return M.DenseOfArray(new[,] { { 1f, 2f, 3f }, { 2f, new Complex32(2f, 2f), 0f }, { 3f, Complex32.Zero, 3f } }); case TestMatrix.DenseSquare4x4: return M.DenseOfArray(new[,] { { new Complex32(-1.1f, -2f), -2.2f, -3.3f, -4.4f }, { 0f, 1.1f, 2.2f, 3.3f }, { 1f, 2.1f, 6.2f, 4.3f }, { -4.4f, 5.5f, 6.6f, -7.7f } }); case TestMatrix.DenseSquare4x4b: return M.DenseOfArray(new[,] { { -1.1f, new Complex32(-2.2f, 3.4f), -3.3f, -4.4f }, { -1.1f, -2.2f, -3.3f, -4.4f }, { -1.1f, -2.2f, -3.3f, -4.4f }, { -1.1f, -2.2f, -3.3f, -4.4f } }); case TestMatrix.DenseTall3x2: return M.DenseOfArray(new[,] { { -1.1f, -2.2f }, { Complex32.Zero, 1.1f }, { -4.4f, 5.5f } }); case TestMatrix.DenseWide2x3: return M.DenseOfArray(new[,] { { -1.1f, -2.2f, -3.3f }, { 0f, new Complex32(1.1f, 0.1f), 2.2f } }); case TestMatrix.SparseSquare3x3: return M.SparseOfArray(new[,] { { 7f, 1f, 2f }, { 1f, 1f, 2f }, { 1f, 1f + Complex32.ImaginaryOne, 2f } }); case TestMatrix.SparseSquare3x3b: return M.SparseOfArray(new[,] { { 7f, 1f, 2f }, { new Complex32(1f, 2f), 0f, Complex32.Zero }, { -2f, 0f, 0f } }); case TestMatrix.SparseWide2x3: return M.SparseOfArray(new[,] { { -1.1f, 0f, 0f }, { 0f, new Complex32(1.1f, 2f), 2.2f } }); case TestMatrix.DiagonalSquare3x3: return M.Diagonal(3, 3, new[] { new Complex32(1f, 1f), -2f, 1.5f }); case TestMatrix.DiagonalSquare3x3b: return M.Diagonal(3, 3, new[] { new Complex32(1f, 2f), 0f, -1.5f }); case TestMatrix.UserSquare3x3: return new UserDefinedMatrix(new[,] { { 0f, 1f, 2f }, { -1f, 7.7f, 0f }, { -2f, Complex32.Zero, 0f } }); default: throw new NotSupportedException(); } } public static Vector<Complex32> Vector(TestVector vector) { switch (vector) { case TestVector.Dense5: return V.Dense(new[] { new Complex32(1, 1), new Complex32(2, 1), new Complex32(3, 1), new Complex32(4, 1), new Complex32(5, 1) }); case TestVector.Dense5WithZeros: return V.Dense(new[] { new Complex32(2, -1), new Complex32(0, 0), new Complex32(0, 2), new Complex32(-5, 1), new Complex32(0, 0) }); case TestVector.Sparse5: return V.SparseOfEnumerable(new[] { new Complex32(1, 1), new Complex32(2, 1), new Complex32(3, 1), new Complex32(4, 1), new Complex32(5, 1) }); case TestVector.Sparse5WithZeros: return V.SparseOfEnumerable(new[] { new Complex32(2, -1), new Complex32(0, 0), new Complex32(0, 2), new Complex32(-5, 1), new Complex32(0, 0) }); case TestVector.Sparse5AllZeros: return V.Sparse(5); case TestVector.SparseMaxLengthAllZeros: return V.Sparse(int.MaxValue); default: throw new NotSupportedException(); } } } }
albertp007/mathnet-numerics
src/UnitTests/LinearAlgebraTests/Complex32/TestData.cs
C#
mit
5,068
# The Dispatcher concept ## HTTP Libraries By "HTTP implementation", it means: *a layer that helps us to work with Request and Response in terms of reading a request, create a response and send it back to the client.* In PHP there are a lot of libraries that do that: * [Zend\Http](https://github.com/zendframework/zend-http) * [Zend\Diactoros](https://github.com/zendframework/zend-diactoros) * [Symfony\HttpFoundation](https://github.com/symfony/HttpFoundation) * [guzzle/psr7](https://github.com/guzzle/psr7) ## Dispatcher The [Dispatcher](https://github.com/gianarb/penny/blob/master/src/Dispatcher.php) (click link to show current implementation), in penny represents the link between: router, request and response. The default Penny Dispatcher implementation uses `Zend\Diactoros`. We can write our own dispatcher that makes use of our favorite HTTP library Main advantages gained by using `Zend\Diactoros` are: * It is supported by the Zend Framework community * It follows PSR-7 standard. [(what is PSR-7?)](http://www.php-fig.org/psr/psr-7/) If the dispatch process is good and exists a callable for our request it returns a RouteInfo implementations. ## Penny, FastRouter and Symfony\HttpFoundation Here we are going to see how to write a dispatcher to use with the `Symfony\HttpFoundation` component. 1. Install it. ``` composer require symfony/http-foundation ``` 2. Write our dispatcher that uses the `HttpFoundation\Request` ```php <?php namespace OurApp\Dispatcher; use Symfony\Component\HttpFoundation\Request; class FastSymfonyDispatcher { private $router; public function __construct($router) { $this->router = $router; } public function dispatch(Request $request) { $routeInfo = $this->router->dispatch($request->getMethod(), $request->getPathInfo()); switch ($routeInfo[0]) { case \FastRoute\Dispatcher::NOT_FOUND: throw new \Penny\Exception\RouteNotFoundException(); break; case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED: throw new \Penny\Exception\MethodNotAllowedException(); break; case \FastRoute\Dispatcher::FOUND: return $routeInfo; break; default: throw new \Exception(null, 500); break; } } } ``` 3. Create custom endpoint that consume `Symfony\Component\HttpFoundation\Request` and `Response` ```php <?php use Penny\App; use OurApp\Dispatcher\FastSymfonyDispatcher; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; $this->app = new App(); $dispatcher = new FastSymfonyDispatcher($router); $this->app->getContainer()->set("dispatcher", $dispatcher); $this->app->run($request, $response); ``` Now our application runs using the `Symfony\HttpFoundation` instead of `Zend\Diactoros`.
pennyphp/penny
docs/the-dispatcher-concept.md
Markdown
mit
2,915
SET @sName = 'bx_decorous'; -- SETTINGS INSERT INTO `sys_options_types`(`group`, `name`, `caption`, `icon`, `order`) VALUES ('templates', @sName, '_bx_decorous_stg_cpt_type', 'bx_decorous@modules/boonex/decorous/|std-icon.svg', 2); SET @iTypeId = LAST_INSERT_ID(); -- SETTINGS: Decorous template System INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_system'), '_bx_decorous_stg_cpt_category_system', 10); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_switcher_title'), '_bx_decorous_stg_cpt_option_switcher_name', 'Decorous', 'digit', '', '', '', 1), (@iCategoryId, CONCAT(@sName, '_default_mix'), '_bx_decorous_stg_cpt_option_default_mix', '', 'select', 'a:2:{s:6:"module";s:11:"bx_decorous";s:6:"method";s:23:"get_options_default_mix";}', '', '', 10); -- SETTINGS: Decorous template Styles General INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_styles_general'), '_bx_decorous_stg_cpt_category_styles_general', 20); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_general_item_bg_color_hover'), '_bx_decorous_stg_cpt_option_general_item_bg_color_hover', 'rgba(245, 245, 245, 1)', 'rgba', '', '', '', 1), (@iCategoryId, CONCAT(@sName, '_general_item_bg_color_active'), '_bx_decorous_stg_cpt_option_general_item_bg_color_active', 'rgba(230, 247, 255, 1)', 'rgba', '', '', '', 2), (@iCategoryId, CONCAT(@sName, '_general_item_bg_color_disabled'), '_bx_decorous_stg_cpt_option_general_item_bg_color_disabled', '', 'rgba', '', '', '', 3); -- SETTINGS: Decorous template Styles Header INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_styles_header'), '_bx_decorous_stg_cpt_category_styles_header', 30); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_header_height'), '_bx_decorous_stg_cpt_option_header_height', '4rem', 'digit', '', '', '', 1), (@iCategoryId, CONCAT(@sName, '_header_content_padding'), '_bx_decorous_stg_cpt_option_header_content_padding', '0.5rem', 'digit', '', '', '', 2), (@iCategoryId, CONCAT(@sName, '_header_bg_color'), '_bx_decorous_stg_cpt_option_header_bg_color', 'rgba(255, 255, 255, 0.8)', 'rgba', '', '', '', 3), (@iCategoryId, CONCAT(@sName, '_header_bg_image'), '_bx_decorous_stg_cpt_option_header_bg_image', '', 'image', '', '', '', 4), (@iCategoryId, CONCAT(@sName, '_header_bg_image_repeat'), '_bx_decorous_stg_cpt_option_header_bg_image_repeat', 'no-repeat', 'select', 'no-repeat,repeat,repeat-x,repeat-y', '', '', 5), (@iCategoryId, CONCAT(@sName, '_header_bg_image_attachment'), '_bx_decorous_stg_cpt_option_header_bg_image_attachment', 'scroll', 'select', 'fixed,scroll,local', '', '', 6), (@iCategoryId, CONCAT(@sName, '_header_bg_image_size'), '_bx_decorous_stg_cpt_option_header_bg_image_size', 'cover', 'select', 'auto,cover,contain', '', '', 7), (@iCategoryId, CONCAT(@sName, '_site_logo'), '_bx_decorous_stg_cpt_option_site_logo', '', 'image', '', '', '', 8), (@iCategoryId, CONCAT(@sName, '_site_logo_alt'), '_bx_decorous_stg_cpt_option_site_logo_alt', '', 'text', '', '', '', 9), (@iCategoryId, CONCAT(@sName, '_site_logo_width'), '_bx_decorous_stg_cpt_option_site_logo_width', '240', 'digit', '', '', '', 10), (@iCategoryId, CONCAT(@sName, '_site_logo_height'), '_bx_decorous_stg_cpt_option_site_logo_height', '64', 'digit', '', '', '', 11), (@iCategoryId, CONCAT(@sName, '_header_border_color'), '_bx_decorous_stg_cpt_option_header_border_color', 'rgba(0, 0, 0, 0.1)', 'rgba', '', '', '', 12), (@iCategoryId, CONCAT(@sName, '_header_border_size'), '_bx_decorous_stg_cpt_option_header_border_size', '1px', 'digit', '', '', '', 13), (@iCategoryId, CONCAT(@sName, '_header_shadow'), '_bx_decorous_stg_cpt_option_header_shadow', '', 'digit', '', '', '', 14), (@iCategoryId, CONCAT(@sName, '_header_icon_color'), '_bx_decorous_stg_cpt_option_header_icon_color', 'rgba(89, 89, 89, 1)', 'rgba', '', '', '', 15), (@iCategoryId, CONCAT(@sName, '_header_icon_color_hover'), '_bx_decorous_stg_cpt_option_header_icon_color_hover', 'rgba(24, 144, 255, 1)', 'rgba', '', '', '', 16), (@iCategoryId, CONCAT(@sName, '_header_link_color'), '_bx_decorous_stg_cpt_option_header_link_color', 'rgba(89, 89, 89, 1)', 'rgba', '', '', '', 17), (@iCategoryId, CONCAT(@sName, '_header_link_color_hover'), '_bx_decorous_stg_cpt_option_header_link_color_hover', 'rgba(24, 144, 255, 1)', 'rgba', '', '', '', 18); -- SETTINGS: Decorous template Styles Footer INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_styles_footer'), '_bx_decorous_stg_cpt_category_styles_footer', 40); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_footer_bg_color'), '_bx_decorous_stg_cpt_option_footer_bg_color', 'rgba(255, 255, 255, 1)', 'rgba', '', '', '', 1), (@iCategoryId, CONCAT(@sName, '_footer_bg_image'), '_bx_decorous_stg_cpt_option_footer_bg_image', '', 'image', '', '', '', 2), (@iCategoryId, CONCAT(@sName, '_footer_bg_image_repeat'), '_bx_decorous_stg_cpt_option_footer_bg_image_repeat', 'no-repeat', 'select', 'no-repeat,repeat,repeat-x,repeat-y', '', '', 3), (@iCategoryId, CONCAT(@sName, '_footer_bg_image_attachment'), '_bx_decorous_stg_cpt_option_footer_bg_image_attachment', 'scroll', 'select', 'fixed,scroll,local', '', '', 4), (@iCategoryId, CONCAT(@sName, '_footer_bg_image_size'), '_bx_decorous_stg_cpt_option_footer_bg_image_size', 'cover', 'select', 'auto,cover,contain', '', '', 5), (@iCategoryId, CONCAT(@sName, '_footer_content_padding'), '_bx_decorous_stg_cpt_option_footer_content_padding', '1rem', 'digit', '', '', '', 6), (@iCategoryId, CONCAT(@sName, '_footer_border_color'), '_bx_decorous_stg_cpt_option_footer_border_color', 'rgba(0, 0, 0, 0.1)', 'rgba', '', '', '', 7), (@iCategoryId, CONCAT(@sName, '_footer_border_size'), '_bx_decorous_stg_cpt_option_footer_border_size', '1px', 'digit', '', '', '', 8), (@iCategoryId, CONCAT(@sName, '_footer_shadow'), '_bx_decorous_stg_cpt_option_footer_shadow', '', 'digit', '', '', '', 9), (@iCategoryId, CONCAT(@sName, '_footer_font_color'), '_bx_decorous_stg_cpt_option_footer_font_color', 'rgba(89, 89, 89, 1)', 'rgba', '', '', '', 10), (@iCategoryId, CONCAT(@sName, '_footer_icon_color'), '_bx_decorous_stg_cpt_option_footer_icon_color', 'rgba(89, 89, 89, 1)', 'rgba', '', '', '', 11), (@iCategoryId, CONCAT(@sName, '_footer_icon_color_hover'), '_bx_decorous_stg_cpt_option_footer_icon_color_hover', '', 'rgba', '', '', '', 12), (@iCategoryId, CONCAT(@sName, '_footer_link_color'), '_bx_decorous_stg_cpt_option_footer_link_color', 'rgba(89, 89, 89, 1)', 'rgba', '', '', '', 13), (@iCategoryId, CONCAT(@sName, '_footer_link_color_hover'), '_bx_decorous_stg_cpt_option_footer_link_color_hover', 'rgba(24, 144, 255, 1)', 'rgba', '', '', '', 14); -- SETTINGS: Decorous template Styles Body INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_styles_body'), '_bx_decorous_stg_cpt_category_styles_body', 50); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_body_bg_color'), '_bx_decorous_stg_cpt_option_body_bg_color', 'rgb(240, 242, 245)', 'rgb', '', '', '', 1), (@iCategoryId, CONCAT(@sName, '_body_bg_image'), '_bx_decorous_stg_cpt_option_body_bg_image', '', 'image', '', '', '', 2), (@iCategoryId, CONCAT(@sName, '_body_bg_image_repeat'), '_bx_decorous_stg_cpt_option_body_bg_image_repeat', 'no-repeat', 'select', 'no-repeat,repeat,repeat-x,repeat-y', '', '', 3), (@iCategoryId, CONCAT(@sName, '_body_bg_image_attachment'), '_bx_decorous_stg_cpt_option_body_bg_image_attachment', 'scroll', 'select', 'fixed,scroll,local', '', '', 4), (@iCategoryId, CONCAT(@sName, '_body_bg_image_size'), '_bx_decorous_stg_cpt_option_body_bg_image_size', 'cover', 'select', 'auto,cover,contain', '', '', 5), (@iCategoryId, CONCAT(@sName, '_page_width'), '_bx_decorous_stg_cpt_option_page_width', '100%', 'digit', '', '', '', 6), (@iCategoryId, CONCAT(@sName, '_body_icon_color'), '_bx_decorous_stg_cpt_option_body_icon_color', 'rgba(89, 89, 89, 1)', 'rgba', '', '', '', 7), (@iCategoryId, CONCAT(@sName, '_body_icon_color_hover'), '_bx_decorous_stg_cpt_option_body_icon_color_hover', 'rgba(24, 144, 255, 0.9)', 'rgba', '', '', '', 8), (@iCategoryId, CONCAT(@sName, '_body_link_color'), '_bx_decorous_stg_cpt_option_body_link_color', 'rgba(89, 89, 89, 1)', 'rgba', '', '', '', 9), (@iCategoryId, CONCAT(@sName, '_body_link_color_hover'), '_bx_decorous_stg_cpt_option_body_link_color_hover', 'rgba(24, 144, 255, 0.9)', 'rgba', '', '', '', 10); -- SETTINGS: Decorous template Styles Cover INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_styles_cover'), '_bx_decorous_stg_cpt_category_styles_cover', 55); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_cover_height'), '_bx_decorous_stg_cpt_option_cover_height', '30vh', 'digit', '', '', '', 1), (@iCategoryId, CONCAT(@sName, '_cover_bg_color'), '_bx_decorous_stg_cpt_option_cover_bg_color', 'rgba(255, 255, 255, 1)', 'rgba', '', '', '', 2), (@iCategoryId, CONCAT(@sName, '_cover_content_padding'), '_bx_decorous_stg_cpt_option_cover_content_padding', '2rem 3rem 2rem 3rem', 'digit', '', '', '', 3), (@iCategoryId, CONCAT(@sName, '_cover_border_color'), '_bx_decorous_stg_cpt_option_cover_border_color', 'rgba(0, 0, 0, 0.1)', 'rgba', '', '', '', 4), (@iCategoryId, CONCAT(@sName, '_cover_border_size'), '_bx_decorous_stg_cpt_option_cover_border_size', '1px', 'digit', '', '', '', 5), (@iCategoryId, CONCAT(@sName, '_cover_border_radius'), '_bx_decorous_stg_cpt_option_cover_border_radius', '0px', 'digit', '', '', '', 6), (@iCategoryId, CONCAT(@sName, '_cover_shadow'), '_bx_decorous_stg_cpt_option_cover_shadow', '', 'digit', '', '', '', 7), (@iCategoryId, CONCAT(@sName, '_cover_icon_border_color'), '_bx_decorous_stg_cpt_option_cover_icon_border_color', 'rgba(208, 208, 208, 1)', 'rgba', '', '', '', 8), (@iCategoryId, CONCAT(@sName, '_cover_icon_border_size'), '_bx_decorous_stg_cpt_option_cover_icon_border_size', '1px', 'digit', '', '', '', 9), (@iCategoryId, CONCAT(@sName, '_cover_icon_border_radius'), '_bx_decorous_stg_cpt_option_cover_icon_border_radius', '3px', 'digit', '', '', '', 10), (@iCategoryId, CONCAT(@sName, '_cover_icon_shadow'), '_bx_decorous_stg_cpt_option_cover_icon_shadow', 'none', 'digit', '', '', '', 11), (@iCategoryId, CONCAT(@sName, '_cover_text_align'), '_bx_decorous_stg_cpt_option_cover_text_align', 'center', 'select', 'left,center,right', '', '', 12), (@iCategoryId, CONCAT(@sName, '_cover_text_shadow'), '_bx_decorous_stg_cpt_option_cover_text_shadow', '0px 1px 3px rgba(0, 0, 0, .3)', 'digit', '', '', '', 13), (@iCategoryId, CONCAT(@sName, '_cover_font_family'), '_bx_decorous_stg_cpt_option_cover_font_family', '-apple-system,BlinkMacSystemFont,segoe ui,Roboto,helvetica neue,Arial,noto sans,sans-serif', 'digit', '', '', '', 14), (@iCategoryId, CONCAT(@sName, '_cover_font_size'), '_bx_decorous_stg_cpt_option_cover_font_size', '2.0rem', 'digit', '', '', '', 15), (@iCategoryId, CONCAT(@sName, '_cover_font_color'), '_bx_decorous_stg_cpt_option_cover_font_color', 'rgba(255, 255, 255, 1)', 'rgba', '', '', '', 16), (@iCategoryId, CONCAT(@sName, '_cover_font_weight'), '_bx_decorous_stg_cpt_option_cover_font_weight', '700', 'digit', '', '', '', 17); -- SETTINGS: Decorous template Styles Block INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_styles_block'), '_bx_decorous_stg_cpt_category_styles_block', 60); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_block_bg_color'), '_bx_decorous_stg_cpt_option_block_bg_color', 'rgba(255, 255, 255, 1)', 'rgba', '', '', '', 1), (@iCategoryId, CONCAT(@sName, '_block_bg_image'), '_bx_decorous_stg_cpt_option_block_bg_image', '', 'image', '', '', '', 2), (@iCategoryId, CONCAT(@sName, '_block_bg_image_repeat'), '_bx_decorous_stg_cpt_option_block_bg_image_repeat', 'no-repeat', 'select', 'no-repeat,repeat,repeat-x,repeat-y', '', '', 3), (@iCategoryId, CONCAT(@sName, '_block_bg_image_attachment'), '_bx_decorous_stg_cpt_option_block_bg_image_attachment', 'scroll', 'select', 'fixed,scroll,local', '', '', 4), (@iCategoryId, CONCAT(@sName, '_block_bg_image_size'), '_bx_decorous_stg_cpt_option_block_bg_image_size', 'cover', 'select', 'auto,cover,contain', '', '', 5), (@iCategoryId, CONCAT(@sName, '_block_content_padding'), '_bx_decorous_stg_cpt_option_block_content_padding', '1rem', 'digit', '', '', '', 6), (@iCategoryId, CONCAT(@sName, '_block_border_color'), '_bx_decorous_stg_cpt_option_block_border_color', 'rgba(0, 0, 0, 0.1)', 'rgba', '', '', '', 7), (@iCategoryId, CONCAT(@sName, '_block_border_size'), '_bx_decorous_stg_cpt_option_block_border_size', '1px', 'digit', '', '', '', 8), (@iCategoryId, CONCAT(@sName, '_block_border_radius'), '_bx_decorous_stg_cpt_option_block_border_radius', '4px', 'digit', '', '', '', 9), (@iCategoryId, CONCAT(@sName, '_block_shadow'), '_bx_decorous_stg_cpt_option_block_shadow', '', 'digit', '', '', '', 10), (@iCategoryId, CONCAT(@sName, '_block_title_bg_color'), '_bx_decorous_stg_cpt_option_block_title_bg_color', '', 'rgba', '', '', '', 11), (@iCategoryId, CONCAT(@sName, '_block_title_padding'), '_bx_decorous_stg_cpt_option_block_title_padding', '0.75rem 1.0rem', 'digit', '', '', '', 12), (@iCategoryId, CONCAT(@sName, '_block_title_border_color'), '_bx_decorous_stg_cpt_option_block_title_border_color', '', 'rgba', '', '', '', 13), (@iCategoryId, CONCAT(@sName, '_block_title_border_size'), '_bx_decorous_stg_cpt_option_block_title_border_size', '', 'digit', '', '', '', 14), (@iCategoryId, CONCAT(@sName, '_block_title_border_radius'), '_bx_decorous_stg_cpt_option_block_title_border_radius', '4px 4px 0px 0px', 'digit', '', '', '', 15), (@iCategoryId, CONCAT(@sName, '_block_title_font_family'), '_bx_decorous_stg_cpt_option_block_title_font_family', '-apple-system,BlinkMacSystemFont,segoe ui,Roboto,helvetica neue,Arial,noto sans,sans-serif', 'digit', '', '', '', 16), (@iCategoryId, CONCAT(@sName, '_block_title_font_size'), '_bx_decorous_stg_cpt_option_block_title_font_size', '1.25rem', 'digit', '', '', '', 17), (@iCategoryId, CONCAT(@sName, '_block_title_font_color'), '_bx_decorous_stg_cpt_option_block_title_font_color', 'rgba(0, 0, 0, 0.85);', 'rgba', '', '', '', 18), (@iCategoryId, CONCAT(@sName, '_block_title_font_weight'), '_bx_decorous_stg_cpt_option_block_title_font_weight', '700', 'digit', '', '', '', 19), (@iCategoryId, CONCAT(@sName, '_block_title_div_height'), '_bx_decorous_stg_cpt_option_block_title_div_height', '1px', 'digit', '', '', '', 20), (@iCategoryId, CONCAT(@sName, '_block_title_div_bg_color'), '_bx_decorous_stg_cpt_option_block_title_div_bg_color', 'rgba(240, 240, 240, 1)', 'rgba', '', '', '', 21); -- SETTINGS: Decorous template Styles Card INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_styles_card'), '_bx_decorous_stg_cpt_category_styles_card', 70); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_card_bg_color'), '_bx_decorous_stg_cpt_option_card_bg_color', 'rgba(255, 255, 255, 1)', 'rgba', '', '', '', 1), (@iCategoryId, CONCAT(@sName, '_card_bg_color_hover'), '_bx_decorous_stg_cpt_option_card_bg_color_hover', 'rgba(255, 255, 255, 0.5)', 'rgba', '', '', '', 2), (@iCategoryId, CONCAT(@sName, '_card_bg_image'), '_bx_decorous_stg_cpt_option_card_bg_image', '', 'image', '', '', '', 3), (@iCategoryId, CONCAT(@sName, '_card_bg_image_repeat'), '_bx_decorous_stg_cpt_option_card_bg_image_repeat', 'no-repeat', 'select', 'no-repeat,repeat,repeat-x,repeat-y', '', '', 4), (@iCategoryId, CONCAT(@sName, '_card_bg_image_attachment'), '_bx_decorous_stg_cpt_option_card_bg_image_attachment', 'scroll', 'select', 'fixed,scroll,local', '', '', 5), (@iCategoryId, CONCAT(@sName, '_card_bg_image_size'), '_bx_decorous_stg_cpt_option_card_bg_image_size', 'cover', 'select', 'auto,cover,contain', '', '', 6), (@iCategoryId, CONCAT(@sName, '_card_content_padding'), '_bx_decorous_stg_cpt_option_card_content_padding', '1rem', 'digit', '', '', '', 7), (@iCategoryId, CONCAT(@sName, '_card_border_color'), '_bx_decorous_stg_cpt_option_card_border_color', 'rgba(0, 0, 0, 0.1)', 'rgba', '', '', '', 8), (@iCategoryId, CONCAT(@sName, '_card_border_size'), '_bx_decorous_stg_cpt_option_card_border_size', '1px', 'digit', '', '', '', 9), (@iCategoryId, CONCAT(@sName, '_card_border_radius'), '_bx_decorous_stg_cpt_option_card_border_radius', '4px', 'digit', '', '', '', 10), (@iCategoryId, CONCAT(@sName, '_card_shadow'), '_bx_decorous_stg_cpt_option_card_shadow', '0px 2px 4px 0px rgba(0, 0, 0, 0.1)', 'digit', '', '', '', 11); -- SETTINGS: Decorous template Styles Popups INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_styles_popup'), '_bx_decorous_stg_cpt_category_styles_popup', 80); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_popup_bg_color'), '_bx_decorous_stg_cpt_option_popup_bg_color', 'rgba(255, 255, 255, 1)', 'rgba', '', '', '', 1), (@iCategoryId, CONCAT(@sName, '_popup_bg_image'), '_bx_decorous_stg_cpt_option_popup_bg_image', '', 'image', '', '', '', 2), (@iCategoryId, CONCAT(@sName, '_popup_bg_image_repeat'), '_bx_decorous_stg_cpt_option_popup_bg_image_repeat', 'no-repeat', 'select', 'no-repeat,repeat,repeat-x,repeat-y', '', '', 3), (@iCategoryId, CONCAT(@sName, '_popup_bg_image_attachment'), '_bx_decorous_stg_cpt_option_popup_bg_image_attachment', 'scroll', 'select', 'fixed,scroll,local', '', '', 4), (@iCategoryId, CONCAT(@sName, '_popup_bg_image_size'), '_bx_decorous_stg_cpt_option_popup_bg_image_size', 'cover', 'select', 'auto,cover,contain', '', '', 5), (@iCategoryId, CONCAT(@sName, '_popup_content_padding'), '_bx_decorous_stg_cpt_option_popup_content_padding', '1.25rem', 'digit', '', '', '', 6), (@iCategoryId, CONCAT(@sName, '_popup_border_color'), '_bx_decorous_stg_cpt_option_popup_border_color', 'rgba(0, 0, 0, 0.2)', 'rgba', '', '', '', 7), (@iCategoryId, CONCAT(@sName, '_popup_border_size'), '_bx_decorous_stg_cpt_option_popup_border_size', '1px', 'digit', '', '', '', 8), (@iCategoryId, CONCAT(@sName, '_popup_border_radius'), '_bx_decorous_stg_cpt_option_popup_border_radius', '3px', 'digit', '', '', '', 9), (@iCategoryId, CONCAT(@sName, '_popup_shadow'), '_bx_decorous_stg_cpt_option_popup_shadow', '0px 1px 5px 0px rgba(0, 0, 0, 0.05)', 'digit', '', '', '', 10), (@iCategoryId, CONCAT(@sName, '_popup_title_bg_color'), '_bx_decorous_stg_cpt_option_popup_title_bg_color', 'rgba(230, 240, 250, 0.9)', 'rgba', '', '', '', 11), (@iCategoryId, CONCAT(@sName, '_popup_title_padding'), '_bx_decorous_stg_cpt_option_popup_title_padding', '1.25rem', 'digit', '', '', '', 12), (@iCategoryId, CONCAT(@sName, '_popup_title_font_family'), '_bx_decorous_stg_cpt_option_popup_title_font_family', '-apple-system,BlinkMacSystemFont,segoe ui,Roboto,helvetica neue,Arial,noto sans,sans-serif', 'digit', '', '', '', 13), (@iCategoryId, CONCAT(@sName, '_popup_title_font_size'), '_bx_decorous_stg_cpt_option_popup_title_font_size', '1rem', 'digit', '', '', '', 14), (@iCategoryId, CONCAT(@sName, '_popup_title_font_color'), '_bx_decorous_stg_cpt_option_popup_title_font_color', 'rgba(40, 50, 60, 0.9)', 'rgba', '', '', '', 15); -- SETTINGS: Decorous template Styles Main Menu INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_styles_menu_main'), '_bx_decorous_stg_cpt_category_styles_menu_main', 90); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_menu_main_bg_color'), '_bx_decorous_stg_cpt_option_menu_main_bg_color', 'rgba(255, 255, 255, 1.0)', 'rgba', '', '', '', 1), (@iCategoryId, CONCAT(@sName, '_menu_main_bg_image'), '_bx_decorous_stg_cpt_option_menu_main_bg_image', '', 'image', '', '', '', 2), (@iCategoryId, CONCAT(@sName, '_menu_main_bg_image_repeat'), '_bx_decorous_stg_cpt_option_menu_main_bg_image_repeat', 'no-repeat', 'select', 'no-repeat,repeat,repeat-x,repeat-y', '', '', 3), (@iCategoryId, CONCAT(@sName, '_menu_main_bg_image_attachment'), '_bx_decorous_stg_cpt_option_menu_main_bg_image_attachment', 'scroll', 'select', 'fixed,scroll,local', '', '', 4), (@iCategoryId, CONCAT(@sName, '_menu_main_bg_image_size'), '_bx_decorous_stg_cpt_option_menu_main_bg_image_size', 'cover', 'select', 'auto,cover,contain', '', '', 5), (@iCategoryId, CONCAT(@sName, '_menu_main_content_padding'), '_bx_decorous_stg_cpt_option_menu_main_content_padding', '', 'digit', '', '', '', 6), (@iCategoryId, CONCAT(@sName, '_menu_main_border_color'), '_bx_decorous_stg_cpt_option_menu_main_border_color', 'rgba(0, 0, 0, 0.1)', 'rgba', '', '', '', 7), (@iCategoryId, CONCAT(@sName, '_menu_main_border_size'), '_bx_decorous_stg_cpt_option_menu_main_border_size', '0px', 'digit', '', '', '', 8), (@iCategoryId, CONCAT(@sName, '_menu_main_shadow'), '_bx_decorous_stg_cpt_option_menu_main_shadow', '2px 0px 8px 0px rgba(0, 0, 0, 0.1)', 'digit', '', '', '', 9), (@iCategoryId, CONCAT(@sName, '_menu_main_font_family'), '_bx_decorous_stg_cpt_option_menu_main_font_family', '-apple-system,BlinkMacSystemFont,segoe ui,Roboto,helvetica neue,Arial,noto sans,sans-serif', 'digit', '', '', '', 10), (@iCategoryId, CONCAT(@sName, '_menu_main_font_size'), '_bx_decorous_stg_cpt_option_menu_main_font_size', '1rem', 'digit', '', '', '', 11), (@iCategoryId, CONCAT(@sName, '_menu_main_font_color'), '_bx_decorous_stg_cpt_option_menu_main_font_color', 'rgba(89, 89, 89, 1)', 'rgba', '', '', '', 12), (@iCategoryId, CONCAT(@sName, '_menu_main_font_color_hover'), '_bx_decorous_stg_cpt_option_menu_main_font_color_hover', 'rgba(24, 144, 255, 0.9)', 'rgba', '', '', '', 13), (@iCategoryId, CONCAT(@sName, '_menu_main_font_color_active'), '_bx_decorous_stg_cpt_option_menu_main_font_color_active', 'rgba(24, 144, 255, 1)', 'rgba', '', '', '', 14), (@iCategoryId, CONCAT(@sName, '_menu_main_font_shadow'), '_bx_decorous_stg_cpt_option_menu_main_font_shadow', 'none', 'digit', '', '', '', 15), (@iCategoryId, CONCAT(@sName, '_menu_main_font_weight'), '_bx_decorous_stg_cpt_option_menu_main_font_weight', '400', 'digit', '', '', '', 16); -- SETTINGS: Decorous template Styles Account Menu INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_styles_menu_account'), '_bx_decorous_stg_cpt_category_styles_menu_account', 95); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_menu_account_bg_color'), '_bx_decorous_stg_cpt_option_menu_account_bg_color', 'rgba(255, 255, 255, 1)', 'rgba', '', '', '', 1), (@iCategoryId, CONCAT(@sName, '_menu_account_bg_image'), '_bx_decorous_stg_cpt_option_menu_account_bg_image', '', 'image', '', '', '', 2), (@iCategoryId, CONCAT(@sName, '_menu_account_bg_image_repeat'), '_bx_decorous_stg_cpt_option_menu_account_bg_image_repeat', 'no-repeat', 'select', 'no-repeat,repeat,repeat-x,repeat-y', '', '', 3), (@iCategoryId, CONCAT(@sName, '_menu_account_bg_image_attachment'), '_bx_decorous_stg_cpt_option_menu_account_bg_image_attachment', 'scroll', 'select', 'fixed,scroll,local', '', '', 4), (@iCategoryId, CONCAT(@sName, '_menu_account_bg_image_size'), '_bx_decorous_stg_cpt_option_menu_account_bg_image_size', 'cover', 'select', 'auto,cover,contain', '', '', 5), (@iCategoryId, CONCAT(@sName, '_menu_account_content_padding'), '_bx_decorous_stg_cpt_option_menu_account_content_padding', '1.25rem', 'digit', '', '', '', 6), (@iCategoryId, CONCAT(@sName, '_menu_account_border_color'), '_bx_decorous_stg_cpt_option_menu_account_border_color', 'rgba(0, 0, 0, 0.1)', 'rgba', '', '', '', 7), (@iCategoryId, CONCAT(@sName, '_menu_account_border_size'), '_bx_decorous_stg_cpt_option_menu_account_border_size', '1px', 'digit', '', '', '', 8), (@iCategoryId, CONCAT(@sName, '_menu_account_shadow'), '_bx_decorous_stg_cpt_option_menu_account_shadow', '0px 8px 16px 0px rgba(0, 0, 0, 0.1)', 'digit', '', '', '', 9), (@iCategoryId, CONCAT(@sName, '_menu_account_font_family'), '_bx_decorous_stg_cpt_option_menu_account_font_family', '-apple-system,BlinkMacSystemFont,segoe ui,Roboto,helvetica neue,Arial,noto sans,sans-serif', 'digit', '', '', '', 10), (@iCategoryId, CONCAT(@sName, '_menu_account_font_size'), '_bx_decorous_stg_cpt_option_menu_account_font_size', '1rem', 'digit', '', '', '', 11), (@iCategoryId, CONCAT(@sName, '_menu_account_font_color'), '_bx_decorous_stg_cpt_option_menu_account_font_color', 'rgba(89, 89, 89, 1)', 'rgba', '', '', '', 12), (@iCategoryId, CONCAT(@sName, '_menu_account_font_color_hover'), '_bx_decorous_stg_cpt_option_menu_account_font_color_hover', 'rgba(24, 144, 255, 0.9)', 'rgba', '', '', '', 13), (@iCategoryId, CONCAT(@sName, '_menu_account_font_color_active'), '_bx_decorous_stg_cpt_option_menu_account_font_color_active', 'rgba(24, 144, 255, 1)', 'rgba', '', '', '', 14), (@iCategoryId, CONCAT(@sName, '_menu_account_font_shadow'), '_bx_decorous_stg_cpt_option_menu_account_font_shadow', 'none', 'digit', '', '', '', 15), (@iCategoryId, CONCAT(@sName, '_menu_account_font_weight'), '_bx_decorous_stg_cpt_option_menu_account_font_weight', '400', 'digit', '', '', '', 16); -- SETTINGS: Decorous template Styles Add Menu INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_styles_menu_add'), '_bx_decorous_stg_cpt_category_styles_menu_add', 97); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_menu_add_bg_color'), '_bx_decorous_stg_cpt_option_menu_add_bg_color', 'rgba(255, 255, 255, 1)', 'rgba', '', '', '', 1), (@iCategoryId, CONCAT(@sName, '_menu_add_bg_image'), '_bx_decorous_stg_cpt_option_menu_add_bg_image', '', 'image', '', '', '', 2), (@iCategoryId, CONCAT(@sName, '_menu_add_bg_image_repeat'), '_bx_decorous_stg_cpt_option_menu_add_bg_image_repeat', 'no-repeat', 'select', 'no-repeat,repeat,repeat-x,repeat-y', '', '', 3), (@iCategoryId, CONCAT(@sName, '_menu_add_bg_image_attachment'), '_bx_decorous_stg_cpt_option_menu_add_bg_image_attachment', 'scroll', 'select', 'fixed,scroll,local', '', '', 4), (@iCategoryId, CONCAT(@sName, '_menu_add_bg_image_size'), '_bx_decorous_stg_cpt_option_menu_add_bg_image_size', 'cover', 'select', 'auto,cover,contain', '', '', 5), (@iCategoryId, CONCAT(@sName, '_menu_add_content_padding'), '_bx_decorous_stg_cpt_option_menu_add_content_padding', '0.5rem 1.25rem', 'digit', '', '', '', 6), (@iCategoryId, CONCAT(@sName, '_menu_add_border_color'), '_bx_decorous_stg_cpt_option_menu_add_border_color', 'rgba(0, 0, 0, 0.1)', 'rgba', '', '', '', 7), (@iCategoryId, CONCAT(@sName, '_menu_add_border_size'), '_bx_decorous_stg_cpt_option_menu_add_border_size', '1px', 'digit', '', '', '', 8), (@iCategoryId, CONCAT(@sName, '_menu_add_shadow'), '_bx_decorous_stg_cpt_option_menu_add_shadow', '0px 8px 16px 0px rgba(0, 0, 0, 0.1)', 'digit', '', '', '', 9), (@iCategoryId, CONCAT(@sName, '_menu_add_font_family'), '_bx_decorous_stg_cpt_option_menu_add_font_family', '-apple-system,BlinkMacSystemFont,segoe ui,Roboto,helvetica neue,Arial,noto sans,sans-serif', 'digit', '', '', '', 10), (@iCategoryId, CONCAT(@sName, '_menu_add_font_size'), '_bx_decorous_stg_cpt_option_menu_add_font_size', '1rem', 'digit', '', '', '', 11), (@iCategoryId, CONCAT(@sName, '_menu_add_font_color'), '_bx_decorous_stg_cpt_option_menu_add_font_color', 'rgba(89, 89, 89, 1)', 'rgba', '', '', '', 12), (@iCategoryId, CONCAT(@sName, '_menu_add_font_color_hover'), '_bx_decorous_stg_cpt_option_menu_add_font_color_hover', 'rgba(24, 144, 255, 0.9)', 'rgba', '', '', '', 13), (@iCategoryId, CONCAT(@sName, '_menu_add_font_color_active'), '_bx_decorous_stg_cpt_option_menu_add_font_color_active', 'rgba(24, 144, 255, 1)', 'rgba', '', '', '', 14), (@iCategoryId, CONCAT(@sName, '_menu_add_font_shadow'), '_bx_decorous_stg_cpt_option_menu_add_font_shadow', 'none', 'digit', '', '', '', 15), (@iCategoryId, CONCAT(@sName, '_menu_add_font_weight'), '_bx_decorous_stg_cpt_option_menu_add_font_weight', '400', 'digit', '', '', '', 16); -- SETTINGS: Decorous template Styles Page Menu INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_styles_menu_page'), '_bx_decorous_stg_cpt_category_styles_menu_page', 100); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_menu_page_bg_color'), '_bx_decorous_stg_cpt_option_menu_page_bg_color', 'rgba(255, 255, 255, 1)', 'rgba', '', '', '', 1), (@iCategoryId, CONCAT(@sName, '_menu_page_bg_image'), '_bx_decorous_stg_cpt_option_menu_page_bg_image', '', 'image', '', '', '', 2), (@iCategoryId, CONCAT(@sName, '_menu_page_bg_image_repeat'), '_bx_decorous_stg_cpt_option_menu_page_bg_image_repeat', 'no-repeat', 'select', 'no-repeat,repeat,repeat-x,repeat-y', '', '', 3), (@iCategoryId, CONCAT(@sName, '_menu_page_bg_image_attachment'), '_bx_decorous_stg_cpt_option_menu_page_bg_image_attachment', 'scroll', 'select', 'fixed,scroll,local', '', '', 4), (@iCategoryId, CONCAT(@sName, '_menu_page_bg_image_size'), '_bx_decorous_stg_cpt_option_menu_page_bg_image_size', 'cover', 'select', 'auto,cover,contain', '', '', 5), (@iCategoryId, CONCAT(@sName, '_menu_page_content_padding'), '_bx_decorous_stg_cpt_option_menu_page_content_padding', '0px', 'digit', '', '', '', 6), (@iCategoryId, CONCAT(@sName, '_menu_page_border_color'), '_bx_decorous_stg_cpt_option_menu_page_border_color', 'rgba(0, 0, 0, 0.1)', 'rgba', '', '', '', 7), (@iCategoryId, CONCAT(@sName, '_menu_page_border_size'), '_bx_decorous_stg_cpt_option_menu_page_border_size', '1px', 'digit', '', '', '', 8), (@iCategoryId, CONCAT(@sName, '_menu_page_shadow'), '_bx_decorous_stg_cpt_option_menu_page_shadow', '', 'digit', '', '', '', 9), (@iCategoryId, CONCAT(@sName, '_menu_page_font_family'), '_bx_decorous_stg_cpt_option_menu_page_font_family', '-apple-system,BlinkMacSystemFont,segoe ui,Roboto,helvetica neue,Arial,noto sans,sans-serif', 'digit', '', '', '', 10), (@iCategoryId, CONCAT(@sName, '_menu_page_font_size'), '_bx_decorous_stg_cpt_option_menu_page_font_size', '1rem', 'digit', '', '', '', 11), (@iCategoryId, CONCAT(@sName, '_menu_page_font_color'), '_bx_decorous_stg_cpt_option_menu_page_font_color', 'rgba(89, 89, 89, 1)', 'rgba', '', '', '', 12), (@iCategoryId, CONCAT(@sName, '_menu_page_font_color_hover'), '_bx_decorous_stg_cpt_option_menu_page_font_color_hover', 'rgba(24, 144, 255, 0.9)', 'rgba', '', '', '', 13), (@iCategoryId, CONCAT(@sName, '_menu_page_font_color_active'), '_bx_decorous_stg_cpt_option_menu_page_font_color_active', 'rgba(24, 144, 255, 1)', 'rgba', '', '', '', 14), (@iCategoryId, CONCAT(@sName, '_menu_page_font_shadow'), '_bx_decorous_stg_cpt_option_menu_page_font_shadow', 'none', 'digit', '', '', '', 15), (@iCategoryId, CONCAT(@sName, '_menu_page_font_weight'), '_bx_decorous_stg_cpt_option_menu_page_font_weight', '400', 'digit', '', '', '', 16); -- SETTINGS: Decorous template Styles Slide Menus INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_styles_menu_slide'), '_bx_decorous_stg_cpt_category_styles_menu_slide', 110); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_menu_slide_bg_color'), '_bx_decorous_stg_cpt_option_menu_slide_bg_color', 'rgba(255, 255, 255, 0.9)', 'rgba', '', '', '', 1), (@iCategoryId, CONCAT(@sName, '_menu_slide_bg_image'), '_bx_decorous_stg_cpt_option_menu_slide_bg_image', '', 'image', '', '', '', 2), (@iCategoryId, CONCAT(@sName, '_menu_slide_bg_image_repeat'), '_bx_decorous_stg_cpt_option_menu_slide_bg_image_repeat', 'no-repeat', 'select', 'no-repeat,repeat,repeat-x,repeat-y', '', '', 3), (@iCategoryId, CONCAT(@sName, '_menu_slide_bg_image_attachment'), '_bx_decorous_stg_cpt_option_menu_slide_bg_image_attachment', 'scroll', 'select', 'fixed,scroll,local', '', '', 4), (@iCategoryId, CONCAT(@sName, '_menu_slide_bg_image_size'), '_bx_decorous_stg_cpt_option_menu_slide_bg_image_size', 'cover', 'select', 'auto,cover,contain', '', '', 5), (@iCategoryId, CONCAT(@sName, '_menu_slide_content_padding'), '_bx_decorous_stg_cpt_option_menu_slide_content_padding', '1.25rem', 'digit', '', '', '', 6), (@iCategoryId, CONCAT(@sName, '_menu_slide_border_color'), '_bx_decorous_stg_cpt_option_menu_slide_border_color', 'rgba(0, 0, 0, 0.1)', 'rgba', '', '', '', 7), (@iCategoryId, CONCAT(@sName, '_menu_slide_border_size'), '_bx_decorous_stg_cpt_option_menu_slide_border_size', '1px 0px 1px 0px', 'digit', '', '', '', 8), (@iCategoryId, CONCAT(@sName, '_menu_slide_shadow'), '_bx_decorous_stg_cpt_option_menu_slide_shadow', 'none', 'digit', '', '', '', 9), (@iCategoryId, CONCAT(@sName, '_menu_slide_font_family'), '_bx_decorous_stg_cpt_option_menu_slide_font_family', '-apple-system,BlinkMacSystemFont,segoe ui,Roboto,helvetica neue,Arial,noto sans,sans-serif', 'digit', '', '', '', 10), (@iCategoryId, CONCAT(@sName, '_menu_slide_font_size'), '_bx_decorous_stg_cpt_option_menu_slide_font_size', '1.0rem', 'digit', '', '', '', 11), (@iCategoryId, CONCAT(@sName, '_menu_slide_font_color'), '_bx_decorous_stg_cpt_option_menu_slide_font_color', 'rgba(40, 50, 60, 0.8)', 'rgba', '', '', '', 12), (@iCategoryId, CONCAT(@sName, '_menu_slide_font_color_hover'), '_bx_decorous_stg_cpt_option_menu_slide_font_color_hover', 'rgba(40, 50, 60, 0.9)', 'rgba', '', '', '', 13), (@iCategoryId, CONCAT(@sName, '_menu_slide_font_color_active'), '_bx_decorous_stg_cpt_option_menu_slide_font_color_active', 'rgba(20, 30, 40, 1)', 'rgba', '', '', '', 14), (@iCategoryId, CONCAT(@sName, '_menu_slide_font_shadow'), '_bx_decorous_stg_cpt_option_menu_slide_font_shadow', 'none', 'digit', '', '', '', 15), (@iCategoryId, CONCAT(@sName, '_menu_slide_font_weight'), '_bx_decorous_stg_cpt_option_menu_slide_font_weight', '400', 'digit', '', '', '', 16); -- SETTINGS: Decorous template Styles Forms INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_styles_form'), '_bx_decorous_stg_cpt_category_styles_form', 120); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_form_input_height'), '_bx_decorous_stg_cpt_option_form_input_height', '2rem', 'digit', '', '', '', 1), (@iCategoryId, CONCAT(@sName, '_form_input_bg_color'), '_bx_decorous_stg_cpt_option_form_input_bg_color', 'rgba(255, 255, 255, 1)', 'rgba', '', '', '', 2), (@iCategoryId, CONCAT(@sName, '_form_input_bg_color_active'), '_bx_decorous_stg_cpt_option_form_input_bg_color_active', 'rgba(255, 255, 255, 1)', 'rgba', '', '', '', 3), (@iCategoryId, CONCAT(@sName, '_form_input_border_color'), '_bx_decorous_stg_cpt_option_form_input_border_color', 'rgba(217, 217, 217, 1)', 'rgba', '', '', '', 4), (@iCategoryId, CONCAT(@sName, '_form_input_border_color_active'), '_bx_decorous_stg_cpt_option_form_input_border_color_active', 'rgba(64, 169, 255, 1)', 'rgba', '', '', '', 5), (@iCategoryId, CONCAT(@sName, '_form_input_border_size'), '_bx_decorous_stg_cpt_option_form_input_border_size', '1px', 'digit', '', '', '', 6), (@iCategoryId, CONCAT(@sName, '_form_input_shadow'), '_bx_decorous_stg_cpt_option_form_input_shadow', '', 'digit', '', '', '', 7), (@iCategoryId, CONCAT(@sName, '_form_input_font_family'), '_bx_decorous_stg_cpt_option_form_input_font_family', '-apple-system,BlinkMacSystemFont,segoe ui,Roboto,helvetica neue,Arial,noto sans,sans-serif', 'digit', '', '', '', 8), (@iCategoryId, CONCAT(@sName, '_form_input_font_size'), '_bx_decorous_stg_cpt_option_form_input_font_size', '1rem', 'digit', '', '', '', 9), (@iCategoryId, CONCAT(@sName, '_form_input_font_color'), '_bx_decorous_stg_cpt_option_form_input_font_color', 'rgba(0, 0, 0, 0.65)', 'rgba', '', '', '', 10); -- SETTINGS: Decorous template Styles Large Buttons INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_styles_large_button'), '_bx_decorous_stg_cpt_category_styles_large_button', 130); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_button_lg_height'), '_bx_decorous_stg_cpt_option_button_lg_height', '2rem', 'digit', '', '', '', 1), (@iCategoryId, CONCAT(@sName, '_button_lg_bg_color'), '_bx_decorous_stg_cpt_option_button_lg_bg_color', 'rgba(24, 144, 255, 1)', 'rgba', '', '', '', 2), (@iCategoryId, CONCAT(@sName, '_button_lg_bg_color_hover'), '_bx_decorous_stg_cpt_option_button_lg_bg_color_hover', 'rgba(64, 169, 255, 1)', 'rgba', '', '', '', 3), (@iCategoryId, CONCAT(@sName, '_button_lg_border_color'), '_bx_decorous_stg_cpt_option_button_lg_border_color', 'rgba(24, 144, 255, 1)', 'rgba', '', '', '', 4), (@iCategoryId, CONCAT(@sName, '_button_lg_border_color_hover'), '_bx_decorous_stg_cpt_option_button_lg_border_color_hover', 'rgba(64, 169, 255, 1)', 'rgba', '', '', '', 5), (@iCategoryId, CONCAT(@sName, '_button_lg_border_size'), '_bx_decorous_stg_cpt_option_button_lg_border_size', '1px', 'digit', '', '', '', 6), (@iCategoryId, CONCAT(@sName, '_button_lg_border_radius'), '_bx_decorous_stg_cpt_option_button_lg_border_radius', '4px', 'digit', '', '', '', 7), (@iCategoryId, CONCAT(@sName, '_button_lg_shadow'), '_bx_decorous_stg_cpt_option_button_lg_shadow', '0px 2px 0px 0px rgba(0, 0, 0, 0.016)', 'digit', '', '', '', 8), (@iCategoryId, CONCAT(@sName, '_button_lg_font_family'), '_bx_decorous_stg_cpt_option_button_lg_font_family', '-apple-system,BlinkMacSystemFont,segoe ui,Roboto,helvetica neue,Arial,noto sans,sans-serif', 'digit', '', '', '', 9), (@iCategoryId, CONCAT(@sName, '_button_lg_font_size'), '_bx_decorous_stg_cpt_option_button_lg_font_size', '0.75rem', 'digit', '', '', '', 10), (@iCategoryId, CONCAT(@sName, '_button_lg_font_color'), '_bx_decorous_stg_cpt_option_button_lg_font_color', 'rgba(255, 255, 255, 0.9)', 'rgba', '', '', '', 11), (@iCategoryId, CONCAT(@sName, '_button_lg_font_color_hover'), '_bx_decorous_stg_cpt_option_button_lg_font_color_hover', 'rgba(255, 255, 255, 1)', 'rgba', '', '', '', 12), (@iCategoryId, CONCAT(@sName, '_button_lg_font_shadow'), '_bx_decorous_stg_cpt_option_button_lg_font_shadow', '0px -1px 0px; rgba(0, 0, 0, 0.12)', 'digit', '', '', '', 13), (@iCategoryId, CONCAT(@sName, '_button_lg_font_weight'), '_bx_decorous_stg_cpt_option_button_lg_font_weight', '600', 'digit', '', '', '', 14); -- SETTINGS: Decorous template Styles Small Buttons INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_styles_small_button'), '_bx_decorous_stg_cpt_category_styles_small_button', 140); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_button_sm_height'), '_bx_decorous_stg_cpt_option_button_sm_height', '1.75rem', 'digit', '', '', '', 1), (@iCategoryId, CONCAT(@sName, '_button_sm_bg_color'), '_bx_decorous_stg_cpt_option_button_sm_bg_color', 'rgba(255, 255, 255, 1)', 'rgba', '', '', '', 2), (@iCategoryId, CONCAT(@sName, '_button_sm_bg_color_hover'), '_bx_decorous_stg_cpt_option_button_sm_bg_color_hover', 'rgba(255, 255, 255, 1)', 'rgba', '', '', '', 3), (@iCategoryId, CONCAT(@sName, '_button_sm_border_color'), '_bx_decorous_stg_cpt_option_button_sm_border_color', 'rgba(217, 217, 217, 1)', 'rgba', '', '', '', 4), (@iCategoryId, CONCAT(@sName, '_button_sm_border_color_hover'), '_bx_decorous_stg_cpt_option_button_sm_border_color_hover', 'rgba(64, 169, 255, 1)', 'rgba', '', '', '', 5), (@iCategoryId, CONCAT(@sName, '_button_sm_border_size'), '_bx_decorous_stg_cpt_option_button_sm_border_size', '1px', 'digit', '', '', '', 6), (@iCategoryId, CONCAT(@sName, '_button_sm_border_radius'), '_bx_decorous_stg_cpt_option_button_sm_border_radius', '4px', 'digit', '', '', '', 7), (@iCategoryId, CONCAT(@sName, '_button_sm_shadow'), '_bx_decorous_stg_cpt_option_button_sm_shadow', '0px 2px 0px 0px rgba(0, 0, 0, 0.016)', 'digit', '', '', '', 8), (@iCategoryId, CONCAT(@sName, '_button_sm_font_family'), '_bx_decorous_stg_cpt_option_button_sm_font_family', '-apple-system,BlinkMacSystemFont,segoe ui,Roboto,helvetica neue,Arial,noto sans,sans-serif', 'digit', '', '', '', 9), (@iCategoryId, CONCAT(@sName, '_button_sm_font_size'), '_bx_decorous_stg_cpt_option_button_sm_font_size', '0.875rem', 'digit', '', '', '', 10), (@iCategoryId, CONCAT(@sName, '_button_sm_font_color'), '_bx_decorous_stg_cpt_option_button_sm_font_color', 'rgba(0, 0, 0, 0.65)', 'rgba', '', '', '', 11), (@iCategoryId, CONCAT(@sName, '_button_sm_font_color_hover'), '_bx_decorous_stg_cpt_option_button_sm_font_color_hover', 'rgba(64, 169, 255, 1)', 'rgba', '', '', '', 12), (@iCategoryId, CONCAT(@sName, '_button_sm_font_shadow'), '_bx_decorous_stg_cpt_option_button_sm_font_shadow', 'none', 'digit', '', '', '', 13), (@iCategoryId, CONCAT(@sName, '_button_sm_font_weight'), '_bx_decorous_stg_cpt_option_button_sm_font_weight', '400', 'digit', '', '', '', 14); -- SETTINGS: Decorous template Styles Font INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_styles_font'), '_bx_decorous_stg_cpt_category_styles_font', 150); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_font_family'), '_bx_decorous_stg_cpt_option_font_family', '-apple-system,BlinkMacSystemFont,segoe ui,Roboto,helvetica neue,Arial,noto sans,sans-serif', 'digit', '', '', '', 1), (@iCategoryId, CONCAT(@sName, '_font_size_default'), '_bx_decorous_stg_cpt_option_font_size_default', '16px', 'digit', '', '', '', 2), (@iCategoryId, CONCAT(@sName, '_font_color_default'), '_bx_decorous_stg_cpt_option_font_color_default', 'rgba(40, 50, 60, 0.9)', 'rgba', '', '', '', 3), (@iCategoryId, CONCAT(@sName, '_font_color_grayed'), '_bx_decorous_stg_cpt_option_font_color_grayed', 'rgba(40, 50, 60, 0.5)', 'rgba', '', '', '', 4), (@iCategoryId, CONCAT(@sName, '_font_color_contrasted'), '_bx_decorous_stg_cpt_option_font_color_contrasted', 'rgba(255, 255, 255, 1)', 'rgba', '', '', '', 5), (@iCategoryId, CONCAT(@sName, '_font_size_small'), '_bx_decorous_stg_cpt_option_font_size_small', '12px', 'digit', '', '', '', 6), (@iCategoryId, CONCAT(@sName, '_font_size_middle'), '_bx_decorous_stg_cpt_option_font_size_middle', '16px', 'digit', '', '', '', 7), (@iCategoryId, CONCAT(@sName, '_font_size_large'), '_bx_decorous_stg_cpt_option_font_size_large', '20px', 'digit', '', '', '', 8), (@iCategoryId, CONCAT(@sName, '_font_size_h1'), '_bx_decorous_stg_cpt_option_font_size_h1', '28px', 'digit', '', '', '', 9), (@iCategoryId, CONCAT(@sName, '_font_weight_h1'), '_bx_decorous_stg_cpt_option_font_weight_h1', '700', 'digit', '', '', '', 10), (@iCategoryId, CONCAT(@sName, '_font_color_default_h1'), '_bx_decorous_stg_cpt_option_font_color_default_h1', 'rgba(40, 50, 60, 1)', 'rgba', '', '', '', 11), (@iCategoryId, CONCAT(@sName, '_font_color_grayed_h1'), '_bx_decorous_stg_cpt_option_font_color_grayed_h1', 'rgba(40, 50, 60, 0.5)', 'rgba', '', '', '', 12), (@iCategoryId, CONCAT(@sName, '_font_color_contrasted_h1'), '_bx_decorous_stg_cpt_option_font_color_contrasted_h1', 'rgba(255, 255, 255, 0.9)', 'rgba', '', '', '', 13), (@iCategoryId, CONCAT(@sName, '_font_color_link_h1'), '_bx_decorous_stg_cpt_option_font_color_link_h1', 'rgba(24, 144, 255, 0.9)', 'rgba', '', '', '', 14), (@iCategoryId, CONCAT(@sName, '_font_color_link_h1_hover'), '_bx_decorous_stg_cpt_option_font_color_link_h1_hover', 'rgba(24, 144, 255, 1)', 'rgba', '', '', '', 15), (@iCategoryId, CONCAT(@sName, '_font_size_h2'), '_bx_decorous_stg_cpt_option_font_size_h2', '24px', 'digit', '', '', '', 16), (@iCategoryId, CONCAT(@sName, '_font_weight_h2'), '_bx_decorous_stg_cpt_option_font_weight_h2', '700', 'digit', '', '', '', 17), (@iCategoryId, CONCAT(@sName, '_font_color_default_h2'), '_bx_decorous_stg_cpt_option_font_color_default_h2', 'rgba(40, 60, 80, 0.9)', 'rgba', '', '', '', 18), (@iCategoryId, CONCAT(@sName, '_font_color_grayed_h2'), '_bx_decorous_stg_cpt_option_font_color_grayed_h2', 'rgba(40, 60, 80, 0.5)', 'rgba', '', '', '', 19), (@iCategoryId, CONCAT(@sName, '_font_color_contrasted_h2'), '_bx_decorous_stg_cpt_option_font_color_contrasted_h2', 'rgba(255, 255, 255, 1)', 'rgba', '', '', '', 20), (@iCategoryId, CONCAT(@sName, '_font_color_link_h2'), '_bx_decorous_stg_cpt_option_font_color_link_h2', 'rgba(24, 144, 255, 0.9)', 'rgba', '', '', '', 21), (@iCategoryId, CONCAT(@sName, '_font_color_link_h2_hover'), '_bx_decorous_stg_cpt_option_font_color_link_h2_hover', 'rgba(24, 144, 255, 1)', 'rgba', '', '', '', 22), (@iCategoryId, CONCAT(@sName, '_font_size_h3'), '_bx_decorous_stg_cpt_option_font_size_h3', '20px', 'digit', '', '', '', 23), (@iCategoryId, CONCAT(@sName, '_font_weight_h3'), '_bx_decorous_stg_cpt_option_font_weight_h3', '500', 'digit', '', '', '', 24), (@iCategoryId, CONCAT(@sName, '_font_color_default_h3'), '_bx_decorous_stg_cpt_option_font_color_default_h3', 'rgba(40, 60, 80, 0.9)', 'rgba', '', '', '', 25), (@iCategoryId, CONCAT(@sName, '_font_color_grayed_h3'), '_bx_decorous_stg_cpt_option_font_color_grayed_h3', 'rgba(40, 60, 80, 0.5)', 'rgba', '', '', '', 26), (@iCategoryId, CONCAT(@sName, '_font_color_contrasted_h3'), '_bx_decorous_stg_cpt_option_font_color_contrasted_h3', 'rgba(255, 255, 255, 1)', 'rgba', '', '', '', 27), (@iCategoryId, CONCAT(@sName, '_font_color_link_h3'), '_bx_decorous_stg_cpt_option_font_color_link_h3', 'rgba(24, 144, 255, 0.9)', 'rgba', '', '', '', 28), (@iCategoryId, CONCAT(@sName, '_font_color_link_h3_hover'), '_bx_decorous_stg_cpt_option_font_color_link_h3_hover', 'rgba(24, 144, 255, 1)', 'rgba', '', '', '', 29); -- SETTINGS: Decorous template Custom Styles INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_styles_custom'), '_bx_decorous_stg_cpt_category_styles_custom', 160); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_styles_custom'), '_bx_decorous_stg_cpt_option_styles_custom', 'div.bx-market-unit-cover div.bx-base-text-unit-no-thumb {\r\n border-width: 0px;\r\n}', 'text', '', '', '', 1); -- SETTINGS: Decorous template Viewport Tablet INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_viewport_tablet'), '_bx_decorous_stg_cpt_category_viewport_tablet', 170); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_vpt_font_size_scale'), '_bx_decorous_stg_cpt_option_vpt_font_size_scale', '100%', 'digit', '', '', '', 1); -- SETTINGS: Decorous template Viewport Mobile INSERT INTO `sys_options_categories`(`type_id`, `name`, `caption`, `order`) VALUES (@iTypeId, CONCAT(@sName, '_viewport_mobile'), '_bx_decorous_stg_cpt_category_viewport_mobile', 180); SET @iCategoryId = LAST_INSERT_ID(); INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `extra`, `check`, `check_error`, `order`) VALUES (@iCategoryId, CONCAT(@sName, '_vpm_font_size_scale'), '_bx_decorous_stg_cpt_option_vpm_font_size_scale', '87.5%', 'digit', '', '', '', 1); -- STUDIO PAGE & WIDGET INSERT INTO `sys_std_pages`(`index`, `name`, `header`, `caption`, `icon`) VALUES (3, @sName, '', '', 'bx_decorous@modules/boonex/decorous/|std-icon.svg'); SET @iPageId = LAST_INSERT_ID(); SET @iParentPageId = (SELECT `id` FROM `sys_std_pages` WHERE `name`='home'); SET @iParentPageOrder = (SELECT MAX(`order`) FROM `sys_std_pages_widgets` WHERE `page_id`=@iParentPageId); INSERT INTO `sys_std_widgets`(`page_id`, `module`, `type`, `url`, `click`, `icon`, `caption`, `cnt_notices`, `cnt_actions`) VALUES (@iPageId, @sName, 'appearance', CONCAT('{url_studio}design.php?name=', @sName), '', 'bx_decorous@modules/boonex/decorous/|std-icon.svg', '_bx_decorous_wgt_cpt', '', 'a:4:{s:6:"module";s:6:"system";s:6:"method";s:11:"get_actions";s:6:"params";a:0:{}s:5:"class";s:18:"TemplStudioDesigns";}'); INSERT INTO `sys_std_pages_widgets`(`page_id`, `widget_id`, `order`) VALUES (@iParentPageId, LAST_INSERT_ID(), @iParentPageOrder + 1);
unaio/una
modules/boonex/decorous/updates/12.0.0_12.0.1/source/install/sql/install.sql
SQL
mit
50,318
/* * Copyright (c) 2010-2015 OTClient <https://github.com/edubart/otclient> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "thing.h" #include "spritemanager.h" #include "thingtypemanager.h" #include <framework/graphics/graphics.h> #include "map.h" #include "tile.h" #include "game.h" Thing::Thing() : m_datId(0) { } void Thing::setPosition(const Position& position) { if(m_position == position) return; Position oldPos = m_position; m_position = position; onPositionChange(position, oldPos); } int Thing::getStackPriority() { if(isGround()) return 0; else if(isGroundBorder()) return 1; else if(isOnBottom()) return 2; else if(isOnTop()) return 3; else if(isCreature()) return 4; else // common items return 5; } const TilePtr& Thing::getTile() { return g_map.getTile(m_position); } ContainerPtr Thing::getParentContainer() { if(m_position.x == 0xffff && m_position.y & 0x40) { int containerId = m_position.y ^ 0x40; return g_game.getContainer(containerId); } return nullptr; } int Thing::getStackPos() { if(m_position.x == 65535 && isItem()) // is inside a container return m_position.z; else if(const TilePtr& tile = getTile()) return tile->getThingStackPos(static_self_cast<Thing>()); else { g_logger.traceError("got a thing with invalid stackpos"); return -1; } } const ThingTypePtr& Thing::getThingType() { return g_things.getNullThingType(); } ThingType* Thing::rawGetThingType() { return g_things.getNullThingType().get(); }
gpedro/otclient
src/client/thing.cpp
C++
mit
2,672
<div id="content"> <div id="inner"> <h1 id="signinLogo"><a href="/"></a></h1> <div id="signinBlock"> <span class="formContainer"> <form id="signInForm" name="login" ng-submit="submit(credentials)"> <input class="fillin validated " autofocus="true" name="email" value="" title="Email" type="email" required="required" placeholder="Email" spellcheck="false" ng-model="credentials.username"> <input class="fillin validated " name="password" title="Password" type="password" required="required" placeholder="Password" ng-model="credentials.password"> <span class="message"></span> <div class="buttonWrap"> <input type="hidden" name="persist" value="true"> <input type="hidden" name="returnTo" value="/"> <input class="button" type="submit" alt="Sign in!" value="Login"> </div> </form> </span> </div> </div> </div>
pfeffer629/CloudScript
src/public/shared/login/login.html
HTML
mit
881
#!/usr/bin/env bash # Copyright 2009 The Go Authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. # This script runs or (given -n) prints suggested commands to generate files for # the Architecture/OS specified by the GOARCH and GOOS environment variables. # See README.md for more information about how the build system works. GOOSARCH="${GOOS}_${GOARCH}" # defaults mksyscall="go run mksyscall.go" mkerrors="./mkerrors.sh" zerrors="zerrors_$GOOSARCH.go" mksysctl="" zsysctl="zsysctl_$GOOSARCH.go" mksysnum= mktypes= mkasm= run="sh" cmd="" case "$1" in -syscalls) for i in zsyscall*go do # Run the command line that appears in the first line # of the generated file to regenerate it. sed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i rm _$i done exit 0 ;; -n) run="cat" cmd="echo" shift esac case "$#" in 0) ;; *) echo 'usage: mkall.sh [-n]' 1>&2 exit 2 esac if [[ "$GOOS" = "linux" ]]; then # Use the Docker-based build system # Files generated through docker (use $cmd so you can Ctl-C the build or run) $cmd docker build --tag generate:$GOOS $GOOS $cmd docker run --interactive --tty --volume $(dirname "$(readlink -f "$0")"):/build generate:$GOOS exit fi GOOSARCH_in=syscall_$GOOSARCH.go case "$GOOSARCH" in _* | *_ | _) echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2 exit 1 ;; aix_ppc) mkerrors="$mkerrors -maix32" mksyscall="go run mksyscall_aix_ppc.go -aix" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; aix_ppc64) mkerrors="$mkerrors -maix64" mksyscall="./mksyscall_aix_ppc64.pl -aix" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; darwin_386) mkerrors="$mkerrors -m32" mksyscall="go run mksyscall.go -l32" mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" mkasm="go run mkasm_darwin.go" ;; darwin_amd64) mkerrors="$mkerrors -m64" mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" mkasm="go run mkasm_darwin.go" ;; darwin_arm) mkerrors="$mkerrors" mksyscall="go run mksyscall.go -l32" mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" mkasm="go run mkasm_darwin.go" ;; darwin_arm64) mkerrors="$mkerrors -m64" mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" mkasm="go run mkasm_darwin.go" ;; dragonfly_amd64) mkerrors="$mkerrors -m64" mksyscall="go run mksyscall.go -dragonfly" mksysnum="go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; freebsd_386) mkerrors="$mkerrors -m32" mksyscall="go run mksyscall.go -l32" mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master'" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; freebsd_amd64) mkerrors="$mkerrors -m64" mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master'" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; freebsd_arm) mkerrors="$mkerrors" mksyscall="go run mksyscall.go -l32 -arm" mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master'" # Let the type of C char be signed for making the bare syscall # API consistent across platforms. mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" ;; freebsd_arm64) mkerrors="$mkerrors -m64" mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master'" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; netbsd_386) mkerrors="$mkerrors -m32" mksyscall="go run mksyscall.go -l32 -netbsd" mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; netbsd_amd64) mkerrors="$mkerrors -m64" mksyscall="go run mksyscall.go -netbsd" mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; netbsd_arm) mkerrors="$mkerrors" mksyscall="go run mksyscall.go -l32 -netbsd -arm" mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'" # Let the type of C char be signed for making the bare syscall # API consistent across platforms. mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" ;; openbsd_386) mkerrors="$mkerrors -m32" mksyscall="go run mksyscall.go -l32 -openbsd" mksysctl="./mksysctl_openbsd.pl" mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; openbsd_amd64) mkerrors="$mkerrors -m64" mksyscall="go run mksyscall.go -openbsd" mksysctl="./mksysctl_openbsd.pl" mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; openbsd_arm) mkerrors="$mkerrors" mksyscall="go run mksyscall.go -l32 -openbsd -arm" mksysctl="./mksysctl_openbsd.pl" mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'" # Let the type of C char be signed for making the bare syscall # API consistent across platforms. mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" ;; solaris_amd64) mksyscall="./mksyscall_solaris.pl" mkerrors="$mkerrors -m64" mksysnum= mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; *) echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2 exit 1 ;; esac ( if [ -n "$mkerrors" ]; then echo "$mkerrors |gofmt >$zerrors"; fi case "$GOOS" in *) syscall_goos="syscall_$GOOS.go" case "$GOOS" in darwin | dragonfly | freebsd | netbsd | openbsd) syscall_goos="syscall_bsd.go $syscall_goos" ;; esac if [ -n "$mksyscall" ]; then if [ "$GOOSARCH" == "aix_ppc64" ]; then # aix/ppc64 script generates files instead of writing to stdin. echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_"$GOOSARCH"_gccgo.go && gofmt -w zsyscall_"$GOOSARCH"_gc.go " ; elif [ "$GOOS" == "darwin" ]; then # pre-1.12, direct syscalls echo "$mksyscall -tags $GOOS,$GOARCH,!go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.1_11.go"; # 1.12 and later, syscalls via libSystem echo "$mksyscall -tags $GOOS,$GOARCH,go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go"; else echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go"; fi fi esac if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi if [ -n "$mktypes" ]; then echo "$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go"; if [ -n "$mkasm" ]; then echo "$mkasm $GOARCH"; fi fi ) | $run
OpenBazaar/openbazaar-go
vendor/golang.org/x/sys/unix/mkall.sh
Shell
mit
7,230
class SS::Extensions::ObjectIds < Array def mongoize self.to_a end class << self def demongoize(object) self.new(object.to_a) end def mongoize(object) case object when self.class then object.mongoize when String then [] when Array ids = object.reject { |m| m.blank? }.uniq.map { |m| m =~ /[a-z]/ ? m.to_s : m.to_i } # ids = object.reject {|m| m.blank? }.uniq.map {|m| BSON::ObjectId.from_string(m) } self.new(ids).mongoize else object end end def evolve(object) case object when self.class then object.mongoize else object end end end end
itowtips/shirasagi
app/models/ss/extensions/object_ids.rb
Ruby
mit
684
# the scanner/lexer require 'forwardable' require 'strscan' require 'puppet' require 'puppet/util/methodhelper' module Puppet class LexError < RuntimeError; end end class Puppet::Pops::Parser::Lexer extend Forwardable attr_reader :file, :lexing_context, :token_queue attr_reader :locator attr_accessor :indefine alias :indefine? :indefine def lex_error msg raise Puppet::LexError.new(msg) end class Token ALWAYS_ACCEPTABLE = Proc.new { |context| true } include Puppet::Util::MethodHelper attr_accessor :regex, :name, :string, :skip, :skip_text alias skip? skip # @overload initialize(string) # @param string [String] a literal string token matcher # @param name [String] the token name (what it is known as in the grammar) # @param options [Hash] see {#set_options} # @overload initialize(regex) # @param regex [Regexp] a regular expression token text matcher # @param name [String] the token name (what it is known as in the grammar) # @param options [Hash] see {#set_options} # def initialize(string_or_regex, name, options = {}) if string_or_regex.is_a?(String) @name, @string = name, string_or_regex @regex = Regexp.new(Regexp.escape(string_or_regex)) else @name, @regex = name, string_or_regex end set_options(options) @acceptable_when = ALWAYS_ACCEPTABLE end # @return [String] human readable token reference; the String if literal, else the token name def to_s string or @name.to_s end # @return [Boolean] if the token is acceptable in the given context or not. # @param context [Hash] the lexing context # def acceptable?(context={}) @acceptable_when.call(context) end # Defines when the token is able to match. # This provides context that cannot be expressed otherwise, such as feature flags. # # @param block [Proc] a proc that given a context returns a boolean def acceptable_when(block) @acceptable_when = block end end # Maintains a list of tokens. class TokenList extend Forwardable attr_reader :regex_tokens, :string_tokens def_delegator :@tokens, :[] # Adds a new token to the set of recognized tokens # @param name [String] the token name # @param regex [Regexp, String] source text token matcher, a litral string or regular expression # @param options [Hash] see {Token::set_options} # @param block [Proc] optional block set as the created tokens `convert` method # @raise [ArgumentError] if the token with the given name is already defined # def add_token(name, regex, options = {}, &block) raise(ArgumentError, "Token #{name} already exists") if @tokens.include?(name) token = Token.new(regex, name, options) @tokens[token.name] = token if token.string @string_tokens << token @tokens_by_string[token.string] = token else @regex_tokens << token end token.meta_def(:convert, &block) if block_given? token end # Creates an empty token list # def initialize @tokens = {} @regex_tokens = [] @string_tokens = [] @tokens_by_string = {} end # Look up a token by its literal (match) value, rather than name. # @param string [String, nil] the literal match string to obtain a {Token} for, or nil if it does not exist. def lookup(string) @tokens_by_string[string] end # Adds tokens from a hash where key is a matcher (literal string or regexp) and the # value is the token's name # @param hash [Hash<{String => Symbol}, Hash<{Regexp => Symbol}] map token text matcher to token name # @return [void] # def add_tokens(hash) hash.each do |regex, name| add_token(name, regex) end end # Sort literal (string-) tokens by length, so we know once we match, we're done. # This helps avoid the O(n^2) nature of token matching. # The tokens are sorted in place. # @return [void] def sort_tokens @string_tokens.sort! { |a, b| b.string.length <=> a.string.length } end # Yield each token name and value in turn. def each @tokens.each {|name, value| yield name, value } end end TOKENS = TokenList.new TOKENS.add_tokens( '[' => :LBRACK, ']' => :RBRACK, # '{' => :LBRACE, # Specialized to handle lambda and brace count # '}' => :RBRACE, # Specialized to handle brace count '(' => :LPAREN, ')' => :RPAREN, '=' => :EQUALS, '+=' => :APPENDS, '-=' => :DELETES, '==' => :ISEQUAL, '>=' => :GREATEREQUAL, '>' => :GREATERTHAN, '<' => :LESSTHAN, '<=' => :LESSEQUAL, '!=' => :NOTEQUAL, '!' => :NOT, ',' => :COMMA, '.' => :DOT, ':' => :COLON, '@' => :AT, '|' => :PIPE, '<<|' => :LLCOLLECT, '|>>' => :RRCOLLECT, '->' => :IN_EDGE, '<-' => :OUT_EDGE, '~>' => :IN_EDGE_SUB, '<~' => :OUT_EDGE_SUB, '<|' => :LCOLLECT, '|>' => :RCOLLECT, ';' => :SEMIC, '?' => :QMARK, '\\' => :BACKSLASH, '=>' => :FARROW, '+>' => :PARROW, '+' => :PLUS, '-' => :MINUS, '/' => :DIV, '*' => :TIMES, '%' => :MODULO, '<<' => :LSHIFT, '>>' => :RSHIFT, '=~' => :MATCH, '!~' => :NOMATCH, %r{((::){0,1}[A-Z][-\w]*)+} => :CLASSREF, "<string>" => :STRING, "<dqstring up to first interpolation>" => :DQPRE, "<dqstring between two interpolations>" => :DQMID, "<dqstring after final interpolation>" => :DQPOST, "<boolean>" => :BOOLEAN, "<select start>" => :SELBRACE # A QMARK followed by '{' ) module Contextual QUOTE_TOKENS = [:DQPRE,:DQMID] REGEX_INTRODUCING_TOKENS = [:NODE,:LBRACE, :SELBRACE, :RBRACE,:MATCH,:NOMATCH,:COMMA] NOT_INSIDE_QUOTES = Proc.new do |context| !QUOTE_TOKENS.include? context[:after] end INSIDE_QUOTES = Proc.new do |context| QUOTE_TOKENS.include? context[:after] end IN_REGEX_POSITION = Proc.new do |context| REGEX_INTRODUCING_TOKENS.include? context[:after] end # DASHED_VARIABLES_ALLOWED = Proc.new do |context| # Puppet[:allow_variables_with_dashes] # end # # VARIABLE_AND_DASHES_ALLOWED = Proc.new do |context| # Contextual::DASHED_VARIABLES_ALLOWED.call(context) and TOKENS[:VARIABLE].acceptable?(context) # end end # Numbers are treated separately from names, so that they may contain dots. TOKENS.add_token :NUMBER, %r{\b(?:0[xX][0-9A-Fa-f]+|0?\d+(?:\.\d+)?(?:[eE]-?\d+)?)\b} do |lexer, value| lexer.assert_numeric(value) [TOKENS[:NAME], value] end TOKENS[:NUMBER].acceptable_when Contextual::NOT_INSIDE_QUOTES TOKENS.add_token :NAME, %r{((::)?[a-z0-9][-\w]*)(::[a-z0-9][-\w]*)*} do |lexer, value| # A name starting with a number must be a valid numeric string (not that # NUMBER token captures those names that do not comply with the name rule. if value =~ /^[0-9].*$/ lexer.assert_numeric(value) end string_token = self # we're looking for keywords here if tmp = KEYWORDS.lookup(value) string_token = tmp if [:TRUE, :FALSE].include?(string_token.name) value = eval(value) string_token = TOKENS[:BOOLEAN] end end [string_token, value] end [:NAME, :CLASSREF].each do |name_token| TOKENS[name_token].acceptable_when Contextual::NOT_INSIDE_QUOTES end TOKENS.add_token :COMMENT, %r{#.*}, :skip => true do |lexer,value| # value.sub!(/# ?/,'') [self, ""] end TOKENS.add_token :MLCOMMENT, %r{/\*(.*?)\*/}m, :skip => true do |lexer, value| # value.sub!(/^\/\* ?/,'') # value.sub!(/ ?\*\/$/,'') [self, ""] end TOKENS.add_token :REGEX, %r{/[^/\n]*/} do |lexer, value| # Make sure we haven't matched an escaped / while value[-2..-2] == '\\' other = lexer.scan_until(%r{/}) value += other end regex = value.sub(%r{\A/}, "").sub(%r{/\Z}, '').gsub("\\/", "/") [self, Regexp.new(regex)] end TOKENS[:REGEX].acceptable_when Contextual::IN_REGEX_POSITION TOKENS.add_token :RETURN, "\n", :skip => true, :skip_text => true TOKENS.add_token :SQUOTE, "'" do |lexer, value| [TOKENS[:STRING], lexer.slurpstring(value,["'"],:ignore_invalid_escapes).first ] end DQ_initial_token_types = {'$' => :DQPRE,'"' => :STRING} DQ_continuation_token_types = {'$' => :DQMID,'"' => :DQPOST} TOKENS.add_token :DQUOTE, /"/ do |lexer, value| lexer.tokenize_interpolated_string(DQ_initial_token_types) end # LBRACE needs look ahead to differentiate between '{' and a '{' # followed by a '|' (start of lambda) The racc grammar can only do one # token lookahead. # TOKENS.add_token :LBRACE, "{" do |lexer, value| lexer.lexing_context[:brace_count] += 1 if lexer.lexing_context[:after] == :QMARK [TOKENS[:SELBRACE], value] else [TOKENS[:LBRACE], value] end end # RBRACE needs to differentiate between a regular brace that is part of # syntax and one that is the ending of a string interpolation. TOKENS.add_token :RBRACE, "}" do |lexer, value| context = lexer.lexing_context if context[:interpolation_stack].empty? || context[:brace_count] != context[:interpolation_stack][-1] context[:brace_count] -= 1 [TOKENS[:RBRACE], value] else lexer.tokenize_interpolated_string(DQ_continuation_token_types) end end TOKENS.add_token :DOLLAR_VAR, %r{\$(::)?(\w+::)*\w+} do |lexer, value| [TOKENS[:VARIABLE],value[1..-1]] end TOKENS.add_token :VARIABLE, %r{(::)?(\w+::)*\w+} do |lexer, value| # If the varname (following $, or ${ is followed by (, it is a function call, and not a variable # reference. # if lexer.match?(%r{[ \t\r]*\(}) # followed by ( is a function call [TOKENS[:NAME], value] elsif kwd_token = KEYWORDS.lookup(value) # true, false, if, unless, case, and undef are keywords that cannot be used as variables # but node, and several others are variables if [ :TRUE, :FALSE ].include?(kwd_token.name) [ TOKENS[:BOOLEAN], eval(value) ] elsif [ :IF, :UNLESS, :CASE, :UNDEF ].include?(kwd_token.name) [kwd_token, value] else [TOKENS[:VARIABLE], value] end else [TOKENS[:VARIABLE], value] end end TOKENS[:VARIABLE].acceptable_when Contextual::INSIDE_QUOTES TOKENS.sort_tokens @@pairs = { "{" => "}", "(" => ")", "[" => "]", "<|" => "|>", "<<|" => "|>>", "|" => "|" } KEYWORDS = TokenList.new KEYWORDS.add_tokens( "case" => :CASE, "class" => :CLASS, "default" => :DEFAULT, "define" => :DEFINE, # "import" => :IMPORT, "if" => :IF, "elsif" => :ELSIF, "else" => :ELSE, "inherits" => :INHERITS, "node" => :NODE, "and" => :AND, "or" => :OR, "undef" => :UNDEF, "false" => :FALSE, "true" => :TRUE, "in" => :IN, "unless" => :UNLESS ) def clear initvars end def expected return nil if @expected.empty? name = @expected[-1] TOKENS.lookup(name) or lex_error "Internal Lexer Error: Could not find expected token #{name}" end # scan the whole file # basically just used for testing def fullscan array = [] self.scan { |token, str| # Ignore any definition nesting problems @indefine = false array.push([token,str]) } array end def file=(file) @file = file contents = Puppet::FileSystem.exist?(file) ? Puppet::FileSystem.read(file) : "" @scanner = StringScanner.new(contents.freeze) @locator = Puppet::Pops::Parser::Locator.locator(contents, file) end def_delegator :@token_queue, :shift, :shift_token def find_string_token # We know our longest string token is three chars, so try each size in turn # until we either match or run out of chars. This way our worst-case is three # tries, where it is otherwise the number of string token we have. Also, # the lookups are optimized hash lookups, instead of regex scans. # _scn = @scanner s = _scn.peek(3) token = TOKENS.lookup(s[0,3]) || TOKENS.lookup(s[0,2]) || TOKENS.lookup(s[0,1]) unless token return [nil, nil] end [ token, _scn.scan(token.regex) ] end # Find the next token that matches a regex. We look for these first. def find_regex_token best_token = nil best_length = 0 # I tried optimizing based on the first char, but it had # a slightly negative affect and was a good bit more complicated. _lxc = @lexing_context _scn = @scanner TOKENS.regex_tokens.each do |token| if length = _scn.match?(token.regex) and token.acceptable?(_lxc) # We've found a longer match if length > best_length best_length = length best_token = token end end end return best_token, _scn.scan(best_token.regex) if best_token end # Find the next token, returning the string and the token. def find_token shift_token || find_regex_token || find_string_token end MULTIBYTE = Puppet::Pops::Parser::Locator::MULTIBYTE SKIPPATTERN = MULTIBYTE ? %r{[[:blank:]\r]+} : %r{[ \t\r]+} def initialize initvars end def assert_numeric(value) if value =~ /^0[xX].*$/ lex_error (positioned_message("Not a valid hex number #{value}")) unless value =~ /^0[xX][0-9A-Fa-f]+$/ elsif value =~ /^0[^.].*$/ lex_error(positioned_message("Not a valid octal number #{value}")) unless value =~ /^0[0-7]+$/ else lex_error(positioned_message("Not a valid decimal number #{value}")) unless value =~ /0?\d+(?:\.\d+)?(?:[eE]-?\d+)?/ end end def initvars @previous_token = nil @scanner = nil @file = nil # AAARRGGGG! okay, regexes in ruby are bloody annoying # no one else has "\n" =~ /\s/ @namestack = [] @token_queue = [] @indefine = false @expected = [] @lexing_context = { :after => nil, :start_of_line => true, :offset => 0, # byte offset before where token starts :end_offset => 0, # byte offset after scanned token :brace_count => 0, # nested depth of braces :interpolation_stack => [] # matching interpolation brace level } end # Make any necessary changes to the token and/or value. def munge_token(token, value) # A token may already have been munged (converted and positioned) # return token, value if value.is_a? Hash @scanner.skip(SKIPPATTERN) if token.skip_text return if token.skip token, value = token.convert(self, value) if token.respond_to?(:convert) return unless token return if token.skip # If the conversion performed the munging/positioning return token, value if value.is_a? Hash return token, positioned_value(value) end # Returns a hash with the current position in source based on the current lexing context # def positioned_value(value) { :value => value, :locator => @locator, :offset => @lexing_context[:offset], :end_offset => @lexing_context[:end_offset] } end def pos @locator.pos_on_line(@lexing_context[:offset]) end # Handling the namespace stack def_delegator :@namestack, :pop, :namepop # This value might have :: in it, but we don't care -- it'll be handled # normally when joining, and when popping we want to pop this full value, # however long the namespace is. def_delegator :@namestack, :<<, :namestack # Collect the current namespace. def namespace @namestack.join("::") end def_delegator :@scanner, :rest LBRACE_CHAR = '{' # this is the heart of the lexer def scan _scn = @scanner #Puppet.debug("entering scan") lex_error "Internal Error: No string or file given to lexer to process." unless _scn # Skip any initial whitespace. _scn.skip(SKIPPATTERN) _lbrace = '{'.freeze # faster to compare against a frozen string in until token_queue.empty? and _scn.eos? do offset = _scn.pos matched_token, value = find_token end_offset = _scn.pos # error out if we didn't match anything at all lex_error "Could not match #{_scn.rest[/^(\S+|\s+|.*)/]}" unless matched_token newline = matched_token.name == :RETURN _lxc = @lexing_context _lxc[:start_of_line] = newline _lxc[:offset] = offset _lxc[:end_offset] = end_offset final_token, token_value = munge_token(matched_token, value) # update end position since munging may have moved the end offset _lxc[:end_offset] = _scn.pos unless final_token _scn.skip(SKIPPATTERN) next end _lxc[:after] = final_token.name unless newline if final_token.name == :DQPRE _lxc[:interpolation_stack] << _lxc[:brace_count] elsif final_token.name == :DQPOST _lxc[:interpolation_stack].pop end value = token_value[:value] _expected = @expected if match = @@pairs[value] and final_token.name != :DQUOTE and final_token.name != :SQUOTE _expected << match elsif exp = _expected[-1] and exp == value and final_token.name != :DQUOTE and final_token.name != :SQUOTE _expected.pop end yield [final_token.name, token_value] _prv = @previous_token if _prv namestack(value) if _prv.name == :CLASS and value != LBRACE_CHAR # TODO: Lexer has no business dealing with this - it is semantic if _prv.name == :DEFINE if indefine? msg = "Cannot nest definition #{value} inside #{@indefine}" self.indefine = false raise Puppet::ParseError, msg end @indefine = value end end @previous_token = final_token _scn.skip(SKIPPATTERN) end # Cannot reset @scanner to nil here - it is needed to answer questions about context after # completed parsing. # Seems meaningless to do this. Everything will be gc anyway. #@scanner = nil # This indicates that we're done parsing. yield [false,false] end def match? r @scanner.match?(r) end # Provide some limited access to the scanner, for those # tokens that need it. def_delegator :@scanner, :scan_until # we've encountered the start of a string... # slurp in the rest of the string and return it def slurpstring(terminators,escapes=%w{ \\ $ ' " r n t s }+["\n"],ignore_invalid_escapes=false) # we search for the next quote that isn't preceded by a # backslash; the caret is there to match empty strings last = @scanner.matched str = @scanner.scan_until(/([^\\]|^|[^\\])([\\]{2})*[#{terminators}]/) || lex_error(positioned_message("Unclosed quote after #{format_quote(last)} followed by '#{followed_by}'")) str.gsub!(/\\(.)/m) { ch = $1 if escapes.include? ch case ch when 'r'; "\r" when 'n'; "\n" when 't'; "\t" when 's'; " " when "\n"; '' else ch end else Puppet.warning(positioned_message("Unrecognized escape sequence '\\#{ch}'")) unless ignore_invalid_escapes "\\#{ch}" end } [ str[0..-2],str[-1,1] ] end # Formats given message by appending file, line and position if available. def positioned_message msg result = [msg] result << "in file #{file}" if file result << "at line #{line}:#{pos}" if line result.join(" ") end # Returns "<eof>" if at end of input, else the following 5 characters with \n \r \t escaped def followed_by return "<eof>" if @scanner.eos? result = @scanner.rest[0,5] + "..." result.gsub!("\t", '\t') result.gsub!("\n", '\n') result.gsub!("\r", '\r') result end def format_quote q if q == "'" '"\'"' else "'#{q}'" end end def tokenize_interpolated_string(token_type,preamble='') # Expecting a (possibly empty) stretch of text terminated by end of string ", a variable $, or expression ${ # The length of this part includes the start and terminating characters. value,terminator = slurpstring('"$') # Advanced after '{' if this is in expression ${} interpolation braced = terminator == '$' && @scanner.scan(/\{/) # make offset to end_ofset be the length of the pre expression string including its start and terminating chars lxc = @lexing_context lxc[:end_offset] = @scanner.pos token_queue << [TOKENS[token_type[terminator]],positioned_value(preamble+value)] variable_regex = if Puppet[:allow_variables_with_dashes] TOKENS[:VARIABLE_WITH_DASH].regex else TOKENS[:VARIABLE].regex end if terminator != '$' or braced return token_queue.shift end tmp_offset = @scanner.pos if var_name = @scanner.scan(variable_regex) lxc[:offset] = tmp_offset lxc[:end_offset] = @scanner.pos warn_if_variable_has_hyphen(var_name) # If the varname after ${ is followed by (, it is a function call, and not a variable # reference. # if braced && @scanner.match?(%r{[ \t\r]*\(}) token_queue << [TOKENS[:NAME], positioned_value(var_name)] else token_queue << [TOKENS[:VARIABLE],positioned_value(var_name)] end lxc[:offset] = @scanner.pos tokenize_interpolated_string(DQ_continuation_token_types) else tokenize_interpolated_string(token_type, replace_false_start_with_text(terminator)) end end def replace_false_start_with_text(appendix) last_token = token_queue.pop value = last_token.last if value.is_a? Hash value[:value] + appendix else value + appendix end end # just parse a string, not a whole file def string=(string, path='') @scanner = StringScanner.new(string.freeze) @locator = Puppet::Pops::Parser::Locator.locator(string, path) end def warn_if_variable_has_hyphen(var_name) if var_name.include?('-') Puppet.deprecation_warning("Using `-` in variable names is deprecated at #{file || '<string>'}:#{line}. See http://links.puppetlabs.com/puppet-hyphenated-variable-deprecation") end end # Returns the line number (starting from 1) for the current position # in the scanned text (at the end of the last produced, but not necessarily # consumed. # def line return 1 unless @lexing_context && locator locator.line_for_offset(@lexing_context[:end_offset]) end end
jorgemancheno/boxen
vendor/bundle/ruby/2.0.0/gems/puppet-3.6.1/lib/puppet/pops/parser/lexer.rb
Ruby
mit
22,497
/* * Planck.js v0.3.0-rc.1 * * Copyright (c) 2016-2018 Ali Shakiba http://shakiba.me/planck.js * Copyright (c) 2006-2013 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ /* * Stage.js * * @copyright 2017 Ali Shakiba http://shakiba.me/stage.js * @license The MIT License */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.planck=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var planck = require("../lib/"); var Stage = require("stage-js/platform/web"); module.exports = planck; planck.testbed = function(opts, callback) { if (typeof opts === "function") { callback = opts; opts = null; } Stage(function(stage, canvas) { stage.on(Stage.Mouse.START, function() { window.focus(); document.activeElement && document.activeElement.blur(); canvas.focus(); }); stage.MAX_ELAPSE = 1e3 / 30; var Vec2 = planck.Vec2; var testbed = {}; var paused = false; stage.on("resume", function() { paused = false; testbed._resume && testbed._resume(); }); stage.on("pause", function() { paused = true; testbed._pause && testbed._pause(); }); testbed.isPaused = function() { return paused; }; testbed.togglePause = function() { paused ? testbed.resume() : testbed.pause(); }; testbed.pause = function() { stage.pause(); }; testbed.resume = function() { stage.resume(); testbed.focus(); }; testbed.focus = function() { document.activeElement && document.activeElement.blur(); canvas.focus(); }; testbed.debug = false; testbed.width = 80; testbed.height = 60; testbed.x = 0; testbed.y = -10; testbed.ratio = 16; testbed.hz = 60; testbed.speed = 1; testbed.activeKeys = {}; testbed.background = "#222222"; var statusText = ""; var statusMap = {}; function statusSet(name, value) { if (typeof value !== "function" && typeof value !== "object") { statusMap[name] = value; } } function statusMerge(obj) { for (var key in obj) { statusSet(key, obj[key]); } } testbed.status = function(a, b) { if (typeof b !== "undefined") { statusSet(a, b); } else if (a && typeof a === "object") { statusMerge(a); } else if (typeof a === "string") { statusText = a; } testbed._status && testbed._status(statusText, statusMap); }; testbed.info = function(text) { testbed._info && testbed._info(text); }; var lastDrawHash = "", drawHash = ""; (function() { var drawingTexture = new Stage.Texture(); stage.append(Stage.image(drawingTexture)); var buffer = []; stage.tick(function() { buffer.length = 0; }, true); drawingTexture.draw = function(ctx) { ctx.save(); ctx.transform(1, 0, 0, -1, -testbed.x, -testbed.y); ctx.lineWidth = 2 / testbed.ratio; ctx.lineCap = "round"; for (var drawing = buffer.shift(); drawing; drawing = buffer.shift()) { drawing(ctx, testbed.ratio); } ctx.restore(); }; testbed.drawPoint = function(p, r, color) { buffer.push(function(ctx, ratio) { ctx.beginPath(); ctx.arc(p.x, p.y, 5 / ratio, 0, 2 * Math.PI); ctx.strokeStyle = color; ctx.stroke(); }); drawHash += "point" + p.x + "," + p.y + "," + r + "," + color; }; testbed.drawCircle = function(p, r, color) { buffer.push(function(ctx) { ctx.beginPath(); ctx.arc(p.x, p.y, r, 0, 2 * Math.PI); ctx.strokeStyle = color; ctx.stroke(); }); drawHash += "circle" + p.x + "," + p.y + "," + r + "," + color; }; testbed.drawSegment = function(a, b, color) { buffer.push(function(ctx) { ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.strokeStyle = color; ctx.stroke(); }); drawHash += "segment" + a.x + "," + a.y + "," + b.x + "," + b.y + "," + color; }; testbed.drawPolygon = function(points, color) { if (!points || !points.length) { return; } buffer.push(function(ctx) { ctx.beginPath(); ctx.moveTo(points[0].x, points[0].y); for (var i = 1; i < points.length; i++) { ctx.lineTo(points[i].x, points[i].y); } ctx.strokeStyle = color; ctx.closePath(); ctx.stroke(); }); drawHash += "segment"; for (var i = 1; i < points.length; i++) { drawHash += points[i].x + "," + points[i].y + ","; } drawHash += color; }; testbed.drawAABB = function(aabb, color) { buffer.push(function(ctx) { ctx.beginPath(); ctx.moveTo(aabb.lowerBound.x, aabb.lowerBound.y); ctx.lineTo(aabb.upperBound.x, aabb.lowerBound.y); ctx.lineTo(aabb.upperBound.x, aabb.upperBound.y); ctx.lineTo(aabb.lowerBound.x, aabb.upperBound.y); ctx.strokeStyle = color; ctx.closePath(); ctx.stroke(); }); drawHash += "aabb"; drawHash += aabb.lowerBound.x + "," + aabb.lowerBound.y + ","; drawHash += aabb.upperBound.x + "," + aabb.upperBound.y + ","; drawHash += color; }; testbed.color = function(r, g, b) { r = r * 256 | 0; g = g * 256 | 0; b = b * 256 | 0; return "rgb(" + r + ", " + g + ", " + b + ")"; }; })(); var world = callback(testbed); var viewer = new Viewer(world, testbed); var lastX = 0, lastY = 0; stage.tick(function(dt, t) { if (lastX !== testbed.x || lastY !== testbed.y) { viewer.offset(-testbed.x, -testbed.y); lastX = testbed.x, lastY = testbed.y; } }); viewer.tick(function(dt, t) { if (typeof testbed.step === "function") { testbed.step(dt, t); } if (targetBody) { testbed.drawSegment(targetBody.getPosition(), mouseMove, "rgba(255,255,255,0.2)"); } if (lastDrawHash !== drawHash) { lastDrawHash = drawHash; stage.touch(); } drawHash = ""; return true; }); stage.background(testbed.background); stage.viewbox(testbed.width, testbed.height); stage.pin("alignX", -.5); stage.pin("alignY", -.5); stage.prepend(viewer); function findBody(point) { var body; var aabb = planck.AABB(point, point); world.queryAABB(aabb, function(fixture) { if (body) { return; } if (!fixture.getBody().isDynamic() || !fixture.testPoint(point)) { return; } body = fixture.getBody(); return true; }); return body; } var mouseGround = world.createBody(); var mouseJoint; var targetBody; var mouseMove = { x: 0, y: 0 }; viewer.attr("spy", true).on(Stage.Mouse.START, function(point) { point = { x: point.x, y: -point.y }; if (targetBody) { return; } var body = findBody(point); if (!body) { return; } if (testbed.mouseForce) { targetBody = body; } else { mouseJoint = planck.MouseJoint({ maxForce: 1e3 }, mouseGround, body, Vec2(point)); world.createJoint(mouseJoint); } }).on(Stage.Mouse.MOVE, function(point) { point = { x: point.x, y: -point.y }; if (mouseJoint) { mouseJoint.setTarget(point); } mouseMove.x = point.x; mouseMove.y = point.y; }).on(Stage.Mouse.END, function(point) { point = { x: point.x, y: -point.y }; if (mouseJoint) { world.destroyJoint(mouseJoint); mouseJoint = null; } if (targetBody) { var force = Vec2.sub(point, targetBody.getPosition()); targetBody.applyForceToCenter(force.mul(testbed.mouseForce), true); targetBody = null; } }).on(Stage.Mouse.CANCEL, function(point) { point = { x: point.x, y: -point.y }; if (mouseJoint) { world.destroyJoint(mouseJoint); mouseJoint = null; } if (targetBody) { targetBody = null; } }); window.addEventListener("keydown", function(e) { switch (e.keyCode) { case "P".charCodeAt(0): testbed.togglePause(); break; } }, false); var downKeys = {}; window.addEventListener("keydown", function(e) { var keyCode = e.keyCode; downKeys[keyCode] = true; updateActiveKeys(keyCode, true); testbed.keydown && testbed.keydown(keyCode, String.fromCharCode(keyCode)); }); window.addEventListener("keyup", function(e) { var keyCode = e.keyCode; downKeys[keyCode] = false; updateActiveKeys(keyCode, false); testbed.keyup && testbed.keyup(keyCode, String.fromCharCode(keyCode)); }); var activeKeys = testbed.activeKeys; function updateActiveKeys(keyCode, down) { var char = String.fromCharCode(keyCode); if (/\w/.test(char)) { activeKeys[char] = down; } activeKeys.right = downKeys[39] || activeKeys["D"]; activeKeys.left = downKeys[37] || activeKeys["A"]; activeKeys.up = downKeys[38] || activeKeys["W"]; activeKeys.down = downKeys[40] || activeKeys["S"]; activeKeys.fire = downKeys[32] || downKeys[13]; } }); }; Viewer._super = Stage; Viewer.prototype = Stage._create(Viewer._super.prototype); function Viewer(world, opts) { Viewer._super.call(this); this.label("Planck"); opts = opts || {}; var options = this._options = {}; this._options.speed = opts.speed || 1; this._options.hz = opts.hz || 60; if (Math.abs(this._options.hz) < 1) { this._options.hz = 1 / this._options.hz; } this._options.ratio = opts.ratio || 16; this._options.lineWidth = 2 / this._options.ratio; this._world = world; var timeStep = 1 / this._options.hz; var elapsedTime = 0; this.tick(function(dt) { dt = dt * .001 * options.speed; elapsedTime += dt; while (elapsedTime > timeStep) { world.step(timeStep); elapsedTime -= timeStep; } this.renderWorld(); return true; }, true); world.on("remove-fixture", function(obj) { obj.ui && obj.ui.remove(); }); world.on("remove-joint", function(obj) { obj.ui && obj.ui.remove(); }); } Viewer.prototype.renderWorld = function(world) { var world = this._world; var viewer = this; for (var b = world.getBodyList(); b; b = b.getNext()) { for (var f = b.getFixtureList(); f; f = f.getNext()) { if (!f.ui) { if (f.render && f.render.stroke) { this._options.strokeStyle = f.render.stroke; } else if (b.render && b.render.stroke) { this._options.strokeStyle = b.render.stroke; } else if (b.isDynamic()) { this._options.strokeStyle = "rgba(255,255,255,0.9)"; } else if (b.isKinematic()) { this._options.strokeStyle = "rgba(255,255,255,0.7)"; } else if (b.isStatic()) { this._options.strokeStyle = "rgba(255,255,255,0.5)"; } if (f.render && f.render.fill) { this._options.fillStyle = f.render.fill; } else if (b.render && b.render.fill) { this._options.fillStyle = b.render.fill; } else { this._options.fillStyle = ""; } var type = f.getType(); var shape = f.getShape(); if (type == "circle") { f.ui = viewer.drawCircle(shape, this._options); } if (type == "edge") { f.ui = viewer.drawEdge(shape, this._options); } if (type == "polygon") { f.ui = viewer.drawPolygon(shape, this._options); } if (type == "chain") { f.ui = viewer.drawChain(shape, this._options); } if (f.ui) { f.ui.appendTo(viewer); } } if (f.ui) { var p = b.getPosition(), r = b.getAngle(); if (f.ui.__lastX !== p.x || f.ui.__lastY !== p.y || f.ui.__lastR !== r) { f.ui.__lastX = p.x; f.ui.__lastY = p.y; f.ui.__lastR = r; f.ui.offset(p.x, -p.y); f.ui.rotate(-r); } } } } for (var j = world.getJointList(); j; j = j.getNext()) { var type = j.getType(); var a = j.getAnchorA(); var b = j.getAnchorB(); if (!j.ui) { this._options.strokeStyle = "rgba(255,255,255,0.2)"; j.ui = viewer.drawJoint(j, this._options); j.ui.pin("handle", .5); if (j.ui) { j.ui.appendTo(viewer); } } if (j.ui) { var cx = (a.x + b.x) * .5; var cy = (-a.y + -b.y) * .5; var dx = a.x - b.x; var dy = -a.y - -b.y; var d = Math.sqrt(dx * dx + dy * dy); j.ui.width(d); j.ui.rotate(Math.atan2(dy, dx)); j.ui.offset(cx, cy); } } }; Viewer.prototype.drawJoint = function(joint, options) { var lw = options.lineWidth; var ratio = options.ratio; var length = 10; var texture = Stage.canvas(function(ctx) { this.size(length + 2 * lw, 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); ctx.moveTo(lw, lw); ctx.lineTo(lw + length, lw); ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture).stretch(); return image; }; Viewer.prototype.drawCircle = function(shape, options) { var lw = options.lineWidth; var ratio = options.ratio; var r = shape.m_radius; var cx = r + lw; var cy = r + lw; var w = r * 2 + lw * 2; var h = r * 2 + lw * 2; var texture = Stage.canvas(function(ctx) { this.size(w, h, ratio); ctx.scale(ratio, ratio); ctx.arc(cx, cy, r, 0, 2 * Math.PI); if (options.fillStyle) { ctx.fillStyle = options.fillStyle; ctx.fill(); } ctx.lineTo(cx, cy); ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture).offset(shape.m_p.x - cx, -shape.m_p.y - cy); var node = Stage.create().append(image); return node; }; Viewer.prototype.drawEdge = function(edge, options) { var lw = options.lineWidth; var ratio = options.ratio; var v1 = edge.m_vertex1; var v2 = edge.m_vertex2; var dx = v2.x - v1.x; var dy = v2.y - v1.y; var length = Math.sqrt(dx * dx + dy * dy); var texture = Stage.canvas(function(ctx) { this.size(length + 2 * lw, 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); ctx.moveTo(lw, lw); ctx.lineTo(lw + length, lw); ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var minX = Math.min(v1.x, v2.x); var minY = Math.min(-v1.y, -v2.y); var image = Stage.image(texture); image.rotate(-Math.atan2(dy, dx)); image.offset(minX - lw, minY - lw); var node = Stage.create().append(image); return node; }; Viewer.prototype.drawPolygon = function(shape, options) { var lw = options.lineWidth; var ratio = options.ratio; var vertices = shape.m_vertices; if (!vertices.length) { return; } var minX = Infinity, minY = Infinity; var maxX = -Infinity, maxY = -Infinity; for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; minX = Math.min(minX, v.x); maxX = Math.max(maxX, v.x); minY = Math.min(minY, -v.y); maxY = Math.max(maxY, -v.y); } var width = maxX - minX; var height = maxY - minY; var texture = Stage.canvas(function(ctx) { this.size(width + 2 * lw, height + 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; var x = v.x - minX + lw; var y = -v.y - minY + lw; if (i == 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); } if (vertices.length > 2) { ctx.closePath(); } if (options.fillStyle) { ctx.fillStyle = options.fillStyle; ctx.fill(); ctx.closePath(); } ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture); image.offset(minX - lw, minY - lw); var node = Stage.create().append(image); return node; }; Viewer.prototype.drawChain = function(shape, options) { var lw = options.lineWidth; var ratio = options.ratio; var vertices = shape.m_vertices; if (!vertices.length) { return; } var minX = Infinity, minY = Infinity; var maxX = -Infinity, maxY = -Infinity; for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; minX = Math.min(minX, v.x); maxX = Math.max(maxX, v.x); minY = Math.min(minY, -v.y); maxY = Math.max(maxY, -v.y); } var width = maxX - minX; var height = maxY - minY; var texture = Stage.canvas(function(ctx) { this.size(width + 2 * lw, height + 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; var x = v.x - minX + lw; var y = -v.y - minY + lw; if (i == 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); } if (vertices.length > 2) {} if (options.fillStyle) { ctx.fillStyle = options.fillStyle; ctx.fill(); ctx.closePath(); } ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture); image.offset(minX - lw, minY - lw); var node = Stage.create().append(image); return node; }; },{"../lib/":27,"stage-js/platform/web":82}],2:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Body; var common = require("./util/common"); var options = require("./util/options"); var Vec2 = require("./common/Vec2"); var Rot = require("./common/Rot"); var Math = require("./common/Math"); var Sweep = require("./common/Sweep"); var Transform = require("./common/Transform"); var Velocity = require("./common/Velocity"); var Position = require("./common/Position"); var Fixture = require("./Fixture"); var Shape = require("./Shape"); var World = require("./World"); var staticBody = Body.STATIC = "static"; var kinematicBody = Body.KINEMATIC = "kinematic"; var dynamicBody = Body.DYNAMIC = "dynamic"; var BodyDef = { type: staticBody, position: Vec2.zero(), angle: 0, linearVelocity: Vec2.zero(), angularVelocity: 0, linearDamping: 0, angularDamping: 0, fixedRotation: false, bullet: false, gravityScale: 1, allowSleep: true, awake: true, active: true, userData: null }; function Body(world, def) { def = options(def, BodyDef); _ASSERT && common.assert(Vec2.isValid(def.position)); _ASSERT && common.assert(Vec2.isValid(def.linearVelocity)); _ASSERT && common.assert(Math.isFinite(def.angle)); _ASSERT && common.assert(Math.isFinite(def.angularVelocity)); _ASSERT && common.assert(Math.isFinite(def.angularDamping) && def.angularDamping >= 0); _ASSERT && common.assert(Math.isFinite(def.linearDamping) && def.linearDamping >= 0); this.m_world = world; this.m_awakeFlag = def.awake; this.m_autoSleepFlag = def.allowSleep; this.m_bulletFlag = def.bullet; this.m_fixedRotationFlag = def.fixedRotation; this.m_activeFlag = def.active; this.m_islandFlag = false; this.m_toiFlag = false; this.m_userData = def.userData; this.m_type = def.type; if (this.m_type == dynamicBody) { this.m_mass = 1; this.m_invMass = 1; } else { this.m_mass = 0; this.m_invMass = 0; } this.m_I = 0; this.m_invI = 0; this.m_xf = Transform.identity(); this.m_xf.p = Vec2.clone(def.position); this.m_xf.q.setAngle(def.angle); this.m_sweep = new Sweep(); this.m_sweep.setTransform(this.m_xf); this.c_velocity = new Velocity(); this.c_position = new Position(); this.m_force = Vec2.zero(); this.m_torque = 0; this.m_linearVelocity = Vec2.clone(def.linearVelocity); this.m_angularVelocity = def.angularVelocity; this.m_linearDamping = def.linearDamping; this.m_angularDamping = def.angularDamping; this.m_gravityScale = def.gravityScale; this.m_sleepTime = 0; this.m_jointList = null; this.m_contactList = null; this.m_fixtureList = null; this.m_prev = null; this.m_next = null; this.m_destroyed = false; } Body.prototype.isWorldLocked = function() { return this.m_world && this.m_world.isLocked() ? true : false; }; Body.prototype.getWorld = function() { return this.m_world; }; Body.prototype.getNext = function() { return this.m_next; }; Body.prototype.setUserData = function(data) { this.m_userData = data; }; Body.prototype.getUserData = function() { return this.m_userData; }; Body.prototype.getFixtureList = function() { return this.m_fixtureList; }; Body.prototype.getJointList = function() { return this.m_jointList; }; Body.prototype.getContactList = function() { return this.m_contactList; }; Body.prototype.isStatic = function() { return this.m_type == staticBody; }; Body.prototype.isDynamic = function() { return this.m_type == dynamicBody; }; Body.prototype.isKinematic = function() { return this.m_type == kinematicBody; }; Body.prototype.setStatic = function() { this.setType(staticBody); return this; }; Body.prototype.setDynamic = function() { this.setType(dynamicBody); return this; }; Body.prototype.setKinematic = function() { this.setType(kinematicBody); return this; }; Body.prototype.getType = function() { return this.m_type; }; Body.prototype.setType = function(type) { _ASSERT && common.assert(type === staticBody || type === kinematicBody || type === dynamicBody); _ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } if (this.m_type == type) { return; } this.m_type = type; this.resetMassData(); if (this.m_type == staticBody) { this.m_linearVelocity.setZero(); this.m_angularVelocity = 0; this.m_sweep.forward(); this.synchronizeFixtures(); } this.setAwake(true); this.m_force.setZero(); this.m_torque = 0; var ce = this.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.m_world.destroyContact(ce0.contact); } this.m_contactList = null; var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { var proxyCount = f.m_proxyCount; for (var i = 0; i < proxyCount; ++i) { broadPhase.touchProxy(f.m_proxies[i].proxyId); } } }; Body.prototype.isBullet = function() { return this.m_bulletFlag; }; Body.prototype.setBullet = function(flag) { this.m_bulletFlag = !!flag; }; Body.prototype.isSleepingAllowed = function() { return this.m_autoSleepFlag; }; Body.prototype.setSleepingAllowed = function(flag) { this.m_autoSleepFlag = !!flag; if (this.m_autoSleepFlag == false) { this.setAwake(true); } }; Body.prototype.isAwake = function() { return this.m_awakeFlag; }; Body.prototype.setAwake = function(flag) { if (flag) { if (this.m_awakeFlag == false) { this.m_awakeFlag = true; this.m_sleepTime = 0; } } else { this.m_awakeFlag = false; this.m_sleepTime = 0; this.m_linearVelocity.setZero(); this.m_angularVelocity = 0; this.m_force.setZero(); this.m_torque = 0; } }; Body.prototype.isActive = function() { return this.m_activeFlag; }; Body.prototype.setActive = function(flag) { _ASSERT && common.assert(this.isWorldLocked() == false); if (flag == this.m_activeFlag) { return; } this.m_activeFlag = !!flag; if (this.m_activeFlag) { var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.createProxies(broadPhase, this.m_xf); } } else { var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.destroyProxies(broadPhase); } var ce = this.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.m_world.destroyContact(ce0.contact); } this.m_contactList = null; } }; Body.prototype.isFixedRotation = function() { return this.m_fixedRotationFlag; }; Body.prototype.setFixedRotation = function(flag) { if (this.m_fixedRotationFlag == flag) { return; } this.m_fixedRotationFlag = !!flag; this.m_angularVelocity = 0; this.resetMassData(); }; Body.prototype.getTransform = function() { return this.m_xf; }; Body.prototype.setTransform = function(position, angle) { _ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } this.m_xf.set(position, angle); this.m_sweep.setTransform(this.m_xf); var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.synchronize(broadPhase, this.m_xf, this.m_xf); } }; Body.prototype.synchronizeTransform = function() { this.m_sweep.getTransform(this.m_xf, 1); }; Body.prototype.synchronizeFixtures = function() { var xf = Transform.identity(); this.m_sweep.getTransform(xf, 0); var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.synchronize(broadPhase, xf, this.m_xf); } }; Body.prototype.advance = function(alpha) { this.m_sweep.advance(alpha); this.m_sweep.c.set(this.m_sweep.c0); this.m_sweep.a = this.m_sweep.a0; this.m_sweep.getTransform(this.m_xf, 1); }; Body.prototype.getPosition = function() { return this.m_xf.p; }; Body.prototype.setPosition = function(p) { this.setTransform(p, this.m_sweep.a); }; Body.prototype.getAngle = function() { return this.m_sweep.a; }; Body.prototype.setAngle = function(angle) { this.setTransform(this.m_xf.p, angle); }; Body.prototype.getWorldCenter = function() { return this.m_sweep.c; }; Body.prototype.getLocalCenter = function() { return this.m_sweep.localCenter; }; Body.prototype.getLinearVelocity = function() { return this.m_linearVelocity; }; Body.prototype.getLinearVelocityFromWorldPoint = function(worldPoint) { var localCenter = Vec2.sub(worldPoint, this.m_sweep.c); return Vec2.add(this.m_linearVelocity, Vec2.cross(this.m_angularVelocity, localCenter)); }; Body.prototype.getLinearVelocityFromLocalPoint = function(localPoint) { return this.getLinearVelocityFromWorldPoint(this.getWorldPoint(localPoint)); }; Body.prototype.setLinearVelocity = function(v) { if (this.m_type == staticBody) { return; } if (Vec2.dot(v, v) > 0) { this.setAwake(true); } this.m_linearVelocity.set(v); }; Body.prototype.getAngularVelocity = function() { return this.m_angularVelocity; }; Body.prototype.setAngularVelocity = function(w) { if (this.m_type == staticBody) { return; } if (w * w > 0) { this.setAwake(true); } this.m_angularVelocity = w; }; Body.prototype.getLinearDamping = function() { return this.m_linearDamping; }; Body.prototype.setLinearDamping = function(linearDamping) { this.m_linearDamping = linearDamping; }; Body.prototype.getAngularDamping = function() { return this.m_angularDamping; }; Body.prototype.setAngularDamping = function(angularDamping) { this.m_angularDamping = angularDamping; }; Body.prototype.getGravityScale = function() { return this.m_gravityScale; }; Body.prototype.setGravityScale = function(scale) { this.m_gravityScale = scale; }; Body.prototype.getMass = function() { return this.m_mass; }; Body.prototype.getInertia = function() { return this.m_I + this.m_mass * Vec2.dot(this.m_sweep.localCenter, this.m_sweep.localCenter); }; function MassData() { this.mass = 0; this.center = Vec2.zero(); this.I = 0; } Body.prototype.getMassData = function(data) { data.mass = this.m_mass; data.I = this.getInertia(); data.center.set(this.m_sweep.localCenter); }; Body.prototype.resetMassData = function() { this.m_mass = 0; this.m_invMass = 0; this.m_I = 0; this.m_invI = 0; this.m_sweep.localCenter.setZero(); if (this.isStatic() || this.isKinematic()) { this.m_sweep.c0.set(this.m_xf.p); this.m_sweep.c.set(this.m_xf.p); this.m_sweep.a0 = this.m_sweep.a; return; } _ASSERT && common.assert(this.isDynamic()); var localCenter = Vec2.zero(); for (var f = this.m_fixtureList; f; f = f.m_next) { if (f.m_density == 0) { continue; } var massData = new MassData(); f.getMassData(massData); this.m_mass += massData.mass; localCenter.addMul(massData.mass, massData.center); this.m_I += massData.I; } if (this.m_mass > 0) { this.m_invMass = 1 / this.m_mass; localCenter.mul(this.m_invMass); } else { this.m_mass = 1; this.m_invMass = 1; } if (this.m_I > 0 && this.m_fixedRotationFlag == false) { this.m_I -= this.m_mass * Vec2.dot(localCenter, localCenter); _ASSERT && common.assert(this.m_I > 0); this.m_invI = 1 / this.m_I; } else { this.m_I = 0; this.m_invI = 0; } var oldCenter = Vec2.clone(this.m_sweep.c); this.m_sweep.setLocalCenter(localCenter, this.m_xf); this.m_linearVelocity.add(Vec2.cross(this.m_angularVelocity, Vec2.sub(this.m_sweep.c, oldCenter))); }; Body.prototype.setMassData = function(massData) { _ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } if (this.m_type != dynamicBody) { return; } this.m_invMass = 0; this.m_I = 0; this.m_invI = 0; this.m_mass = massData.mass; if (this.m_mass <= 0) { this.m_mass = 1; } this.m_invMass = 1 / this.m_mass; if (massData.I > 0 && this.m_fixedRotationFlag == false) { this.m_I = massData.I - this.m_mass * Vec2.dot(massData.center, massData.center); _ASSERT && common.assert(this.m_I > 0); this.m_invI = 1 / this.m_I; } var oldCenter = Vec2.clone(this.m_sweep.c); this.m_sweep.setLocalCenter(massData.center, this.m_xf); this.m_linearVelocity.add(Vec2.cross(this.m_angularVelocity, Vec2.sub(this.m_sweep.c, oldCenter))); }; Body.prototype.applyForce = function(force, point, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_force.add(force); this.m_torque += Vec2.cross(Vec2.sub(point, this.m_sweep.c), force); } }; Body.prototype.applyForceToCenter = function(force, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_force.add(force); } }; Body.prototype.applyTorque = function(torque, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_torque += torque; } }; Body.prototype.applyLinearImpulse = function(impulse, point, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_linearVelocity.addMul(this.m_invMass, impulse); this.m_angularVelocity += this.m_invI * Vec2.cross(Vec2.sub(point, this.m_sweep.c), impulse); } }; Body.prototype.applyAngularImpulse = function(impulse, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_angularVelocity += this.m_invI * impulse; } }; Body.prototype.shouldCollide = function(that) { if (this.m_type != dynamicBody && that.m_type != dynamicBody) { return false; } for (var jn = this.m_jointList; jn; jn = jn.next) { if (jn.other == that) { if (jn.joint.m_collideConnected == false) { return false; } } } return true; }; Body.prototype.createFixture = function(shape, fixdef) { _ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return null; } var fixture = new Fixture(this, shape, fixdef); if (this.m_activeFlag) { var broadPhase = this.m_world.m_broadPhase; fixture.createProxies(broadPhase, this.m_xf); } fixture.m_next = this.m_fixtureList; this.m_fixtureList = fixture; if (fixture.m_density > 0) { this.resetMassData(); } this.m_world.m_newFixture = true; return fixture; }; Body.prototype.destroyFixture = function(fixture) { _ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } _ASSERT && common.assert(fixture.m_body == this); var found = false; if (this.m_fixtureList === fixture) { this.m_fixtureList = fixture.m_next; found = true; } else { var node = this.m_fixtureList; while (node != null) { if (node.m_next === fixture) { node.m_next = fixture.m_next; found = true; break; } node = node.m_next; } } _ASSERT && common.assert(found); var edge = this.m_contactList; while (edge) { var c = edge.contact; edge = edge.next; var fixtureA = c.getFixtureA(); var fixtureB = c.getFixtureB(); if (fixture == fixtureA || fixture == fixtureB) { this.m_world.destroyContact(c); } } if (this.m_activeFlag) { var broadPhase = this.m_world.m_broadPhase; fixture.destroyProxies(broadPhase); } fixture.m_body = null; fixture.m_next = null; this.m_world.publish("remove-fixture", fixture); this.resetMassData(); }; Body.prototype.getWorldPoint = function(localPoint) { return Transform.mulVec2(this.m_xf, localPoint); }; Body.prototype.getWorldVector = function(localVector) { return Rot.mulVec2(this.m_xf.q, localVector); }; Body.prototype.getLocalPoint = function(worldPoint) { return Transform.mulTVec2(this.m_xf, worldPoint); }; Body.prototype.getLocalVector = function(worldVector) { return Rot.mulTVec2(this.m_xf.q, worldVector); }; },{"./Fixture":4,"./Shape":8,"./World":10,"./common/Math":18,"./common/Position":19,"./common/Rot":20,"./common/Sweep":21,"./common/Transform":22,"./common/Vec2":23,"./common/Velocity":25,"./util/common":51,"./util/options":53}],3:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var DEBUG_SOLVER = false; var common = require("./util/common"); var Pool = require("./util/Pool"); var Math = require("./common/Math"); var Vec2 = require("./common/Vec2"); var Transform = require("./common/Transform"); var Mat22 = require("./common/Mat22"); var Rot = require("./common/Rot"); var Settings = require("./Settings"); var Manifold = require("./Manifold"); var Distance = require("./collision/Distance"); module.exports = Contact; function ContactEdge(contact) { this.contact = contact; this.prev = null; this.next = null; this.other = null; } function Contact() { this.m_nodeA = new ContactEdge(this); this.m_nodeB = new ContactEdge(this); this.m_manifold = new Manifold(); this.v_points_cache = [ new VelocityConstraintPoint(), new VelocityConstraintPoint() ]; this.v_points = []; this.v_normal = Vec2.zero(); this.v_normalMass = new Mat22(); this.v_K = new Mat22(); this.p_localPoints_cache = [ Vec2.zero(), Vec2.zero() ]; this.p_localPoints = []; this.p_localNormal = Vec2.zero(); this.p_localPoint = Vec2.zero(); this.p_localCenterA = Vec2.zero(); this.p_localCenterB = Vec2.zero(); } Contact.prototype.init = function(fA, indexA, fB, indexB, evaluateFcn) { this.m_fixtureA = fA; this.m_fixtureB = fB; this.m_indexA = indexA; this.m_indexB = indexB; this.m_evaluateFcn = evaluateFcn; this.m_manifold.init(); this.m_prev = null; this.m_next = null; this.m_toi = 1; this.m_toiCount = 0; this.m_toiFlag = false; this.m_friction = mixFriction(this.m_fixtureA.m_friction, this.m_fixtureB.m_friction); this.m_restitution = mixRestitution(this.m_fixtureA.m_restitution, this.m_fixtureB.m_restitution); this.m_tangentSpeed = 0; this.m_enabledFlag = true; this.m_islandFlag = false; this.m_touchingFlag = false; this.m_filterFlag = false; this.m_bulletHitFlag = false; this.v_points.length = 0; this.v_normal.setZero(); this.v_normalMass.setZero(); this.v_K.setZero(); this.v_pointCount = null; this.v_tangentSpeed = null; this.v_friction = null; this.v_restitution = null; this.v_invMassA = null; this.v_invMassB = null; this.v_invIA = null; this.v_invIB = null; this.p_localPoints.length = 0; this.p_localNormal.setZero(); this.p_localPoint.setZero(); this.p_localCenterA.setZero(); this.p_localCenterB.setZero(); this.p_type = null; this.p_radiusA = null; this.p_radiusB = null; this.p_pointCount = null; this.p_invMassA = null; this.p_invMassB = null; this.p_invIA = null; this.p_invIB = null; }; Contact.prototype.initConstraint = function(step) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var shapeA = fixtureA.getShape(); var shapeB = fixtureB.getShape(); var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var manifold = this.m_manifold; var pointCount = manifold.pointCount; _ASSERT && common.assert(pointCount > 0); this.v_invMassA = bodyA.m_invMass; this.v_invMassB = bodyB.m_invMass; this.v_invIA = bodyA.m_invI; this.v_invIB = bodyB.m_invI; this.v_friction = this.m_friction; this.v_restitution = this.m_restitution; this.v_tangentSpeed = this.m_tangentSpeed; this.v_pointCount = pointCount; this.v_K.setZero(); this.v_normalMass.setZero(); this.p_invMassA = bodyA.m_invMass; this.p_invMassB = bodyB.m_invMass; this.p_invIA = bodyA.m_invI; this.p_invIB = bodyB.m_invI; this.p_localCenterA.setVec2(bodyA.m_sweep.localCenter); this.p_localCenterB.setVec2(bodyB.m_sweep.localCenter); this.p_radiusA = shapeA.m_radius; this.p_radiusB = shapeB.m_radius; this.p_type = manifold.type; this.p_localNormal.setVec2(manifold.localNormal); this.p_localPoint.setVec2(manifold.localPoint); this.p_pointCount = pointCount; for (var j = 0; j < pointCount; ++j) { var cp = manifold.points[j]; var vcp = this.v_points[j] = this.v_points_cache[j].init(); if (step.warmStarting) { vcp.normalImpulse = step.dtRatio * cp.normalImpulse; vcp.tangentImpulse = step.dtRatio * cp.tangentImpulse; } else { vcp.normalImpulse = 0; vcp.tangentImpulse = 0; } vcp.rA.setZero(); vcp.rB.setZero(); vcp.normalMass = 0; vcp.tangentMass = 0; vcp.velocityBias = 0; this.p_localPoints[j] = this.p_localPoints_cache[j].setVec2(cp.localPoint); } }; Contact.prototype.getManifold = function() { return this.m_manifold; }; Contact.prototype.getWorldManifold = function(worldManifold) { var bodyA = this.m_fixtureA.getBody(); var bodyB = this.m_fixtureB.getBody(); var shapeA = this.m_fixtureA.getShape(); var shapeB = this.m_fixtureB.getShape(); var manifold = this.m_manifold.getWorldManifold(worldManifold, bodyA.getTransform(), shapeA.m_radius, bodyB.getTransform(), shapeB.m_radius); return manifold; }; Contact.prototype.setEnabled = function(flag) { this.m_enabledFlag = !!flag; }; Contact.prototype.isEnabled = function() { return this.m_enabledFlag; }; Contact.prototype.isTouching = function() { return this.m_touchingFlag; }; Contact.prototype.getNext = function() { return this.m_next; }; Contact.prototype.getFixtureA = function() { return this.m_fixtureA; }; Contact.prototype.getFixtureB = function() { return this.m_fixtureB; }; Contact.prototype.getChildIndexA = function() { return this.m_indexA; }; Contact.prototype.getChildIndexB = function() { return this.m_indexB; }; Contact.prototype.flagForFiltering = function() { this.m_filterFlag = true; }; Contact.prototype.setFriction = function(friction) { this.m_friction = friction; }; Contact.prototype.getFriction = function() { return this.m_friction; }; Contact.prototype.resetFriction = function() { this.m_friction = mixFriction(this.m_fixtureA.m_friction, this.m_fixtureB.m_friction); }; Contact.prototype.setRestitution = function(restitution) { this.m_restitution = restitution; }; Contact.prototype.getRestitution = function() { return this.m_restitution; }; Contact.prototype.resetRestitution = function() { this.m_restitution = mixRestitution(this.m_fixtureA.m_restitution, this.m_fixtureB.m_restitution); }; Contact.prototype.setTangentSpeed = function(speed) { this.m_tangentSpeed = speed; }; Contact.prototype.getTangentSpeed = function() { return this.m_tangentSpeed; }; Contact.prototype.evaluate = function(manifold, xfA, xfB) { this.m_evaluateFcn(manifold, xfA, this.m_fixtureA, this.m_indexA, xfB, this.m_fixtureB, this.m_indexB); }; var cup_manifold = new Manifold(); Contact.prototype.update = function(listener) { this.m_enabledFlag = true; var touching = false; var wasTouching = this.m_touchingFlag; var sensorA = this.m_fixtureA.isSensor(); var sensorB = this.m_fixtureB.isSensor(); var sensor = sensorA || sensorB; var bodyA = this.m_fixtureA.getBody(); var bodyB = this.m_fixtureB.getBody(); var xfA = bodyA.getTransform(); var xfB = bodyB.getTransform(); if (sensor) { var shapeA = this.m_fixtureA.getShape(); var shapeB = this.m_fixtureB.getShape(); touching = Distance.testOverlap(shapeA, this.m_indexA, shapeB, this.m_indexB, xfA, xfB); this.m_manifold.pointCount = 0; } else { var oldManifold = this.m_manifold; this.m_manifold = cup_manifold.init(); cup_manifold = oldManifold; this.evaluate(this.m_manifold, xfA, xfB); touching = this.m_manifold.pointCount > 0; for (var i = 0; i < this.m_manifold.pointCount; ++i) { var nmp = this.m_manifold.points[i]; nmp.normalImpulse = 0; nmp.tangentImpulse = 0; for (var j = 0; j < oldManifold.pointCount; ++j) { var omp = oldManifold.points[j]; if (omp.id.key == nmp.id.key) { nmp.normalImpulse = omp.normalImpulse; nmp.tangentImpulse = omp.tangentImpulse; break; } } } if (touching !== wasTouching) { bodyA.setAwake(true); bodyB.setAwake(true); } } this.m_touchingFlag = touching; if (!wasTouching && touching && listener) { listener.beginContact(this); } if (wasTouching && !touching && listener) { listener.endContact(this); } if (!sensor && touching && listener) { listener.preSolve(this, oldManifold); } }; Contact.prototype.solvePositionConstraint = function(step) { return this._solvePositionConstraint(step, false); }; Contact.prototype.solvePositionConstraintTOI = function(step, toiA, toiB) { return this._solvePositionConstraint(step, true, toiA, toiB); }; var spc_localCenterA = Vec2.zero(); var spc_localCenterB = Vec2.zero(); var spc_cA = Vec2.zero(); var spc_cB = Vec2.zero(); var spc_xfA = Transform.identity(); var spc_xfB = Transform.identity(); var spc_t1 = Vec2.zero(); var spc_t2 = Vec2.zero(); var spc_normal = Vec2.zero(); var spc_point = Vec2.zero(); var spc_pointA = Vec2.zero(); var spc_pointB = Vec2.zero(); var spc_planePoint = Vec2.zero(); var spc_clipPoint = Vec2.zero(); var spc_rA = Vec2.zero(); var spc_rB = Vec2.zero(); var spc_P = Vec2.zero(); Contact.prototype._solvePositionConstraint = function(step, toi, toiA, toiB) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var velocityA = bodyA.c_velocity; var velocityB = bodyB.c_velocity; var positionA = bodyA.c_position; var positionB = bodyB.c_position; var localCenterA = spc_localCenterA.setVec2(this.p_localCenterA); var localCenterB = spc_localCenterB.setVec2(this.p_localCenterB); var mA = 0; var iA = 0; if (!toi || (bodyA === toiA || bodyA === toiB)) { mA = this.p_invMassA; iA = this.p_invIA; } var mB = 0; var iB = 0; if (!toi || (bodyB === toiA || bodyB === toiB)) { mB = this.p_invMassB; iB = this.p_invIB; } var cA = spc_cA.setVec2(positionA.c); var aA = positionA.a; var cB = spc_cB.setVec2(positionB.c); var aB = positionB.a; var minSeparation = 0; for (var j = 0; j < this.p_pointCount; ++j) { var xfA = spc_xfA.setIdentity(); var xfB = spc_xfB.setIdentity(); xfA.q.set(aA); xfB.q.set(aB); xfA.p.setVec2(Vec2.sub_(cA, Rot.mulVec2_(xfA.q, localCenterA, spc_t1), spc_t2)); xfB.p.setVec2(Vec2.sub_(cB, Rot.mulVec2_(xfB.q, localCenterB, spc_t1), spc_t2)); var normal, point, separation; switch (this.p_type) { case Manifold.e_circles: var pointA = Transform.mulVec2_(xfA, this.p_localPoint, spc_pointA); var pointB = Transform.mulVec2_(xfB, this.p_localPoints[0], spc_pointB); normal = Vec2.sub_(pointB, pointA, spc_normal); normal.normalize(); point = Vec2.combine_(.5, pointA, .5, pointB, spc_point); separation = Vec2.dot(Vec2.sub(pointB, pointA), normal) - this.p_radiusA - this.p_radiusB; break; case Manifold.e_faceA: normal = Rot.mulVec2_(xfA.q, this.p_localNormal, spc_normal); var planePoint = Transform.mulVec2_(xfA, this.p_localPoint, spc_planePoint); var clipPoint = Transform.mulVec2_(xfB, this.p_localPoints[j], spc_clipPoint); separation = Vec2.dot(Vec2.sub_(clipPoint, planePoint, spc_t1), normal) - this.p_radiusA - this.p_radiusB; point = spc_point.setVec2(clipPoint); break; case Manifold.e_faceB: normal = Rot.mulVec2_(xfB.q, this.p_localNormal, spc_normal); var planePoint = Transform.mulVec2_(xfB, this.p_localPoint, spc_planePoint); var clipPoint = Transform.mulVec2_(xfA, this.p_localPoints[j], spc_clipPoint); separation = Vec2.dot(Vec2.sub_(clipPoint, planePoint, spc_t1), normal) - this.p_radiusA - this.p_radiusB; point = spc_point.setVec2(clipPoint); normal.mul(-1); break; } var rA = Vec2.sub_(point, cA, spc_rA); var rB = Vec2.sub_(point, cB, spc_rB); minSeparation = Math.min(minSeparation, separation); var baumgarte = toi ? Settings.toiBaugarte : Settings.baumgarte; var linearSlop = Settings.linearSlop; var maxLinearCorrection = Settings.maxLinearCorrection; var C = Math.clamp(baumgarte * (separation + linearSlop), -maxLinearCorrection, 0); var rnA = Vec2.crossVec2Vec2(rA, normal); var rnB = Vec2.crossVec2Vec2(rB, normal); var K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; var impulse = K > 0 ? -C / K : 0; var P = Vec2.mulNumVec2_(impulse, normal, spc_P); cA.subMul(mA, P); aA -= iA * Vec2.crossVec2Vec2(rA, P); cB.addMul(mB, P); aB += iB * Vec2.crossVec2Vec2(rB, P); } positionA.c.setVec2(cA); positionA.a = aA; positionB.c.setVec2(cB); positionB.a = aB; return minSeparation; }; function VelocityConstraintPoint() { this.rA = Vec2.zero(); this.rB = Vec2.zero(); this.normalImpulse = 0; this.tangentImpulse = 0; this.normalMass = 0; this.tangentMass = 0; this.velocityBias = 0; } VelocityConstraintPoint.prototype.init = function() { this.rA.setZero(); this.rB.setZero(); this.normalImpulse = 0; this.tangentImpulse = 0; this.normalMass = 0; this.tangentMass = 0; this.velocityBias = 0; return this; }; var ivc_localCenterA = Vec2.zero(); var ivc_localCenterB = Vec2.zero(); var ivc_normal = Vec2.zero(); var ivc_cA = Vec2.zero(); var ivc_cB = Vec2.zero(); var ivc_vA = Vec2.zero(); var ivc_vB = Vec2.zero(); var ivc_t1 = Vec2.zero(); var ivc_t2 = Vec2.zero(); var ivc_xfA = Transform.identity(); var ivc_xfB = Transform.identity(); Contact.prototype.initVelocityConstraint = function(step) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var velocityA = bodyA.c_velocity; var velocityB = bodyB.c_velocity; var positionA = bodyA.c_position; var positionB = bodyB.c_position; var radiusA = this.p_radiusA; var radiusB = this.p_radiusB; var manifold = this.m_manifold; var mA = this.v_invMassA; var mB = this.v_invMassB; var iA = this.v_invIA; var iB = this.v_invIB; var localCenterA = ivc_localCenterA.setVec2(this.p_localCenterA); var localCenterB = ivc_localCenterB.setVec2(this.p_localCenterB); var cA = ivc_cA.setVec2(positionA.c); var aA = positionA.a; var vA = ivc_vA.setVec2(velocityA.v); var wA = velocityA.w; var cB = ivc_cB.set(positionB.c); var aB = positionB.a; var vB = ivc_vB.set(velocityB.v); var wB = velocityB.w; _ASSERT && common.assert(manifold.pointCount > 0); var xfA = ivc_xfA.setIdentity(); var xfB = ivc_xfB.setIdentity(); xfA.q.set(aA); xfB.q.set(aB); xfA.p.setCombine(1, cA, -1, Rot.mulVec2(xfA.q, localCenterA)); xfB.p.setCombine(1, cB, -1, Rot.mulVec2(xfB.q, localCenterB)); var worldManifold = manifold.getWorldManifold(null, xfA, radiusA, xfB, radiusB); this.v_normal.set(worldManifold.normal); for (var j = 0; j < this.v_pointCount; ++j) { var vcp = this.v_points[j]; vcp.rA.setCombine(1, worldManifold.points[j], -1, cA); vcp.rB.setCombine(1, worldManifold.points[j], -1, cB); var rnA = Vec2.crossVec2Vec2(vcp.rA, this.v_normal); var rnB = Vec2.crossVec2Vec2(vcp.rB, this.v_normal); var kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; vcp.normalMass = kNormal > 0 ? 1 / kNormal : 0; var tangent = Vec2.crossVec2Num_(this.v_normal, 1, ivc_normal); var rtA = Vec2.crossVec2Vec2(vcp.rA, tangent); var rtB = Vec2.crossVec2Vec2(vcp.rB, tangent); var kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; vcp.tangentMass = kTangent > 0 ? 1 / kTangent : 0; vcp.velocityBias = 0; var vRel = Vec2.dot(this.v_normal, vB) + Vec2.dot(this.v_normal, Vec2.crossNumVec2_(wB, vcp.rB, ivc_t1)) - Vec2.dot(this.v_normal, vA) - Vec2.dot(this.v_normal, Vec2.crossNumVec2_(wA, vcp.rA, ivc_t2)); if (vRel < -Settings.velocityThreshold) { vcp.velocityBias = -this.v_restitution * vRel; } } if (this.v_pointCount === 2 && step.blockSolve) { var vcp1 = this.v_points[0]; var vcp2 = this.v_points[1]; var rn1A = Vec2.crossVec2Vec2(vcp1.rA, this.v_normal); var rn1B = Vec2.crossVec2Vec2(vcp1.rB, this.v_normal); var rn2A = Vec2.crossVec2Vec2(vcp2.rA, this.v_normal); var rn2B = Vec2.crossVec2Vec2(vcp2.rB, this.v_normal); var k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B; var k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B; var k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B; var k_maxConditionNumber = 1e3; if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) { this.v_K.ex.set(k11, k12); this.v_K.ey.set(k12, k22); this.v_normalMass.set(this.v_K.getInverse()); } else { this.v_pointCount = 1; } } positionA.c.set(cA); positionA.a = aA; velocityA.v.set(vA); velocityA.w = wA; positionB.c.set(cB); positionB.a = aB; velocityB.v.set(vB); velocityB.w = wB; }; var wsc_vA = Vec2.zero(); var wsc_vB = Vec2.zero(); var wsc_normal = Vec2.zero(); var wsc_P = Vec2.zero(); Contact.prototype.warmStartConstraint = function(step) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var velocityA = bodyA.c_velocity; var velocityB = bodyB.c_velocity; var positionA = bodyA.c_position; var positionB = bodyB.c_position; var mA = this.v_invMassA; var iA = this.v_invIA; var mB = this.v_invMassB; var iB = this.v_invIB; var vA = wsc_vA.set(velocityA.v); var wA = velocityA.w; var vB = wsc_vB.set(velocityB.v); var wB = velocityB.w; var normal = this.v_normal; var tangent = Vec2.crossVec2Num_(normal, 1, wsc_normal); for (var j = 0; j < this.v_pointCount; ++j) { var vcp = this.v_points[j]; var P = wsc_P.setCombine(vcp.normalImpulse, normal, vcp.tangentImpulse, tangent); wA -= iA * Vec2.crossVec2Vec2(vcp.rA, P); vA.subMul(mA, P); wB += iB * Vec2.crossVec2Vec2(vcp.rB, P); vB.addMul(mB, P); } velocityA.v.set(vA); velocityA.w = wA; velocityB.v.set(vB); velocityB.w = wB; }; Contact.prototype.storeConstraintImpulses = function(step) { var manifold = this.m_manifold; for (var j = 0; j < this.v_pointCount; ++j) { manifold.points[j].normalImpulse = this.v_points[j].normalImpulse; manifold.points[j].tangentImpulse = this.v_points[j].tangentImpulse; } }; var svc_vA = Vec2.zero(); var svc_vB = Vec2.zero(); var svc_dv = Vec2.zero(); var svc_P = Vec2.zero(); var svc_tangent = Vec2.zero(); var svc_a = Vec2.zero(); var svc_b = Vec2.zero(); var svc_d = Vec2.zero(); var svc_x = Vec2.zero(); var svc_dv1 = Vec2.zero(); var svc_dv2 = Vec2.zero(); var svc_P1 = Vec2.zero(); var svc_P2 = Vec2.zero(); var svc_t1 = Vec2.zero(); var svc_t2 = Vec2.zero(); Contact.prototype.solveVelocityConstraint = function(step) { var bodyA = this.m_fixtureA.m_body; var bodyB = this.m_fixtureB.m_body; var velocityA = bodyA.c_velocity; var positionA = bodyA.c_position; var velocityB = bodyB.c_velocity; var positionB = bodyB.c_position; var mA = this.v_invMassA; var iA = this.v_invIA; var mB = this.v_invMassB; var iB = this.v_invIB; var vA = svc_vA.setVec2(velocityA.v); var wA = velocityA.w; var vB = svc_vB.setVec2(velocityB.v); var wB = velocityB.w; var normal = this.v_normal; var tangent = Vec2.crossVec2Num_(normal, 1, svc_tangent); var friction = this.v_friction; _ASSERT && common.assert(this.v_pointCount === 1 || this.v_pointCount === 2); for (var j = 0; j < this.v_pointCount; ++j) { var vcp = this.v_points[j]; var dv = svc_dv.setZero(); dv.addCombine(1, vB, 1, Vec2.crossNumVec2_(wB, vcp.rB, svc_t1)); dv.subCombine(1, vA, 1, Vec2.crossNumVec2_(wA, vcp.rA, svc_t1)); var vt = Vec2.dot(dv, tangent) - this.v_tangentSpeed; var lambda = vcp.tangentMass * -vt; var maxFriction = friction * vcp.normalImpulse; var newImpulse = Math.clamp(vcp.tangentImpulse + lambda, -maxFriction, maxFriction); lambda = newImpulse - vcp.tangentImpulse; vcp.tangentImpulse = newImpulse; var P = Vec2.mulNumVec2_(lambda, tangent, svc_P); vA.subMul(mA, P); wA -= iA * Vec2.crossVec2Vec2(vcp.rA, P); vB.addMul(mB, P); wB += iB * Vec2.crossVec2Vec2(vcp.rB, P); } if (this.v_pointCount == 1 || step.blockSolve == false) { for (var i = 0; i < this.v_pointCount; ++i) { var vcp = this.v_points[i]; var dv = svc_dv.setZero(); dv.addCombine(1, vB, 1, Vec2.crossNumVec2_(wB, vcp.rB, svc_t1)); dv.subCombine(1, vA, 1, Vec2.crossNumVec2_(wA, vcp.rA, svc_t1)); var vn = Vec2.dot(dv, normal); var lambda = -vcp.normalMass * (vn - vcp.velocityBias); var newImpulse = Math.max(vcp.normalImpulse + lambda, 0); lambda = newImpulse - vcp.normalImpulse; vcp.normalImpulse = newImpulse; var P = Vec2.mulNumVec2_(lambda, normal, svc_P); vA.subMul(mA, P); wA -= iA * Vec2.crossVec2Vec2(vcp.rA, P); vB.addMul(mB, P); wB += iB * Vec2.crossVec2Vec2(vcp.rB, P); } } else { var vcp1 = this.v_points[0]; var vcp2 = this.v_points[1]; var a = svc_a.set(vcp1.normalImpulse, vcp2.normalImpulse); _ASSERT && common.assert(a.x >= 0 && a.y >= 0); var dv1 = svc_dv1.setZero().add(vB).add(Vec2.crossNumVec2_(wB, vcp1.rB, svc_t1)).sub(vA).sub(Vec2.crossNumVec2_(wA, vcp1.rA, svc_t2)); var dv2 = svc_dv2.setZero().add(vB).add(Vec2.crossNumVec2_(wB, vcp2.rB, svc_t1)).sub(vA).sub(Vec2.crossNumVec2_(wA, vcp2.rA, svc_t2)); var vn1 = Vec2.dot(dv1, normal); var vn2 = Vec2.dot(dv2, normal); var b = svc_b.set(vn1 - vcp1.velocityBias, vn2 - vcp2.velocityBias); b.sub(Mat22.mulVec2_(this.v_K, a, svc_t1)); var k_errorTol = .001; for (;;) { var x = Mat22.mulVec2_(this.v_normalMass, b, svc_x).neg(); if (x.x >= 0 && x.y >= 0) { var d = Vec2.sub_(x, a, svc_d); var P1 = Vec2.mulNumVec2_(d.x, normal, svc_P1); var P2 = Vec2.mulNumVec2_(d.y, normal, svc_P2); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.crossVec2Vec2(vcp1.rA, P1) + Vec2.crossVec2Vec2(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.crossVec2Vec2(vcp1.rB, P1) + Vec2.crossVec2Vec2(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { dv1 = vB + Vec2.cross(wB, vcp1.rB) - vA - Vec2.cross(wA, vcp1.rA); dv2 = vB + Vec2.cross(wB, vcp2.rB) - vA - Vec2.cross(wA, vcp2.rA); vn1 = Vec2.dot(dv1, normal); vn2 = Vec2.dot(dv2, normal); _ASSERT && common.assert(Math.abs(vn1 - vcp1.velocityBias) < k_errorTol); _ASSERT && common.assert(Math.abs(vn2 - vcp2.velocityBias) < k_errorTol); } break; } x.x = -vcp1.normalMass * b.x; x.y = 0; vn1 = 0; vn2 = this.v_K.ex.y * x.x + b.y; if (x.x >= 0 && vn2 >= 0) { var d = Vec2.sub_(x, a, svc_d); var P1 = Vec2.mulNumVec2_(d.x, normal, svc_P1); var P2 = Vec2.mulNumVec2_(d.y, normal, svc_P2); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.crossVec2Vec2(vcp1.rA, P1) + Vec2.crossVec2Vec2(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.crossVec2Vec2(vcp1.rB, P1) + Vec2.crossVec2Vec2(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { var dv1B = Vec2.add(vB, Vec2.cross(wB, vcp1.rB)); var dv1A = Vec2.add(vA, Vec2.cross(wA, vcp1.rA)); var dv1 = Vec2.sub(dv1B, dv1A); vn1 = Vec2.dot(dv1, normal); _ASSERT && common.assert(Math.abs(vn1 - vcp1.velocityBias) < k_errorTol); } break; } x.x = 0; x.y = -vcp2.normalMass * b.y; vn1 = this.v_K.ey.x * x.y + b.x; vn2 = 0; if (x.y >= 0 && vn1 >= 0) { var d = Vec2.sub_(x, a, svc_d); var P1 = Vec2.mulNumVec2_(d.x, normal, svc_P1); var P2 = Vec2.mulNumVec2_(d.y, normal, svc_P2); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.crossVec2Vec2(vcp1.rA, P1) + Vec2.crossVec2Vec2(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.crossVec2Vec2(vcp1.rB, P1) + Vec2.crossVec2Vec2(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { var dv2B = Vec2.add(vB, Vec2.cross(wB, vcp2.rB)); var dv2A = Vec2.add(vA, Vec2.cross(wA, vcp2.rA)); var dv1 = Vec2.sub(dv2B, dv2A); vn2 = Vec2.dot(dv2, normal); _ASSERT && common.assert(Math.abs(vn2 - vcp2.velocityBias) < k_errorTol); } break; } x.x = 0; x.y = 0; vn1 = b.x; vn2 = b.y; if (vn1 >= 0 && vn2 >= 0) { var d = Vec2.sub_(x, a, svc_d); var P1 = Vec2.mulNumVec2_(d.x, normal, svc_P1); var P2 = Vec2.mulNumVec2_(d.y, normal, svc_P2); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.crossVec2Vec2(vcp1.rA, P1) + Vec2.crossVec2Vec2(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.crossVec2Vec2(vcp1.rB, P1) + Vec2.crossVec2Vec2(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; break; } break; } } velocityA.v.set(vA); velocityA.w = wA; velocityB.v.set(vB); velocityB.w = wB; }; function mixFriction(friction1, friction2) { return Math.sqrt(friction1 * friction2); } function mixRestitution(restitution1, restitution2) { return restitution1 > restitution2 ? restitution1 : restitution2; } var s_registers = []; var contactPool = new Pool({ create: function() { return new Contact(); } }); Contact.addType = function(type1, type2, callback) { s_registers[type1] = s_registers[type1] || {}; s_registers[type1][type2] = callback; }; Contact.create = function(fixtureA, indexA, fixtureB, indexB) { var typeA = fixtureA.getType(); var typeB = fixtureB.getType(); var contact, evaluateFcn; if (evaluateFcn = s_registers[typeA] && s_registers[typeA][typeB]) { contact = contactPool.allocate(); contact.init(fixtureA, indexA, fixtureB, indexB, evaluateFcn); } else if (evaluateFcn = s_registers[typeB] && s_registers[typeB][typeA]) { contact = contactPool.allocate(); contact.init(fixtureB, indexB, fixtureA, indexA, evaluateFcn); } else { return null; } fixtureA = contact.getFixtureA(); fixtureB = contact.getFixtureB(); indexA = contact.getChildIndexA(); indexB = contact.getChildIndexB(); var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); contact.m_nodeA.contact = contact; contact.m_nodeA.other = bodyB; contact.m_nodeA.prev = null; contact.m_nodeA.next = bodyA.m_contactList; if (bodyA.m_contactList != null) { bodyA.m_contactList.prev = contact.m_nodeA; } bodyA.m_contactList = contact.m_nodeA; contact.m_nodeB.contact = contact; contact.m_nodeB.other = bodyA; contact.m_nodeB.prev = null; contact.m_nodeB.next = bodyB.m_contactList; if (bodyB.m_contactList != null) { bodyB.m_contactList.prev = contact.m_nodeB; } bodyB.m_contactList = contact.m_nodeB; if (!fixtureA.isSensor() && !fixtureB.isSensor()) { bodyA.setAwake(true); bodyB.setAwake(true); } return contact; }; Contact.destroy = function(contact, listener) { var fixtureA = contact.m_fixtureA; var fixtureB = contact.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); if (contact.isTouching()) { listener.endContact(contact); } if (contact.m_nodeA.prev) { contact.m_nodeA.prev.next = contact.m_nodeA.next; } if (contact.m_nodeA.next) { contact.m_nodeA.next.prev = contact.m_nodeA.prev; } if (contact.m_nodeA === bodyA.m_contactList) { bodyA.m_contactList = contact.m_nodeA.next; } if (contact.m_nodeB.prev) { contact.m_nodeB.prev.next = contact.m_nodeB.next; } if (contact.m_nodeB.next) { contact.m_nodeB.next.prev = contact.m_nodeB.prev; } if (contact.m_nodeB === bodyB.m_contactList) { bodyB.m_contactList = contact.m_nodeB.next; } if (contact.m_manifold.pointCount > 0 && !fixtureA.isSensor() && !fixtureB.isSensor()) { bodyA.setAwake(true); bodyB.setAwake(true); } var typeA = fixtureA.getType(); var typeB = fixtureB.getType(); var destroyFcn = s_registers[typeA][typeB].destroyFcn; if (typeof destroyFcn === "function") { destroyFcn(contact); } contactPool.release(contact); }; },{"./Manifold":6,"./Settings":7,"./collision/Distance":13,"./common/Mat22":16,"./common/Math":18,"./common/Rot":20,"./common/Transform":22,"./common/Vec2":23,"./util/Pool":49,"./util/common":51}],4:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Fixture; var common = require("./util/common"); var options = require("./util/options"); var Math = require("./common/Math"); var Vec2 = require("./common/Vec2"); var AABB = require("./collision/AABB"); var FixtureDef = { userData: null, friction: .2, restitution: 0, density: 0, isSensor: false, filterGroupIndex: 0, filterCategoryBits: 1, filterMaskBits: 65535 }; function FixtureProxy(fixture, childIndex) { this.aabb = new AABB(); this.fixture = fixture; this.childIndex = childIndex; this.proxyId; } function Fixture(body, shape, def) { if (shape.shape) { def = shape; shape = shape.shape; } else if (typeof def === "number") { def = { density: def }; } def = options(def, FixtureDef); this.m_body = body; this.m_friction = def.friction; this.m_restitution = def.restitution; this.m_density = def.density; this.m_isSensor = def.isSensor; this.m_filterGroupIndex = def.filterGroupIndex; this.m_filterCategoryBits = def.filterCategoryBits; this.m_filterMaskBits = def.filterMaskBits; this.m_shape = shape; this.m_next = null; this.m_proxies = []; this.m_proxyCount = 0; var childCount = this.m_shape.getChildCount(); for (var i = 0; i < childCount; ++i) { this.m_proxies[i] = new FixtureProxy(this, i); } this.m_userData = def.userData; } Fixture.prototype.getType = function() { return this.m_shape.getType(); }; Fixture.prototype.getShape = function() { return this.m_shape; }; Fixture.prototype.isSensor = function() { return this.m_isSensor; }; Fixture.prototype.setSensor = function(sensor) { if (sensor != this.m_isSensor) { this.m_body.setAwake(true); this.m_isSensor = sensor; } }; Fixture.prototype.getUserData = function() { return this.m_userData; }; Fixture.prototype.setUserData = function(data) { this.m_userData = data; }; Fixture.prototype.getBody = function() { return this.m_body; }; Fixture.prototype.getNext = function() { return this.m_next; }; Fixture.prototype.getDensity = function() { return this.m_density; }; Fixture.prototype.setDensity = function(density) { _ASSERT && common.assert(Math.isFinite(density) && density >= 0); this.m_density = density; }; Fixture.prototype.getFriction = function() { return this.m_friction; }; Fixture.prototype.setFriction = function(friction) { this.m_friction = friction; }; Fixture.prototype.getRestitution = function() { return this.m_restitution; }; Fixture.prototype.setRestitution = function(restitution) { this.m_restitution = restitution; }; Fixture.prototype.testPoint = function(p) { return this.m_shape.testPoint(this.m_body.getTransform(), p); }; Fixture.prototype.rayCast = function(output, input, childIndex) { return this.m_shape.rayCast(output, input, this.m_body.getTransform(), childIndex); }; Fixture.prototype.getMassData = function(massData) { this.m_shape.computeMass(massData, this.m_density); }; Fixture.prototype.getAABB = function(childIndex) { _ASSERT && common.assert(0 <= childIndex && childIndex < this.m_proxyCount); return this.m_proxies[childIndex].aabb; }; Fixture.prototype.createProxies = function(broadPhase, xf) { _ASSERT && common.assert(this.m_proxyCount == 0); this.m_proxyCount = this.m_shape.getChildCount(); for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i]; this.m_shape.computeAABB(proxy.aabb, xf, i); proxy.proxyId = broadPhase.createProxy(proxy.aabb, proxy); } }; Fixture.prototype.destroyProxies = function(broadPhase) { for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i]; broadPhase.destroyProxy(proxy.proxyId); proxy.proxyId = null; } this.m_proxyCount = 0; }; Fixture.prototype.synchronize = function(broadPhase, xf1, xf2) { for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i]; var aabb1 = new AABB(); var aabb2 = new AABB(); this.m_shape.computeAABB(aabb1, xf1, proxy.childIndex); this.m_shape.computeAABB(aabb2, xf2, proxy.childIndex); proxy.aabb.combine(aabb1, aabb2); var displacement = Vec2.sub(xf2.p, xf1.p); broadPhase.moveProxy(proxy.proxyId, proxy.aabb, displacement); } }; Fixture.prototype.setFilterData = function(filter) { this.m_filterGroupIndex = filter.groupIndex; this.m_filterCategoryBits = filter.categoryBits; this.m_filterMaskBits = filter.maskBits; this.refilter(); }; Fixture.prototype.getFilterGroupIndex = function() { return this.m_filterGroupIndex; }; Fixture.prototype.getFilterCategoryBits = function() { return this.m_filterCategoryBits; }; Fixture.prototype.getFilterMaskBits = function() { return this.m_filterMaskBits; }; Fixture.prototype.refilter = function() { if (this.m_body == null) { return; } var edge = this.m_body.getContactList(); while (edge) { var contact = edge.contact; var fixtureA = contact.getFixtureA(); var fixtureB = contact.getFixtureB(); if (fixtureA == this || fixtureB == this) { contact.flagForFiltering(); } edge = edge.next; } var world = this.m_body.getWorld(); if (world == null) { return; } var broadPhase = world.m_broadPhase; for (var i = 0; i < this.m_proxyCount; ++i) { broadPhase.touchProxy(this.m_proxies[i].proxyId); } }; Fixture.prototype.shouldCollide = function(that) { if (that.m_filterGroupIndex == this.m_filterGroupIndex && that.m_filterGroupIndex != 0) { return that.m_filterGroupIndex > 0; } var collide = (that.m_filterMaskBits & this.m_filterCategoryBits) != 0 && (that.m_filterCategoryBits & this.m_filterMaskBits) != 0; return collide; }; },{"./collision/AABB":11,"./common/Math":18,"./common/Vec2":23,"./util/common":51,"./util/options":53}],5:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Joint; var common = require("./util/common"); function JointEdge() { this.other = null; this.joint = null; this.prev = null; this.next = null; } var DEFAULTS = { userData: null, collideConnected: false }; function Joint(def, bodyA, bodyB) { bodyA = def.bodyA || bodyA; bodyB = def.bodyB || bodyB; _ASSERT && common.assert(bodyA); _ASSERT && common.assert(bodyB); _ASSERT && common.assert(bodyA != bodyB); this.m_type = "unknown-joint"; this.m_bodyA = bodyA; this.m_bodyB = bodyB; this.m_index = 0; this.m_collideConnected = !!def.collideConnected; this.m_prev = null; this.m_next = null; this.m_edgeA = new JointEdge(); this.m_edgeB = new JointEdge(); this.m_islandFlag = false; this.m_userData = def.userData; } Joint.prototype.isActive = function() { return this.m_bodyA.isActive() && this.m_bodyB.isActive(); }; Joint.prototype.getType = function() { return this.m_type; }; Joint.prototype.getBodyA = function() { return this.m_bodyA; }; Joint.prototype.getBodyB = function() { return this.m_bodyB; }; Joint.prototype.getNext = function() { return this.m_next; }; Joint.prototype.getUserData = function() { return this.m_userData; }; Joint.prototype.setUserData = function(data) { this.m_userData = data; }; Joint.prototype.getCollideConnected = function() { return this.m_collideConnected; }; Joint.prototype.getAnchorA = function() {}; Joint.prototype.getAnchorB = function() {}; Joint.prototype.getReactionForce = function(inv_dt) {}; Joint.prototype.getReactionTorque = function(inv_dt) {}; Joint.prototype.shiftOrigin = function(newOrigin) {}; Joint.prototype.initVelocityConstraints = function(step) {}; Joint.prototype.solveVelocityConstraints = function(step) {}; Joint.prototype.solvePositionConstraints = function(step) {}; },{"./util/common":51}],6:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("./util/common"); var Vec2 = require("./common/Vec2"); var Transform = require("./common/Transform"); var Math = require("./common/Math"); var Rot = require("./common/Rot"); module.exports = Manifold; module.exports.clipSegmentToLine = clipSegmentToLine; module.exports.clipVertex = ClipVertex; module.exports.getPointStates = getPointStates; module.exports.PointState = PointState; Manifold.e_circles = 0; Manifold.e_faceA = 1; Manifold.e_faceB = 2; Manifold.e_vertex = 0; Manifold.e_face = 1; function Manifold() { this.type = -1; this.localNormal = Vec2.zero(); this.localPoint = Vec2.zero(); this.points = [ new ManifoldPoint(), new ManifoldPoint() ]; this.pointCount = 0; } Manifold.prototype.init = function() { this.type = -1; this.localNormal.setZero(); this.localPoint.setZero(); this.points[0].init(); this.points[1].init(); this.pointCount = 0; return this; }; function ManifoldPoint() { this.localPoint = Vec2.zero(); this.normalImpulse = 0; this.tangentImpulse = 0; this.id = new ContactID(); } ManifoldPoint.prototype.init = function() { this.localPoint.setZero(); this.normalImpulse = 0; this.tangentImpulse = 0; this.id.init(); }; function ContactID() { this.cf = new ContactFeature(); } ContactID.prototype.init = function() { this.cf.init(); }; Object.defineProperty(ContactID.prototype, "key", { get: function() { return this.cf.indexA + this.cf.indexB * 4 + this.cf.typeA * 16 + this.cf.typeB * 64; }, enumerable: true, configurable: true }); ContactID.prototype.set = function(o) { this.cf.set(o.cf); }; function ContactFeature() { this.indexA; this.indexB; this.typeA; this.typeB; } ContactFeature.prototype.init = function() { this.indexA = 0; this.indexB = 0; this.typeA = 0; this.typeB = 0; }; ContactFeature.prototype.set = function(o) { this.indexA = o.indexA; this.indexB = o.indexB; this.typeA = o.typeA; this.typeB = o.typeB; }; function WorldManifold() { this.normal; this.points = []; this.separations = []; } Manifold.prototype.getWorldManifold = function(wm, xfA, radiusA, xfB, radiusB) { if (this.pointCount == 0) { return; } wm = wm || new WorldManifold(); var normal = wm.normal; var points = wm.points; var separations = wm.separations; switch (this.type) { case Manifold.e_circles: normal = Vec2.neo(1, 0); var pointA = Transform.mulVec2(xfA, this.localPoint); var pointB = Transform.mulVec2(xfB, this.points[0].localPoint); var dist = Vec2.sub(pointB, pointA); if (Vec2.lengthSquared(dist) > Math.EPSILON * Math.EPSILON) { normal.set(dist); normal.normalize(); } points[0] = Vec2.mid(pointA, pointB); separations[0] = -radiusB - radiusA; points.length = 1; separations.length = 1; break; case Manifold.e_faceA: normal = Rot.mulVec2(xfA.q, this.localNormal); var planePoint = Transform.mulVec2(xfA, this.localPoint); for (var i = 0; i < this.pointCount; ++i) { var clipPoint = Transform.mulVec2(xfB, this.points[i].localPoint); var cA = Vec2.clone(clipPoint).addMul(radiusA - Vec2.dot(Vec2.sub(clipPoint, planePoint), normal), normal); var cB = Vec2.clone(clipPoint).subMul(radiusB, normal); points[i] = Vec2.mid(cA, cB); separations[i] = Vec2.dot(Vec2.sub(cB, cA), normal); } points.length = this.pointCount; separations.length = this.pointCount; break; case Manifold.e_faceB: normal = Rot.mulVec2(xfB.q, this.localNormal); var planePoint = Transform.mulVec2(xfB, this.localPoint); for (var i = 0; i < this.pointCount; ++i) { var clipPoint = Transform.mulVec2(xfA, this.points[i].localPoint); var cB = Vec2.combine(1, clipPoint, radiusB - Vec2.dot(Vec2.sub(clipPoint, planePoint), normal), normal); var cA = Vec2.combine(1, clipPoint, -radiusA, normal); points[i] = Vec2.mid(cA, cB); separations[i] = Vec2.dot(Vec2.sub(cA, cB), normal); } points.length = this.pointCount; separations.length = this.pointCount; normal.mul(-1); break; } wm.normal = normal; wm.points = points; wm.separations = separations; return wm; }; var PointState = { nullState: 0, addState: 1, persistState: 2, removeState: 3 }; function getPointStates(state1, state2, manifold1, manifold2) { for (var i = 0; i < manifold1.pointCount; ++i) { var id = manifold1.points[i].id; state1[i] = PointState.removeState; for (var j = 0; j < manifold2.pointCount; ++j) { if (manifold2.points[j].id.key == id.key) { state1[i] = PointState.persistState; break; } } } for (var i = 0; i < manifold2.pointCount; ++i) { var id = manifold2.points[i].id; state2[i] = PointState.addState; for (var j = 0; j < manifold1.pointCount; ++j) { if (manifold1.points[j].id.key == id.key) { state2[i] = PointState.persistState; break; } } } } function ClipVertex() { this.v = Vec2.zero(); this.id = new ContactID(); } ClipVertex.prototype.set = function(o) { this.v.set(o.v); this.id.set(o.id); }; ClipVertex.prototype.init = function() { this.v.setZero(); this.id.init(); }; function clipSegmentToLine(vOut, vIn, normal, offset, vertexIndexA) { var numOut = 0; var distance0 = Vec2.dot(normal, vIn[0].v) - offset; var distance1 = Vec2.dot(normal, vIn[1].v) - offset; if (distance0 <= 0) vOut[numOut++].set(vIn[0]); if (distance1 <= 0) vOut[numOut++].set(vIn[1]); if (distance0 * distance1 < 0) { var interp = distance0 / (distance0 - distance1); vOut[numOut].v.setCombine(1 - interp, vIn[0].v, interp, vIn[1].v); vOut[numOut].id.cf.indexA = vertexIndexA; vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB; vOut[numOut].id.cf.typeA = Manifold.e_vertex; vOut[numOut].id.cf.typeB = Manifold.e_face; ++numOut; } return numOut; } },{"./common/Math":18,"./common/Rot":20,"./common/Transform":22,"./common/Vec2":23,"./util/common":51}],7:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = exports; Settings.maxManifoldPoints = 2; Settings.maxPolygonVertices = 12; Settings.aabbExtension = .1; Settings.aabbMultiplier = 2; Settings.linearSlop = .005; Settings.linearSlopSquared = Settings.linearSlop * Settings.linearSlop; Settings.angularSlop = 2 / 180 * Math.PI; Settings.polygonRadius = 2 * Settings.linearSlop; Settings.maxSubSteps = 8; Settings.maxTOIContacts = 32; Settings.maxTOIIterations = 20; Settings.maxDistnceIterations = 20; Settings.velocityThreshold = 1; Settings.maxLinearCorrection = .2; Settings.maxAngularCorrection = 8 / 180 * Math.PI; Settings.maxTranslation = 2; Settings.maxTranslationSquared = Settings.maxTranslation * Settings.maxTranslation; Settings.maxRotation = .5 * Math.PI; Settings.maxRotationSquared = Settings.maxRotation * Settings.maxRotation; Settings.baumgarte = .2; Settings.toiBaugarte = .75; Settings.timeToSleep = .5; Settings.linearSleepTolerance = .01; Settings.linearSleepToleranceSqr = Math.pow(Settings.linearSleepTolerance, 2); Settings.angularSleepTolerance = 2 / 180 * Math.PI; Settings.angularSleepToleranceSqr = Math.pow(Settings.angularSleepTolerance, 2); },{}],8:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Shape; var Math = require("./common/Math"); function Shape() { this.m_type; this.m_radius; } Shape.isValid = function(shape) { return !!shape; }; Shape.prototype.getRadius = function() { return this.m_radius; }; Shape.prototype.getType = function() { return this.m_type; }; Shape.prototype._clone = function() {}; Shape.prototype.getChildCount = function() {}; Shape.prototype.testPoint = function(xf, p) {}; Shape.prototype.rayCast = function(output, input, transform, childIndex) {}; Shape.prototype.computeAABB = function(aabb, xf, childIndex) {}; Shape.prototype.computeMass = function(massData, density) {}; Shape.prototype.computeDistanceProxy = function(proxy) {}; },{"./common/Math":18}],9:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Solver; module.exports.TimeStep = TimeStep; var Settings = require("./Settings"); var common = require("./util/common"); var Vec2 = require("./common/Vec2"); var Math = require("./common/Math"); var Body = require("./Body"); var Contact = require("./Contact"); var Joint = require("./Joint"); var TimeOfImpact = require("./collision/TimeOfImpact"); var TOIInput = TimeOfImpact.Input; var TOIOutput = TimeOfImpact.Output; var Distance = require("./collision/Distance"); var DistanceInput = Distance.Input; var DistanceOutput = Distance.Output; var DistanceProxy = Distance.Proxy; var SimplexCache = Distance.Cache; function TimeStep(dt) { this.dt = 0; this.inv_dt = 0; this.velocityIterations = 0; this.positionIterations = 0; this.warmStarting = false; this.blockSolve = true; this.inv_dt0 = 0; this.dtRatio = 1; } TimeStep.prototype.reset = function(dt) { if (this.dt > 0) { this.inv_dt0 = this.inv_dt; } this.dt = dt; this.inv_dt = dt == 0 ? 0 : 1 / dt; this.dtRatio = dt * this.inv_dt0; }; function Solver(world) { this.m_world = world; this.m_stack = []; this.m_bodies = []; this.m_contacts = []; this.m_joints = []; } Solver.prototype.clear = function() { this.m_stack.length = 0; this.m_bodies.length = 0; this.m_contacts.length = 0; this.m_joints.length = 0; }; Solver.prototype.addBody = function(body) { _ASSERT && common.assert(body instanceof Body, "Not a Body!", body); this.m_bodies.push(body); }; Solver.prototype.addContact = function(contact) { _ASSERT && common.assert(contact instanceof Contact, "Not a Contact!", contact); this.m_contacts.push(contact); }; Solver.prototype.addJoint = function(joint) { _ASSERT && common.assert(joint instanceof Joint, "Not a Joint!", joint); this.m_joints.push(joint); }; Solver.prototype.solveWorld = function(step) { var world = this.m_world; for (var b = world.m_bodyList; b; b = b.m_next) { b.m_islandFlag = false; } for (var c = world.m_contactList; c; c = c.m_next) { c.m_islandFlag = false; } for (var j = world.m_jointList; j; j = j.m_next) { j.m_islandFlag = false; } var stack = this.m_stack; var loop = -1; for (var seed = world.m_bodyList; seed; seed = seed.m_next) { loop++; if (seed.m_islandFlag) { continue; } if (seed.isAwake() == false || seed.isActive() == false) { continue; } if (seed.isStatic()) { continue; } this.clear(); stack.push(seed); seed.m_islandFlag = true; while (stack.length > 0) { var b = stack.pop(); _ASSERT && common.assert(b.isActive() == true); this.addBody(b); b.setAwake(true); if (b.isStatic()) { continue; } for (var ce = b.m_contactList; ce; ce = ce.next) { var contact = ce.contact; if (contact.m_islandFlag) { continue; } if (contact.isEnabled() == false || contact.isTouching() == false) { continue; } var sensorA = contact.m_fixtureA.m_isSensor; var sensorB = contact.m_fixtureB.m_isSensor; if (sensorA || sensorB) { continue; } this.addContact(contact); contact.m_islandFlag = true; var other = ce.other; if (other.m_islandFlag) { continue; } stack.push(other); other.m_islandFlag = true; } for (var je = b.m_jointList; je; je = je.next) { if (je.joint.m_islandFlag == true) { continue; } var other = je.other; if (other.isActive() == false) { continue; } this.addJoint(je.joint); je.joint.m_islandFlag = true; if (other.m_islandFlag) { continue; } stack.push(other); other.m_islandFlag = true; } } this.solveIsland(step); for (var i = 0; i < this.m_bodies.length; ++i) { var b = this.m_bodies[i]; if (b.isStatic()) { b.m_islandFlag = false; } } } }; Solver.prototype.solveIsland = function(step) { var world = this.m_world; var gravity = world.m_gravity; var allowSleep = world.m_allowSleep; var h = step.dt; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var c = Vec2.clone(body.m_sweep.c); var a = body.m_sweep.a; var v = Vec2.clone(body.m_linearVelocity); var w = body.m_angularVelocity; body.m_sweep.c0.set(body.m_sweep.c); body.m_sweep.a0 = body.m_sweep.a; if (body.isDynamic()) { v.addMul(h * body.m_gravityScale, gravity); v.addMul(h * body.m_invMass, body.m_force); w += h * body.m_invI * body.m_torque; v.mul(1 / (1 + h * body.m_linearDamping)); w *= 1 / (1 + h * body.m_angularDamping); } body.c_position.c = c; body.c_position.a = a; body.c_velocity.v = v; body.c_velocity.w = w; } for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initConstraint(step); } _DEBUG && this.printBodies("M: "); for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initVelocityConstraint(step); } _DEBUG && this.printBodies("R: "); if (step.warmStarting) { for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.warmStartConstraint(step); } } _DEBUG && this.printBodies("Q: "); for (var i = 0; i < this.m_joints.length; ++i) { var joint = this.m_joints[i]; joint.initVelocityConstraints(step); } _DEBUG && this.printBodies("E: "); for (var i = 0; i < step.velocityIterations; ++i) { for (var j = 0; j < this.m_joints.length; ++j) { var joint = this.m_joints[j]; joint.solveVelocityConstraints(step); } for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; contact.solveVelocityConstraint(step); } } _DEBUG && this.printBodies("D: "); for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.storeConstraintImpulses(step); } _DEBUG && this.printBodies("C: "); for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var c = Vec2.clone(body.c_position.c); var a = body.c_position.a; var v = Vec2.clone(body.c_velocity.v); var w = body.c_velocity.w; var translation = Vec2.mul(h, v); if (Vec2.lengthSquared(translation) > Settings.maxTranslationSquared) { var ratio = Settings.maxTranslation / translation.length(); v.mul(ratio); } var rotation = h * w; if (rotation * rotation > Settings.maxRotationSquared) { var ratio = Settings.maxRotation / Math.abs(rotation); w *= ratio; } c.addMul(h, v); a += h * w; body.c_position.c.set(c); body.c_position.a = a; body.c_velocity.v.set(v); body.c_velocity.w = w; } _DEBUG && this.printBodies("B: "); var positionSolved = false; for (var i = 0; i < step.positionIterations; ++i) { var minSeparation = 0; for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; var separation = contact.solvePositionConstraint(step); minSeparation = Math.min(minSeparation, separation); } var contactsOkay = minSeparation >= -3 * Settings.linearSlop; var jointsOkay = true; for (var j = 0; j < this.m_joints.length; ++j) { var joint = this.m_joints[j]; var jointOkay = joint.solvePositionConstraints(step); jointsOkay = jointsOkay && jointOkay; } if (contactsOkay && jointsOkay) { positionSolved = true; break; } } _DEBUG && this.printBodies("L: "); for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.m_sweep.c.set(body.c_position.c); body.m_sweep.a = body.c_position.a; body.m_linearVelocity.set(body.c_velocity.v); body.m_angularVelocity = body.c_velocity.w; body.synchronizeTransform(); } this.postSolveIsland(); if (allowSleep) { var minSleepTime = Infinity; var linTolSqr = Settings.linearSleepToleranceSqr; var angTolSqr = Settings.angularSleepToleranceSqr; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; if (body.isStatic()) { continue; } if (body.m_autoSleepFlag == false || body.m_angularVelocity * body.m_angularVelocity > angTolSqr || Vec2.lengthSquared(body.m_linearVelocity) > linTolSqr) { body.m_sleepTime = 0; minSleepTime = 0; } else { body.m_sleepTime += h; minSleepTime = Math.min(minSleepTime, body.m_sleepTime); } } if (minSleepTime >= Settings.timeToSleep && positionSolved) { for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.setAwake(false); } } } }; Solver.prototype.printBodies = function(tag) { for (var i = 0; i < this.m_bodies.length; ++i) { var b = this.m_bodies[i]; common.debug(tag, b.c_position.a, b.c_position.c.x, b.c_position.c.y, b.c_velocity.w, b.c_velocity.v.x, b.c_velocity.v.y); } }; var s_subStep = new TimeStep(); Solver.prototype.solveWorldTOI = function(step) { var world = this.m_world; if (world.m_stepComplete) { for (var b = world.m_bodyList; b; b = b.m_next) { b.m_islandFlag = false; b.m_sweep.alpha0 = 0; } for (var c = world.m_contactList; c; c = c.m_next) { c.m_toiFlag = false; c.m_islandFlag = false; c.m_toiCount = 0; c.m_toi = 1; } } for (;;) { var minContact = null; var minAlpha = 1; for (var c = world.m_contactList; c; c = c.m_next) { if (c.isEnabled() == false) { continue; } if (c.m_toiCount > Settings.maxSubSteps) { continue; } var alpha = 1; if (c.m_toiFlag) { alpha = c.m_toi; } else { var fA = c.getFixtureA(); var fB = c.getFixtureB(); if (fA.isSensor() || fB.isSensor()) { continue; } var bA = fA.getBody(); var bB = fB.getBody(); _ASSERT && common.assert(bA.isDynamic() || bB.isDynamic()); var activeA = bA.isAwake() && !bA.isStatic(); var activeB = bB.isAwake() && !bB.isStatic(); if (activeA == false && activeB == false) { continue; } var collideA = bA.isBullet() || !bA.isDynamic(); var collideB = bB.isBullet() || !bB.isDynamic(); if (collideA == false && collideB == false) { continue; } var alpha0 = bA.m_sweep.alpha0; if (bA.m_sweep.alpha0 < bB.m_sweep.alpha0) { alpha0 = bB.m_sweep.alpha0; bA.m_sweep.advance(alpha0); } else if (bB.m_sweep.alpha0 < bA.m_sweep.alpha0) { alpha0 = bA.m_sweep.alpha0; bB.m_sweep.advance(alpha0); } _ASSERT && common.assert(alpha0 < 1); var indexA = c.getChildIndexA(); var indexB = c.getChildIndexB(); var sweepA = bA.m_sweep; var sweepB = bB.m_sweep; var input = new TOIInput(); input.proxyA.set(fA.getShape(), indexA); input.proxyB.set(fB.getShape(), indexB); input.sweepA.set(bA.m_sweep); input.sweepB.set(bB.m_sweep); input.tMax = 1; var output = new TOIOutput(); TimeOfImpact(output, input); var beta = output.t; if (output.state == TOIOutput.e_touching) { alpha = Math.min(alpha0 + (1 - alpha0) * beta, 1); } else { alpha = 1; } c.m_toi = alpha; c.m_toiFlag = true; } if (alpha < minAlpha) { minContact = c; minAlpha = alpha; } } if (minContact == null || 1 - 10 * Math.EPSILON < minAlpha) { world.m_stepComplete = true; break; } var fA = minContact.getFixtureA(); var fB = minContact.getFixtureB(); var bA = fA.getBody(); var bB = fB.getBody(); var backup1 = bA.m_sweep.clone(); var backup2 = bB.m_sweep.clone(); bA.advance(minAlpha); bB.advance(minAlpha); minContact.update(world); minContact.m_toiFlag = false; ++minContact.m_toiCount; if (minContact.isEnabled() == false || minContact.isTouching() == false) { minContact.setEnabled(false); bA.m_sweep.set(backup1); bB.m_sweep.set(backup2); bA.synchronizeTransform(); bB.synchronizeTransform(); continue; } bA.setAwake(true); bB.setAwake(true); this.clear(); this.addBody(bA); this.addBody(bB); this.addContact(minContact); bA.m_islandFlag = true; bB.m_islandFlag = true; minContact.m_islandFlag = true; var bodies = [ bA, bB ]; for (var i = 0; i < bodies.length; ++i) { var body = bodies[i]; if (body.isDynamic()) { for (var ce = body.m_contactList; ce; ce = ce.next) { var contact = ce.contact; if (contact.m_islandFlag) { continue; } var other = ce.other; if (other.isDynamic() && !body.isBullet() && !other.isBullet()) { continue; } var sensorA = contact.m_fixtureA.m_isSensor; var sensorB = contact.m_fixtureB.m_isSensor; if (sensorA || sensorB) { continue; } var backup = other.m_sweep.clone(); if (other.m_islandFlag == false) { other.advance(minAlpha); } contact.update(world); if (contact.isEnabled() == false || contact.isTouching() == false) { other.m_sweep.set(backup); other.synchronizeTransform(); continue; } contact.m_islandFlag = true; this.addContact(contact); if (other.m_islandFlag) { continue; } other.m_islandFlag = true; if (!other.isStatic()) { other.setAwake(true); } this.addBody(other); } } } s_subStep.reset((1 - minAlpha) * step.dt); s_subStep.dtRatio = 1; s_subStep.positionIterations = 20; s_subStep.velocityIterations = step.velocityIterations; s_subStep.warmStarting = false; this.solveIslandTOI(s_subStep, bA, bB); for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.m_islandFlag = false; if (!body.isDynamic()) { continue; } body.synchronizeFixtures(); for (var ce = body.m_contactList; ce; ce = ce.next) { ce.contact.m_toiFlag = false; ce.contact.m_islandFlag = false; } } world.findNewContacts(); if (world.m_subStepping) { world.m_stepComplete = false; break; } } if (_DEBUG) for (var b = world.m_bodyList; b; b = b.m_next) { var c = b.m_sweep.c; var a = b.m_sweep.a; var v = b.m_linearVelocity; var w = b.m_angularVelocity; } }; Solver.prototype.solveIslandTOI = function(subStep, toiA, toiB) { var world = this.m_world; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.c_position.c.set(body.m_sweep.c); body.c_position.a = body.m_sweep.a; body.c_velocity.v.set(body.m_linearVelocity); body.c_velocity.w = body.m_angularVelocity; } for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initConstraint(subStep); } for (var i = 0; i < subStep.positionIterations; ++i) { var minSeparation = 0; for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; var separation = contact.solvePositionConstraintTOI(subStep, toiA, toiB); minSeparation = Math.min(minSeparation, separation); } var contactsOkay = minSeparation >= -1.5 * Settings.linearSlop; if (contactsOkay) { break; } } if (false) { for (var i = 0; i < this.m_contacts.length; ++i) { var c = this.m_contacts[i]; var fA = c.getFixtureA(); var fB = c.getFixtureB(); var bA = fA.getBody(); var bB = fB.getBody(); var indexA = c.getChildIndexA(); var indexB = c.getChildIndexB(); var input = new DistanceInput(); input.proxyA.set(fA.getShape(), indexA); input.proxyB.set(fB.getShape(), indexB); input.transformA = bA.getTransform(); input.transformB = bB.getTransform(); input.useRadii = false; var output = new DistanceOutput(); var cache = new SimplexCache(); Distance(output, cache, input); if (output.distance == 0 || cache.count == 3) { cache.count += 0; } } } toiA.m_sweep.c0.set(toiA.c_position.c); toiA.m_sweep.a0 = toiA.c_position.a; toiB.m_sweep.c0.set(toiB.c_position.c); toiB.m_sweep.a0 = toiB.c_position.a; for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initVelocityConstraint(subStep); } for (var i = 0; i < subStep.velocityIterations; ++i) { for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; contact.solveVelocityConstraint(subStep); } } var h = subStep.dt; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var c = Vec2.clone(body.c_position.c); var a = body.c_position.a; var v = Vec2.clone(body.c_velocity.v); var w = body.c_velocity.w; var translation = Vec2.mul(h, v); if (Vec2.dot(translation, translation) > Settings.maxTranslationSquared) { var ratio = Settings.maxTranslation / translation.length(); v.mul(ratio); } var rotation = h * w; if (rotation * rotation > Settings.maxRotationSquared) { var ratio = Settings.maxRotation / Math.abs(rotation); w *= ratio; } c.addMul(h, v); a += h * w; body.c_position.c = c; body.c_position.a = a; body.c_velocity.v = v; body.c_velocity.w = w; body.m_sweep.c = c; body.m_sweep.a = a; body.m_linearVelocity = v; body.m_angularVelocity = w; body.synchronizeTransform(); } this.postSolveIsland(); }; function ContactImpulse() { this.normalImpulses = []; this.tangentImpulses = []; } Solver.prototype.postSolveIsland = function() { var impulse = new ContactImpulse(); for (var c = 0; c < this.m_contacts.length; ++c) { var contact = this.m_contacts[c]; for (var p = 0; p < contact.v_points.length; ++p) { impulse.normalImpulses.push(contact.v_points[p].normalImpulse); impulse.tangentImpulses.push(contact.v_points[p].tangentImpulse); } this.m_world.postSolve(contact, impulse); } }; },{"./Body":2,"./Contact":3,"./Joint":5,"./Settings":7,"./collision/Distance":13,"./collision/TimeOfImpact":15,"./common/Math":18,"./common/Vec2":23,"./util/common":51}],10:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = World; var options = require("./util/options"); var common = require("./util/common"); var Vec2 = require("./common/Vec2"); var BroadPhase = require("./collision/BroadPhase"); var Solver = require("./Solver"); var Body = require("./Body"); var Contact = require("./Contact"); var WorldDef = { gravity: Vec2.zero(), allowSleep: true, warmStarting: true, continuousPhysics: true, subStepping: false, blockSolve: true, velocityIterations: 8, positionIterations: 3 }; function World(def) { if (!(this instanceof World)) { return new World(def); } if (def && Vec2.isValid(def)) { def = { gravity: def }; } def = options(def, WorldDef); this.m_solver = new Solver(this); this.m_broadPhase = new BroadPhase(); this.m_contactList = null; this.m_contactCount = 0; this.m_bodyList = null; this.m_bodyCount = 0; this.m_jointList = null; this.m_jointCount = 0; this.m_stepComplete = true; this.m_allowSleep = def.allowSleep; this.m_gravity = Vec2.clone(def.gravity); this.m_clearForces = true; this.m_newFixture = false; this.m_locked = false; this.m_warmStarting = def.warmStarting; this.m_continuousPhysics = def.continuousPhysics; this.m_subStepping = def.subStepping; this.m_blockSolve = def.blockSolve; this.m_velocityIterations = def.velocityIterations; this.m_positionIterations = def.positionIterations; this.m_t = 0; this.m_stepCount = 0; this.addPair = this.createContact.bind(this); } World.prototype.getBodyList = function() { return this.m_bodyList; }; World.prototype.getJointList = function() { return this.m_jointList; }; World.prototype.getContactList = function() { return this.m_contactList; }; World.prototype.getBodyCount = function() { return this.m_bodyCount; }; World.prototype.getJointCount = function() { return this.m_jointCount; }; World.prototype.getContactCount = function() { return this.m_contactCount; }; World.prototype.setGravity = function(gravity) { this.m_gravity = gravity; }; World.prototype.getGravity = function() { return this.m_gravity; }; World.prototype.isLocked = function() { return this.m_locked; }; World.prototype.setAllowSleeping = function(flag) { if (flag == this.m_allowSleep) { return; } this.m_allowSleep = flag; if (this.m_allowSleep == false) { for (var b = this.m_bodyList; b; b = b.m_next) { b.setAwake(true); } } }; World.prototype.getAllowSleeping = function() { return this.m_allowSleep; }; World.prototype.setWarmStarting = function(flag) { this.m_warmStarting = flag; }; World.prototype.getWarmStarting = function() { return this.m_warmStarting; }; World.prototype.setContinuousPhysics = function(flag) { this.m_continuousPhysics = flag; }; World.prototype.getContinuousPhysics = function() { return this.m_continuousPhysics; }; World.prototype.setSubStepping = function(flag) { this.m_subStepping = flag; }; World.prototype.getSubStepping = function() { return this.m_subStepping; }; World.prototype.setAutoClearForces = function(flag) { this.m_clearForces = flag; }; World.prototype.getAutoClearForces = function() { return this.m_clearForces; }; World.prototype.clearForces = function() { for (var body = this.m_bodyList; body; body = body.getNext()) { body.m_force.setZero(); body.m_torque = 0; } }; World.prototype.queryAABB = function(aabb, queryCallback) { _ASSERT && common.assert(typeof queryCallback === "function"); var broadPhase = this.m_broadPhase; this.m_broadPhase.query(aabb, function(proxyId) { var proxy = broadPhase.getUserData(proxyId); return queryCallback(proxy.fixture); }); }; World.prototype.rayCast = function(point1, point2, reportFixtureCallback) { _ASSERT && common.assert(typeof reportFixtureCallback === "function"); var broadPhase = this.m_broadPhase; this.m_broadPhase.rayCast({ maxFraction: 1, p1: point1, p2: point2 }, function(input, proxyId) { var proxy = broadPhase.getUserData(proxyId); var fixture = proxy.fixture; var index = proxy.childIndex; var output = {}; var hit = fixture.rayCast(output, input, index); if (hit) { var fraction = output.fraction; var point = Vec2.add(Vec2.mul(1 - fraction, input.p1), Vec2.mul(fraction, input.p2)); return reportFixtureCallback(fixture, point, output.normal, fraction); } return input.maxFraction; }); }; World.prototype.getProxyCount = function() { return this.m_broadPhase.getProxyCount(); }; World.prototype.getTreeHeight = function() { return this.m_broadPhase.getTreeHeight(); }; World.prototype.getTreeBalance = function() { return this.m_broadPhase.getTreeBalance(); }; World.prototype.getTreeQuality = function() { return this.m_broadPhase.getTreeQuality(); }; World.prototype.shiftOrigin = function(newOrigin) { _ASSERT && common.assert(this.m_locked == false); if (this.m_locked) { return; } for (var b = this.m_bodyList; b; b = b.m_next) { b.m_xf.p.sub(newOrigin); b.m_sweep.c0.sub(newOrigin); b.m_sweep.c.sub(newOrigin); } for (var j = this.m_jointList; j; j = j.m_next) { j.shiftOrigin(newOrigin); } this.m_broadPhase.shiftOrigin(newOrigin); }; World.prototype.createBody = function(def, angle) { _ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return null; } if (def && Vec2.isValid(def)) { def = { position: def, angle: angle }; } var body = new Body(this, def); body.m_prev = null; body.m_next = this.m_bodyList; if (this.m_bodyList) { this.m_bodyList.m_prev = body; } this.m_bodyList = body; ++this.m_bodyCount; return body; }; World.prototype.createDynamicBody = function(def, angle) { if (!def) { def = {}; } else if (Vec2.isValid(def)) { def = { position: def, angle: angle }; } def.type = "dynamic"; return this.createBody(def); }; World.prototype.createKinematicBody = function(def, angle) { if (!def) { def = {}; } else if (Vec2.isValid(def)) { def = { position: def, angle: angle }; } def.type = "kinematic"; return this.createBody(def); }; World.prototype.destroyBody = function(b) { _ASSERT && common.assert(this.m_bodyCount > 0); _ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return; } if (b.m_destroyed) { return false; } var je = b.m_jointList; while (je) { var je0 = je; je = je.next; this.publish("remove-joint", je0.joint); this.destroyJoint(je0.joint); b.m_jointList = je; } b.m_jointList = null; var ce = b.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.destroyContact(ce0.contact); b.m_contactList = ce; } b.m_contactList = null; var f = b.m_fixtureList; while (f) { var f0 = f; f = f.m_next; this.publish("remove-fixture", f0); f0.destroyProxies(this.m_broadPhase); b.m_fixtureList = f; } b.m_fixtureList = null; if (b.m_prev) { b.m_prev.m_next = b.m_next; } if (b.m_next) { b.m_next.m_prev = b.m_prev; } if (b == this.m_bodyList) { this.m_bodyList = b.m_next; } b.m_destroyed = true; --this.m_bodyCount; this.publish("remove-body", b); return true; }; World.prototype.createJoint = function(joint) { _ASSERT && common.assert(!!joint.m_bodyA); _ASSERT && common.assert(!!joint.m_bodyB); _ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return null; } joint.m_prev = null; joint.m_next = this.m_jointList; if (this.m_jointList) { this.m_jointList.m_prev = joint; } this.m_jointList = joint; ++this.m_jointCount; joint.m_edgeA.joint = joint; joint.m_edgeA.other = joint.m_bodyB; joint.m_edgeA.prev = null; joint.m_edgeA.next = joint.m_bodyA.m_jointList; if (joint.m_bodyA.m_jointList) joint.m_bodyA.m_jointList.prev = joint.m_edgeA; joint.m_bodyA.m_jointList = joint.m_edgeA; joint.m_edgeB.joint = joint; joint.m_edgeB.other = joint.m_bodyA; joint.m_edgeB.prev = null; joint.m_edgeB.next = joint.m_bodyB.m_jointList; if (joint.m_bodyB.m_jointList) joint.m_bodyB.m_jointList.prev = joint.m_edgeB; joint.m_bodyB.m_jointList = joint.m_edgeB; if (joint.m_collideConnected == false) { for (var edge = joint.m_bodyB.getContactList(); edge; edge = edge.next) { if (edge.other == joint.m_bodyA) { edge.contact.flagForFiltering(); } } } return joint; }; World.prototype.destroyJoint = function(joint) { _ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return; } if (joint.m_prev) { joint.m_prev.m_next = joint.m_next; } if (joint.m_next) { joint.m_next.m_prev = joint.m_prev; } if (joint == this.m_jointList) { this.m_jointList = joint.m_next; } var bodyA = joint.m_bodyA; var bodyB = joint.m_bodyB; bodyA.setAwake(true); bodyB.setAwake(true); if (joint.m_edgeA.prev) { joint.m_edgeA.prev.next = joint.m_edgeA.next; } if (joint.m_edgeA.next) { joint.m_edgeA.next.prev = joint.m_edgeA.prev; } if (joint.m_edgeA == bodyA.m_jointList) { bodyA.m_jointList = joint.m_edgeA.next; } joint.m_edgeA.prev = null; joint.m_edgeA.next = null; if (joint.m_edgeB.prev) { joint.m_edgeB.prev.next = joint.m_edgeB.next; } if (joint.m_edgeB.next) { joint.m_edgeB.next.prev = joint.m_edgeB.prev; } if (joint.m_edgeB == bodyB.m_jointList) { bodyB.m_jointList = joint.m_edgeB.next; } joint.m_edgeB.prev = null; joint.m_edgeB.next = null; _ASSERT && common.assert(this.m_jointCount > 0); --this.m_jointCount; if (joint.m_collideConnected == false) { var edge = bodyB.getContactList(); while (edge) { if (edge.other == bodyA) { edge.contact.flagForFiltering(); } edge = edge.next; } } this.publish("remove-joint", joint); }; var s_step = new Solver.TimeStep(); World.prototype.step = function(timeStep, velocityIterations, positionIterations) { if ((velocityIterations | 0) !== velocityIterations) { velocityIterations = 0; } velocityIterations = velocityIterations || this.m_velocityIterations; positionIterations = positionIterations || this.m_positionIterations; this.m_stepCount++; if (this.m_newFixture) { this.findNewContacts(); this.m_newFixture = false; } this.m_locked = true; s_step.reset(timeStep); s_step.velocityIterations = velocityIterations; s_step.positionIterations = positionIterations; s_step.warmStarting = this.m_warmStarting; s_step.blockSolve = this.m_blockSolve; this.updateContacts(); if (this.m_stepComplete && timeStep > 0) { this.m_solver.solveWorld(s_step); for (var b = this.m_bodyList; b; b = b.getNext()) { if (b.m_islandFlag == false) { continue; } if (b.isStatic()) { continue; } b.synchronizeFixtures(); } this.findNewContacts(); } if (this.m_continuousPhysics && timeStep > 0) { this.m_solver.solveWorldTOI(s_step); } if (this.m_clearForces) { this.clearForces(); } this.m_locked = false; }; World.prototype.findNewContacts = function() { this.m_broadPhase.updatePairs(this.addPair); }; World.prototype.createContact = function(proxyA, proxyB) { var fixtureA = proxyA.fixture; var fixtureB = proxyB.fixture; var indexA = proxyA.childIndex; var indexB = proxyB.childIndex; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); if (bodyA === bodyB) { return; } var edge = bodyB.getContactList(); while (edge) { if (edge.other === bodyA) { var fA = edge.contact.getFixtureA(); var fB = edge.contact.getFixtureB(); var iA = edge.contact.getChildIndexA(); var iB = edge.contact.getChildIndexB(); if (fA === fixtureA && fB === fixtureB && iA === indexA && iB === indexB) { return; } if (fA === fixtureB && fB === fixtureA && iA === indexB && iB === indexA) { return; } } edge = edge.next; } if (bodyB.shouldCollide(bodyA) === false) { return; } if (fixtureB.shouldCollide(fixtureA) === false) { return; } var contact = Contact.create(fixtureA, indexA, fixtureB, indexB); if (contact == null) { return; } contact.m_prev = null; if (this.m_contactList != null) { contact.m_next = this.m_contactList; this.m_contactList.m_prev = contact; } this.m_contactList = contact; ++this.m_contactCount; }; World.prototype.updateContacts = function() { var c, next_c = this.m_contactList; while (c = next_c) { next_c = c.getNext(); var fixtureA = c.getFixtureA(); var fixtureB = c.getFixtureB(); var indexA = c.getChildIndexA(); var indexB = c.getChildIndexB(); var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); if (c.m_filterFlag) { if (bodyB.shouldCollide(bodyA) == false) { this.destroyContact(c); continue; } if (fixtureB.shouldCollide(fixtureA) == false) { this.destroyContact(c); continue; } c.m_filterFlag = false; } var activeA = bodyA.isAwake() && !bodyA.isStatic(); var activeB = bodyB.isAwake() && !bodyB.isStatic(); if (activeA == false && activeB == false) { continue; } var proxyIdA = fixtureA.m_proxies[indexA].proxyId; var proxyIdB = fixtureB.m_proxies[indexB].proxyId; var overlap = this.m_broadPhase.testOverlap(proxyIdA, proxyIdB); if (overlap == false) { this.destroyContact(c); continue; } c.update(this); } }; World.prototype.destroyContact = function(contact) { Contact.destroy(contact, this); if (contact.m_prev) { contact.m_prev.m_next = contact.m_next; } if (contact.m_next) { contact.m_next.m_prev = contact.m_prev; } if (contact == this.m_contactList) { this.m_contactList = contact.m_next; } --this.m_contactCount; }; World.prototype._listeners = null; World.prototype.on = function(name, listener) { if (typeof name !== "string" || typeof listener !== "function") { return this; } if (!this._listeners) { this._listeners = {}; } if (!this._listeners[name]) { this._listeners[name] = []; } this._listeners[name].push(listener); return this; }; World.prototype.off = function(name, listener) { if (typeof name !== "string" || typeof listener !== "function") { return this; } var listeners = this._listeners && this._listeners[name]; if (!listeners || !listeners.length) { return this; } var index = listeners.indexOf(listener); if (index >= 0) { listeners.splice(index, 1); } return this; }; World.prototype.publish = function(name, arg1, arg2, arg3) { var listeners = this._listeners && this._listeners[name]; if (!listeners || !listeners.length) { return 0; } for (var l = 0; l < listeners.length; l++) { listeners[l].call(this, arg1, arg2, arg3); } return listeners.length; }; World.prototype.beginContact = function(contact) { this.publish("begin-contact", contact); }; World.prototype.endContact = function(contact) { this.publish("end-contact", contact); }; World.prototype.preSolve = function(contact, oldManifold) { this.publish("pre-solve", contact, oldManifold); }; World.prototype.postSolve = function(contact, impulse) { this.publish("post-solve", contact, impulse); }; },{"./Body":2,"./Contact":3,"./Solver":9,"./collision/BroadPhase":12,"./common/Vec2":23,"./util/common":51,"./util/options":53}],11:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); module.exports = AABB; function AABB(lower, upper) { if (!(this instanceof AABB)) { return new AABB(lower, upper); } this.lowerBound = Vec2.zero(); this.upperBound = Vec2.zero(); if (typeof lower === "object") { this.lowerBound.set(lower); } if (typeof upper === "object") { this.upperBound.set(upper); } } AABB.prototype.isValid = function() { return AABB.isValid(this); }; AABB.isValid = function(aabb) { var d = Vec2.sub(aabb.upperBound, aabb.lowerBound); var valid = d.x >= 0 && d.y >= 0 && Vec2.isValid(aabb.lowerBound) && Vec2.isValid(aabb.upperBound); return valid; }; AABB.assert = function(o) { if (!_ASSERT) return; if (!AABB.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid AABB!"); } }; AABB.prototype.getCenter = function() { return Vec2.neo((this.lowerBound.x + this.upperBound.x) * .5, (this.lowerBound.y + this.upperBound.y) * .5); }; AABB.prototype.getExtents = function() { return Vec2.neo((this.upperBound.x - this.lowerBound.x) * .5, (this.upperBound.y - this.lowerBound.y) * .5); }; AABB.prototype.getPerimeter = function() { return 2 * (this.upperBound.x - this.lowerBound.x + this.upperBound.y - this.lowerBound.y); }; AABB.prototype.combine = function(a, b) { var lowerA = a.lowerBound; var upperA = a.upperBound; var lowerB = b.lowerBound; var upperB = b.upperBound; var lowerX = Math.min(lowerA.x, lowerB.x); var lowerY = Math.min(lowerA.y, lowerB.y); var upperX = Math.max(upperB.x, upperA.x); var upperY = Math.max(upperB.y, upperA.y); this.lowerBound.set(lowerX, lowerY); this.upperBound.set(upperX, upperY); }; AABB.prototype.combinePoints = function(a, b) { this.lowerBound.set(Math.min(a.x, b.x), Math.min(a.y, b.y)); this.upperBound.set(Math.max(a.x, b.x), Math.max(a.y, b.y)); }; AABB.prototype.set = function(aabb) { this.lowerBound.set(aabb.lowerBound.x, aabb.lowerBound.y); this.upperBound.set(aabb.upperBound.x, aabb.upperBound.y); }; AABB.prototype.contains = function(aabb) { var result = true; result = result && this.lowerBound.x <= aabb.lowerBound.x; result = result && this.lowerBound.y <= aabb.lowerBound.y; result = result && aabb.upperBound.x <= this.upperBound.x; result = result && aabb.upperBound.y <= this.upperBound.y; return result; }; AABB.prototype.extend = function(value) { AABB.extend(this, value); }; AABB.extend = function(aabb, value) { aabb.lowerBound.x -= value; aabb.lowerBound.y -= value; aabb.upperBound.x += value; aabb.upperBound.y += value; }; AABB.testOverlap = function(a, b) { var d1x = b.lowerBound.x - a.upperBound.x; var d2x = a.lowerBound.x - b.upperBound.x; var d1y = b.lowerBound.y - a.upperBound.y; var d2y = a.lowerBound.y - b.upperBound.y; if (d1x > 0 || d1y > 0 || d2x > 0 || d2y > 0) { return false; } return true; }; AABB.areEqual = function(a, b) { return Vec2.areEqual(a.lowerBound, b.lowerBound) && Vec2.areEqual(a.upperBound, b.upperBound); }; AABB.diff = function(a, b) { var wD = Math.max(0, Math.min(a.upperBound.x, b.upperBound.x) - Math.max(b.lowerBound.x, a.lowerBound.x)); var hD = Math.max(0, Math.min(a.upperBound.y, b.upperBound.y) - Math.max(b.lowerBound.y, a.lowerBound.y)); var wA = a.upperBound.x - a.lowerBound.x; var hA = a.upperBound.y - a.lowerBound.y; var wB = b.upperBound.x - b.lowerBound.x; var hB = b.upperBound.y - b.lowerBound.y; return wA * hA + wB * hB - wD * hD; }; AABB.prototype.rayCast = function(output, input) { var tmin = -Infinity; var tmax = Infinity; var p = input.p1; var d = Vec2.sub(input.p2, input.p1); var absD = Vec2.abs(d); var normal = Vec2.zero(); for (var f = "x"; f !== null; f = f === "x" ? "y" : null) { if (absD.x < Math.EPSILON) { if (p[f] < this.lowerBound[f] || this.upperBound[f] < p[f]) { return false; } } else { var inv_d = 1 / d[f]; var t1 = (this.lowerBound[f] - p[f]) * inv_d; var t2 = (this.upperBound[f] - p[f]) * inv_d; var s = -1; if (t1 > t2) { var temp = t1; t1 = t2, t2 = temp; s = 1; } if (t1 > tmin) { normal.setZero(); normal[f] = s; tmin = t1; } tmax = Math.min(tmax, t2); if (tmin > tmax) { return false; } } } if (tmin < 0 || input.maxFraction < tmin) { return false; } output.fraction = tmin; output.normal = normal; return true; }; AABB.prototype.toString = function() { return JSON.stringify(this); }; },{"../Settings":7,"../common/Math":18,"../common/Vec2":23}],12:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = require("../Settings"); var common = require("../util/common"); var Math = require("../common/Math"); var AABB = require("./AABB"); var DynamicTree = require("./DynamicTree"); module.exports = BroadPhase; function BroadPhase() { this.m_tree = new DynamicTree(); this.m_proxyCount = 0; this.m_moveBuffer = []; this.queryCallback = this.queryCallback.bind(this); } BroadPhase.prototype.getUserData = function(proxyId) { return this.m_tree.getUserData(proxyId); }; BroadPhase.prototype.testOverlap = function(proxyIdA, proxyIdB) { var aabbA = this.m_tree.getFatAABB(proxyIdA); var aabbB = this.m_tree.getFatAABB(proxyIdB); return AABB.testOverlap(aabbA, aabbB); }; BroadPhase.prototype.getFatAABB = function(proxyId) { return this.m_tree.getFatAABB(proxyId); }; BroadPhase.prototype.getProxyCount = function() { return this.m_proxyCount; }; BroadPhase.prototype.getTreeHeight = function() { return this.m_tree.getHeight(); }; BroadPhase.prototype.getTreeBalance = function() { return this.m_tree.getMaxBalance(); }; BroadPhase.prototype.getTreeQuality = function() { return this.m_tree.getAreaRatio(); }; BroadPhase.prototype.query = function(aabb, queryCallback) { this.m_tree.query(aabb, queryCallback); }; BroadPhase.prototype.rayCast = function(input, rayCastCallback) { this.m_tree.rayCast(input, rayCastCallback); }; BroadPhase.prototype.shiftOrigin = function(newOrigin) { this.m_tree.shiftOrigin(newOrigin); }; BroadPhase.prototype.createProxy = function(aabb, userData) { _ASSERT && common.assert(AABB.isValid(aabb)); var proxyId = this.m_tree.createProxy(aabb, userData); this.m_proxyCount++; this.bufferMove(proxyId); return proxyId; }; BroadPhase.prototype.destroyProxy = function(proxyId) { this.unbufferMove(proxyId); this.m_proxyCount--; this.m_tree.destroyProxy(proxyId); }; BroadPhase.prototype.moveProxy = function(proxyId, aabb, displacement) { _ASSERT && common.assert(AABB.isValid(aabb)); var changed = this.m_tree.moveProxy(proxyId, aabb, displacement); if (changed) { this.bufferMove(proxyId); } }; BroadPhase.prototype.touchProxy = function(proxyId) { this.bufferMove(proxyId); }; BroadPhase.prototype.bufferMove = function(proxyId) { this.m_moveBuffer.push(proxyId); }; BroadPhase.prototype.unbufferMove = function(proxyId) { for (var i = 0; i < this.m_moveBuffer.length; ++i) { if (this.m_moveBuffer[i] == proxyId) { this.m_moveBuffer[i] = null; } } }; BroadPhase.prototype.updatePairs = function(addPairCallback) { _ASSERT && common.assert(typeof addPairCallback === "function"); this.m_callback = addPairCallback; while (this.m_moveBuffer.length > 0) { this.m_queryProxyId = this.m_moveBuffer.pop(); if (this.m_queryProxyId === null) { continue; } var fatAABB = this.m_tree.getFatAABB(this.m_queryProxyId); this.m_tree.query(fatAABB, this.queryCallback); } }; BroadPhase.prototype.queryCallback = function(proxyId) { if (proxyId == this.m_queryProxyId) { return true; } var proxyIdA = Math.min(proxyId, this.m_queryProxyId); var proxyIdB = Math.max(proxyId, this.m_queryProxyId); var userDataA = this.m_tree.getUserData(proxyIdA); var userDataB = this.m_tree.getUserData(proxyIdB); this.m_callback(userDataA, userDataB); return true; }; },{"../Settings":7,"../common/Math":18,"../util/common":51,"./AABB":11,"./DynamicTree":14}],13:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Distance; module.exports.Input = DistanceInput; module.exports.Output = DistanceOutput; module.exports.Proxy = DistanceProxy; module.exports.Cache = SimplexCache; var Settings = require("../Settings"); var common = require("../util/common"); var stats = require("../common/stats"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); stats.gjkCalls = 0; stats.gjkIters = 0; stats.gjkMaxIters = 0; function DistanceInput() { this.proxyA = new DistanceProxy(); this.proxyB = new DistanceProxy(); this.transformA = null; this.transformB = null; this.useRadii = false; } function DistanceOutput() { this.pointA = Vec2.zero(); this.pointB = Vec2.zero(); this.distance; this.iterations; } function SimplexCache() { this.metric = 0; this.indexA = []; this.indexB = []; this.count = 0; } function Distance(output, cache, input) { ++stats.gjkCalls; var proxyA = input.proxyA; var proxyB = input.proxyB; var xfA = input.transformA; var xfB = input.transformB; var simplex = new Simplex(); simplex.readCache(cache, proxyA, xfA, proxyB, xfB); var vertices = simplex.m_v; var k_maxIters = Settings.maxDistnceIterations; var saveA = []; var saveB = []; var saveCount = 0; var distanceSqr1 = Infinity; var distanceSqr2 = Infinity; var iter = 0; while (iter < k_maxIters) { saveCount = simplex.m_count; for (var i = 0; i < saveCount; ++i) { saveA[i] = vertices[i].indexA; saveB[i] = vertices[i].indexB; } simplex.solve(); if (simplex.m_count == 3) { break; } var p = simplex.getClosestPoint(); distanceSqr2 = p.lengthSquared(); if (distanceSqr2 >= distanceSqr1) {} distanceSqr1 = distanceSqr2; var d = simplex.getSearchDirection(); if (d.lengthSquared() < Math.EPSILON * Math.EPSILON) { break; } var vertex = vertices[simplex.m_count]; vertex.indexA = proxyA.getSupport(Rot.mulTVec2(xfA.q, Vec2.neg(d))); vertex.wA = Transform.mulVec2(xfA, proxyA.getVertex(vertex.indexA)); vertex.indexB = proxyB.getSupport(Rot.mulTVec2(xfB.q, d)); vertex.wB = Transform.mulVec2(xfB, proxyB.getVertex(vertex.indexB)); vertex.w = Vec2.sub(vertex.wB, vertex.wA); ++iter; ++stats.gjkIters; var duplicate = false; for (var i = 0; i < saveCount; ++i) { if (vertex.indexA == saveA[i] && vertex.indexB == saveB[i]) { duplicate = true; break; } } if (duplicate) { break; } ++simplex.m_count; } stats.gjkMaxIters = Math.max(stats.gjkMaxIters, iter); simplex.getWitnessPoints(output.pointA, output.pointB); output.distance = Vec2.distance(output.pointA, output.pointB); output.iterations = iter; simplex.writeCache(cache); if (input.useRadii) { var rA = proxyA.m_radius; var rB = proxyB.m_radius; if (output.distance > rA + rB && output.distance > Math.EPSILON) { output.distance -= rA + rB; var normal = Vec2.sub(output.pointB, output.pointA); normal.normalize(); output.pointA.addMul(rA, normal); output.pointB.subMul(rB, normal); } else { var p = Vec2.mid(output.pointA, output.pointB); output.pointA.set(p); output.pointB.set(p); output.distance = 0; } } } function DistanceProxy() { this.m_buffer = []; this.m_vertices = []; this.m_count = 0; this.m_radius = 0; } DistanceProxy.prototype.getVertexCount = function() { return this.m_count; }; DistanceProxy.prototype.getVertex = function(index) { _ASSERT && common.assert(0 <= index && index < this.m_count); return this.m_vertices[index]; }; DistanceProxy.prototype.getSupport = function(d) { var bestIndex = 0; var bestValue = Vec2.dot(this.m_vertices[0], d); for (var i = 0; i < this.m_count; ++i) { var value = Vec2.dot(this.m_vertices[i], d); if (value > bestValue) { bestIndex = i; bestValue = value; } } return bestIndex; }; DistanceProxy.prototype.getSupportVertex = function(d) { return this.m_vertices[this.getSupport(d)]; }; DistanceProxy.prototype.set = function(shape, index) { _ASSERT && common.assert(typeof shape.computeDistanceProxy === "function"); shape.computeDistanceProxy(this, index); }; function SimplexVertex() { this.indexA; this.indexB; this.wA = Vec2.zero(); this.wB = Vec2.zero(); this.w = Vec2.zero(); this.a; } SimplexVertex.prototype.set = function(v) { this.indexA = v.indexA; this.indexB = v.indexB; this.wA = Vec2.clone(v.wA); this.wB = Vec2.clone(v.wB); this.w = Vec2.clone(v.w); this.a = v.a; }; function Simplex() { this.m_v1 = new SimplexVertex(); this.m_v2 = new SimplexVertex(); this.m_v3 = new SimplexVertex(); this.m_v = [ this.m_v1, this.m_v2, this.m_v3 ]; this.m_count; } Simplex.prototype.print = function() { if (this.m_count == 3) { return [ "+" + this.m_count, this.m_v1.a, this.m_v1.wA.x, this.m_v1.wA.y, this.m_v1.wB.x, this.m_v1.wB.y, this.m_v2.a, this.m_v2.wA.x, this.m_v2.wA.y, this.m_v2.wB.x, this.m_v2.wB.y, this.m_v3.a, this.m_v3.wA.x, this.m_v3.wA.y, this.m_v3.wB.x, this.m_v3.wB.y ].toString(); } else if (this.m_count == 2) { return [ "+" + this.m_count, this.m_v1.a, this.m_v1.wA.x, this.m_v1.wA.y, this.m_v1.wB.x, this.m_v1.wB.y, this.m_v2.a, this.m_v2.wA.x, this.m_v2.wA.y, this.m_v2.wB.x, this.m_v2.wB.y ].toString(); } else if (this.m_count == 1) { return [ "+" + this.m_count, this.m_v1.a, this.m_v1.wA.x, this.m_v1.wA.y, this.m_v1.wB.x, this.m_v1.wB.y ].toString(); } else { return "+" + this.m_count; } }; Simplex.prototype.readCache = function(cache, proxyA, transformA, proxyB, transformB) { _ASSERT && common.assert(cache.count <= 3); this.m_count = cache.count; for (var i = 0; i < this.m_count; ++i) { var v = this.m_v[i]; v.indexA = cache.indexA[i]; v.indexB = cache.indexB[i]; var wALocal = proxyA.getVertex(v.indexA); var wBLocal = proxyB.getVertex(v.indexB); v.wA = Transform.mulVec2(transformA, wALocal); v.wB = Transform.mulVec2(transformB, wBLocal); v.w = Vec2.sub(v.wB, v.wA); v.a = 0; } if (this.m_count > 1) { var metric1 = cache.metric; var metric2 = this.getMetric(); if (metric2 < .5 * metric1 || 2 * metric1 < metric2 || metric2 < Math.EPSILON) { this.m_count = 0; } } if (this.m_count == 0) { var v = this.m_v[0]; v.indexA = 0; v.indexB = 0; var wALocal = proxyA.getVertex(0); var wBLocal = proxyB.getVertex(0); v.wA = Transform.mulVec2(transformA, wALocal); v.wB = Transform.mulVec2(transformB, wBLocal); v.w = Vec2.sub(v.wB, v.wA); v.a = 1; this.m_count = 1; } }; Simplex.prototype.writeCache = function(cache) { cache.metric = this.getMetric(); cache.count = this.m_count; for (var i = 0; i < this.m_count; ++i) { cache.indexA[i] = this.m_v[i].indexA; cache.indexB[i] = this.m_v[i].indexB; } }; Simplex.prototype.getSearchDirection = function() { switch (this.m_count) { case 1: return Vec2.neg(this.m_v1.w); case 2: { var e12 = Vec2.sub(this.m_v2.w, this.m_v1.w); var sgn = Vec2.cross(e12, Vec2.neg(this.m_v1.w)); if (sgn > 0) { return Vec2.cross(1, e12); } else { return Vec2.cross(e12, 1); } } default: _ASSERT && common.assert(false); return Vec2.zero(); } }; Simplex.prototype.getClosestPoint = function() { switch (this.m_count) { case 0: _ASSERT && common.assert(false); return Vec2.zero(); case 1: return Vec2.clone(this.m_v1.w); case 2: return Vec2.combine(this.m_v1.a, this.m_v1.w, this.m_v2.a, this.m_v2.w); case 3: return Vec2.zero(); default: _ASSERT && common.assert(false); return Vec2.zero(); } }; Simplex.prototype.getWitnessPoints = function(pA, pB) { switch (this.m_count) { case 0: _ASSERT && common.assert(false); break; case 1: pA.set(this.m_v1.wA); pB.set(this.m_v1.wB); break; case 2: pA.setCombine(this.m_v1.a, this.m_v1.wA, this.m_v2.a, this.m_v2.wA); pB.setCombine(this.m_v1.a, this.m_v1.wB, this.m_v2.a, this.m_v2.wB); break; case 3: pA.setCombine(this.m_v1.a, this.m_v1.wA, this.m_v2.a, this.m_v2.wA); pA.addMul(this.m_v3.a, this.m_v3.wA); pB.set(pA); break; default: _ASSERT && common.assert(false); break; } }; Simplex.prototype.getMetric = function() { switch (this.m_count) { case 0: _ASSERT && common.assert(false); return 0; case 1: return 0; case 2: return Vec2.distance(this.m_v1.w, this.m_v2.w); case 3: return Vec2.cross(Vec2.sub(this.m_v2.w, this.m_v1.w), Vec2.sub(this.m_v3.w, this.m_v1.w)); default: _ASSERT && common.assert(false); return 0; } }; Simplex.prototype.solve = function() { switch (this.m_count) { case 1: break; case 2: this.solve2(); break; case 3: this.solve3(); break; default: _ASSERT && common.assert(false); } }; Simplex.prototype.solve2 = function() { var w1 = this.m_v1.w; var w2 = this.m_v2.w; var e12 = Vec2.sub(w2, w1); var d12_2 = -Vec2.dot(w1, e12); if (d12_2 <= 0) { this.m_v1.a = 1; this.m_count = 1; return; } var d12_1 = Vec2.dot(w2, e12); if (d12_1 <= 0) { this.m_v2.a = 1; this.m_count = 1; this.m_v1.set(this.m_v2); return; } var inv_d12 = 1 / (d12_1 + d12_2); this.m_v1.a = d12_1 * inv_d12; this.m_v2.a = d12_2 * inv_d12; this.m_count = 2; }; Simplex.prototype.solve3 = function() { var w1 = this.m_v1.w; var w2 = this.m_v2.w; var w3 = this.m_v3.w; var e12 = Vec2.sub(w2, w1); var w1e12 = Vec2.dot(w1, e12); var w2e12 = Vec2.dot(w2, e12); var d12_1 = w2e12; var d12_2 = -w1e12; var e13 = Vec2.sub(w3, w1); var w1e13 = Vec2.dot(w1, e13); var w3e13 = Vec2.dot(w3, e13); var d13_1 = w3e13; var d13_2 = -w1e13; var e23 = Vec2.sub(w3, w2); var w2e23 = Vec2.dot(w2, e23); var w3e23 = Vec2.dot(w3, e23); var d23_1 = w3e23; var d23_2 = -w2e23; var n123 = Vec2.cross(e12, e13); var d123_1 = n123 * Vec2.cross(w2, w3); var d123_2 = n123 * Vec2.cross(w3, w1); var d123_3 = n123 * Vec2.cross(w1, w2); if (d12_2 <= 0 && d13_2 <= 0) { this.m_v1.a = 1; this.m_count = 1; return; } if (d12_1 > 0 && d12_2 > 0 && d123_3 <= 0) { var inv_d12 = 1 / (d12_1 + d12_2); this.m_v1.a = d12_1 * inv_d12; this.m_v2.a = d12_2 * inv_d12; this.m_count = 2; return; } if (d13_1 > 0 && d13_2 > 0 && d123_2 <= 0) { var inv_d13 = 1 / (d13_1 + d13_2); this.m_v1.a = d13_1 * inv_d13; this.m_v3.a = d13_2 * inv_d13; this.m_count = 2; this.m_v2.set(this.m_v3); return; } if (d12_1 <= 0 && d23_2 <= 0) { this.m_v2.a = 1; this.m_count = 1; this.m_v1.set(this.m_v2); return; } if (d13_1 <= 0 && d23_1 <= 0) { this.m_v3.a = 1; this.m_count = 1; this.m_v1.set(this.m_v3); return; } if (d23_1 > 0 && d23_2 > 0 && d123_1 <= 0) { var inv_d23 = 1 / (d23_1 + d23_2); this.m_v2.a = d23_1 * inv_d23; this.m_v3.a = d23_2 * inv_d23; this.m_count = 2; this.m_v1.set(this.m_v3); return; } var inv_d123 = 1 / (d123_1 + d123_2 + d123_3); this.m_v1.a = d123_1 * inv_d123; this.m_v2.a = d123_2 * inv_d123; this.m_v3.a = d123_3 * inv_d123; this.m_count = 3; }; Distance.testOverlap = function(shapeA, indexA, shapeB, indexB, xfA, xfB) { var input = new DistanceInput(); input.proxyA.set(shapeA, indexA); input.proxyB.set(shapeB, indexB); input.transformA = xfA; input.transformB = xfB; input.useRadii = true; var cache = new SimplexCache(); var output = new DistanceOutput(); Distance(output, cache, input); return output.distance < 10 * Math.EPSILON; }; },{"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../common/stats":26,"../util/common":51}],14:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = require("../Settings"); var common = require("../util/common"); var Pool = require("../util/Pool"); var Vec2 = require("../common/Vec2"); var Math = require("../common/Math"); var AABB = require("./AABB"); module.exports = DynamicTree; var aabbPool = new Pool({ create: function() { return new AABB(); }, release: function(aabb) { aabb.lowerBound.setZero(); aabb.upperBound.setZero(); } }); var nodePool = new Pool({ create: function() { return new TreeNode(); } }); function TreeNode(id) { this.id = id; this.aabb = new AABB(); this.userData = null; this.parent = null; this.child1 = null; this.child2 = null; this.height = -1; this.toString = function() { return this.id + ": " + this.userData; }; } TreeNode.prototype.isLeaf = function() { return this.child1 == null; }; function DynamicTree() { this.m_root = null; this.m_nodes = {}; this.m_lastProxyId = 0; } DynamicTree.prototype.getUserData = function(id) { var node = this.m_nodes[id]; _ASSERT && common.assert(!!node); return node.userData; }; DynamicTree.prototype.getFatAABB = function(id) { var node = this.m_nodes[id]; _ASSERT && common.assert(!!node); return node.aabb; }; DynamicTree.prototype.allocateNode = function() { var node = nodePool.allocate(); node.id = ++this.m_lastProxyId; node.userData = null; node.parent = null; node.child1 = null; node.child2 = null; node.height = -1; this.m_nodes[node.id] = node; return node; }; DynamicTree.prototype.freeNode = function(node) { nodePool.release(node); node.height = -1; delete this.m_nodes[node.id]; }; DynamicTree.prototype.createProxy = function(aabb, userData) { _ASSERT && common.assert(AABB.isValid(aabb)); var node = this.allocateNode(); node.aabb.set(aabb); node.aabb.extend(Settings.aabbExtension); node.userData = userData; node.height = 0; this.insertLeaf(node); return node.id; }; DynamicTree.prototype.destroyProxy = function(id) { var node = this.m_nodes[id]; _ASSERT && common.assert(!!node); _ASSERT && common.assert(node.isLeaf()); this.removeLeaf(node); this.freeNode(node); }; DynamicTree.prototype.moveProxy = function(id, aabb, d) { _ASSERT && common.assert(AABB.isValid(aabb)); _ASSERT && common.assert(!d || Vec2.isValid(d)); var node = this.m_nodes[id]; _ASSERT && common.assert(!!node); _ASSERT && common.assert(node.isLeaf()); if (node.aabb.contains(aabb)) { return false; } this.removeLeaf(node); node.aabb.set(aabb); aabb = node.aabb; AABB.extend(aabb, Settings.aabbExtension); if (d.x < 0) { aabb.lowerBound.x += d.x * Settings.aabbMultiplier; } else { aabb.upperBound.x += d.x * Settings.aabbMultiplier; } if (d.y < 0) { aabb.lowerBound.y += d.y * Settings.aabbMultiplier; } else { aabb.upperBound.y += d.y * Settings.aabbMultiplier; } this.insertLeaf(node); return true; }; DynamicTree.prototype.insertLeaf = function(leaf) { _ASSERT && common.assert(AABB.isValid(leaf.aabb)); if (this.m_root == null) { this.m_root = leaf; this.m_root.parent = null; return; } var leafAABB = leaf.aabb; var index = this.m_root; while (index.isLeaf() == false) { var child1 = index.child1; var child2 = index.child2; var area = index.aabb.getPerimeter(); var combinedAABB = aabbPool.allocate(); combinedAABB.combine(index.aabb, leafAABB); var combinedArea = combinedAABB.getPerimeter(); aabbPool.release(combinedAABB); var cost = 2 * combinedArea; var inheritanceCost = 2 * (combinedArea - area); var cost1; if (child1.isLeaf()) { var aabb = aabbPool.allocate(); aabb.combine(leafAABB, child1.aabb); cost1 = aabb.getPerimeter() + inheritanceCost; aabbPool.release(aabb); } else { var aabb = aabbPool.allocate(); aabb.combine(leafAABB, child1.aabb); var oldArea = child1.aabb.getPerimeter(); var newArea = aabb.getPerimeter(); cost1 = newArea - oldArea + inheritanceCost; aabbPool.release(aabb); } var cost2; if (child2.isLeaf()) { var aabb = aabbPool.allocate(); aabb.combine(leafAABB, child2.aabb); cost2 = aabb.getPerimeter() + inheritanceCost; aabbPool.release(aabb); } else { var aabb = aabbPool.allocate(); aabb.combine(leafAABB, child2.aabb); var oldArea = child2.aabb.getPerimeter(); var newArea = aabb.getPerimeter(); cost2 = newArea - oldArea + inheritanceCost; aabbPool.release(aabb); } if (cost < cost1 && cost < cost2) { break; } if (cost1 < cost2) { index = child1; } else { index = child2; } } var sibling = index; var oldParent = sibling.parent; var newParent = this.allocateNode(); newParent.parent = oldParent; newParent.userData = null; newParent.aabb.combine(leafAABB, sibling.aabb); newParent.height = sibling.height + 1; if (oldParent != null) { if (oldParent.child1 == sibling) { oldParent.child1 = newParent; } else { oldParent.child2 = newParent; } newParent.child1 = sibling; newParent.child2 = leaf; sibling.parent = newParent; leaf.parent = newParent; } else { newParent.child1 = sibling; newParent.child2 = leaf; sibling.parent = newParent; leaf.parent = newParent; this.m_root = newParent; } index = leaf.parent; while (index != null) { index = this.balance(index); var child1 = index.child1; var child2 = index.child2; _ASSERT && common.assert(child1 != null); _ASSERT && common.assert(child2 != null); index.height = 1 + Math.max(child1.height, child2.height); index.aabb.combine(child1.aabb, child2.aabb); index = index.parent; } }; DynamicTree.prototype.removeLeaf = function(leaf) { if (leaf == this.m_root) { this.m_root = null; return; } var parent = leaf.parent; var grandParent = parent.parent; var sibling; if (parent.child1 == leaf) { sibling = parent.child2; } else { sibling = parent.child1; } if (grandParent != null) { if (grandParent.child1 == parent) { grandParent.child1 = sibling; } else { grandParent.child2 = sibling; } sibling.parent = grandParent; this.freeNode(parent); var index = grandParent; while (index != null) { index = this.balance(index); var child1 = index.child1; var child2 = index.child2; index.aabb.combine(child1.aabb, child2.aabb); index.height = 1 + Math.max(child1.height, child2.height); index = index.parent; } } else { this.m_root = sibling; sibling.parent = null; this.freeNode(parent); } }; DynamicTree.prototype.balance = function(iA) { _ASSERT && common.assert(iA != null); var A = iA; if (A.isLeaf() || A.height < 2) { return iA; } var B = A.child1; var C = A.child2; var balance = C.height - B.height; if (balance > 1) { var F = C.child1; var G = C.child2; C.child1 = A; C.parent = A.parent; A.parent = C; if (C.parent != null) { if (C.parent.child1 == iA) { C.parent.child1 = C; } else { C.parent.child2 = C; } } else { this.m_root = C; } if (F.height > G.height) { C.child2 = F; A.child2 = G; G.parent = A; A.aabb.combine(B.aabb, G.aabb); C.aabb.combine(A.aabb, F.aabb); A.height = 1 + Math.max(B.height, G.height); C.height = 1 + Math.max(A.height, F.height); } else { C.child2 = G; A.child2 = F; F.parent = A; A.aabb.combine(B.aabb, F.aabb); C.aabb.combine(A.aabb, G.aabb); A.height = 1 + Math.max(B.height, F.height); C.height = 1 + Math.max(A.height, G.height); } return C; } if (balance < -1) { var D = B.child1; var E = B.child2; B.child1 = A; B.parent = A.parent; A.parent = B; if (B.parent != null) { if (B.parent.child1 == A) { B.parent.child1 = B; } else { B.parent.child2 = B; } } else { this.m_root = B; } if (D.height > E.height) { B.child2 = D; A.child1 = E; E.parent = A; A.aabb.combine(C.aabb, E.aabb); B.aabb.combine(A.aabb, D.aabb); A.height = 1 + Math.max(C.height, E.height); B.height = 1 + Math.max(A.height, D.height); } else { B.child2 = E; A.child1 = D; D.parent = A; A.aabb.combine(C.aabb, D.aabb); B.aabb.combine(A.aabb, E.aabb); A.height = 1 + Math.max(C.height, D.height); B.height = 1 + Math.max(A.height, E.height); } return B; } return A; }; DynamicTree.prototype.getHeight = function() { if (this.m_root == null) { return 0; } return this.m_root.height; }; DynamicTree.prototype.getAreaRatio = function() { if (this.m_root == null) { return 0; } var root = this.m_root; var rootArea = root.aabb.getPerimeter(); var totalArea = 0; var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { if (node.height < 0) { continue; } totalArea += node.aabb.getPerimeter(); } iteratorPool.release(it); return totalArea / rootArea; }; DynamicTree.prototype.computeHeight = function(id) { var node; if (typeof id !== "undefined") { node = this.m_nodes[id]; } else { node = this.m_root; } if (node.isLeaf()) { return 0; } var height1 = ComputeHeight(node.child1); var height2 = ComputeHeight(node.child2); return 1 + Math.max(height1, height2); }; DynamicTree.prototype.validateStructure = function(node) { if (node == null) { return; } if (node == this.m_root) { _ASSERT && common.assert(node.parent == null); } var child1 = node.child1; var child2 = node.child2; if (node.isLeaf()) { _ASSERT && common.assert(child1 == null); _ASSERT && common.assert(child2 == null); _ASSERT && common.assert(node.height == 0); return; } _ASSERT && common.assert(child1.parent == node); _ASSERT && common.assert(child2.parent == node); this.validateStructure(child1); this.validateStructure(child2); }; DynamicTree.prototype.validateMetrics = function(node) { if (node == null) { return; } var child1 = node.child1; var child2 = node.child2; if (node.isLeaf()) { _ASSERT && common.assert(child1 == null); _ASSERT && common.assert(child2 == null); _ASSERT && common.assert(node.height == 0); return; } var height1 = this.m_nodes[child1].height; var height2 = this.m_nodes[child2].height; var height = 1 + Math.max(height1, height2); _ASSERT && common.assert(node.height == height); _ASSERT && common.assert(AABB.areEqual(new AABB().combine(child1.aabb, child2.aabb), node.aabb)); this.validateMetrics(child1); this.validateMetrics(child2); }; DynamicTree.prototype.validate = function() { ValidateStructure(this.m_root); ValidateMetrics(this.m_root); _ASSERT && common.assert(this.getHeight() == this.computeHeight()); }; DynamicTree.prototype.getMaxBalance = function() { var maxBalance = 0; var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { if (node.height <= 1) { continue; } _ASSERT && common.assert(node.isLeaf() == false); var balance = Math.abs(node.child2.height - node.child1.height); maxBalance = Math.max(maxBalance, balance); } iteratorPool.release(it); return maxBalance; }; DynamicTree.prototype.rebuildBottomUp = function() { var nodes = []; var count = 0; var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { if (node.height < 0) { continue; } if (node.isLeaf()) { node.parent = null; nodes[count] = node; ++count; } else { this.freeNode(node); } } iteratorPool.release(it); while (count > 1) { var minCost = Infinity; var iMin = -1, jMin = -1; for (var i = 0; i < count; ++i) { var aabbi = nodes[i].aabb; for (var j = i + 1; j < count; ++j) { var aabbj = nodes[j].aabb; var b = aabbPool.allocate(); b.combine(aabbi, aabbj); var cost = b.getPerimeter(); if (cost < minCost) { iMin = i; jMin = j; minCost = cost; } aabbPool.release(b); } } var child1 = nodes[iMin]; var child2 = nodes[jMin]; var parent = this.allocateNode(); parent.child1 = child1; parent.child2 = child2; parent.height = 1 + Math.max(child1.height, child2.height); parent.aabb.combine(child1.aabb, child2.aabb); parent.parent = null; child1.parent = parent; child2.parent = parent; nodes[jMin] = nodes[count - 1]; nodes[iMin] = parent; --count; } this.m_root = nodes[0]; this.validate(); }; DynamicTree.prototype.shiftOrigin = function(newOrigin) { var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { var aabb = node.aabb; aabb.lowerBound.x -= newOrigin.x; aabb.lowerBound.y -= newOrigin.y; aabb.upperBound.x -= newOrigin.x; aabb.upperBound.y -= newOrigin.y; } iteratorPool.release(it); }; DynamicTree.prototype.query = function(aabb, queryCallback) { _ASSERT && common.assert(typeof queryCallback === "function"); var stack = stackPool.allocate(); stack.push(this.m_root); while (stack.length > 0) { var node = stack.pop(); if (node == null) { continue; } if (AABB.testOverlap(node.aabb, aabb)) { if (node.isLeaf()) { var proceed = queryCallback(node.id); if (proceed == false) { return; } } else { stack.push(node.child1); stack.push(node.child2); } } } stackPool.release(stack); }; DynamicTree.prototype.rayCast = function(input, rayCastCallback) { _ASSERT && common.assert(typeof rayCastCallback === "function"); var p1 = input.p1; var p2 = input.p2; var r = Vec2.sub(p2, p1); _ASSERT && common.assert(r.lengthSquared() > 0); r.normalize(); var v = Vec2.cross(1, r); var abs_v = Vec2.abs(v); var maxFraction = input.maxFraction; var segmentAABB = new AABB(); var t = Vec2.combine(1 - maxFraction, p1, maxFraction, p2); segmentAABB.combinePoints(p1, t); var stack = stackPool.allocate(); var subInput = inputPool.allocate(); stack.push(this.m_root); while (stack.length > 0) { var node = stack.pop(); if (node == null) { continue; } if (AABB.testOverlap(node.aabb, segmentAABB) == false) { continue; } var c = node.aabb.getCenter(); var h = node.aabb.getExtents(); var separation = Math.abs(Vec2.dot(v, Vec2.sub(p1, c))) - Vec2.dot(abs_v, h); if (separation > 0) { continue; } if (node.isLeaf()) { subInput.p1 = Vec2.clone(input.p1); subInput.p2 = Vec2.clone(input.p2); subInput.maxFraction = maxFraction; var value = rayCastCallback(subInput, node.id); if (value == 0) { return; } if (value > 0) { maxFraction = value; t = Vec2.combine(1 - maxFraction, p1, maxFraction, p2); segmentAABB.combinePoints(p1, t); } } else { stack.push(node.child1); stack.push(node.child2); } } stackPool.release(stack); inputPool.release(subInput); }; var inputPool = new Pool({ create: function() { return {}; }, release: function(stack) {} }); var stackPool = new Pool({ create: function() { return []; }, release: function(stack) { stack.length = 0; } }); var iteratorPool = new Pool({ create: function() { return new Iterator(); }, release: function(iterator) { iterator.close(); } }); function Iterator() { var parents = []; var states = []; return { preorder: function(root) { parents.length = 0; parents.push(root); states.length = 0; states.push(0); return this; }, next: function() { while (parents.length > 0) { var i = parents.length - 1; var node = parents[i]; if (states[i] === 0) { states[i] = 1; return node; } if (states[i] === 1) { states[i] = 2; if (node.child1) { parents.push(node.child1); states.push(1); return node.child1; } } if (states[i] === 2) { states[i] = 3; if (node.child2) { parents.push(node.child2); states.push(1); return node.child2; } } parents.pop(); states.pop(); } }, close: function() { parents.length = 0; } }; } },{"../Settings":7,"../common/Math":18,"../common/Vec2":23,"../util/Pool":49,"../util/common":51,"./AABB":11}],15:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = TimeOfImpact; module.exports.Input = TOIInput; module.exports.Output = TOIOutput; var Settings = require("../Settings"); var common = require("../util/common"); var Timer = require("../util/Timer"); var stats = require("../common/stats"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Distance = require("./Distance"); var DistanceInput = Distance.Input; var DistanceOutput = Distance.Output; var DistanceProxy = Distance.Proxy; var SimplexCache = Distance.Cache; function TOIInput() { this.proxyA = new DistanceProxy(); this.proxyB = new DistanceProxy(); this.sweepA = new Sweep(); this.sweepB = new Sweep(); this.tMax; } TOIOutput.e_unknown = 0; TOIOutput.e_failed = 1; TOIOutput.e_overlapped = 2; TOIOutput.e_touching = 3; TOIOutput.e_separated = 4; function TOIOutput() { this.state; this.t; } stats.toiTime = 0; stats.toiMaxTime = 0; stats.toiCalls = 0; stats.toiIters = 0; stats.toiMaxIters = 0; stats.toiRootIters = 0; stats.toiMaxRootIters = 0; function TimeOfImpact(output, input) { var timer = Timer.now(); ++stats.toiCalls; output.state = TOIOutput.e_unknown; output.t = input.tMax; var proxyA = input.proxyA; var proxyB = input.proxyB; var sweepA = input.sweepA; var sweepB = input.sweepB; sweepA.normalize(); sweepB.normalize(); var tMax = input.tMax; var totalRadius = proxyA.m_radius + proxyB.m_radius; var target = Math.max(Settings.linearSlop, totalRadius - 3 * Settings.linearSlop); var tolerance = .25 * Settings.linearSlop; _ASSERT && common.assert(target > tolerance); var t1 = 0; var k_maxIterations = Settings.maxTOIIterations; var iter = 0; var cache = new SimplexCache(); var distanceInput = new DistanceInput(); distanceInput.proxyA = input.proxyA; distanceInput.proxyB = input.proxyB; distanceInput.useRadii = false; for (;;) { var xfA = Transform.identity(); var xfB = Transform.identity(); sweepA.getTransform(xfA, t1); sweepB.getTransform(xfB, t1); distanceInput.transformA = xfA; distanceInput.transformB = xfB; var distanceOutput = new DistanceOutput(); Distance(distanceOutput, cache, distanceInput); if (distanceOutput.distance <= 0) { output.state = TOIOutput.e_overlapped; output.t = 0; break; } if (distanceOutput.distance < target + tolerance) { output.state = TOIOutput.e_touching; output.t = t1; break; } var fcn = new SeparationFunction(); fcn.initialize(cache, proxyA, sweepA, proxyB, sweepB, t1); if (false) { var N = 100; var dx = 1 / N; var xs = []; var fs = []; var x = 0; for (var i = 0; i <= N; ++i) { sweepA.getTransform(xfA, x); sweepB.getTransform(xfB, x); var f = fcn.evaluate(xfA, xfB) - target; printf("%g %g\n", x, f); xs[i] = x; fs[i] = f; x += dx; } } var done = false; var t2 = tMax; var pushBackIter = 0; for (;;) { var s2 = fcn.findMinSeparation(t2); var indexA = fcn.indexA; var indexB = fcn.indexB; if (s2 > target + tolerance) { output.state = TOIOutput.e_separated; output.t = tMax; done = true; break; } if (s2 > target - tolerance) { t1 = t2; break; } var s1 = fcn.evaluate(t1); var indexA = fcn.indexA; var indexB = fcn.indexB; if (s1 < target - tolerance) { output.state = TOIOutput.e_failed; output.t = t1; done = true; break; } if (s1 <= target + tolerance) { output.state = TOIOutput.e_touching; output.t = t1; done = true; break; } var rootIterCount = 0; var a1 = t1, a2 = t2; for (;;) { var t; if (rootIterCount & 1) { t = a1 + (target - s1) * (a2 - a1) / (s2 - s1); } else { t = .5 * (a1 + a2); } ++rootIterCount; ++stats.toiRootIters; var s = fcn.evaluate(t); var indexA = fcn.indexA; var indexB = fcn.indexB; if (Math.abs(s - target) < tolerance) { t2 = t; break; } if (s > target) { a1 = t; s1 = s; } else { a2 = t; s2 = s; } if (rootIterCount == 50) { break; } } stats.toiMaxRootIters = Math.max(stats.toiMaxRootIters, rootIterCount); ++pushBackIter; if (pushBackIter == Settings.maxPolygonVertices) { break; } } ++iter; ++stats.toiIters; if (done) { break; } if (iter == k_maxIterations) { output.state = TOIOutput.e_failed; output.t = t1; break; } } stats.toiMaxIters = Math.max(stats.toiMaxIters, iter); var time = Timer.diff(timer); stats.toiMaxTime = Math.max(stats.toiMaxTime, time); stats.toiTime += time; } var e_points = 1; var e_faceA = 2; var e_faceB = 3; function SeparationFunction() { this.m_proxyA = new DistanceProxy(); this.m_proxyB = new DistanceProxy(); this.m_sweepA; this.m_sweepB; this.m_type; this.m_localPoint = Vec2.zero(); this.m_axis = Vec2.zero(); } SeparationFunction.prototype.initialize = function(cache, proxyA, sweepA, proxyB, sweepB, t1) { this.m_proxyA = proxyA; this.m_proxyB = proxyB; var count = cache.count; _ASSERT && common.assert(0 < count && count < 3); this.m_sweepA = sweepA; this.m_sweepB = sweepB; var xfA = Transform.identity(); var xfB = Transform.identity(); this.m_sweepA.getTransform(xfA, t1); this.m_sweepB.getTransform(xfB, t1); if (count == 1) { this.m_type = e_points; var localPointA = this.m_proxyA.getVertex(cache.indexA[0]); var localPointB = this.m_proxyB.getVertex(cache.indexB[0]); var pointA = Transform.mulVec2(xfA, localPointA); var pointB = Transform.mulVec2(xfB, localPointB); this.m_axis.setCombine(1, pointB, -1, pointA); var s = this.m_axis.normalize(); return s; } else if (cache.indexA[0] == cache.indexA[1]) { this.m_type = e_faceB; var localPointB1 = proxyB.getVertex(cache.indexB[0]); var localPointB2 = proxyB.getVertex(cache.indexB[1]); this.m_axis = Vec2.cross(Vec2.sub(localPointB2, localPointB1), 1); this.m_axis.normalize(); var normal = Rot.mulVec2(xfB.q, this.m_axis); this.m_localPoint = Vec2.mid(localPointB1, localPointB2); var pointB = Transform.mulVec2(xfB, this.m_localPoint); var localPointA = proxyA.getVertex(cache.indexA[0]); var pointA = Transform.mulVec2(xfA, localPointA); var s = Vec2.dot(pointA, normal) - Vec2.dot(pointB, normal); if (s < 0) { this.m_axis = Vec2.neg(this.m_axis); s = -s; } return s; } else { this.m_type = e_faceA; var localPointA1 = this.m_proxyA.getVertex(cache.indexA[0]); var localPointA2 = this.m_proxyA.getVertex(cache.indexA[1]); this.m_axis = Vec2.cross(Vec2.sub(localPointA2, localPointA1), 1); this.m_axis.normalize(); var normal = Rot.mulVec2(xfA.q, this.m_axis); this.m_localPoint = Vec2.mid(localPointA1, localPointA2); var pointA = Transform.mulVec2(xfA, this.m_localPoint); var localPointB = this.m_proxyB.getVertex(cache.indexB[0]); var pointB = Transform.mulVec2(xfB, localPointB); var s = Vec2.dot(pointB, normal) - Vec2.dot(pointA, normal); if (s < 0) { this.m_axis = Vec2.neg(this.m_axis); s = -s; } return s; } }; SeparationFunction.prototype.compute = function(find, t) { var xfA = Transform.identity(); var xfB = Transform.identity(); this.m_sweepA.getTransform(xfA, t); this.m_sweepB.getTransform(xfB, t); switch (this.m_type) { case e_points: { if (find) { var axisA = Rot.mulTVec2(xfA.q, this.m_axis); var axisB = Rot.mulTVec2(xfB.q, Vec2.neg(this.m_axis)); this.indexA = this.m_proxyA.getSupport(axisA); this.indexB = this.m_proxyB.getSupport(axisB); } var localPointA = this.m_proxyA.getVertex(this.indexA); var localPointB = this.m_proxyB.getVertex(this.indexB); var pointA = Transform.mulVec2(xfA, localPointA); var pointB = Transform.mulVec2(xfB, localPointB); var sep = Vec2.dot(pointB, this.m_axis) - Vec2.dot(pointA, this.m_axis); return sep; } case e_faceA: { var normal = Rot.mulVec2(xfA.q, this.m_axis); var pointA = Transform.mulVec2(xfA, this.m_localPoint); if (find) { var axisB = Rot.mulTVec2(xfB.q, Vec2.neg(normal)); this.indexA = -1; this.indexB = this.m_proxyB.getSupport(axisB); } var localPointB = this.m_proxyB.getVertex(this.indexB); var pointB = Transform.mulVec2(xfB, localPointB); var sep = Vec2.dot(pointB, normal) - Vec2.dot(pointA, normal); return sep; } case e_faceB: { var normal = Rot.mulVec2(xfB.q, this.m_axis); var pointB = Transform.mulVec2(xfB, this.m_localPoint); if (find) { var axisA = Rot.mulTVec2(xfA.q, Vec2.neg(normal)); this.indexB = -1; this.indexA = this.m_proxyA.getSupport(axisA); } var localPointA = this.m_proxyA.getVertex(this.indexA); var pointA = Transform.mulVec2(xfA, localPointA); var sep = Vec2.dot(pointA, normal) - Vec2.dot(pointB, normal); return sep; } default: _ASSERT && common.assert(false); if (find) { this.indexA = -1; this.indexB = -1; } return 0; } }; SeparationFunction.prototype.findMinSeparation = function(t) { return this.compute(true, t); }; SeparationFunction.prototype.evaluate = function(t) { return this.compute(false, t); }; },{"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../common/stats":26,"../util/Timer":50,"../util/common":51,"./Distance":13}],16:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Mat22; var common = require("../util/common"); var Math = require("./Math"); var Vec2 = require("./Vec2"); function Mat22(a, b, c, d) { if (typeof a === "object" && a !== null) { this.ex = Vec2.clone(a); this.ey = Vec2.clone(b); } else if (typeof a === "number") { this.ex = Vec2.neo(a, c); this.ey = Vec2.neo(b, d); } else { this.ex = Vec2.zero(); this.ey = Vec2.zero(); } } Mat22.prototype.toString = function() { return JSON.stringify(this); }; Mat22.isValid = function(o) { return o && Vec2.isValid(o.ex) && Vec2.isValid(o.ey); }; Mat22.assert = function(o) { if (!_ASSERT) return; if (!Mat22.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Mat22!"); } }; Mat22.prototype.set = function(a, b, c, d) { if (typeof a === "number" && typeof b === "number" && typeof c === "number" && typeof d === "number") { this.ex.set(a, c); this.ey.set(b, d); } else if (typeof a === "object" && typeof b === "object") { this.ex.set(a); this.ey.set(b); } else if (typeof a === "object") { _ASSERT && Mat22.assert(a); this.ex.set(a.ex); this.ey.set(a.ey); } else { _ASSERT && common.assert(false); } }; Mat22.prototype.setIdentity = function() { this.ex.x = 1; this.ey.x = 0; this.ex.y = 0; this.ey.y = 1; }; Mat22.prototype.setZero = function() { this.ex.x = 0; this.ey.x = 0; this.ex.y = 0; this.ey.y = 0; }; Mat22.prototype.getInverse = function() { var a = this.ex.x; var b = this.ey.x; var c = this.ex.y; var d = this.ey.y; var det = a * d - b * c; if (det != 0) { det = 1 / det; } var imx = new Mat22(); imx.ex.x = det * d; imx.ey.x = -det * b; imx.ex.y = -det * c; imx.ey.y = det * a; return imx; }; Mat22.prototype.solve = function(v) { _ASSERT && Vec2.assert(v); var a = this.ex.x; var b = this.ey.x; var c = this.ex.y; var d = this.ey.y; var det = a * d - b * c; if (det != 0) { det = 1 / det; } var w = Vec2.zero(); w.x = det * (d * v.x - b * v.y); w.y = det * (a * v.y - c * v.x); return w; }; Mat22.mul = function(mx, v) { if (v && "x" in v && "y" in v) { _ASSERT && Vec2.assert(v); var x = mx.ex.x * v.x + mx.ey.x * v.y; var y = mx.ex.y * v.x + mx.ey.y * v.y; return Vec2.neo(x, y); } else if (v && "ex" in v && "ey" in v) { _ASSERT && Mat22.assert(v); return new Mat22(Vec2.mul(mx, v.ex), Vec2.mul(mx, v.ey)); } _ASSERT && common.assert(false); }; Mat22.mulVec2 = function(mx, v) { _ASSERT && Vec2.assert(v); var x = mx.ex.x * v.x + mx.ey.x * v.y; var y = mx.ex.y * v.x + mx.ey.y * v.y; return Vec2.neo(x, y); }; Mat22.mulVec2_ = function(mx, v, _) { _ASSERT && Vec2.assert(v); var x = mx.ex.x * v.x + mx.ey.x * v.y; var y = mx.ex.y * v.x + mx.ey.y * v.y; return _.set(x, y); }; Mat22.mulMat22 = function(mx, v) { _ASSERT && Mat22.assert(v); return new Mat22(Vec2.mul(mx, v.ex), Vec2.mul(mx, v.ey)); _ASSERT && common.assert(false); }; Mat22.mulT = function(mx, v) { if (v && "x" in v && "y" in v) { _ASSERT && Vec2.assert(v); return Vec2.neo(Vec2.dot(v, mx.ex), Vec2.dot(v, mx.ey)); } else if (v && "ex" in v && "ey" in v) { _ASSERT && Mat22.assert(v); var c1 = Vec2.neo(Vec2.dot(mx.ex, v.ex), Vec2.dot(mx.ey, v.ex)); var c2 = Vec2.neo(Vec2.dot(mx.ex, v.ey), Vec2.dot(mx.ey, v.ey)); return new Mat22(c1, c2); } _ASSERT && common.assert(false); }; Mat22.mulTVec2 = function(mx, v) { _ASSERT && Mat22.assert(mx); _ASSERT && Vec2.assert(v); return Vec2.neo(Vec2.dot(v, mx.ex), Vec2.dot(v, mx.ey)); }; Mat22.mulTMat22 = function(mx, v) { _ASSERT && Mat22.assert(mx); _ASSERT && Mat22.assert(v); var c1 = Vec2.neo(Vec2.dot(mx.ex, v.ex), Vec2.dot(mx.ey, v.ex)); var c2 = Vec2.neo(Vec2.dot(mx.ex, v.ey), Vec2.dot(mx.ey, v.ey)); return new Mat22(c1, c2); }; Mat22.abs = function(mx) { _ASSERT && Mat22.assert(mx); return new Mat22(Vec2.abs(mx.ex), Vec2.abs(mx.ey)); }; Mat22.add = function(mx1, mx2) { _ASSERT && Mat22.assert(mx1); _ASSERT && Mat22.assert(mx2); return new Mat22(Vec2.add(mx1.ex + mx2.ex), Vec2.add(mx1.ey + mx2.ey)); }; },{"../util/common":51,"./Math":18,"./Vec2":23}],17:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Mat33; var common = require("../util/common"); var Math = require("./Math"); var Vec2 = require("./Vec2"); var Vec3 = require("./Vec3"); function Mat33(a, b, c) { if (typeof a === "object" && a !== null) { this.ex = Vec3.clone(a); this.ey = Vec3.clone(b); this.ez = Vec3.clone(c); } else { this.ex = Vec3(); this.ey = Vec3(); this.ez = Vec3(); } } Mat33.prototype.toString = function() { return JSON.stringify(this); }; Mat33.isValid = function(o) { return o && Vec3.isValid(o.ex) && Vec3.isValid(o.ey) && Vec3.isValid(o.ez); }; Mat33.assert = function(o) { if (!_ASSERT) return; if (!Mat33.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Mat33!"); } }; Mat33.prototype.setZero = function() { this.ex.setZero(); this.ey.setZero(); this.ez.setZero(); return this; }; Mat33.prototype.solve33 = function(v) { var det = Vec3.dot(this.ex, Vec3.cross(this.ey, this.ez)); if (det != 0) { det = 1 / det; } var r = new Vec3(); r.x = det * Vec3.dot(v, Vec3.cross(this.ey, this.ez)); r.y = det * Vec3.dot(this.ex, Vec3.cross(v, this.ez)); r.z = det * Vec3.dot(this.ex, Vec3.cross(this.ey, v)); return r; }; Mat33.prototype.solve22 = function(v) { var a11 = this.ex.x; var a12 = this.ey.x; var a21 = this.ex.y; var a22 = this.ey.y; var det = a11 * a22 - a12 * a21; if (det != 0) { det = 1 / det; } var r = Vec2.zero(); r.x = det * (a22 * v.x - a12 * v.y); r.y = det * (a11 * v.y - a21 * v.x); return r; }; Mat33.prototype.getInverse22 = function(M) { var a = this.ex.x; var b = this.ey.x; var c = this.ex.y; var d = this.ey.y; var det = a * d - b * c; if (det != 0) { det = 1 / det; } M.ex.x = det * d; M.ey.x = -det * b; M.ex.z = 0; M.ex.y = -det * c; M.ey.y = det * a; M.ey.z = 0; M.ez.x = 0; M.ez.y = 0; M.ez.z = 0; }; Mat33.prototype.getSymInverse33 = function(M) { var det = Vec3.dot(this.ex, Vec3.cross(this.ey, this.ez)); if (det != 0) { det = 1 / det; } var a11 = this.ex.x; var a12 = this.ey.x; var a13 = this.ez.x; var a22 = this.ey.y; var a23 = this.ez.y; var a33 = this.ez.z; M.ex.x = det * (a22 * a33 - a23 * a23); M.ex.y = det * (a13 * a23 - a12 * a33); M.ex.z = det * (a12 * a23 - a13 * a22); M.ey.x = M.ex.y; M.ey.y = det * (a11 * a33 - a13 * a13); M.ey.z = det * (a13 * a12 - a11 * a23); M.ez.x = M.ex.z; M.ez.y = M.ey.z; M.ez.z = det * (a11 * a22 - a12 * a12); }; Mat33.mul = function(a, b) { _ASSERT && Mat33.assert(a); if (b && "z" in b && "y" in b && "x" in b) { _ASSERT && Vec3.assert(b); var x = a.ex.x * b.x + a.ey.x * b.y + a.ez.x * b.z; var y = a.ex.y * b.x + a.ey.y * b.y + a.ez.y * b.z; var z = a.ex.z * b.x + a.ey.z * b.y + a.ez.z * b.z; return new Vec3(x, y, z); } else if (b && "y" in b && "x" in b) { _ASSERT && Vec2.assert(b); var x = a.ex.x * b.x + a.ey.x * b.y; var y = a.ex.y * b.x + a.ey.y * b.y; return Vec2.neo(x, y); } _ASSERT && common.assert(false); }; Mat33.mulVec3 = function(a, b) { _ASSERT && Mat33.assert(a); _ASSERT && Vec3.assert(b); var x = a.ex.x * b.x + a.ey.x * b.y + a.ez.x * b.z; var y = a.ex.y * b.x + a.ey.y * b.y + a.ez.y * b.z; var z = a.ex.z * b.x + a.ey.z * b.y + a.ez.z * b.z; return new Vec3(x, y, z); }; Mat33.mulVec2 = function(a, b) { _ASSERT && Mat33.assert(a); _ASSERT && Vec2.assert(b); var x = a.ex.x * b.x + a.ey.x * b.y; var y = a.ex.y * b.x + a.ey.y * b.y; return Vec2.neo(x, y); }; Mat33.add = function(a, b) { _ASSERT && Mat33.assert(a); _ASSERT && Mat33.assert(b); return new Mat33(Vec3.add(a.ex + b.ex), Vec3.add(a.ey + b.ey), Vec3.add(a.ez + b.ez)); }; },{"../util/common":51,"./Math":18,"./Vec2":23,"./Vec3":24}],18:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var native = Math; var math = module.exports = create(native); math.EPSILON = 1e-9; math.isFinite = function(x) { return typeof x === "number" && isFinite(x) && !isNaN(x); }; math.assert = function(x) { if (!_ASSERT) return; if (!math.isFinite(x)) { _DEBUG && common.debug(x); throw new Error("Invalid Number!"); } }; math.invSqrt = function(x) { return 1 / native.sqrt(x); }; math.nextPowerOfTwo = function(x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x + 1; }; math.isPowerOfTwo = function(x) { return x > 0 && (x & x - 1) == 0; }; math.mod = function(num, min, max) { if (typeof min === "undefined") { max = 1, min = 0; } else if (typeof max === "undefined") { max = min, min = 0; } if (max > min) { num = (num - min) % (max - min); return num + (num < 0 ? max : min); } else { num = (num - max) % (min - max); return num + (num <= 0 ? min : max); } }; math.clamp = function(num, min, max) { if (num < min) { return min; } else if (num > max) { return max; } else { return num; } }; math.random = function(min, max) { if (typeof min === "undefined") { max = 1; min = 0; } else if (typeof max === "undefined") { max = min; min = 0; } return min == max ? min : native.random() * (max - min) + min; }; },{"../util/common":51,"../util/create":52}],19:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Position; var Vec2 = require("./Vec2"); var Rot = require("./Rot"); function Position() { this.c = Vec2.zero(); this.a = 0; } Position.prototype.getTransform = function(xf, p) { xf.q.set(this.a); xf.p.set(Vec2.sub(this.c, Rot.mulVec2(xf.q, p))); return xf; }; },{"./Rot":20,"./Vec2":23}],20:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Rot; var common = require("../util/common"); var Vec2 = require("./Vec2"); var Math = require("./Math"); function Rot(angle) { if (!(this instanceof Rot)) { return new Rot(angle); } if (typeof angle === "number") { this.setAngle(angle); } else if (typeof angle === "object") { this.set(angle); } else { this.setIdentity(); } } Rot.neo = function(angle) { var obj = Object.create(Rot.prototype); obj.setAngle(angle); return obj; }; Rot.clone = function(rot) { _ASSERT && Rot.assert(rot); var obj = Object.create(Rot.prototype); obj.s = rot.s; obj.c = rot.c; return obj; }; Rot.identity = function() { var obj = Object.create(Rot.prototype); obj.s = 0; obj.c = 1; return obj; }; Rot.isValid = function(o) { return o && Math.isFinite(o.s) && Math.isFinite(o.c); }; Rot.assert = function(o) { if (!_ASSERT) return; if (!Rot.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Rot!"); } }; Rot.prototype.setIdentity = function() { this.s = 0; this.c = 1; return this; }; Rot.prototype.set = function(angle) { if (typeof angle === "object") { _ASSERT && Rot.assert(angle); this.s = angle.s; this.c = angle.c; } else { _ASSERT && Math.assert(angle); this.s = Math.sin(angle); this.c = Math.cos(angle); } }; Rot.prototype.setAngle = function(angle) { _ASSERT && Math.assert(angle); this.s = Math.sin(angle); this.c = Math.cos(angle); }; Rot.prototype.getAngle = function() { return Math.atan2(this.s, this.c); }; Rot.prototype.getXAxis = function() { return Vec2.neo(this.c, this.s); }; Rot.prototype.getYAxis = function() { return Vec2.neo(-this.s, this.c); }; Rot.mul = function(rot, m) { _ASSERT && Rot.assert(rot); if ("c" in m && "s" in m) { _ASSERT && Rot.assert(m); var qr = Rot.identity(); qr.s = rot.s * m.c + rot.c * m.s; qr.c = rot.c * m.c - rot.s * m.s; return qr; } else if ("x" in m && "y" in m) { _ASSERT && Vec2.assert(m); return Vec2.neo(rot.c * m.x - rot.s * m.y, rot.s * m.x + rot.c * m.y); } }; Rot.mulRot = function(rot, m) { _ASSERT && Rot.assert(rot); _ASSERT && Rot.assert(m); var qr = Rot.identity(); qr.s = rot.s * m.c + rot.c * m.s; qr.c = rot.c * m.c - rot.s * m.s; return qr; }; Rot.mulVec2 = function(rot, m) { _ASSERT && Rot.assert(rot); _ASSERT && Vec2.assert(m); return Vec2.neo(rot.c * m.x - rot.s * m.y, rot.s * m.x + rot.c * m.y); }; Rot.mulVec2_ = function(rot, m, _) { _ASSERT && Rot.assert(rot); _ASSERT && Vec2.assert(m); return _.set(rot.c * m.x - rot.s * m.y, rot.s * m.x + rot.c * m.y); }; Rot.mulSub = function(rot, v, w) { var x = rot.c * (v.x - w.x) - rot.s * (v.y - w.y); var y = rot.s * (v.x - w.y) + rot.c * (v.y - w.y); return Vec2.neo(x, y); }; Rot.mulT = function(rot, m) { if ("c" in m && "s" in m) { _ASSERT && Rot.assert(m); var qr = Rot.identity(); qr.s = rot.c * m.s - rot.s * m.c; qr.c = rot.c * m.c + rot.s * m.s; return qr; } else if ("x" in m && "y" in m) { _ASSERT && Vec2.assert(m); return Vec2.neo(rot.c * m.x + rot.s * m.y, -rot.s * m.x + rot.c * m.y); } }; Rot.mulTRot = function(rot, m) { _ASSERT && Rot.assert(m); var qr = Rot.identity(); qr.s = rot.c * m.s - rot.s * m.c; qr.c = rot.c * m.c + rot.s * m.s; return qr; }; Rot.mulTRot_ = function(rot, m, _) { _ASSERT && Rot.assert(m); var qr = _.setIdentity(); qr.s = rot.c * m.s - rot.s * m.c; qr.c = rot.c * m.c + rot.s * m.s; return qr; }; Rot.mulTVec2 = function(rot, m) { _ASSERT && Vec2.assert(m); return Vec2.neo(rot.c * m.x + rot.s * m.y, -rot.s * m.x + rot.c * m.y); }; Rot.mulTVec2_ = function(rot, m, _) { _ASSERT && Vec2.assert(m); return _.set(rot.c * m.x + rot.s * m.y, -rot.s * m.x + rot.c * m.y); }; },{"../util/common":51,"./Math":18,"./Vec2":23}],21:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Sweep; var common = require("../util/common"); var Math = require("./Math"); var Vec2 = require("./Vec2"); var Rot = require("./Rot"); var Transform = require("./Transform"); function Sweep(c, a) { _ASSERT && common.assert(typeof c === "undefined"); _ASSERT && common.assert(typeof a === "undefined"); this.localCenter = Vec2.zero(); this.c = Vec2.zero(); this.a = 0; this.alpha0 = 0; this.c0 = Vec2.zero(); this.a0 = 0; } Sweep.prototype.setTransform = function(xf) { var c = Transform.mulVec2(xf, this.localCenter); this.c.set(c); this.c0.set(c); this.a = xf.q.getAngle(); this.a0 = xf.q.getAngle(); }; Sweep.prototype.setLocalCenter = function(localCenter, xf) { this.localCenter.set(localCenter); var c = Transform.mulVec2(xf, this.localCenter); this.c.set(c); this.c0.set(c); }; Sweep.prototype.getTransform = function(xf, beta) { beta = typeof beta === "undefined" ? 0 : beta; xf.q.setAngle((1 - beta) * this.a0 + beta * this.a); xf.p.setCombine(1 - beta, this.c0, beta, this.c); xf.p.sub(Rot.mulVec2(xf.q, this.localCenter)); }; Sweep.prototype.advance = function(alpha) { _ASSERT && common.assert(this.alpha0 < 1); var beta = (alpha - this.alpha0) / (1 - this.alpha0); this.c0.setCombine(beta, this.c, 1 - beta, this.c0); this.a0 = beta * this.a + (1 - beta) * this.a0; this.alpha0 = alpha; }; Sweep.prototype.forward = function() { this.a0 = this.a; this.c0.set(this.c); }; Sweep.prototype.normalize = function() { var a0 = Math.mod(this.a0, -Math.PI, +Math.PI); this.a -= this.a0 - a0; this.a0 = a0; }; Sweep.prototype.clone = function() { var clone = new Sweep(); clone.localCenter.set(this.localCenter); clone.alpha0 = this.alpha0; clone.a0 = this.a0; clone.a = this.a; clone.c0.set(this.c0); clone.c.set(this.c); return clone; }; Sweep.prototype.set = function(that) { this.localCenter.set(that.localCenter); this.alpha0 = that.alpha0; this.a0 = that.a0; this.a = that.a; this.c0.set(that.c0); this.c.set(that.c); }; },{"../util/common":51,"./Math":18,"./Rot":20,"./Transform":22,"./Vec2":23}],22:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Transform; var common = require("../util/common"); var Vec2 = require("./Vec2"); var Rot = require("./Rot"); function Transform(position, rotation) { if (!(this instanceof Transform)) { return new Transform(position, rotation); } this.p = Vec2.zero(); this.q = Rot.identity(); if (typeof position !== "undefined") { this.p.set(position); } if (typeof rotation !== "undefined") { this.q.set(rotation); } } Transform.clone = function(xf) { var obj = Object.create(Transform.prototype); obj.p = Vec2.clone(xf.p); obj.q = Rot.clone(xf.q); return obj; }; Transform.neo = function(position, rotation) { var obj = Object.create(Transform.prototype); obj.p = Vec2.clone(position); obj.q = Rot.clone(rotation); return obj; }; Transform.identity = function() { var obj = Object.create(Transform.prototype); obj.p = Vec2.zero(); obj.q = Rot.identity(); return obj; }; Transform.prototype.setIdentity = function() { this.p.setZero(); this.q.setIdentity(); return this; }; Transform.prototype.set = function(a, b) { if (typeof b === "undefined") { this.p.set(a.p); this.q.set(a.q); } else { this.p.set(a); this.q.set(b); } }; Transform.isValid = function(o) { return o && Vec2.isValid(o.p) && Rot.isValid(o.q); }; Transform.assert = function(o) { if (!_ASSERT) return; if (!Transform.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Transform!"); } }; Transform.mul = function(a, b) { _ASSERT && Transform.assert(a); if (Array.isArray(b)) { var arr = []; for (var i = 0; i < b.length; i++) { arr[i] = Transform.mul(a, b[i]); } return arr; } else if ("x" in b && "y" in b) { _ASSERT && Vec2.assert(b); var x = a.q.c * b.x - a.q.s * b.y + a.p.x; var y = a.q.s * b.x + a.q.c * b.y + a.p.y; return Vec2.neo(x, y); } else if ("p" in b && "q" in b) { _ASSERT && Transform.assert(b); var xf = Transform.identity(); xf.q = Rot.mulRot(a.q, b.q); xf.p = Vec2.add(Rot.mulVec2(a.q, b.p), a.p); return xf; } }; Transform.mulAll = function(a, b) { _ASSERT && Transform.assert(a); var arr = []; for (var i = 0; i < b.length; i++) { arr[i] = Transform.mul(a, b[i]); } return arr; }; Transform.mulFn = function(a) { _ASSERT && Transform.assert(a); return function(b) { return Transform.mul(a, b); }; }; Transform.mulVec2 = function(a, b) { _ASSERT && Transform.assert(a); _ASSERT && Vec2.assert(b); var x = a.q.c * b.x - a.q.s * b.y + a.p.x; var y = a.q.s * b.x + a.q.c * b.y + a.p.y; return Vec2.neo(x, y); }; Transform.mulVec2_ = function(a, b, _) { _ASSERT && Transform.assert(a); _ASSERT && Vec2.assert(b); var x = a.q.c * b.x - a.q.s * b.y + a.p.x; var y = a.q.s * b.x + a.q.c * b.y + a.p.y; return _.set(x, y); }; Transform.mulXf = function(a, b) { _ASSERT && Transform.assert(a); _ASSERT && Transform.assert(b); var xf = Transform.identity(); xf.q = Rot.mulRot(a.q, b.q); xf.p = Vec2.add(Rot.mulVec2(a.q, b.p), a.p); return xf; }; Transform.mulT = function(a, b) { _ASSERT && Transform.assert(a); if ("x" in b && "y" in b) { _ASSERT && Vec2.assert(b); var px = b.x - a.p.x; var py = b.y - a.p.y; var x = a.q.c * px + a.q.s * py; var y = -a.q.s * px + a.q.c * py; return Vec2.neo(x, y); } else if ("p" in b && "q" in b) { _ASSERT && Transform.assert(b); var xf = Transform.identity(); xf.q.set(Rot.mulTRot(a.q, b.q)); xf.p.set(Rot.mulTVec2(a.q, Vec2.sub(b.p, a.p))); return xf; } }; Transform.mulTVec2 = function(a, b) { _ASSERT && Transform.assert(a); _ASSERT && Vec2.assert(b); var px = b.x - a.p.x; var py = b.y - a.p.y; var x = a.q.c * px + a.q.s * py; var y = -a.q.s * px + a.q.c * py; return Vec2.neo(x, y); }; Transform.mulTVec2_ = function(a, b, _) { _ASSERT && Transform.assert(a); _ASSERT && Vec2.assert(b); var px = b.x - a.p.x; var py = b.y - a.p.y; var x = a.q.c * px + a.q.s * py; var y = -a.q.s * px + a.q.c * py; return _.set(x, y); }; Transform.mulTXf = function(a, b) { _ASSERT && Transform.assert(a); _ASSERT && Transform.assert(b); var xf = Transform.identity(); xf.q.set(Rot.mulTRot(a.q, b.q)); xf.p.set(Rot.mulTVec2(a.q, Vec2.sub(b.p, a.p))); return xf; }; var _vt1 = Vec2.zero(); Transform.mulTXf_ = function(a, b, _) { _ASSERT && Transform.assert(a); _ASSERT && Transform.assert(b); Rot.mulTRot_(a.q, b.q, _.q); Rot.mulTVec2_(a.q, Vec2.sub(b.p, a.p, _vt1), _.p); return _; }; },{"../util/common":51,"./Rot":20,"./Vec2":23}],23:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Vec2; var common = require("../util/common"); var Math = require("./Math"); function Vec2(x, y) { if (!(this instanceof Vec2)) { return new Vec2(x, y); } if (typeof x === "undefined") { this.x = 0; this.y = 0; } else if (typeof x === "object") { this.x = x.x; this.y = x.y; } else { this.x = x; this.y = y; } _ASSERT && Vec2.assert(this); } Vec2.zero = function() { var obj = Object.create(Vec2.prototype); obj.x = 0; obj.y = 0; return obj; }; Vec2.neo = function(x, y) { var obj = Object.create(Vec2.prototype); obj.x = x; obj.y = y; return obj; }; Vec2.clone = function(v) { _ASSERT && Vec2.assert(v); return Vec2.neo(v.x, v.y); }; Vec2.prototype.toString = function() { return JSON.stringify(this); }; Vec2.isValid = function(v) { return v && Math.isFinite(v.x) && Math.isFinite(v.y); }; Vec2.assert = function(o) { if (!_ASSERT) return; if (!Vec2.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Vec2!"); } }; Vec2.prototype.clone = function() { return Vec2.clone(this); }; Vec2.prototype.setZero = function() { this.x = 0; this.y = 0; return this; }; Vec2.prototype.set = function(x, y) { if (typeof x === "object") { _ASSERT && Vec2.assert(x); this.x = x.x; this.y = x.y; } else { _ASSERT && Math.assert(x); _ASSERT && Math.assert(y); this.x = x; this.y = y; } return this; }; Vec2.prototype.setXY = function(x, y) { this.x = x; this.y = y; return this; }; Vec2.prototype.setVec2 = function(x) { this.x = x.x; this.y = x.y; return this; }; Vec2.prototype.wSet = function(a, v, b, w) { if (typeof b !== "undefined" || typeof w !== "undefined") { return this.setCombine(a, v, b, w); } else { return this.setMul(a, v); } }; Vec2.prototype.setCombine = function(a, v, b, w) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); _ASSERT && Math.assert(b); _ASSERT && Vec2.assert(w); var x = a * v.x + b * w.x; var y = a * v.y + b * w.y; this.x = x; this.y = y; return this; }; Vec2.prototype.setMul = function(a, v) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; this.x = x; this.y = y; return this; }; Vec2.prototype.add = function(w) { _ASSERT && Vec2.assert(w); this.x += w.x; this.y += w.y; return this; }; Vec2.prototype.wAdd = function(a, v, b, w) { if (typeof b !== "undefined" || typeof w !== "undefined") { return this.addCombine(a, v, b, w); } else { return this.addMul(a, v); } }; Vec2.prototype.addCombine = function(a, v, b, w) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); _ASSERT && Math.assert(b); _ASSERT && Vec2.assert(w); var x = a * v.x + b * w.x; var y = a * v.y + b * w.y; this.x += x; this.y += y; return this; }; Vec2.prototype.addMul = function(a, v) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; this.x += x; this.y += y; return this; }; Vec2.prototype.wSub = function(a, v, b, w) { if (typeof b !== "undefined" || typeof w !== "undefined") { return this.subCombine(a, v, b, w); } else { return this.subMul(a, v); } }; Vec2.prototype.subCombine = function(a, v, b, w) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); _ASSERT && Math.assert(b); _ASSERT && Vec2.assert(w); var x = a * v.x + b * w.x; var y = a * v.y + b * w.y; this.x -= x; this.y -= y; return this; }; Vec2.prototype.subMul = function(a, v) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; this.x -= x; this.y -= y; return this; }; Vec2.prototype.sub = function(w) { _ASSERT && Vec2.assert(w); this.x -= w.x; this.y -= w.y; return this; }; Vec2.prototype.mul = function(m) { _ASSERT && Math.assert(m); this.x *= m; this.y *= m; return this; }; Vec2.prototype.length = function() { return Vec2.lengthOf(this); }; Vec2.prototype.lengthSquared = function() { return Vec2.lengthSquared(this); }; Vec2.prototype.normalize = function() { var length = this.length(); if (length < Math.EPSILON) { return 0; } var invLength = 1 / length; this.x *= invLength; this.y *= invLength; return length; }; Vec2.lengthOf = function(v) { _ASSERT && Vec2.assert(v); return Math.sqrt(v.x * v.x + v.y * v.y); }; Vec2.lengthSquared = function(v) { _ASSERT && Vec2.assert(v); return v.x * v.x + v.y * v.y; }; Vec2.distance = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); var dx = v.x - w.x, dy = v.y - w.y; return Math.sqrt(dx * dx + dy * dy); }; Vec2.distanceSquared = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); var dx = v.x - w.x, dy = v.y - w.y; return dx * dx + dy * dy; }; Vec2.areEqual = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return v == w || typeof w === "object" && w !== null && v.x === w.x && v.y === w.y; }; Vec2.skew = function(v) { _ASSERT && Vec2.assert(v); return Vec2.neo(-v.y, v.x); }; Vec2.dot = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return v.x * w.x + v.y * w.y; }; Vec2.cross = function(v, w) { if (typeof w === "number") { _ASSERT && Vec2.assert(v); _ASSERT && Math.assert(w); return Vec2.neo(w * v.y, -w * v.x); } else if (typeof v === "number") { _ASSERT && Math.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo(-v * w.y, v * w.x); } else { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return v.x * w.y - v.y * w.x; } }; Vec2.crossVec2Vec2 = function(v, w) { return v.x * w.y - v.y * w.x; }; Vec2.crossNumVec2_ = function(v, w, _) { return _.setXY(-v * w.y, v * w.x); }; Vec2.crossVec2Num_ = function(v, w, _) { return _.setXY(w * v.y, -w * v.x); }; Vec2.addCross = function(a, v, w) { if (typeof w === "number") { _ASSERT && Vec2.assert(v); _ASSERT && Math.assert(w); return Vec2.neo(w * v.y + a.x, -w * v.x + a.y); } else if (typeof v === "number") { _ASSERT && Math.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo(-v * w.y + a.x, v * w.x + a.y); } _ASSERT && common.assert(false); }; Vec2.add = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo(v.x + w.x, v.y + w.y); }; Vec2.wAdd = function(a, v, b, w) { if (typeof b !== "undefined" || typeof w !== "undefined") { return Vec2.combine(a, v, b, w); } else { return Vec2.mul(a, v); } }; Vec2.combine = function(a, v, b, w) { return Vec2.zero().setCombine(a, v, b, w); }; Vec2.combine_ = function(a, v, b, w, _) { return _.setCombine(a, v, b, w); }; Vec2.sub = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo(v.x - w.x, v.y - w.y); }; Vec2.sub_ = function(v, w, _) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return _.setXY(v.x - w.x, v.y - w.y); }; Vec2.mul = function(a, b) { if (typeof a === "object") { _ASSERT && Vec2.assert(a); _ASSERT && Math.assert(b); return Vec2.neo(a.x * b, a.y * b); } else if (typeof b === "object") { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(b); return Vec2.neo(a * b.x, a * b.y); } }; Vec2.mulVec2Num_ = function(a, b, _) { return _.setXY(a.x * b, a.y * b); }; Vec2.mulNumVec2_ = function(a, b, _) { return _.setXY(a * b.x, a * b.y); }; Vec2.prototype.neg = function() { this.x = -this.x; this.y = -this.y; return this; }; Vec2.neg = function(v) { _ASSERT && Vec2.assert(v); return Vec2.neo(-v.x, -v.y); }; Vec2.neg_ = function(v, _) { _ASSERT && Vec2.assert(v); return _.setXY(-v.x, -v.y); }; Vec2.abs = function(v) { _ASSERT && Vec2.assert(v); return Vec2.neo(Math.abs(v.x), Math.abs(v.y)); }; Vec2.mid = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo((v.x + w.x) * .5, (v.y + w.y) * .5); }; Vec2.upper = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo(Math.max(v.x, w.x), Math.max(v.y, w.y)); }; Vec2.lower = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo(Math.min(v.x, w.x), Math.min(v.y, w.y)); }; Vec2.prototype.clamp = function(max) { var lengthSqr = this.x * this.x + this.y * this.y; if (lengthSqr > max * max) { var invLength = Math.invSqrt(lengthSqr); this.x *= invLength * max; this.y *= invLength * max; } return this; }; Vec2.clamp = function(v, max) { v = Vec2.neo(v.x, v.y); v.clamp(max); return v; }; Vec2.scaleFn = function(x, y) { return function(v) { return Vec2.neo(v.x * x, v.y * y); }; }; Vec2.translateFn = function(x, y) { return function(v) { return Vec2.neo(v.x + x, v.y + y); }; }; },{"../util/common":51,"./Math":18}],24:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Vec3; var common = require("../util/common"); var Math = require("./Math"); function Vec3(x, y, z) { if (!(this instanceof Vec3)) { return new Vec3(x, y, z); } if (typeof x === "undefined") { this.x = 0, this.y = 0, this.z = 0; } else if (typeof x === "object") { this.x = x.x, this.y = x.y, this.z = x.z; } else { this.x = x, this.y = y, this.z = z; } _ASSERT && Vec3.assert(this); } Vec3.neo = function(x, y, z) { var obj = Object.create(Vec3.prototype); obj.x = x; obj.y = y; obj.z = z; return obj; }; Vec3.clone = function(v) { _ASSERT && Vec3.assert(v); return Vec3.neo(v.x, v.y, v.z); }; Vec3.prototype.toString = function() { return JSON.stringify(this); }; Vec3.isValid = function(v) { return v && Math.isFinite(v.x) && Math.isFinite(v.y) && Math.isFinite(v.z); }; Vec3.assert = function(o) { if (!_ASSERT) return; if (!Vec3.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Vec3!"); } }; Vec3.prototype.setZero = function() { this.x = 0; this.y = 0; this.z = 0; return this; }; Vec3.prototype.set = function(x, y, z) { this.x = x; this.y = y; this.z = z; return this; }; Vec3.prototype.add = function(w) { this.x += w.x; this.y += w.y; this.z += w.z; return this; }; Vec3.prototype.sub = function(w) { this.x -= w.x; this.y -= w.y; this.z -= w.z; return this; }; Vec3.prototype.mul = function(m) { this.x *= m; this.y *= m; this.z *= m; return this; }; Vec3.areEqual = function(v, w) { _ASSERT && Vec3.assert(v); _ASSERT && Vec3.assert(w); return v == w || typeof v === "object" && v !== null && typeof w === "object" && w !== null && v.x === w.x && v.y === w.y && v.z === w.z; }; Vec3.dot = function(v, w) { return v.x * w.x + v.y * w.y + v.z * w.z; }; Vec3.cross = function(v, w) { return new Vec3(v.y * w.z - v.z * w.y, v.z * w.x - v.x * w.z, v.x * w.y - v.y * w.x); }; Vec3.add = function(v, w) { return new Vec3(v.x + w.x, v.y + w.y, v.z + w.z); }; Vec3.sub = function(v, w) { return new Vec3(v.x - w.x, v.y - w.y, v.z - w.z); }; Vec3.mul = function(v, m) { return new Vec3(m * v.x, m * v.y, m * v.z); }; Vec3.prototype.neg = function() { this.x = -this.x; this.y = -this.y; this.z = -this.z; return this; }; Vec3.neg = function(v) { return new Vec3(-v.x, -v.y, -v.z); }; },{"../util/common":51,"./Math":18}],25:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Velocity; var Vec2 = require("./Vec2"); function Velocity() { this.v = Vec2.zero(); this.w = 0; } },{"./Vec2":23}],26:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; exports.toString = function(newline) { newline = typeof newline === "string" ? newline : "\n"; var string = ""; for (var name in this) { if (typeof this[name] !== "function" && typeof this[name] !== "object") { string += name + ": " + this[name] + newline; } } return string; }; },{}],27:[function(require,module,exports){ exports.internal = {}; exports.Math = require("./common/Math"); exports.Vec2 = require("./common/Vec2"); exports.Vec3 = require("./common/Vec3"); exports.Mat22 = require("./common/Mat22"); exports.Mat33 = require("./common/Mat33"); exports.Transform = require("./common/Transform"); exports.Rot = require("./common/Rot"); exports.AABB = require("./collision/AABB"); exports.Shape = require("./Shape"); exports.Fixture = require("./Fixture"); exports.Body = require("./Body"); exports.Contact = require("./Contact"); exports.Joint = require("./Joint"); exports.World = require("./World"); exports.Circle = require("./shape/CircleShape"); exports.Edge = require("./shape/EdgeShape"); exports.Polygon = require("./shape/PolygonShape"); exports.Chain = require("./shape/ChainShape"); exports.Box = require("./shape/BoxShape"); require("./shape/CollideCircle"); require("./shape/CollideEdgeCircle"); exports.internal.CollidePolygons = require("./shape/CollidePolygon"); require("./shape/CollideCirclePolygone"); require("./shape/CollideEdgePolygon"); exports.DistanceJoint = require("./joint/DistanceJoint"); exports.FrictionJoint = require("./joint/FrictionJoint"); exports.GearJoint = require("./joint/GearJoint"); exports.MotorJoint = require("./joint/MotorJoint"); exports.MouseJoint = require("./joint/MouseJoint"); exports.PrismaticJoint = require("./joint/PrismaticJoint"); exports.PulleyJoint = require("./joint/PulleyJoint"); exports.RevoluteJoint = require("./joint/RevoluteJoint"); exports.RopeJoint = require("./joint/RopeJoint"); exports.WeldJoint = require("./joint/WeldJoint"); exports.WheelJoint = require("./joint/WheelJoint"); exports.internal.Sweep = require("./common/Sweep"); exports.internal.stats = require("./common/stats"); exports.internal.Manifold = require("./Manifold"); exports.internal.Distance = require("./collision/Distance"); exports.internal.TimeOfImpact = require("./collision/TimeOfImpact"); exports.internal.DynamicTree = require("./collision/DynamicTree"); exports.internal.Settings = require("./Settings"); },{"./Body":2,"./Contact":3,"./Fixture":4,"./Joint":5,"./Manifold":6,"./Settings":7,"./Shape":8,"./World":10,"./collision/AABB":11,"./collision/Distance":13,"./collision/DynamicTree":14,"./collision/TimeOfImpact":15,"./common/Mat22":16,"./common/Mat33":17,"./common/Math":18,"./common/Rot":20,"./common/Sweep":21,"./common/Transform":22,"./common/Vec2":23,"./common/Vec3":24,"./common/stats":26,"./joint/DistanceJoint":28,"./joint/FrictionJoint":29,"./joint/GearJoint":30,"./joint/MotorJoint":31,"./joint/MouseJoint":32,"./joint/PrismaticJoint":33,"./joint/PulleyJoint":34,"./joint/RevoluteJoint":35,"./joint/RopeJoint":36,"./joint/WeldJoint":37,"./joint/WheelJoint":38,"./shape/BoxShape":39,"./shape/ChainShape":40,"./shape/CircleShape":41,"./shape/CollideCircle":42,"./shape/CollideCirclePolygone":43,"./shape/CollideEdgeCircle":44,"./shape/CollideEdgePolygon":45,"./shape/CollidePolygon":46,"./shape/EdgeShape":47,"./shape/PolygonShape":48}],28:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = DistanceJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); DistanceJoint.TYPE = "distance-joint"; DistanceJoint._super = Joint; DistanceJoint.prototype = create(DistanceJoint._super.prototype); var DEFAULTS = { frequencyHz: 0, dampingRatio: 0 }; function DistanceJoint(def, bodyA, bodyB, anchorA, anchorB) { if (!(this instanceof DistanceJoint)) { return new DistanceJoint(def, bodyA, bodyB, anchorA, anchorB); } if (bodyB && anchorA && "m_type" in anchorA && "x" in bodyB && "y" in bodyB) { var temp = bodyB; bodyB = anchorA; anchorA = temp; } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = DistanceJoint.TYPE; this.m_localAnchorA = anchorA ? bodyA.getLocalPoint(anchorA) : def.localAnchorA || Vec2.zero(); this.m_localAnchorB = anchorB ? bodyB.getLocalPoint(anchorB) : def.localAnchorB || Vec2.zero(); this.m_length = Math.isFinite(def.length) ? def.length : Vec2.distance(bodyA.getWorldPoint(this.m_localAnchorA), bodyB.getWorldPoint(this.m_localAnchorB)); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_impulse = 0; this.m_gamma = 0; this.m_bias = 0; this.m_u; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass; } DistanceJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; DistanceJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; DistanceJoint.prototype.setLength = function(length) { this.m_length = length; }; DistanceJoint.prototype.getLength = function() { return this.m_length; }; DistanceJoint.prototype.setFrequency = function(hz) { this.m_frequencyHz = hz; }; DistanceJoint.prototype.getFrequency = function() { return this.m_frequencyHz; }; DistanceJoint.prototype.setDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; DistanceJoint.prototype.getDampingRatio = function() { return this.m_dampingRatio; }; DistanceJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; DistanceJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; DistanceJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(this.m_impulse, this.m_u).mul(inv_dt); }; DistanceJoint.prototype.getReactionTorque = function(inv_dt) { return 0; }; DistanceJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); this.m_u = Vec2.sub(Vec2.add(cB, this.m_rB), Vec2.add(cA, this.m_rA)); var length = this.m_u.length(); if (length > Settings.linearSlop) { this.m_u.mul(1 / length); } else { this.m_u.set(0, 0); } var crAu = Vec2.cross(this.m_rA, this.m_u); var crBu = Vec2.cross(this.m_rB, this.m_u); var invMass = this.m_invMassA + this.m_invIA * crAu * crAu + this.m_invMassB + this.m_invIB * crBu * crBu; this.m_mass = invMass != 0 ? 1 / invMass : 0; if (this.m_frequencyHz > 0) { var C = length - this.m_length; var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * this.m_mass * this.m_dampingRatio * omega; var k = this.m_mass * omega * omega; var h = step.dt; this.m_gamma = h * (d + h * k); this.m_gamma = this.m_gamma != 0 ? 1 / this.m_gamma : 0; this.m_bias = C * h * k * this.m_gamma; invMass += this.m_gamma; this.m_mass = invMass != 0 ? 1 / invMass : 0; } else { this.m_gamma = 0; this.m_bias = 0; } if (step.warmStarting) { this.m_impulse *= step.dtRatio; var P = Vec2.mul(this.m_impulse, this.m_u); vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.addMul(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; DistanceJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vpA = Vec2.add(vA, Vec2.cross(wA, this.m_rA)); var vpB = Vec2.add(vB, Vec2.cross(wB, this.m_rB)); var Cdot = Vec2.dot(this.m_u, vpB) - Vec2.dot(this.m_u, vpA); var impulse = -this.m_mass * (Cdot + this.m_bias + this.m_gamma * this.m_impulse); this.m_impulse += impulse; var P = Vec2.mul(impulse, this.m_u); vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.addMul(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; DistanceJoint.prototype.solvePositionConstraints = function(step) { if (this.m_frequencyHz > 0) { return true; } var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB); var u = Vec2.sub(Vec2.add(cB, rB), Vec2.add(cA, rA)); var length = u.normalize(); var C = length - this.m_length; C = Math.clamp(C, -Settings.maxLinearCorrection, Settings.maxLinearCorrection); var impulse = -this.m_mass * C; var P = Vec2.mul(impulse, u); cA.subMul(this.m_invMassA, P); aA -= this.m_invIA * Vec2.cross(rA, P); cB.addMul(this.m_invMassB, P); aB += this.m_invIB * Vec2.cross(rB, P); this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return Math.abs(C) < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],29:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = FrictionJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); FrictionJoint.TYPE = "friction-joint"; FrictionJoint._super = Joint; FrictionJoint.prototype = create(FrictionJoint._super.prototype); var DEFAULTS = { maxForce: 0, maxTorque: 0 }; function FrictionJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof FrictionJoint)) { return new FrictionJoint(def, bodyA, bodyB, anchor); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = FrictionJoint.TYPE; this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero(); this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero(); this.m_linearImpulse = Vec2.zero(); this.m_angularImpulse = 0; this.m_maxForce = def.maxForce; this.m_maxTorque = def.maxTorque; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_linearMass; this.m_angularMass; } FrictionJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; FrictionJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; FrictionJoint.prototype.setMaxForce = function(force) { _ASSERT && common.assert(Math.isFinite(force) && force >= 0); this.m_maxForce = force; }; FrictionJoint.prototype.getMaxForce = function() { return this.m_maxForce; }; FrictionJoint.prototype.setMaxTorque = function(torque) { _ASSERT && common.assert(Math.isFinite(torque) && torque >= 0); this.m_maxTorque = torque; }; FrictionJoint.prototype.getMaxTorque = function() { return this.m_maxTorque; }; FrictionJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; FrictionJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; FrictionJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(inv_dt, this.m_linearImpulse); }; FrictionJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_angularImpulse; }; FrictionJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA), qB = Rot.neo(aB); this.m_rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var K = new Mat22(); K.ex.x = mA + mB + iA * this.m_rA.y * this.m_rA.y + iB * this.m_rB.y * this.m_rB.y; K.ex.y = -iA * this.m_rA.x * this.m_rA.y - iB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * this.m_rA.x * this.m_rA.x + iB * this.m_rB.x * this.m_rB.x; this.m_linearMass = K.getInverse(); this.m_angularMass = iA + iB; if (this.m_angularMass > 0) { this.m_angularMass = 1 / this.m_angularMass; } if (step.warmStarting) { this.m_linearImpulse.mul(step.dtRatio); this.m_angularImpulse *= step.dtRatio; var P = Vec2.neo(this.m_linearImpulse.x, this.m_linearImpulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_angularImpulse); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_angularImpulse); } else { this.m_linearImpulse.setZero(); this.m_angularImpulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; FrictionJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var h = step.dt; { var Cdot = wB - wA; var impulse = -this.m_angularMass * Cdot; var oldImpulse = this.m_angularImpulse; var maxImpulse = h * this.m_maxTorque; this.m_angularImpulse = Math.clamp(this.m_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } { var Cdot = Vec2.sub(Vec2.add(vB, Vec2.cross(wB, this.m_rB)), Vec2.add(vA, Vec2.cross(wA, this.m_rA))); var impulse = Vec2.neg(Mat22.mulVec2(this.m_linearMass, Cdot)); var oldImpulse = this.m_linearImpulse; this.m_linearImpulse.add(impulse); var maxImpulse = h * this.m_maxForce; if (this.m_linearImpulse.lengthSquared() > maxImpulse * maxImpulse) { this.m_linearImpulse.normalize(); this.m_linearImpulse.mul(maxImpulse); } impulse = Vec2.sub(this.m_linearImpulse, oldImpulse); vA.subMul(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.addMul(mB, impulse); wB += iB * Vec2.cross(this.m_rB, impulse); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; FrictionJoint.prototype.solvePositionConstraints = function(step) { return true; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],30:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = GearJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var RevoluteJoint = require("./RevoluteJoint"); var PrismaticJoint = require("./PrismaticJoint"); GearJoint.TYPE = "gear-joint"; GearJoint._super = Joint; GearJoint.prototype = create(GearJoint._super.prototype); var DEFAULTS = { ratio: 1 }; function GearJoint(def, bodyA, bodyB, joint1, joint2, ratio) { if (!(this instanceof GearJoint)) { return new GearJoint(def, bodyA, bodyB, joint1, joint2, ratio); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = GearJoint.TYPE; _ASSERT && common.assert(joint1.m_type === RevoluteJoint.TYPE || joint1.m_type === PrismaticJoint.TYPE); _ASSERT && common.assert(joint2.m_type === RevoluteJoint.TYPE || joint2.m_type === PrismaticJoint.TYPE); this.m_joint1 = joint1 ? joint1 : def.joint1; this.m_joint2 = joint2 ? joint2 : def.joint2; this.m_ratio = Math.isFinite(ratio) ? ratio : def.ratio; this.m_type1 = this.m_joint1.getType(); this.m_type2 = this.m_joint2.getType(); var coordinateA, coordinateB; this.m_bodyC = this.m_joint1.getBodyA(); this.m_bodyA = this.m_joint1.getBodyB(); var xfA = this.m_bodyA.m_xf; var aA = this.m_bodyA.m_sweep.a; var xfC = this.m_bodyC.m_xf; var aC = this.m_bodyC.m_sweep.a; if (this.m_type1 === RevoluteJoint.TYPE) { var revolute = this.m_joint1; this.m_localAnchorC = revolute.m_localAnchorA; this.m_localAnchorA = revolute.m_localAnchorB; this.m_referenceAngleA = revolute.m_referenceAngle; this.m_localAxisC = Vec2.zero(); coordinateA = aA - aC - this.m_referenceAngleA; } else { var prismatic = this.m_joint1; this.m_localAnchorC = prismatic.m_localAnchorA; this.m_localAnchorA = prismatic.m_localAnchorB; this.m_referenceAngleA = prismatic.m_referenceAngle; this.m_localAxisC = prismatic.m_localXAxisA; var pC = this.m_localAnchorC; var pA = Rot.mulTVec2(xfC.q, Vec2.add(Rot.mul(xfA.q, this.m_localAnchorA), Vec2.sub(xfA.p, xfC.p))); coordinateA = Vec2.dot(pA, this.m_localAxisC) - Vec2.dot(pC, this.m_localAxisC); } this.m_bodyD = this.m_joint2.getBodyA(); this.m_bodyB = this.m_joint2.getBodyB(); var xfB = this.m_bodyB.m_xf; var aB = this.m_bodyB.m_sweep.a; var xfD = this.m_bodyD.m_xf; var aD = this.m_bodyD.m_sweep.a; if (this.m_type2 === RevoluteJoint.TYPE) { var revolute = this.m_joint2; this.m_localAnchorD = revolute.m_localAnchorA; this.m_localAnchorB = revolute.m_localAnchorB; this.m_referenceAngleB = revolute.m_referenceAngle; this.m_localAxisD = Vec2.zero(); coordinateB = aB - aD - this.m_referenceAngleB; } else { var prismatic = this.m_joint2; this.m_localAnchorD = prismatic.m_localAnchorA; this.m_localAnchorB = prismatic.m_localAnchorB; this.m_referenceAngleB = prismatic.m_referenceAngle; this.m_localAxisD = prismatic.m_localXAxisA; var pD = this.m_localAnchorD; var pB = Rot.mulTVec2(xfD.q, Vec2.add(Rot.mul(xfB.q, this.m_localAnchorB), Vec2.sub(xfB.p, xfD.p))); coordinateB = Vec2.dot(pB, this.m_localAxisD) - Vec2.dot(pD, this.m_localAxisD); } this.m_constant = coordinateA + this.m_ratio * coordinateB; this.m_impulse = 0; this.m_lcA, this.m_lcB, this.m_lcC, this.m_lcD; this.m_mA, this.m_mB, this.m_mC, this.m_mD; this.m_iA, this.m_iB, this.m_iC, this.m_iD; this.m_JvAC, this.m_JvBD; this.m_JwA, this.m_JwB, this.m_JwC, this.m_JwD; this.m_mass; } GearJoint.prototype.getJoint1 = function() { return this.m_joint1; }; GearJoint.prototype.getJoint2 = function() { return this.m_joint2; }; GearJoint.prototype.setRatio = function(ratio) { _ASSERT && common.assert(Math.isFinite(ratio)); this.m_ratio = ratio; }; GearJoint.prototype.getRatio = function() { return this.m_ratio; }; GearJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; GearJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; GearJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(this.m_impulse, this.m_JvAC).mul(inv_dt); }; GearJoint.prototype.getReactionTorque = function(inv_dt) { var L = this.m_impulse * this.m_JwA; return inv_dt * L; }; GearJoint.prototype.initVelocityConstraints = function(step) { this.m_lcA = this.m_bodyA.m_sweep.localCenter; this.m_lcB = this.m_bodyB.m_sweep.localCenter; this.m_lcC = this.m_bodyC.m_sweep.localCenter; this.m_lcD = this.m_bodyD.m_sweep.localCenter; this.m_mA = this.m_bodyA.m_invMass; this.m_mB = this.m_bodyB.m_invMass; this.m_mC = this.m_bodyC.m_invMass; this.m_mD = this.m_bodyD.m_invMass; this.m_iA = this.m_bodyA.m_invI; this.m_iB = this.m_bodyB.m_invI; this.m_iC = this.m_bodyC.m_invI; this.m_iD = this.m_bodyD.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var aC = this.m_bodyC.c_position.a; var vC = this.m_bodyC.c_velocity.v; var wC = this.m_bodyC.c_velocity.w; var aD = this.m_bodyD.c_position.a; var vD = this.m_bodyD.c_velocity.v; var wD = this.m_bodyD.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var qC = Rot.neo(aC); var qD = Rot.neo(aD); this.m_mass = 0; if (this.m_type1 == RevoluteJoint.TYPE) { this.m_JvAC = Vec2.zero(); this.m_JwA = 1; this.m_JwC = 1; this.m_mass += this.m_iA + this.m_iC; } else { var u = Rot.mulVec2(qC, this.m_localAxisC); var rC = Rot.mulSub(qC, this.m_localAnchorC, this.m_lcC); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_lcA); this.m_JvAC = u; this.m_JwC = Vec2.cross(rC, u); this.m_JwA = Vec2.cross(rA, u); this.m_mass += this.m_mC + this.m_mA + this.m_iC * this.m_JwC * this.m_JwC + this.m_iA * this.m_JwA * this.m_JwA; } if (this.m_type2 == RevoluteJoint.TYPE) { this.m_JvBD = Vec2.zero(); this.m_JwB = this.m_ratio; this.m_JwD = this.m_ratio; this.m_mass += this.m_ratio * this.m_ratio * (this.m_iB + this.m_iD); } else { var u = Rot.mulVec2(qD, this.m_localAxisD); var rD = Rot.mulSub(qD, this.m_localAnchorD, this.m_lcD); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_lcB); this.m_JvBD = Vec2.mul(this.m_ratio, u); this.m_JwD = this.m_ratio * Vec2.cross(rD, u); this.m_JwB = this.m_ratio * Vec2.cross(rB, u); this.m_mass += this.m_ratio * this.m_ratio * (this.m_mD + this.m_mB) + this.m_iD * this.m_JwD * this.m_JwD + this.m_iB * this.m_JwB * this.m_JwB; } this.m_mass = this.m_mass > 0 ? 1 / this.m_mass : 0; if (step.warmStarting) { vA.addMul(this.m_mA * this.m_impulse, this.m_JvAC); wA += this.m_iA * this.m_impulse * this.m_JwA; vB.addMul(this.m_mB * this.m_impulse, this.m_JvBD); wB += this.m_iB * this.m_impulse * this.m_JwB; vC.subMul(this.m_mC * this.m_impulse, this.m_JvAC); wC -= this.m_iC * this.m_impulse * this.m_JwC; vD.subMul(this.m_mD * this.m_impulse, this.m_JvBD); wD -= this.m_iD * this.m_impulse * this.m_JwD; } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; this.m_bodyC.c_velocity.v.set(vC); this.m_bodyC.c_velocity.w = wC; this.m_bodyD.c_velocity.v.set(vD); this.m_bodyD.c_velocity.w = wD; }; GearJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vC = this.m_bodyC.c_velocity.v; var wC = this.m_bodyC.c_velocity.w; var vD = this.m_bodyD.c_velocity.v; var wD = this.m_bodyD.c_velocity.w; var Cdot = Vec2.dot(this.m_JvAC, vA) - Vec2.dot(this.m_JvAC, vC) + Vec2.dot(this.m_JvBD, vB) - Vec2.dot(this.m_JvBD, vD); Cdot += this.m_JwA * wA - this.m_JwC * wC + (this.m_JwB * wB - this.m_JwD * wD); var impulse = -this.m_mass * Cdot; this.m_impulse += impulse; vA.addMul(this.m_mA * impulse, this.m_JvAC); wA += this.m_iA * impulse * this.m_JwA; vB.addMul(this.m_mB * impulse, this.m_JvBD); wB += this.m_iB * impulse * this.m_JwB; vC.subMul(this.m_mC * impulse, this.m_JvAC); wC -= this.m_iC * impulse * this.m_JwC; vD.subMul(this.m_mD * impulse, this.m_JvBD); wD -= this.m_iD * impulse * this.m_JwD; this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; this.m_bodyC.c_velocity.v.set(vC); this.m_bodyC.c_velocity.w = wC; this.m_bodyD.c_velocity.v.set(vD); this.m_bodyD.c_velocity.w = wD; }; GearJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var cC = this.m_bodyC.c_position.c; var aC = this.m_bodyC.c_position.a; var cD = this.m_bodyD.c_position.c; var aD = this.m_bodyD.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var qC = Rot.neo(aC); var qD = Rot.neo(aD); var linearError = 0; var coordinateA, coordinateB; var JvAC, JvBD; var JwA, JwB, JwC, JwD; var mass = 0; if (this.m_type1 == RevoluteJoint.TYPE) { JvAC = Vec2.zero(); JwA = 1; JwC = 1; mass += this.m_iA + this.m_iC; coordinateA = aA - aC - this.m_referenceAngleA; } else { var u = Rot.mulVec2(qC, this.m_localAxisC); var rC = Rot.mulSub(qC, this.m_localAnchorC, this.m_lcC); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_lcA); JvAC = u; JwC = Vec2.cross(rC, u); JwA = Vec2.cross(rA, u); mass += this.m_mC + this.m_mA + this.m_iC * JwC * JwC + this.m_iA * JwA * JwA; var pC = Vec2.sub(this.m_localAnchorC, this.m_lcC); var pA = Rot.mulTVec2(qC, Vec2.add(rA, Vec2.sub(cA, cC))); coordinateA = Vec2.dot(Vec2.sub(pA, pC), this.m_localAxisC); } if (this.m_type2 == RevoluteJoint.TYPE) { JvBD = Vec2.zero(); JwB = this.m_ratio; JwD = this.m_ratio; mass += this.m_ratio * this.m_ratio * (this.m_iB + this.m_iD); coordinateB = aB - aD - this.m_referenceAngleB; } else { var u = Rot.mulVec2(qD, this.m_localAxisD); var rD = Rot.mulSub(qD, this.m_localAnchorD, this.m_lcD); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_lcB); JvBD = Vec2.mul(this.m_ratio, u); JwD = this.m_ratio * Vec2.cross(rD, u); JwB = this.m_ratio * Vec2.cross(rB, u); mass += this.m_ratio * this.m_ratio * (this.m_mD + this.m_mB) + this.m_iD * JwD * JwD + this.m_iB * JwB * JwB; var pD = Vec2.sub(this.m_localAnchorD, this.m_lcD); var pB = Rot.mulTVec2(qD, Vec2.add(rB, Vec2.sub(cB, cD))); coordinateB = Vec2.dot(pB, this.m_localAxisD) - Vec2.dot(pD, this.m_localAxisD); } var C = coordinateA + this.m_ratio * coordinateB - this.m_constant; var impulse = 0; if (mass > 0) { impulse = -C / mass; } cA.addMul(this.m_mA * impulse, JvAC); aA += this.m_iA * impulse * JwA; cB.addMul(this.m_mB * impulse, JvBD); aB += this.m_iB * impulse * JwB; cC.subMul(this.m_mC * impulse, JvAC); aC -= this.m_iC * impulse * JwC; cD.subMul(this.m_mD * impulse, JvBD); aD -= this.m_iD * impulse * JwD; this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; this.m_bodyC.c_position.c.set(cC); this.m_bodyC.c_position.a = aC; this.m_bodyD.c_position.c.set(cD); this.m_bodyD.c_position.a = aD; return linearError < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53,"./PrismaticJoint":33,"./RevoluteJoint":35}],31:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = MotorJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); MotorJoint.TYPE = "motor-joint"; MotorJoint._super = Joint; MotorJoint.prototype = create(MotorJoint._super.prototype); var DEFAULTS = { maxForce: 1, maxTorque: 1, correctionFactor: .3 }; function MotorJoint(def, bodyA, bodyB) { if (!(this instanceof MotorJoint)) { return new MotorJoint(def, bodyA, bodyB); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = MotorJoint.TYPE; this.m_linearOffset = def.linearOffset ? def.linearOffset : bodyA.getLocalPoint(bodyB.getPosition()); var angleA = bodyA.getAngle(); var angleB = bodyB.getAngle(); this.m_angularOffset = angleB - angleA; this.m_linearImpulse = Vec2.zero(); this.m_angularImpulse = 0; this.m_maxForce = def.maxForce; this.m_maxTorque = def.maxTorque; this.m_correctionFactor = def.correctionFactor; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_linearError; this.m_angularError; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_linearMass; this.m_angularMass; } MotorJoint.prototype.setMaxForce = function(force) { _ASSERT && common.assert(Math.isFinite(force) && force >= 0); this.m_maxForce = force; }; MotorJoint.prototype.getMaxForce = function() { return this.m_maxForce; }; MotorJoint.prototype.setMaxTorque = function(torque) { _ASSERT && common.assert(Math.isFinite(torque) && torque >= 0); this.m_maxTorque = torque; }; MotorJoint.prototype.getMaxTorque = function() { return this.m_maxTorque; }; MotorJoint.prototype.setCorrectionFactor = function(factor) { _ASSERT && common.assert(Math.isFinite(factor) && 0 <= factor && factor <= 1); this.m_correctionFactor = factor; }; MotorJoint.prototype.getCorrectionFactor = function() { return this.m_correctionFactor; }; MotorJoint.prototype.setLinearOffset = function(linearOffset) { if (linearOffset.x != this.m_linearOffset.x || linearOffset.y != this.m_linearOffset.y) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_linearOffset = linearOffset; } }; MotorJoint.prototype.getLinearOffset = function() { return this.m_linearOffset; }; MotorJoint.prototype.setAngularOffset = function(angularOffset) { if (angularOffset != this.m_angularOffset) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_angularOffset = angularOffset; } }; MotorJoint.prototype.getAngularOffset = function() { return this.m_angularOffset; }; MotorJoint.prototype.getAnchorA = function() { return this.m_bodyA.getPosition(); }; MotorJoint.prototype.getAnchorB = function() { return this.m_bodyB.getPosition(); }; MotorJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(inv_dt, this.m_linearImpulse); }; MotorJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_angularImpulse; }; MotorJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA), qB = Rot.neo(aB); this.m_rA = Rot.mulVec2(qA, Vec2.neg(this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.neg(this.m_localCenterB)); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var K = new Mat22(); K.ex.x = mA + mB + iA * this.m_rA.y * this.m_rA.y + iB * this.m_rB.y * this.m_rB.y; K.ex.y = -iA * this.m_rA.x * this.m_rA.y - iB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * this.m_rA.x * this.m_rA.x + iB * this.m_rB.x * this.m_rB.x; this.m_linearMass = K.getInverse(); this.m_angularMass = iA + iB; if (this.m_angularMass > 0) { this.m_angularMass = 1 / this.m_angularMass; } this.m_linearError = Vec2.zero(); this.m_linearError.addCombine(1, cB, 1, this.m_rB); this.m_linearError.subCombine(1, cA, 1, this.m_rA); this.m_linearError.sub(Rot.mulVec2(qA, this.m_linearOffset)); this.m_angularError = aB - aA - this.m_angularOffset; if (step.warmStarting) { this.m_linearImpulse.mul(step.dtRatio); this.m_angularImpulse *= step.dtRatio; var P = Vec2.neo(this.m_linearImpulse.x, this.m_linearImpulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_angularImpulse); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_angularImpulse); } else { this.m_linearImpulse.setZero(); this.m_angularImpulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; MotorJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var h = step.dt; var inv_h = step.inv_dt; { var Cdot = wB - wA + inv_h * this.m_correctionFactor * this.m_angularError; var impulse = -this.m_angularMass * Cdot; var oldImpulse = this.m_angularImpulse; var maxImpulse = h * this.m_maxTorque; this.m_angularImpulse = Math.clamp(this.m_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } { var Cdot = Vec2.zero(); Cdot.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); Cdot.addMul(inv_h * this.m_correctionFactor, this.m_linearError); var impulse = Vec2.neg(Mat22.mulVec2(this.m_linearMass, Cdot)); var oldImpulse = Vec2.clone(this.m_linearImpulse); this.m_linearImpulse.add(impulse); var maxImpulse = h * this.m_maxForce; this.m_linearImpulse.clamp(maxImpulse); impulse = Vec2.sub(this.m_linearImpulse, oldImpulse); vA.subMul(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.addMul(mB, impulse); wB += iB * Vec2.cross(this.m_rB, impulse); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; MotorJoint.prototype.solvePositionConstraints = function(step) { return true; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],32:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = MouseJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); MouseJoint.TYPE = "mouse-joint"; MouseJoint._super = Joint; MouseJoint.prototype = create(MouseJoint._super.prototype); var DEFAULTS = { maxForce: 0, frequencyHz: 5, dampingRatio: .7 }; function MouseJoint(def, bodyA, bodyB, target) { if (!(this instanceof MouseJoint)) { return new MouseJoint(def, bodyA, bodyB, target); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = MouseJoint.TYPE; _ASSERT && common.assert(Math.isFinite(def.maxForce) && def.maxForce >= 0); _ASSERT && common.assert(Math.isFinite(def.frequencyHz) && def.frequencyHz >= 0); _ASSERT && common.assert(Math.isFinite(def.dampingRatio) && def.dampingRatio >= 0); this.m_targetA = target ? Vec2.clone(target) : def.target || Vec2.zero(); this.m_localAnchorB = Transform.mulTVec2(bodyB.getTransform(), this.m_targetA); this.m_maxForce = def.maxForce; this.m_impulse = Vec2.zero(); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_beta = 0; this.m_gamma = 0; this.m_rB = Vec2.zero(); this.m_localCenterB = Vec2.zero(); this.m_invMassB = 0; this.m_invIB = 0; this.mass = new Mat22(); this.m_C = Vec2.zero(); } MouseJoint.prototype.setTarget = function(target) { if (this.m_bodyB.isAwake() == false) { this.m_bodyB.setAwake(true); } this.m_targetA = Vec2.clone(target); }; MouseJoint.prototype.getTarget = function() { return this.m_targetA; }; MouseJoint.prototype.setMaxForce = function(force) { this.m_maxForce = force; }; MouseJoint.getMaxForce = function() { return this.m_maxForce; }; MouseJoint.prototype.setFrequency = function(hz) { this.m_frequencyHz = hz; }; MouseJoint.prototype.getFrequency = function() { return this.m_frequencyHz; }; MouseJoint.prototype.setDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; MouseJoint.prototype.getDampingRatio = function() { return this.m_dampingRatio; }; MouseJoint.prototype.getAnchorA = function() { return Vec2.clone(this.m_targetA); }; MouseJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; MouseJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(inv_dt, this.m_impulse); }; MouseJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * 0; }; MouseJoint.prototype.shiftOrigin = function(newOrigin) { this.m_targetA.sub(newOrigin); }; MouseJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIB = this.m_bodyB.m_invI; var position = this.m_bodyB.c_position; var velocity = this.m_bodyB.c_velocity; var cB = position.c; var aB = position.a; var vB = velocity.v; var wB = velocity.w; var qB = Rot.neo(aB); var mass = this.m_bodyB.getMass(); var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * mass * this.m_dampingRatio * omega; var k = mass * (omega * omega); var h = step.dt; _ASSERT && common.assert(d + h * k > Math.EPSILON); this.m_gamma = h * (d + h * k); if (this.m_gamma != 0) { this.m_gamma = 1 / this.m_gamma; } this.m_beta = h * k * this.m_gamma; this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var K = new Mat22(); K.ex.x = this.m_invMassB + this.m_invIB * this.m_rB.y * this.m_rB.y + this.m_gamma; K.ex.y = -this.m_invIB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = this.m_invMassB + this.m_invIB * this.m_rB.x * this.m_rB.x + this.m_gamma; this.m_mass = K.getInverse(); this.m_C.set(cB); this.m_C.addCombine(1, this.m_rB, -1, this.m_targetA); this.m_C.mul(this.m_beta); wB *= .98; if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); vB.addMul(this.m_invMassB, this.m_impulse); wB += this.m_invIB * Vec2.cross(this.m_rB, this.m_impulse); } else { this.m_impulse.setZero(); } velocity.v.set(vB); velocity.w = wB; }; MouseJoint.prototype.solveVelocityConstraints = function(step) { var velocity = this.m_bodyB.c_velocity; var vB = Vec2.clone(velocity.v); var wB = velocity.w; var Cdot = Vec2.cross(wB, this.m_rB); Cdot.add(vB); Cdot.addCombine(1, this.m_C, this.m_gamma, this.m_impulse); Cdot.neg(); var impulse = Mat22.mulVec2(this.m_mass, Cdot); var oldImpulse = Vec2.clone(this.m_impulse); this.m_impulse.add(impulse); var maxImpulse = step.dt * this.m_maxForce; this.m_impulse.clamp(maxImpulse); impulse = Vec2.sub(this.m_impulse, oldImpulse); vB.addMul(this.m_invMassB, impulse); wB += this.m_invIB * Vec2.cross(this.m_rB, impulse); velocity.v.set(vB); velocity.w = wB; }; MouseJoint.prototype.solvePositionConstraints = function(step) { return true; }; },{"../Joint":5,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],33:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = PrismaticJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var inactiveLimit = 0; var atLowerLimit = 1; var atUpperLimit = 2; var equalLimits = 3; PrismaticJoint.TYPE = "prismatic-joint"; PrismaticJoint._super = Joint; PrismaticJoint.prototype = create(PrismaticJoint._super.prototype); var DEFAULTS = { enableLimit: false, lowerTranslation: 0, upperTranslation: 0, enableMotor: false, maxMotorForce: 0, motorSpeed: 0 }; function PrismaticJoint(def, bodyA, bodyB, anchor, axis) { if (!(this instanceof PrismaticJoint)) { return new PrismaticJoint(def, bodyA, bodyB, anchor, axis); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = PrismaticJoint.TYPE; this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero(); this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero(); this.m_localXAxisA = axis ? bodyA.getLocalVector(axis) : def.localAxisA || Vec2.neo(1, 0); this.m_localXAxisA.normalize(); this.m_localYAxisA = Vec2.cross(1, this.m_localXAxisA); this.m_referenceAngle = Math.isFinite(def.referenceAngle) ? def.referenceAngle : bodyB.getAngle() - bodyA.getAngle(); this.m_impulse = Vec3(); this.m_motorMass = 0; this.m_motorImpulse = 0; this.m_lowerTranslation = def.lowerTranslation; this.m_upperTranslation = def.upperTranslation; this.m_maxMotorForce = def.maxMotorForce; this.m_motorSpeed = def.motorSpeed; this.m_enableLimit = def.enableLimit; this.m_enableMotor = def.enableMotor; this.m_limitState = inactiveLimit; this.m_axis = Vec2.zero(); this.m_perp = Vec2.zero(); this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_axis, this.m_perp; this.m_s1, this.m_s2; this.m_a1, this.m_a2; this.m_K = new Mat33(); this.m_motorMass; } PrismaticJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; PrismaticJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; PrismaticJoint.prototype.getLocalAxisA = function() { return this.m_localXAxisA; }; PrismaticJoint.prototype.getReferenceAngle = function() { return this.m_referenceAngle; }; PrismaticJoint.prototype.getJointTranslation = function() { var pA = this.m_bodyA.getWorldPoint(this.m_localAnchorA); var pB = this.m_bodyB.getWorldPoint(this.m_localAnchorB); var d = Vec2.sub(pB, pA); var axis = this.m_bodyA.getWorldVector(this.m_localXAxisA); var translation = Vec2.dot(d, axis); return translation; }; PrismaticJoint.prototype.getJointSpeed = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; var rA = Rot.mulVec2(bA.m_xf.q, Vec2.sub(this.m_localAnchorA, bA.m_sweep.localCenter)); var rB = Rot.mulVec2(bB.m_xf.q, Vec2.sub(this.m_localAnchorB, bB.m_sweep.localCenter)); var p1 = Vec2.add(bA.m_sweep.c, rA); var p2 = Vec2.add(bB.m_sweep.c, rB); var d = Vec2.sub(p2, p1); var axis = Rot.mulVec2(bA.m_xf.q, this.m_localXAxisA); var vA = bA.m_linearVelocity; var vB = bB.m_linearVelocity; var wA = bA.m_angularVelocity; var wB = bB.m_angularVelocity; var speed = Vec2.dot(d, Vec2.cross(wA, axis)) + Vec2.dot(axis, Vec2.sub(Vec2.addCross(vB, wB, rB), Vec2.addCross(vA, wA, rA))); return speed; }; PrismaticJoint.prototype.isLimitEnabled = function() { return this.m_enableLimit; }; PrismaticJoint.prototype.enableLimit = function(flag) { if (flag != this.m_enableLimit) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableLimit = flag; this.m_impulse.z = 0; } }; PrismaticJoint.prototype.getLowerLimit = function() { return this.m_lowerTranslation; }; PrismaticJoint.prototype.getUpperLimit = function() { return this.m_upperTranslation; }; PrismaticJoint.prototype.setLimits = function(lower, upper) { _ASSERT && common.assert(lower <= upper); if (lower != this.m_lowerTranslation || upper != this.m_upperTranslation) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_lowerTranslation = lower; this.m_upperTranslation = upper; this.m_impulse.z = 0; } }; PrismaticJoint.prototype.isMotorEnabled = function() { return this.m_enableMotor; }; PrismaticJoint.prototype.enableMotor = function(flag) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; }; PrismaticJoint.prototype.setMotorSpeed = function(speed) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; }; PrismaticJoint.prototype.setMaxMotorForce = function(force) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_maxMotorForce = force; }; PrismaticJoint.prototype.getMotorSpeed = function() { return this.m_motorSpeed; }; PrismaticJoint.prototype.getMotorForce = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; PrismaticJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; PrismaticJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; PrismaticJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.combine(this.m_impulse.x, this.m_perp, this.m_motorImpulse + this.m_impulse.z, this.m_axis).mul(inv_dt); }; PrismaticJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.y; }; PrismaticJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.addCombine(1, cB, 1, rB); d.subCombine(1, cA, 1, rA); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; { this.m_axis = Rot.mulVec2(qA, this.m_localXAxisA); this.m_a1 = Vec2.cross(Vec2.add(d, rA), this.m_axis); this.m_a2 = Vec2.cross(rB, this.m_axis); this.m_motorMass = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } } { this.m_perp = Rot.mulVec2(qA, this.m_localYAxisA); this.m_s1 = Vec2.cross(Vec2.add(d, rA), this.m_perp); this.m_s2 = Vec2.cross(rB, this.m_perp); var s1test = Vec2.cross(rA, this.m_perp); var k11 = mA + mB + iA * this.m_s1 * this.m_s1 + iB * this.m_s2 * this.m_s2; var k12 = iA * this.m_s1 + iB * this.m_s2; var k13 = iA * this.m_s1 * this.m_a1 + iB * this.m_s2 * this.m_a2; var k22 = iA + iB; if (k22 == 0) { k22 = 1; } var k23 = iA * this.m_a1 + iB * this.m_a2; var k33 = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2; this.m_K.ex.set(k11, k12, k13); this.m_K.ey.set(k12, k22, k23); this.m_K.ez.set(k13, k23, k33); } if (this.m_enableLimit) { var jointTranslation = Vec2.dot(this.m_axis, d); if (Math.abs(this.m_upperTranslation - this.m_lowerTranslation) < 2 * Settings.linearSlop) { this.m_limitState = equalLimits; } else if (jointTranslation <= this.m_lowerTranslation) { if (this.m_limitState != atLowerLimit) { this.m_limitState = atLowerLimit; this.m_impulse.z = 0; } } else if (jointTranslation >= this.m_upperTranslation) { if (this.m_limitState != atUpperLimit) { this.m_limitState = atUpperLimit; this.m_impulse.z = 0; } } else { this.m_limitState = inactiveLimit; this.m_impulse.z = 0; } } else { this.m_limitState = inactiveLimit; this.m_impulse.z = 0; } if (this.m_enableMotor == false) { this.m_motorImpulse = 0; } if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); this.m_motorImpulse *= step.dtRatio; var P = Vec2.combine(this.m_impulse.x, this.m_perp, this.m_motorImpulse + this.m_impulse.z, this.m_axis); var LA = this.m_impulse.x * this.m_s1 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a1; var LB = this.m_impulse.x * this.m_s2 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a2; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } else { this.m_impulse.setZero(); this.m_motorImpulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; PrismaticJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; if (this.m_enableMotor && this.m_limitState != equalLimits) { var Cdot = Vec2.dot(this.m_axis, Vec2.sub(vB, vA)) + this.m_a2 * wB - this.m_a1 * wA; var impulse = this.m_motorMass * (this.m_motorSpeed - Cdot); var oldImpulse = this.m_motorImpulse; var maxImpulse = step.dt * this.m_maxMotorForce; this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; var P = Vec2.mul(impulse, this.m_axis); var LA = impulse * this.m_a1; var LB = impulse * this.m_a2; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } var Cdot1 = Vec2.zero(); Cdot1.x += Vec2.dot(this.m_perp, vB) + this.m_s2 * wB; Cdot1.x -= Vec2.dot(this.m_perp, vA) + this.m_s1 * wA; Cdot1.y = wB - wA; if (this.m_enableLimit && this.m_limitState != inactiveLimit) { var Cdot2 = 0; Cdot2 += Vec2.dot(this.m_axis, vB) + this.m_a2 * wB; Cdot2 -= Vec2.dot(this.m_axis, vA) + this.m_a1 * wA; var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2); var f1 = Vec3(this.m_impulse); var df = this.m_K.solve33(Vec3.neg(Cdot)); this.m_impulse.add(df); if (this.m_limitState == atLowerLimit) { this.m_impulse.z = Math.max(this.m_impulse.z, 0); } else if (this.m_limitState == atUpperLimit) { this.m_impulse.z = Math.min(this.m_impulse.z, 0); } var b = Vec2.combine(-1, Cdot1, -(this.m_impulse.z - f1.z), Vec2.neo(this.m_K.ez.x, this.m_K.ez.y)); var f2r = Vec2.add(this.m_K.solve22(b), Vec2.neo(f1.x, f1.y)); this.m_impulse.x = f2r.x; this.m_impulse.y = f2r.y; df = Vec3.sub(this.m_impulse, f1); var P = Vec2.combine(df.x, this.m_perp, df.z, this.m_axis); var LA = df.x * this.m_s1 + df.y + df.z * this.m_a1; var LB = df.x * this.m_s2 + df.y + df.z * this.m_a2; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } else { var df = this.m_K.solve22(Vec2.neg(Cdot1)); this.m_impulse.x += df.x; this.m_impulse.y += df.y; var P = Vec2.mul(df.x, this.m_perp); var LA = df.x * this.m_s1 + df.y; var LB = df.x * this.m_s2 + df.y; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; PrismaticJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.sub(Vec2.add(cB, rB), Vec2.add(cA, rA)); var axis = Rot.mulVec2(qA, this.m_localXAxisA); var a1 = Vec2.cross(Vec2.add(d, rA), axis); var a2 = Vec2.cross(rB, axis); var perp = Rot.mulVec2(qA, this.m_localYAxisA); var s1 = Vec2.cross(Vec2.add(d, rA), perp); var s2 = Vec2.cross(rB, perp); var impulse = Vec3(); var C1 = Vec2.zero(); C1.x = Vec2.dot(perp, d); C1.y = aB - aA - this.m_referenceAngle; var linearError = Math.abs(C1.x); var angularError = Math.abs(C1.y); var linearSlop = Settings.linearSlop; var maxLinearCorrection = Settings.maxLinearCorrection; var active = false; var C2 = 0; if (this.m_enableLimit) { var translation = Vec2.dot(axis, d); if (Math.abs(this.m_upperTranslation - this.m_lowerTranslation) < 2 * linearSlop) { C2 = Math.clamp(translation, -maxLinearCorrection, maxLinearCorrection); linearError = Math.max(linearError, Math.abs(translation)); active = true; } else if (translation <= this.m_lowerTranslation) { C2 = Math.clamp(translation - this.m_lowerTranslation + linearSlop, -maxLinearCorrection, 0); linearError = Math.max(linearError, this.m_lowerTranslation - translation); active = true; } else if (translation >= this.m_upperTranslation) { C2 = Math.clamp(translation - this.m_upperTranslation - linearSlop, 0, maxLinearCorrection); linearError = Math.max(linearError, translation - this.m_upperTranslation); active = true; } } if (active) { var k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; var k12 = iA * s1 + iB * s2; var k13 = iA * s1 * a1 + iB * s2 * a2; var k22 = iA + iB; if (k22 == 0) { k22 = 1; } var k23 = iA * a1 + iB * a2; var k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2; var K = new Mat33(); K.ex.set(k11, k12, k13); K.ey.set(k12, k22, k23); K.ez.set(k13, k23, k33); var C = Vec3(); C.x = C1.x; C.y = C1.y; C.z = C2; impulse = K.solve33(Vec3.neg(C)); } else { var k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; var k12 = iA * s1 + iB * s2; var k22 = iA + iB; if (k22 == 0) { k22 = 1; } var K = new Mat22(); K.ex.set(k11, k12); K.ey.set(k12, k22); var impulse1 = K.solve(Vec2.neg(C1)); impulse.x = impulse1.x; impulse.y = impulse1.y; impulse.z = 0; } var P = Vec2.combine(impulse.x, perp, impulse.z, axis); var LA = impulse.x * s1 + impulse.y + impulse.z * a1; var LB = impulse.x * s2 + impulse.y + impulse.z * a2; cA.subMul(mA, P); aA -= iA * LA; cB.addMul(mB, P); aB += iB * LB; this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return linearError <= Settings.linearSlop && angularError <= Settings.angularSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],34:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = PulleyJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); PulleyJoint.TYPE = "pulley-joint"; PulleyJoint.MIN_PULLEY_LENGTH = 2; PulleyJoint._super = Joint; PulleyJoint.prototype = create(PulleyJoint._super.prototype); var PulleyJointDef = { collideConnected: true }; function PulleyJoint(def, bodyA, bodyB, groundA, groundB, anchorA, anchorB, ratio) { if (!(this instanceof PulleyJoint)) { return new PulleyJoint(def, bodyA, bodyB, groundA, groundB, anchorA, anchorB, ratio); } def = options(def, PulleyJointDef); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = PulleyJoint.TYPE; this.m_groundAnchorA = groundA ? groundA : def.groundAnchorA || Vec2.neo(-1, 1); this.m_groundAnchorB = groundB ? groundB : def.groundAnchorB || Vec2.neo(1, 1); this.m_localAnchorA = anchorA ? bodyA.getLocalPoint(anchorA) : def.localAnchorA || Vec2.neo(-1, 0); this.m_localAnchorB = anchorB ? bodyB.getLocalPoint(anchorB) : def.localAnchorB || Vec2.neo(1, 0); this.m_lengthA = Math.isFinite(def.lengthA) ? def.lengthA : Vec2.distance(anchorA, groundA); this.m_lengthB = Math.isFinite(def.lengthB) ? def.lengthB : Vec2.distance(anchorB, groundB); this.m_ratio = Math.isFinite(ratio) ? ratio : def.ratio; _ASSERT && common.assert(ratio > Math.EPSILON); this.m_constant = this.m_lengthA + this.m_ratio * this.m_lengthB; this.m_impulse = 0; this.m_uA; this.m_uB; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass; } PulleyJoint.prototype.getGroundAnchorA = function() { return this.m_groundAnchorA; }; PulleyJoint.prototype.getGroundAnchorB = function() { return this.m_groundAnchorB; }; PulleyJoint.prototype.getLengthA = function() { return this.m_lengthA; }; PulleyJoint.prototype.getLengthB = function() { return this.m_lengthB; }; PulleyJoint.prototype.getRatio = function() { return this.m_ratio; }; PulleyJoint.prototype.getCurrentLengthA = function() { var p = this.m_bodyA.getWorldPoint(this.m_localAnchorA); var s = this.m_groundAnchorA; return Vec2.distance(p, s); }; PulleyJoint.prototype.getCurrentLengthB = function() { var p = this.m_bodyB.getWorldPoint(this.m_localAnchorB); var s = this.m_groundAnchorB; return Vec2.distance(p, s); }; PulleyJoint.prototype.shiftOrigin = function(newOrigin) { this.m_groundAnchorA.sub(newOrigin); this.m_groundAnchorB.sub(newOrigin); }; PulleyJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; PulleyJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; PulleyJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(this.m_impulse, this.m_uB).mul(inv_dt); }; PulleyJoint.prototype.getReactionTorque = function(inv_dt) { return 0; }; PulleyJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); this.m_uA = Vec2.sub(Vec2.add(cA, this.m_rA), this.m_groundAnchorA); this.m_uB = Vec2.sub(Vec2.add(cB, this.m_rB), this.m_groundAnchorB); var lengthA = this.m_uA.length(); var lengthB = this.m_uB.length(); if (lengthA > 10 * Settings.linearSlop) { this.m_uA.mul(1 / lengthA); } else { this.m_uA.setZero(); } if (lengthB > 10 * Settings.linearSlop) { this.m_uB.mul(1 / lengthB); } else { this.m_uB.setZero(); } var ruA = Vec2.cross(this.m_rA, this.m_uA); var ruB = Vec2.cross(this.m_rB, this.m_uB); var mA = this.m_invMassA + this.m_invIA * ruA * ruA; var mB = this.m_invMassB + this.m_invIB * ruB * ruB; this.m_mass = mA + this.m_ratio * this.m_ratio * mB; if (this.m_mass > 0) { this.m_mass = 1 / this.m_mass; } if (step.warmStarting) { this.m_impulse *= step.dtRatio; var PA = Vec2.mul(-this.m_impulse, this.m_uA); var PB = Vec2.mul(-this.m_ratio * this.m_impulse, this.m_uB); vA.addMul(this.m_invMassA, PA); wA += this.m_invIA * Vec2.cross(this.m_rA, PA); vB.addMul(this.m_invMassB, PB); wB += this.m_invIB * Vec2.cross(this.m_rB, PB); } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; PulleyJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vpA = Vec2.add(vA, Vec2.cross(wA, this.m_rA)); var vpB = Vec2.add(vB, Vec2.cross(wB, this.m_rB)); var Cdot = -Vec2.dot(this.m_uA, vpA) - this.m_ratio * Vec2.dot(this.m_uB, vpB); var impulse = -this.m_mass * Cdot; this.m_impulse += impulse; var PA = Vec2.mul(-impulse, this.m_uA); var PB = Vec2.mul(-this.m_ratio * impulse, this.m_uB); vA.addMul(this.m_invMassA, PA); wA += this.m_invIA * Vec2.cross(this.m_rA, PA); vB.addMul(this.m_invMassB, PB); wB += this.m_invIB * Vec2.cross(this.m_rB, PB); this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; PulleyJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA), qB = Rot.neo(aB); var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var uA = Vec2.sub(Vec2.add(cA, this.m_rA), this.m_groundAnchorA); var uB = Vec2.sub(Vec2.add(cB, this.m_rB), this.m_groundAnchorB); var lengthA = uA.length(); var lengthB = uB.length(); if (lengthA > 10 * Settings.linearSlop) { uA.mul(1 / lengthA); } else { uA.setZero(); } if (lengthB > 10 * Settings.linearSlop) { uB.mul(1 / lengthB); } else { uB.setZero(); } var ruA = Vec2.cross(rA, uA); var ruB = Vec2.cross(rB, uB); var mA = this.m_invMassA + this.m_invIA * ruA * ruA; var mB = this.m_invMassB + this.m_invIB * ruB * ruB; var mass = mA + this.m_ratio * this.m_ratio * mB; if (mass > 0) { mass = 1 / mass; } var C = this.m_constant - lengthA - this.m_ratio * lengthB; var linearError = Math.abs(C); var impulse = -mass * C; var PA = Vec2.mul(-impulse, uA); var PB = Vec2.mul(-this.m_ratio * impulse, uB); cA.addMul(this.m_invMassA, PA); aA += this.m_invIA * Vec2.cross(rA, PA); cB.addMul(this.m_invMassB, PB); aB += this.m_invIB * Vec2.cross(rB, PB); this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return linearError < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],35:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = RevoluteJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var inactiveLimit = 0; var atLowerLimit = 1; var atUpperLimit = 2; var equalLimits = 3; RevoluteJoint.TYPE = "revolute-joint"; RevoluteJoint._super = Joint; RevoluteJoint.prototype = create(RevoluteJoint._super.prototype); var DEFAULTS = { lowerAngle: 0, upperAngle: 0, maxMotorTorque: 0, motorSpeed: 0, enableLimit: false, enableMotor: false }; function RevoluteJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof RevoluteJoint)) { return new RevoluteJoint(def, bodyA, bodyB, anchor); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = RevoluteJoint.TYPE; this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero(); this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero(); this.m_referenceAngle = Math.isFinite(def.referenceAngle) ? def.referenceAngle : bodyB.getAngle() - bodyA.getAngle(); this.m_impulse = Vec3(); this.m_motorImpulse = 0; this.m_lowerAngle = def.lowerAngle; this.m_upperAngle = def.upperAngle; this.m_maxMotorTorque = def.maxMotorTorque; this.m_motorSpeed = def.motorSpeed; this.m_enableLimit = def.enableLimit; this.m_enableMotor = def.enableMotor; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass = new Mat33(); this.m_motorMass; this.m_limitState = inactiveLimit; } RevoluteJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; RevoluteJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; RevoluteJoint.prototype.getReferenceAngle = function() { return this.m_referenceAngle; }; RevoluteJoint.prototype.getJointAngle = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; return bB.m_sweep.a - bA.m_sweep.a - this.m_referenceAngle; }; RevoluteJoint.prototype.getJointSpeed = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; return bB.m_angularVelocity - bA.m_angularVelocity; }; RevoluteJoint.prototype.isMotorEnabled = function() { return this.m_enableMotor; }; RevoluteJoint.prototype.enableMotor = function(flag) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; }; RevoluteJoint.prototype.getMotorTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; RevoluteJoint.prototype.setMotorSpeed = function(speed) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; }; RevoluteJoint.prototype.getMotorSpeed = function() { return this.m_motorSpeed; }; RevoluteJoint.prototype.setMaxMotorTorque = function(torque) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_maxMotorTorque = torque; }; RevoluteJoint.prototype.isLimitEnabled = function() { return this.m_enableLimit; }; RevoluteJoint.prototype.enableLimit = function(flag) { if (flag != this.m_enableLimit) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableLimit = flag; this.m_impulse.z = 0; } }; RevoluteJoint.prototype.getLowerLimit = function() { return this.m_lowerAngle; }; RevoluteJoint.prototype.getUpperLimit = function() { return this.m_upperAngle; }; RevoluteJoint.prototype.setLimits = function(lower, upper) { _ASSERT && common.assert(lower <= upper); if (lower != this.m_lowerAngle || upper != this.m_upperAngle) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_impulse.z = 0; this.m_lowerAngle = lower; this.m_upperAngle = upper; } }; RevoluteJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; RevoluteJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; RevoluteJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.neo(this.m_impulse.x, this.m_impulse.y).mul(inv_dt); }; RevoluteJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.z; }; RevoluteJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var fixedRotation = iA + iB === 0; this.m_mass.ex.x = mA + mB + this.m_rA.y * this.m_rA.y * iA + this.m_rB.y * this.m_rB.y * iB; this.m_mass.ey.x = -this.m_rA.y * this.m_rA.x * iA - this.m_rB.y * this.m_rB.x * iB; this.m_mass.ez.x = -this.m_rA.y * iA - this.m_rB.y * iB; this.m_mass.ex.y = this.m_mass.ey.x; this.m_mass.ey.y = mA + mB + this.m_rA.x * this.m_rA.x * iA + this.m_rB.x * this.m_rB.x * iB; this.m_mass.ez.y = this.m_rA.x * iA + this.m_rB.x * iB; this.m_mass.ex.z = this.m_mass.ez.x; this.m_mass.ey.z = this.m_mass.ez.y; this.m_mass.ez.z = iA + iB; this.m_motorMass = iA + iB; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } if (this.m_enableMotor == false || fixedRotation) { this.m_motorImpulse = 0; } if (this.m_enableLimit && fixedRotation == false) { var jointAngle = aB - aA - this.m_referenceAngle; if (Math.abs(this.m_upperAngle - this.m_lowerAngle) < 2 * Settings.angularSlop) { this.m_limitState = equalLimits; } else if (jointAngle <= this.m_lowerAngle) { if (this.m_limitState != atLowerLimit) { this.m_impulse.z = 0; } this.m_limitState = atLowerLimit; } else if (jointAngle >= this.m_upperAngle) { if (this.m_limitState != atUpperLimit) { this.m_impulse.z = 0; } this.m_limitState = atUpperLimit; } else { this.m_limitState = inactiveLimit; this.m_impulse.z = 0; } } else { this.m_limitState = inactiveLimit; } if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); this.m_motorImpulse *= step.dtRatio; var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_motorImpulse + this.m_impulse.z); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_motorImpulse + this.m_impulse.z); } else { this.m_impulse.setZero(); this.m_motorImpulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; RevoluteJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var fixedRotation = iA + iB === 0; if (this.m_enableMotor && this.m_limitState != equalLimits && fixedRotation == false) { var Cdot = wB - wA - this.m_motorSpeed; var impulse = -this.m_motorMass * Cdot; var oldImpulse = this.m_motorImpulse; var maxImpulse = step.dt * this.m_maxMotorTorque; this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } if (this.m_enableLimit && this.m_limitState != inactiveLimit && fixedRotation == false) { var Cdot1 = Vec2.zero(); Cdot1.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); var Cdot2 = wB - wA; var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2); var impulse = Vec3.neg(this.m_mass.solve33(Cdot)); if (this.m_limitState == equalLimits) { this.m_impulse.add(impulse); } else if (this.m_limitState == atLowerLimit) { var newImpulse = this.m_impulse.z + impulse.z; if (newImpulse < 0) { var rhs = Vec2.combine(-1, Cdot1, this.m_impulse.z, Vec2.neo(this.m_mass.ez.x, this.m_mass.ez.y)); var reduced = this.m_mass.solve22(rhs); impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -this.m_impulse.z; this.m_impulse.x += reduced.x; this.m_impulse.y += reduced.y; this.m_impulse.z = 0; } else { this.m_impulse.add(impulse); } } else if (this.m_limitState == atUpperLimit) { var newImpulse = this.m_impulse.z + impulse.z; if (newImpulse > 0) { var rhs = Vec2.combine(-1, Cdot1, this.m_impulse.z, Vec2.neo(this.m_mass.ez.x, this.m_mass.ez.y)); var reduced = this.m_mass.solve22(rhs); impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -this.m_impulse.z; this.m_impulse.x += reduced.x; this.m_impulse.y += reduced.y; this.m_impulse.z = 0; } else { this.m_impulse.add(impulse); } } var P = Vec2.neo(impulse.x, impulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + impulse.z); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + impulse.z); } else { var Cdot = Vec2.zero(); Cdot.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); var impulse = this.m_mass.solve22(Vec2.neg(Cdot)); this.m_impulse.x += impulse.x; this.m_impulse.y += impulse.y; vA.subMul(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.addMul(mB, impulse); wB += iB * Vec2.cross(this.m_rB, impulse); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; RevoluteJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var angularError = 0; var positionError = 0; var fixedRotation = this.m_invIA + this.m_invIB == 0; if (this.m_enableLimit && this.m_limitState != inactiveLimit && fixedRotation == false) { var angle = aB - aA - this.m_referenceAngle; var limitImpulse = 0; if (this.m_limitState == equalLimits) { var C = Math.clamp(angle - this.m_lowerAngle, -Settings.maxAngularCorrection, Settings.maxAngularCorrection); limitImpulse = -this.m_motorMass * C; angularError = Math.abs(C); } else if (this.m_limitState == atLowerLimit) { var C = angle - this.m_lowerAngle; angularError = -C; C = Math.clamp(C + Settings.angularSlop, -Settings.maxAngularCorrection, 0); limitImpulse = -this.m_motorMass * C; } else if (this.m_limitState == atUpperLimit) { var C = angle - this.m_upperAngle; angularError = C; C = Math.clamp(C - Settings.angularSlop, 0, Settings.maxAngularCorrection); limitImpulse = -this.m_motorMass * C; } aA -= this.m_invIA * limitImpulse; aB += this.m_invIB * limitImpulse; } { qA.set(aA); qB.set(aB); var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var C = Vec2.zero(); C.addCombine(1, cB, 1, rB); C.subCombine(1, cA, 1, rA); positionError = C.length(); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var K = new Mat22(); K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; var impulse = Vec2.neg(K.solve(C)); cA.subMul(mA, impulse); aA -= iA * Vec2.cross(rA, impulse); cB.addMul(mB, impulse); aB += iB * Vec2.cross(rB, impulse); } this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],36:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = RopeJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var inactiveLimit = 0; var atLowerLimit = 1; var atUpperLimit = 2; var equalLimits = 3; RopeJoint.TYPE = "rope-joint"; RopeJoint._super = Joint; RopeJoint.prototype = create(RopeJoint._super.prototype); var DEFAULTS = { maxLength: 0 }; function RopeJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof RopeJoint)) { return new RopeJoint(def, bodyA, bodyB, anchor); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = RopeJoint.TYPE; this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.neo(-1, 0); this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.neo(1, 0); this.m_maxLength = def.maxLength; this.m_mass = 0; this.m_impulse = 0; this.m_length = 0; this.m_state = inactiveLimit; this.m_u; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass; } RopeJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; RopeJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; RopeJoint.prototype.setMaxLength = function(length) { this.m_maxLength = length; }; RopeJoint.prototype.getMaxLength = function() { return this.m_maxLength; }; RopeJoint.prototype.getLimitState = function() { return this.m_state; }; RopeJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; RopeJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; RopeJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(this.m_impulse, this.m_u).mul(inv_dt); }; RopeJoint.prototype.getReactionTorque = function(inv_dt) { return 0; }; RopeJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA); this.m_rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB); this.m_u = Vec2.zero(); this.m_u.addCombine(1, cB, 1, this.m_rB); this.m_u.subCombine(1, cA, 1, this.m_rA); this.m_length = this.m_u.length(); var C = this.m_length - this.m_maxLength; if (C > 0) { this.m_state = atUpperLimit; } else { this.m_state = inactiveLimit; } if (this.m_length > Settings.linearSlop) { this.m_u.mul(1 / this.m_length); } else { this.m_u.setZero(); this.m_mass = 0; this.m_impulse = 0; return; } var crA = Vec2.cross(this.m_rA, this.m_u); var crB = Vec2.cross(this.m_rB, this.m_u); var invMass = this.m_invMassA + this.m_invIA * crA * crA + this.m_invMassB + this.m_invIB * crB * crB; this.m_mass = invMass != 0 ? 1 / invMass : 0; if (step.warmStarting) { this.m_impulse *= step.dtRatio; var P = Vec2.mul(this.m_impulse, this.m_u); vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.addMul(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; RopeJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vpA = Vec2.addCross(vA, wA, this.m_rA); var vpB = Vec2.addCross(vB, wB, this.m_rB); var C = this.m_length - this.m_maxLength; var Cdot = Vec2.dot(this.m_u, Vec2.sub(vpB, vpA)); if (C < 0) { Cdot += step.inv_dt * C; } var impulse = -this.m_mass * Cdot; var oldImpulse = this.m_impulse; this.m_impulse = Math.min(0, this.m_impulse + impulse); impulse = this.m_impulse - oldImpulse; var P = Vec2.mul(impulse, this.m_u); vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.addMul(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; RopeJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB); var u = Vec2.zero(); u.addCombine(1, cB, 1, rB); u.subCombine(1, cA, 1, rA); var length = u.normalize(); var C = length - this.m_maxLength; C = Math.clamp(C, 0, Settings.maxLinearCorrection); var impulse = -this.m_mass * C; var P = Vec2.mul(impulse, u); cA.subMul(this.m_invMassA, P); aA -= this.m_invIA * Vec2.cross(rA, P); cB.addMul(this.m_invMassB, P); aB += this.m_invIB * Vec2.cross(rB, P); this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return length - this.m_maxLength < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],37:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = WeldJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); WeldJoint.TYPE = "weld-joint"; WeldJoint._super = Joint; WeldJoint.prototype = create(WeldJoint._super.prototype); var DEFAULTS = { frequencyHz: 0, dampingRatio: 0 }; function WeldJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof WeldJoint)) { return new WeldJoint(def, bodyA, bodyB, anchor); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = WeldJoint.TYPE; this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero(); this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero(); this.m_referenceAngle = Math.isFinite(def.referenceAngle) ? def.referenceAngle : bodyB.getAngle() - bodyA.getAngle(); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_impulse = Vec3(); this.m_bias = 0; this.m_gamma = 0; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass = new Mat33(); } WeldJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; WeldJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; WeldJoint.prototype.getReferenceAngle = function() { return this.m_referenceAngle; }; WeldJoint.prototype.setFrequency = function(hz) { this.m_frequencyHz = hz; }; WeldJoint.prototype.getFrequency = function() { return this.m_frequencyHz; }; WeldJoint.prototype.setDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; WeldJoint.prototype.getDampingRatio = function() { return this.m_dampingRatio; }; WeldJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; WeldJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; WeldJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.neo(this.m_impulse.x, this.m_impulse.y).mul(inv_dt); }; WeldJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.z; }; WeldJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA), qB = Rot.neo(aB); this.m_rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var K = new Mat33(); K.ex.x = mA + mB + this.m_rA.y * this.m_rA.y * iA + this.m_rB.y * this.m_rB.y * iB; K.ey.x = -this.m_rA.y * this.m_rA.x * iA - this.m_rB.y * this.m_rB.x * iB; K.ez.x = -this.m_rA.y * iA - this.m_rB.y * iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + this.m_rA.x * this.m_rA.x * iA + this.m_rB.x * this.m_rB.x * iB; K.ez.y = this.m_rA.x * iA + this.m_rB.x * iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (this.m_frequencyHz > 0) { K.getInverse22(this.m_mass); var invM = iA + iB; var m = invM > 0 ? 1 / invM : 0; var C = aB - aA - this.m_referenceAngle; var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * m * this.m_dampingRatio * omega; var k = m * omega * omega; var h = step.dt; this.m_gamma = h * (d + h * k); this.m_gamma = this.m_gamma != 0 ? 1 / this.m_gamma : 0; this.m_bias = C * h * k * this.m_gamma; invM += this.m_gamma; this.m_mass.ez.z = invM != 0 ? 1 / invM : 0; } else if (K.ez.z == 0) { K.getInverse22(this.m_mass); this.m_gamma = 0; this.m_bias = 0; } else { K.getSymInverse33(this.m_mass); this.m_gamma = 0; this.m_bias = 0; } if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_impulse.z); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_impulse.z); } else { this.m_impulse.setZero(); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; WeldJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; if (this.m_frequencyHz > 0) { var Cdot2 = wB - wA; var impulse2 = -this.m_mass.ez.z * (Cdot2 + this.m_bias + this.m_gamma * this.m_impulse.z); this.m_impulse.z += impulse2; wA -= iA * impulse2; wB += iB * impulse2; var Cdot1 = Vec2.zero(); Cdot1.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); var impulse1 = Vec2.neg(Mat33.mulVec2(this.m_mass, Cdot1)); this.m_impulse.x += impulse1.x; this.m_impulse.y += impulse1.y; var P = Vec2.clone(impulse1); vA.subMul(mA, P); wA -= iA * Vec2.cross(this.m_rA, P); vB.addMul(mB, P); wB += iB * Vec2.cross(this.m_rB, P); } else { var Cdot1 = Vec2.zero(); Cdot1.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); var Cdot2 = wB - wA; var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2); var impulse = Vec3.neg(Mat33.mulVec3(this.m_mass, Cdot)); this.m_impulse.add(impulse); var P = Vec2.neo(impulse.x, impulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + impulse.z); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + impulse.z); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; WeldJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA), qB = Rot.neo(aB); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var positionError, angularError; var K = new Mat33(); K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; K.ez.x = -rA.y * iA - rB.y * iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; K.ez.y = rA.x * iA + rB.x * iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (this.m_frequencyHz > 0) { var C1 = Vec2.zero(); C1.addCombine(1, cB, 1, rB); C1.subCombine(1, cA, 1, rA); positionError = C1.length(); angularError = 0; var P = Vec2.neg(K.solve22(C1)); cA.subMul(mA, P); aA -= iA * Vec2.cross(rA, P); cB.addMul(mB, P); aB += iB * Vec2.cross(rB, P); } else { var C1 = Vec2.zero(); C1.addCombine(1, cB, 1, rB); C1.subCombine(1, cA, 1, rA); var C2 = aB - aA - this.m_referenceAngle; positionError = C1.length(); angularError = Math.abs(C2); var C = Vec3(C1.x, C1.y, C2); var impulse = Vec3(); if (K.ez.z > 0) { impulse = Vec3.neg(K.solve33(C)); } else { var impulse2 = Vec2.neg(K.solve22(C1)); impulse.set(impulse2.x, impulse2.y, 0); } var P = Vec2.neo(impulse.x, impulse.y); cA.subMul(mA, P); aA -= iA * (Vec2.cross(rA, P) + impulse.z); cB.addMul(mB, P); aB += iB * (Vec2.cross(rB, P) + impulse.z); } this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],38:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = WheelJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); WheelJoint.TYPE = "wheel-joint"; WheelJoint._super = Joint; WheelJoint.prototype = create(WheelJoint._super.prototype); var DEFAULTS = { enableMotor: false, maxMotorTorque: 0, motorSpeed: 0, frequencyHz: 2, dampingRatio: .7 }; function WheelJoint(def, bodyA, bodyB, anchor, axis) { if (!(this instanceof WheelJoint)) { return new WheelJoint(def, bodyA, bodyB, anchor, axis); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = WheelJoint.TYPE; this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero(); this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero(); this.m_localAxis = axis ? bodyA.getLocalVector(axis) : def.localAxisA || Vec2.neo(1, 0); this.m_localXAxisA = this.m_localAxis; this.m_localYAxisA = Vec2.cross(1, this.m_localXAxisA); this.m_mass = 0; this.m_impulse = 0; this.m_motorMass = 0; this.m_motorImpulse = 0; this.m_springMass = 0; this.m_springImpulse = 0; this.m_maxMotorTorque = def.maxMotorTorque; this.m_motorSpeed = def.motorSpeed; this.m_enableMotor = def.enableMotor; this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_bias = 0; this.m_gamma = 0; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_ax = Vec2.zero(); this.m_ay = Vec2.zero(); this.m_sAx; this.m_sBx; this.m_sAy; this.m_sBy; } WheelJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; WheelJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; WheelJoint.prototype.getLocalAxisA = function() { return this.m_localXAxisA; }; WheelJoint.prototype.getJointTranslation = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; var pA = bA.getWorldPoint(this.m_localAnchorA); var pB = bB.getWorldPoint(this.m_localAnchorB); var d = Vec2.sub(pB, pA); var axis = bA.getWorldVector(this.m_localXAxisA); var translation = Vec2.dot(d, axis); return translation; }; WheelJoint.prototype.getJointSpeed = function() { var wA = this.m_bodyA.m_angularVelocity; var wB = this.m_bodyB.m_angularVelocity; return wB - wA; }; WheelJoint.prototype.isMotorEnabled = function() { return this.m_enableMotor; }; WheelJoint.prototype.enableMotor = function(flag) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; }; WheelJoint.prototype.setMotorSpeed = function(speed) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; }; WheelJoint.prototype.getMotorSpeed = function() { return this.m_motorSpeed; }; WheelJoint.prototype.setMaxMotorTorque = function(torque) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_maxMotorTorque = torque; }; WheelJoint.prototype.getMaxMotorTorque = function() { return this.m_maxMotorTorque; }; WheelJoint.prototype.getMotorTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; WheelJoint.prototype.setSpringFrequencyHz = function(hz) { this.m_frequencyHz = hz; }; WheelJoint.prototype.getSpringFrequencyHz = function() { return this.m_frequencyHz; }; WheelJoint.prototype.setSpringDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; WheelJoint.prototype.getSpringDampingRatio = function() { return this.m_dampingRatio; }; WheelJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; WheelJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; WheelJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.combine(this.m_impulse, this.m_ay, this.m_springImpulse, this.m_ax).mul(inv_dt); }; WheelJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; WheelJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.addCombine(1, cB, 1, rB); d.subCombine(1, cA, 1, rA); { this.m_ay = Rot.mulVec2(qA, this.m_localYAxisA); this.m_sAy = Vec2.cross(Vec2.add(d, rA), this.m_ay); this.m_sBy = Vec2.cross(rB, this.m_ay); this.m_mass = mA + mB + iA * this.m_sAy * this.m_sAy + iB * this.m_sBy * this.m_sBy; if (this.m_mass > 0) { this.m_mass = 1 / this.m_mass; } } this.m_springMass = 0; this.m_bias = 0; this.m_gamma = 0; if (this.m_frequencyHz > 0) { this.m_ax = Rot.mulVec2(qA, this.m_localXAxisA); this.m_sAx = Vec2.cross(Vec2.add(d, rA), this.m_ax); this.m_sBx = Vec2.cross(rB, this.m_ax); var invMass = mA + mB + iA * this.m_sAx * this.m_sAx + iB * this.m_sBx * this.m_sBx; if (invMass > 0) { this.m_springMass = 1 / invMass; var C = Vec2.dot(d, this.m_ax); var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * this.m_springMass * this.m_dampingRatio * omega; var k = this.m_springMass * omega * omega; var h = step.dt; this.m_gamma = h * (d + h * k); if (this.m_gamma > 0) { this.m_gamma = 1 / this.m_gamma; } this.m_bias = C * h * k * this.m_gamma; this.m_springMass = invMass + this.m_gamma; if (this.m_springMass > 0) { this.m_springMass = 1 / this.m_springMass; } } } else { this.m_springImpulse = 0; } if (this.m_enableMotor) { this.m_motorMass = iA + iB; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } } else { this.m_motorMass = 0; this.m_motorImpulse = 0; } if (step.warmStarting) { this.m_impulse *= step.dtRatio; this.m_springImpulse *= step.dtRatio; this.m_motorImpulse *= step.dtRatio; var P = Vec2.combine(this.m_impulse, this.m_ay, this.m_springImpulse, this.m_ax); var LA = this.m_impulse * this.m_sAy + this.m_springImpulse * this.m_sAx + this.m_motorImpulse; var LB = this.m_impulse * this.m_sBy + this.m_springImpulse * this.m_sBx + this.m_motorImpulse; vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * LA; vB.addMul(this.m_invMassB, P); wB += this.m_invIB * LB; } else { this.m_impulse = 0; this.m_springImpulse = 0; this.m_motorImpulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; WheelJoint.prototype.solveVelocityConstraints = function(step) { var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; { var Cdot = Vec2.dot(this.m_ax, vB) - Vec2.dot(this.m_ax, vA) + this.m_sBx * wB - this.m_sAx * wA; var impulse = -this.m_springMass * (Cdot + this.m_bias + this.m_gamma * this.m_springImpulse); this.m_springImpulse += impulse; var P = Vec2.mul(impulse, this.m_ax); var LA = impulse * this.m_sAx; var LB = impulse * this.m_sBx; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } { var Cdot = wB - wA - this.m_motorSpeed; var impulse = -this.m_motorMass * Cdot; var oldImpulse = this.m_motorImpulse; var maxImpulse = step.dt * this.m_maxMotorTorque; this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } { var Cdot = Vec2.dot(this.m_ay, vB) - Vec2.dot(this.m_ay, vA) + this.m_sBy * wB - this.m_sAy * wA; var impulse = -this.m_mass * Cdot; this.m_impulse += impulse; var P = Vec2.mul(impulse, this.m_ay); var LA = impulse * this.m_sAy; var LB = impulse * this.m_sBy; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; WheelJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.addCombine(1, cB, 1, rB); d.subCombine(1, cA, 1, rA); var ay = Rot.mulVec2(qA, this.m_localYAxisA); var sAy = Vec2.cross(Vec2.add(d, rA), ay); var sBy = Vec2.cross(rB, ay); var C = Vec2.dot(d, ay); var k = this.m_invMassA + this.m_invMassB + this.m_invIA * this.m_sAy * this.m_sAy + this.m_invIB * this.m_sBy * this.m_sBy; var impulse; if (k != 0) { impulse = -C / k; } else { impulse = 0; } var P = Vec2.mul(impulse, ay); var LA = impulse * sAy; var LB = impulse * sBy; cA.subMul(this.m_invMassA, P); aA -= this.m_invIA * LA; cB.addMul(this.m_invMassB, P); aB += this.m_invIB * LB; this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return Math.abs(C) <= Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],39:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = BoxShape; var common = require("../util/common"); var create = require("../util/create"); var PolygonShape = require("./PolygonShape"); BoxShape._super = PolygonShape; BoxShape.prototype = create(BoxShape._super.prototype); BoxShape.TYPE = "polygon"; function BoxShape(hx, hy, center, angle) { if (!(this instanceof BoxShape)) { return new BoxShape(hx, hy, center, angle); } BoxShape._super.call(this); this._setAsBox(hx, hy, center, angle); } },{"../util/common":51,"../util/create":52,"./PolygonShape":48}],40:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = ChainShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Shape = require("../Shape"); var EdgeShape = require("./EdgeShape"); ChainShape._super = Shape; ChainShape.prototype = create(ChainShape._super.prototype); ChainShape.TYPE = "chain"; function ChainShape(vertices, loop) { if (!(this instanceof ChainShape)) { return new ChainShape(vertices, loop); } ChainShape._super.call(this); this.m_type = ChainShape.TYPE; this.m_radius = Settings.polygonRadius; this.m_vertices = []; this.m_count = 0; this.m_prevVertex = null; this.m_nextVertex = null; this.m_hasPrevVertex = false; this.m_hasNextVertex = false; if (vertices && vertices.length) { if (loop) { this._createLoop(vertices); } else { this._createChain(vertices); } } } ChainShape.prototype._createLoop = function(vertices) { _ASSERT && common.assert(this.m_vertices.length == 0 && this.m_count == 0); _ASSERT && common.assert(vertices.length >= 3); for (var i = 1; i < vertices.length; ++i) { var v1 = vertices[i - 1]; var v2 = vertices[i]; _ASSERT && common.assert(Vec2.distanceSquared(v1, v2) > Settings.linearSlopSquared); } this.m_vertices.length = 0; this.m_count = vertices.length + 1; for (var i = 0; i < vertices.length; ++i) { this.m_vertices[i] = vertices[i].clone(); } this.m_vertices[vertices.length] = vertices[0].clone(); this.m_prevVertex = this.m_vertices[this.m_count - 2]; this.m_nextVertex = this.m_vertices[1]; this.m_hasPrevVertex = true; this.m_hasNextVertex = true; return this; }; ChainShape.prototype._createChain = function(vertices) { _ASSERT && common.assert(this.m_vertices.length == 0 && this.m_count == 0); _ASSERT && common.assert(vertices.length >= 2); for (var i = 1; i < vertices.length; ++i) { var v1 = vertices[i - 1]; var v2 = vertices[i]; _ASSERT && common.assert(Vec2.distanceSquared(v1, v2) > Settings.linearSlopSquared); } this.m_count = vertices.length; for (var i = 0; i < vertices.length; ++i) { this.m_vertices[i] = vertices[i].clone(); } this.m_hasPrevVertex = false; this.m_hasNextVertex = false; this.m_prevVertex = null; this.m_nextVertex = null; return this; }; ChainShape.prototype._setPrevVertex = function(prevVertex) { this.m_prevVertex = prevVertex; this.m_hasPrevVertex = true; }; ChainShape.prototype._setNextVertex = function(nextVertex) { this.m_nextVertex = nextVertex; this.m_hasNextVertex = true; }; ChainShape.prototype._clone = function() { var clone = new ChainShape(); clone.createChain(this.m_vertices); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_prevVertex = this.m_prevVertex; clone.m_nextVertex = this.m_nextVertex; clone.m_hasPrevVertex = this.m_hasPrevVertex; clone.m_hasNextVertex = this.m_hasNextVertex; return clone; }; ChainShape.prototype.getChildCount = function() { return this.m_count - 1; }; ChainShape.prototype.getChildEdge = function(edge, childIndex) { _ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count - 1); edge.m_type = EdgeShape.TYPE; edge.m_radius = this.m_radius; edge.m_vertex1 = this.m_vertices[childIndex]; edge.m_vertex2 = this.m_vertices[childIndex + 1]; if (childIndex > 0) { edge.m_vertex0 = this.m_vertices[childIndex - 1]; edge.m_hasVertex0 = true; } else { edge.m_vertex0 = this.m_prevVertex; edge.m_hasVertex0 = this.m_hasPrevVertex; } if (childIndex < this.m_count - 2) { edge.m_vertex3 = this.m_vertices[childIndex + 2]; edge.m_hasVertex3 = true; } else { edge.m_vertex3 = this.m_nextVertex; edge.m_hasVertex3 = this.m_hasNextVertex; } }; ChainShape.prototype.getVertex = function(index) { _ASSERT && common.assert(0 <= index && index <= this.m_count); if (index < this.m_count) { return this.m_vertices[index]; } else { return this.m_vertices[0]; } }; ChainShape.prototype.testPoint = function(xf, p) { return false; }; ChainShape.prototype.rayCast = function(output, input, xf, childIndex) { _ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count); var edgeShape = new EdgeShape(this.getVertex(childIndex), this.getVertex(childIndex + 1)); return edgeShape.rayCast(output, input, xf, 0); }; ChainShape.prototype.computeAABB = function(aabb, xf, childIndex) { _ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count); var v1 = Transform.mulVec2(xf, this.getVertex(childIndex)); var v2 = Transform.mulVec2(xf, this.getVertex(childIndex + 1)); aabb.combinePoints(v1, v2); }; ChainShape.prototype.computeMass = function(massData, density) { massData.mass = 0; massData.center = Vec2.neo(); massData.I = 0; }; ChainShape.prototype.computeDistanceProxy = function(proxy, childIndex) { _ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count); proxy.m_buffer[0] = this.getVertex(childIndex); proxy.m_buffer[1] = this.getVertex(childIndex + 1); proxy.m_vertices = proxy.m_buffer; proxy.m_count = 2; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53,"./EdgeShape":47}],41:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = CircleShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Shape = require("../Shape"); CircleShape._super = Shape; CircleShape.prototype = create(CircleShape._super.prototype); CircleShape.TYPE = "circle"; function CircleShape(a, b) { if (!(this instanceof CircleShape)) { return new CircleShape(a, b); } CircleShape._super.call(this); this.m_type = CircleShape.TYPE; this.m_p = Vec2.zero(); this.m_radius = 1; if (typeof a === "object" && Vec2.isValid(a)) { this.m_p.set(a); if (typeof b === "number") { this.m_radius = b; } } else if (typeof a === "number") { this.m_radius = a; } } CircleShape.prototype.getRadius = function() { return this.m_radius; }; CircleShape.prototype.getCenter = function() { return this.m_p; }; CircleShape.prototype.getVertex = function(index) { _ASSERT && common.assert(index == 0); return this.m_p; }; CircleShape.prototype.getVertexCount = function(index) { return 1; }; CircleShape.prototype._clone = function() { var clone = new CircleShape(); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_p = this.m_p.clone(); return clone; }; CircleShape.prototype.getChildCount = function() { return 1; }; CircleShape.prototype.testPoint = function(xf, p) { var center = Vec2.add(xf.p, Rot.mulVec2(xf.q, this.m_p)); var d = Vec2.sub(p, center); return Vec2.dot(d, d) <= this.m_radius * this.m_radius; }; CircleShape.prototype.rayCast = function(output, input, xf, childIndex) { var position = Vec2.add(xf.p, Rot.mulVec2(xf.q, this.m_p)); var s = Vec2.sub(input.p1, position); var b = Vec2.dot(s, s) - this.m_radius * this.m_radius; var r = Vec2.sub(input.p2, input.p1); var c = Vec2.dot(s, r); var rr = Vec2.dot(r, r); var sigma = c * c - rr * b; if (sigma < 0 || rr < Math.EPSILON) { return false; } var a = -(c + Math.sqrt(sigma)); if (0 <= a && a <= input.maxFraction * rr) { a /= rr; output.fraction = a; output.normal = Vec2.add(s, Vec2.mul(a, r)); output.normal.normalize(); return true; } return false; }; CircleShape.prototype.computeAABB = function(aabb, xf, childIndex) { var p = Vec2.add(xf.p, Rot.mulVec2(xf.q, this.m_p)); aabb.lowerBound.set(p.x - this.m_radius, p.y - this.m_radius); aabb.upperBound.set(p.x + this.m_radius, p.y + this.m_radius); }; CircleShape.prototype.computeMass = function(massData, density) { massData.mass = density * Math.PI * this.m_radius * this.m_radius; massData.center = this.m_p; massData.I = massData.mass * (.5 * this.m_radius * this.m_radius + Vec2.dot(this.m_p, this.m_p)); }; CircleShape.prototype.computeDistanceProxy = function(proxy) { proxy.m_vertices.push(this.m_p); proxy.m_count = 1; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53}],42:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Vec2 = require("../common/Vec2"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Contact = require("../Contact"); var Manifold = require("../Manifold"); var CircleShape = require("./CircleShape"); Contact.addType(CircleShape.TYPE, CircleShape.TYPE, CircleCircleContact); function CircleCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { _ASSERT && common.assert(fixtureA.getType() == CircleShape.TYPE); _ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); CollideCircles(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB); } function CollideCircles(manifold, circleA, xfA, circleB, xfB) { manifold.pointCount = 0; var pA = Transform.mulVec2(xfA, circleA.m_p); var pB = Transform.mulVec2(xfB, circleB.m_p); var distSqr = Vec2.distanceSquared(pB, pA); var rA = circleA.m_radius; var rB = circleB.m_radius; var radius = rA + rB; if (distSqr > radius * radius) { return; } manifold.type = Manifold.e_circles; manifold.localPoint.set(circleA.m_p); manifold.localNormal.setZero(); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; } exports.CollideCircles = CollideCircles; },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"./CircleShape":41}],43:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Manifold = require("../Manifold"); var Contact = require("../Contact"); var Shape = require("../Shape"); var CircleShape = require("./CircleShape"); var PolygonShape = require("./PolygonShape"); Contact.addType(PolygonShape.TYPE, CircleShape.TYPE, PolygonCircleContact); function PolygonCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { _ASSERT && common.assert(fixtureA.getType() == PolygonShape.TYPE); _ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); CollidePolygonCircle(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB); } function CollidePolygonCircle(manifold, polygonA, xfA, circleB, xfB) { manifold.pointCount = 0; var c = Transform.mulVec2(xfB, circleB.m_p); var cLocal = Transform.mulTVec2(xfA, c); var normalIndex = 0; var separation = -Infinity; var radius = polygonA.m_radius + circleB.m_radius; var vertexCount = polygonA.m_count; var vertices = polygonA.m_vertices; var normals = polygonA.m_normals; for (var i = 0; i < vertexCount; ++i) { var s = Vec2.dot(normals[i], Vec2.sub(cLocal, vertices[i])); if (s > radius) { return; } if (s > separation) { separation = s; normalIndex = i; } } var vertIndex1 = normalIndex; var vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0; var v1 = vertices[vertIndex1]; var v2 = vertices[vertIndex2]; if (separation < Math.EPSILON) { manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.set(normals[normalIndex]); manifold.localPoint.setCombine(.5, v1, .5, v2); manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; return; } var u1 = Vec2.dot(Vec2.sub(cLocal, v1), Vec2.sub(v2, v1)); var u2 = Vec2.dot(Vec2.sub(cLocal, v2), Vec2.sub(v1, v2)); if (u1 <= 0) { if (Vec2.distanceSquared(cLocal, v1) > radius * radius) { return; } manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.setCombine(1, cLocal, -1, v1); manifold.localNormal.normalize(); manifold.localPoint.set(v1); manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; } else if (u2 <= 0) { if (Vec2.distanceSquared(cLocal, v2) > radius * radius) { return; } manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.setCombine(1, cLocal, -1, v2); manifold.localNormal.normalize(); manifold.localPoint.set(v2); manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; } else { var faceCenter = Vec2.mid(v1, v2); var separation = Vec2.dot(cLocal, normals[vertIndex1]) - Vec2.dot(faceCenter, normals[vertIndex1]); if (separation > radius) { return; } manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.set(normals[vertIndex1]); manifold.localPoint.set(faceCenter); manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; } } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"./CircleShape":41,"./PolygonShape":48}],44:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Vec2 = require("../common/Vec2"); var Rot = require("../common/Rot"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Contact = require("../Contact"); var Manifold = require("../Manifold"); var EdgeShape = require("./EdgeShape"); var ChainShape = require("./ChainShape"); var CircleShape = require("./CircleShape"); Contact.addType(EdgeShape.TYPE, CircleShape.TYPE, EdgeCircleContact); Contact.addType(ChainShape.TYPE, CircleShape.TYPE, ChainCircleContact); function EdgeCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { _ASSERT && common.assert(fixtureA.getType() == EdgeShape.TYPE); _ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); var shapeA = fixtureA.getShape(); var shapeB = fixtureB.getShape(); CollideEdgeCircle(manifold, shapeA, xfA, shapeB, xfB); } function ChainCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { _ASSERT && common.assert(fixtureA.getType() == ChainShape.TYPE); _ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); var chain = fixtureA.getShape(); var edge = new EdgeShape(); chain.getChildEdge(edge, indexA); var shapeA = edge; var shapeB = fixtureB.getShape(); CollideEdgeCircle(manifold, shapeA, xfA, shapeB, xfB); } function CollideEdgeCircle(manifold, edgeA, xfA, circleB, xfB) { manifold.pointCount = 0; var Q = Transform.mulTVec2(xfA, Transform.mulVec2(xfB, circleB.m_p)); var A = edgeA.m_vertex1; var B = edgeA.m_vertex2; var e = Vec2.sub(B, A); var u = Vec2.dot(e, Vec2.sub(B, Q)); var v = Vec2.dot(e, Vec2.sub(Q, A)); var radius = edgeA.m_radius + circleB.m_radius; if (v <= 0) { var P = Vec2.clone(A); var d = Vec2.sub(Q, P); var dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } if (edgeA.m_hasVertex0) { var A1 = edgeA.m_vertex0; var B1 = A; var e1 = Vec2.sub(B1, A1); var u1 = Vec2.dot(e1, Vec2.sub(B1, Q)); if (u1 > 0) { return; } } manifold.type = Manifold.e_circles; manifold.localNormal.setZero(); manifold.localPoint.set(P); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; return; } if (u <= 0) { var P = Vec2.clone(B); var d = Vec2.sub(Q, P); var dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } if (edgeA.m_hasVertex3) { var B2 = edgeA.m_vertex3; var A2 = B; var e2 = Vec2.sub(B2, A2); var v2 = Vec2.dot(e2, Vec2.sub(Q, A2)); if (v2 > 0) { return; } } manifold.type = Manifold.e_circles; manifold.localNormal.setZero(); manifold.localPoint.set(P); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.cf.indexA = 1; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; return; } var den = Vec2.dot(e, e); _ASSERT && common.assert(den > 0); var P = Vec2.combine(u / den, A, v / den, B); var d = Vec2.sub(Q, P); var dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } var n = Vec2.neo(-e.y, e.x); if (Vec2.dot(n, Vec2.sub(Q, A)) < 0) { n.set(-n.x, -n.y); } n.normalize(); manifold.type = Manifold.e_faceA; manifold.localNormal.set(n); manifold.localPoint.set(A); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_face; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"./ChainShape":40,"./CircleShape":41,"./EdgeShape":47}],45:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Vec2 = require("../common/Vec2"); var Rot = require("../common/Rot"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Contact = require("../Contact"); var Manifold = require("../Manifold"); var EdgeShape = require("./EdgeShape"); var ChainShape = require("./ChainShape"); var PolygonShape = require("./PolygonShape"); Contact.addType(EdgeShape.TYPE, PolygonShape.TYPE, EdgePolygonContact); Contact.addType(ChainShape.TYPE, PolygonShape.TYPE, ChainPolygonContact); function EdgePolygonContact(manifold, xfA, fA, indexA, xfB, fB, indexB) { _ASSERT && common.assert(fA.getType() == EdgeShape.TYPE); _ASSERT && common.assert(fB.getType() == PolygonShape.TYPE); CollideEdgePolygon(manifold, fA.getShape(), xfA, fB.getShape(), xfB); } function ChainPolygonContact(manifold, xfA, fA, indexA, xfB, fB, indexB) { _ASSERT && common.assert(fA.getType() == ChainShape.TYPE); _ASSERT && common.assert(fB.getType() == PolygonShape.TYPE); var chain = fA.getShape(); var edge = new EdgeShape(); chain.getChildEdge(edge, indexA); CollideEdgePolygon(manifold, edge, xfA, fB.getShape(), xfB); } var e_unknown = -1; var e_edgeA = 1; var e_edgeB = 2; var e_isolated = 0; var e_concave = 1; var e_convex = 2; function EPAxis() { this.type; this.index; this.separation; } function TempPolygon() { this.vertices = []; this.normals = []; this.count = 0; } function ReferenceFace() { this.i1, this.i2; this.v1, this.v2; this.normal = Vec2.zero(); this.sideNormal1 = Vec2.zero(); this.sideOffset1; this.sideNormal2 = Vec2.zero(); this.sideOffset2; } var edgeAxis = new EPAxis(); var polygonAxis = new EPAxis(); var polygonBA = new TempPolygon(); var rf = new ReferenceFace(); function CollideEdgePolygon(manifold, edgeA, xfA, polygonB, xfB) { var m_type1, m_type2; var xf = Transform.mulTXf(xfA, xfB); var centroidB = Transform.mulVec2(xf, polygonB.m_centroid); var v0 = edgeA.m_vertex0; var v1 = edgeA.m_vertex1; var v2 = edgeA.m_vertex2; var v3 = edgeA.m_vertex3; var hasVertex0 = edgeA.m_hasVertex0; var hasVertex3 = edgeA.m_hasVertex3; var edge1 = Vec2.sub(v2, v1); edge1.normalize(); var normal1 = Vec2.neo(edge1.y, -edge1.x); var offset1 = Vec2.dot(normal1, Vec2.sub(centroidB, v1)); var offset0 = 0; var offset2 = 0; var convex1 = false; var convex2 = false; if (hasVertex0) { var edge0 = Vec2.sub(v1, v0); edge0.normalize(); var normal0 = Vec2.neo(edge0.y, -edge0.x); convex1 = Vec2.cross(edge0, edge1) >= 0; offset0 = Vec2.dot(normal0, centroidB) - Vec2.dot(normal0, v0); } if (hasVertex3) { var edge2 = Vec2.sub(v3, v2); edge2.normalize(); var normal2 = Vec2.neo(edge2.y, -edge2.x); convex2 = Vec2.cross(edge1, edge2) > 0; offset2 = Vec2.dot(normal2, centroidB) - Vec2.dot(normal2, v2); } var front; var normal = Vec2.zero(); var lowerLimit = Vec2.zero(); var upperLimit = Vec2.zero(); if (hasVertex0 && hasVertex3) { if (convex1 && convex2) { front = offset0 >= 0 || offset1 >= 0 || offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.set(normal2); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal1); upperLimit.setMul(-1, normal1); } } else if (convex1) { front = offset0 >= 0 || offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.set(normal1); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal2); upperLimit.setMul(-1, normal1); } } else if (convex2) { front = offset2 >= 0 || offset0 >= 0 && offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.set(normal2); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal1); upperLimit.setMul(-1, normal0); } } else { front = offset0 >= 0 && offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.set(normal1); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal2); upperLimit.setMul(-1, normal0); } } } else if (hasVertex0) { if (convex1) { front = offset0 >= 0 || offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.setMul(-1, normal1); } else { normal.setMul(-1, normal1); lowerLimit.set(normal1); upperLimit.setMul(-1, normal1); } } else { front = offset0 >= 0 && offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.setMul(-1, normal1); } else { normal.setMul(-1, normal1); lowerLimit.set(normal1); upperLimit.setMul(-1, normal0); } } } else if (hasVertex3) { if (convex2) { front = offset1 >= 0 || offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.setMul(-1, normal1); upperLimit.set(normal2); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal1); upperLimit.set(normal1); } } else { front = offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.setMul(-1, normal1); upperLimit.set(normal1); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal2); upperLimit.set(normal1); } } } else { front = offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.setMul(-1, normal1); upperLimit.setMul(-1, normal1); } else { normal.setMul(-1, normal1); lowerLimit.set(normal1); upperLimit.set(normal1); } } polygonBA.count = polygonB.m_count; for (var i = 0; i < polygonB.m_count; ++i) { polygonBA.vertices[i] = Transform.mulVec2(xf, polygonB.m_vertices[i]); polygonBA.normals[i] = Rot.mulVec2(xf.q, polygonB.m_normals[i]); } var radius = 2 * Settings.polygonRadius; manifold.pointCount = 0; { edgeAxis.type = e_edgeA; edgeAxis.index = front ? 0 : 1; edgeAxis.separation = Infinity; for (var i = 0; i < polygonBA.count; ++i) { var s = Vec2.dot(normal, Vec2.sub(polygonBA.vertices[i], v1)); if (s < edgeAxis.separation) { edgeAxis.separation = s; } } } if (edgeAxis.type == e_unknown) { return; } if (edgeAxis.separation > radius) { return; } { polygonAxis.type = e_unknown; polygonAxis.index = -1; polygonAxis.separation = -Infinity; var perp = Vec2.neo(-normal.y, normal.x); for (var i = 0; i < polygonBA.count; ++i) { var n = Vec2.neg(polygonBA.normals[i]); var s1 = Vec2.dot(n, Vec2.sub(polygonBA.vertices[i], v1)); var s2 = Vec2.dot(n, Vec2.sub(polygonBA.vertices[i], v2)); var s = Math.min(s1, s2); if (s > radius) { polygonAxis.type = e_edgeB; polygonAxis.index = i; polygonAxis.separation = s; break; } if (Vec2.dot(n, perp) >= 0) { if (Vec2.dot(Vec2.sub(n, upperLimit), normal) < -Settings.angularSlop) { continue; } } else { if (Vec2.dot(Vec2.sub(n, lowerLimit), normal) < -Settings.angularSlop) { continue; } } if (s > polygonAxis.separation) { polygonAxis.type = e_edgeB; polygonAxis.index = i; polygonAxis.separation = s; } } } if (polygonAxis.type != e_unknown && polygonAxis.separation > radius) { return; } var k_relativeTol = .98; var k_absoluteTol = .001; var primaryAxis; if (polygonAxis.type == e_unknown) { primaryAxis = edgeAxis; } else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) { primaryAxis = polygonAxis; } else { primaryAxis = edgeAxis; } var ie = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; if (primaryAxis.type == e_edgeA) { manifold.type = Manifold.e_faceA; var bestIndex = 0; var bestValue = Vec2.dot(normal, polygonBA.normals[0]); for (var i = 1; i < polygonBA.count; ++i) { var value = Vec2.dot(normal, polygonBA.normals[i]); if (value < bestValue) { bestValue = value; bestIndex = i; } } var i1 = bestIndex; var i2 = i1 + 1 < polygonBA.count ? i1 + 1 : 0; ie[0].v = polygonBA.vertices[i1]; ie[0].id.cf.indexA = 0; ie[0].id.cf.indexB = i1; ie[0].id.cf.typeA = Manifold.e_face; ie[0].id.cf.typeB = Manifold.e_vertex; ie[1].v = polygonBA.vertices[i2]; ie[1].id.cf.indexA = 0; ie[1].id.cf.indexB = i2; ie[1].id.cf.typeA = Manifold.e_face; ie[1].id.cf.typeB = Manifold.e_vertex; if (front) { rf.i1 = 0; rf.i2 = 1; rf.v1 = v1; rf.v2 = v2; rf.normal.set(normal1); } else { rf.i1 = 1; rf.i2 = 0; rf.v1 = v2; rf.v2 = v1; rf.normal.setMul(-1, normal1); } } else { manifold.type = Manifold.e_faceB; ie[0].v = v1; ie[0].id.cf.indexA = 0; ie[0].id.cf.indexB = primaryAxis.index; ie[0].id.cf.typeA = Manifold.e_vertex; ie[0].id.cf.typeB = Manifold.e_face; ie[1].v = v2; ie[1].id.cf.indexA = 0; ie[1].id.cf.indexB = primaryAxis.index; ie[1].id.cf.typeA = Manifold.e_vertex; ie[1].id.cf.typeB = Manifold.e_face; rf.i1 = primaryAxis.index; rf.i2 = rf.i1 + 1 < polygonBA.count ? rf.i1 + 1 : 0; rf.v1 = polygonBA.vertices[rf.i1]; rf.v2 = polygonBA.vertices[rf.i2]; rf.normal.set(polygonBA.normals[rf.i1]); } rf.sideNormal1.set(rf.normal.y, -rf.normal.x); rf.sideNormal2.setMul(-1, rf.sideNormal1); rf.sideOffset1 = Vec2.dot(rf.sideNormal1, rf.v1); rf.sideOffset2 = Vec2.dot(rf.sideNormal2, rf.v2); var clipPoints1 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var clipPoints2 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var np; np = Manifold.clipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); if (np < Settings.maxManifoldPoints) { return; } np = Manifold.clipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); if (np < Settings.maxManifoldPoints) { return; } if (primaryAxis.type == e_edgeA) { manifold.localNormal = Vec2.clone(rf.normal); manifold.localPoint = Vec2.clone(rf.v1); } else { manifold.localNormal = Vec2.clone(polygonB.m_normals[rf.i1]); manifold.localPoint = Vec2.clone(polygonB.m_vertices[rf.i1]); } var pointCount = 0; for (var i = 0; i < Settings.maxManifoldPoints; ++i) { var separation = Vec2.dot(rf.normal, Vec2.sub(clipPoints2[i].v, rf.v1)); if (separation <= radius) { var cp = manifold.points[pointCount]; if (primaryAxis.type == e_edgeA) { cp.localPoint = Transform.mulT(xf, clipPoints2[i].v); cp.id = clipPoints2[i].id; } else { cp.localPoint = clipPoints2[i].v; cp.id.cf.typeA = clipPoints2[i].id.cf.typeB; cp.id.cf.typeB = clipPoints2[i].id.cf.typeA; cp.id.cf.indexA = clipPoints2[i].id.cf.indexB; cp.id.cf.indexB = clipPoints2[i].id.cf.indexA; } ++pointCount; } } manifold.pointCount = pointCount; } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"./ChainShape":40,"./EdgeShape":47,"./PolygonShape":48}],46:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Manifold = require("../Manifold"); var Contact = require("../Contact"); var Shape = require("../Shape"); var PolygonShape = require("./PolygonShape"); module.exports = CollidePolygons; Contact.addType(PolygonShape.TYPE, PolygonShape.TYPE, PolygonContact); function PolygonContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { _ASSERT && common.assert(fixtureA.getType() == PolygonShape.TYPE); _ASSERT && common.assert(fixtureB.getType() == PolygonShape.TYPE); CollidePolygons(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB); } var fms_v1 = Vec2.zero(); var fms_n = Vec2.zero(); var fms_xf = Transform.identity(); var fms_maxSeparation; var fms_bestIndex; function FindMaxSeparation(poly1, xf1, poly2, xf2) { var count1 = poly1.m_count; var count2 = poly2.m_count; var n1s = poly1.m_normals; var v1s = poly1.m_vertices; var v2s = poly2.m_vertices; var xf = Transform.mulTXf_(xf2, xf1, fms_xf); var bestIndex = 0; var maxSeparation = -Infinity; for (var i = 0; i < count1; ++i) { var n = Rot.mulVec2_(xf.q, n1s[i], fms_n); var v1 = Transform.mulVec2_(xf, v1s[i], fms_v1); var si = Infinity; for (var j = 0; j < count2; ++j) { var sij = Vec2.dot(n, v2s[j]) - Vec2.dot(n, v1); if (sij < si) { si = sij; } } if (si > maxSeparation) { maxSeparation = si; bestIndex = i; } } fms_maxSeparation = maxSeparation; fms_bestIndex = bestIndex; } var fie_t1 = Vec2.zero(); var fie_normal1 = Vec2.zero(); function FindIncidentEdge(c, poly1, xf1, edge1, poly2, xf2) { var normals1 = poly1.m_normals; var count2 = poly2.m_count; var vertices2 = poly2.m_vertices; var normals2 = poly2.m_normals; _ASSERT && common.assert(0 <= edge1 && edge1 < poly1.m_count); var normal1 = Rot.mulTVec2_(xf2.q, Rot.mulVec2_(xf1.q, normals1[edge1], fie_t1), fie_normal1); var index = 0; var minDot = Infinity; for (var i = 0; i < count2; ++i) { var dot = Vec2.dot(normal1, normals2[i]); if (dot < minDot) { minDot = dot; index = i; } } var i1 = index; var i2 = i1 + 1 < count2 ? i1 + 1 : 0; c[0].v = Transform.mulVec2(xf2, vertices2[i1]); c[0].id.cf.indexA = edge1; c[0].id.cf.indexB = i1; c[0].id.cf.typeA = Manifold.e_face; c[0].id.cf.typeB = Manifold.e_vertex; c[1].v = Transform.mulVec2(xf2, vertices2[i2]); c[1].id.cf.indexA = edge1; c[1].id.cf.indexB = i2; c[1].id.cf.typeA = Manifold.e_face; c[1].id.cf.typeB = Manifold.e_vertex; } var cpg_planePoint = Vec2.zero(); var cpg_tangent = Vec2.zero(); var cpg_normal = Vec2.zero(); var cpg_localTangent = Vec2.zero(); var cpg_localNormal = Vec2.zero(); var cpg_v11 = Vec2.zero(); var cpg_v12 = Vec2.zero(); var cpg_t1 = Vec2.zero(); var cpg_clipPoints1 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var cpg_clipPoints2 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var cpg_incidentEdge = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; function CollidePolygons(manifold, polyA, xfA, polyB, xfB) { manifold.pointCount = 0; var totalRadius = polyA.m_radius + polyB.m_radius; FindMaxSeparation(polyA, xfA, polyB, xfB); var edgeA = fms_bestIndex; var separationA = fms_maxSeparation; if (separationA > totalRadius) return; FindMaxSeparation(polyB, xfB, polyA, xfA); var edgeB = fms_bestIndex; var separationB = fms_maxSeparation; if (separationB > totalRadius) return; var poly1; var poly2; var xf1; var xf2; var edge1; var flip; var k_tol = .1 * Settings.linearSlop; if (separationB > separationA + k_tol) { poly1 = polyB; poly2 = polyA; xf1 = xfB; xf2 = xfA; edge1 = edgeB; manifold.type = Manifold.e_faceB; flip = 1; } else { poly1 = polyA; poly2 = polyB; xf1 = xfA; xf2 = xfB; edge1 = edgeA; manifold.type = Manifold.e_faceA; flip = 0; } var incidentEdge = cpg_incidentEdge; cpg_incidentEdge[0].init(); cpg_incidentEdge[1].init(); FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); var count1 = poly1.m_count; var vertices1 = poly1.m_vertices; var iv1 = edge1; var iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0; var v11 = cpg_v11.set(vertices1[iv1]); var v12 = cpg_v12.set(vertices1[iv2]); var localTangent = Vec2.sub_(v12, v11, cpg_localTangent); localTangent.normalize(); var localNormal = Vec2.crossVec2Num_(localTangent, 1, cpg_localNormal); var planePoint = Vec2.combine_(.5, v11, .5, v12, cpg_planePoint); var tangent = Rot.mulVec2_(xf1.q, localTangent, cpg_tangent); var normal = Vec2.crossVec2Num_(tangent, 1, cpg_normal); v11 = Transform.mulVec2_(xf1, v11, v11); v12 = Transform.mulVec2_(xf1, v12, v12); var frontOffset = Vec2.dot(normal, v11); var sideOffset1 = -Vec2.dot(tangent, v11) + totalRadius; var sideOffset2 = Vec2.dot(tangent, v12) + totalRadius; cpg_clipPoints1[0].init(); cpg_clipPoints1[1].init(); cpg_clipPoints2[0].init(); cpg_clipPoints2[1].init(); var clipPoints1 = cpg_clipPoints1; var clipPoints2 = cpg_clipPoints2; var np; np = Manifold.clipSegmentToLine(clipPoints1, incidentEdge, Vec2.neg_(tangent, cpg_t1), sideOffset1, iv1); if (np < Settings.maxManifoldPoints) { return; } np = Manifold.clipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2); if (np < Settings.maxManifoldPoints) { return; } manifold.localNormal.set(localNormal); manifold.localPoint.set(planePoint); var pointCount = 0; for (var i = 0; i < Settings.maxManifoldPoints; ++i) { var separation = Vec2.dot(normal, clipPoints2[i].v) - frontOffset; if (separation <= totalRadius) { var cp = manifold.points[i]; cp.init(); cp.localPoint.set(Transform.mulTVec2(xf2, clipPoints2[i].v, cpg_t1)); cp.id = clipPoints2[i].id; if (flip) { var cf = cp.id.cf; var indexA = cf.indexA; var indexB = cf.indexB; var typeA = cf.typeA; var typeB = cf.typeB; cf.indexA = indexB; cf.indexB = indexA; cf.typeA = typeB; cf.typeB = typeA; } ++pointCount; } } manifold.pointCount = pointCount; } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"./PolygonShape":48}],47:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = EdgeShape; var create = require("../util/create"); var options = require("../util/options"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); EdgeShape._super = Shape; EdgeShape.prototype = create(EdgeShape._super.prototype); EdgeShape.TYPE = "edge"; function EdgeShape(v1, v2) { if (!(this instanceof EdgeShape)) { return new EdgeShape(v1, v2); } EdgeShape._super.call(this); this.m_type = EdgeShape.TYPE; this.m_radius = Settings.polygonRadius; this.m_vertex1 = v1 ? Vec2.clone(v1) : Vec2.zero(); this.m_vertex2 = v2 ? Vec2.clone(v2) : Vec2.zero(); this.m_vertex0 = Vec2.zero(); this.m_vertex3 = Vec2.zero(); this.m_hasVertex0 = false; this.m_hasVertex3 = false; } EdgeShape.prototype.setNext = function(v3) { if (v3) { this.m_vertex3.set(v3); this.m_hasVertex3 = true; } else { this.m_vertex3.setZero(); this.m_hasVertex3 = false; } return this; }; EdgeShape.prototype.setPrev = function(v0) { if (v0) { this.m_vertex0.set(v0); this.m_hasVertex0 = true; } else { this.m_vertex0.setZero(); this.m_hasVertex0 = false; } return this; }; EdgeShape.prototype._set = function(v1, v2) { this.m_vertex1.set(v1); this.m_vertex2.set(v2); this.m_hasVertex0 = false; this.m_hasVertex3 = false; return this; }; EdgeShape.prototype._clone = function() { var clone = new EdgeShape(); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_vertex1.set(this.m_vertex1); clone.m_vertex2.set(this.m_vertex2); clone.m_vertex0.set(this.m_vertex0); clone.m_vertex3.set(this.m_vertex3); clone.m_hasVertex0 = this.m_hasVertex0; clone.m_hasVertex3 = this.m_hasVertex3; return clone; }; EdgeShape.prototype.getChildCount = function() { return 1; }; EdgeShape.prototype.testPoint = function(xf, p) { return false; }; EdgeShape.prototype.rayCast = function(output, input, xf, childIndex) { var p1 = Rot.mulTVec2(xf.q, Vec2.sub(input.p1, xf.p)); var p2 = Rot.mulTVec2(xf.q, Vec2.sub(input.p2, xf.p)); var d = Vec2.sub(p2, p1); var v1 = this.m_vertex1; var v2 = this.m_vertex2; var e = Vec2.sub(v2, v1); var normal = Vec2.neo(e.y, -e.x); normal.normalize(); var numerator = Vec2.dot(normal, Vec2.sub(v1, p1)); var denominator = Vec2.dot(normal, d); if (denominator == 0) { return false; } var t = numerator / denominator; if (t < 0 || input.maxFraction < t) { return false; } var q = Vec2.add(p1, Vec2.mul(t, d)); var r = Vec2.sub(v2, v1); var rr = Vec2.dot(r, r); if (rr == 0) { return false; } var s = Vec2.dot(Vec2.sub(q, v1), r) / rr; if (s < 0 || 1 < s) { return false; } output.fraction = t; if (numerator > 0) { output.normal = Rot.mulVec2(xf.q, normal).neg(); } else { output.normal = Rot.mulVec2(xf.q, normal); } return true; }; EdgeShape.prototype.computeAABB = function(aabb, xf, childIndex) { var v1 = Transform.mulVec2(xf, this.m_vertex1); var v2 = Transform.mulVec2(xf, this.m_vertex2); aabb.combinePoints(v1, v2); aabb.extend(this.m_radius); }; EdgeShape.prototype.computeMass = function(massData, density) { massData.mass = 0; massData.center.setCombine(.5, this.m_vertex1, .5, this.m_vertex2); massData.I = 0; }; EdgeShape.prototype.computeDistanceProxy = function(proxy) { proxy.m_vertices.push(this.m_vertex1); proxy.m_vertices.push(this.m_vertex2); proxy.m_count = 2; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/create":52,"../util/options":53}],48:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = PolygonShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Shape = require("../Shape"); PolygonShape._super = Shape; PolygonShape.prototype = create(PolygonShape._super.prototype); PolygonShape.TYPE = "polygon"; function PolygonShape(vertices) { if (!(this instanceof PolygonShape)) { return new PolygonShape(vertices); } PolygonShape._super.call(this); this.m_type = PolygonShape.TYPE; this.m_radius = Settings.polygonRadius; this.m_centroid = Vec2.zero(); this.m_vertices = []; this.m_normals = []; this.m_count = 0; if (vertices && vertices.length) { this._set(vertices); } } PolygonShape.prototype.getVertex = function(index) { _ASSERT && common.assert(0 <= index && index < this.m_count); return this.m_vertices[index]; }; PolygonShape.prototype._clone = function() { var clone = new PolygonShape(); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_count = this.m_count; clone.m_centroid.set(this.m_centroid); for (var i = 0; i < this.m_count; i++) { clone.m_vertices.push(this.m_vertices[i].clone()); } for (var i = 0; i < this.m_normals.length; i++) { clone.m_normals.push(this.m_normals[i].clone()); } return clone; }; PolygonShape.prototype.getChildCount = function() { return 1; }; function ComputeCentroid(vs, count) { _ASSERT && common.assert(count >= 3); var c = Vec2.zero(); var area = 0; var pRef = Vec2.zero(); if (false) { for (var i = 0; i < count; ++i) { pRef.add(vs[i]); } pRef.mul(1 / count); } var inv3 = 1 / 3; for (var i = 0; i < count; ++i) { var p1 = pRef; var p2 = vs[i]; var p3 = i + 1 < count ? vs[i + 1] : vs[0]; var e1 = Vec2.sub(p2, p1); var e2 = Vec2.sub(p3, p1); var D = Vec2.cross(e1, e2); var triangleArea = .5 * D; area += triangleArea; c.addMul(triangleArea * inv3, p1); c.addMul(triangleArea * inv3, p2); c.addMul(triangleArea * inv3, p3); } _ASSERT && common.assert(area > Math.EPSILON); c.mul(1 / area); return c; } PolygonShape.prototype._set = function(vertices) { _ASSERT && common.assert(3 <= vertices.length && vertices.length <= Settings.maxPolygonVertices); if (vertices.length < 3) { this._setAsBox(1, 1); return; } var n = Math.min(vertices.length, Settings.maxPolygonVertices); var ps = []; var tempCount = 0; for (var i = 0; i < n; ++i) { var v = vertices[i]; var unique = true; for (var j = 0; j < tempCount; ++j) { if (Vec2.distanceSquared(v, ps[j]) < .25 * Settings.linearSlopSquared) { unique = false; break; } } if (unique) { ps[tempCount++] = v; } } n = tempCount; if (n < 3) { _ASSERT && common.assert(false); this._setAsBox(1, 1); return; } var i0 = 0; var x0 = ps[0].x; for (var i = 1; i < n; ++i) { var x = ps[i].x; if (x > x0 || x == x0 && ps[i].y < ps[i0].y) { i0 = i; x0 = x; } } var hull = []; var m = 0; var ih = i0; for (;;) { hull[m] = ih; var ie = 0; for (var j = 1; j < n; ++j) { if (ie == ih) { ie = j; continue; } var r = Vec2.sub(ps[ie], ps[hull[m]]); var v = Vec2.sub(ps[j], ps[hull[m]]); var c = Vec2.cross(r, v); if (c < 0) { ie = j; } if (c == 0 && v.lengthSquared() > r.lengthSquared()) { ie = j; } } ++m; ih = ie; if (ie == i0) { break; } } if (m < 3) { _ASSERT && common.assert(false); this._setAsBox(1, 1); return; } this.m_count = m; for (var i = 0; i < m; ++i) { this.m_vertices[i] = ps[hull[i]]; } for (var i = 0; i < m; ++i) { var i1 = i; var i2 = i + 1 < m ? i + 1 : 0; var edge = Vec2.sub(this.m_vertices[i2], this.m_vertices[i1]); _ASSERT && common.assert(edge.lengthSquared() > Math.EPSILON * Math.EPSILON); this.m_normals[i] = Vec2.cross(edge, 1); this.m_normals[i].normalize(); } this.m_centroid = ComputeCentroid(this.m_vertices, m); }; PolygonShape.prototype._setAsBox = function(hx, hy, center, angle) { this.m_vertices[0] = Vec2.neo(-hx, -hy); this.m_vertices[1] = Vec2.neo(hx, -hy); this.m_vertices[2] = Vec2.neo(hx, hy); this.m_vertices[3] = Vec2.neo(-hx, hy); this.m_normals[0] = Vec2.neo(0, -1); this.m_normals[1] = Vec2.neo(1, 0); this.m_normals[2] = Vec2.neo(0, 1); this.m_normals[3] = Vec2.neo(-1, 0); this.m_count = 4; if (Vec2.isValid(center)) { angle = angle || 0; this.m_centroid.set(center); var xf = Transform.identity(); xf.p.set(center); xf.q.set(angle); for (var i = 0; i < this.m_count; ++i) { this.m_vertices[i] = Transform.mulVec2(xf, this.m_vertices[i]); this.m_normals[i] = Rot.mulVec2(xf.q, this.m_normals[i]); } } }; PolygonShape.prototype.testPoint = function(xf, p) { var pLocal = Rot.mulTVec2(xf.q, Vec2.sub(p, xf.p)); for (var i = 0; i < this.m_count; ++i) { var dot = Vec2.dot(this.m_normals[i], Vec2.sub(pLocal, this.m_vertices[i])); if (dot > 0) { return false; } } return true; }; PolygonShape.prototype.rayCast = function(output, input, xf, childIndex) { var p1 = Rot.mulTVec2(xf.q, Vec2.sub(input.p1, xf.p)); var p2 = Rot.mulTVec2(xf.q, Vec2.sub(input.p2, xf.p)); var d = Vec2.sub(p2, p1); var lower = 0; var upper = input.maxFraction; var index = -1; for (var i = 0; i < this.m_count; ++i) { var numerator = Vec2.dot(this.m_normals[i], Vec2.sub(this.m_vertices[i], p1)); var denominator = Vec2.dot(this.m_normals[i], d); if (denominator == 0) { if (numerator < 0) { return false; } } else { if (denominator < 0 && numerator < lower * denominator) { lower = numerator / denominator; index = i; } else if (denominator > 0 && numerator < upper * denominator) { upper = numerator / denominator; } } if (upper < lower) { return false; } } _ASSERT && common.assert(0 <= lower && lower <= input.maxFraction); if (index >= 0) { output.fraction = lower; output.normal = Rot.mulVec2(xf.q, this.m_normals[index]); return true; } return false; }; PolygonShape.prototype.computeAABB = function(aabb, xf, childIndex) { var minX = Infinity, minY = Infinity; var maxX = -Infinity, maxY = -Infinity; for (var i = 0; i < this.m_count; ++i) { var v = Transform.mulVec2(xf, this.m_vertices[i]); minX = Math.min(minX, v.x); maxX = Math.max(maxX, v.x); minY = Math.min(minY, v.y); maxY = Math.max(maxY, v.y); } aabb.lowerBound.set(minX, minY); aabb.upperBound.set(maxX, maxY); aabb.extend(this.m_radius); }; PolygonShape.prototype.computeMass = function(massData, density) { _ASSERT && common.assert(this.m_count >= 3); var center = Vec2.zero(); var area = 0; var I = 0; var s = Vec2.zero(); for (var i = 0; i < this.m_count; ++i) { s.add(this.m_vertices[i]); } s.mul(1 / this.m_count); var k_inv3 = 1 / 3; for (var i = 0; i < this.m_count; ++i) { var e1 = Vec2.sub(this.m_vertices[i], s); var e2 = i + 1 < this.m_count ? Vec2.sub(this.m_vertices[i + 1], s) : Vec2.sub(this.m_vertices[0], s); var D = Vec2.cross(e1, e2); var triangleArea = .5 * D; area += triangleArea; center.addCombine(triangleArea * k_inv3, e1, triangleArea * k_inv3, e2); var ex1 = e1.x; var ey1 = e1.y; var ex2 = e2.x; var ey2 = e2.y; var intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2; var inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2; I += .25 * k_inv3 * D * (intx2 + inty2); } massData.mass = density * area; _ASSERT && common.assert(area > Math.EPSILON); center.mul(1 / area); massData.center.setCombine(1, center, 1, s); massData.I = density * I; massData.I += massData.mass * (Vec2.dot(massData.center, massData.center) - Vec2.dot(center, center)); }; PolygonShape.prototype.validate = function() { for (var i = 0; i < this.m_count; ++i) { var i1 = i; var i2 = i < this.m_count - 1 ? i1 + 1 : 0; var p = this.m_vertices[i1]; var e = Vec2.sub(this.m_vertices[i2], p); for (var j = 0; j < this.m_count; ++j) { if (j == i1 || j == i2) { continue; } var v = Vec2.sub(this.m_vertices[j], p); var c = Vec2.cross(e, v); if (c < 0) { return false; } } } return true; }; PolygonShape.prototype.computeDistanceProxy = function(proxy) { proxy.m_vertices = this.m_vertices; proxy.m_count = this.m_count; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53}],49:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Pool; function Pool(opts) { var _queue = []; var _max = opts.max || Infinity; var _createFn = opts.create || function() { return {}; }; var _outFn = opts.allocate || function() {}; var _inFn = opts.release || function() {}; var _discardFn = opts.discard || function() {}; var _createCount = 0; var _outCount = 0; var _inCount = 0; var _discardCount = 0; this.max = function(n) { if (typeof n === "number") { _max = n; return this; } return _max; }; this.size = function() { return _queue.length; }; this.allocate = function() { var obj; if (_queue.length > 0) { obj = _queue.shift(); } else { _createCount++; obj = _createFn(); } _outCount++; _outFn(obj); return obj; }; this.release = function(obj) { if (_queue.length < _max) { _inCount++; _inFn(obj); _queue.push(obj); } else { _discardCount++; _discardFn(obj); } }; this.toString = function() { return " +" + _createCount + " >" + _outCount + " <" + _inCount + " -" + _discardCount + " =" + _queue.length + "/" + _max; }; } },{}],50:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports.now = function() { return Date.now(); }; module.exports.diff = function(time) { return Date.now() - time; }; },{}],51:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; exports.debug = function() { if (!_DEBUG) return; console.log.apply(console, arguments); }; exports.assert = function(statement, err, log) { if (!_ASSERT) return; if (statement) return; log && console.log(log); throw new Error(err); }; },{}],52:[function(require,module,exports){ if (typeof Object.create == "function") { module.exports = function(proto, props) { return Object.create.call(Object, proto, props); }; } else { module.exports = function(proto, props) { if (props) throw Error("Second argument is not supported!"); if (typeof proto !== "object" || proto === null) throw Error("Invalid prototype!"); noop.prototype = proto; return new noop(); }; function noop() {} } },{}],53:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var propIsEnumerable = Object.prototype.propertyIsEnumerable; module.exports = function(to, from) { if (to === null || typeof to === "undefined") { to = {}; } for (var key in from) { if (from.hasOwnProperty(key) && typeof to[key] === "undefined") { to[key] = from[key]; } } if (typeof Object.getOwnPropertySymbols === "function") { var symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { var symbol = symbols[i]; if (from.propertyIsEnumerable(symbol) && typeof to[key] === "undefined") { to[symbol] = from[symbol]; } } } return to; }; },{}],54:[function(require,module,exports){ function _identity(x) { return x; }; var _cache = {}; var _modes = {}; var _easings = {}; function Easing(token) { if (typeof token === 'function') { return token; } if (typeof token !== 'string') { return _identity; } var fn = _cache[token]; if (fn) { return fn; } var match = /^(\w+)(-(in|out|in-out|out-in))?(\((.*)\))?$/i.exec(token); if (!match || !match.length) { return _identity; } var easing = _easings[match[1]]; var mode = _modes[match[3]]; var params = match[5]; if (easing && easing.fn) { fn = easing.fn; } else if (easing && easing.fc) { fn = easing.fc.apply(easing.fc, params && params.replace(/\s+/, '').split(',')); } else { fn = _identity; } if (mode) { fn = mode.fn(fn); } // TODO: It can be a memory leak with different `params`. _cache[token] = fn; return fn; }; Easing.add = function(data) { // TODO: create a map of all { name-mode : data } var names = (data.name || data.mode).split(/\s+/); for (var i = 0; i < names.length; i++) { var name = names[i]; if (name) { (data.name ? _easings : _modes)[name] = data; } } }; Easing.add({ mode : 'in', fn : function(f) { return f; } }); Easing.add({ mode : 'out', fn : function(f) { return function(t) { return 1 - f(1 - t); }; } }); Easing.add({ mode : 'in-out', fn : function(f) { return function(t) { return (t < 0.5) ? (f(2 * t) / 2) : (1 - f(2 * (1 - t)) / 2); }; } }); Easing.add({ mode : 'out-in', fn : function(f) { return function(t) { return (t < 0.5) ? (1 - f(2 * (1 - t)) / 2) : (f(2 * t) / 2); }; } }); Easing.add({ name : 'linear', fn : function(t) { return t; } }); Easing.add({ name : 'quad', fn : function(t) { return t * t; } }); Easing.add({ name : 'cubic', fn : function(t) { return t * t * t; } }); Easing.add({ name : 'quart', fn : function(t) { return t * t * t * t; } }); Easing.add({ name : 'quint', fn : function(t) { return t * t * t * t * t; } }); Easing.add({ name : 'sin sine', fn : function(t) { return 1 - Math.cos(t * Math.PI / 2); } }); Easing.add({ name : 'exp expo', fn : function(t) { return t == 0 ? 0 : Math.pow(2, 10 * (t - 1)); } }); Easing.add({ name : 'circle circ', fn : function(t) { return 1 - Math.sqrt(1 - t * t); } }); Easing.add({ name : 'bounce', fn : function(t) { return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; } }); Easing.add({ name : 'poly', fc : function(e) { return function(t) { return Math.pow(t, e); }; } }); Easing.add({ name : 'elastic', fc : function(a, p) { p = p || 0.45; a = a || 1; var s = p / (2 * Math.PI) * Math.asin(1 / a); return function(t) { return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p); }; } }); Easing.add({ name : 'back', fc : function(s) { s = typeof s !== 'undefined' ? s : 1.70158; return function(t) { return t * t * ((s + 1) * t - s); }; } }); module.exports = Easing; },{}],55:[function(require,module,exports){ if (typeof DEBUG === 'undefined') DEBUG = true; require('../core')._load(function(stage, elem) { Mouse.subscribe(stage, elem); }); // TODO: capture mouse Mouse.CLICK = 'click'; Mouse.START = 'touchstart mousedown'; Mouse.MOVE = 'touchmove mousemove'; Mouse.END = 'touchend mouseup'; Mouse.CANCEL = 'touchcancel mousecancel'; Mouse.subscribe = function(stage, elem) { if (stage.mouse) { return; } stage.mouse = new Mouse(stage, elem); // `click` events are synthesized from start/end events on same nodes // `mousecancel` events are synthesized on blur or mouseup outside element elem.addEventListener('touchstart', handleStart); elem.addEventListener('touchend', handleEnd); elem.addEventListener('touchmove', handleMove); elem.addEventListener('touchcancel', handleCancel); elem.addEventListener('mousedown', handleStart); elem.addEventListener('mouseup', handleEnd); elem.addEventListener('mousemove', handleMove); document.addEventListener('mouseup', handleCancel); window.addEventListener("blur", handleCancel); var clicklist = [], cancellist = []; function handleStart(event) { event.preventDefault(); stage.mouse.locate(event); // DEBUG && console.log('Mouse Start: ' + event.type + ' ' + mouse); stage.mouse.publish(event.type, event); stage.mouse.lookup('click', clicklist); stage.mouse.lookup('mousecancel', cancellist); } function handleMove(event) { event.preventDefault(); stage.mouse.locate(event); stage.mouse.publish(event.type, event); } function handleEnd(event) { event.preventDefault(); // up/end location is not available, last one is used instead // DEBUG && console.log('Mouse End: ' + event.type + ' ' + mouse); stage.mouse.publish(event.type, event); if (clicklist.length) { // DEBUG && console.log('Mouse Click: ' + clicklist.length); stage.mouse.publish('click', event, clicklist); } cancellist.length = 0; } function handleCancel(event) { if (cancellist.length) { // DEBUG && console.log('Mouse Cancel: ' + event.type); stage.mouse.publish('mousecancel', event, cancellist); } clicklist.length = 0; } }; function Mouse(stage, elem) { if (!(this instanceof Mouse)) { // old-style mouse subscription return; } var ratio = stage.viewport().ratio || 1; stage.on('viewport', function(size) { ratio = size.ratio || ratio; }); this.x = 0; this.y = 0; this.toString = function() { return (this.x | 0) + 'x' + (this.y | 0); }; this.locate = function(event) { locateElevent(elem, event, this); this.x *= ratio; this.y *= ratio; }; this.lookup = function(type, collect) { this.type = type; this.root = stage; this.event = null; collect.length = 0; this.collect = collect; this.root.visit(this.visitor, this); }; this.publish = function(type, event, targets) { this.type = type; this.root = stage; this.event = event; this.collect = false; this.timeStamp = Date.now(); if (type !== 'mousemove' && type !== 'touchmove') { DEBUG && console.log(this.type + ' ' + this); } if (targets) { while (targets.length) if (this.visitor.end(targets.shift(), this)) break; targets.length = 0; } else { this.root.visit(this.visitor, this); } }; this.visitor = { reverse : true, visible : true, start : function(node, mouse) { return !node._flag(mouse.type); }, end : function(node, mouse) { // mouse: event/collect, type, root rel.raw = mouse.event; rel.type = mouse.type; rel.timeStamp = mouse.timeStamp; rel.abs.x = mouse.x; rel.abs.y = mouse.y; var listeners = node.listeners(mouse.type); if (!listeners) { return; } node.matrix().inverse().map(mouse, rel); if (!(node === mouse.root || node.hitTest(rel))) { return; } if (mouse.collect) { mouse.collect.push(node); } if (mouse.event) { var cancel = false; for (var l = 0; l < listeners.length; l++) { cancel = listeners[l].call(node, rel) ? true : cancel; } return cancel; } } }; }; // TODO: define per mouse object with get-only x and y var rel = {}, abs = {}; defineValue(rel, 'clone', function(obj) { obj = obj || {}, obj.x = this.x, obj.y = this.y; return obj; }); defineValue(rel, 'toString', function() { return (this.x | 0) + 'x' + (this.y | 0) + ' (' + this.abs + ')'; }); defineValue(rel, 'abs', abs); defineValue(abs, 'clone', function(obj) { obj = obj || {}, obj.x = this.x, obj.y = this.y; return obj; }); defineValue(abs, 'toString', function() { return (this.x | 0) + 'x' + (this.y | 0); }); function defineValue(obj, name, value) { Object.defineProperty(obj, name, { value : value }); } function locateElevent(el, ev, loc) { // pageX/Y if available? if (ev.touches && ev.touches.length) { loc.x = ev.touches[0].clientX; loc.y = ev.touches[0].clientY; } else { loc.x = ev.clientX; loc.y = ev.clientY; } var rect = el.getBoundingClientRect(); loc.x -= rect.left; loc.y -= rect.top; loc.x -= el.clientLeft | 0; loc.y -= el.clientTop | 0; return loc; }; module.exports = Mouse; },{"../core":60}],56:[function(require,module,exports){ var Easing = require('./easing'); var Class = require('../core'); var Pin = require('../pin'); Class.prototype.tween = function(duration, delay, append) { if (typeof duration !== 'number') { append = duration, delay = 0, duration = 0; } else if (typeof delay !== 'number') { append = delay, delay = 0; } if (!this._tweens) { this._tweens = []; var ticktime = 0; this.tick(function(elapsed, now, last) { if (!this._tweens.length) { return; } // ignore old elapsed var ignore = ticktime != last; ticktime = now; if (ignore) { return true; } var head = this._tweens[0]; var next = head.tick(this, elapsed, now, last); if (next && head === this._tweens[0]) { this._tweens.shift(); } if (typeof next === 'function') { try { next.call(this); } catch (e) { console.log(e); } } if (typeof next === 'object') { this._tweens.unshift(next); } return true; }, true); } this.touch(); if (!append) { this._tweens.length = 0; } var tween = new Tween(this, duration, delay); this._tweens.push(tween); return tween; }; function Tween(owner, duration, delay) { this._end = {}; this._duration = duration || 400; this._delay = delay || 0; this._owner = owner; this._time = 0; }; Tween.prototype.tick = function(node, elapsed, now, last) { this._time += elapsed; if (this._time < this._delay) { return; } var time = this._time - this._delay; if (!this._start) { this._start = {}; for ( var key in this._end) { this._start[key] = this._owner.pin(key); } } var p, over; if (time < this._duration) { p = time / this._duration; over = false; } else { p = 1; over = true; } if (typeof this._easing == 'function') { p = this._easing(p); } var q = 1 - p; for ( var key in this._end) { this._owner.pin(key, this._start[key] * q + this._end[key] * p); } if (over) { return this._next || this._done || true; } }; Tween.prototype.tween = function(duration, delay) { return this._next = new Tween(this._owner, duration, delay); }; Tween.prototype.duration = function(duration) { this._duration = duration; return this; }; Tween.prototype.delay = function(delay) { this._delay = delay; return this; }; Tween.prototype.ease = function(easing) { this._easing = Easing(easing); return this; }; Tween.prototype.done = function(fn) { this._done = fn; return this; }; Tween.prototype.hide = function() { this.done(function() { this.hide(); }); return this; }; Tween.prototype.remove = function() { this.done(function() { this.remove(); }); return this; }; Tween.prototype.pin = function(a, b) { if (typeof a === 'object') { for ( var attr in a) { pinning(this._owner, this._end, attr, a[attr]); } } else if (typeof b !== 'undefined') { pinning(this._owner, this._end, a, b); } return this; }; function pinning(node, map, key, value) { if (typeof node.pin(key) === 'number') { map[key] = value; } else if (typeof node.pin(key + 'X') === 'number' && typeof node.pin(key + 'Y') === 'number') { map[key + 'X'] = value; map[key + 'Y'] = value; } } Pin._add_shortcuts(Tween); /** * @deprecated Use .done(fn) instead. */ Tween.prototype.then = function(fn) { this.done(fn); return this; }; /** * @deprecated NOOP */ Tween.prototype.clear = function(forward) { return this; }; module.exports = Tween; },{"../core":60,"../pin":68,"./easing":54}],57:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var create = require('./util/create'); var math = require('./util/math'); Class.anim = function(frames, fps) { var anim = new Anim(); anim.frames(frames).gotoFrame(0); fps && anim.fps(fps); return anim; }; Anim._super = Class; Anim.prototype = create(Anim._super.prototype); // TODO: replace with atlas fps or texture time Class.Anim = { FPS : 15 }; function Anim() { Anim._super.call(this); this.label('Anim'); this._textures = []; this._fps = Class.Anim.FPS; this._ft = 1000 / this._fps; this._time = -1; this._repeat = 0; this._index = 0; this._frames = []; var lastTime = 0; this.tick(function(t, now, last) { if (this._time < 0 || this._frames.length <= 1) { return; } // ignore old elapsed var ignore = lastTime != last; lastTime = now; if (ignore) { return true; } this._time += t; if (this._time < this._ft) { return true; } var n = this._time / this._ft | 0; this._time -= n * this._ft; this.moveFrame(n); if (this._repeat > 0 && (this._repeat -= n) <= 0) { this.stop(); this._callback && this._callback(); return false; } return true; }, false); }; Anim.prototype.fps = function(fps) { if (typeof fps === 'undefined') { return this._fps; } this._fps = fps > 0 ? fps : Class.Anim.FPS; this._ft = 1000 / this._fps; return this; }; /** * @deprecated Use frames */ Anim.prototype.setFrames = function(a, b, c) { return this.frames(a, b, c); }; Anim.prototype.frames = function(frames) { this._index = 0; this._frames = Class.texture(frames).array(); this.touch(); return this; }; Anim.prototype.length = function() { return this._frames ? this._frames.length : 0; }; Anim.prototype.gotoFrame = function(frame, resize) { this._index = math.rotate(frame, this._frames.length) | 0; resize = resize || !this._textures[0]; this._textures[0] = this._frames[this._index]; if (resize) { this.pin('width', this._textures[0].width); this.pin('height', this._textures[0].height); } this.touch(); return this; }; Anim.prototype.moveFrame = function(move) { return this.gotoFrame(this._index + move); }; Anim.prototype.repeat = function(repeat, callback) { this._repeat = repeat * this._frames.length - 1; this._callback = callback; this.play(); return this; }; Anim.prototype.play = function(frame) { if (typeof frame !== 'undefined') { this.gotoFrame(frame); this._time = 0; } else if (this._time < 0) { this._time = 0; } this.touch(); return this; }; Anim.prototype.stop = function(frame) { this._time = -1; if (typeof frame !== 'undefined') { this.gotoFrame(frame); } return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/math":78}],58:[function(require,module,exports){ if (typeof DEBUG === 'undefined') DEBUG = true; var Class = require('./core'); var Texture = require('./texture'); var extend = require('./util/extend'); var create = require('./util/create'); var is = require('./util/is'); var string = require('./util/string'); // name : atlas var _atlases_map = {}; // [atlas] var _atlases_arr = []; // TODO: print subquery not found error // TODO: index textures Class.atlas = function(def) { var atlas = is.fn(def.draw) ? def : new Atlas(def); if (def.name) { _atlases_map[def.name] = atlas; } _atlases_arr.push(atlas); deprecated(def, 'imagePath'); deprecated(def, 'imageRatio'); var url = def.imagePath; var ratio = def.imageRatio || 1; if (is.string(def.image)) { url = def.image; } else if (is.hash(def.image)) { url = def.image.src || def.image.url; ratio = def.image.ratio || ratio; } url && Class.preload(function(done) { url = Class.resolve(url); DEBUG && console.log('Loading atlas: ' + url); var imageloader = Class.config('image-loader'); imageloader(url, function(image) { DEBUG && console.log('Image loaded: ' + url); atlas.src(image, ratio); done(); }, function(err) { DEBUG && console.log('Error loading atlas: ' + url, err); done(); }); }); return atlas; }; Atlas._super = Texture; Atlas.prototype = create(Atlas._super.prototype); function Atlas(def) { Atlas._super.call(this); var atlas = this; deprecated(def, 'filter'); deprecated(def, 'cutouts'); deprecated(def, 'sprites'); deprecated(def, 'factory'); var map = def.map || def.filter; var ppu = def.ppu || def.ratio || 1; var trim = def.trim || 0; var textures = def.textures; var factory = def.factory; var cutouts = def.cutouts || def.sprites; function make(def) { if (!def || is.fn(def.draw)) { return def; } def = extend({}, def); if (is.fn(map)) { def = map(def); } if (ppu != 1) { def.x *= ppu, def.y *= ppu; def.width *= ppu, def.height *= ppu; def.top *= ppu, def.bottom *= ppu; def.left *= ppu, def.right *= ppu; } if (trim != 0) { def.x += trim, def.y += trim; def.width -= 2 * trim, def.height -= 2 * trim; def.top -= trim, def.bottom -= trim; def.left -= trim, def.right -= trim; } var texture = atlas.pipe(); texture.top = def.top, texture.bottom = def.bottom; texture.left = def.left, texture.right = def.right; texture.src(def.x, def.y, def.width, def.height); return texture; } function find(query) { if (textures) { if (is.fn(textures)) { return textures(query); } else if (is.hash(textures)) { return textures[query]; } } if (cutouts) { // deprecated var result = null, n = 0; for (var i = 0; i < cutouts.length; i++) { if (string.startsWith(cutouts[i].name, query)) { if (n === 0) { result = cutouts[i]; } else if (n === 1) { result = [ result, cutouts[i] ]; } else { result.push(cutouts[i]); } n++; } } if (n === 0 && is.fn(factory)) { result = function(subquery) { return factory(query + (subquery ? subquery : '')); }; } return result; } } this.select = function(query) { if (!query) { // TODO: if `textures` is texture def, map or fn? return new Selection(this.pipe()); } var found = find(query); if (found) { return new Selection(found, find, make); } }; }; var nfTexture = new Texture(); nfTexture.x = nfTexture.y = nfTexture.width = nfTexture.height = 0; nfTexture.pipe = nfTexture.src = nfTexture.dest = function() { return this; }; nfTexture.draw = function() { }; var nfSelection = new Selection(nfTexture); function Selection(result, find, make) { function link(result, subquery) { if (!result) { return nfTexture; } else if (is.fn(result.draw)) { return result; } else if (is.hash(result) && is.number(result.width) && is.number(result.height) && is.fn(make)) { return make(result); } else if (is.hash(result) && is.defined(subquery)) { return link(result[subquery]); } else if (is.fn(result)) { return link(result(subquery)); } else if (is.array(result)) { return link(result[0]); } else if (is.string(result) && is.fn(find)) { return link(find(result)); } } this.one = function(subquery) { return link(result, subquery); }; this.array = function(arr) { var array = is.array(arr) ? arr : []; if (is.array(result)) { for (var i = 0; i < result.length; i++) { array[i] = link(result[i]); } } else { array[0] = link(result); } return array; }; } Class.texture = function(query) { if (!is.string(query)) { return new Selection(query); } var result = null, atlas, i; if ((i = query.indexOf(':')) > 0 && query.length > i + 1) { atlas = _atlases_map[query.slice(0, i)]; result = atlas && atlas.select(query.slice(i + 1)); } if (!result && (atlas = _atlases_map[query])) { result = atlas.select(); } for (i = 0; !result && i < _atlases_arr.length; i++) { result = _atlases_arr[i].select(query); } if (!result) { console.error('Texture not found: ' + query); result = nfSelection; } return result; }; function deprecated(hash, name, msg) { if (name in hash) console.log(msg ? msg.replace('%name', name) : '\'' + name + '\' field of texture atlas is deprecated.'); }; module.exports = Atlas; },{"./core":60,"./texture":71,"./util/create":74,"./util/extend":76,"./util/is":77,"./util/string":81}],59:[function(require,module,exports){ var Class = require('./core'); var Texture = require('./texture'); Class.canvas = function(type, attributes, callback) { if (typeof type === 'string') { if (typeof attributes === 'object') { } else { if (typeof attributes === 'function') { callback = attributes; } attributes = {}; } } else { if (typeof type === 'function') { callback = type; } attributes = {}; type = '2d'; } var canvas = document.createElement('canvas'); var context = canvas.getContext(type, attributes); var texture = new Texture(canvas); texture.context = function() { return context; }; texture.size = function(width, height, ratio) { ratio = ratio || 1; canvas.width = width * ratio; canvas.height = height * ratio; this.src(canvas, ratio); return this; }; texture.canvas = function(fn) { if (typeof fn === 'function') { fn.call(this, context); } else if (typeof fn === 'undefined' && typeof callback === 'function') { callback.call(this, context); } return this; }; if (typeof callback === 'function') { callback.call(texture, context); } return texture; }; },{"./core":60,"./texture":71}],60:[function(require,module,exports){ if (typeof DEBUG === 'undefined') DEBUG = true; var stats = require('./util/stats'); var extend = require('./util/extend'); var is = require('./util/is'); var _await = require('./util/await'); stats.create = 0; function Class(arg) { if (!(this instanceof Class)) { if (is.fn(arg)) { return Class.app.apply(Class, arguments); } else if (is.object(arg)) { return Class.atlas.apply(Class, arguments); } else { return arg; } } stats.create++; for (var i = 0; i < _init.length; i++) { _init[i].call(this); } } var _init = []; Class._init = function(fn) { _init.push(fn); }; var _load = []; Class._load = function(fn) { _load.push(fn); }; var _config = {}; Class.config = function() { if (arguments.length === 1 && is.string(arguments[0])) { return _config[arguments[0]]; } if (arguments.length === 1 && is.object(arguments[0])) { extend(_config, arguments[0]); } if (arguments.length === 2 && is.string(arguments[0])) { _config[arguments[0], arguments[1]]; } }; var _app_queue = []; var _preload_queue = []; var _stages = []; var _loaded = false; var _paused = false; Class.app = function(app, opts) { if (!_loaded) { _app_queue.push(arguments); return; } DEBUG && console.log('Creating app...'); var loader = Class.config('app-loader'); loader(function(stage, canvas) { DEBUG && console.log('Initing app...'); for (var i = 0; i < _load.length; i++) { _load[i].call(this, stage, canvas); } app(stage, canvas); _stages.push(stage); DEBUG && console.log('Starting app...'); stage.start(); }, opts); }; var loading = _await(); Class.preload = function(load) { if (typeof load === 'string') { var url = Class.resolve(load); if (/\.js($|\?|\#)/.test(url)) { DEBUG && console.log('Loading script: ' + url); load = function(callback) { loadScript(url, callback); }; } } if (typeof load !== 'function') { return; } // if (!_started) { // _preload_queue.push(load); // return; // } load(loading()); }; Class.start = function(config) { DEBUG && console.log('Starting...'); Class.config(config); // DEBUG && console.log('Preloading...'); // _started = true; // while (_preload_queue.length) { // var load = _preload_queue.shift(); // load(loading()); // } loading.then(function() { DEBUG && console.log('Loading apps...'); _loaded = true; while (_app_queue.length) { var args = _app_queue.shift(); Class.app.apply(Class, args); } }); }; Class.pause = function() { if (!_paused) { _paused = true; for (var i = _stages.length - 1; i >= 0; i--) { _stages[i].pause(); } } }; Class.resume = function() { if (_paused) { _paused = false; for (var i = _stages.length - 1; i >= 0; i--) { _stages[i].resume(); } } }; Class.create = function() { return new Class(); }; Class.resolve = (function() { if (typeof window === 'undefined' || typeof document === 'undefined') { return function(url) { return url; }; } var scripts = document.getElementsByTagName('script'); function getScriptSrc() { // HTML5 if (document.currentScript) { return document.currentScript.src; } // IE>=10 var stack; try { var err = new Error(); if (err.stack) { stack = err.stack; } else { throw err; } } catch (err) { stack = err.stack; } if (typeof stack === 'string') { stack = stack.split('\n'); // Uses the last line, where the call started for (var i = stack.length; i--;) { var url = stack[i].match(/(\w+\:\/\/[^/]*?\/.+?)(:\d+)(:\d+)?/); if (url) { return url[1]; } } } // IE<11 if (scripts.length && 'readyState' in scripts[0]) { for (var i = scripts.length; i--;) { if (scripts[i].readyState === 'interactive') { return scripts[i].src; } } } return location.href; } return function(url) { if (/^\.\//.test(url)) { var src = getScriptSrc(); var base = src.substring(0, src.lastIndexOf('/') + 1); url = base + url.substring(2); // } else if (/^\.\.\//.test(url)) { // url = base + url; } return url; }; })(); module.exports = Class; function loadScript(src, callback) { var el = document.createElement('script'); el.addEventListener('load', function() { callback(); }); el.addEventListener('error', function(err) { callback(err || 'Error loading script: ' + src); }); el.src = src; el.id = 'preload-' + Date.now(); document.body.appendChild(el); }; },{"./util/await":73,"./util/extend":76,"./util/is":77,"./util/stats":80}],61:[function(require,module,exports){ require('./util/event')(require('./core').prototype, function(obj, name, on) { obj._flag(name, on); }); },{"./core":60,"./util/event":75}],62:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var repeat = require('./util/repeat'); var create = require('./util/create'); module.exports = Image; Class.image = function(image) { var img = new Image(); image && img.image(image); return img; }; Image._super = Class; Image.prototype = create(Image._super.prototype); function Image() { Image._super.call(this); this.label('Image'); this._textures = []; this._image = null; }; /** * @deprecated Use image */ Image.prototype.setImage = function(a, b, c) { return this.image(a, b, c); }; Image.prototype.image = function(image) { this._image = Class.texture(image).one(); this.pin('width', this._image ? this._image.width : 0); this.pin('height', this._image ? this._image.height : 0); this._textures[0] = this._image.pipe(); this._textures.length = 1; return this; }; Image.prototype.tile = function(inner) { this._repeat(false, inner); return this; }; Image.prototype.stretch = function(inner) { this._repeat(true, inner); return this; }; Image.prototype._repeat = function(stretch, inner) { var self = this; this.untick(this._repeatTicker); this.tick(this._repeatTicker = function() { if (this._mo_stretch == this._pin._ts_transform) { return; } this._mo_stretch = this._pin._ts_transform; var width = this.pin('width'); var height = this.pin('height'); this._textures.length = repeat(this._image, width, height, stretch, inner, insert); }); function insert(i, sx, sy, sw, sh, dx, dy, dw, dh) { var repeat = self._textures.length > i ? self._textures[i] : self._textures[i] = self._image.pipe(); repeat.src(sx, sy, sw, sh); repeat.dest(dx, dy, dw, dh); } }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/repeat":79}],63:[function(require,module,exports){ module.exports = require('./core'); module.exports.Matrix = require('./matrix'); module.exports.Texture = require('./texture'); require('./atlas'); require('./tree'); require('./event'); require('./pin'); require('./loop'); require('./root'); },{"./atlas":58,"./core":60,"./event":61,"./loop":66,"./matrix":67,"./pin":68,"./root":69,"./texture":71,"./tree":72}],64:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var create = require('./util/create'); Class.row = function(align) { return Class.create().row(align).label('Row'); }; Class.prototype.row = function(align) { this.sequence('row', align); return this; }; Class.column = function(align) { return Class.create().column(align).label('Row'); }; Class.prototype.column = function(align) { this.sequence('column', align); return this; }; Class.sequence = function(type, align) { return Class.create().sequence(type, align).label('Sequence'); }; Class.prototype.sequence = function(type, align) { this._padding = this._padding || 0; this._spacing = this._spacing || 0; this.untick(this._layoutTiker); this.tick(this._layoutTiker = function() { if (this._mo_seq == this._ts_touch) { return; } this._mo_seq = this._ts_touch; var alignChildren = (this._mo_seqAlign != this._ts_children); this._mo_seqAlign = this._ts_children; var width = 0, height = 0; var child, next = this.first(true); var first = true; while (child = next) { next = child.next(true); child.matrix(true); var w = child.pin('boxWidth'); var h = child.pin('boxHeight'); if (type == 'column') { !first && (height += this._spacing); child.pin('offsetY') != height && child.pin('offsetY', height); width = Math.max(width, w); height = height + h; alignChildren && child.pin('alignX', align); } else if (type == 'row') { !first && (width += this._spacing); child.pin('offsetX') != width && child.pin('offsetX', width); width = width + w; height = Math.max(height, h); alignChildren && child.pin('alignY', align); } first = false; } width += 2 * this._padding; height += 2 * this._padding; this.pin('width') != width && this.pin('width', width); this.pin('height') != height && this.pin('height', height); }); return this; }; Class.box = function() { return Class.create().box().label('Box'); }; Class.prototype.box = function() { this._padding = this._padding || 0; this.untick(this._layoutTiker); this.tick(this._layoutTiker = function() { if (this._mo_box == this._ts_touch) { return; } this._mo_box = this._ts_touch; var width = 0, height = 0; var child, next = this.first(true); while (child = next) { next = child.next(true); child.matrix(true); var w = child.pin('boxWidth'); var h = child.pin('boxHeight'); width = Math.max(width, w); height = Math.max(height, h); } width += 2 * this._padding; height += 2 * this._padding; this.pin('width') != width && this.pin('width', width); this.pin('height') != height && this.pin('height', height); }); return this; }; Class.layer = function() { return Class.create().layer().label('Layer'); }; Class.prototype.layer = function() { this.untick(this._layoutTiker); this.tick(this._layoutTiker = function() { var parent = this.parent(); if (parent) { var width = parent.pin('width'); if (this.pin('width') != width) { this.pin('width', width); } var height = parent.pin('height'); if (this.pin('height') != height) { this.pin('height', height); } } }, true); return this; }; // TODO: move padding to pin Class.prototype.padding = function(pad) { this._padding = pad; return this; }; Class.prototype.spacing = function(space) { this._spacing = space; return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74}],65:[function(require,module,exports){ /** * Default loader for web. */ if (typeof DEBUG === 'undefined') DEBUG = true; var Class = require('../core'); Class._supported = (function() { var elem = document.createElement('canvas'); return (elem.getContext && elem.getContext('2d')) ? true : false; })(); window.addEventListener('load', function() { DEBUG && console.log('On load.'); if (Class._supported) { Class.start(); } // TODO if not supported }, false); Class.config({ 'app-loader' : AppLoader, 'image-loader' : ImageLoader }); function AppLoader(app, configs) { configs = configs || {}; var canvas = configs.canvas, context = null, full = false; var width = 0, height = 0, ratio = 1; if (typeof canvas === 'string') { canvas = document.getElementById(canvas); } if (!canvas) { canvas = document.getElementById('cutjs') || document.getElementById('stage'); } if (!canvas) { full = true; DEBUG && console.log('Creating Canvas...'); canvas = document.createElement('canvas'); canvas.style.position = 'absolute'; canvas.style.top = '0'; canvas.style.left = '0'; var body = document.body; body.insertBefore(canvas, body.firstChild); } context = canvas.getContext('2d'); var devicePixelRatio = window.devicePixelRatio || 1; var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; ratio = devicePixelRatio / backingStoreRatio; var requestAnimationFrame = window.requestAnimationFrame || window.msRequestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.oRequestAnimationFrame || function(callback) { return window.setTimeout(callback, 1000 / 60); }; DEBUG && console.log('Creating stage...'); var root = Class.root(requestAnimationFrame, render); function render() { context.setTransform(1, 0, 0, 1, 0, 0); context.clearRect(0, 0, width, height); root.render(context); } root.background = function(color) { canvas.style.backgroundColor = color; return this; }; app(root, canvas); resize(); window.addEventListener('resize', resize, false); window.addEventListener('orientationchange', resize, false); function resize() { if (full) { // screen.availWidth/Height? width = (window.innerWidth > 0 ? window.innerWidth : screen.width); height = (window.innerHeight > 0 ? window.innerHeight : screen.height); canvas.style.width = width + 'px'; canvas.style.height = height + 'px'; } else { width = canvas.clientWidth; height = canvas.clientHeight; } width *= ratio; height *= ratio; if (canvas.width === width && canvas.height === height) { return; } canvas.width = width; canvas.height = height; DEBUG && console.log('Resize: ' + width + ' x ' + height + ' / ' + ratio); root.viewport(width, height, ratio); render(); } } function ImageLoader(src, success, error) { DEBUG && console.log('Loading image: ' + src); var image = new Image(); image.onload = function() { success(image); }; image.onerror = error; image.src = src; } },{"../core":60}],66:[function(require,module,exports){ var Class = require('./core'); require('./pin'); var stats = require('./util/stats'); Class.prototype._textures = null; Class.prototype._alpha = 1; Class.prototype.render = function(context) { if (!this._visible) { return; } stats.node++; var m = this.matrix(); context.setTransform(m.a, m.b, m.c, m.d, m.e, m.f); // move this elsewhere! this._alpha = this._pin._alpha * (this._parent ? this._parent._alpha : 1); var alpha = this._pin._textureAlpha * this._alpha; if (context.globalAlpha != alpha) { context.globalAlpha = alpha; } if (this._textures !== null) { for (var i = 0, n = this._textures.length; i < n; i++) { this._textures[i].draw(context); } } if (context.globalAlpha != this._alpha) { context.globalAlpha = this._alpha; } var child, next = this._first; while (child = next) { next = child._next; child.render(context); } }; Class.prototype._tickBefore = null; Class.prototype._tickAfter = null; Class.prototype.MAX_ELAPSE = Infinity; Class.prototype._tick = function(elapsed, now, last) { if (!this._visible) { return; } if (elapsed > this.MAX_ELAPSE) { elapsed = this.MAX_ELAPSE; } var ticked = false; if (this._tickBefore !== null) { for (var i = 0; i < this._tickBefore.length; i++) { stats.tick++; var tickFn = this._tickBefore[i]; ticked = tickFn.call(this, elapsed, now, last) === true || ticked; } } var child, next = this._first; while (child = next) { next = child._next; if (child._flag('_tick')) { ticked = child._tick(elapsed, now, last) === true ? true : ticked; } } if (this._tickAfter !== null) { for (var i = 0; i < this._tickAfter.length; i++) { stats.tick++; var tickFn = this._tickAfter[i]; ticked = tickFn.call(this, elapsed, now, last) === true || ticked; } } return ticked; }; Class.prototype.tick = function(ticker, before) { if (typeof ticker !== 'function') { return; } if (before) { if (this._tickBefore === null) { this._tickBefore = []; } this._tickBefore.push(ticker); } else { if (this._tickAfter === null) { this._tickAfter = []; } this._tickAfter.push(ticker); } this._flag('_tick', this._tickAfter !== null && this._tickAfter.length > 0 || this._tickBefore !== null && this._tickBefore.length > 0); }; Class.prototype.untick = function(ticker) { if (typeof ticker !== 'function') { return; } var i; if (this._tickBefore !== null && (i = this._tickBefore.indexOf(ticker)) >= 0) { this._tickBefore.splice(i, 1); } if (this._tickAfter !== null && (i = this._tickAfter.indexOf(ticker)) >= 0) { this._tickAfter.splice(i, 1); } }; Class.prototype.timeout = function(fn, time) { this.setTimeout(fn, time); }; Class.prototype.setTimeout = function(fn, time) { function timer(t) { if ((time -= t) < 0) { this.untick(timer); fn.call(this); } else { return true; } } this.tick(timer); return timer; }; Class.prototype.clearTimeout = function(timer) { this.untick(timer); }; },{"./core":60,"./pin":68,"./util/stats":80}],67:[function(require,module,exports){ function Matrix(a, b, c, d, e, f) { this.reset(a, b, c, d, e, f); }; Matrix.prototype.toString = function() { return '[' + this.a + ', ' + this.b + ', ' + this.c + ', ' + this.d + ', ' + this.e + ', ' + this.f + ']'; }; Matrix.prototype.clone = function() { return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f); }; Matrix.prototype.reset = function(a, b, c, d, e, f) { this._dirty = true; if (typeof a === 'object') { this.a = a.a, this.d = a.d; this.b = a.b, this.c = a.c; this.e = a.e, this.f = a.f; } else { this.a = a || 1, this.d = d || 1; this.b = b || 0, this.c = c || 0; this.e = e || 0, this.f = f || 0; } return this; }; Matrix.prototype.identity = function() { this._dirty = true; this.a = 1; this.b = 0; this.c = 0; this.d = 1; this.e = 0; this.f = 0; return this; }; Matrix.prototype.rotate = function(angle) { if (!angle) { return this; } this._dirty = true; var u = angle ? Math.cos(angle) : 1; // android bug may give bad 0 values var v = angle ? Math.sin(angle) : 0; var a = u * this.a - v * this.b; var b = u * this.b + v * this.a; var c = u * this.c - v * this.d; var d = u * this.d + v * this.c; var e = u * this.e - v * this.f; var f = u * this.f + v * this.e; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; return this; }; Matrix.prototype.translate = function(x, y) { if (!x && !y) { return this; } this._dirty = true; this.e += x; this.f += y; return this; }; Matrix.prototype.scale = function(x, y) { if (!(x - 1) && !(y - 1)) { return this; } this._dirty = true; this.a *= x; this.b *= y; this.c *= x; this.d *= y; this.e *= x; this.f *= y; return this; }; Matrix.prototype.skew = function(x, y) { if (!x && !y) { return this; } this._dirty = true; var a = this.a + this.b * x; var b = this.b + this.a * y; var c = this.c + this.d * x; var d = this.d + this.c * y; var e = this.e + this.f * x; var f = this.f + this.e * y; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; return this; }; Matrix.prototype.concat = function(m) { this._dirty = true; var n = this; var a = n.a * m.a + n.b * m.c; var b = n.b * m.d + n.a * m.b; var c = n.c * m.a + n.d * m.c; var d = n.d * m.d + n.c * m.b; var e = n.e * m.a + m.e + n.f * m.c; var f = n.f * m.d + m.f + n.e * m.b; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; return this; }; Matrix.prototype.inverse = Matrix.prototype.reverse = function() { if (this._dirty) { this._dirty = false; this.inversed = this.inversed || new Matrix(); var z = this.a * this.d - this.b * this.c; this.inversed.a = this.d / z; this.inversed.b = -this.b / z; this.inversed.c = -this.c / z; this.inversed.d = this.a / z; this.inversed.e = (this.c * this.f - this.e * this.d) / z; this.inversed.f = (this.e * this.b - this.a * this.f) / z; } return this.inversed; }; Matrix.prototype.map = function(p, q) { q = q || {}; q.x = this.a * p.x + this.c * p.y + this.e; q.y = this.b * p.x + this.d * p.y + this.f; return q; }; Matrix.prototype.mapX = function(x, y) { if (typeof x === 'object') y = x.y, x = x.x; return this.a * x + this.c * y + this.e; }; Matrix.prototype.mapY = function(x, y) { if (typeof x === 'object') y = x.y, x = x.x; return this.b * x + this.d * y + this.f; }; module.exports = Matrix; },{}],68:[function(require,module,exports){ var Class = require('./core'); var Matrix = require('./matrix'); var iid = 0; Class._init(function() { this._pin = new Pin(this); }); Class.prototype.matrix = function(relative) { if (relative === true) { return this._pin.relativeMatrix(); } return this._pin.absoluteMatrix(); }; Class.prototype.pin = function(a, b) { if (typeof a === 'object') { this._pin.set(a); return this; } else if (typeof a === 'string') { if (typeof b === 'undefined') { return this._pin.get(a); } else { this._pin.set(a, b); return this; } } else if (typeof a === 'undefined') { return this._pin; } }; function Pin(owner) { this._owner = owner; this._parent = null; // relative to parent this._relativeMatrix = new Matrix(); // relative to stage this._absoluteMatrix = new Matrix(); this.reset(); }; Pin.prototype.reset = function() { this._textureAlpha = 1; this._alpha = 1; this._width = 0; this._height = 0; this._scaleX = 1; this._scaleY = 1; this._skewX = 0; this._skewY = 0; this._rotation = 0; // scale/skew/rotate center this._pivoted = false; this._pivotX = null; this._pivotY = null; // self pin point this._handled = false; this._handleX = 0; this._handleY = 0; // parent pin point this._aligned = false; this._alignX = 0; this._alignY = 0; // as seen by parent px this._offsetX = 0; this._offsetY = 0; this._boxX = 0; this._boxY = 0; this._boxWidth = this._width; this._boxHeight = this._height; // TODO: also set for owner this._ts_translate = ++iid; this._ts_transform = ++iid; this._ts_matrix = ++iid; }; Pin.prototype._update = function() { this._parent = this._owner._parent && this._owner._parent._pin; // if handled and transformed then be translated if (this._handled && this._mo_handle != this._ts_transform) { this._mo_handle = this._ts_transform; this._ts_translate = ++iid; } if (this._aligned && this._parent && this._mo_align != this._parent._ts_transform) { this._mo_align = this._parent._ts_transform; this._ts_translate = ++iid; } return this; }; Pin.prototype.toString = function() { return this._owner + ' (' + (this._parent ? this._parent._owner : null) + ')'; }; // TODO: ts fields require refactoring Pin.prototype.absoluteMatrix = function() { this._update(); var ts = Math.max(this._ts_transform, this._ts_translate, this._parent ? this._parent._ts_matrix : 0); if (this._mo_abs == ts) { return this._absoluteMatrix; } this._mo_abs = ts; var abs = this._absoluteMatrix; abs.reset(this.relativeMatrix()); this._parent && abs.concat(this._parent._absoluteMatrix); this._ts_matrix = ++iid; return abs; }; Pin.prototype.relativeMatrix = function() { this._update(); var ts = Math.max(this._ts_transform, this._ts_translate, this._parent ? this._parent._ts_transform : 0); if (this._mo_rel == ts) { return this._relativeMatrix; } this._mo_rel = ts; var rel = this._relativeMatrix; rel.identity(); if (this._pivoted) { rel.translate(-this._pivotX * this._width, -this._pivotY * this._height); } rel.scale(this._scaleX, this._scaleY); rel.skew(this._skewX, this._skewY); rel.rotate(this._rotation); if (this._pivoted) { rel.translate(this._pivotX * this._width, this._pivotY * this._height); } // calculate effective box if (this._pivoted) { // origin this._boxX = 0; this._boxY = 0; this._boxWidth = this._width; this._boxHeight = this._height; } else { // aabb var p, q; if (rel.a > 0 && rel.c > 0 || rel.a < 0 && rel.c < 0) { p = 0, q = rel.a * this._width + rel.c * this._height; } else { p = rel.a * this._width, q = rel.c * this._height; } if (p > q) { this._boxX = q; this._boxWidth = p - q; } else { this._boxX = p; this._boxWidth = q - p; } if (rel.b > 0 && rel.d > 0 || rel.b < 0 && rel.d < 0) { p = 0, q = rel.b * this._width + rel.d * this._height; } else { p = rel.b * this._width, q = rel.d * this._height; } if (p > q) { this._boxY = q; this._boxHeight = p - q; } else { this._boxY = p; this._boxHeight = q - p; } } this._x = this._offsetX; this._y = this._offsetY; this._x -= this._boxX + this._handleX * this._boxWidth; this._y -= this._boxY + this._handleY * this._boxHeight; if (this._aligned && this._parent) { this._parent.relativeMatrix(); this._x += this._alignX * this._parent._width; this._y += this._alignY * this._parent._height; } rel.translate(this._x, this._y); return this._relativeMatrix; }; Pin.prototype.get = function(key) { if (typeof getters[key] === 'function') { return getters[key](this); } }; // TODO: Use defineProperty instead? What about multi-field pinning? Pin.prototype.set = function(a, b) { if (typeof a === 'string') { if (typeof setters[a] === 'function' && typeof b !== 'undefined') { setters[a](this, b); } } else if (typeof a === 'object') { for (b in a) { if (typeof setters[b] === 'function' && typeof a[b] !== 'undefined') { setters[b](this, a[b], a); } } } if (this._owner) { this._owner._ts_pin = ++iid; this._owner.touch(); } return this; }; var getters = { alpha : function(pin) { return pin._alpha; }, textureAlpha : function(pin) { return pin._textureAlpha; }, width : function(pin) { return pin._width; }, height : function(pin) { return pin._height; }, boxWidth : function(pin) { return pin._boxWidth; }, boxHeight : function(pin) { return pin._boxHeight; }, // scale : function(pin) { // }, scaleX : function(pin) { return pin._scaleX; }, scaleY : function(pin) { return pin._scaleY; }, // skew : function(pin) { // }, skewX : function(pin) { return pin._skewX; }, skewY : function(pin) { return pin._skewY; }, rotation : function(pin) { return pin._rotation; }, // pivot : function(pin) { // }, pivotX : function(pin) { return pin._pivotX; }, pivotY : function(pin) { return pin._pivotY; }, // offset : function(pin) { // }, offsetX : function(pin) { return pin._offsetX; }, offsetY : function(pin) { return pin._offsetY; }, // align : function(pin) { // }, alignX : function(pin) { return pin._alignX; }, alignY : function(pin) { return pin._alignY; }, // handle : function(pin) { // }, handleX : function(pin) { return pin._handleX; }, handleY : function(pin) { return pin._handleY; } }; var setters = { alpha : function(pin, value) { pin._alpha = value; }, textureAlpha : function(pin, value) { pin._textureAlpha = value; }, width : function(pin, value) { pin._width_ = value; pin._width = value; pin._ts_transform = ++iid; }, height : function(pin, value) { pin._height_ = value; pin._height = value; pin._ts_transform = ++iid; }, scale : function(pin, value) { pin._scaleX = value; pin._scaleY = value; pin._ts_transform = ++iid; }, scaleX : function(pin, value) { pin._scaleX = value; pin._ts_transform = ++iid; }, scaleY : function(pin, value) { pin._scaleY = value; pin._ts_transform = ++iid; }, skew : function(pin, value) { pin._skewX = value; pin._skewY = value; pin._ts_transform = ++iid; }, skewX : function(pin, value) { pin._skewX = value; pin._ts_transform = ++iid; }, skewY : function(pin, value) { pin._skewY = value; pin._ts_transform = ++iid; }, rotation : function(pin, value) { pin._rotation = value; pin._ts_transform = ++iid; }, pivot : function(pin, value) { pin._pivotX = value; pin._pivotY = value; pin._pivoted = true; pin._ts_transform = ++iid; }, pivotX : function(pin, value) { pin._pivotX = value; pin._pivoted = true; pin._ts_transform = ++iid; }, pivotY : function(pin, value) { pin._pivotY = value; pin._pivoted = true; pin._ts_transform = ++iid; }, offset : function(pin, value) { pin._offsetX = value; pin._offsetY = value; pin._ts_translate = ++iid; }, offsetX : function(pin, value) { pin._offsetX = value; pin._ts_translate = ++iid; }, offsetY : function(pin, value) { pin._offsetY = value; pin._ts_translate = ++iid; }, align : function(pin, value) { this.alignX(pin, value); this.alignY(pin, value); }, alignX : function(pin, value) { pin._alignX = value; pin._aligned = true; pin._ts_translate = ++iid; this.handleX(pin, value); }, alignY : function(pin, value) { pin._alignY = value; pin._aligned = true; pin._ts_translate = ++iid; this.handleY(pin, value); }, handle : function(pin, value) { this.handleX(pin, value); this.handleY(pin, value); }, handleX : function(pin, value) { pin._handleX = value; pin._handled = true; pin._ts_translate = ++iid; }, handleY : function(pin, value) { pin._handleY = value; pin._handled = true; pin._ts_translate = ++iid; }, resizeMode : function(pin, value, all) { if (all) { if (value == 'in') { value = 'in-pad'; } else if (value == 'out') { value = 'out-crop'; } scaleTo(pin, all.resizeWidth, all.resizeHeight, value); } }, resizeWidth : function(pin, value, all) { if (!all || !all.resizeMode) { scaleTo(pin, value, null); } }, resizeHeight : function(pin, value, all) { if (!all || !all.resizeMode) { scaleTo(pin, null, value); } }, scaleMode : function(pin, value, all) { if (all) { scaleTo(pin, all.scaleWidth, all.scaleHeight, value); } }, scaleWidth : function(pin, value, all) { if (!all || !all.scaleMode) { scaleTo(pin, value, null); } }, scaleHeight : function(pin, value, all) { if (!all || !all.scaleMode) { scaleTo(pin, null, value); } }, matrix : function(pin, value) { this.scaleX(pin, value.a); this.skewX(pin, value.c / value.d); this.skewY(pin, value.b / value.a); this.scaleY(pin, value.d); this.offsetX(pin, value.e); this.offsetY(pin, value.f); this.rotation(pin, 0); } }; function scaleTo(pin, width, height, mode) { var w = typeof width === 'number'; var h = typeof height === 'number'; var m = typeof mode === 'string'; pin._ts_transform = ++iid; if (w) { pin._scaleX = width / pin._width_; pin._width = pin._width_; } if (h) { pin._scaleY = height / pin._height_; pin._height = pin._height_; } if (w && h && m) { if (mode == 'out' || mode == 'out-crop') { pin._scaleX = pin._scaleY = Math.max(pin._scaleX, pin._scaleY); } else if (mode == 'in' || mode == 'in-pad') { pin._scaleX = pin._scaleY = Math.min(pin._scaleX, pin._scaleY); } if (mode == 'out-crop' || mode == 'in-pad') { pin._width = width / pin._scaleX; pin._height = height / pin._scaleY; } } }; Class.prototype.scaleTo = function(a, b, c) { if (typeof a === 'object') c = b, b = a.y, a = a.x; scaleTo(this._pin, a, b, c); return this; }; // Used by Tween class Pin._add_shortcuts = function(Class) { Class.prototype.size = function(w, h) { this.pin('width', w); this.pin('height', h); return this; }; Class.prototype.width = function(w) { if (typeof w === 'undefined') { return this.pin('width'); } this.pin('width', w); return this; }; Class.prototype.height = function(h) { if (typeof h === 'undefined') { return this.pin('height'); } this.pin('height', h); return this; }; Class.prototype.offset = function(a, b) { if (typeof a === 'object') b = a.y, a = a.x; this.pin('offsetX', a); this.pin('offsetY', b); return this; }; Class.prototype.rotate = function(a) { this.pin('rotation', a); return this; }; Class.prototype.skew = function(a, b) { if (typeof a === 'object') b = a.y, a = a.x; else if (typeof b === 'undefined') b = a; this.pin('skewX', a); this.pin('skewY', b); return this; }; Class.prototype.scale = function(a, b) { if (typeof a === 'object') b = a.y, a = a.x; else if (typeof b === 'undefined') b = a; this.pin('scaleX', a); this.pin('scaleY', b); return this; }; Class.prototype.alpha = function(a, ta) { this.pin('alpha', a); if (typeof ta !== 'undefined') { this.pin('textureAlpha', ta); } return this; }; }; Pin._add_shortcuts(Class); module.exports = Pin; },{"./core":60,"./matrix":67}],69:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var stats = require('./util/stats'); var create = require('./util/create'); var extend = require('./util/extend'); Root._super = Class; Root.prototype = create(Root._super.prototype); Class.root = function(request, render) { return new Root(request, render); }; function Root(request, render) { Root._super.call(this); this.label('Root'); var paused = true; var self = this; var lastTime = 0; var loop = function(now) { if (paused === true) { return; } stats.tick = stats.node = stats.draw = 0; var last = lastTime || now; var elapsed = now - last; lastTime = now; var ticked = self._tick(elapsed, now, last); if (self._mo_touch != self._ts_touch) { self._mo_touch = self._ts_touch; render(self); request(loop); } else if (ticked) { request(loop); } else { paused = true; } stats.fps = elapsed ? 1000 / elapsed : 0; }; this.start = function() { return this.resume(); }; this.resume = function() { if (paused) { this.publish('resume'); paused = false; request(loop); } return this; }; this.pause = function() { if (!paused) { this.publish('pause'); } paused = true; return this; }; this.touch_root = this.touch; this.touch = function() { this.resume(); return this.touch_root(); }; }; Root.prototype.background = function(color) { // to be implemented by loaders return this; }; Root.prototype.viewport = function(width, height, ratio) { if (typeof width === 'undefined') { return extend({}, this._viewport); } this._viewport = { width : width, height : height, ratio : ratio || 1 }; this.viewbox(); var data = extend({}, this._viewport); this.visit({ start : function(node) { if (!node._flag('viewport')) { return true; } node.publish('viewport', [ data ]); } }); return this; }; // TODO: static/fixed viewbox Root.prototype.viewbox = function(width, height, mode) { if (typeof width === 'number' && typeof height === 'number') { this._viewbox = { width : width, height : height, mode : /^(in|out|in-pad|out-crop)$/.test(mode) ? mode : 'in-pad' }; } var box = this._viewbox; var size = this._viewport; if (size && box) { this.pin({ width : box.width, height : box.height }); this.scaleTo(size.width, size.height, box.mode); } else if (size) { this.pin({ width : size.width, height : size.height }); } return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/extend":76,"./util/stats":80}],70:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var create = require('./util/create'); var is = require('./util/is'); Class.string = function(frames) { return new Str().frames(frames); }; Str._super = Class; Str.prototype = create(Str._super.prototype); function Str() { Str._super.call(this); this.label('String'); this._textures = []; }; /** * @deprecated Use frames */ Str.prototype.setFont = function(a, b, c) { return this.frames(a, b, c); }; Str.prototype.frames = function(frames) { this._textures = []; if (typeof frames == 'string') { frames = Class.texture(frames); this._item = function(value) { return frames.one(value); }; } else if (typeof frames === 'object') { this._item = function(value) { return frames[value]; }; } else if (typeof frames === 'function') { this._item = frames; } return this; }; /** * @deprecated Use value */ Str.prototype.setValue = function(a, b, c) { return this.value(a, b, c); }; Str.prototype.value = function(value) { if (typeof value === 'undefined') { return this._value; } if (this._value === value) { return this; } this._value = value; if (value === null) { value = ''; } else if (typeof value !== 'string' && !is.array(value)) { value = value.toString(); } this._spacing = this._spacing || 0; var width = 0, height = 0; for (var i = 0; i < value.length; i++) { var image = this._textures[i] = this._item(value[i]); width += i > 0 ? this._spacing : 0; image.dest(width, 0); width = width + image.width; height = Math.max(height, image.height); } this.pin('width', width); this.pin('height', height); this._textures.length = value.length; return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/is":77}],71:[function(require,module,exports){ var stats = require('./util/stats'); var math = require('./util/math'); function Texture(image, ratio) { if (typeof image === 'object') { this.src(image, ratio); } } Texture.prototype.pipe = function() { return new Texture(this); }; /** * Signatures: (image), (x, y, w, h), (w, h) */ Texture.prototype.src = function(x, y, w, h) { if (typeof x === 'object') { var image = x, ratio = y || 1; this._image = image; this._sx = this._dx = 0; this._sy = this._dy = 0; this._sw = this._dw = image.width / ratio; this._sh = this._dh = image.height / ratio; this.width = image.width / ratio; this.height = image.height / ratio; this.ratio = ratio; } else { if (typeof w === 'undefined') { w = x, h = y; } else { this._sx = x, this._sy = y; } this._sw = this._dw = w; this._sh = this._dh = h; this.width = w; this.height = h; } return this; }; /** * Signatures: (x, y, w, h), (x, y) */ Texture.prototype.dest = function(x, y, w, h) { this._dx = x, this._dy = y; this._dx = x, this._dy = y; if (typeof w !== 'undefined') { this._dw = w, this._dh = h; this.width = w, this.height = h; } return this; }; Texture.prototype.draw = function(context, x1, y1, x2, y2, x3, y3, x4, y4) { var image = this._image; if (image === null || typeof image !== 'object') { return; } var sx = this._sx, sy = this._sy; var sw = this._sw, sh = this._sh; var dx = this._dx, dy = this._dy; var dw = this._dw, dh = this._dh; if (typeof x3 !== 'undefined') { x1 = math.limit(x1, 0, this._sw), x2 = math.limit(x2, 0, this._sw - x1); y1 = math.limit(y1, 0, this._sh), y2 = math.limit(y2, 0, this._sh - y1); sx += x1, sy += y1, sw = x2, sh = y2; dx = x3, dy = y3, dw = x4, dh = y4; } else if (typeof x2 !== 'undefined') { dx = x1, dy = y1, dw = x2, dh = y2; } else if (typeof x1 !== 'undefined') { dw = x1, dh = y1; } var ratio = this.ratio || 1; sx *= ratio, sy *= ratio, sw *= ratio, sh *= ratio; try { if (typeof image.draw === 'function') { image.draw(context, sx, sy, sw, sh, dx, dy, dw, dh); } else { stats.draw++; context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh); } } catch (ex) { if (!image._draw_failed) { console.log('Unable to draw: ', image); console.log(ex); image._draw_failed = true; } } }; module.exports = Texture; },{"./util/math":78,"./util/stats":80}],72:[function(require,module,exports){ var Class = require('./core'); var is = require('./util/is'); var iid = 0; // TODO: do not clear next/prev/parent on remove Class.prototype._label = ''; Class.prototype._visible = true; Class.prototype._parent = null; Class.prototype._next = null; Class.prototype._prev = null; Class.prototype._first = null; Class.prototype._last = null; Class.prototype._attrs = null; Class.prototype._flags = null; Class.prototype.toString = function() { return '[' + this._label + ']'; }; /** * @deprecated Use label() */ Class.prototype.id = function(id) { return this.label(id); }; Class.prototype.label = function(label) { if (typeof label === 'undefined') { return this._label; } this._label = label; return this; }; Class.prototype.attr = function(name, value) { if (typeof value === 'undefined') { return this._attrs !== null ? this._attrs[name] : undefined; } (this._attrs !== null ? this._attrs : this._attrs = {})[name] = value; return this; }; Class.prototype.visible = function(visible) { if (typeof visible === 'undefined') { return this._visible; } this._visible = visible; this._parent && (this._parent._ts_children = ++iid); this._ts_pin = ++iid; this.touch(); return this; }; Class.prototype.hide = function() { return this.visible(false); }; Class.prototype.show = function() { return this.visible(true); }; Class.prototype.parent = function() { return this._parent; }; Class.prototype.next = function(visible) { var next = this._next; while (next && visible && !next._visible) { next = next._next; } return next; }; Class.prototype.prev = function(visible) { var prev = this._prev; while (prev && visible && !prev._visible) { prev = prev._prev; } return prev; }; Class.prototype.first = function(visible) { var next = this._first; while (next && visible && !next._visible) { next = next._next; } return next; }; Class.prototype.last = function(visible) { var prev = this._last; while (prev && visible && !prev._visible) { prev = prev._prev; } return prev; }; Class.prototype.visit = function(visitor, data) { var reverse = visitor.reverse; var visible = visitor.visible; if (visitor.start && visitor.start(this, data)) { return; } var child, next = reverse ? this.last(visible) : this.first(visible); while (child = next) { next = reverse ? child.prev(visible) : child.next(visible); if (child.visit(visitor, data)) { return true; } } return visitor.end && visitor.end(this, data); }; Class.prototype.append = function(child, more) { if (is.array(child)) for (var i = 0; i < child.length; i++) append(this, child[i]); else if (typeof more !== 'undefined') // deprecated for (var i = 0; i < arguments.length; i++) append(this, arguments[i]); else if (typeof child !== 'undefined') append(this, child); return this; }; Class.prototype.prepend = function(child, more) { if (is.array(child)) for (var i = child.length - 1; i >= 0; i--) prepend(this, child[i]); else if (typeof more !== 'undefined') // deprecated for (var i = arguments.length - 1; i >= 0; i--) prepend(this, arguments[i]); else if (typeof child !== 'undefined') prepend(this, child); return this; }; Class.prototype.appendTo = function(parent) { append(parent, this); return this; }; Class.prototype.prependTo = function(parent) { prepend(parent, this); return this; }; Class.prototype.insertNext = function(sibling, more) { if (is.array(sibling)) for (var i = 0; i < sibling.length; i++) insertAfter(sibling[i], this); else if (typeof more !== 'undefined') // deprecated for (var i = 0; i < arguments.length; i++) insertAfter(arguments[i], this); else if (typeof sibling !== 'undefined') insertAfter(sibling, this); return this; }; Class.prototype.insertPrev = function(sibling, more) { if (is.array(sibling)) for (var i = sibling.length - 1; i >= 0; i--) insertBefore(sibling[i], this); else if (typeof more !== 'undefined') // deprecated for (var i = arguments.length - 1; i >= 0; i--) insertBefore(arguments[i], this); else if (typeof sibling !== 'undefined') insertBefore(sibling, this); return this; }; Class.prototype.insertAfter = function(prev) { insertAfter(this, prev); return this; }; Class.prototype.insertBefore = function(next) { insertBefore(this, next); return this; }; function append(parent, child) { _ensure(child); _ensure(parent); child.remove(); if (parent._last) { parent._last._next = child; child._prev = parent._last; } child._parent = parent; parent._last = child; if (!parent._first) { parent._first = child; } child._parent._flag(child, true); child._ts_parent = ++iid; parent._ts_children = ++iid; parent.touch(); } function prepend(parent, child) { _ensure(child); _ensure(parent); child.remove(); if (parent._first) { parent._first._prev = child; child._next = parent._first; } child._parent = parent; parent._first = child; if (!parent._last) { parent._last = child; } child._parent._flag(child, true); child._ts_parent = ++iid; parent._ts_children = ++iid; parent.touch(); }; function insertBefore(self, next) { _ensure(self); _ensure(next); self.remove(); var parent = next._parent; var prev = next._prev; next._prev = self; prev && (prev._next = self) || parent && (parent._first = self); self._parent = parent; self._prev = prev; self._next = next; self._parent._flag(self, true); self._ts_parent = ++iid; self.touch(); }; function insertAfter(self, prev) { _ensure(self); _ensure(prev); self.remove(); var parent = prev._parent; var next = prev._next; prev._next = self; next && (next._prev = self) || parent && (parent._last = self); self._parent = parent; self._prev = prev; self._next = next; self._parent._flag(self, true); self._ts_parent = ++iid; self.touch(); }; Class.prototype.remove = function(child, more) { if (typeof child !== 'undefined') { if (is.array(child)) { for (var i = 0; i < child.length; i++) _ensure(child[i]).remove(); } else if (typeof more !== 'undefined') { for (var i = 0; i < arguments.length; i++) _ensure(arguments[i]).remove(); } else { _ensure(child).remove(); } return this; } if (this._prev) { this._prev._next = this._next; } if (this._next) { this._next._prev = this._prev; } if (this._parent) { if (this._parent._first === this) { this._parent._first = this._next; } if (this._parent._last === this) { this._parent._last = this._prev; } this._parent._flag(this, false); this._parent._ts_children = ++iid; this._parent.touch(); } this._prev = this._next = this._parent = null; this._ts_parent = ++iid; // this._parent.touch(); return this; }; Class.prototype.empty = function() { var child, next = this._first; while (child = next) { next = child._next; child._prev = child._next = child._parent = null; this._flag(child, false); } this._first = this._last = null; this._ts_children = ++iid; this.touch(); return this; }; Class.prototype.touch = function() { this._ts_touch = ++iid; this._parent && this._parent.touch(); return this; }; /** * Deep flags used for optimizing event distribution. */ Class.prototype._flag = function(obj, name) { if (typeof name === 'undefined') { return this._flags !== null && this._flags[obj] || 0; } if (typeof obj === 'string') { if (name) { this._flags = this._flags || {}; if (!this._flags[obj] && this._parent) { this._parent._flag(obj, true); } this._flags[obj] = (this._flags[obj] || 0) + 1; } else if (this._flags && this._flags[obj] > 0) { if (this._flags[obj] == 1 && this._parent) { this._parent._flag(obj, false); } this._flags[obj] = this._flags[obj] - 1; } } if (typeof obj === 'object') { if (obj._flags) { for ( var type in obj._flags) { if (obj._flags[type] > 0) { this._flag(type, name); } } } } return this; }; /** * @private */ Class.prototype.hitTest = function(hit) { if (this.attr('spy')) { return true; } return hit.x >= 0 && hit.x <= this._pin._width && hit.y >= 0 && hit.y <= this._pin._height; }; function _ensure(obj) { if (obj && obj instanceof Class) { return obj; } throw 'Invalid node: ' + obj; }; module.exports = Class; },{"./core":60,"./util/is":77}],73:[function(require,module,exports){ module.exports = function() { var count = 0; function fork(fn, n) { count += n = (typeof n === 'number' && n >= 1 ? n : 1); return function() { fn && fn.apply(this, arguments); if (n > 0) { n--, count--, call(); } }; } var then = []; function call() { if (count === 0) { while (then.length) { setTimeout(then.shift(), 0); } } } fork.then = function(fn) { if (count === 0) { setTimeout(fn, 0); } else { then.push(fn); } }; return fork; }; },{}],74:[function(require,module,exports){ if (typeof Object.create == 'function') { module.exports = function(proto, props) { return Object.create.call(Object, proto, props); }; } else { module.exports = function(proto, props) { if (props) throw Error('Second argument is not supported!'); if (typeof proto !== 'object' || proto === null) throw Error('Invalid prototype!'); noop.prototype = proto; return new noop; }; function noop() { } } },{}],75:[function(require,module,exports){ module.exports = function(prototype, callback) { prototype._listeners = null; prototype.on = prototype.listen = function(types, listener) { if (!types || !types.length || typeof listener !== 'function') { return this; } if (this._listeners === null) { this._listeners = {}; } var isarray = typeof types !== 'string' && typeof types.join === 'function'; if (types = (isarray ? types.join(' ') : types).match(/\S+/g)) { for (var i = 0; i < types.length; i++) { var type = types[i]; this._listeners[type] = this._listeners[type] || []; this._listeners[type].push(listener); if (typeof callback === 'function') { callback(this, type, true); } } } return this; }; prototype.off = function(types, listener) { if (!types || !types.length || typeof listener !== 'function') { return this; } if (this._listeners === null) { return this; } var isarray = typeof types !== 'string' && typeof types.join === 'function'; if (types = (isarray ? types.join(' ') : types).match(/\S+/g)) { for (var i = 0; i < types.length; i++) { var type = types[i], all = this._listeners[type], index; if (all && (index = all.indexOf(listener)) >= 0) { all.splice(index, 1); if (!all.length) { delete this._listeners[type]; } if (typeof callback === 'function') { callback(this, type, false); } } } } return this; }; prototype.listeners = function(type) { return this._listeners && this._listeners[type]; }; prototype.publish = function(name, args) { var listeners = this.listeners(name); if (!listeners || !listeners.length) { return 0; } for (var l = 0; l < listeners.length; l++) { listeners[l].apply(this, args); } return listeners.length; }; prototype.trigger = function(name, args) { this.publish(name, args); return this; }; }; },{}],76:[function(require,module,exports){ module.exports = function(base) { for (var i = 1; i < arguments.length; i++) { var obj = arguments[i]; for ( var key in obj) { if (obj.hasOwnProperty(key)) { base[key] = obj[key]; } } } return base; }; },{}],77:[function(require,module,exports){ /** * ! is the definitive JavaScript type testing library * * @copyright 2013-2014 Enrico Marino / Jordan Harband * @license MIT */ var objProto = Object.prototype; var owns = objProto.hasOwnProperty; var toStr = objProto.toString; var NON_HOST_TYPES = { 'boolean' : 1, 'number' : 1, 'string' : 1, 'undefined' : 1 }; var hexRegex = /^[A-Fa-f0-9]+$/; var is = module.exports = {}; is.a = is.an = is.type = function(value, type) { return typeof value === type; }; is.defined = function(value) { return typeof value !== 'undefined'; }; is.empty = function(value) { var type = toStr.call(value); var key; if ('[object Array]' === type || '[object Arguments]' === type || '[object String]' === type) { return value.length === 0; } if ('[object Object]' === type) { for (key in value) { if (owns.call(value, key)) { return false; } } return true; } return !value; }; is.equal = function(value, other) { if (value === other) { return true; } var type = toStr.call(value); var key; if (type !== toStr.call(other)) { return false; } if ('[object Object]' === type) { for (key in value) { if (!is.equal(value[key], other[key]) || !(key in other)) { return false; } } for (key in other) { if (!is.equal(value[key], other[key]) || !(key in value)) { return false; } } return true; } if ('[object Array]' === type) { key = value.length; if (key !== other.length) { return false; } while (--key) { if (!is.equal(value[key], other[key])) { return false; } } return true; } if ('[object Function]' === type) { return value.prototype === other.prototype; } if ('[object Date]' === type) { return value.getTime() === other.getTime(); } return false; }; is.instance = function(value, constructor) { return value instanceof constructor; }; is.nil = function(value) { return value === null; }; is.undef = function(value) { return typeof value === 'undefined'; }; is.array = function(value) { return '[object Array]' === toStr.call(value); }; is.emptyarray = function(value) { return is.array(value) && value.length === 0; }; is.arraylike = function(value) { return !!value && !is.boolean(value) && owns.call(value, 'length') && isFinite(value.length) && is.number(value.length) && value.length >= 0; }; is.boolean = function(value) { return '[object Boolean]' === toStr.call(value); }; is.element = function(value) { return value !== undefined && typeof HTMLElement !== 'undefined' && value instanceof HTMLElement && value.nodeType === 1; }; is.fn = function(value) { return '[object Function]' === toStr.call(value); }; is.number = function(value) { return '[object Number]' === toStr.call(value); }; is.nan = function(value) { return !is.number(value) || value !== value; }; is.object = function(value) { return '[object Object]' === toStr.call(value); }; is.hash = function(value) { return is.object(value) && value.constructor === Object && !value.nodeType && !value.setInterval; }; is.regexp = function(value) { return '[object RegExp]' === toStr.call(value); }; is.string = function(value) { return '[object String]' === toStr.call(value); }; is.hex = function(value) { return is.string(value) && (!value.length || hexRegex.test(value)); }; },{}],78:[function(require,module,exports){ var create = require('./create'); var native = Math; module.exports = create(Math); module.exports.random = function(min, max) { if (typeof min === 'undefined') { max = 1, min = 0; } else if (typeof max === 'undefined') { max = min, min = 0; } return min == max ? min : native.random() * (max - min) + min; }; module.exports.rotate = function(num, min, max) { if (typeof min === 'undefined') { max = 1, min = 0; } else if (typeof max === 'undefined') { max = min, min = 0; } if (max > min) { num = (num - min) % (max - min); return num + (num < 0 ? max : min); } else { num = (num - max) % (min - max); return num + (num <= 0 ? min : max); } }; module.exports.limit = function(num, min, max) { if (num < min) { return min; } else if (num > max) { return max; } else { return num; } }; module.exports.length = function(x, y) { return native.sqrt(x * x + y * y); }; },{"./create":74}],79:[function(require,module,exports){ module.exports = function(img, owidth, oheight, stretch, inner, insert) { var width = img.width; var height = img.height; var left = img.left; var right = img.right; var top = img.top; var bottom = img.bottom; left = typeof left === 'number' && left === left ? left : 0; right = typeof right === 'number' && right === right ? right : 0; top = typeof top === 'number' && top === top ? top : 0; bottom = typeof bottom === 'number' && bottom === bottom ? bottom : 0; width = width - left - right; height = height - top - bottom; if (!inner) { owidth = Math.max(owidth - left - right, 0); oheight = Math.max(oheight - top - bottom, 0); } var i = 0; if (top > 0 && left > 0) insert(i++, 0, 0, left, top, 0, 0, left, top); if (bottom > 0 && left > 0) insert(i++, 0, height + top, left, bottom, 0, oheight + top, left, bottom); if (top > 0 && right > 0) insert(i++, width + left, 0, right, top, owidth + left, 0, right, top); if (bottom > 0 && right > 0) insert(i++, width + left, height + top, right, bottom, owidth + left, oheight + top, right, bottom); if (stretch) { if (top > 0) insert(i++, left, 0, width, top, left, 0, owidth, top); if (bottom > 0) insert(i++, left, height + top, width, bottom, left, oheight + top, owidth, bottom); if (left > 0) insert(i++, 0, top, left, height, 0, top, left, oheight); if (right > 0) insert(i++, width + left, top, right, height, owidth + left, top, right, oheight); // center insert(i++, left, top, width, height, left, top, owidth, oheight); } else { // tile var l = left, r = owidth, w; while (r > 0) { w = Math.min(width, r), r -= width; var t = top, b = oheight, h; while (b > 0) { h = Math.min(height, b), b -= height; insert(i++, left, top, w, h, l, t, w, h); if (r <= 0) { if (left) insert(i++, 0, top, left, h, 0, t, left, h); if (right) insert(i++, width + left, top, right, h, l + w, t, right, h); } t += h; } if (top) insert(i++, left, 0, w, top, l, 0, w, top); if (bottom) insert(i++, left, height + top, w, bottom, l, t, w, bottom); l += w; } } return i; }; },{}],80:[function(require,module,exports){ module.exports = {}; },{}],81:[function(require,module,exports){ module.exports.startsWith = function(str, sub) { return typeof str === 'string' && typeof sub === 'string' && str.substring(0, sub.length) == sub; }; },{}],82:[function(require,module,exports){ module.exports = require('../lib/'); module.exports.internal = {}; require('../lib/canvas'); module.exports.internal.Image = require('../lib/image'); require('../lib/anim'); require('../lib/str'); require('../lib/layout'); require('../lib/addon/tween'); module.exports.Mouse = require('../lib/addon/mouse'); module.exports.Math = require('../lib/util/math'); module.exports._extend = require('../lib/util/extend'); module.exports._create = require('../lib/util/create'); require('../lib/loader/web'); },{"../lib/":63,"../lib/addon/mouse":55,"../lib/addon/tween":56,"../lib/anim":57,"../lib/canvas":59,"../lib/image":62,"../lib/layout":64,"../lib/loader/web":65,"../lib/str":70,"../lib/util/create":74,"../lib/util/extend":76,"../lib/util/math":78}]},{},[1])(1) });
sufuf3/cdnjs
ajax/libs/planck-js/0.3.0-rc.1/planck-with-testbed.js
JavaScript
mit
478,044
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.mod.mixin.core.event.state; import net.minecraftforge.fml.common.event.FMLEvent; import net.minecraftforge.fml.common.event.FMLStateEvent; import org.spongepowered.api.Game; import org.spongepowered.api.util.annotation.NonnullByDefault; import org.spongepowered.api.util.event.callback.CallbackList; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.mod.SpongeMod; @NonnullByDefault @Mixin(FMLStateEvent.class) public abstract class MixinEventState extends FMLEvent { public Game getGame() { return SpongeMod.instance.getGame(); } public CallbackList getCallbacks() { // TODO return null; } }
joseph00713/Sponge
src/main/java/org/spongepowered/mod/mixin/core/event/state/MixinEventState.java
Java
mit
1,933
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), meta: { banner : '/*!\n' + ' * <%= pkg.title %> v<%= pkg.version %> - <%= pkg.description %>\n' + ' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %> - <%= pkg.homepage %>\n' + ' * License: <%= pkg.license %>\n' + ' */\n\n' }, uglify: { options : { banner : '<%= meta.banner %>', report: 'gzip' }, dist: { files: { 'jquery.timepicker.min.js': ['jquery.timepicker.js'] } } }, cssmin: { minify: { files: { 'jquery.timepicker.min.css': ['jquery.timepicker.css'] } } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.registerTask('default', ['uglify', 'cssmin']); };
MuddyPaw/testcalendar
web/vendor/timepicker/GruntFile.js
JavaScript
mit
825
<?php namespace Chamilo\Application\Weblcms\Tool\Implementation\Geolocation\Package; class Activator extends \Chamilo\Configuration\Package\Action\Activator { }
cosnicsTHLU/cosnics
src/Chamilo/Application/Weblcms/Tool/Implementation/Geolocation/Package/Activator.php
PHP
mit
162
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ This module defines Entry classes for containing experimental data. """ __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __date__ = "Jun 27, 2012" from pymatgen.analysis.phase_diagram import PDEntry from pymatgen.core.composition import Composition from monty.json import MSONable from pymatgen.analysis.thermochemistry import ThermoData class ExpEntry(PDEntry, MSONable): """ An lightweight ExpEntry object containing experimental data for a composition for many purposes. Extends a PDEntry so that it can be used for phase diagram generation and reaction calculation. Current version works only with solid phases and at 298K. Further extensions for temperature dependence are planned. """ def __init__(self, composition, thermodata, temperature=298): """ Args: composition: Composition of the entry. For flexibility, this can take the form of all the typical input taken by a Composition, including a {symbol: amt} dict, a string formula, and others. thermodata: A sequence of ThermoData associated with the entry. temperature: A temperature for the entry in Kelvin. Defaults to 298K. """ comp = Composition(composition) self._thermodata = thermodata found = False enthalpy = float("inf") for data in self._thermodata: if data.type == "fH" and data.value < enthalpy and \ (data.phaseinfo != "gas" and data.phaseinfo != "liquid"): enthalpy = data.value found = True if not found: raise ValueError("List of Thermodata does not contain enthalpy " "values.") self.temperature = temperature super().__init__(comp, enthalpy) def __repr__(self): return "ExpEntry {}, Energy = {:.4f}".format(self.composition.formula, self.energy) def __str__(self): return self.__repr__() @classmethod def from_dict(cls, d): """ :param d: Dict representation. :return: ExpEntry """ thermodata = [ThermoData.from_dict(td) for td in d["thermodata"]] return cls(d["composition"], thermodata, d["temperature"]) def as_dict(self): """ :return: MSONable dict """ return {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "thermodata": [td.as_dict() for td in self._thermodata], "composition": self.composition.as_dict(), "temperature": self.temperature}
mbkumar/pymatgen
pymatgen/entries/exp_entries.py
Python
mit
2,923
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html><meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>void override_outcome_exception(basic_outcome&lt;T, EC, EP, NoValuePolicy&gt; *, U &amp;&amp;) noexcept - Boost.Outcome documentation</title> <link rel="stylesheet" href="../../../css/boost.css" type="text/css"> <meta name="generator" content="Hugo 0.52 with Boostdoc theme"> <meta name="viewport" content="width=device-width,initial-scale=1.0"/> <link rel="icon" href="../../../images/favicon.ico" type="image/ico"/> <body><div class="spirit-nav"> <a accesskey="p" href="../../../reference/functions/hooks/hook_result_move_construction.html"><img src="../../../images/prev.png" alt="Prev"></a> <a accesskey="u" href="../../../reference/functions/hooks.html"><img src="../../../images/up.png" alt="Up"></a> <a accesskey="h" href="../../../index.html"><img src="../../../images/home.png" alt="Home"></a><a accesskey="n" href="../../../reference/functions/hooks/set_spare_storage.html"><img src="../../../images/next.png" alt="Next"></a></div><div id="content"> <div class="titlepage"><div><div><h1 style="clear: both"><code>void override_outcome_exception(basic_outcome&lt;T, EC, EP, NoValuePolicy&gt; *, U &amp;&amp;) noexcept</code></h1></div></div></div> <p>Overrides the exception to something other than what was constructed. You <em>almost certainly</em> never want to use this function. A much better way of overriding the exception returned is to create a custom no-value policy which lazily synthesises a custom exception object at the point of need.</p> <p>The only reason that this function exists is because some people have very corner case needs where a custom no-value policy can&rsquo;t be used, and where move-constructing a new <code>outcome</code> from an old <code>outcome</code> with the exception state replaced isn&rsquo;t possible (e.g. when the types are non-copyable and non-moveable).</p> <p>Unless you are in a situation where no other viable alternative exists, do not use this function.</p> <p><em>Overridable</em>: Not overridable.</p> <p><em>Requires</em>: Nothing.</p> <p><em>Namespace</em>: <code>BOOST_OUTCOME_V2_NAMESPACE::hooks</code></p> <p><em>Header</em>: <code>&lt;boost/outcome/basic_outcome.hpp&gt;</code></p> </div><p><small>Last revised: January 30, 2019 at 16:16:10 UTC</small></p> <hr> <div class="spirit-nav"> <a accesskey="p" href="../../../reference/functions/hooks/hook_result_move_construction.html"><img src="../../../images/prev.png" alt="Prev"></a> <a accesskey="u" href="../../../reference/functions/hooks.html"><img src="../../../images/up.png" alt="Up"></a> <a accesskey="h" href="../../../index.html"><img src="../../../images/home.png" alt="Home"></a><a accesskey="n" href="../../../reference/functions/hooks/set_spare_storage.html"><img src="../../../images/next.png" alt="Next"></a></div></body> </html>
davehorton/drachtio-server
deps/boost_1_77_0/libs/outcome/doc/html/reference/functions/hooks/override_outcome_exception.html
HTML
mit
2,986
<?php class CM_FormField_FloatTest extends CMTest_TestCase { public function testValidate() { $environment = new CM_Frontend_Environment(); $field = new CM_FormField_Float(['name' => 'foo']); $this->assertSame(1.3, $field->validate($environment, 1.3)); $this->assertInstanceOf('CM_Exception_FormFieldValidation', $this->catchException(function() use ($field, $environment) { $field->validate($environment, 'foo'); })); } public function testValidateMinMaxOptions() { $environment = new CM_Frontend_Environment(); $field = new CM_FormField_Float(['name' => 'foo', 'min' => 1.3, 'max' => 2.5]); $this->assertSame(1.3, $field->validate($environment, 1.3)); $this->assertInstanceOf('CM_Exception_FormFieldValidation', $this->catchException(function() use ($field, $environment) { $field->validate($environment, 1.2); })); $this->assertInstanceOf('CM_Exception_FormFieldValidation', $this->catchException(function() use ($field, $environment) { $field->validate($environment, 2.6); })); } }
njam/CM
tests/library/CM/FormField/FloatTest.php
PHP
mit
1,150
var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;$jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(b,d,a){b!=Array.prototype&&b!=Object.prototype&&(b[d]=a.value)};$jscomp.getGlobal=function(b){return"undefined"!=typeof window&&window===b?b:"undefined"!=typeof global&&null!=global?global:b};$jscomp.global=$jscomp.getGlobal(this);$jscomp.SYMBOL_PREFIX="jscomp_symbol_"; $jscomp.initSymbol=function(){$jscomp.initSymbol=function(){};$jscomp.global.Symbol||($jscomp.global.Symbol=$jscomp.Symbol)};$jscomp.symbolCounter_=0;$jscomp.Symbol=function(b){return $jscomp.SYMBOL_PREFIX+(b||"")+$jscomp.symbolCounter_++}; $jscomp.initSymbolIterator=function(){$jscomp.initSymbol();var b=$jscomp.global.Symbol.iterator;b||(b=$jscomp.global.Symbol.iterator=$jscomp.global.Symbol("iterator"));"function"!=typeof Array.prototype[b]&&$jscomp.defineProperty(Array.prototype,b,{configurable:!0,writable:!0,value:function(){return $jscomp.arrayIterator(this)}});$jscomp.initSymbolIterator=function(){}};$jscomp.arrayIterator=function(b){var d=0;return $jscomp.iteratorPrototype(function(){return d<b.length?{done:!1,value:b[d++]}:{done:!0}})}; $jscomp.iteratorPrototype=function(b){$jscomp.initSymbolIterator();b={next:b};b[$jscomp.global.Symbol.iterator]=function(){return this};return b};$jscomp.iteratorFromArray=function(b,d){$jscomp.initSymbolIterator();b instanceof String&&(b+="");var a=0,h={next:function(){if(a<b.length){var l=a++;return{value:d(l,b[l]),done:!1}}h.next=function(){return{done:!0,value:void 0}};return h.next()}};h[Symbol.iterator]=function(){return h};return h}; $jscomp.polyfill=function(b,d,a,h){if(d){a=$jscomp.global;b=b.split(".");for(h=0;h<b.length-1;h++){var l=b[h];l in a||(a[l]={});a=a[l]}b=b[b.length-1];h=a[b];d=d(h);d!=h&&null!=d&&$jscomp.defineProperty(a,b,{configurable:!0,writable:!0,value:d})}};$jscomp.polyfill("Array.prototype.keys",function(b){return b?b:function(){return $jscomp.iteratorFromArray(this,function(b){return b})}},"es6","es3");$jscomp.polyfill("Object.getOwnPropertySymbols",function(b){return b?b:function(){return[]}},"es6","es5"); $jscomp.owns=function(b,d){return Object.prototype.hasOwnProperty.call(b,d)};$jscomp.polyfill("Object.assign",function(b){return b?b:function(b,a){for(var d=1;d<arguments.length;d++){var l=arguments[d];if(l)for(var g in l)$jscomp.owns(l,g)&&(b[g]=l[g])}return b}},"es6","es3");$jscomp.findInternal=function(b,d,a){b instanceof String&&(b=String(b));for(var h=b.length,l=0;l<h;l++){var g=b[l];if(d.call(a,g,l,b))return{i:l,v:g}}return{i:-1,v:void 0}}; $jscomp.polyfill("Array.prototype.find",function(b){return b?b:function(b,a){return $jscomp.findInternal(this,b,a).v}},"es6","es3");$jscomp.polyfill("Array.prototype.values",function(b){return b?b:function(){return $jscomp.iteratorFromArray(this,function(b,a){return a})}},"es6","es3"); (function(b,d){"object"===typeof exports&&"object"===typeof module?module.exports=d():"function"===typeof define&&define.amd?define([],d):"object"===typeof exports?exports.RxPlayer=d():b.RxPlayer=d()})(this,function(){return function(b){function d(h){if(a[h])return a[h].exports;var l=a[h]={i:h,l:!1,exports:{}};b[h].call(l.exports,l,l.exports,d);l.l=!0;return l.exports}var a={};d.m=b;d.c=a;d.i=function(a){return a};d.d=function(a,b,g){d.o(a,b)||Object.defineProperty(a,b,{configurable:!1,enumerable:!0, get:g})};d.n=function(a){var b=a&&a.__esModule?function(){return a["default"]}:function(){return a};d.d(b,"a",b);return b};d.o=function(a,b){return Object.prototype.hasOwnProperty.call(a,b)};d.p="";return d(d.s=138)}([function(b,d,a){var h=a(12),l=a(263),g=a(48);b=function(){function a(a){this._isScalar=!1;a&&(this._subscribe=a)}a.prototype.lift=function(f){var c=new a;c.source=this;c.operator=f;return c};a.prototype.subscribe=function(a,c,e){var f=this.operator;a=l.toSubscriber(a,c,e);f?f.call(a, this.source):a.add(this.source?this._subscribe(a):this._trySubscribe(a));if(a.syncErrorThrowable&&(a.syncErrorThrowable=!1,a.syncErrorThrown))throw a.syncErrorValue;return a};a.prototype._trySubscribe=function(a){try{return this._subscribe(a)}catch(c){a.syncErrorThrown=!0,a.syncErrorValue=c,a.error(c)}};a.prototype.forEach=function(a,c){var e=this;c||(h.root.Rx&&h.root.Rx.config&&h.root.Rx.config.Promise?c=h.root.Rx.config.Promise:h.root.Promise&&(c=h.root.Promise));if(!c)throw Error("no Promise impl found"); return new c(function(c,f){var k=e.subscribe(function(c){if(k)try{a(c)}catch(p){f(p),k.unsubscribe()}else a(c)},f,c)})};a.prototype._subscribe=function(a){return this.source.subscribe(a)};a.prototype[g.observable]=function(){return this};a.create=function(f){return new a(f)};return a}();d.Observable=b},function(b,d,a){function h(){}var l={NONE:0,ERROR:1,WARNING:2,INFO:3,DEBUG:4},g=function(){};h.error=g;h.warn=g;h.info=g;h.debug=g;h.setLevel=function(a){"string"==typeof a&&(a=l[a]);h.error=a>=l.ERROR? console.error.bind(console):g;h.warn=a>=l.WARNING?console.warn.bind(console):g;h.info=a>=l.INFO?console.info.bind(console):g;h.debug=a>=l.DEBUG?console.log.bind(console):g};d.a=h},function(b,d,a){function h(a){this.name="AssertionError";this.message=a;Error.captureStackTrace&&Error.captureStackTrace(this,h)}function l(a,f){if(!a)throw new h(f);}var g="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor=== Symbol&&a!==Symbol.prototype?"symbol":typeof a};h.prototype=Error();l.equal=function(a,f,c){return l(a===f,c)};l.iface=function(a,f,c){l(a,f+" should be an object");for(var e in c)l.equal(g(a[e]),c[e],f+" should have property "+e+" as a "+c[e])};d.a=l},function(b,d,a){var h=this&&this.__extends||function(a,e){function c(){this.constructor=a}for(var f in e)e.hasOwnProperty(f)&&(a[f]=e[f]);a.prototype=null===e?Object.create(e):(c.prototype=e.prototype,new c)},l=a(51);b=a(11);var g=a(71),k=a(49);a=function(a){function c(e, k,b){a.call(this);this.syncErrorValue=null;this.isStopped=this.syncErrorThrowable=this.syncErrorThrown=!1;switch(arguments.length){case 0:this.destination=g.empty;break;case 1:if(!e){this.destination=g.empty;break}if("object"===typeof e){e instanceof c?(this.destination=e,this.destination.add(this)):(this.syncErrorThrowable=!0,this.destination=new f(this,e));break}default:this.syncErrorThrowable=!0,this.destination=new f(this,e,k,b)}}h(c,a);c.prototype[k.rxSubscriber]=function(){return this};c.create= function(a,e,f){a=new c(a,e,f);a.syncErrorThrowable=!1;return a};c.prototype.next=function(a){this.isStopped||this._next(a)};c.prototype.error=function(a){this.isStopped||(this.isStopped=!0,this._error(a))};c.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())};c.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,a.prototype.unsubscribe.call(this))};c.prototype._next=function(a){this.destination.next(a)};c.prototype._error=function(a){this.destination.error(a); this.unsubscribe()};c.prototype._complete=function(){this.destination.complete();this.unsubscribe()};c.prototype._unsubscribeAndRecycle=function(){var a=this._parent,c=this._parents;this._parents=this._parent=null;this.unsubscribe();this.isStopped=this.closed=!1;this._parent=a;this._parents=c;return this};return c}(b.Subscription);d.Subscriber=a;var f=function(a){function c(c,e,f,k){a.call(this);this._parentSubscriber=c;c=this;if(l.isFunction(e))var m=e;else e&&(m=e.next,f=e.error,k=e.complete,e!== g.empty&&(c=Object.create(e),l.isFunction(c.unsubscribe)&&this.add(c.unsubscribe.bind(c)),c.unsubscribe=this.unsubscribe.bind(this)));this._context=c;this._next=m;this._error=f;this._complete=k}h(c,a);c.prototype.next=function(a){if(!this.isStopped&&this._next){var c=this._parentSubscriber;c.syncErrorThrowable?this.__tryOrSetError(c,this._next,a)&&this.unsubscribe():this.__tryOrUnsub(this._next,a)}};c.prototype.error=function(a){if(!this.isStopped){var c=this._parentSubscriber;if(this._error)c.syncErrorThrowable? this.__tryOrSetError(c,this._error,a):this.__tryOrUnsub(this._error,a),this.unsubscribe();else if(c.syncErrorThrowable)c.syncErrorValue=a,c.syncErrorThrown=!0,this.unsubscribe();else throw this.unsubscribe(),a;}};c.prototype.complete=function(){var a=this;if(!this.isStopped){var c=this._parentSubscriber;if(this._complete){var e=function(){return a._complete.call(a._context)};c.syncErrorThrowable?this.__tryOrSetError(c,e):this.__tryOrUnsub(e)}this.unsubscribe()}};c.prototype.__tryOrUnsub=function(a, c){try{a.call(this._context,c)}catch(q){throw this.unsubscribe(),q;}};c.prototype.__tryOrSetError=function(a,c,e){try{c.call(this._context,e)}catch(r){return a.syncErrorValue=r,a.syncErrorThrown=!0}return!1};c.prototype._unsubscribe=function(){var a=this._parentSubscriber;this._parentSubscriber=this._context=null;a.unsubscribe()};return c}(a)},function(b,d,a){d.a={DEFAULT_UNMUTED_VOLUME:.1,DEFAULT_AUDIO_TRACK:{language:"fra",audioDescription:!1},DEFAULT_TEXT_TRACK:null,DEFAULT_AUTO_PLAY:!1,DEFAULT_SHOW_SUBTITLE:!0, DEFAULT_WANTED_BUFFER_AHEAD:30,DEFAULT_MAX_BUFFER_AHEAD:Infinity,DEFAULT_MAX_BUFFER_BEHIND:Infinity,DEFAULT_INITIAL_BITRATES:{audio:0,video:0,other:0},DEFAULT_MAX_BITRATES:{audio:Infinity,video:Infinity,other:Infinity},DEFAULT_ADAPTIVE_BUFFER_THRESHOLD:.3,INACTIVITY_DELAY:6E4,DEFAULT_THROTTLE_WHEN_HIDDEN:!1,DEFAULT_LIMIT_VIDEO_WIDTH:!1,DEFAULT_LIVE_GAP:10,DEFAULT_SUGGESTED_PRESENTATION_DELAY:{SMOOTH:10,DASH:10},DISCONTINUITY_THRESHOLD:1,END_OF_PLAY:.5,BITRATE_REBUFFERING_RATIO:1.5,BUFFER_GC_GAPS:{CALM:240, BEEFY:30},DEFAULT_MAX_PIPELINES_RETRY_ON_ERROR:4,DEFAULT_MAX_PIPELINES_RETRY_ON_OFFLINE:Infinity,INITIAL_BACKOFF_DELAY_BASE:200,MAX_BACKOFF_DELAY_BASE:3E3,SAMPLING_INTERVAL_MEDIASOURCE:1E3,SAMPLING_INTERVAL_NO_MEDIASOURCE:500,ABR_MINIMUM_TOTAL_BYTES:128E3,ABR_MINIMUM_CHUNK_SIZE:16E3,ABR_STARVATION_GAP:5,OUT_OF_STARVATION_GAP:7,RESUME_AFTER_SEEKING_GAP:.5,RESUME_AFTER_BUFFERING_GAP:5,STALL_GAP:.5,MAX_MISSING_FROM_COMPLETE_SEGMENT:.12,MAX_BUFFERED_DISTANCE:.1,MINIMUM_SEGMENT_SIZE:.3,EME_DEFAULT_WIDEVINE_ROBUSTNESSES:["HW_SECURE_ALL", "HW_SECURE_DECODE","HW_SECURE_CRYPTO","SW_SECURE_DECODE","SW_SECURE_CRYPTO"],EME_KEY_SYSTEMS:{clearkey:["webkit-org.w3.clearkey","org.w3.clearkey"],widevine:["com.widevine.alpha"],playready:["com.microsoft.playready","com.chromecast.playready","com.youtube.playready"]}}},function(b,d,a){var h=this&&this.__extends||function(a,c){function e(){this.constructor=a}for(var f in c)c.hasOwnProperty(f)&&(a[f]=c[f]);a.prototype=null===c?Object.create(c):(e.prototype=c.prototype,new e)},l=a(0);b=a(3);var g= a(11),k=a(50),f=a(72),c=a(49),e=function(a){function c(c){a.call(this,c);this.destination=c}h(c,a);return c}(b.Subscriber);d.SubjectSubscriber=e;a=function(a){function b(){a.call(this);this.observers=[];this.hasError=this.isStopped=this.closed=!1;this.thrownError=null}h(b,a);b.prototype[c.rxSubscriber]=function(){return new e(this)};b.prototype.lift=function(a){var c=new m(this,this);c.operator=a;return c};b.prototype.next=function(a){if(this.closed)throw new k.ObjectUnsubscribedError;if(!this.isStopped){var c= this.observers,e=c.length;c=c.slice();for(var f=0;f<e;f++)c[f].next(a)}};b.prototype.error=function(a){if(this.closed)throw new k.ObjectUnsubscribedError;this.hasError=!0;this.thrownError=a;this.isStopped=!0;var c=this.observers,e=c.length;c=c.slice();for(var f=0;f<e;f++)c[f].error(a);this.observers.length=0};b.prototype.complete=function(){if(this.closed)throw new k.ObjectUnsubscribedError;this.isStopped=!0;var a=this.observers,c=a.length;a=a.slice();for(var e=0;e<c;e++)a[e].complete();this.observers.length= 0};b.prototype.unsubscribe=function(){this.closed=this.isStopped=!0;this.observers=null};b.prototype._trySubscribe=function(c){if(this.closed)throw new k.ObjectUnsubscribedError;return a.prototype._trySubscribe.call(this,c)};b.prototype._subscribe=function(a){if(this.closed)throw new k.ObjectUnsubscribedError;if(this.hasError)return a.error(this.thrownError),g.Subscription.EMPTY;if(this.isStopped)return a.complete(),g.Subscription.EMPTY;this.observers.push(a);return new f.SubjectSubscription(this, a)};b.prototype.asObservable=function(){var a=new l.Observable;a.source=this;return a};b.create=function(a,c){return new m(a,c)};return b}(l.Observable);d.Subject=a;var m=function(a){function c(c,e){a.call(this);this.destination=c;this.source=e}h(c,a);c.prototype.next=function(a){var c=this.destination;c&&c.next&&c.next(a)};c.prototype.error=function(a){var c=this.destination;c&&c.error&&this.destination.error(a)};c.prototype.complete=function(){var a=this.destination;a&&a.complete&&this.destination.complete()}; c.prototype._subscribe=function(a){return this.source?this.source.subscribe(a):g.Subscription.EMPTY};return c}(a);d.AnonymousSubject=m},function(b,d,a){function h(a){return!!a&&!!a.type&&0<=l.a.keys.indexOf(a.type)}a.d(d,"d",function(){return h});var l=a(18),g=a(132),k=a(133),f=a(134),c=a(135),e=a(136),m=a(137);a.d(d,"b",function(){return l.b});a.d(d,"a",function(){return l.a});a.d(d,"j",function(){return l.c});a.d(d,"c",function(){return g.a});a.d(d,"g",function(){return k.a});a.d(d,"f",function(){return f.a}); a.d(d,"i",function(){return c.a});a.d(d,"e",function(){return e.a});a.d(d,"h",function(){return m.a})},function(b,d,a){function h(a){return!!p.a&&p.a.isTypeSupported(a)}function l(){return p.b}function g(a){return a.readyState>=p.c.HAVE_METADATA?q.Observable.of(null):t.f(a).take(1)}function k(c){return c.readyState>=p.c.HAVE_ENOUGH_DATA?q.Observable.of(null):a.i(r.a)(c,"canplay").take(1)}function f(a,c){var e=void 0;if(p.b){var f=a.textTracks.length;a=0<f?a.textTracks[f-1]:a.addTextTrack("subtitles"); a.mode=c?a.HIDDEN:a.SHOWING}else e=document.createElement("track"),a.appendChild(e),a=e.track,e.kind="subtitles",a.mode=c?"hidden":"showing";return{track:a,trackElement:e}}function c(){return!p.b}function e(a){return p.d&&a.stalled&&"timeupdate"===a.state&&a.range&&10<a.range.end-a.currentTime}function m(a){a.src="";a.removeAttribute("src")}function n(){return!1===navigator.onLine}a.d(d,"n",function(){return f});a.d(d,"j",function(){return k});a.d(d,"i",function(){return g});a.d(d,"k",function(){return m}); a.d(d,"p",function(){return h});a.d(d,"q",function(){return n});a.d(d,"m",function(){return e});a.d(d,"o",function(){return c});a.d(d,"e",function(){return l});var q=a(0);a.n(q);var r=a(31);b=a(29);var p=a(34),t=a(17),u=a(90),w=a(88);a.d(d,"a",function(){return p.e});a.d(d,"f",function(){return w.a});a.d(d,"l",function(){return p.a});a.d(d,"c",function(){return u.a});a.d(d,"b",function(){return u.b});a.d(d,"r",function(){return p.b});a.d(d,"d",function(){return u.c});a.d(d,"g",function(){return w.b}); a.d(d,"h",function(){return w.c});if(window.WebKitSourceBuffer&&!window.WebKitSourceBuffer.prototype.addEventListener){d=window.WebKitSourceBuffer.prototype;for(var x in b.a.prototype)d[x]=b.a.prototype[x];d.__listeners=[];d.appendBuffer=function(a){if(this.updating)throw Error("updating");this.trigger("updatestart");this.updating=!0;try{this.append(a)}catch(y){this.__emitUpdate("error",y);return}this.__emitUpdate("update")};d.__emitUpdate=function(a,c){var e=this;setTimeout(function(){e.trigger(a, c);e.updating=!1;e.trigger("updateend")},0)}}},function(b,d,a){var h=Object.getOwnPropertySymbols,l=Object.prototype.hasOwnProperty,g=Object.prototype.propertyIsEnumerable;b.exports=function(){try{if(!Object.assign)return!1;var a=new String("abc");a[5]="de";if("5"===Object.getOwnPropertyNames(a)[0])return!1;var f={};for(a=0;10>a;a++)f["_"+String.fromCharCode(a)]=a;if("0123456789"!==Object.getOwnPropertyNames(f).map(function(a){return f[a]}).join(""))return!1;var c={};"abcdefghijklmnopqrst".split("").forEach(function(a){c[a]= a});return"abcdefghijklmnopqrst"!==Object.keys(Object.assign({},c)).join("")?!1:!0}catch(e){return!1}}()?Object.assign:function(a,f){if(null===a||void 0===a)throw new TypeError("Object.assign cannot be called with null or undefined");var c=Object(a);for(var e,k=1;k<arguments.length;k++){var b=Object(arguments[k]);for(var d in b)l.call(b,d)&&(c[d]=b[d]);if(h){e=h(b);for(var r=0;r<e.length;r++)g.call(b,e[r])&&(c[e[r]]=b[e[r]])}}return c}},function(b,d,a){d.a=function(a){return a instanceof h.Observable? a:a&&"function"==typeof a.subscribe?new h.Observable(function(g){var k=a.subscribe(function(a){return g.next(a)},function(a){return g.error(a)},function(){return g.complete()});return function(){k&&k.dispose?k.dispose():k&&k.unsubscribe&&k.unsubscribe()}}):a&&"function"==typeof a.then?h.Observable.fromPromise(a):h.Observable.of(a)};var h=a(0);a.n(h)},function(b,d,a){function h(a,c){return{start:Math.min(a.start,c.start),end:Math.max(a.end,c.end)}}function l(a,c){var e=a.end;return a.start<=c&&c<e} function g(a,c){return l(a,c.start)||a.start<c.end&&c.end<a.end||l(c,a.start)}function k(a){for(var c=[],e=0;e<a.length;e++)c.push({start:a.start(e),end:a.end(e)});return c}function f(a,c){for(var e=a.length-1;0<=e;e--){var f=a.start(e);if(c>=f){var k=a.end(e);if(c<k)return{start:f,end:k}}}return null}function c(a,c){for(var e=a.length,f=0;f<e;f++){var k=a.start(f);if(c<k)return k-c}return Infinity}function e(a,c){for(var e=null,f=[],k=a.length-1;0<=k;k--){var g=a.start(k),b=a.end(k);c<g||c>=b?f.push({start:g, end:b}):e={start:g,end:b}}return{outerRanges:f,innerRange:e}}function m(a,c){return(a=f(a,c))?a.end-a.start:0}function n(a,c){return(a=f(a,c))?c-a.start:0}function q(a,c){return(a=f(a,c))?a.end-c:Infinity}function r(a,c){if(c.start===c.end)return a;for(var e=0;e<a.length;e++){var f=a[e],k=g(c,f),b=Math.abs(f.start-c.end)<t||Math.abs(f.end-c.start)<t;if(k||b)c=h(c,f),a.splice(e--,1);else if(0===e){if(c.end<=a[0].start)break}else if(a[e-1].end<=c.start&&c.end<=f.start)break}a.splice(e,0,c);for(c=0;c< a.length;c++)e=a[c],e.start===e.end&&a.splice(c++,1);for(c=1;c<a.length;c++)if(e=a[c-1],f=a[c],Math.abs(f.start-e.end)<t||Math.abs(f.end-e.start)<t)e=h(e,f),a.splice(--c,2,e);return a}function p(a,c){for(var e=0;e<a.length;e++){var f=a[e];a:{var k=f;for(var b=c,m=0;m<b.length;m++)if(g(k,b[m])){k=b[m];break a}k=null}k?k.start>f.start?f.start=k.start:k.end<f.end&&(f.end=k.end):a.splice(e--,1)}return a}a.d(d,"h",function(){return k});a.d(d,"g",function(){return e});a.d(d,"a",function(){return q});a.d(d, "d",function(){return c});a.d(d,"c",function(){return n});a.d(d,"i",function(){return f});a.d(d,"b",function(){return m});a.d(d,"e",function(){return r});a.d(d,"f",function(){return p});var t=1/60},function(b,d,a){function h(a){return a.reduce(function(a,c){return a.concat(c instanceof e.UnsubscriptionError?c.errors:c)},[])}var l=a(26),g=a(84),k=a(51),f=a(52),c=a(33),e=a(262);b=function(){function a(a){this.closed=!1;this._subscriptions=this._parents=this._parent=null;a&&(this._unsubscribe=a)}a.prototype.unsubscribe= function(){var a=!1;if(!this.closed){var b=this._parent;var m=this._parents,d=this._unsubscribe,t=this._subscriptions;this.closed=!0;this._subscriptions=this._parents=this._parent=null;for(var u=-1,w=m?m.length:0;b;)b.remove(this),b=++u<w&&m[u]||null;if(k.isFunction(d)&&(b=f.tryCatch(d).call(this),b===c.errorObject)){a=!0;var x=x||(c.errorObject.e instanceof e.UnsubscriptionError?h(c.errorObject.e.errors):[c.errorObject.e])}if(l.isArray(t))for(u=-1,w=t.length;++u<w;)b=t[u],g.isObject(b)&&(b=f.tryCatch(b.unsubscribe).call(b), b===c.errorObject&&(a=!0,x=x||[],b=c.errorObject.e,b instanceof e.UnsubscriptionError?x=x.concat(h(b.errors)):x.push(b)));if(a)throw new e.UnsubscriptionError(x);}};a.prototype.add=function(c){if(!c||c===a.EMPTY)return a.EMPTY;if(c===this)return this;var e=c;switch(typeof c){case "function":e=new a(c);case "object":if(e.closed||"function"!==typeof e.unsubscribe)return e;if(this.closed)return e.unsubscribe(),e;"function"!==typeof e._addParent&&(c=e,e=new a,e._subscriptions=[c]);break;default:throw Error("unrecognized teardown "+ c+" added to Subscription.");}(this._subscriptions||(this._subscriptions=[])).push(e);e._addParent(this);return e};a.prototype.remove=function(a){var c=this._subscriptions;c&&(a=c.indexOf(a),-1!==a&&c.splice(a,1))};a.prototype._addParent=function(a){var c=this._parent,e=this._parents;c&&c!==a?e?-1===e.indexOf(a)&&e.push(a):this._parents=[a]:this._parent=a};a.EMPTY=function(a){a.closed=!0;return a}(new a);return a}();d.Subscription=b},function(b,d,a){b=a(264);a="undefined"!==typeof self&&"undefined"!== typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&self;b="undefined"!==typeof window&&window||"undefined"!==typeof b&&b||a;d.root=b;if(!b)throw Error("RxJS could not find any global context (window, self, global)");},function(b,d,a){function h(a){for(var c=a.length,e=new Uint8Array(c),f=0;f<c;f++)e[f]=a.charCodeAt(f)&255;return e}function l(a){return String.fromCharCode.apply(null,a)}function g(a){for(var c="",e=a.length,f=0;f<e;f+=2)c+=String.fromCharCode(a[f]);return c}function k(a){for(var c= a.length,e=new Uint8Array(c/2),f=0,k=0;f<c;f+=2,k++)e[k]=parseInt(a.substr(f,2),16)&255;return e}function f(a,c){c||(c="");for(var e="",f=0;f<a.byteLength;f++)e+=(a[f]>>>4).toString(16),e+=(a[f]&15).toString(16),c.length&&f<a.byteLength-1&&(e+=c);return e}function c(){for(var a=arguments.length,c=-1,e=0,f;++c<a;)f=arguments[c],e+="number"===typeof f?f:f.length;e=new Uint8Array(e);var k=0;for(c=-1;++c<a;)f=arguments[c],"number"===typeof f?k+=f:0<f.length&&(e.set(f,k),k+=f.length);return e}function e(a, c){return(a[0+c]<<8)+(a[1+c]<<0)}function m(a,c){return 65536*a[0+c]+256*a[1+c]+a[2+c]}function n(a,c){return 16777216*a[0+c]+65536*a[1+c]+256*a[2+c]+a[3+c]}function q(a,c){return 4294967296*(16777216*a[0+c]+65536*a[1+c]+256*a[2+c]+a[3+c])+16777216*a[4+c]+65536*a[5+c]+256*a[6+c]+a[7+c]}function r(a){return new Uint8Array([a>>>8&255,a&255])}function p(a){return new Uint8Array([a>>>24&255,a>>>16&255,a>>>8&255,a&255])}function t(a){var c=a%4294967296;a=(a-c)/4294967296;return new Uint8Array([a>>>24& 255,a>>>16&255,a>>>8&255,a&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255])}function u(a,c){return(a[0+c]<<0)+(a[1+c]<<8)}function w(a,c){return a[0+c]+256*a[1+c]+65536*a[2+c]+16777216*a[3+c]}function x(a){v.a.equal(a.length,16,"UUID length should be 16");var c=h(a);a=c[0];var e=c[1],k=c[2],b=c[3],g=c[4],m=c[5],n=c[6],l=c[7],d=c.subarray(8,10);c=c.subarray(10,16);var q=new Uint8Array(16);q[0]=b;q[1]=k;q[2]=e;q[3]=a;q[4]=m;q[5]=g;q[6]=l;q[7]=n;q.set(d,8);q.set(c,10);return f(q)}a.d(d,"b",function(){return h}); a.d(d,"a",function(){return l});a.d(d,"l",function(){return g});a.d(d,"k",function(){return k});a.d(d,"p",function(){return f});a.d(d,"i",function(){return c});a.d(d,"g",function(){return e});a.d(d,"h",function(){return m});a.d(d,"e",function(){return n});a.d(d,"f",function(){return q});a.d(d,"d",function(){return u});a.d(d,"c",function(){return w});a.d(d,"n",function(){return r});a.d(d,"j",function(){return p});a.d(d,"o",function(){return t});a.d(d,"m",function(){return x});var v=a(2)},function(b, d,a){var h=this&&this.__extends||function(a,b){function k(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(k.prototype=b.prototype,new k)};b=function(a){function b(){a.apply(this,arguments)}h(b,a);b.prototype.notifyNext=function(a,f,c,e,b){this.destination.next(f)};b.prototype.notifyError=function(a,f){this.destination.error(a)};b.prototype.notifyComplete=function(a){this.destination.complete()};return b}(a(3).Subscriber);d.OuterSubscriber= b},function(b,d,a){var h=this&&this.__extends||function(a,c){function e(){this.constructor=a}for(var f in c)c.hasOwnProperty(f)&&(a[f]=c[f]);a.prototype=null===c?Object.create(c):(e.prototype=c.prototype,new e)};b=a(0);var l=a(44),g=a(25),k=a(20);a=function(a){function c(c,f){a.call(this);this.array=c;this.scheduler=f;f||1!==c.length||(this._isScalar=!0,this.value=c[0])}h(c,a);c.create=function(a,f){return new c(a,f)};c.of=function(){for(var a=[],f=0;f<arguments.length;f++)a[f-0]=arguments[f];f=a[a.length- 1];k.isScheduler(f)?a.pop():f=null;var b=a.length;return 1<b?new c(a,f):1===b?new l.ScalarObservable(a[0],f):new g.EmptyObservable(f)};c.dispatch=function(a){var c=a.array,e=a.index,f=a.subscriber;e>=a.count?f.complete():(f.next(c[e]),f.closed||(a.index=e+1,this.schedule(a)))};c.prototype._subscribe=function(a){var e=this.array,f=e.length,k=this.scheduler;if(k)return k.schedule(c.dispatch,0,{array:e,index:0,count:f,subscriber:a});for(k=0;k<f&&!a.closed;k++)a.next(e[k]);a.complete()};return c}(b.Observable); d.ArrayObservable=a},function(b,d,a){var h=a(12),l=a(81),g=a(85),k=a(84),f=a(0),c=a(47),e=a(172),m=a(48);d.subscribeToResult=function(a,b,d,p){var n=new e.InnerSubscriber(a,d,p);if(n.closed)return null;if(b instanceof f.Observable)if(b._isScalar)n.next(b.value),n.complete();else return b.subscribe(n);else if(l.isArrayLike(b)){a=0;for(d=b.length;a<d&&!n.closed;a++)n.next(b[a]);n.closed||n.complete()}else{if(g.isPromise(b))return b.then(function(a){n.closed||(n.next(a),n.complete())},function(a){return n.error(a)}).then(null, function(a){h.root.setTimeout(function(){throw a;})}),n;if(b&&"function"===typeof b[c.iterator]){b=b[c.iterator]();do{a=b.next();if(a.done){n.complete();break}n.next(a.value);if(n.closed)break}while(1)}else if(b&&"function"===typeof b[m.observable])if(b=b[m.observable](),"function"!==typeof b.subscribe)n.error(new TypeError("Provided object does not correctly implement Symbol.observable"));else return b.subscribe(new e.InnerSubscriber(a,d,p));else b=k.isObject(b)?"an invalid object":"'"+b+"'",n.error(new TypeError("You provided "+ b+" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable."))}return null}},function(b,d,a){function h(a,c){return c.filter(function(c){var e=document.createElement(a.tagName);c="on"+c;c in e?e=!0:(e.setAttribute(c,"return;"),e="function"==typeof e[c]);return e})[0]}function l(a,e){return a.reduce(function(a,f){return a.concat((e||c.g).map(function(a){return a+f}))},[])}function g(e,b){var g=void 0;e=l(e,b);return function(b){return b instanceof c.h?("undefined"== typeof g&&(g=h(b,e)||null),g?k.Observable.fromEvent(b,g):k.Observable.never()):a.i(f.a)(b,e)}}a.d(d,"b",function(){return q});a.d(d,"c",function(){return r});a.d(d,"f",function(){return p});a.d(d,"a",function(){return t});a.d(d,"e",function(){return u});a.d(d,"d",function(){return w});a.d(d,"i",function(){return x});a.d(d,"g",function(){return v});a.d(d,"h",function(){return y});a.d(d,"j",function(){return z});var k=a(0);a.n(k);b=a(4);a(1);var f=a(31),c=a(34);b=b.a.INACTIVITY_DELAY;var e=window.devicePixelRatio|| 1;d=function(){var c=void 0;null!=document.hidden?c="":null!=document.mozHidden?c="moz":null!=document.msHidden?c="ms":null!=document.webkitHidden&&(c="webkit");var e=c?c+"Hidden":"hidden";c+="visibilitychange";return a.i(f.a)(document,c).map(function(){return document[e]})};var m=d().filter(function(a){return!1===a}),n=d().debounceTime(b).filter(function(a){return!0===a}),q=function(){return k.Observable.merge(m,n).startWith(!1)},r=function(c){return k.Observable.merge(k.Observable.interval(2E4), a.i(f.a)(window,"resize").debounceTime(500)).startWith("init").map(function(){return c.clientWidth*e}).distinctUntilChanged()},p=g(["loadedmetadata"]),t=g(["fullscreenchange","FullscreenChange"],c.g.concat("MS")),u=g(["sourceopen","webkitsourceopen"]),w=g(["encrypted","needkey"]),x=g(["keymessage","message"]),v=g(["keyadded","ready"]),y=g(["keyerror","error"]),z=g(["keystatuseschange"])},function(b,d,a){a.d(d,"a",function(){return h});a.d(d,"c",function(){return l});a.d(d,"b",function(){return g}); b=a(165);var h=a.i(b.a)(["NETWORK_ERROR","MEDIA_ERROR","ENCRYPTED_MEDIA_ERROR","INDEX_ERROR","OTHER_ERROR"]),l=a.i(b.a)(["TIMEOUT","ERROR_EVENT","ERROR_HTTP_CODE","PARSE_ERROR"]),g=a.i(b.a)("PIPELINE_RESOLVE_ERROR PIPELINE_LOAD_ERROR PIPELINE_PARSING_ERROR MANIFEST_PARSE_ERROR MANIFEST_INCOMPATIBLE_CODECS_ERROR MEDIA_IS_ENCRYPTED_ERROR KEY_ERROR KEY_STATUS_CHANGE_ERROR KEY_UPDATE_ERROR KEY_LOAD_ERROR KEY_LOAD_TIMEOUT KEY_GENERATE_REQUEST_ERROR INCOMPATIBLE_KEYSYSTEMS LICENSE_SERVER_CERTIFICATE_ERROR BUFFER_APPEND_ERROR BUFFER_FULL_ERROR BUFFER_TYPE_UNKNOWN MEDIA_ERR_ABORTED MEDIA_ERR_NETWORK MEDIA_ERR_DECODE MEDIA_ERR_SRC_NOT_SUPPORTED MEDIA_SOURCE_NOT_SUPPORTED MEDIA_KEYS_NOT_SUPPORTED OUT_OF_INDEX_ERROR UNKNOWN_INDEX".split(" "))}, function(b,d,a){d.a=function(a,b,g){if("function"===typeof Array.prototype.includes)return a.includes(b,g);var k=a.length>>>0;if(0===k)return!1;g|=0;for(g=Math.max(0<=g?g:k-Math.abs(g),0);g<k;){var f=a[g],c=b;if(f===c||"number"===typeof f&&"number"===typeof c&&isNaN(f)&&isNaN(c))return!0;g++}return!1}},function(b,d,a){d.isScheduler=function(a){return a&&"function"===typeof a.schedule}},function(b,d,a){b.exports=function(a,b,g){if("function"===typeof Array.prototype.find)return a.find(b,g);g=g||this; var k=a.length,f;if("function"!==typeof b)throw new TypeError(b+" is not a function");for(f=0;f<k;f++)if(b.call(g,a[f],f,a))return a[f]}},function(b,d,a){d.a=function(a,b,g){return a+"("+b+")"+(g?": "+g.message:"")}},function(b,d,a){a.d(d,"d",function(){return l});a.d(d,"e",function(){return g});a.d(d,"a",function(){return k});a.d(d,"b",function(){return f});a.d(d,"c",function(){return c});a(2);var h=a(27),l=function(a,c,f){var e=a.presentationTimeOffset||0;a=a.timescale||1;return{up:c*a-e,to:(c+ f)*a-e}},g=function(a){var c=a.ts,e=a.d;a=a.r;return-1===e?c:c+(a+1)*e},k=function(a,c){var e=c.initialization;e=void 0===e?{}:e;return new h.a({id:""+a+"_init",init:!0,range:e.range||null,indexRange:c.indexRange||null,media:e.media,timescale:c.timescale})},f=function(a,c){a.timescale!==c&&(a.timescale=c);return a},c=function(a,c){return c/a.timescale}},function(b,d,a){function h(){for(var a=arguments.length,c=Array(a),e=0;e<a;e++)c[e]=arguments[e];a=c.length;if(0===a)return"";e="";for(var b=0;b< a;b++){var n=c[b];"string"===typeof n&&""!==n&&(g.test(n)?e=n:("/"===n[0]&&(n=n.substr(1)),"/"===e[e.length-1]&&(e=e.substr(0,e.length-1)),e=e+"/"+n))}a=e;if(k.test(a)){c=[];a=a.split("/");e=0;for(b=a.length;e<b;e++)".."==a[e]?c.pop():"."!=a[e]&&c.push(a[e]);c=c.join("/")}else c=a;return c}function l(a){var c=a.lastIndexOf("/");return 0<=c?a.substring(0,c+1):a}a.d(d,"b",function(){return h});a.d(d,"a",function(){return l});var g=/^(?:[a-z]+:)?\/\//i,k=/\/\.{1,2}\//},function(b,d,a){var h=this&&this.__extends|| function(a,b){function k(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(k.prototype=b.prototype,new k)};b=function(a){function b(b){a.call(this);this.scheduler=b}h(b,a);b.create=function(a){return new b(a)};b.dispatch=function(a){a.subscriber.complete()};b.prototype._subscribe=function(a){var f=this.scheduler;if(f)return f.schedule(b.dispatch,0,{subscriber:a});a.complete()};return b}(a(0).Observable);d.EmptyObservable=b},function(b,d,a){d.isArray= Array.isArray||function(a){return a&&"number"===typeof a.length}},function(b,d,a){d.a=function l(){var a=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};if(!(this instanceof l))throw new TypeError("Cannot call a class as a function");this.id=a.id;this.duration=a.duration;this.isInit=!!a.init;this.range=a.range;this.time=a.time;this.indexRange=a.indexRange;this.number=a.number;this.timescale=null==a.timescale?1:a.timescale;this.media=a.media}},function(b,d,a){function h(a,e){return new Date(1E3* (a+e.availabilityStartTime))}function l(a,e){var c=e.suggestedPresentationDelay,f=e.presentationLiveGap,b=e.timeShiftBufferDepth;"number"!=typeof a&&(a=a.getTime());var k=Date.now();return Math.max(Math.min(a,k-1E3*(f+c)),k-1E3*b)/1E3-e.availabilityStartTime}function g(a){return f(a)[0]}function k(a){if(!a.isLive)return a.getDuration();var c=a.availabilityStartTime;a=a.presentationLiveGap;return Date.now()/1E3-c-a}function f(a){if(!a.isLive)return[0,a.getDuration()];var c=a.availabilityStartTime, f=a.presentationLiveGap;a=a.timeShiftBufferDepth;c=Date.now()/1E3-c-f;return[Math.min(c,c-a+5),c]}a.d(d,"a",function(){return h});a.d(d,"b",function(){return l});a.d(d,"c",function(){return g});a.d(d,"d",function(){return k});a.d(d,"e",function(){return f})},function(b,d,a){function h(){this.__listeners={}}var l=a(1),g=a(2);h.prototype.addEventListener=function(b,f){a.i(g.a)("function"==typeof f,"eventemitter: second argument should be a function");this.__listeners[b]||(this.__listeners[b]=[]);this.__listeners[b].push(f)}; h.prototype.removeEventListener=function(a,f){if(0===arguments.length)this.__listeners={};else if(this.__listeners.hasOwnProperty(a))if(1===arguments.length)delete this.__listeners[a];else{var c=this.__listeners[a],e=c.indexOf(f);~e&&c.splice(e,1);c.length||delete this.__listeners[a]}};h.prototype.trigger=function(a,f){this.__listeners.hasOwnProperty(a)&&this.__listeners[a].slice().forEach(function(a){try{a(f)}catch(e){l.a.error(e,e.stack)}})};h.prototype.on=h.prototype.addEventListener;h.prototype.off= h.prototype.removeEventListener;d.a=h},function(b,d,a){function h(a){if(null!=a){if("string"===typeof a){var c=a;a=!1}else c=a.language,a=!!a.closedCaption;return{language:c,closedCaption:a,normalized:g(c)}}return a}function l(a){if(null!=a){if("string"===typeof a){var c=a;a=!1}else c=a.language,a=!!a.audioDescription;return{language:c,audioDescription:a,normalized:g(c)}}return a}function g(a){if(null==a||""===a)return"";a=(""+a).toLowerCase().split("-");var c=a[0],b=void 0;2===c.length?b=k.a[c]: 3===c.length&&(b=f.a[c]);(c=b||c)&&(a[0]=c);return a.join("-")}a.d(d,"a",function(){return g});a.d(d,"b",function(){return l});a.d(d,"c",function(){return h});var k=a(163),f=a(164)},function(b,d,a){d.a=function(a,b){return Array.isArray(b)?h.Observable.merge.apply(null,b.map(function(b){return h.Observable.fromEvent(a,b)})):h.Observable.fromEvent(a,b)};var h=a(0);a.n(h)},function(b,d,a){b=a(78);a=a(79);d.async=new a.AsyncScheduler(b.AsyncAction)},function(b,d,a){d.errorObject={e:{}}},function(b,d, a){a.d(d,"g",function(){return h});a.d(d,"h",function(){return l});a.d(d,"e",function(){return g});a.d(d,"a",function(){return k});a.d(d,"f",function(){return f});a.d(d,"b",function(){return c});a.d(d,"d",function(){return e});a.d(d,"c",function(){return m});b=window;var h=["","webkit","moz","ms"],l=b.HTMLElement,g=b.HTMLVideoElement,k=b.MediaSource||b.MozMediaSource||b.WebKitMediaSource||b.MSMediaSource,f=b.MediaKeys||b.MozMediaKeys||b.WebKitMediaKeys||b.MSMediaKeys;f||(b=function(){throw new MediaError("MEDIA_KEYS_NOT_SUPPORTED", null,!0);},f={create:b,isTypeSupported:b});var c="Microsoft Internet Explorer"==navigator.appName||"Netscape"==navigator.appName&&/(Trident|Edge)\//.test(navigator.userAgent),e=-1!==navigator.userAgent.toLowerCase().indexOf("firefox"),m={HAVE_NOTHING:0,HAVE_METADATA:1,HAVE_CURRENT_DATA:2,HAVE_FUTURE_DATA:3,HAVE_ENOUGH_DATA:4}},function(b,d,a){a.d(d,"a",function(){return h});var h={STOPPED:"STOPPED",LOADED:"LOADED",LOADING:"LOADING",PLAYING:"PLAYING",PAUSED:"PAUSED",ENDED:"ENDED",BUFFERING:"BUFFERING", SEEKING:"SEEKING"}},function(b,d,a){a.d(d,"a",function(){return h});a.d(d,"b",function(){return l});b=a(113);var h=new b.a({load:function(){return[]},save:function(){}}),l=new b.b},function(b,d,a){Object.defineProperty(d,"__esModule",{value:!0});var h=a(27),l=a(23),g=function(a,f){a=a.timeline;for(var c=0,e=a.length;c<e;){var b=c+e>>>1;a[b].ts<f?c=b+1:e=b}return 0<c?c-1:c};d["default"]={getInitSegment:l.a,setTimescale:l.b,scale:l.c,getSegments:function(b,f,c,e){e=a.i(l.d)(f,c,e);c=e.up;e=e.to;var k= f.timeline,n=f.timescale,d=f.media,r=[],p=k.length;f=g(f,c)-1;var t=k.length&&k[0].d||0;a:for(;!(++f>=p);){var u=k[f],w=u.d,x=u.ts,v=u.range;t=Math.max(t,w);if(0>w){x+t<e&&r.push(new h.a({id:""+b+"_"+x,time:x,init:!1,range:v,duration:void 0,indexRange:null,timescale:n,media:d}));break}var y=k[f+1],z=u.r||0;0>z&&(z=Math.ceil(((y?y.t:Infinity)-u.ts)/u.d)-1);u=z;y=c-x;y=0<y?Math.floor(y/w):0;for(;(z=x+y*w)<e;)if(y++<=u)r.push(new h.a({id:""+b+"_"+z,time:z,init:!1,range:v,duration:w,indexRange:null,timescale:n, media:d}));else continue a;break}return r},shouldRefresh:function(b,f,c,e){c=b.timeline;f=b.timescale;b=b.presentationTimeOffset;c=c[c.length-1];if(!c)return!1;0>c.d&&(c={ts:c.ts,d:0,r:c.r});return!(e*f-(void 0===b?0:b)<=a.i(l.e)(c))},getFirstPosition:function(a){if(a.timeline.length)return a.timeline[0].ts/a.timescale},getLastPosition:function(b){if(b.timeline.length){var f=b.timeline[b.timeline.length-1];return a.i(l.e)(f)/b.timescale}},checkDiscontinuity:function(b,f){var c=b.timeline,e=b.timescale; e=void 0===e?1:e;f*=e;if(0>=f)return-1;var k=g(b,f);if(0>k||k>=c.length-1)return-1;var n=c[k];if(-1===n.d)return-1;b=n.ts;n=a.i(l.e)(n);c=c[k+1];return n!==c.ts&&f>=b&&f<=n&&n-f<e?c.ts/e:-1},_addSegmentInfos:function(b,f,c){var e=b.timeline,k=b.timescale,g=e.length,d=e[g-1];f=f.timescale===k?{time:f.time,duration:f.duration}:{time:f.time/f.timescale*k,duration:f.duration/f.timescale*k};var h=void 0;c&&(h=c.timescale===k?c.time:c.time/c.timescale*k);if(null!=h&&f.time===h){c=f.time+f.duration;k=c- (d.ts+d.d*d.r);if(0>=k)return!1;-1===d.d&&((g=e[g-2])&&g.d===k?(g.r++,e.pop()):d.d=k);b.timeline.push({d:-1,ts:c,r:0});return!0}return f.time>=a.i(l.e)(d)?(d.d===f.duration?d.r++:b.timeline.push({d:f.duration,ts:f.time,r:0}),!0):!1}}},function(b,d,a){function h(c,e){for(var f=c.length,b=0,k,g=void 0;b+8<f&&(g=a.i(r.e)(c,b),k=a.i(r.e)(c,b+4),a.i(q.a)(0<g,"out of range size"),k!==e);)b+=g;if(b>=f)return-1;a.i(q.a)(b+g<=f,"atom out of range");return b}function l(c,e){var f=h(c,1936286840);if(-1==f)return null; var b=a.i(r.e)(c,f);f=f+4+4;var k=c[f];f+=8;var g=a.i(r.e)(c,f);f+=4;if(0===k)k=a.i(r.e)(c,f),f+=4,e+=a.i(r.e)(c,f)+b,f+=4;else if(1===k)k=a.i(r.f)(c,f),f+=8,e+=a.i(r.f)(c,f)+b,f+=8;else return null;b=[];f+=2;var m=a.i(r.g)(c,f);for(f+=2;0<=--m;){var n=a.i(r.e)(c,f);f+=4;var d=n&2147483647;if(1==(n&2147483648)>>>31)throw Error("not implemented");n=a.i(r.e)(c,f);f+=4;f+=4;b.push({time:k,duration:n,count:0,timescale:g,range:[e,e+d-1]});k+=n;e+=d}return b}function g(e){e=c(e,1836019558);if(!e)return-1; e=c(e,1953653094);if(!e)return-1;var f=h(e,1952867444);if(-1==f)return-1;f=f+4+4;var b=e[f];f+=4;return 1<b?-1:b?a.i(r.f)(e,f):a.i(r.e)(e,f)}function k(e){e=c(e,1836019558);if(!e)return-1;e=c(e,1953653094);if(!e)return-1;var f=h(e,1953658222);if(-1==f)return-1;f=f+4+4;var b=e[f];f+=1;if(1<b)return-1;var k=a.i(r.h)(e,f);f+=3;b=k&256;var g=0;if(!b)return f=h(e,1952868452),-1==f?g=-1:(f=f+4+4+1,b=a.i(r.h)(e,f),b&8?(f+=4,b&1&&(f+=8),b&2&&(f+=4),g=a.i(r.e)(e,f)):g=-1),0<=g?g:-1;var m=k&1,n=k&4,d=k&512, l=k&1024;k&=2048;var q=a.i(r.e)(e,f);f+=4;m&&(f+=4);n&&(f+=4);m=q;for(n=0;m--;)b?(n+=a.i(r.e)(e,f),f+=4):n+=g,d&&(f+=4),l&&(f+=4),k&&(f+=4);return n}function f(e){e=c(e,1836019574);if(!e)return-1;e=c(e,1953653099);if(-1==f)return-1;e=c(e,1835297121);if(-1==f)return-1;var f=h(e,1835296868);if(f/-1)return-1;f=f+4+4;var b=e[f];f+=4;return 1===b?(f+=16,a.i(r.e)(e,f)):0==b?(f+=8,a.i(r.e)(e,f)):-1}function c(c,e){for(var f=c.length,b=0,k,g=void 0;b+8<f&&(g=a.i(r.e)(c,b),k=a.i(r.e)(c,b+4),a.i(q.a)(0<g,"out of range size"), k!==e);)b+=g;return b<f?c.subarray(b+8,b+g):null}function e(a){return c(a,1835295092)}function m(c){var e=c.systemId;c=c.privateData;e=e.replace(/-/g,"");a.i(q.a)(32===e.length);e=a.i(r.i)(4,a.i(r.k)(e),a.i(r.j)(c.length),c);c=e.length+8;return a.i(r.i)(a.i(r.j)(c),a.i(r.b)("pssh"),e)}function n(c,e){if(!e||!e.length)return c;var f=h(c,1836019574);if(-1==f)return c;for(var b=a.i(r.e)(c,f),k=[c.subarray(f,f+b)],g=0;g<e.length;g++)k.push(m(e[g]));k=r.i.apply(null,k);k.set(a.i(r.j)(k.length),0);return a.i(r.i)(c.subarray(0, f),k,c.subarray(f+b))}a.d(d,"b",function(){return f});a.d(d,"e",function(){return g});a.d(d,"f",function(){return k});a.d(d,"a",function(){return l});a.d(d,"d",function(){return e});a.d(d,"c",function(){return n});var q=a(2),r=a(13)},function(b,d,a){function h(c,e){var f=e.length+8,b=a.i(n.i);f=a.i(n.j)(f);if(r[c])c=r[c];else{var k=a.i(n.b)(c);c=r[c]=k}return b(f,c,e)}function l(c,e,f,b,k){for(var g=c.length,m=0,d;m<g;){d=a.i(n.e)(c,m);if(1970628964===a.i(n.e)(c,m+4)&&a.i(n.e)(c,m+8)===e&&a.i(n.e)(c, m+12)===f&&a.i(n.e)(c,m+16)===b&&a.i(n.e)(c,m+20)===k)return c.subarray(m+24,m+d);m+=d}}function g(c,f){for(var b=c.length,k=0,g,m=void 0;k+8<b&&(m=a.i(n.e)(c,k),g=a.i(n.e)(c,k+4),a.i(e.a)(0<m,"smooth: out of range size"),g!==f);)k+=m;return k<b?c.subarray(k+8,k+m):null}function k(a,c,e,f){var b=[a,c,e];f.forEach(function(a){a=p.pssh(a.systemId,a.privateData,a.keyIds);b.push(a)});return b}function f(c,e,f,b){var k=c.length,g=e.length;f=f.length;c=c.subarray(f,k);k=new Uint8Array(g+(k-f));k.set(e, 0);k.set(c,g);e=e.length+8;k.set(a.i(n.j)(e),b+16);return k}function c(c,e,f,b,g,m,d){f=p.mult("stbl",[f,h("stts",new Uint8Array(8)),h("stsc",new Uint8Array(8)),h("stsz",new Uint8Array(12)),h("stco",new Uint8Array(8))]);var l=h("url ",new Uint8Array([0,0,0,1]));l=p.dref(l);l=p.mult("dinf",[l]);b=p.mult("minf",[b,l,f]);e=p.hdlr(e);f=p.mdhd(c);e=p.mult("mdia",[f,e,b]);g=p.tkhd(g,m,1);g=p.mult("trak",[g,e]);m=p.trex(1);m=p.mult("mvex",[m]);c=p.mvhd(c,1);d=p.mult("moov",k(c,m,g,d));c=p.ftyp("isom",["isom", "iso2","iso6","avc1","dash"]);return a.i(n.i)(c,d)}var e=a(2),m=a(7),n=a(13),q=[96E3,88200,64E3,48E3,44100,32E3,24E3,22050,16E3,12E3,11025,8E3,7350],r={},p={mult:function(a,c){return h(a,n.i.apply(null,c))},avc1encv:function(c,e,f,b,k,g,m,d,l,q){return h(c,a.i(n.i)(6,a.i(n.n)(e),16,a.i(n.n)(f),a.i(n.n)(b),a.i(n.n)(k),2,a.i(n.n)(g),6,[0,1,m.length],a.i(n.b)(m),31-m.length,a.i(n.n)(d),[255,255],l,"encv"===c?q:[]))},avcc:function(c,e,f){f=2===f?1:4===f?3:0;var b=c[1],k=c[2],g=c[3];return h("avcC",a.i(n.i)([1, b,k,g,252|f,225],a.i(n.n)(c.length),c,[1],a.i(n.n)(e.length),e))},dref:function(c){return h("dref",a.i(n.i)(7,[1],c))},esds:function(c,e){return h("esds",a.i(n.i)(4,[3,25],a.i(n.n)(c),[0,4,17,64,21],11,[5,2],a.i(n.k)(e),[6,1,2]))},frma:function(c){return h("frma",a.i(n.b)(c))},free:function(a){return h("free",new Uint8Array(a-8))},ftyp:function(c,e){return h("ftyp",n.i.apply(null,[a.i(n.b)(c),[0,0,0,1]].concat(e.map(n.b))))},hdlr:function(c){switch(c){case "video":c="vide";var e="VideoHandler";break; case "audio":c="soun";e="SoundHandler";break;default:c="hint",e=""}return h("hdlr",a.i(n.i)(8,a.i(n.b)(c),12,a.i(n.b)(e),1))},mdhd:function(c){return h("mdhd",a.i(n.i)(12,a.i(n.j)(c),8))},moof:function(a,c){return p.mult("moof",[a,c])},mp4aenca:function(c,e,f,b,k,g,m,d){return h(c,a.i(n.i)(6,a.i(n.n)(e),8,a.i(n.n)(f),a.i(n.n)(b),2,a.i(n.n)(k),a.i(n.n)(g),2,m,"enca"===c?d:[]))},mvhd:function(c,e){return h("mvhd",a.i(n.i)(12,a.i(n.j)(c),4,[0,1],2,[1,0],10,[0,1],14,[0,1],14,[64,0,0,0],26,a.i(n.n)(e+ 1)))},pssh:function(c){var f=1<arguments.length&&void 0!==arguments[1]?arguments[1]:[],b=2<arguments.length&&void 0!==arguments[2]?arguments[2]:[];c=c.replace(/-/g,"");a.i(e.a)(32===c.length,"wrong system id length");var k=b.length;if(0<k){var g=1;b=n.i.apply(null,[a.i(n.j)(k)].concat(b))}else g=0,b=[];return h("pssh",a.i(n.i)([g,0,0,0],a.i(n.k)(c),b,a.i(n.j)(f.length),f))},saio:function(c,e,f,b){return h("saio",a.i(n.i)(4,[0,0,0,1],a.i(n.j)(c.length+e.length+f.length+b.length+8+8+8+8)))},saiz:function(c){if(0=== c.length)return h("saiz",new Uint8Array);var e=a.i(n.e)(c,0),f=a.i(n.e)(c,4),b=new Uint8Array(9+f);b.set(a.i(n.j)(f),5);f=9;for(var k=8,g,m;k<c.length;)k+=8,2===(e&2)?(m=2,g=a.i(n.g)(c,k),k+=2+6*g):m=g=0,b[f]=6*g+8+m,f++;return h("saiz",b)},schm:function(c,e){return h("schm",a.i(n.i)(4,a.i(n.b)(c),a.i(n.j)(e)))},senc:function(a){return h("senc",a)},smhd:function(){return h("smhd",new Uint8Array(8))},stsd:function(a){return h("stsd",n.i.apply(null,[7,[a.length]].concat(a)))},tkhd:function(c,e,f){return h("tkhd", a.i(n.i)(a.i(n.j)(7),8,a.i(n.j)(f),20,[1,0,0,0],[0,1,0,0],12,[0,1,0,0],12,[64,0,0,0],a.i(n.n)(c),2,a.i(n.n)(e),2))},trex:function(c){return h("trex",a.i(n.i)(4,a.i(n.j)(c),[0,0,0,1],12))},tfdt:function(c){return h("tfdt",a.i(n.i)([1,0,0,0],a.i(n.o)(c)))},tenc:function(c,e,f){return h("tenc",a.i(n.i)(6,[c,e],a.i(n.k)(f)))},traf:function(a,c,e,f,b){var k=[a,c,e];f&&k.push(p.senc(f),p.saiz(f),p.saio(b,a,c,e));return p.mult("traf",k)},trun:function(c){if(c[11]&1)return c;var e=new Uint8Array(c.length+ 4);e.set(a.i(n.j)(c.length+4),0);e.set(c.subarray(4,16),4);e[11]|=1;e.set([0,0,0,0],16);e.set(c.subarray(16,c.length),20);return e},vmhd:function(){var a=new Uint8Array(12);a[3]=1;return h("vmhd",a)}},t={traf:function(a){return(a=g(a,1836019558))?g(a,1953653094):null},senc:function(a){return l(a,2721664850,1520127764,2722393154,2086964724)},tfxd:function(a){return l(a,1830656773,1121273062,2162299933,2952222642)},tfrf:function(a){return l(a,3565190898,3392751253,2387879627,2655430559)},mdat:function(a){return g(a, 1835295092)}};d.a={getMdat:t.mdat,getTraf:t.traf,parseTfrf:function(c){c=t.tfrf(c);if(!c)return[];for(var e=[],f=c[0],b=c[4],k=0;k<b;k++){if(1==f){var g=a.i(n.f)(c,16*k+5);var m=a.i(n.f)(c,16*k+13)}else g=a.i(n.e)(c,8*k+5),m=a.i(n.e)(c,8*k+9);e.push({time:g,duration:m})}return e},parseTfxd:function(c){if(c=t.tfxd(c))return{duration:a.i(n.f)(c,12),time:a.i(n.f)(c,4)}},createVideoInitSegment:function(e,f,b,k,g,m,d,l,h){h||(h=[]);var q=d.split("00000001");d=q[1];q=q[2];d=a.i(n.k)(d);q=a.i(n.k)(q);m= p.avcc(d,q,m);h.length?(l=p.tenc(1,8,l),l=p.mult("schi",[l]),d=p.schm("cenc",65536),q=p.frma("avc1"),l=p.mult("sinf",[q,d,l]),k=p.avc1encv("encv",1,f,b,k,g,"AVC Coding",24,m,l)):k=p.avc1encv("avc1",1,f,b,k,g,"AVC Coding",24,m);k=p.stsd([k]);return c(e,"video",k,p.vmhd(),f,b,h)},createAudioInitSegment:function(e,f,b,k,g,m,d,l){l||(l=[]);m||(m=(32|q.indexOf(g)&31)<<4,m=(m|f&31)<<3,m=a.i(n.p)(a.i(n.n)(m)));m=p.esds(1,m);if(l.length){d=p.tenc(1,8,d);d=p.mult("schi",[d]);var h=p.schm("cenc",65536),r=p.frma("mp4a"); d=p.mult("sinf",[r,h,d]);f=p.mp4aenca("enca",1,f,b,k,g,m,d)}else f=p.mp4aenca("mp4a",1,f,b,k,g,m);f=p.stsd([f]);return c(e,"audio",f,p.smhd(),0,0,l)},patchSegment:function(c,e){var b=c.subarray(0,a.i(n.e)(c,0)),k=p.tfdt(e);e=k.length;var g=a.i(n.e)(b,8),d=a.i(n.e)(b,8+g),l=a.i(n.e)(b,8+g+8),h=a.i(n.e)(b,8+g+8+l),q=b.subarray(8,8+g),r=b.subarray(8+g+8,8+g+8+d-8);d=r.subarray(0,l);h=r.subarray(l,l+h);d.set([0,0,0,1],12);r=t.senc(r);h=p.trun(h);k=p.traf(d,k,h,r,q);q=p.moof(q,k);e=8+g+8+l+e;return m.r? f(c,q,b,e):8<=b.length-q.length?(b=b.length-q.length,c.set(q,0),c.set(p.free(b),q.length),b=q.length+8+b,c.set(a.i(n.j)(b),e+16),c):f(c,q,b,e)}}},function(b,d,a){var h=0;d.a=function(){var a=0;h<Number.MAX_VALUE&&(a=h+1);h=a;return""+a}},function(b,d,a){var h=a(0);a.n(h);var l=a(6);d.a=function(a){var b={url:"",headers:null,method:"GET",responseType:"json",timeout:3E4,body:void 0},f;for(f in b)a.hasOwnProperty(f)&&(b[f]=a[f]);return h.Observable.create(function(c){var e=b.url,f=b.headers,k=b.responseType, g=b.timeout,d=b.body,h=new XMLHttpRequest;h.open(b.method,e,!0);0<=g&&(h.timeout=g);h.responseType=k;"document"===h.responseType&&h.overrideMimeType("text/xml");if(f)for(var t in f)h.setRequestHeader(t,f[t]);var u=Date.now();h.onerror=function(){c.error(new l.h(h,e,l.j.ERROR_EVENT))};h.ontimeout=function(){c.error(new l.h(h,e,l.j.TIMEOUT))};a.ignoreProgressEvents||(h.onprogress=function(a){c.next({type:"progress",value:{url:e,sentTime:u,currentTime:Date.now(),loadedSize:a.loaded,totalSize:a.total}})}); h.onload=function(a){if(4===h.readyState)if(200<=h.status&&300>h.status){var f=Date.now();a=a.total;var b=h.status,k=h.responseType,g=h.responseURL||e,m=void 0;if("json"===k)if("string"!=typeof h.response)m=h.response;else try{m=JSON.parse(h.responseText)}catch(C){m=null}else m=h.response;null==m?c.error(new l.h(h,g,l.j.PARSE_ERROR)):(c.next({type:"response",value:{status:b,url:g,responseType:k,sentTime:u,receivedTime:f,size:a,responseData:m}}),c.complete())}else c.error(new l.h(h,e,l.j.ERROR_HTTP_CODE))}; void 0!==d?h.send(d):h.send();return function(){h&&4!==h.readyState&&h.abort()}})}},function(b,d,a){d.a=function(a,b){try{return a(b)}catch(k){return h.Observable.throw(k)}};var h=a(0);a.n(h)},function(b,d,a){var h=this&&this.__extends||function(a,b){function f(){this.constructor=a}for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);a.prototype=null===b?Object.create(b):(f.prototype=b.prototype,new f)};b=a(5);var l=a(50);a=function(a){function b(f){a.call(this);this._value=f}h(b,a);Object.defineProperty(b.prototype, "value",{get:function(){return this.getValue()},enumerable:!0,configurable:!0});b.prototype._subscribe=function(f){var c=a.prototype._subscribe.call(this,f);c&&!c.closed&&f.next(this._value);return c};b.prototype.getValue=function(){if(this.hasError)throw this.thrownError;if(this.closed)throw new l.ObjectUnsubscribedError;return this._value};b.prototype.next=function(f){a.prototype.next.call(this,this._value=f)};return b}(b.Subject);d.BehaviorSubject=a},function(b,d,a){var h=this&&this.__extends|| function(a,b){function k(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(k.prototype=b.prototype,new k)};b=function(a){function b(b,f){a.call(this);this.value=b;this.scheduler=f;this._isScalar=!0;f&&(this._isScalar=!1)}h(b,a);b.create=function(a,f){return new b(a,f)};b.dispatch=function(a){var f=a.value,c=a.subscriber;a.done?c.complete():(c.next(f),c.closed||(a.done=!0,this.schedule(a)))};b.prototype._subscribe=function(a){var f=this.value, c=this.scheduler;if(c)return c.schedule(b.dispatch,0,{done:!1,value:f,subscriber:a});a.next(f);a.closed||a.complete()};return b}(a(0).Observable);d.ScalarObservable=b},function(b,d,a){var h=this&&this.__extends||function(a,c){function e(){this.constructor=a}for(var f in c)c.hasOwnProperty(f)&&(a[f]=c[f]);a.prototype=null===c?Object.create(c):(e.prototype=c.prototype,new e)};b=a(14);var l=a(16);d.mergeAll=function(a){void 0===a&&(a=Number.POSITIVE_INFINITY);return this.lift(new g(a))};var g=function(){function a(a){this.concurrent= a}a.prototype.call=function(a,e){return e.subscribe(new k(a,this.concurrent))};return a}();d.MergeAllOperator=g;var k=function(a){function c(c,f){a.call(this,c);this.concurrent=f;this.hasCompleted=!1;this.buffer=[];this.active=0}h(c,a);c.prototype._next=function(a){this.active<this.concurrent?(this.active++,this.add(l.subscribeToResult(this,a))):this.buffer.push(a)};c.prototype._complete=function(){this.hasCompleted=!0;0===this.active&&0===this.buffer.length&&this.destination.complete()};c.prototype.notifyComplete= function(a){var c=this.buffer;this.remove(a);this.active--;0<c.length?this._next(c.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()};return c}(b.OuterSubscriber);d.MergeAllSubscriber=k},function(b,d,a){var h=a(214);d.multicast=function(a,b){var f="function"===typeof a?a:function(){return a};if("function"===typeof b)return this.lift(new l(f,b));b=Object.create(this,h.connectableObservableDescriptor);b.source=this;b.subjectFactory=f;return b};var l=function(){function a(a,f){this.subjectFactory= a;this.selector=f}a.prototype.call=function(a,f){var c=this.selector,e=this.subjectFactory();a=c(e).subscribe(a);a.add(f.subscribe(e));return a};return a}();d.MulticastOperator=l},function(b,d,a){function h(a){var b=a.Symbol;if("function"===typeof b)return b.iterator||(b.iterator=b("iterator polyfill")),b.iterator;if((b=a.Set)&&"function"===typeof(new b)["@@iterator"])return"@@iterator";if(a=a.Map){b=Object.getOwnPropertyNames(a.prototype);for(var k=0;k<b.length;++k){var f=b[k];if("entries"!==f&& "size"!==f&&a.prototype[f]===a.prototype.entries)return f}}return"@@iterator"}b=a(12);d.symbolIteratorPonyfill=h;d.iterator=h(b.root);d.$$iterator=d.iterator},function(b,d,a){function h(a){var b=a.Symbol;"function"===typeof b?b.observable?a=b.observable:(a=b("observable"),b.observable=a):a="@@observable";return a}b=a(12);d.getSymbolObservable=h;d.observable=h(b.root);d.$$observable=d.observable},function(b,d,a){b=a(12).root.Symbol;d.rxSubscriber="function"===typeof b&&"function"===typeof b.for?b.for("rxSubscriber"): "@@rxSubscriber";d.$$rxSubscriber=d.rxSubscriber},function(b,d,a){var h=this&&this.__extends||function(a,b){function k(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(k.prototype=b.prototype,new k)};b=function(a){function b(){var b=a.call(this,"object unsubscribed");this.name=b.name="ObjectUnsubscribedError";this.stack=b.stack;this.message=b.message}h(b,a);return b}(Error);d.ObjectUnsubscribedError=b},function(b,d,a){d.isFunction=function(a){return"function"=== typeof a}},function(b,d,a){function h(){try{return g.apply(this,arguments)}catch(k){return l.errorObject.e=k,l.errorObject}}var l=a(33),g;d.tryCatch=function(a){g=a;return h}},function(b,d,a){b.exports=function(a,b,g){if("function"===typeof Array.prototype.findIndex)return a.findIndex(b,g);if("function"!==typeof b)throw new TypeError("predicate must be a function");a=Object(a);var k=a.length;if(0===k)return-1;for(var f=0;f<k;f++)if(b.call(g,a[f],f,a))return f;return-1}},function(b,d,a){function h(a, c){function e(){var a=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};a.errorCode&&(a={systemCode:a.systemCode,code:a.errorCode.code});this.name="KeySessionError";this.mediaKeyError=a;this.message="MediaKeyError code:"+a.code+" and systemCode:"+a.systemCode}e.prototype=Error();return function(f,b){var k="function"==typeof c?c.call(this):this,g=m.g(k),d=m.h(k).map(function(a){throw new e(k.error||a);});try{return a.call(this,f,b),l.Observable.merge(g,d).take(1)}catch(H){return l.Observable.throw(H)}}} a.d(d,"b",function(){return r});a.d(d,"a",function(){return q});b=a(8);b=a.n(b);var l=a(0);a.n(l);var g=a(29),k=a(13),f=a(2),c=a(9),e=a(34),m=a(17),n=a(55),q=void 0;navigator.requestMediaKeySystemAccess&&(q=function(e,f){return a.i(c.a)(navigator.requestMediaKeySystemAccess(e,f))});var r=function(){};if(!q&&e.e.prototype.webkitGenerateKeyRequest){var p=function(a,c){var e=this;g.a.call(this);this.sessionId="";this._vid=a;this._key=c;this._con=l.Observable.merge(m.i(a),m.g(a),m.h(a)).subscribe(function(a){return e.trigger(a.type, a)})};p.prototype=b()({generateRequest:function(a,c){this._vid.webkitGenerateKeyRequest(this._key,c)},update:h(function(c,e){if(0<=this._key.indexOf("clearkey")){var f=JSON.parse(a.i(k.a)(c));c=a.i(k.b)(atob(f.keys[0].k));f=a.i(k.b)(atob(f.keys[0].kid));this._vid.webkitAddKey(this._key,c,f,e)}else this._vid.webkitAddKey(this._key,c,null,e);this.sessionId=e}),close:function(){this._con&&this._con.unsubscribe();this._vid=this._con=null}},g.a.prototype);r=function(a){this.ks_=a};r.prototype={_setVideo:function(a){this._vid= a},createSession:function(){return new p(this._vid,this.ks_)}};var t=function(a){var c=document.querySelector("video")||document.createElement("video");return c&&c.canPlayType?!!c.canPlayType("video/mp4",a):!1};q=function(a,c){if(!t(a))return l.Observable.throw();for(var e=0;e<c.length;e++){var f=c[e],b=f.videoCapabilities,k=f.audioCapabilities,g=f.initDataTypes,m=f.sessionTypes,d=f.distinctiveIdentifier;f=f.persistentState;var h=!0;if(h=(h=(h=(h=h&&(!g||!!g.filter(function(a){return"cenc"===a})[0]))&& (!m||m.filter(function(a){return"temporary"===a}).length===m.length))&&"required"!==d)&&"required"!==f)return c={videoCapabilities:b,audioCapabilities:k,initDataTypes:["cenc"],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]},l.Observable.of(new n.a(a,new r(a),c))}return l.Observable.throw()}}else if(e.f&&!q){var u=function(a){g.a.call(this);this.sessionId="";this._mk=a};u.prototype=b()({generateRequest:function(a,c){var e=this;this._ss=this._mk.memCreateSession("video/mp4", c);this._con=l.Observable.merge(m.i(this._ss),m.g(this._ss),m.h(this._ss)).subscribe(function(a){return e.trigger(a.type,a)})},update:h(function(c,e){a.i(f.a)(this._ss);this._ss.update(c,e);this.sessionId=e},function(){return this._ss}),close:function(){this._ss&&(this._ss.close(),this._ss=null);this._con&&(this._con.unsubscribe(),this._con=null)}},g.a.prototype);e.f.prototype.alwaysRenew=!0;e.f.prototype.memCreateSession=e.f.prototype.createSession;e.f.prototype.createSession=function(){return new u(this)}; q=function(a,c){if(!e.f.isTypeSupported(a))return l.Observable.throw();for(var f=0;f<c.length;f++){var b=c[f],k=b.videoCapabilities,g=b.audioCapabilities,m=b.initDataTypes;b=b.distinctiveIdentifier;var d=!0;if(d=(d=d&&(!m||!!m.filter(function(a){return"cenc"===a})[0]))&&"required"!==b)return c={videoCapabilities:k,audioCapabilities:g,initDataTypes:["cenc"],distinctiveIdentifier:"not-allowed",persistentState:"required",sessionTypes:["temporary","persistent-license"]},l.Observable.of(new n.a(a,new e.f(a), c))}return l.Observable.throw()}}},function(b,d,a){var h=a(0);a.n(h);var l=function(){function a(a,f){for(var c=0;c<f.length;c++){var e=f[c];e.enumerable=e.enumerable||!1;e.configurable=!0;"value"in e&&(e.writable=!0);Object.defineProperty(a,e.key,e)}}return function(b,f,c){f&&a(b.prototype,f);c&&a(b,c);return b}}();b=function(){function a(b,f,c){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this._keyType=b;this._mediaKeys=f;this._configuration=c}a.prototype.createMediaKeys= function(){return h.Observable.of(this._mediaKeys)};a.prototype.getConfiguration=function(){return this._configuration};l(a,[{key:"keySystem",get:function(){return this._keyType}}]);return a}();d.a=b},function(b,d,a){b=function(){function a(b){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this._alpha=Math.exp(Math.log(.5)/b);this._totalWeight=this._lastEstimate=0}a.prototype.addSample=function(a,b){var k=Math.pow(this._alpha,a);b=b*(1-k)+k*this._lastEstimate;isNaN(b)|| (this._lastEstimate=b,this._totalWeight+=a)};a.prototype.getEstimate=function(){return this._lastEstimate/(1-Math.pow(this._alpha,this._totalWeight))};return a}();d.a=b},function(b,d,a){function h(b,g,d){function l(e){return a.i(c.a)(e.createMediaKeys())}function h(c,e){var g=e.keySystem,h=e.keySystemAccess;g.persistentLicense&&m.a.setStorage(g.licenseStorage);f.a.info("eme: encrypted event",c);return l(h).mergeMap(function(e){var f=g.serverCertificate;f=f&&"function"===typeof e.setServerCertificate? a.i(n.a)(e,f,d):k.Observable.empty();var m=h.getConfiguration();return f.concat(k.Observable.merge(a.i(q.a)(e,m,b,g,t),a.i(r.a)(e,m,g,c.initDataType,new Uint8Array(c.initData),d)))})}return k.Observable.combineLatest(a.i(e.d)(b),a.i(p.a)(g,t)).take(1).mergeMap(function(a){return h(a[0],a[1])})}function l(){a.i(q.b)(t.$videoElement).subscribe(function(){});t.$mediaKeys=null;t.$keySystem=null;t.$videoElement=null;t.$mediaKeySystemConfiguration=null;m.b.dispose()}function g(){return a.i(p.b)(t)}a.d(d, "c",function(){return h});a.d(d,"b",function(){return g});a.d(d,"a",function(){return l});var k=a(0);a.n(k);var f=a(1),c=a(9);a(2);var e=a(17),m=a(36),n=a(110),q=a(115),r=a(111),p=a(109);a.d(d,"d",function(){return e.d});var t={$mediaKeys:null,$mediaKeySystemConfiguration:null,$keySystem:null,$videoElement:null}},function(b,d,a){b=function(){function a(){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this._entries=[]}a.prototype.find=function(a){for(var b=0;b<this._entries.length;b++)if(!0=== a(this._entries[b]))return this._entries[b];return null};return a}();d.a=b},function(b,d,a){d.a=function(a){if("number"==typeof a)return a;for(var b=0,g,k=0;k<a.length;k++)g=a[k],b=(b<<5)-b+g,b&=b;return b}},function(b,d,a){function h(a,c){if("function"!==typeof c&&null!==c)throw new TypeError("Super expression must either be null or a function, not "+typeof c);a.prototype=Object.create(c&&c.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});c&&(Object.setPrototypeOf?Object.setPrototypeOf(a, c):a.__proto__=c)}a.d(d,"a",function(){return c});b=a(29);var l=a(2),g=a(42),k=a(9),f=a(128),c=function(c){function e(a){if(!(this instanceof e))throw new TypeError("Cannot call a class as a function");var b=c.call(this);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");b=!b||"object"!==typeof b&&"function"!==typeof b?this:b;b.codec=a;b.updating=!1;b.readyState="opened";b.buffered=new f.a;return b}h(e,c);e.prototype.appendBuffer=function(a){var c=this; this._lock(function(){return c._append(a)})};e.prototype.remove=function(a,c){var e=this;this._lock(function(){return e._remove(a,c)})};e.prototype.abort=function(){this.remove(0,Infinity);this.updating=!1;this.readyState="closed";this._abort()};e.prototype._append=function(){};e.prototype._remove=function(){};e.prototype._abort=function(){};e.prototype._lock=function(c){var e=this;a.i(l.a)(!this.updating,"updating");this.updating=!0;this.trigger("updatestart");a.i(g.a)(function(){return a.i(k.a)(c())}).subscribe(function(){return setTimeout(function(){return e._unlock("update")}, 0)},function(a){return setTimeout(function(){return e._unlock("error",a)},0)})};e.prototype._unlock=function(a,c){this.updating=!1;this.trigger(a,c);this.trigger("updateend")};return e}(b.a)},function(b,d,a){function h(b){var k=0,f=b.length,c=a.i(l.a)(b.subarray(k,k+8));k+=8;var e=b[k];k+=1;var g=b[k];k+=1;var d=b[k];k+=1;var h=b[k];k+=1;e=[e,g,d,h].join(".");g=b[k]+a.i(l.c)(b,k+1);k+=4;d=a.i(l.c)(b,k);k+=4;h=a.i(l.a)(b.subarray(k,k+4));k+=4;var r=a.i(l.d)(b,k);k+=2;var p=a.i(l.d)(b,k);k+=2;var t= [b[k],b[k+1]].join(":"),u=1===b[k+2];k=64;var w=[],x=void 0,v=0;if(!g)throw Error("bif: no images to parse");for(;k<f;){var y=a.i(l.c)(b,k);k+=4;var z=a.i(l.c)(b,k);k+=4;if(x){var B=x.index,C=d,A=v;x=b.subarray(x.offset,z);w.push({index:B,duration:C,ts:A,data:x});v+=d}if(4294967295===y)break;x={index:y,offset:z}}return{fileFormat:c,version:e,imageCount:g,timescale:d,format:h,width:r,height:p,aspectRatio:t,isVod:u,thumbs:w}}a.d(d,"a",function(){return h});var l=a(13)},function(b,d,a){function h(a){return a.replace(f, "\n").replace(k,function(a,c){return String.fromCharCode(c)})}function l(f,b){var k=/<sync[ >]/ig,d=/<sync[ >]|<\/body>/ig,n=[],l=f.match(c)[1];d.exec(f);var q=/\.(\S+)\s*{([^}]*)}/gi;for(var x={},v;v=q.exec(l);){var y=v[1];v=v[2].match(/\s*lang:\s*(\S+);/i)[1];y&&v&&(x[v]=y)}l=x[b];for(a.i(g.a)(l,"sami: could not find lang "+b+" in CSS");;){b=k.exec(f);q=d.exec(f);if(!b&&!q)break;if(!b||!q||b.index>=q.index)throw Error("parse error");q=f.slice(b.index,q.index);b=q.match(m);if(!b)throw Error("parse error (sync time attribute)"); x=+b[1];if(isNaN(x))throw Error("parse error (sync time attribute NaN)");b=n;q=q.split("\n");x/=1E3;for(y=q.length;0<=--y;)if(v=q[y].match(e)){var z=v[2];l===v[1]&&("&nbsp;"===z?b[b.length-1].end=x:b.push({text:h(z),start:x}))}}return n}a.d(d,"a",function(){return l});var g=a(2),k=/&#([0-9]+);/g,f=/<br>/gi,c=/<style[^>]*>([\s\S]*?)<\/style[^>]*>/i,e=/\s*<p class=([^>]+)>(.*)/i,m=/<sync[^>]+?start="?([0-9]*)"?[^0-9]/i},function(b,d,a){function h(a,c,e){a="string"==typeof a?(new DOMParser).parseFromString(a, "text/xml"):a;if(!(a instanceof window.Document||a instanceof window.HTMLElement))throw Error("ttml needs a Document to parse");a=a.querySelector("tt");if(!a)throw Error("ttml could not find <tt> tag");a=l(a.querySelector("body"),0);for(c=0;c<a.length;c++){var f=a[c];f.start+=e;f.end+=e}return a}function l(a,c){var e=0;a=a.firstChild;for(var b=[],m;a;){if(1===a.nodeType)switch(a.tagName.toUpperCase()){case "P":m=a;var d=c,n=e;e=g(m.getAttribute("begin"),d);var h=g(m.getAttribute("end"),d),q=g(m.getAttribute("dur"), 0);if("number"==!("undefined"===typeof e||k(e))&&"number"==!("undefined"===typeof h||k(h))&&"number"==!("undefined"===typeof q||k(q)))throw Error("ttml unsupported timestamp format");0<q?(null==e&&(e=n||d),null==h&&(h=e+q)):null==h&&(h=g(m.getAttribute("duration"),0),h=0<=h?h+e:Number.MAX_VALUE);d=m.innerHTML;null==d&&(d=(new XMLSerializer).serializeToString(m),d=(new DOMParser).parseFromString(d,"text/html").body.firstChild.innerHTML);d=window.escape(d.replace(f,"\r\n"));d=d.replace(/%C3%26nbsp%3B/gm, "%C3%A0");m={id:m.getAttribute("xml:id")||m.getAttribute("id"),text:window.decodeURIComponent(d),start:e,end:h};e=m.end;b.push(m);break;case "DIV":m=g(a.getAttribute("begin"),0),null==m&&(m=c),b.push.apply(b,l(a,m))}a=a.nextSibling}return b}function g(a,f){if(!a)return null;var b;if(b=a.match(c)){f=b;a=f[3];b=f[4];var k=f[6];return 3600*parseInt(f[2]||0,10)+60*parseInt(a,10)+parseInt(b,10)+parseFloat("0."+k)}return(b=a.match(e))?(a=b,b=a[4],parseFloat(a[1])*m[b]+f):null}a.d(d,"a",function(){return h}); var k="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},f=/<br( )*\/* *>/gm,c=/^(([0-9]+):)?([0-9]+):([0-9]+)(\.([0-9]+))?$/,e=/(([0-9]+)(\.[0-9]+)?)(ms|h|m|s)/,m={h:3600,m:60,s:1,ms:.001}},function(b,d,a){function h(a){if("timeline"===a.indexType){var c=a.timeline[a.timeline.length-1],e=c.d;return(c.ts+(c.r+1)*e)/a.timescale-Math.min(Math.max(e/ a.timescale,5),10)}return Date.now()/1E3-5}function l(a){return a}function g(a){return"true"==a}function k(a){return"true"==a?!0:"false"==a?!1:parseInt(a)}function f(a){return new Date(Date.parse(a))}function c(c){if(!c)return 0;var e=x.exec(c);a.i(w.a)(e,c+" is not a valid ISO8601 duration");return 31536E3*parseFloat(e[2]||0)+2592E3*parseFloat(e[4]||0)+86400*parseFloat(e[6]||0)+3600*parseFloat(e[8]||0)+60*parseFloat(e[10]||0)+parseFloat(e[12]||0)}function e(a){var c=y.exec(a);if(!c)return-1;a=parseInt(c[1])|| 0;c=parseInt(c[2])||0;return 0<c?a/c:a}function m(a){return a}function n(a){return(a=v.exec(a))?[+a[1],+a[2]]:null}function q(a,c,e){for(a=a.firstElementChild;a;)e=c(e,a.nodeName,a),a=a.nextElementSibling;return e}function r(a){return a?"urn:tva:metadata:cs:AudioPurposeCS:2007"===a.schemeIdUri&&1===a.value:!1}function p(c){var e=c.mimeType;e=void 0===e?"":e;var f=e.split("/")[0];if(a.i(u.a)(z,f))return f;if("application/bif"===e)return"image";if("application/ttml+xml"===e)return"text";if("application/mp4"=== e)return(c=c.role)&&"urn:mpeg:dash:role:2011"===c.schemeIdUri&&"subtitle"===c.value?"text":"metadata";c=c.representations;c=void 0===c?[]:c;return c.length&&(c=c[0].mimeType.split("/")[0],a.i(u.a)(z,c))?c:"unknown"}function t(a){return a?"urn:tva:metadata:cs:AudioPurposeCS:2007"===a.schemeIdUri&&2===a.value:!1}a.d(d,"g",function(){return l});a.d(d,"h",function(){return e});a.d(d,"f",function(){return n});a.d(d,"i",function(){return g});a.d(d,"m",function(){return f});a.d(d,"j",function(){return c}); a.d(d,"l",function(){return k});a.d(d,"k",function(){return m});a.d(d,"a",function(){return q});a.d(d,"b",function(){return B});a.d(d,"d",function(){return t});a.d(d,"e",function(){return r});a.d(d,"c",function(){return p});var u=a(19),w=a(2),x=/^P(([\d.]*)Y)?(([\d.]*)M)?(([\d.]*)D)?T?(([\d.]*)H)?(([\d.]*)M)?(([\d.]*)S)?/,v=/([0-9]+)-([0-9]+)/,y=/([0-9]+)(\/([0-9]+))?/,z=["audio","video","text","image"],B=function(a){if(a){var c=a.representations||[],e=c.filter(function(a){return a&&a.index});if(!c.length)return h(a.index); var f=Math.min.apply(Math,e.map(function(a){return h(a.index)}));if(!isNaN(f)){if(c.length===e.length)return f;if(a.index)return a=h(a.index),Math.min(f,a)}}}},function(b,d,a){function h(a){var b=a.value;return"response"===a.type?{type:"response",value:{responseData:b.responseData,size:b.size,duration:b.receivedTime-b.sentTime,url:b.url}}:{type:"progress",value:{size:b.loadedSize,totalSize:b.totalSize,duration:b.currentTime-b.sentTime,url:b.url}}}var l=a(41);d.a=function(b){return a.i(l.a)(b).map(h)}}, function(b,d,a){function h(a){return function(c,e,b){c=b?parseInt(b,10):1;e=""+a;e=e.toString();c=e.length>=c?e:(Array(c+1).join("0")+e).slice(-c);return c}}function l(a,c,e){return-1===a.indexOf("$")?a:a.replace(/\$\$/g,"$").replace(/\$RepresentationID\$/g,e.id).replace(/\$Bandwidth(|\%0(\d+)d)\$/g,h(e.bitrate)).replace(/\$Number(|\%0(\d+)d)\$/g,h(c.number)).replace(/\$Time(|\%0(\d+)d)\$/g,h(c.time))}function g(a){return"application/mp4"===a.mimeType}function k(a){var c=a[0];return(a=a[1])&&Infinity!== a?"bytes="+ +c+"-"+ +a:"bytes="+ +c+"-"}a.d(d,"b",function(){return l});a.d(d,"a",function(){return g});a.d(d,"c",function(){return k})},function(b,d,a){function h(a){var b=a.value;return"response"===a.type?{type:"response",value:{responseData:b.responseData,size:b.size,duration:b.receivedTime-b.sentTime,url:b.url}}:{type:"progress",value:{size:b.loadedSize,totalSize:b.totalSize,duration:b.currentTime-b.sentTime,url:b.url}}}var l=a(41);d.a=function(b){return a.i(l.a)(b).map(h)}},function(b,d,a){function h(a){var c= a[0];return(a=a[1])&&Infinity!==a?"bytes="+ +c+"-"+ +a:"bytes="+ +c+"-"}function l(a){return a.responseData.getElementsByTagName("media")[0].getAttribute("src")}function g(a){return(a=a.match(m))&&a[1]||""}function k(a,c){return c?a.replace(m,"?token="+c):a.replace(m,"")}function f(a){var c=a.match(e);return c?a.replace(c[1],c[1]+"/manifest"):a}function c(a,c,e){return a.replace(/\{bitrate\}/g,c.bitrate).replace(/\{start time\}/g,e.time)}a.d(d,"f",function(){return h});a.d(d,"c",function(){return l}); a.d(d,"a",function(){return g});a.d(d,"b",function(){return k});a.d(d,"d",function(){return f});a.d(d,"e",function(){return c});var e=/\.(isml?)(\?token=\S+)?$/,m=/\?token=(\S+)/},function(b,d,a){function h(a){return a*(1+(2*Math.random()-1)*g)}function l(a){return h(a*Math.pow(2,(1<arguments.length&&void 0!==arguments[1]?arguments[1]:1)-1))}a.d(d,"b",function(){return h});a.d(d,"a",function(){return l});var g=.3},function(b,d,a){function h(a,e){var c=0;return function(){c&&clearTimeout(c);c=setTimeout(a, e)}}function l(c,e){var b=e.retryDelay,g=e.totalRetry,d=e.shouldRetry,l=e.resetDelay,p=e.errorSelector,t=e.onRetry,u=0,w=void 0;0<l&&(w=h(function(){return u=0},l));return c.catch(function(c,e){if(d&&!d(c)||u++>=g){if(p)throw p(c,u);throw c;}t&&t(c,u);c=a.i(f.a)(b,u);return k.Observable.timer(c).mergeMap(function(){w&&w();return e})})}function g(c,e){var b=e.retryDelay,g=e.totalRetry,d=e.shouldRetry,l=e.resetDelay,p=e.errorSelector,t=e.onRetry,u=0,w=void 0;0<l&&(w=h(function(){return u=0},l));return function v(){for(var e= arguments.length,m=Array(e),l=0;l<e;l++)m[l]=arguments[l];return c.apply(void 0,m).catch(function(c){if(d&&!d(c)||u++>=g){if(p)throw p(c,u);throw c;}t&&t(c,u);c=a.i(f.a)(b,u);return k.Observable.timer(c).mergeMap(function(){w&&w();return v.apply(void 0,m)})})}}a.d(d,"a",function(){return l});a.d(d,"b",function(){return g});var k=a(0);a.n(k);var f=a(69)},function(b,d,a){d.empty={closed:!0,next:function(a){},error:function(a){throw a;},complete:function(){}}},function(b,d,a){var h=this&&this.__extends|| function(a,b){function k(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(k.prototype=b.prototype,new k)};b=function(a){function b(b,f){a.call(this);this.subject=b;this.subscriber=f;this.closed=!1}h(b,a);b.prototype.unsubscribe=function(){if(!this.closed){this.closed=!0;var a=this.subject,b=a.observers;this.subject=null;!b||0===b.length||a.isStopped||a.closed||(a=b.indexOf(this.subscriber),-1!==a&&b.splice(a,1))}};return b}(a(11).Subscription); d.SubjectSubscription=b},function(b,d,a){function h(a){var c=a.value;a=a.subscriber;a.closed||(a.next(c),a.complete())}function l(a){var c=a.err;a=a.subscriber;a.closed||a.error(c)}var g=this&&this.__extends||function(a,c){function e(){this.constructor=a}for(var b in c)c.hasOwnProperty(b)&&(a[b]=c[b]);a.prototype=null===c?Object.create(c):(e.prototype=c.prototype,new e)},k=a(12);b=function(a){function c(c,b){a.call(this);this.promise=c;this.scheduler=b}g(c,a);c.create=function(a,b){return new c(a, b)};c.prototype._subscribe=function(a){var c=this,e=this.promise,b=this.scheduler;if(null==b)this._isScalar?a.closed||(a.next(this.value),a.complete()):e.then(function(e){c.value=e;c._isScalar=!0;a.closed||(a.next(e),a.complete())},function(c){a.closed||a.error(c)}).then(null,function(a){k.root.setTimeout(function(){throw a;})});else if(this._isScalar){if(!a.closed)return b.schedule(h,0,{value:this.value,subscriber:a})}else e.then(function(e){c.value=e;c._isScalar=!0;a.closed||a.add(b.schedule(h, 0,{value:e,subscriber:a}))},function(c){a.closed||a.add(b.schedule(l,0,{err:c,subscriber:a}))}).then(null,function(a){k.root.setTimeout(function(){throw a;})})};return c}(a(0).Observable);d.PromiseObservable=b},function(b,d,a){function h(){for(var a=[],e=0;e<arguments.length;e++)a[e-0]=arguments[e];e=null;g.isScheduler(a[a.length-1])&&(e=a.pop());return null===e&&1===a.length&&a[0]instanceof l.Observable?a[0]:(new k.ArrayObservable(a,e)).lift(new f.MergeAllOperator(1))}var l=a(0),g=a(20),k=a(15), f=a(45);d.concat=function(){for(var a=[],e=0;e<arguments.length;e++)a[e-0]=arguments[e];return this.lift.call(h.apply(void 0,[this].concat(a)))};d.concatStatic=h},function(b,d,a){function h(){for(var a=[],e=0;e<arguments.length;e++)a[e-0]=arguments[e];e=Number.POSITIVE_INFINITY;var b=null,d=a[a.length-1];f.isScheduler(d)?(b=a.pop(),1<a.length&&"number"===typeof a[a.length-1]&&(e=a.pop())):"number"===typeof d&&(e=a.pop());return null===b&&1===a.length&&a[0]instanceof l.Observable?a[0]:(new g.ArrayObservable(a, b)).lift(new k.MergeAllOperator(e))}var l=a(0),g=a(15),k=a(45),f=a(20);d.merge=function(){for(var a=[],e=0;e<arguments.length;e++)a[e-0]=arguments[e];return this.lift.call(h.apply(void 0,[this].concat(a)))};d.mergeStatic=h},function(b,d,a){var h=this&&this.__extends||function(a,c){function e(){this.constructor=a}for(var b in c)c.hasOwnProperty(b)&&(a[b]=c[b]);a.prototype=null===c?Object.create(c):(e.prototype=c.prototype,new e)},l=a(16);b=a(14);d.mergeMap=function(a,c,e){void 0===e&&(e=Number.POSITIVE_INFINITY); "number"===typeof c&&(e=c,c=null);return this.lift(new g(a,c,e))};var g=function(){function a(a,e,b){void 0===b&&(b=Number.POSITIVE_INFINITY);this.project=a;this.resultSelector=e;this.concurrent=b}a.prototype.call=function(a,e){return e.subscribe(new k(a,this.project,this.resultSelector,this.concurrent))};return a}();d.MergeMapOperator=g;var k=function(a){function c(c,b,f,k){void 0===k&&(k=Number.POSITIVE_INFINITY);a.call(this,c);this.project=b;this.resultSelector=f;this.concurrent=k;this.hasCompleted= !1;this.buffer=[];this.index=this.active=0}h(c,a);c.prototype._next=function(a){this.active<this.concurrent?this._tryNext(a):this.buffer.push(a)};c.prototype._tryNext=function(a){var c=this.index++;try{var e=this.project(a,c)}catch(q){this.destination.error(q);return}this.active++;this._innerSub(e,a,c)};c.prototype._innerSub=function(a,c,b){this.add(l.subscribeToResult(this,a,c,b))};c.prototype._complete=function(){this.hasCompleted=!0;0===this.active&&0===this.buffer.length&&this.destination.complete()}; c.prototype.notifyNext=function(a,c,b,f,k){this.resultSelector?this._notifyResultSelector(a,c,b,f):this.destination.next(c)};c.prototype._notifyResultSelector=function(a,c,b,f){try{var e=this.resultSelector(a,c,b,f)}catch(p){this.destination.error(p);return}this.destination.next(e)};c.prototype.notifyComplete=function(a){var c=this.buffer;this.remove(a);this.active--;0<c.length?this._next(c.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()};return c}(b.OuterSubscriber);d.MergeMapSubscriber= k},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);var l=a(173);d.observeOn=function(a,b){void 0===b&&(b=0);return this.lift(new g(a,b))};var g=function(){function a(a,c){void 0===c&&(c=0);this.scheduler=a;this.delay=c}a.prototype.call=function(a,c){return c.subscribe(new k(a,this.scheduler,this.delay))};return a}();d.ObserveOnOperator= g;var k=function(a){function c(c,b,e){void 0===e&&(e=0);a.call(this,c);this.scheduler=b;this.delay=e}h(c,a);c.dispatch=function(a){a.notification.observe(a.destination);this.unsubscribe()};c.prototype.scheduleMessage=function(a){this.add(this.scheduler.schedule(c.dispatch,this.delay,new f(a,this.destination)))};c.prototype._next=function(a){this.scheduleMessage(l.Notification.createNext(a))};c.prototype._error=function(a){this.scheduleMessage(l.Notification.createError(a))};c.prototype._complete= function(){this.scheduleMessage(l.Notification.createComplete())};return c}(b.Subscriber);d.ObserveOnSubscriber=k;var f=function(){return function(a,b){this.notification=a;this.destination=b}}();d.ObserveOnMessage=f},function(b,d,a){var h=this&&this.__extends||function(a,b){function f(){this.constructor=a}for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);a.prototype=null===b?Object.create(b):(f.prototype=b.prototype,new f)},l=a(12);b=function(a){function b(b,c){a.call(this,b,c);this.scheduler=b;this.work= c;this.pending=!1}h(b,a);b.prototype.schedule=function(a,c){void 0===c&&(c=0);if(this.closed)return this;this.state=a;this.pending=!0;a=this.id;var b=this.scheduler;null!=a&&(this.id=this.recycleAsyncId(b,a,c));this.delay=c;this.id=this.id||this.requestAsyncId(b,this.id,c);return this};b.prototype.requestAsyncId=function(a,c,b){void 0===b&&(b=0);return l.root.setInterval(a.flush.bind(a,this),b)};b.prototype.recycleAsyncId=function(a,c,b){void 0===b&&(b=0);return null!==b&&this.delay===b&&!1===this.pending? c:(l.root.clearInterval(c),void 0)};b.prototype.execute=function(a,c){if(this.closed)return Error("executing a cancelled action");this.pending=!1;if(a=this._execute(a,c))return a;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))};b.prototype._execute=function(a,c){c=!1;var b=void 0;try{this.work(a)}catch(m){c=!0,b=!!m&&m||Error(m)}if(c)return this.unsubscribe(),b};b.prototype._unsubscribe=function(){var a=this.id,c=this.scheduler,b=c.actions,k=b.indexOf(this); this.state=this.work=null;this.pending=!1;this.scheduler=null;-1!==k&&b.splice(k,1);null!=a&&(this.id=this.recycleAsyncId(c,a,null));this.delay=null};return b}(a(257).Action);d.AsyncAction=b},function(b,d,a){var h=this&&this.__extends||function(a,b){function k(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(k.prototype=b.prototype,new k)};b=function(a){function b(){a.apply(this,arguments);this.actions=[];this.active=!1;this.scheduled=void 0} h(b,a);b.prototype.flush=function(a){var b=this.actions;if(this.active)b.push(a);else{var c;this.active=!0;do if(c=a.execute(a.state,a.delay))break;while(a=b.shift());this.active=!1;if(c){for(;a=b.shift();)a.unsubscribe();throw c;}}};return b}(a(175).Scheduler);d.AsyncScheduler=b},function(b,d,a){var h=this&&this.__extends||function(a,b){function k(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(k.prototype=b.prototype,new k)};b=function(a){function b(){var b= a.call(this,"Timeout has occurred");this.name=b.name="TimeoutError";this.stack=b.stack;this.message=b.message}h(b,a);return b}(Error);d.TimeoutError=b},function(b,d,a){d.isArrayLike=function(a){return a&&"number"===typeof a.length}},function(b,d,a){d.isDate=function(a){return a instanceof Date&&!isNaN(+a)}},function(b,d,a){var h=a(26);d.isNumeric=function(a){return!h.isArray(a)&&0<=a-parseFloat(a)+1}},function(b,d,a){d.isObject=function(a){return null!=a&&"object"===typeof a}},function(b,d,a){d.isPromise= function(a){return a&&"function"!==typeof a.subscribe&&"function"===typeof a.then}},function(b,d,a){d.noop=function(){}},function(b,d,a){Object.defineProperty(d,"__esModule",{value:!0});b=a(176);a.n(b);b=a(177);a.n(b);b=a(178);a.n(b);b=a(179);a.n(b);b=a(180);a.n(b);b=a(181);a.n(b);b=a(182);a.n(b);b=a(183);a.n(b);b=a(184);a.n(b);b=a(185);a.n(b);b=a(186);a.n(b);b=a(187);a.n(b);b=a(188);a.n(b);b=a(189);a.n(b);b=a(190);a.n(b);b=a(191);a.n(b);b=a(192);a.n(b);b=a(193);a.n(b);b=a(194);a.n(b);b=a(195);a.n(b); b=a(196);a.n(b);b=a(197);a.n(b);b=a(198);a.n(b);b=a(199);a.n(b);b=a(200);a.n(b);b=a(201);a.n(b);b=a(202);a.n(b);b=a(203);a.n(b);b=a(204);a.n(b);b=a(205);a.n(b);b=a(206);a.n(b);b=a(207);a.n(b);b=a(208);a.n(b);b=a(209);a.n(b);b=a(210);a.n(b);b=a(211);a.n(b);b=a(212);a.n(b);a(1);a=a(98);d["default"]=a.a},function(b,d,a){var h=a(54),l=a(89),g=a(55);a.d(d,"b",function(){return h.a});a.d(d,"c",function(){return l.a});a.d(d,"a",function(){return g.a})},function(b,d,a){function h(a,c){if(c instanceof k.b)return c._setVideo(a); if(a.setMediaKeys)return a.setMediaKeys(c);if(null!==c){if(a.WebkitSetMediaKeys)return a.WebkitSetMediaKeys(c);if(a.mozSetMediaKeys)return a.mozSetMediaKeys(c);if(a.msSetMediaKeys)return a.msSetMediaKeys(c)}}var l=a(0);a.n(l);var g=a(9),k=a(54);d.a=function(b,c){return l.Observable.defer(function(){return a.i(g.a)(h(b,c))})}},function(b,d,a){function h(a){g()||(a.requestFullscreen?a.requestFullscreen():a.msRequestFullscreen?a.msRequestFullscreen():a.mozRequestFullScreen?a.mozRequestFullScreen():a.webkitRequestFullscreen&& a.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT))}function l(){g()&&(document.exitFullscreen?document.exitFullscreen():document.msExitFullscreen?document.msExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen())}function g(){return!!(document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement)}a.d(d,"c",function(){return h});a.d(d,"a",function(){return l}); a.d(d,"b",function(){return g})},function(b,d,a){var h=a(56);b=a(4);var l=b.a.ABR_MINIMUM_TOTAL_BYTES,g=b.a.ABR_MINIMUM_CHUNK_SIZE;b=function(){function a(){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this._fast=new h.a(2);this._slow=new h.a(10);this._bytesSampled=0}a.prototype.addSample=function(a,c){if(!(c<g)){var b=8E3*c/a;a/=1E3;this._bytesSampled+=c;this._fast.addSample(a,b);this._slow.addSample(a,b)}};a.prototype.getEstimate=function(){if(!(this._bytesSampled< l))return Math.min(this._fast.getEstimate(),this._slow.getEstimate())};a.prototype.reset=function(){this._fast=new h.a(2);this._slow=new h.a(10);this._bytesSampled=0};return a}();d.a=b},function(b,d,a){d.a=function(a,b){var k=h()(a,function(a){return a.bitrate>b});return-1===k?a:a.slice(0,k)};b=a(53);var h=a.n(b)},function(b,d,a){d.a=function(a,b){var k=a.sort(function(a,b){return a.width-b.width});if(k=h()(k,function(a){return a.width>=b})){var f=k.width;return a.filter(function(a){return a.width<= f})}return a};b=a(21);var h=a.n(b)},function(b,d,a){d.a=function(a,b){var k=h()(a,function(a){return a.bitrate>b});return-1===k?a[a.length-1]:a[k-1]};b=a(53);var h=a.n(b)},function(b,d,a){var h=a(5);a.n(h);a(19);a(2);var l=a(96),g=function(a,b){if(!a._choosers[b]){var c=a._choosers;a=a._chooserInstanceOptions;a=new l.a({limitWidth$:a.limitWidth[b],throttle$:a.throttle[b],initialBitrate:a.initialBitrates[b],manualBitrate:a.manualBitrates[b],maxAutoBitrate:a.maxAutoBitrates[b]});c[b]=a}};b=function(){function a(b, c){var e=this,f=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this._dispose$=new h.Subject;this._choosers={};this._chooserInstanceOptions={initialBitrates:f.initialBitrates||{},manualBitrates:f.manualBitrates||{},maxAutoBitrates:f.maxAutoBitrates||{},throttle:f.throttle||{},limitWidth:f.limitWidth||{}};c.takeUntil(this._dispose$).subscribe(function(a){var c=a.type;a=a.value;g(e,c);e._choosers[c].addEstimate(a.duration, a.size)});b.mergeMap(function(a){return a}).takeUntil(this._dispose$).subscribe(function(a){var c=a.type,b=a.event;a=a.value;g(e,c);switch(b){case "requestBegin":e._choosers[c].addPendingRequest(a.id,a);break;case "requestEnd":e._choosers[c].removePendingRequest(a.id);break;case "progress":e._choosers[c].addRequestProgress(a.id,a)}})}a.prototype.get$=function(a,c){var b=2<arguments.length&&void 0!==arguments[2]?arguments[2]:[];g(this,a);return this._choosers[a].get$(c,b)};a.prototype.setManualBitrate= function(a,c){var b=this._choosers[a];b?b.manualBitrate$.next(c):this._chooserInstanceOptions.initialBitrates[a]=c};a.prototype.setMaxAutoBitrate=function(a,c){var b=this._choosers[a];b?b.maxAutoBitrate$.next(c):this._chooserInstanceOptions.maxAutoBitrates[a]=c};a.prototype.getManualBitrate=function(a){var c=this._choosers[a];return c?c.manualBitrate$.getValue():this._chooserInstanceOptions.manualBitrates[a]};a.prototype.getMaxAutoBitrate=function(a){var c=this._choosers[a];return c?c.maxAutoBitrate$.getValue(): this._chooserInstanceOptions.maxAutoBitrates[a]};a.prototype.dispose=function(){var a=this;Object.keys(this._choosers).forEach(function(c){a._choosers[c].dispose()});this._choosers=this._chooserInstanceOptions=null;this._dispose$.next();this._dispose$.complete()};return a}();d.a=b},function(b,d,a){b=a(8);var h=a.n(b),l=a(43);a.n(l);var g=a(5);a.n(g);var k=a(0);a.n(k);b=a(4);a(2);var f=a(91),c=a(93),e=a(92),m=a(94),n=a(56),q=b.a.ABR_STARVATION_GAP,r=b.a.OUT_OF_STARVATION_GAP,p=function(c,b){c=a.i(m.a)(c, b)||c[0];return k.Observable.of(c).concat(k.Observable.never())};b=function(){function b(){var a=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};if(!(this instanceof b))throw new TypeError("Cannot call a class as a function");this._dispose$=new g.Subject;this.manualBitrate$=(new l.BehaviorSubject(null!=a.manualBitrate?a.manualBitrate:-1)).takeUntil(this._dispose$);this.maxAutoBitrate$=(new l.BehaviorSubject(null!=a.maxAutoBitrate?a.maxAutoBitrate:Infinity)).takeUntil(this._dispose$);this.estimator= new f.a;this._currentRequests={};this.initialBitrate=a.initialBitrate||0;this._limitWidth$=a.limitWidth$;this._throttle$=a.throttle$}b.prototype.get$=function(b,f){var d=this;if(2>f.length)return k.Observable.of({bitrate:void 0,representation:f.length?f[0]:null}).concat(k.Observable.never()).takeUntil(this._dispose$);var g=this.initialBitrate,l=this.manualBitrate$,w=this.maxAutoBitrate$,t=[];this._limitWidth$&&t.push(this._limitWidth$.map(function(a){return{width:a}}));this._throttle$&&t.push(this._throttle$.map(function(a){return{bitrate:a}})); var u=t.length?k.Observable.combineLatest.apply(k.Observable,t).map(function(a){return h.a.apply(void 0,[{}].concat(a))}):k.Observable.of({});return l.switchMap(function(h){if(0<=h)return p(f,h);var l=!1;return k.Observable.combineLatest(b,w,u).map(function(b){var k=b[0],h=b[1];b=b[2];var p=void 0,w=k.bufferGap;w<=q?l=!0:l&&w>=r&&(l=!1);if(l){var y=k.bitrate;a:{var t=d._currentRequests;w+=k.position;for(var v=Object.keys(t),u=v.length,A=0;A<u-1;A++){var x=t[v[A]];if(Math.abs(w-x.time)<x.duration){w= x;break a}}w=void 0}if(w&&(v=w.duration,t=w.requestTimestamp,t=(Date.now()-t)/1E3,v&&t>1+1.2*v)){u=w;v=void 0;w=u.duration;if(2<=u.progress.length){v=new n.a(2);u=u.progress;for(A=1;A<u.length;A++)x=u[A].timestamp-u[A-1].timestamp,v.addSample(x/1E3,8*(u[A].size-u[A-1].size)/(x/1E3));v=v.getEstimate()}v||(v=w*y/(5*t/4));if(t=v)d.resetEstimate(),p=Math.min(t,y,h)}}null==p&&(p=d.estimator.getEstimate(),p=null!=p&&k.bufferGap<=l?.95*p:p,p=Math.min(null==p?g:p,h));1<k.speed&&(p/=k.speed);k=f;b.hasOwnProperty("bitrate")&& (k=a.i(e.a)(k,b.bitrate));b.hasOwnProperty("width")&&(k=a.i(c.a)(k,b.width));return{bitrate:p,representation:a.i(m.a)(k,p)||f[0]}}).do(function(a){a=a.bitrate;null!=a&&(g=a)}).share()})};b.prototype.addEstimate=function(a,c){null!=a&&null!=c&&this.estimator.addSample(a,c)};b.prototype.resetEstimate=function(){this.estimator.reset()};b.prototype.addPendingRequest=function(a,c){this._currentRequests[a]=c;this._currentRequests[a].progress=[]};b.prototype.addRequestProgress=function(a,c){this._currentRequests[a].progress.push(c)}; b.prototype.removePendingRequest=function(a){delete this._currentRequests[a]};b.prototype.resetRequests=function(){this._currentRequests={}};b.prototype.dispose=function(){this._dispose$.next()};return b}();d.a=b},function(b,d,a){function h(c,b){var e=c.currentTime,f=c.paused,d=c.playbackRate,g=c.readyState,m=c.buffered;return{currentTime:e,buffered:m,duration:c.duration,bufferGap:a.i(k.a)(m,e),state:b,playbackRate:d,currentRange:a.i(k.i)(m,e),readyState:g,paused:f}}var l=a(0);a.n(l);var g=a(43); a.n(g);b=a(4);var k=a(10),f=b.a.SAMPLING_INTERVAL_MEDIASOURCE,c=b.a.SAMPLING_INTERVAL_NO_MEDIASOURCE,e=b.a.RESUME_AFTER_SEEKING_GAP,m=b.a.RESUME_AFTER_BUFFERING_GAP,n=b.a.STALL_GAP,q="canplay play progress seeking seeked loadedmetadata".split(" ");d.a=function(a,b){var k=b.withMediaSource;return l.Observable.create(function(b){function d(c){c=h(a,c&&c.type||"timeupdate");var f=c.state;var d=c.currentTime,l=c.bufferGap,q=c.paused,r=c.readyState,p=g.stalled,v=g.state,t=g.currentTime;var w=(w=c.currentRange)&& c.duration-(l+w.end)<=n;var y=1<=r&&"loadedmetadata"!=f&&!p&&!w,u=void 0,x=void 0;k?y&&(l<=n||Infinity===l||1===r)?u=!0:p&&1<r&&Infinity>l&&(l>("seeking"==p.state?e:m)||w)&&(x=!0):y&&(!q&&"timeupdate"==f&&"timeupdate"==v&&d===t||"seeking"==f&&Infinity===l)?u=!0:p&&("seeking"!=f&&d!==t||"canplay"==f||Infinity>l&&(l>("seeking"==p.state?e:m)||w))&&(x=!0);f=u?{state:f,timestamp:Date.now()}:x?null:p;c.stalled=f;g=c;b.next(g)}var g=h(a,"init");g.stalled=null;var l=setInterval(d,k?f:c);q.forEach(function(c){return a.addEventListener(c, d)});b.next(g);return function(){clearInterval(l);q.forEach(function(c){return a.removeEventListener(c,d)})}}).multicast(function(){return new g.BehaviorSubject({})}).refCount()}},function(b,d,a){function h(a,c){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!c||"object"!==typeof c&&"function"!==typeof c?a:c}function l(a,c){if("function"!==typeof c&&null!==c)throw new TypeError("Super expression must either be null or a function, not "+typeof c); a.prototype=Object.create(c&&c.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});c&&(Object.setPrototypeOf?Object.setPrototypeOf(a,c):a.__proto__=c)}function g(a,c){return a.filter(function(a){return a.type==c}).map(function(a){return a.value})}var k=a(0);a.n(k);var f=a(5);a.n(f);var c=a(43);a.n(c);b=a(4);var e=a(1),m=a(31),n=a(29),q=a(2),r=a(10),p=a(7),t=a(17),u=a(148),w=a(28),x=a(6),v=a(121),y=a(57),z=a(35),B=a(97),C=a(102),A=a(99),H=a(101),E="function"===typeof Symbol&& "symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},I=function(){function a(a,c){for(var b=0;b<c.length;b++){var e=c[b];e.enumerable=e.enumerable||!1;e.configurable=!0;"value"in e&&(e.writable=!0);Object.defineProperty(a,e.key,e)}}return function(c,b,e){b&&a(c.prototype,b);e&&a(c,e);return c}}(),J=b.a.DEFAULT_UNMUTED_VOLUME;b=function(b){function d(k){if(!(this instanceof d))throw new TypeError("Cannot call a class as a function"); var g=h(this,b.call(this)),m=a.i(H.a)(k);k=m.defaultAudioTrack;var l=m.defaultTextTrack,n=m.initialAudioBitrate,r=m.initialVideoBitrate,w=m.limitVideoWidth,v=m.maxAudioBitrate,u=m.maxBufferAhead,y=m.maxBufferBehind,A=m.maxVideoBitrate,x=m.throttleWhenHidden,B=m.transport,Q=m.transportOptions,D=m.videoElement;m=m.wantedBufferAhead;a.i(q.a)(D instanceof p.a,"videoElement needs to be an HTMLVideoElement");D.preload="auto";g.version="3.0.0-rc4";g.log=e.a;g.state=void 0;g.defaultTransport=B;g.defaultTransportOptions= Q;g.videoElement=D;g._priv=a.i(C.a)(g);g._priv.destroy$=new f.Subject;g._priv.fullScreenSubscription=a.i(t.a)(D).takeUntil(g._priv.destroy$).subscribe(function(){return g.trigger("fullscreenChange",g.isFullscreen())});g._priv.errorStream$=(new f.Subject).takeUntil(g._priv.destroy$);g._priv.playing$=new c.BehaviorSubject;g._priv.speed$=new c.BehaviorSubject(D.playbackRate);g._priv.unsubscribeLoadedVideo$=(new f.Subject).takeUntil(g._priv.destroy$);g._priv.wantedBufferAhead$=new c.BehaviorSubject(m); g._priv.maxBufferAhead$=new c.BehaviorSubject(u);g._priv.maxBufferBehind$=new c.BehaviorSubject(y);g._priv.lastAudioTrack=k;g._priv.lastTextTrack=l;g._priv.lastBitrates={audio:n,video:r};g._priv.initialMaxAutoBitrates={audio:v,video:A};g._priv.manualBitrates={audio:-1,video:-1};g._priv.throttleWhenHidden=x;g._priv.limitVideoWidth=w;g._priv.mutedMemory=J;"abrManager currentAdaptations currentImagePlaylist currentRepresentations fatalError initialAudioTrack initialTextTrack languageManager manifest recordedEvents".split(" ").forEach(function(a){g._priv[a]= void 0});g._priv.resetContentState();g._priv.setPlayerState(z.a.STOPPED);return g}l(d,b);I(d,null,[{key:"ErrorTypes",get:function(){return x.a}},{key:"ErrorCodes",get:function(){return x.b}}]);d.prototype.stop=function(){this.state!==z.a.STOPPED&&(this._priv.resetContentState(),this._priv.unsubscribeLoadedVideo$.next(),this._priv.setPlayerState(z.a.STOPPED))};d.prototype.dispose=function(){this.stop();a.i(y.a)();var c=this._priv;c.destroy$.next();c.destroy$.complete();c.playing$.complete();c.speed$.complete(); c.wantedBufferAhead$.complete();c.maxBufferAhead$.complete();c.maxBufferBehind$.complete();c.playing$=null;c.speed$=null;c.wantedBufferAhead$=null;c.maxBufferAhead$=null;c.maxBufferBehind$=null;c.unsubscribeLoadedVideo$=null;c.fullScreenSubscription=null;c.errorStream$=null;c.lastBitrates=null;c.manualBitrates=null;this.videoElement=c.initialMaxAutoBitrates=null};d.prototype.loadVideo=function(){var c=this,b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};b=a.i(H.b)(b,this);e.a.info("loadvideo", b);var f=b,d=f.autoPlay;b=f.defaultAudioTrack;var l=f.defaultTextTrack,h=f.hideNativeSubtitle,n=f.keySystems,r=f.startAt,p=f.supplementaryImageTracks,w=f.supplementaryTextTracks,y=f.transport,x=f.transportOptions;f=f.url;a.i(q.a)(f,"you have to give an url");a.i(q.a)(y,"you have to set the transport type");var C=u.a[y];a.i(q.a)(C,'transport "'+y+'" not supported');C=C(x);this.stop();this._priv.initialAudioTrack=b;this._priv.initialTextTrack=l;this._priv.playing$.next(d);x=this.videoElement;var D= this._priv;b=D.errorStream$;l=D.unsubscribeLoadedVideo$;var E=D.wantedBufferAhead$,I=D.maxBufferAhead$;D=D.maxBufferBehind$;var G=!y.directFile;y=a.i(B.a)(x,{withMediaSource:G});var J={initialBitrates:this._priv.lastBitrates,manualBitrates:this._priv.manualBitrates,maxAutoBitrates:this._priv.initialMaxAutoBitrates,throttle:this._priv.throttleWhenHidden&&{video:a.i(t.b)().map(function(a){return a?0:Infinity}).takeUntil(l)},limitWidth:this._priv.limitVideoWidth&&{video:a.i(t.c)(x).takeUntil(l)}};E= {wantedBufferAhead$:E,maxBufferAhead$:I,maxBufferBehind$:D};d=a.i(v.a)({adaptiveOptions:J,autoPlay:d,bufferOptions:E,errorStream:b,hideNativeSubtitle:h,keySystems:n,speed$:this._priv.speed$,startAt:r,timings$:y,transport:C,url:f,videoElement:x,withMediaSource:G,supplementaryImageTracks:p,supplementaryTextTracks:w}).takeUntil(l).publish();h=g(d,"stalled").startWith(null);h=g(d,"loaded").take(1).share().mapTo(z.a.LOADED).concat(k.Observable.combineLatest(this._priv.playing$,h,A.a)).distinctUntilChanged().startWith(z.a.LOADING); n=a.i(m.a)(x,["play","pause"]);r=a.i(m.a)(x.textTracks,["addtrack"]);var K=void 0;l.take(1).subscribe(function(){K&&K.unsubscribe()});p=function(){};n.takeUntil(l).subscribe(function(a){return c._priv.onPlayPauseNext(a)},p);r.takeUntil(l).subscribe(function(a){return c._priv.onNativeTextTrackNext(a)},p);y.takeUntil(l).subscribe(function(a){return c._priv.triggerTimeChange(a)},p);h.takeUntil(l).subscribe(function(a){return c._priv.setPlayerState(a)},p);d.subscribe(function(a){return c._priv.onStreamNext(a)}, function(a){return c._priv.onStreamError(a)},function(){return c._priv.onStreamComplete()});b.takeUntil(l).subscribe(function(a){return c._priv.onErrorStreamNext(a)});K=d.connect()};d.prototype.getError=function(){return this._priv.fatalError};d.prototype.getManifest=function(){return this._priv.manifest||null};d.prototype.getCurrentAdaptations=function(){return this._priv.manifest?this._priv.currentAdaptations:null};d.prototype.getCurrentRepresentations=function(){return this._priv.manifest?this._priv.currentRepresentations: null};d.prototype.getVideoElement=function(){return this.videoElement};d.prototype.getNativeTextTrack=function(){return 0<this.videoElement.textTracks.length?this.videoElement.textTracks[0]:null};d.prototype.getPlayerState=function(){return this.state};d.prototype.isLive=function(){return this._priv.manifest?this._priv.manifest.isLive:!1};d.prototype.getUrl=function(){if(this._priv.manifest)return this._priv.manifest.getUrl()};d.prototype.getVideoDuration=function(){return this.videoElement.duration}; d.prototype.getVideoBufferGap=function(){return a.i(r.a)(this.videoElement.buffered,this.videoElement.currentTime)};d.prototype.getVideoLoadedTime=function(){return a.i(r.b)(this.videoElement.buffered,this.videoElement.currentTime)};d.prototype.getVideoPlayedTime=function(){return a.i(r.c)(this.videoElement.buffered,this.videoElement.currentTime)};d.prototype.getWallClockTime=function(){if(!this._priv.manifest)return 0;var c=this.videoElement.currentTime;return this.isLive()?+a.i(w.a)(c,this._priv.manifest)/ 1E3:c};d.prototype.getPosition=function(){return this.videoElement.currentTime};d.prototype.getPlaybackRate=function(){return this._priv.speed$.getValue()};d.prototype.getVolume=function(){return this.videoElement.volume};d.prototype.isFullscreen=function(){return a.i(p.b)()};d.prototype.getAvailableVideoBitrates=function(){var a=this._priv.currentAdaptations.video;return a?a.representations.map(function(a){return a.bitrate}):[]};d.prototype.getAvailableAudioBitrates=function(){var a=this._priv.currentAdaptations.audio; return a?a.representations.map(function(a){return a.bitrate}):[]};d.prototype.getManualAudioBitrate=function(){return this._priv.manualBitrates.audio};d.prototype.getManualVideoBitrate=function(){return this._priv.manualBitrates.video};d.prototype.getVideoBitrate=function(){return this._priv.recordedEvents.videoBitrate};d.prototype.getAudioBitrate=function(){return this._priv.recordedEvents.audioBitrate};d.prototype.getMaxVideoBitrate=function(){return this._priv.abrManager?this._priv.abrManager.getMaxAutoBitrate("video"): this._priv.initialMaxAutoBitrates.video};d.prototype.getMaxAudioBitrate=function(){return this._priv.abrManager?this._priv.abrManager.getMaxAutoBitrate("audio"):this._priv.initialMaxAutoBitrates.audio};d.prototype.play=function(){this.videoElement.play()};d.prototype.pause=function(){this.videoElement.pause()};d.prototype.setPlaybackRate=function(a){this._priv.speed$.next(a)};d.prototype.seekTo=function(c){a.i(q.a)(this._priv.manifest,"player: no manifest loaded");var b=void 0,e="undefined"===typeof c? "undefined":E(c);if("number"===e)b=c;else if("object"===e)if(b=this.videoElement.currentTime,null!=c.relative)b+=c.relative;else if(null!=c.position)b=c.position;else if(c.wallClockTime)b=a.i(w.b)(1E3*c.wallClockTime,this._priv.manifest);else throw Error('invalid time object. You must set one of the following properties: "relative", "position" or "wallClockTime"');if(void 0===b)throw Error("invalid time given");return this.videoElement.currentTime=b};d.prototype.exitFullscreen=function(){a.i(p.c)()}; d.prototype.setFullscreen=function(){(0<arguments.length&&void 0!==arguments[0]?arguments[0]:1)?a.i(p.d)(this.videoElement):a.i(p.c)()};d.prototype.setVolume=function(a){a!==this.videoElement.volume&&(this.videoElement.volume=a,this.trigger("volumeChange",a))};d.prototype.isMute=function(){return!this.getVolume()};d.prototype.mute=function(){this._priv.mutedMemory=this.getVolume();this.setVolume(0)};d.prototype.unMute=function(){0===this.getVolume()&&this.setVolume(this._priv.mutedMemory||J)};d.prototype.setVideoBitrate= function(a){this._priv.manualBitrates.video=a;this._priv.abrManager&&this._priv.abrManager.setManualBitrate("video",a)};d.prototype.setAudioBitrate=function(a){this._priv.manualBitrates.audio=a;this._priv.abrManager&&this._priv.abrManager.setManualBitrate("audio",a)};d.prototype.setMaxVideoBitrate=function(a){this._priv.initialMaxAutoBitrates.video=a;this._priv.abrManager&&this._priv.abrManager.setMaxAutoBitrate("video",a)};d.prototype.setMaxAudioBitrate=function(a){this._priv.initialMaxAutoBitrates.audio= a;this._priv.abrManager&&this._priv.abrManager.setMaxAutoBitrate("audio",a)};d.prototype.setMaxBufferBehind=function(a){this._priv.maxBufferBehind$.next(a)};d.prototype.setMaxBufferAhead=function(a){this._priv.maxBufferAhead$.next(a)};d.prototype.setWantedBufferAhead=function(a){this._priv.wantedBufferAhead$.next(a)};d.prototype.getMaxBufferBehind=function(){return this._priv.maxBufferBehind$.getValue()};d.prototype.getMaxBufferAhead=function(){return this._priv.maxBufferAhead$.getValue()};d.prototype.getWantedBufferAhead= function(){return this._priv.wantedBufferAhead$.getValue()};d.prototype.getCurrentKeySystem=function(){return a.i(y.b)()};d.prototype.getAvailableAudioTracks=function(){return this._priv.languageManager?this._priv.languageManager.getAvailableAudioTracks():null};d.prototype.getAvailableTextTracks=function(){return this._priv.languageManager?this._priv.languageManager.getAvailableTextTracks():null};d.prototype.getAudioTrack=function(){if(this._priv.languageManager)return this._priv.languageManager.getCurrentAudioTrack()}; d.prototype.getTextTrack=function(){if(this._priv.languageManager)return this._priv.languageManager.getCurrentTextTrack()};d.prototype.setAudioTrack=function(c){a.i(q.a)(this._priv.languageManager,"No compatible content launched.");try{this._priv.languageManager.setAudioTrack(c)}catch(L){throw Error("player: unknown audio track");}};d.prototype.setTextTrack=function(c){a.i(q.a)(this._priv.languageManager,"No compatible content launched.");try{this._priv.languageManager.setTextTrack(c)}catch(L){throw Error("player: unknown text track"); }};d.prototype.disableTextTrack=function(){if(this._priv.languageManager)return this._priv.languageManager.disableTextTrack()};d.prototype.getImageTrackData=function(){return this._priv.manifest?this._priv.currentImagePlaylist:null};d.prototype.getMinimumPosition=function(){return this._priv.manifest?a.i(w.c)(this._priv.manifest):null};d.prototype.getMaximumPosition=function(){return this._priv.manifest?a.i(w.d)(this._priv.manifest):null};return d}(n.a);d.a=b},function(b,d,a){d.a=function(a,b){return b? "seeking"==b.state?h.a.SEEKING:h.a.BUFFERING:a?h.a.PLAYING:h.a.PAUSED};var h=a(35)},function(b,d,a){b=a(21);var h=a.n(b),l=function(a,b){if(!b)return null;if(a.length)return h()(a,function(a){return b.normalized===a.normalizedLanguage&&b.closedCaption===a.isClosedCaption})},g=function(a,b){if(a.length&&b)return h()(a,function(a){return b.normalized===a.normalizedLanguage&&b.audioDescription===a.isAudioDescription})};a=function(){function a(b,c){var e=b.text,f=b.audio,d=c.text$,k=c.audio$,h=2<arguments.length&& void 0!==arguments[2]?arguments[2]:{};if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");var p=h.defaultAudioTrack;h=h.defaultTextTrack;e=e||[];f=f||[];this._currentTextAdaptation=this._currentAudioAdaptation=null;this._textAdaptations=e;this._audioAdaptations=f;this._text$=d;if(this._audio$=k)this._currentAudioAdaptation=p?g(f,p)||f[0]:f[0],k.next(this._currentAudioAdaptation);d&&(this._currentTextAdaptation=h?l(e,h)||null:null,d.next(this._currentTextAdaptation))}a.prototype.updateAdaptations= function(a){var c=a.audio;a=a.text;this._audioAdaptations=c||[];this._textAdaptations=a||[];var b=this._currentAudioAdaptation,f=b&&b.id,d=void 0;null!=f&&(d=h()(c,function(a){return a.id===f}));d||(this._currentAudioAdaptation=g(c,{language:b.language,audioDescription:!!b.isAudioDescription})||c[0],this._audio$.next(this._currentAudioAdaptation));var k=(c=this._currentTextAdaptation)&&c.id;b=void 0;null!=k&&(b=h()(a,function(a){return a.id===k}));null===k||b||(this._currentTextAdaptation=l(a,{language:c.language, closedCaption:!!c.isClosedCaption})||a[0],this._text$.next(this._currentTextAdaptation))};a.prototype.setAudioTrack=function(a){var c=h()(this._audioAdaptations,function(c){return c.id===a});if(void 0===c)throw Error("Audio Track not found.");this._currentAudioAdaptation=c;this._audio$.next(this._currentAudioAdaptation)};a.prototype.setTextTrack=function(a){var c=h()(this._textAdaptations,function(c){return c.id===a});if(void 0===c)throw Error("Text Track not found.");this._currentTextAdaptation= c;this._text$.next(this._currentTextAdaptation)};a.prototype.disableTextTrack=function(){this._currentTextAdaptation=null;this._text$.next(this._currentTextAdaptation)};a.prototype.getCurrentAudioTrack=function(){var a=this._currentAudioAdaptation;return a?{language:a.language,normalized:a.normalizedLanguage,audioDescription:a.isAudioDescription,id:a.id}:null};a.prototype.getCurrentTextTrack=function(){var a=this._currentTextAdaptation;return a?{language:a.language,normalized:a.normalizedLanguage, closedCaption:a.isClosedCaption,id:a.id}:null};a.prototype.getAvailableAudioTracks=function(){var a=this._currentAudioAdaptation,c=a&&a.id;return this._audioAdaptations.map(function(a){return{language:a.language,normalized:a.normalizedLanguage,audioDescription:a.isAudioDescription,id:a.id,active:null==c?!1:c===a.id}})};a.prototype.getAvailableTextTracks=function(){var a=this._currentTextAdaptation,c=a&&a.id;return this._textAdaptations.map(function(a){return{language:a.language,normalized:a.normalizedLanguage, closedCaption:a.isClosedCaption,id:a.id,active:null==c?!1:c===a.id}})};return a}();d.a=a},function(b,d,a){function h(){var c=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},b={transport:c.transport,transportOptions:v(c.transportOptions,{}),maxBufferAhead:v(c.maxBufferAhead,r),maxBufferBehind:v(c.maxBufferBehind,p),limitVideoWidth:v(c.limitVideoWidth,x),defaultAudioTrack:a.i(f.b)(v(c.defaultAudioTrack,m)),defaultTextTrack:a.i(f.c)(v(c.defaultTextTrack,n)),wantedBufferAhead:v(c.wantedBufferAhead, q),throttleWhenHidden:v(c.throttleWhenHidden,w),videoElement:c.videoElement?c.videoElement:document.createElement("video")},e=t||{},d=u||{};b.initialAudioBitrate=v(c.initialAudioBitrate,e.audio,e.other);b.initialVideoBitrate=v(c.initialVideoBitrate,e.video,e.other);b.maxAudioBitrate=v(c.maxAudioBitrate,d.audio,d.other);b.maxVideoBitrate=v(c.maxVideoBitrate,d.video,d.other);return b}function l(){var b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},d=arguments[1],g=d.defaultTransportOptions, m=d._priv,l=m.lastTextTrack;m=m.lastAudioTrack;d={url:b.url,transport:v(b.transport,d.defaultTransport),autoPlay:v(b.autoPlay,c),keySystems:v(b.keySystems,[]),transportOptions:v(b.transportOptions,g),hideNativeSubtitle:v(b.hideNativeSubtitle,!e),supplementaryTextTracks:v(b.supplementaryTextTracks,[]),supplementaryImageTracks:v(b.supplementaryImageTracks,[]),defaultAudioTrack:a.i(f.b)(v(b.defaultAudioTrack,m)),defaultTextTrack:a.i(f.c)(v(b.defaultTextTrack,l))};d.startAt=b.startAt&&b.startAt.wallClockTime instanceof Date?k()({},b.startAt,{wallClockTime:b.startAt.wallClockTime/1E3}):b.startAt;b.directFile&&(d.transport="directfile");return d}a.d(d,"a",function(){return h});a.d(d,"b",function(){return l});b=a(4);d=a(167);var g=a(8),k=a.n(g),f=a(30),c=b.a.DEFAULT_AUTO_PLAY,e=b.a.DEFAULT_SHOW_SUBTITLE,m=b.a.DEFAULT_AUDIO_TRACK,n=b.a.DEFAULT_TEXT_TRACK,q=b.a.DEFAULT_WANTED_BUFFER_AHEAD,r=b.a.DEFAULT_MAX_BUFFER_AHEAD,p=b.a.DEFAULT_MAX_BUFFER_BEHIND,t=b.a.DEFAULT_INITIAL_BITRATES,u=b.a.DEFAULT_MAX_BITRATES,w=b.a.DEFAULT_THROTTLE_WHEN_HIDDEN, x=b.a.DEFAULT_LIMIT_VIDEO_WIDTH,v=d.a},function(b,d,a){b=a(169);var h=a.n(b),l=a(1);a(2);var g=a(28),k=a(35),f=a(100);d.a=function(c){return{resetContentState:function(){c._priv.initialAudioTrack=void 0;c._priv.initialTextTrack=void 0;c._priv.languageManager=null;c._priv.abrManager=null;c._priv.manifest=null;c._priv.currentRepresentations={};c._priv.currentAdaptations={};c._priv.recordedEvents={};c._priv.fatalError=null;c._priv.currentImagePlaylist=null},recordState:function(a,b){var e=c._priv.recordedEvents[a]; h()(e,b)||(c._priv.recordedEvents[a]=b,c.trigger(a+"Change",b))},onStreamNext:function(a){var b=a.value;switch(a.type){case "representationChange":c._priv.onRepresentationChange(b);break;case "manifestUpdate":c._priv.onManifestUpdate(b);break;case "adaptationChange":c._priv.onAdaptationChange(b);break;case "bitrateEstimationChange":c._priv.onBitrateEstimationChange(b);break;case "manifestChange":c._priv.onManifestChange(b);break;case "pipeline":a=b.parsed,"image"===b.bufferType&&(c._priv.currentImagePlaylist= a.segmentData,c.trigger("imageTrackUpdate",{data:c._priv.currentImagePlaylist}))}},onErrorStreamNext:function(a){c.trigger("warning",a)},onStreamError:function(a){c._priv.resetContentState();c._priv.fatalError=a;c._priv.unsubscribeLoadedVideo$.next();c._priv.setPlayerState(k.a.STOPPED);c._priv.fatalError===a&&c.trigger("error",a)},onStreamComplete:function(){c._priv.resetContentState();c._priv.unsubscribeLoadedVideo$.next();c._priv.setPlayerState(k.a.ENDED)},onManifestChange:function(a){var b=a.manifest, e=a.adaptations$,d=void 0===e?{}:e;c._priv.manifest=b;c._priv.languageManager=new f.a(b.adaptations,{audio$:d.audio,text$:d.text},{defaultAudioTrack:c._priv.initialAudioTrack,defaultTextTrack:c._priv.initialTextTrack});Object.keys(d).forEach(function(a){"audio"!==a&&"text"!==a&&d[a].next((b.adaptations[a]||[])[0]||null)});c._priv.abrManager=a.abrManager;c.trigger("manifestChange",b)},onManifestUpdate:function(a){a=a.manifest;c._priv.manifest=a;c._priv.languageManager.updateAdaptations(a.adaptations); c.trigger("manifestUpdate",a)},onAdaptationChange:function(a){var b=a.type;c._priv.currentAdaptations[b]=a.adaptation;c._priv.languageManager&&("audio"===b?(a=c._priv.languageManager.getCurrentAudioTrack(),c._priv.lastAudioTrack=a,c._priv.recordState("audioTrack",a)):"text"===b&&(a=c._priv.languageManager.getCurrentTextTrack(),c._priv.lastTextTrack=a,c._priv.recordState("textTrack",a)))},onRepresentationChange:function(a){var b=a.type;a=a.representation;a=(c._priv.currentRepresentations[b]=a)&&a.bitrate; null!=a&&(c._priv.lastBitrates[b]=a);"video"==b?c._priv.recordState("videoBitrate",null!=a?a:-1):"audio"==b&&c._priv.recordState("audioBitrate",null!=a?a:-1)},onBitrateEstimationChange:function(a){c._priv.recordState("bitrateEstimation",{type:a.type,bitrate:a.bitrate})},onPlayPauseNext:function(a){!0!==c.videoElement.ended&&c._priv.playing$.next("play"==a.type)},onNativeTextTrackNext:function(a){(a=a.target[0])&&c.trigger("nativeTextTrackChange",a)},setPlayerState:function(a){c.state!==a&&(c.state= a,l.a.info("playerStateChange",a),c.trigger("playerStateChange",a))},triggerTimeChange:function(b){if(c._priv.manifest&&b){var e={position:b.currentTime,duration:b.duration,playbackRate:b.playbackRate,bufferGap:isFinite(b.bufferGap)?b.bufferGap:0};c._priv.manifest.isLive&&0<b.currentTime&&(e.wallClockTime=a.i(g.a)(b.currentTime,c._priv.manifest).getTime()/1E3,e.liveGap=a.i(g.d)(c._priv.manifest)-b.currentTime);c.trigger("positionUpdate",e)}}}}},function(b,d,a){d.a=function(b,d,f,c){if(!isFinite(f)&& !isFinite(c))return h.Observable.empty();var e=[],k=a.i(l.g)(b.getBuffered(),d),g=k.innerRange,q=k.outerRanges;(function(){if(isFinite(f)){for(var a=0;a<q.length;a++){var c=q[a];d-f>=c.end?e.push(c):d>=c.end&&d-f>c.start&&d-f<c.end&&e.push({start:c.start,end:d-f})}g&&d-f>g.start&&e.push({start:g.start,end:d-f})}})();(function(){if(isFinite(c)){for(var a=0;a<q.length;a++){var b=q[a];d+c<=b.start?e.push(b):d<=b.start&&d+c<b.end&&d+c>b.start&&e.push({start:d+c,end:b.end})}g&&d+c<g.end&&e.push({start:d+ c,end:g.end})}})();return h.Observable.from(e.map(function(a){return b.removeBuffer(a)})).concatAll().ignoreElements()};var h=a(0);a.n(h);var l=a(10)},function(b,d,a){function h(c,b,f){var e=a.i(k.g)(b,c);b=e.innerRange;e=e.outerRanges;for(var d=[],m=0;m<e.length;m++){var l=e[m];c-f<l.end?d.push(l):c+f>l.start&&d.push(l)}b&&(g.a.debug("buffer: gc removing part of inner range",d),c-f>b.start&&d.push({start:b.start,end:c-f}),c+f<b.end&&d.push({start:c+f,end:b.end}));return d}d.a=function(a,b){g.a.warn("buffer: running garbage collector"); return a.take(1).mergeMap(function(a){var e=b.getBuffered(),d=h(a.currentTime,e,f);0===d.length&&(d=h(a.currentTime,e,c));g.a.debug("buffer: gc cleaning",d);return l.Observable.from(d.map(function(a){return b.removeBuffer(a)})).concatAll()})};var l=a(0);a.n(l);b=a(4);var g=a(1),k=a(10),f=b.a.BUFFER_GC_GAPS.CALM,c=b.a.BUFFER_GC_GAPS.BEEFY},function(b,d,a){function h(b){function d(b){function k(a){if(l.test(a.id))return!1;if(a.isInit||0>a.time)return!0;a=L.hasCompleteSegment(a.time,a.duration,a.timescale); return!a||a.bitrate*u<b.bitrate}c.a.info("bitrate",E,b.bitrate);var l=new e.a,q=function(a){return h({segment:a,representation:b,init:J}).map(function(c){return f()({segment:a},c)})},r=g.Observable.combineLatest(B,C,A,H).mergeMap(function(e,f){var d=e[0],h=e[2],r=e[3];var p=Math.min(e[1],r);var v=M.getBuffered();L.addBufferedInfos(v);d.stalled&&I&&(e=b.index.checkDiscontinuity(d.currentTime),0<e&&D.next({type:"index-discontinuity",value:{ts:e+1}}));e=null;0===f&&(c.a.debug("add init segment",E),e= b.index.getInitSegment());if(0===d.readyState)e=e?[e]:[];else{f=G;var w=Q,u=w;w=d.currentTime+d.timeOffset;var A=(d.duration||Infinity)-w;p=Math.max(0,null==d.liveGap?Math.min(p,A):Math.min(p,d.liveGap,A));v=a.i(m.a)(v,w);v=w+(v>f&&Infinity>v?Math.min(v,u):0);f=p=w+p;p=f-v;b.index.shouldRefresh(d.currentTime+d.timeOffset,v,f)&&(f=new n.g("OUT_OF_INDEX_ERROR",b.index.getType(),!1),D.next({type:"out-of-index",value:f}));v=b.index.getSegments(v,p);e&&v.unshift(e);e=v}e=e.filter(k);for(v=0;v<e.length;v++)l.add(e[v].id); e=g.Observable.of.apply(g.Observable,e).concatMap(q);d=a.i(t.a)(M,d.currentTime,h,r);return g.Observable.merge(e,d)}).concatMap(function(c){var e=c.segment,d=c.parsed,k=d.segmentData,g=d.nextSegments,m=d.segmentInfos;e.isInit&&(J=m);var h=g?b.index._addSegments(g,m):[],q=function(){l.remove(e.id);if(!e.isInit){var a=m?m:e,c=a.time,f=a.timescale;L.insert(e,c/f,(c+a.duration)/f,b.bitrate)}},r=function(){return M.appendBuffer(k).do(q)};return r().catch(function(c){if("QuotaExceededError"!=c.name)throw l.remove(e.id), new n.f("BUFFER_APPEND_ERROR",c,!0);return a.i(p.a)(B,M).mergeMap(r).catch(function(a){l.remove(e.id);throw new n.f("BUFFER_FULL_ERROR",a,!0);})}).map(function(){return{type:"pipeline",value:f()({bufferType:E,addedSegments:h},c)}})});return g.Observable.merge(r,D).catch(function(a){if(!I||a.type!=n.a.NETWORK_ERROR||!a.isHttpError(412))throw a;return g.Observable.of({type:"precondition-failed",value:a}).concat(g.Observable.timer(2E3)).concat(d(b))}).startWith({type:"representationChange",value:{type:E, representation:b}})}var l=b.sourceBuffer,h=b.downloader,w=b.switch$,B=b.clock$,C=b.wantedBufferAhead,A=b.maxBufferBehind,H=b.maxBufferAhead,E=b.bufferType,I=b.isLive,J=null,D=new k.Subject,G="video"==E?4:1,Q="video"==E?6:1,L=new q.a,M=new r.a(l);return w.switchMap(d).finally(function(){return M.dispose()})}function l(a){return g.Observable.of({type:"representationChange",value:{type:a.bufferType,representation:null}})}a.d(d,"b",function(){return h});a.d(d,"a",function(){return l});var g=a(0);a.n(g); var k=a(5);a.n(k);b=a(8);var f=a.n(b);b=a(4);var c=a(1),e=a(161),m=a(10),n=a(6),q=a(107),r=a(106),p=a(104),t=a(103),u=b.a.BITRATE_REBUFFERING_RATIO},function(b,d,a){var h=a(5);a.n(h);b=function(){function a(b){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.buffer=b;this.queue=[];this.flushing=null;this.__onUpdate=this._onUpdate.bind(this);this.__onError=this._onError.bind(this);this.__flush=this._flush.bind(this);this.buffer.addEventListener("update",this.__onUpdate); this.buffer.addEventListener("error",this.__onError);this.buffer.addEventListener("updateend",this.__flush)}a.prototype.appendBuffer=function(a){return this._queueAction("append",a)};a.prototype.removeBuffer=function(a){return this._queueAction("remove",{start:a.start,end:a.end})};a.prototype.getBuffered=function(){return this.buffer.buffered};a.prototype.dispose=function(){this.buffer.removeEventListener("update",this.__onUpdate);this.buffer.removeEventListener("error",this.__onError);this.buffer.removeEventListener("updateend", this.__flush);this.buffer=null;this.queue.length=0;this.flushing=null};a.prototype._onUpdate=function(a){this.flushing&&(this.flushing.next(a),this.flushing.complete(),this.flushing=null)};a.prototype._onError=function(a){this.flushing&&(this.flushing.error(a),this.flushing=null)};a.prototype._queueAction=function(a,b){var f=new h.Subject;1===this.queue.unshift({type:a,args:b,subj:f})&&this._flush();return f};a.prototype._flush=function(){if(!this.flushing&&0!==this.queue.length&&!this.buffer.updating){var a= this.queue.pop(),b=a.type,f=a.args;this.flushing=a.subj;try{switch(b){case "append":this.buffer.appendBuffer(f);break;case "remove":this.buffer.remove(f.start,f.end)}}catch(c){this._onError(c)}}};return a}();d.a=b},function(b,d,a){b=a(4);a(2);var h=a(168),l=a(10),g=b.a.MAX_MISSING_FROM_COMPLETE_SEGMENT,k=b.a.MAX_BUFFERED_DISTANCE,f=b.a.MINIMUM_SEGMENT_SIZE;b=function(){function c(){if(!(this instanceof c))throw new TypeError("Cannot call a class as a function");this._inventory=[]}c.prototype.addBufferedInfos= function(c){c=a.i(l.h)(c);for(var b=c.length-1,e=this._inventory,d=0,g=e[0],p=0;p<=b;p++){if(!g)return;var t=c[p],u=t.start;t=t.end;if(!(t-u<f)){for(var w=d;g&&a.i(h.a)(g.bufferedEnd,g.end)-u<f;)g=e[++d];var x=-1,v=d-w;v&&(d=e[w+v-1],x=a.i(h.a)(d.bufferedEnd,d.end),e.splice(w,v),d=w);if(!g)return;t-a.i(h.a)(g.bufferedStart,g.start)>=f&&(null!=g.bufferedStart&&g.bufferedStart<u?g.bufferedStart=u:null==g.bufferedStart&&(-1!==x&&x>u?g.bufferedStart-x<=k&&(g.bufferedStart=x):g.bufferedStart=g.start-u<= k?u:g.start),g=e[++d]);for(;g&&t-a.i(h.a)(g.bufferedStart,g.start)>=f;)u=e[d-1],null==u.bufferedEnd&&(u.bufferedEnd=u.end),g.bufferedStart=u.bufferedEnd,g=e[++d];if(u=e[d-1])null!=u.bufferedEnd&&u.bufferedEnd>t?u.bufferedEnd=t:null==u.bufferedEnd&&(u.bufferedEnd=t-u.end<=k?t:u.end)}}g&&e.splice(d,e.length-d)};c.prototype.insert=function(a,c,b,f){if(null!=b){var e=this._inventory;b={bitrate:f,start:c,end:b,bufferedStart:void 0,bufferedEnd:void 0,segment:a};for(f=e.length-1;0<=f;f--){var d=e[f];if(d.start<= c){d.end<=c?this._inventory.splice(f+1,0,b):d.start>=c?this._inventory.splice(f,1,b):(null!=d.end&&(d.end=c),this._inventory.splice(f+1,0,b));return}}(e=this._inventory[0])?null==a.end?e.start===c?this._inventory.splice(0,1,b):this._inventory.splice(0,0,b):e.start>=a.end?this._inventory.splice(0,0,b):e.end<=a.end?this._inventory.splice(0,1,b):(e.start=a.end,this._inventory.splice(0,0,b)):this._inventory.push(b)}};c.prototype.hasCompleteSegment=function(a,c,b){for(var e=this._inventory,f=e.length- 1;0<=f;f--){var d=e[f],k=d.segment,m=a,l=c;k.timescale!==b&&(m=a*k.timescale/b,l=c*k.timescale/b);if(k.time===m&&k.duration===l){if((a=e[f-1])&&null==a.bufferedEnd||null==d.bufferedStart)break;if((!a||a.bufferedEnd<d.bufferedStart)&&d.bufferedStart-d.start>g)break;if((e=e[f+1])&&null==e.bufferedStart||null==d.bufferedEnd)break;if(null!=d.end&&(!e||e.bufferedStart>d.bufferedEnd)&&d.end-d.bufferedEnd>g)break;return d}}return null};return c}();d.a=b},function(b,d,a){a.d(d,"a",function(){return h});var h= {expired:!0,"internal-error":!0}},function(b,d,a){function h(b){var e=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},f=e.$keySystem,d=e.$mediaKeys,k=e.$mediaKeySystemConfiguration;return f&&d&&!a.i(c.e)()?(e=b.filter(function(a){return a.type!==f.type||a.persistentLicense&&"required"!=k.persistentState||a.distinctiveIdentifierRequired&&"required"!=k.distinctiveIdentifier?!1:!0})[0])?{keySystem:e,keySystemAccess:new c.f(f,d,k)}:null:null}function l(a){var c=["temporary"],b="optional",e= "optional";a.persistentLicense&&(b="required",c.push("persistent-license"));a.persistentStateRequired&&(b="required");a.distinctiveIdentifierRequired&&(e="required");var f=a.audioRobustnesses||m;a=(a.videoRobustnesses||m).map(function(a){return{contentType:'video/mp4;codecs="avc1.4d401e"',robustness:a}});f=f.map(function(a){return{contentType:'audio/mp4;codecs="mp4a.40.2"',robustness:a}});return[{initDataTypes:["cenc"],videoCapabilities:a,audioCapabilities:f,distinctiveIdentifier:e,persistentState:b, sessionTypes:c},{initDataTypes:["cenc"],videoCapabilities:void 0,audioCapabilities:void 0,distinctiveIdentifier:e,persistentState:b,sessionTypes:c}]}function g(){var a=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};return a.$keySystem&&a.$keySystem.type}a.d(d,"b",function(){return g});var k=a(0);a.n(k);b=a(4);var f=a(1),c=a(7),e=a(6),m=b.a.EME_DEFAULT_WIDEVINE_ROBUSTNESSES,n=b.a.EME_KEY_SYSTEMS;d.a=function(b,d){if(d=h(b,d))return f.a.debug("eme: found compatible keySystem quickly",d), k.Observable.of(d);var g=b.reduce(function(a,c){return a.concat((n[c.type]||[]).map(function(a){return{keyType:a,keySystem:c}}))},[]);return k.Observable.create(function(b){function d(h){if(!k)if(h>=g.length)b.error(new e.c("INCOMPATIBLE_KEYSYSTEMS",null,!0));else{var n=g[h],q=n.keyType,r=n.keySystem,p=l(r);f.a.debug("eme: request keysystem access "+q+","+(h+1+" of "+g.length),p);m=a.i(c.g)(q,p).subscribe(function(a){f.a.info("eme: found compatible keysystem",q,p);b.next({keySystem:r,keySystemAccess:a}); b.complete()},function(){f.a.debug("eme: rejected access to keysystem",q,p);m=null;d(h+1)})}}var k=!1,m=null;d(0);return function(){k=!0;m&&m.unsubscribe()}})}},function(b,d,a){function h(c,b){return g.Observable.defer(function(){return a.i(k.a)(c.setServerCertificate(b)).ignoreElements().catch(function(a){throw new f.c("LICENSE_SERVER_CERTIFICATE_ERROR",a,!0);})})}function l(a,b,f){return h(a,b).catch(function(a){a.fatal=!1;f.next(a);return g.Observable.empty()})}a.d(d,"a",function(){return l}); var g=a(0);a.n(g);var k=a(9),f=a(6)},function(b,d,a){function h(a,c,b){return{type:"eme",value:e()({name:a,session:c},b)}}function l(c,b,e){function f(a,c){return a.type===u.a.ENCRYPTED_MEDIA_ERROR?(a.fatal=c,a):new u.c("KEY_LOAD_ERROR",a,c)}x.a.debug("eme: handle message events",c);var d=void 0,k={totalRetry:2,retryDelay:200,errorSelector:function(a){return f(a,!0)},onRetry:function(a){return e.next(f(a,!1))}},g=a.i(t.h)(c).map(function(a){throw new u.c("KEY_ERROR",a,!0);}),l=a.i(t.j)(c).mergeMap(function(e){d= e.sessionId;x.a.debug("eme: keystatuseschange event",d,c,e);c.keyStatuses.forEach(function(a,c){if(w.a[c]||w.a[a])throw new u.c("KEY_STATUS_CHANGE_ERROR",c,!0);});return b.onKeyStatusesChange?a.i(q.a)(function(){return a.i(r.a)(b.onKeyStatusesChange(e,c))}).catch(function(a){throw new u.c("KEY_STATUS_CHANGE_ERROR",a,!0);}):(x.a.info("eme: keystatuseschange event not handled"),m.Observable.empty())}),v=a.i(t.i)(c).mergeMap(function(e){d=e.sessionId;var f=new Uint8Array(e.message),g=e.messageType|| "license-request";x.a.debug("eme: event message type "+g,c,e);e=m.Observable.defer(function(){return a.i(r.a)(b.getLicense(f,g)).timeout(1E4).catch(function(a){if(a instanceof n.TimeoutError)throw new u.c("KEY_LOAD_TIMEOUT",null,!1);throw a;})});return a.i(p.a)(e,k)});l=m.Observable.merge(v,l).concatMap(function(b){x.a.debug("eme: update session",d,b);return a.i(r.a)(c.update(b,d)).catch(function(a){throw new u.c("KEY_UPDATE_ERROR",a,!0);}).mapTo(h("session-update",c,{updatedWith:b}))});g=m.Observable.merge(l, g);return c.closed?g.takeUntil(a.i(r.a)(c.closed)):g}function g(a,c,b,e,f){x.a.debug("eme: create a new "+c+" session");var d=a.createSession(c);a=l(d,b,f).finally(function(){v.b.deleteAndClose(d);v.a.delete(e)}).publish();return{session:d,sessionEvents:a}}function k(c,b,e,f,d,k){c=g(c,e,b,d,k);var l=c.session;c=c.sessionEvents;v.b.add(d,l,c);x.a.debug("eme: generate request",f,d);f=a.i(r.a)(l.generateRequest(f,d)).catch(function(a){throw new u.c("KEY_GENERATE_REQUEST_ERROR",a,!1);}).do(function(){"persistent-license"== e&&v.a.add(d,l)}).mapTo(h("generated-request",l,{initData:d,initDataType:f}));return m.Observable.merge(c,f)}function f(a,c,b,e,f,d){return k(a,c,b,e,f,d).catch(function(g){if(g.code!==u.b.KEY_GENERATE_REQUEST_ERROR)throw g;var l=v.b.getFirst();if(!l)throw g;x.a.warn("eme: could not create a new session, retry after closing a currently loaded session",g);return v.b.deleteAndClose(l).mergeMap(function(){return k(a,c,b,e,f,d)})})}function c(c,b,e,d,k,l){x.a.debug("eme: load persisted session",e);var n= g(c,"persistent-license",b,k,l),q=n.session,p=n.sessionEvents;return a.i(r.a)(q.load(e)).catch(function(){return m.Observable.of(!1)}).mergeMap(function(a){if(a)return v.b.add(k,q,p),v.a.add(k,q),p.startWith(h("loaded-session",q,{storedSessionId:e}));x.a.warn("eme: no data stored for the loaded session, do fallback",e);v.b.deleteById(e);v.a.delete(k);q.sessionId&&q.remove();return f(c,b,"persistent-license",d,k,l).startWith(h("loaded-session-failed",q,{storedSessionId:e}))})}b=a(8);var e=a.n(b),m= a(0);a.n(m);var n=a(80);a.n(n);var q=a(42),r=a(9),p=a(70),t=a(17),u=a(6),w=a(108),x=a(1),v=a(36);d.a=function(a,b,e,d,k,g){return m.Observable.defer(function(){var l=v.b.get(k);if(l&&l.sessionId)return x.a.debug("eme: reuse loaded session",l.sessionId),m.Observable.of(h("reuse-session",l));var n=(l=b.sessionTypes)&&0<=l.indexOf("persistent-license");l=n&&e.persistentLicense?"persistent-license":"temporary";return n&&e.persistentLicense&&(n=v.a.get(k))?c(a,e,n.sessionId,d,k,g):f(a,e,l,d,k,g)})}},function(b, d,a){function h(a,b){if("function"!==typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}var l=a(0);a.n(l);var g=a(1),k=a(9);b=a(58);var f=a(59);b=function(c){function b(){if(!(this instanceof b))throw new TypeError("Cannot call a class as a function");var a=c.apply(this, arguments);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!a||"object"!==typeof a&&"function"!==typeof a?this:a}h(b,c);b.prototype.getFirst=function(){if(0<this._entries.length)return this._entries[0].session};b.prototype.find=function(a){for(var c=0;c<this._entries.length;c++)if(!0===a(this._entries[c]))return this._entries[c];return null};b.prototype.get=function(c){c=a.i(f.a)(c);var b=this.find(function(a){return a.initData===c});return b?b.session: null};b.prototype.add=function(c,b,e){c=a.i(f.a)(c);var d=this.get(c);d&&this.deleteAndClose(d);e=e.connect();c={session:b,initData:c,eventSubscription:e};g.a.debug("eme-mem-store: add session",c);this._entries.push(c)};b.prototype.deleteById=function(a){var c=this.find(function(c){return c.session.sessionId===a});return c?this.delete(c.session):null};b.prototype.delete=function(a){var c=this.find(function(c){return c.session===a});if(!c)return null;var b=c.session,e=c.eventSubscription;g.a.debug("eme-mem-store: delete session", c);c=this._entries.indexOf(c);this._entries.splice(c,1);e.unsubscribe();return b};b.prototype.deleteAndClose=function(c){return(c=this.delete(c))?(g.a.debug("eme-mem-store: close session",c),a.i(k.a)(c.close()).catch(function(){return l.Observable.of(null)})):l.Observable.of(null)};b.prototype.dispose=function(){var a=this,c=this._entries.map(function(c){return a.deleteAndClose(c.session)});this._entries=[];return l.Observable.merge.apply(null,c)};return b}(b.a);d.a=b},function(b,d,a){var h=a(112), l=a(114);a.d(d,"b",function(){return h.a});a.d(d,"a",function(){return l.a})},function(b,d,a){function h(a,c){if("function"!==typeof c&&null!==c)throw new TypeError("Super expression must either be null or a function, not "+typeof c);a.prototype=Object.create(c&&c.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});c&&(Object.setPrototypeOf?Object.setPrototypeOf(a,c):a.__proto__=c)}var l=a(1),g=a(2);b=a(58);var k=a(59);b=function(b){function c(a){if(!(this instanceof c))throw new TypeError("Cannot call a class as a function"); var e=b.call(this);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");e=!e||"object"!==typeof e&&"function"!==typeof e?this:e;e.setStorage(a);return e}h(c,b);c.prototype.setStorage=function(c){if(this._storage!==c){a.i(g.a)(c,"no licenseStorage given for keySystem with persistentLicense");g.a.iface(c,"licenseStorage",{save:"function",load:"function"});this._storage=c;try{this._entries=this._storage.load(),a.i(g.a)(Array.isArray(this._entries))}catch(m){l.a.warn("eme-persitent-store: could not get entries from license storage", m),this.dispose()}}};c.prototype.get=function(c){c=a.i(k.a)(c);return this.find(function(a){return a.initData===c})||null};c.prototype.add=function(c,b){var e=b&&b.sessionId;if(e){c=a.i(k.a)(c);var f=this.get(c);f&&f.sessionId===e||(f&&this.delete(c),l.a.info("eme-persitent-store: add new session",e,b),this._entries.push({sessionId:e,initData:c}),this._save())}};c.prototype.delete=function(c){c=a.i(k.a)(c);var b=this.find(function(a){return a.initData===c});b&&(l.a.warn("eme-persitent-store: delete session from store", b),b=this._entries.indexOf(b),this._entries.splice(b,1),this._save())};c.prototype.dispose=function(){this._entries=[];this._save()};c.prototype._save=function(){try{this._storage.save(this._entries)}catch(e){l.a.warn("eme-persitent-store: could not save licenses in localStorage")}};return c}(b.a);d.a=b},function(b,d,a){function h(c){return c?a.i(k.h)(c,null):l.Observable.empty()}a.d(d,"b",function(){return h});var l=a(0);a.n(l);var g=a(1),k=a(7),f=a(36);d.a=function(c,b,d,h,q){return l.Observable.defer(function(){var e= q.$videoElement,m=q.$mediaKeys;q.$mediaKeys=c;q.$mediaKeySystemConfiguration=b;q.$keySystem=h;q.$videoElement=d;if(d.mediaKeys===c)return l.Observable.of(c);m&&m!==c&&f.b.dispose();e&&e!==d?(g.a.debug("eme: unlink old video element and set mediakeys"),e=a.i(k.h)(e,null).concat(a.i(k.h)(d,c))):(g.a.debug("eme: set mediakeys"),e=a.i(k.h)(d,c));return e.mapTo(c)})}},function(b,d,a){function h(c){var b=a.i(t.a)(c.locations[0]);return(c=c.periods[0])&&c.baseURL?a.i(t.b)(b,c.baseURL):b}function l(a,c,b, f){if(!c.transportType)throw new w.f("MANIFEST_PARSE_ERROR",null,!0);c.id=c.id||"gen-manifest-"+B++;c.type=c.type||"static";c.isLive="dynamic"==c.type;var d=c.locations;d&&d.length||(c.locations=[a]);var k={rootURL:h(c),baseURL:c.baseURL,isLive:c.isLive};a=c.periods.map(function(a){return g(a,k,b,f)});c=e(c,a[0]);c.periods=null;c.duration||(c.duration=Infinity);c.isLive&&(c.suggestedPresentationDelay=c.suggestedPresentationDelay||0,c.availabilityStartTime=c.availabilityStartTime||0);return new v.a(c)} function g(a,b,e,d){"undefined"==typeof a.id&&(a.id="gen-period-"+B++);var g=a.adaptations.map(function(a){return k(a,b)});e&&g.push.apply(g,f(e).map(function(a){return k(a,b)}));d&&g.push.apply(g,c(d).map(function(a){return k(a,b)}));e=g.filter(function(a){return 0>C.indexOf(a.type)?(p.a.info("not supported adaptation type",a.type),!1):!0});if(0===e.length)throw new w.f("MANIFEST_PARSE_ERROR",null,!0);d={};for(g=0;g<e.length;g++){var l=e[g],h=l.representations,m=l.type;d[m]||(d[m]=[]);0<h.length&& d[m].push(l)}for(var n in d)if(0===d[n].length)throw new w.f("MANIFEST_INCOMPATIBLE_CODECS_ERROR",null,!0);a.adaptations=d;return a}function k(c,b){if("undefined"==typeof c.id)throw new w.f("MANIFEST_PARSE_ERROR",null,!0);var f=e(b,c),d={};z.forEach(function(a){a in f&&(d[a]=f[a])});c=f.representations.map(function(c){var b=f.rootURL,g=f.baseURL;if("undefined"==typeof c.id)throw new w.f("MANIFEST_PARSE_ERROR",null,!0);c=e(d,c);c.index=c.index||{};c.index.timescale||(c.index.timescale=1);c.bitrate|| (c.bitrate=1);"mp4a.40.02"==c.codecs&&(c.codecs="mp4a.40.2");c.baseURL=a.i(t.b)(b,g,c.baseURL);c.codec=c.codecs;return c}).sort(function(a,c){return a.bitrate-c.bitrate});b=f.type;var g=f.accessibility;g=void 0===g?[]:g;if(!b)throw new w.f("MANIFEST_PARSE_ERROR",null,!0);"video"==b||"audio"==b?(c=c.filter(function(c){return a.i(u.p)(n(c))}),"audio"===b&&(b=a.i(r.a)(g,"visuallyImpaired"),f.audioDescription=b)):"text"===b&&(b=a.i(r.a)(g,"hardOfHearing"),f.closedCaption=b);f.representations=c;f.bitrates= c.map(function(a){return a.bitrate});return f}function f(c){return(Array.isArray(c)?c:[c]).reduce(function(c,b){var e=b.mimeType,f=b.codecs,d=b.url,g=b.language,k=b.languages,l=b.closedCaption;g&&(k=[g]);return c.concat(k.map(function(c){return{id:"gen-text-ada-"+B++,type:"text",language:c,normalizedLanguage:a.i(x.a)(c),accessibility:l?["hardOfHearing"]:[],baseURL:d,representations:[{id:"gen-text-rep-"+B++,mimeType:e,codecs:f,index:{indexType:"template",duration:Number.MAX_VALUE,timescale:1,startNumber:0}}]}}))}, [])}function c(a){return(Array.isArray(a)?a:[a]).map(function(a){var c=a.mimeType;a=a.url;return{id:"gen-image-ada-"+B++,type:"image",baseURL:a,representations:[{id:"gen-image-rep-"+B++,mimeType:c,index:{indexType:"template",duration:Number.MAX_VALUE,timescale:1,startNumber:0}}]}})}function e(){for(var a={},c=arguments.length,b=Array(c),f=0;f<c;f++)b[f]=arguments[f];for(c=b.length-1;0<=c;c--){f=b[c];for(var d in f)if(!a.hasOwnProperty(d)){var g=f[d];g&&"object"===("undefined"===typeof g?"undefined": y(g))?g instanceof Date?a[d]=new Date(g.getTime()):Array.isArray(g)?a[d]=g.slice(0):a[d]=e(g):a[d]=g}}return a}function m(a,c){var b=function(a,c){return q()(c,function(c){return c.id===a})},e=a.getAdaptations();c=c.getAdaptations();for(var f=0;f<e.length;f++){var d=b(e[f].id,c);if(d){var g=e[f].representations;d=d.representations;for(var k=0;k<g.length;k++){var l=b(g[k].id,d);l?g[k].index.update(l.index):p.a.warn('manifest: representation "'+g[k].id+'" not found when merging.')}}else p.a.warn('manifest: adaptation "'+ e[f].id+'" not found when merging.')}return a}function n(a){return a.mimeType+';codecs="'+a.codec+'"'}a.d(d,"a",function(){return l});a.d(d,"c",function(){return n});a.d(d,"b",function(){return m});b=a(21);var q=a.n(b),r=a(19),p=a(1),t=a(24),u=a(7),w=a(6),x=a(30),v=a(140),y="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},z="audioSamplingRate codecs codingDependency frameRate height index maxPlayoutRate maximumSAPPeriod mimeType profiles segmentProfiles width".split(" "), B=0,C=["audio","video","text","image"]},function(b,d,a){var h=a(0);a.n(h);var l=a(6),g=a(7),k=a(69);d.a=function(b,c){var e=c.baseDelay,f=c.maxDelay,d=c.maxRetryRegular,q=c.maxRetryOffline,r=c.onRetry,p=0,t=0;return b.catch(function(c,b){var m=c instanceof l.h?c.type===l.j.ERROR_HTTP_CODE?500<=c.status||404==c.status:c.type===l.j.TIMEOUT||c.type===l.j.ERROR_EVENT:!1;if(!m)throw c;m=c.type===l.j.ERROR_EVENT&&a.i(g.q)()?2:1;var n=2===m?q:d;m!==t&&(p=0,t=m);if(++p>n)throw c;r&&r(c,p);c=Math.min(e*Math.pow(2, p-1),f);c=a.i(k.b)(c);return h.Observable.timer(c).mergeMap(function(){return b})})}},function(b,d,a){function h(c,b){var e=2<arguments.length&&void 0!==arguments[2]?arguments[2]:!0;a.i(f.d)(b)||(b=new (b instanceof f.h?f.i:f.e)(c,b,e));return b}d.a=function(b){var f=b.resolver,d=b.loader,v=b.parser,u=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},z=u.maxRetry,B=u.cache,C=new k.Subject;f||(f=g.Observable.of);d||(d=g.Observable.of);v||(v=g.Observable.of);var A={baseDelay:t,maxDelay:p,maxRetryRegular:"number"=== typeof z?z:q,maxRetryOffline:r,onRetry:function(a){C.next(h("PIPELINE_LOAD_ERROR",a,!1))}},H=function(c){return a.i(e.a)(f,c).catch(function(a){throw h("PIPELINE_RESOLVE_ERROR",a);})},E=function(c,b){var f=function(c){return a.i(n.a)(a.i(e.a)(d,c),A).catch(function(a){throw h("PIPELINE_LOAD_ERROR",a);}).do(function(a){var b=a.value;"response"===a.type&&B&&B.add(c,b)}).startWith({type:"request",value:b})},g=B?B.get(c):null;return null===g?f(c):a.i(m.a)(g).map(function(a){return{type:"cache",value:a}}).catch(function(){return f(c)})}, I=function(c){return a.i(e.a)(v,c).catch(function(a){throw h("PIPELINE_PARSING_ERROR",a);})};return function(b){var e=H(b).mergeMap(function(e){return E(e,b).mergeMap(function(b){var f=b.type;b=b.value;if(a.i(c.a)(["cache","data","response"],f)){var d=l()({response:b},e);return("response"===f?g.Observable.of({type:"metrics",value:{size:b.size,duration:b.duration}}):g.Observable.empty()).concat(I(d).map(function(a){return{type:"data",value:l()({parsed:a},d)}}))}return g.Observable.of({type:f,value:b})})}).do(null, null,function(){f.complete()}),f=C.map(function(a){return{type:"error",value:a}});return g.Observable.merge(e,f)}};b=a(8);var l=a.n(b),g=a(0);a.n(g);var k=a(5);a.n(k);b=a(4);var f=a(6),c=a(19),e=a(42),m=a(9),n=a(117),q=b.a.DEFAULT_MAX_PIPELINES_RETRY_ON_ERROR,r=b.a.DEFAULT_MAX_PIPELINES_RETRY_ON_OFFLINE,p=b.a.MAX_BACKOFF_DELAY_BASE,t=b.a.INITIAL_BACKOFF_DELAY_BASE},function(b,d,a){var h=a(6),l=a(1),g=a(57);d.a=function(b,f,c){return f&&f.length?a.i(g.c)(b,f,c):a.i(g.d)(b).map(function(){l.a.error("eme: ciphered media and no keySystem passed"); throw new h.c("MEDIA_IS_ENCRYPTED_ERROR",null,!0);})}},function(b,d,a){d.a=function(b){return a.i(l.a)(b,"error").mergeMap(function(){var a=void 0;switch(b.error.code){case 1:a="MEDIA_ERR_ABORTED";break;case 2:a="MEDIA_ERR_NETWORK";break;case 3:a="MEDIA_ERR_DECODE";break;case 4:a="MEDIA_ERR_SRC_NOT_SUPPORTED"}h.a.error("stream: video element MEDIA_ERR("+a+")");throw new MediaError(a,null,!0);})};var h=a(1),l=a(31)},function(b,d,a){d.a=function(b){function f(b,e,f,d,g,k,l,m){var n=D(e);return l.switchMap(function(l){if(!l)return a.i(y.a)(F, b,e,P,S),a.i(u.a)({bufferType:e}).startWith({type:"adaptationChange",value:{type:e,adaptation:l}});var q=null,r=R.map(function(a){var c=void 0,b=void 0;q&&(c=q.bitrate,q.index&&(b=q.index.getLastPosition()));return{bitrate:c,bufferGap:a.bufferGap,duration:a.duration,isLive:k.isLive,lastIndexPosition:b,position:a.currentTime,speed:U.getValue()}});r=m.get$(e,r,l.representations);var p=r.map(function(a){return a.representation}).distinctUntilChanged(function(a,c){return(a&&a.bitrate)===(c&&c.bitrate)&& (a&&a.id)===(c&&c.id)}).do(function(a){return q=a}),v=a.i(y.b)(F,b,e,f,P,S,{hideNativeSubtitle:ha});p=h.Observable.combineLatest(p,g).map(function(a){return a[0]});v=a.i(u.b)({sourceBuffer:v,downloader:function(c){var b=c.segment,f=c.representation;c=c.init;b=a.i(w.a)(V[e],n)({segment:b,representation:f,adaptation:l,manifest:k,init:c});return a.i(A.a)(e,b,X,Y,O)},switch$:p,clock$:d,wantedBufferAhead:ia,maxBufferBehind:ja,maxBufferAhead:ka,bufferType:e,isLive:k.isLive}).startWith({type:"adaptationChange", value:{type:e,adaptation:l}}).catch(function(b){c.a.error("buffer",e,"has crashed",b);if(!a.i(y.c)(e))return O.next(b),h.Observable.empty();throw b;});r=r.filter(function(a){return null!=a.bitrate}).map(function(a){return{type:"bitrateEstimationChange",value:{type:e,bitrate:a.bitrate}}});return h.Observable.merge(v,r)})}function d(b,e){var f=a.i(v.a)(b,ca),d=f;b=a.i(r.i)(F).do(function(){c.a.info("set initial time",f);F.playbackRate=1;F.currentTime=f;d=0});var g=a.i(r.j)(F).do(function(){c.a.info("canplay event"); T&&F.play();T=!0});return{clock$:e.map(function(a){return k()({timeOffset:d},a)}),loaded$:h.Observable.combineLatest(b,g).take(1).mapTo({type:"loaded",value:!0})}}function n(c){return Z(c.getUrl()).map(function(b){return{type:"manifestUpdate",value:{manifest:a.i(t.b)(c,b)}}})}function G(b,e){b&&a.i(z.a)(b,e.getDuration());var k=a.i(B.a)(e,R),l=k.timings,m=k.seekings,q=d(e,l);k=q.loaded$;var r=q.clock$,p=new x.a(Y,X,aa),v={};q=Object.keys(e.adaptations).map(function(c){v[c]=new g.ReplaySubject(1); var d=a.i(t.c)(e.adaptations[c][0].representations[0]);a.i(y.c)(c)&&a.i(y.d)(b,c,d,P);return f(b,c,d,r,m,e,v[c],p)});q=e.isLive?h.Observable.merge.apply(h.Observable,q).mergeMap(function(a){a:{switch(a.type){case "index-discontinuity":c.a.warn("explicit discontinuity seek",a.value.ts);F.currentTime=a.value.ts;break;case "precondition-failed":e.updateLiveGap(1);c.a.warn("precondition failed",e.presentationLiveGap);break;case "out-of-index":c.a.info("out of index");a=n(e);break a}a=h.Observable.of(a)}return a}): h.Observable.merge.apply(h.Observable,q);var w=h.Observable.of({type:"manifestChange",value:{manifest:e,adaptations$:v,abrManager:p}}),u=a.i(I.a)(F,ba,O),A=a.i(H.a)(F,U,l,{changePlaybackRate:K}).map(function(a){return{type:"speed",value:a}});l=a.i(E.a)(F,e,l).map(function(a){return{type:"stalled",value:a}});var D=a.i(C.a)(F);return h.Observable.merge(q,u,k,w,D,A,l).finally(function(){return p.dispose()})}var aa=b.adaptiveOptions,T=b.autoPlay,N=b.bufferOptions,ba=b.keySystems,ca=b.startAt,da=b.url, F=b.videoElement,U=b.speed$,ea=b.supplementaryTextTracks,fa=b.supplementaryImageTracks,R=b.timings$,ha=b.hideNativeSubtitle,O=b.errorStream,W=b.withMediaSource,K=void 0===W?!0:W,V=b.transport,ia=N.wantedBufferAhead$,ka=N.maxBufferAhead$,ja=N.maxBufferBehind$,X=new l.Subject,Y=new l.Subject,la=a.i(w.a)(V.manifest),Z=a.i(m.a)(function(c){c=la({url:c});var b=new l.Subject;return a.i(A.a)("manifest",c,b,b,O).map(function(c){c=c.parsed;return a.i(t.a)(c.url,c.manifest,ea,fa)})}),P={},S={};b=R.filter(function(a){var c= a.currentTime;a=a.duration;return 0<a&&a-c<J});N=a.i(e.b)(function(c){var b=c.url,e=c.mediaSource;c=e?a.i(p.e)(e):h.Observable.of(null);return h.Observable.combineLatest(Z(b),c).mergeMap(function(a){return G(e,a[0])})},{totalRetry:3,retryDelay:250,resetDelay:6E4,shouldRetry:function(a){return!0!==a.fatal},errorSelector:function(c){a.i(q.d)(c)||(c=new q.e("NONE",c,!0));c.fatal=!0;return c},onRetry:function(a,b){c.a.warn("stream retry",a,b);O.next(a)}});return a.i(z.b)(da,F,K,S,P).mergeMap(N).takeUntil(b)}; var h=a(0);a.n(h);var l=a(5);a.n(l);var g=a(174);a.n(g);b=a(8);var k=a.n(b);b=a(4);var f=a(19),c=a(1);a(2);var e=a(70),m=a(166),n=a(162),q=a(6),r=a(7),p=a(17),t=a(116),u=a(105),w=a(118),x=a(95),v=a(122),y=a(126),z=a(123),B=a(131),C=a(120),A=a(124),H=a(129),E=a(130),I=a(119),J=b.a.END_OF_PLAY,D=function(c){var b={};a.i(f.a)(["audio","video"],c)?b.cache=new n.a:"image"===c&&(b.maxRetry=0);return b}},function(b,d,a){d.a=function(b,d){if(d){var f=a.i(h.e)(b),c=f[0];f=f[1];if(null!=d.position)return Math.max(Math.min(d.position, f),c);if(null!=d.wallClockTime)return Math.max(Math.min(b.isLive?d.wallClockTime-b.availabilityStartTime:d.wallClockTime,f),c);if(null!=d.fromFirstPosition)return b=d.fromFirstPosition,0>=b?c:Math.min(c+b,f);if(null!=d.fromLastPosition)return b=d.fromLastPosition,0<=b?f:Math.max(c,f+b)}return b.isLive?(c=b.suggestedPresentationDelay,a.i(h.d)(b)-(null==c?l:c)):0};b=a(4);var h=a(28),l=b.a.DEFAULT_LIVE_GAP},function(b,d,a){a.d(d,"b",function(){return f});a.d(d,"a",function(){return k});var h=a(0);a.n(h); var l=a(1),g=a(7),k=function(a,b){b=Infinity===b?Number.MAX_VALUE:b;a.duration!==b&&(a.duration=b,l.a.info("set duration",a.duration))},f=function(c,b,f,d,k){return h.Observable.create(function(e){function h(){if(m&&"closed"!=m.readyState){var c=m,e=c.readyState;c=c.sourceBuffers;for(var f=0;f<c.length;f++){var h=c[f];try{"open"==e&&h.abort(),m.removeSourceBuffer(h)}catch(z){l.a.warn("error while disposing souceBuffer",z)}}}Object.keys(k).forEach(function(a){delete k[a]});Object.keys(d).forEach(function(a){var c= d[a];try{c.abort()}catch(C){l.a.warn("error while disposing souceBuffer",C)}delete d[a]});a.i(g.k)(b);if(n)try{URL.revokeObjectURL(n)}catch(z){l.a.warn("error while revoking ObjectURL",z)}n=m=null}var m=void 0,n=void 0;h();if(f){if(!g.l)throw new MediaError("MEDIA_SOURCE_NOT_SUPPORTED",null,!0);m=new g.l;n=URL.createObjectURL(m)}else m=null,n=c;b.src=n;e.next({url:c,mediaSource:m});l.a.info("create mediasource object",n);return h})}},function(b,d,a){d.a=function(a,b,d,f,c){var e=void 0,g=void 0;return b.filter(function(b){var k= b.type;b=b.value;if("data"===k)return!0;if("error"===k)b.pipelineType=a,c.next(b);else if("manifest"!==a)if("metrics"===k)d.next({type:a,value:b});else if("request"===k){if(k=b&&b.segment,null!=k){b=k.duration/k.timescale;var l=k.time/k.timescale;g=k.id;k={duration:isNaN(b)?void 0:b,time:isNaN(l)?void 0:l,requestTimestamp:Date.now(),id:g};e=new h.Subject;f.next(e);e.next({type:a,event:"requestBegin",value:k})}}else"progress"===k&&b.size!==b.totalSize&&(k={duration:b.duration,size:b.size,totalSize:b.totalSize, timestamp:Date.now(),id:g},e.next({type:a,event:"progress",value:k}))}).map(function(a){return a.value}).finally(function(){e&&(null!=g&&e.next({type:a,event:"requestEnd",value:{id:g}}),e.complete())}).share()};var h=a(5);a.n(h)},function(b,d,a){function h(a,b){if("function"!==typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});b&&(Object.setPrototypeOf? Object.setPrototypeOf(a,b):a.__proto__=b)}b=function(a){function b(){if(!(this instanceof b))throw new TypeError("Cannot call a class as a function");var d=a.apply(this,arguments);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!d||"object"!==typeof d&&"function"!==typeof d?this:d}h(b,a);b.prototype._append=function(){this.buffered.insert(0,Number.MAX_VALUE)};return b}(a(60).a);d.a=b},function(b,d,a){a.d(d,"c",function(){return k});a.d(d,"d",function(){return f}); a.d(d,"b",function(){return c});a.d(d,"a",function(){return e});var h=a(1),l=a(127),g=a(125),k=function(a){return"audio"==a||"video"==a},f=function(a,c,b,e){e[c]||(h.a.info("add sourcebuffer",b),e[c]=a.addSourceBuffer(b));return e[c]},c=function(a,c,b,e,d,t){var m=6<arguments.length&&void 0!==arguments[6]?arguments[6]:{};if(k(b))m=f(c,b,e,d);else{var n=t[b];if(n)try{n.abort()}catch(x){h.a.warn(x)}finally{delete t[b]}if("text"==b)h.a.info("add text sourcebuffer",e),m=new l.a(a,e,m.hideNativeSubtitle); else if("image"==b)h.a.info("add image sourcebuffer",e),m=new g.a(e);else throw h.a.error("unknown buffer type "+b),new MediaError("BUFFER_TYPE_UNKNOWN",null,!0);t[b]=m}return m},e=function(a,c,b,e,f){var d=k(b);d?(a=e[b],delete e[b]):(a=f[b],delete f[b]);if(a)try{a.abort(),d&&c.removeSourceBuffer(a)}catch(u){h.a.warn(u)}}},function(b,d,a){function h(a,b){if("function"!==typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&& b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function l(a){for(var c=[],b=0;b<a.length;b++){var d=a[b],g=d.start,k=d.end;(d=d.text)&&c.push(new f(g,k,d))}return c}b=a(60);var g=a(7),k=a(1),f=window.VTTCue||window.TextTrackCue;b=function(c){function b(e,f,d){if(!(this instanceof b))throw new TypeError("Cannot call a class as a function");var k=c.call(this,f);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); k=!k||"object"!==typeof k&&"function"!==typeof k?this:k;var l=a.i(g.n)(e,d);d=l.track;l=l.trackElement;k._videoElement=e;k._isVtt=/^text\/vtt/.test(f);k._track=d;k._trackElement=l;return k}h(b,c);b.prototype._append=function(c){var b=this,e=c.timescale,f=c.start,d=c.end;c=c.data;if(!(0>=d-f))if(f/=e,e=null!=d?d/e:void 0,this._isVtt)a.i(g.o)()&&this._trackElement?(d=new Blob([c],{type:"text/vtt"}),d=URL.createObjectURL(d),this._trackElement.src=d,this.buffered.insert(f,null!=e?e:Number.MAX_VALUE)): k.a.warn("vtt subtitles not supported");else if(d=l(c),0<d.length){c=d[0];var h=this._track.cues;0<h.length&&c.startTime<h[h.length-1].startTime&&this._remove(c.startTime,Infinity);d.forEach(function(a){return b._track.addCue(a)});this.buffered.insert(f,null!=e?e:d[d.length-1].endTime)}};b.prototype._remove=function(a,c){for(var b=this._track,e=b.cues,f=e.length-1;0<=f;f--){var d=e[f],k=d.startTime,g=d.endTime;k>=a&&k<=c&&g<=c&&b.removeCue(d)}this.buffered.remove(a,c)};b.prototype._abort=function(){var a= this._trackElement,c=this._videoElement;a&&c&&c.hasChildNodes(a)&&c.removeChild(a);this._track.mode="disabled";this.size=0;this._videoElement=this._track=this._trackElement=null};return b}(b.a);d.a=b},function(b,d,a){a(2);var h=a(10);b=function(){function b(){if(!(this instanceof b))throw new TypeError("Cannot call a class as a function");this._ranges=[];this.length=0}b.prototype.insert=function(b,d){a.i(h.e)(this._ranges,{start:b,end:d});this.length=this._ranges.length};b.prototype.remove=function(b, d){var f=[];0<b&&f.push({start:0,end:b});Infinity>d&&f.push({start:d,end:Infinity});a.i(h.f)(this._ranges,f);this.length=this._ranges.length};b.prototype.start=function(a){if(a>=this._ranges.length)throw Error("INDEX_SIZE_ERROR");return this._ranges[a].start};b.prototype.end=function(a){if(a>=this._ranges.length)throw Error("INDEX_SIZE_ERROR");return this._ranges[a].end};return b}();d.a=b},function(b,d,a){var h=a(0);a.n(h);var l=a(1);d.a=function(a,b,f,c){c=c.pauseWhenStalled;var e=void 0;e=void 0=== c||c?f.pairwise().map(function(a){var c=a[1].stalled;a=a[0].stalled;if(!a!==!c||a&&c&&a.state!==c.state)return!a}).filter(function(a){return null!=a}).startWith(!1):h.Observable.of(!1).concat(h.Observable.never());return e.switchMap(function(c){return c?h.Observable.defer(function(){l.a.info("pause playback to build buffer");a.playbackRate=0;return h.Observable.of(0)}):b.do(function(c){l.a.info("resume playback speed",c);a.playbackRate=c})})}},function(b,d,a){b=a(4);var h=a(1),l=a(10),g=a(7),k=b.a.DISCONTINUITY_THRESHOLD; d.a=function(b,c,e){return e.do(function(c){if(c.stalled){var e=c.buffered,f=c.currentTime;e=a.i(l.d)(e,f);a.i(g.m)(c)?(h.a.warn("after freeze seek",f,c.range),b.currentTime=f):e<k&&(c=f+e+1/60,h.a.warn("discontinuity seek",f,e,c),b.currentTime=c)}}).share().map(function(a){return a.stalled}).distinctUntilChanged(function(a,c){return!a&&!c||a&&c&&a.state===c.state})}},function(b,d,a){function h(a){return a.filter(function(a){return"seeking"==a.state&&(Infinity===a.bufferGap||-2>a.bufferGap)}).skip(1).startWith(!0)} b=a(8);var l=a.n(b),g=a(28);d.a=function(b,f){f=f.map(function(c){var e=l()({},c);e.liveGap=b.isLive?a.i(g.d)(b)-c.currentTime:Infinity;return e});var c=h(f);return{timings:f,seekings:c}}},function(b,d,a){function h(b,f,c){this.name="EncryptedMediaError";this.type=l.a.ENCRYPTED_MEDIA_ERROR;this.reason=f;this.code=l.b[b];this.fatal=c;this.message=a.i(g.a)(this.name,this.code,this.reason)}var l=a(18),g=a(22);h.prototype=Error();d.a=h},function(b,d,a){function h(b,f,c){this.name="IndexError";this.type= l.a.INDEX_ERROR;this.indexType=f;this.reason=null;this.code=l.b[b];this.fatal=c;this.message=a.i(g.a)(this.name,this.code,null)}var l=a(18),g=a(22);h.prototype=Error();d.a=h},function(b,d,a){function h(b,f,c){this.name="MediaError";this.type=l.a.MEDIA_ERROR;this.reason=f;this.code=l.b[b];this.fatal=c;this.message=a.i(g.a)(this.name,this.code,this.reason)}var l=a(18),g=a(22);h.prototype=Error();d.a=h},function(b,d,a){function h(b,f,c){this.name="NetworkError";this.type=l.a.NETWORK_ERROR;this.xhr=f.xhr; this.url=f.url;this.status=f.status;this.reqType=f.type;this.reason=f;this.code=l.b[b];this.fatal=c;this.reason?this.message=a.i(g.a)(this.name,this.code,this.reason):(b=""+this.reqType+(0<this.status?"("+this.status+")":"")+" on "+this.url,this.message=a.i(g.a)(this.name,this.code,{message:b}))}var l=a(18),g=a(22);h.prototype=Error();h.prototype.isHttpError=function(a){return this.reqType==l.c.ERROR_HTTP_CODE&&this.status==a};d.a=h},function(b,d,a){function h(b,f,c){this.name="OtherError";this.type= l.a.OTHER_ERROR;this.reason=f;this.code=l.b[b];this.fatal=c;this.message=a.i(g.a)(this.name,this.code,this.reason)}var l=a(18),g=a(22);h.prototype=Error();d.a=h},function(b,d,a){function h(a,b,d){this.name="RequestError";this.url=b;this.xhr=a;this.status=a.status;this.message=this.type=d}h.prototype=Error();d.a=h},function(b,d,a){b.exports=a(87).default},function(b,d,a){b=a(8);var h=a.n(b);b=a(21);var l=a.n(b),g=a(146),k=a(40);b=function(){function b(){var c=this,e=0<arguments.length&&void 0!==arguments[0]? arguments[0]:{};if(!(this instanceof b))throw new TypeError("Cannot call a class as a function");var f=a.i(k.a)();this.id=null==e.id?f:""+e.id;this.type=e.type||"";this.representations=Array.isArray(e.representations)?e.representations.map(function(a){return new g.a(h()({rootId:c.id},a))}).sort(function(a,c){return a.bitrate-c.bitrate}):[];null!=e.language&&(this.language=e.language);null!=e.normalizedLanguage&&(this.normalizedLanguage=e.normalizedLanguage);null!=e.closedCaption&&(this.isClosedCaption= e.closedCaption);null!=e.audioDescription&&(this.isAudioDescription=e.audioDescription);null!=e.contentProtection&&(this.contentProtection=e.contentProtection);null!=e.smoothProtection&&(this._smoothProtection=e.smoothProtection);this.manual=e.manual}b.prototype.getAvailableBitrates=function(){return this.representations.map(function(a){return a.bitrate})};b.prototype.getRepresentation=function(a){return l()(this.representations,function(c){return a===c.id})};b.prototype.getRepresentationsForBitrate= function(a){return this.representations.filter(function(c){return c.bitrate===a})||null};return b}();d.a=b},function(b,d,a){b=a(21);var h=a.n(b),l=a(139),g=a(40);b=function(){function b(){var f=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};if(!(this instanceof b))throw new TypeError("Cannot call a class as a function");var c=a.i(g.a)();this.id=null==f.id?c:""+f.id;this.transport=f.transportType||"";this.adaptations=f.adaptations?Object.keys(f.adaptations).reduce(function(a,c){a[c]=f.adaptations[c].map(function(a){return new l.a(a)}); return a},{}):[];this.periods=[{adaptations:this.adaptations}];this.isLive="dynamic"===f.type;this.uris=f.locations||[];this._duration=f.duration;this.suggestedPresentationDelay=f.suggestedPresentationDelay;this.availabilityStartTime=f.availabilityStartTime;this.presentationLiveGap=f.presentationLiveGap;this.timeShiftBufferDepth=f.timeShiftBufferDepth}b.prototype.getDuration=function(){return this._duration};b.prototype.getUrl=function(){return this.uris[0]};b.prototype.getAdaptations=function(){var a= this.adaptations;if(!a)return[];var c=[],b;for(b in a)c.push.apply(c,a[b]);return c};b.prototype.getAdaptation=function(a){return h()(this.getAdaptations(),function(c){return a===c.id})};b.prototype.updateLiveGap=function(a){this.isLive&&(this.presentationLiveGap+=a)};return b}();d.a=b},function(b,d,a){Object.defineProperty(d,"__esModule",{value:!0});b=a(8);b=a.n(b);var h=a(37);a=a(23);d["default"]=b()({},h["default"],{getInitSegment:a.a,setTimescale:a.b,scale:a.c,_addSegmentInfos:function(a,b){if(b.timescale!== a.timescale){var d=a.timescale;a.timeline.push({ts:b.time/b.timescale*d,d:b.duration/b.timescale*d,r:b.count,range:b.range})}else a.timeline.push({ts:b.time,d:b.duration,r:b.count,range:b.range});return!0},shouldRefresh:function(){return!1}})},function(b,d,a){var h={};h.smooth=a(144).default;h.timeline=a(37).default;h.template=a(145).default;h.list=a(143).default;h.base=a(141).default;d.a=function(a){return h[a.indexType]}},function(b,d,a){Object.defineProperty(d,"__esModule",{value:!0});var h=a(27), l=a(23);d["default"]={getInitSegment:l.a,setTimescale:l.b,scale:l.c,getSegments:function(b,d,f,c){var e=a.i(l.d)(d,f,c);f=d.duration;c=d.list;d=d.timescale;var g=Math.min(c.length-1,Math.floor(e.to/f)),k=[];for(e=Math.floor(e.up/f);e<=g;)k.push(new h.a({id:""+b+"_"+e,time:e*f,init:!1,range:c[e].range,duration:f,indexRange:null,timescale:d,media:c[e].media})),e++;return k},getFirstPosition:function(){return 0},getLastPosition:function(a){return a.list.length*a.duration/a.timescale},shouldRefresh:function(a, b,f,c){b=a.list;f=a.presentationTimeOffset;a=Math.floor((c*a.timescale-(void 0===f?0:f))/a.duration);return!(0<=a&&a<b.length)},_addSegmentInfos:function(){return!1},checkDiscontinuity:function(){return-1}}},function(b,d,a){Object.defineProperty(d,"__esModule",{value:!0});b=a(37);var h=a(23);d["default"]={getSegments:b["default"].getSegments,getInitSegment:h.a,checkDiscontinuity:b["default"].checkDiscontinuity,_addSegmentInfos:b["default"]._addSegmentInfos,setTimescale:h.b,scale:h.c,shouldRefresh:function(b, d,k,f){var c=b.timeline;k=b.timescale;b=b.presentationTimeOffset;b=void 0===b?0:b;d=d*k-b;c=c[c.length-1];if(!c)return!1;0>c.d&&(c={ts:c.ts,d:0,r:c.r});c=a.i(h.e)(c);return 1>=(c-d)/k&&f*k-b>c},getFirstPosition:function(a){if(a.timeline.length)return a.timeline[0].ts/a.timescale},getLastPosition:function(b){if(b.timeline.length){var d=b.timeline[b.timeline.length-1];return a.i(h.e)(d)/b.timescale}}}},function(b,d,a){Object.defineProperty(d,"__esModule",{value:!0});var h=a(27),l=a(23);d["default"]= {getInitSegment:l.a,setTimescale:l.b,scale:l.c,getSegments:function(b,d,f,c){var e=a.i(l.d)(d,f,c);f=e.to;c=d.duration;var k=d.startNumber,g=d.timescale;d=d.media;var q=[];for(e=e.up;e<=f;e+=c){var r=Math.floor(e/c)+(null==k?1:k);q.push(new h.a({id:""+b+"_"+r,number:r,time:r*c,init:!1,duration:c,range:null,indexRange:null,timescale:g,media:d}))}return q},getFirstPosition:function(){},getLastPosition:function(){},shouldRefresh:function(){return!1},checkDiscontinuity:function(){return-1},_addSegmentInfos:function(){return!1}}}, function(b,d,a){var h=a(40),l=a(147);d.a=function k(){var b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};if(!(this instanceof k))throw new TypeError("Cannot call a class as a function");var c=a.i(h.a)();this.id=null==b.id?c:b.id;this.bitrate=b.bitrate;this.codec=b.codecs;null!=b.height&&(this.height=b.height);null!=b.width&&(this.width=b.width);null!=b.mimeType&&(this.mimeType=b.mimeType);this.index=new l.a({index:b.index,rootId:this.id});this.baseURL=b.baseURL;null!=b.codecPrivateData&& (this._codecPrivateData=b.codecPrivateData);null!=b.channels&&(this._channels=b.channels);null!=b.bitsPerSample&&(this._bitsPerSample=b.bitsPerSample);null!=b.packetSize&&(this._packetSize=b.packetSize);null!=b.samplingRate&&(this._samplingRate=b.samplingRate)}},function(b,d,a){var h=a(142);b=function(){function b(d){if(!(this instanceof b))throw new TypeError("Cannot call a class as a function");this._index=d.index;this._rootId=d.rootId;this._indexHelpers=a.i(h.a)(this._index)}b.prototype.getInitSegment= function(){return this._indexHelpers.getInitSegment(this._rootId,this._index)};b.prototype.getSegments=function(a,b){return this._indexHelpers.getSegments(this._rootId,this._index,a,b)};b.prototype.shouldRefresh=function(a,b,f){return this._indexHelpers.shouldRefresh(this._index,a,b,f)};b.prototype.getFirstPosition=function(){return this._indexHelpers.getFirstPosition(this._index)};b.prototype.getLastPosition=function(){return this._indexHelpers.getLastPosition(this._index)};b.prototype.checkDiscontinuity= function(a){return this._indexHelpers.checkDiscontinuity(this._index,a)};b.prototype.scale=function(a){return this._indexHelpers.scale(this._index,a)};b.prototype.setTimescale=function(a){return this._indexHelpers.setTimescale(this._index,a)};b.prototype._addSegments=function(a,b){for(var f=[],c=0;c<a.length;c++)this._indexHelpers._addSegmentInfos(this._index,a[c],b)&&f.push(a[c]);return f};b.prototype.update=function(a){this._index=a._index};b.prototype.getType=function(){return this._index.indexType|| ""};return b}();d.a=b},function(b,d,a){b={};b.smooth=a(157).default;b.dash=a(149).default;b.directfile=a(156).default;d.a=b},function(b,d,a){Object.defineProperty(d,"__esModule",{value:!0});var h=a(0);a.n(h);var l=a(1),g=a(24),k=a(13),f=a(38),c=a(62),e=a(63),m=a(61),n=a(153),q=a(150),r=a(65),p=a(66),t=a(155);d["default"]=function(){var b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},d=a.i(t.a)(b.segmentLoader),x=b.contentProtectionParser;x||(x=function(){});b={loader:function(a){return d({segment:a.segment, representation:a.representation,adaptation:a.adaptation,manifest:a.manifest})},parser:function(c){var b=c.segment,e=c.adaptation,d=c.init;c=new Uint8Array(c.response.responseData);var k=void 0,g=c,l=b.indexRange;(l=a.i(f.a)(c,l?l[0]:0))&&(k=l);b.isInit?(b={time:-1,duration:0},d=a.i(f.b)(c),0<d&&(b.timescale=d),e.contentProtection&&(g=a.i(f.c)(c,e.contentProtection))):b=a.i(q.a)(b,c,l,d);return h.Observable.of({segmentData:g,segmentInfos:b,nextSegments:k})}};return{directFile:!1,manifest:{loader:function(c){c= c.url;return a.i(r.a)({url:c,responseType:"document"})},parser:function(c){c=c.response;var b=c.responseData;return h.Observable.of({manifest:a.i(n.a)(b,x),url:c.url})}},audio:b,video:b,text:{loader:function(c){var b=c.segment,e=c.representation,f=b.media,d=b.range;c=b.indexRange;var k=b.isInit,l=a.i(p.a)(e)?"arraybuffer":"text";if(k&&!(f||d||c))return h.Observable.empty();b=f?a.i(p.b)(f,b,e):"";b=a.i(g.b)(e.baseURL,b);if(d&&c&&d[1]===c[0]-1)return a.i(r.a)({url:b,responseType:l,headers:{Range:a.i(p.c)([d[0], c[1]])}});d=a.i(r.a)({url:b,responseType:l,headers:d?{Range:a.i(p.c)(d)}:null});return c?(c=a.i(r.a)({url:b,responseType:l,headers:{Range:a.i(p.c)(c)}}),h.Observable.merge(d,c)):d},parser:function(b){var d=b.response,g=b.segment,m=b.representation,n=b.init,r=b.adaptation.language,v=g.isInit,w=g.indexRange,t=b=void 0,u=void 0,x=a.i(p.a)(m);if(x){var G=new Uint8Array(d.responseData);d=a.i(k.a)(a.i(f.d)(G));(w=a.i(f.a)(G,w?w[0]:0))&&(b=w);v||(t=a.i(q.a)(g,G,w,n))}else G=d=d.responseData,t={time:g.time, duration:g.duration,timescale:g.timescale};if(v)t={time:-1,duration:0},x&&(g=a.i(f.b)(G),0<g&&(t.timescale=g)),u={start:0,end:0,timescale:t.timescale||0,data:[]};else if(x)switch(g=m.codec,(void 0===g?"":g).toLowerCase()){case "stpp":u={start:t.time,end:t.time+t.duration,timescale:t.timescale,data:a.i(e.a)(d,r,0)};break;default:l.a.warn("The codec used for the subtitle is not managed yet.")}else switch(m.mimeType){case "application/ttml+xml":u={start:t.time,end:t.time+t.duration,timescale:t.timescale, data:a.i(e.a)(d,r,0)};break;case "application/x-sami":case "application/smil":u={start:t.time,end:t.time+t.duration,timescale:t.timescale,data:a.i(c.a)(d,r,0)};break;case "text/vtt":u={start:t.time,end:t.time+t.duration,timescale:t.timescale,data:d};break;default:l.a.warn("The codec used for the subtitle is not managed yet.")}return h.Observable.of({segmentData:u,segmentInfos:t,nextSegments:b})}},image:{loader:function(c){var b=c.segment;c=c.representation;if(b.isInit)return h.Observable.empty(); var e=b.media;b=e?a.i(p.b)(e,b,c):"";b=a.i(g.b)(c.baseURL,b);return a.i(r.a)({url:b,responseType:"arraybuffer"})},parser:function(c){var b=new Uint8Array(c.response.responseData);c={time:0,duration:Number.MAX_VALUE};var e=void 0;b&&(b=a.i(m.a)(b),e=b.thumbs,c.timescale=b.timescale);return h.Observable.of({segmentData:e,segmentInfos:c})}}}}},function(b,d,a){a(2);var h=a(38);d.a=function(b,d,k,f){k||(k=[]);var c=void 0,e=void 0,g=a.i(h.e)(d),l=a.i(h.f)(d);f=f&&0<f.timescale?f.timescale:b.timescale; if(f===b.timescale){d=Math.min(.9*f,b.duration/4);var q=b.time;b=b.duration}else d=Math.min(.9*f,b.duration/b.timescale*f/4),q=b.time/b.timescale*f,b=b.duration/b.timescale*f;0<=g&&(null==q||Math.abs(g-q)<=d)&&(c=g);0<=l&&(null==b||Math.abs(l-b)<=d)&&(e=l);null==c&&(1===k.length?(c=k[0].time,0<=c&&(null==q||Math.abs(q-c)<=d)?(g=k[0].timescale,c=null!=g&&g!==f?c/g*f:c):c=q):c=q);null==e&&(1===k.length?(e=k[0].duration,0<=e&&(null==b||Math.abs(b-e)<=d)?(k=k[0].timescale,e=null!=k&&k!==f?e/k*f:e):e= b):e=b);return{timescale:f,time:c||0,duration:e||0}}},function(b,d,a){b=a(4);var h=a(2),l=a(30),g=a(64),k=[{k:"profiles",fn:g.g},{k:"width",fn:parseInt},{k:"height",fn:parseInt},{k:"frameRate",fn:g.h},{k:"audioSamplingRate",fn:g.g},{k:"mimeType",fn:g.g},{k:"segmentProfiles",fn:g.g},{k:"codecs",fn:g.g},{k:"maximumSAPPeriod",fn:parseFloat},{k:"maxPlayoutRate",fn:parseFloat},{k:"codingDependency",fn:g.i}],f=[{k:"timescale",fn:parseInt,def:1},{k:"timeShiftBufferDepth",fn:g.j},{k:"presentationTimeOffset", fn:parseFloat,def:0},{k:"indexRange",fn:g.f},{k:"indexRangeExact",fn:g.i,def:!1},{k:"availabilityTimeOffset",fn:parseFloat},{k:"availabilityTimeComplete",fn:g.i,def:!0}],c=f.concat([{k:"duration",fn:parseInt},{k:"startNumber",fn:parseInt}]),e={ContentProtection:[{k:"schemeIdUri",fn:g.g},{k:"value",fn:g.g}],SegmentURL:[{k:"media",fn:g.g},{k:"mediaRange",fn:g.f},{k:"index",fn:g.g},{k:"indexRange",fn:g.f}],S:[{k:"t",fn:parseInt,n:"ts"},{k:"d",fn:parseInt},{k:"r",fn:parseInt}],SegmentTimeline:[],SegmentBase:f, SegmentTemplate:c.concat([{k:"initialization",fn:function(a){return{media:a,range:void 0}}},{k:"index",fn:g.g},{k:"media",fn:g.g},{k:"bitstreamSwitching",fn:g.g}]),SegmentList:c,ContentComponent:[{k:"id",fn:g.g},{k:"lang",fn:g.g,n:"language"},{k:"lang",fn:l.a,n:"normalizedLanguage"},{k:"contentType",fn:g.g},{k:"par",fn:g.k}],Representation:k.concat([{k:"id",fn:g.g},{k:"bandwidth",fn:parseInt,n:"bitrate"},{k:"qualityRanking",fn:parseInt}]),AdaptationSet:k.concat([{k:"id",fn:g.g},{k:"group",fn:parseInt}, {k:"lang",fn:g.g,n:"language"},{k:"lang",fn:l.a,n:"normalizedLanguage"},{k:"contentType",fn:g.g},{k:"par",fn:g.k},{k:"minBandwidth",fn:parseInt,n:"minBitrate"},{k:"maxBandwidth",fn:parseInt,n:"maxBitrate"},{k:"minWidth",fn:parseInt},{k:"maxWidth",fn:parseInt},{k:"minHeight",fn:parseInt},{k:"maxHeight",fn:parseInt},{k:"minFrameRate",fn:g.h},{k:"maxFrameRate",fn:g.h},{k:"segmentAlignment",fn:g.l},{k:"subsegmentAlignment",fn:g.l},{k:"bitstreamSwitching",fn:g.i}]),Period:[{k:"id",fn:g.g},{k:"start",fn:g.j}, {k:"duration",fn:g.j},{k:"bitstreamSwitching",fn:g.i}],MPD:[{k:"id",fn:g.g},{k:"profiles",fn:g.g},{k:"type",fn:g.g,def:"static"},{k:"availabilityStartTime",fn:g.m},{k:"availabilityEndTime",fn:g.m},{k:"publishTime",fn:g.m},{k:"mediaPresentationDuration",fn:g.j,n:"duration"},{k:"minimumUpdatePeriod",fn:g.j},{k:"minBufferTime",fn:g.j},{k:"timeShiftBufferDepth",fn:g.j},{k:"suggestedPresentationDelay",fn:g.j,def:b.a.DEFAULT_SUGGESTED_PRESENTATION_DELAY.DASH},{k:"maxSegmentDuration",fn:g.j},{k:"maxSubsegmentDuration", fn:g.j}],Role:[{k:"schemeIdUri",fn:g.g},{k:"value",fn:g.g}],Accessibility:[{k:"schemeIdUri",fn:g.g},{k:"value",fn:parseInt}]};d.a=function(c,b){var f=e[c.nodeName];a.i(h.a)(f,"no attributes for "+c.nodeName);b=b||{};for(var d=0;d<f.length;d++){var k=f[d],g=k.k,l=k.fn,m=k.n;k=k.def;c.hasAttribute(g)?b[m||g]=l(c.getAttribute(g)):null!=k&&(b[m||g]=k)}return b}},function(b,d,a){a.d(d,"a",function(){return h});a.d(d,"b",function(){return l});a.d(d,"c",function(){return g});a.d(d,"d",function(){return k}); b=function(a){return function(b){return a.reduce(function(a,c){b.hasOwnProperty(c)&&(a[c]=b[c]);return a},{})}};var h=b("availabilityStartTime baseURL duration id locations periods presentationLiveGap suggestedPresentationDelay timeShiftBufferDepth transportType type".split(" ")),l=b(["adaptations","baseURL","duration","id","start"]),g=b("contentProtection accessibility baseURL contentProtection id language normalizedLanguage representations type".split(" ")),k=b("bitrate baseURL codecs height id index mimeType width".split(" "))}, function(b,d,a){function h(a,b){return"string"==typeof a?h.parseFromString(a,b):h.parseFromDocument(a,b)}var l=a(2),g=a(154);h.parseFromString=function(a,b){return h.parseFromDocument((new DOMParser).parseFromString(a,"application/xml"),b)};h.parseFromDocument=function(b,f){b=b.documentElement;l.a.equal(b.nodeName,"MPD","document root should be MPD");return a.i(g.a)(b,f)};d.a=h},function(b,d,a){function h(b,c){var e=a.i(r.a)(b,function(a,b,e){switch(b){case "BaseURL":a.baseURL=e.textContent;break; case "Location":a.locations.push(e.textContent);break;case "Period":a.periods.push(l(e,c))}return a},{transportType:"dash",periods:[],locations:[]});b=a.i(t.a)(b,e);/dynamic/.test(b.type)&&(e=b.periods[0].adaptations.filter(function(a){return"video"==a.type})[0],e=a.i(r.b)(e),e||(q.a.warn("Live edge not deduced from manifest, setting a default one"),e=Date.now()/1E3-60),b.availabilityStartTime=b.availabilityStartTime.getTime()/1E3,b.presentationLiveGap=Date.now()/1E3-(e+b.availabilityStartTime)); return a.i(p.a)(b)}function l(b,c){b=a.i(t.a)(b,a.i(r.a)(b,function(a,b,e){switch(b){case "BaseURL":a.baseURL=e.textContent;break;case "AdaptationSet":b=g(e,c),null==b.id&&(b.id=a.adaptations.length),a.adaptations.push(b)}return a},{adaptations:[]}));return a.i(p.b)(b)}function g(b,d){var g=void 0,h=a.i(r.a)(b,function(b,h,l){switch(h){case "Accessibility":g=a.i(t.a)(l);break;case "BaseURL":b.baseURL=l.textContent;break;case "ContentComponent":h=a.i(t.a)(l);b.contentComponent=h;break;case "ContentProtection":h= d(a.i(t.a)(l),l);b.contentProtection=h;break;case "Representation":h=k(l);null==h.id&&(h.id=b.representations.length);b.representations.push(h);break;case "Role":h=a.i(t.a)(l);b.role=h;break;case "SegmentBase":b.index=e(l);break;case "SegmentList":b.index=c(l);break;case "SegmentTemplate":b.index=f(l)}return b},{representations:[]}),l=a.i(t.a)(b,h);l.type=a.i(r.c)(l);l.accessibility=[];a.i(r.d)(g)&&l.accessibility.push("hardOfHearing");a.i(r.e)(g)&&l.accessibility.push("visuallyImpaired");l.representations= l.representations.map(function(a){u.forEach(function(b){!a.hasOwnProperty(b)&&l.hasOwnProperty(b)&&(a[b]=l[b])});return a});return a.i(p.c)(l)}function k(b){var d=a.i(r.a)(b,function(a,b,d){switch(b){case "BaseURL":a.baseURL=d.textContent;break;case "SegmentBase":a.index=e(d);break;case "SegmentList":a.index=c(d);break;case "SegmentTemplate":a.index=f(d)}return a},{});b=a.i(t.a)(b,d);return a.i(p.d)(b)}function f(a){a=m(a);a.indexType||(a.indexType="template");return a}function c(b){var c=m(b);c.list= [];c.indexType="list";return a.i(r.a)(b,function(b,c,e){"SegmentURL"==c&&b.list.push(a.i(t.a)(e));return b},c)}function e(b){var c=a.i(r.a)(b,function(b,c,e){if("Initialization"==c){var f=c=void 0;e.hasAttribute("range")&&(c=a.i(r.f)(e.getAttribute("range")));e.hasAttribute("sourceURL")&&(f=e.getAttribute("sourceURL"));b.initialization={range:c,media:f}}return b},a.i(t.a)(b));"SegmentBase"==b.nodeName&&(c.indexType="base",c.timeline=[]);return c}function m(b){return a.i(r.a)(b,function(a,b,c){"SegmentTimeline"== b&&(a.indexType="timeline",a.timeline=n(c));return a},e(b))}function n(b){return a.i(r.a)(b,function(b,c,e){c=b.length;e=a.i(t.a)(e);null==e.ts&&(c=0<c&&b[c-1],e.ts=c?c.ts+c.d*(c.r+1):0);null==e.r&&(e.r=0);b.push(e);return b},[])}a.d(d,"a",function(){return h});var q=a(1);a(2);var r=a(64),p=a(152),t=a(151),u=["codecs","height","index","mimeType","width"]},function(b,d,a){function h(b){var c=b.url;b=b.segment;var d=b.range;b=b.indexRange;if(d&&b&&d[1]===b[0]-1)return a.i(k.a)({url:c,responseType:"arraybuffer", headers:{Range:a.i(f.c)([d[0],b[1]])}});d=d?{Range:a.i(f.c)(d)}:null;d=a.i(k.a)({url:c,responseType:"arraybuffer",headers:d});return b?(c=a.i(k.a)({url:c,responseType:"arraybuffer",headers:{Range:a.i(f.c)(b)}}),l.Observable.merge(d,c)):d}var l=a(0);a.n(l);var g=a(24),k=a(65),f=a(66);d.a=function(b){return function(c){var e=c.segment,d=c.adaptation,k=c.representation;c=c.manifest;var r=e.media,p=e.range,t=e.indexRange;if(e.isInit&&!(r||p||t))return l.Observable.empty();r=r?a.i(f.b)(r,e,k):"";r=a.i(g.b)(k.baseURL, r);var u={adaptation:d,representation:k,manifest:c,segment:e,transport:"dash",url:r};return b?l.Observable.create(function(a){var c=!1,e=!1,f=b(u,{reject:function(){var b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};e||(c=!0,a.error(b))},resolve:function(){var b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};e||(c=!0,a.next({responseData:b.data,size:b.size||0,duration:b.duration||0}),a.complete())},fallback:function(){e=!0;h(u).subscribe(a)}});return function(){c||e||"function"!== typeof f||f()}}):h(u)}}},function(b,d,a){Object.defineProperty(d,"__esModule",{value:!0});var h=a(0);a.n(h);d["default"]={directFile:!0,manifest:{parser:function(a){a=a.url;return h.Observable.of({manifest:{transportType:"directfile",locations:[a],periods:[],isLive:!1,duration:Infinity,adaptations:null},url:a})}}}},function(b,d,a){Object.defineProperty(d,"__esModule",{value:!0});var h=a(0);a.n(h);var l=a(13),g=a(24),k=a(41),f=a(159),c=a(61);b=a(62);var e=a(63),m=a(39),n=a(67),q=a(68),r=a(158),p=a(160), t=m.a.patchSegment,u=m.a.getMdat,w={"application/x-sami":b.a,"application/smil":b.a,"application/ttml+xml":e.a,"application/ttml+xml+mp4":e.a,"text/vtt":function(a){return a}},x=/\.wsx?(\?token=\S+)?/;d["default"]=function(){var b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},e=a.i(f.a)(b),d=a.i(p.a)(b.segmentLoader);b={loader:function(a){return d({segment:a.segment,representation:a.representation,adaptation:a.adaptation,manifest:a.manifest})},parser:function(b){var c=b.segment,e=b.manifest; b=b.response.responseData;if(c.isInit)return h.Observable.of({segmentData:b,segmentInfos:{timescale:c.timescale,time:-1,duration:0}});b=new Uint8Array(b);e=a.i(r.a)(b,c,e.isLive);c=e.nextSegments;e=e.segmentInfos;b=t(b,e.time);return h.Observable.of({segmentData:b,segmentInfos:e,nextSegments:c})}};return{directFile:!1,manifest:{resolver:function(b){b=b.url;var c=void 0,e=a.i(q.a)(b);c=x.test(b)?a.i(k.a)({url:a.i(q.b)(b,""),responseType:"document",ignoreProgressEvents:!0}).map(function(a){return a.value}).map(q.c): h.Observable.of(b);return c.map(function(b){return{url:a.i(q.b)(a.i(q.d)(b),e)}})},loader:function(b){b=b.url;return a.i(n.a)({url:b,responseType:"document"})},parser:function(a){a=a.response;var b=e(a.responseData);return h.Observable.of({manifest:b,url:a.url})}},audio:b,video:b,text:{loader:function(b){var c=b.segment,e=b.representation;if(c.isInit)return h.Observable.empty();b=e.mimeType;var f=a.i(g.b)(e.baseURL);c=a.i(q.e)(f,e,c);return 0<=b.indexOf("mp4")?a.i(n.a)({url:c,responseType:"arraybuffer"}): a.i(n.a)({url:c,responseType:"text"})},parser:function(b){var c=b.response,e=b.segment,f=b.manifest,d=b.adaptation.language,k=b.representation.mimeType;b=w[k];if(!b)throw Error("could not find a text-track parser for the type "+k);var g=c.responseData,m=c=void 0,n={};0<=k.indexOf("mp4")?(g=new Uint8Array(g),k=a.i(l.a)(u(g)),f=a.i(r.a)(g,e,f.isLive),c=f.nextSegments,m=f.segmentInfos,n.start=m.start,n.end=null!=m.duration?m.start+m.duration:void 0,n.timescale=m.timescale):(k=g,n.start=e.time,n.end= null!=e.duration?e.time+e.duration:void 0,n.timescale=e.timescale);n.data=b(k,d,e.time/e.timescale);return h.Observable.of({segmentData:n,segmentInfos:m,nextSegments:c})}},image:{loader:function(b){var c=b.segment;b=b.representation;if(c.isInit)return h.Observable.empty();var e=a.i(g.b)(b.baseURL);c=a.i(q.e)(e,b,c);return a.i(n.a)({url:c,responseType:"arraybuffer"})},parser:function(b){var e=new Uint8Array(b.response.responseData);b={time:0,duration:Number.MAX_VALUE};var f=void 0;e&&(e=a.i(c.a)(e), f=e.thumbs,b.timescale=e.timescale);return h.Observable.of({segmentData:f,segmentInfos:b})}}}}},function(b,d,a){var h=a(1),l=a(38);b=a(39);var g=b.a.getTraf,k=b.a.parseTfrf,f=b.a.parseTfxd;d.a=function(b,e,d){var c=void 0,m=void 0;d?(d=g(b))?(c=k(d),m=f(d)):h.a.warn("smooth: could not find traf atom"):c=null;m||(m=Math.min(.9*e.timescale,e.duration/4),b=a.i(l.f)(b),m=0<=b&&Math.abs(b-e.duration)<=m?{time:e.time,duration:b}:{time:e.time,duration:e.duration});if(c)for(b=c.length-1;0<=b;b--)c[b].timescale= e.timescale;m&&(m.timescale=e.timescale);return{nextSegments:c,segmentInfos:m}}},function(b,d,a){function h(a){return"boolean"==typeof a?a:"string"==typeof a?"TRUE"===a.toUpperCase():!1}function l(a){if(!a)return Infinity;a=a.index;var b=a.timeline[a.timeline.length-1];return(b.ts+(b.r+1)*b.d)/a.timescale}function g(b){return[{systemId:"edef8ba9-79d6-4ace-a3c8-27dcd51d21ed",privateData:a.i(c.i)([8,1,18,16],b)}]}var k=a(19),f=a(4),c=a(13),e=a(2),m=a(30),n={audio:"audio/mp4",video:"video/mp4",text:"application/ttml+xml"}, q={audio:"mp4a.40.2",video:"avc1.4D401E"};b={AACL:"audio/mp4",AVC1:"video/mp4",H264:"video/mp4",TTML:"application/ttml+xml+mp4"};var r={audio:[["Bitrate","bitrate",parseInt],["AudioTag","audiotag",parseInt],["FourCC","mimeType",b],["Channels","channels",parseInt],["SamplingRate","samplingRate",parseInt],["BitsPerSample","bitsPerSample",parseInt],["PacketSize","packetSize",parseInt],["CodecPrivateData","codecPrivateData",String]],video:[["Bitrate","bitrate",parseInt],["FourCC","mimeType",b],["CodecPrivateData", "codecs",function(a){return(a=(/00000001\d7([0-9a-fA-F]{6})/.exec(a)||[])[1])?"avc1."+a:""}],["MaxWidth","width",parseInt],["MaxHeight","height",parseInt],["CodecPrivateData","codecPrivateData",String]],text:[["Bitrate","bitrate",parseInt],["FourCC","mimeType",b]]};d.a=function(){function b(a,b,c){for(a=a.firstElementChild;a;)c=b(c,a.nodeName,a),a=a.nextElementSibling;return c}function d(c,f){c.hasAttribute("Timescale")&&(f=+c.getAttribute("Timescale"));var d=c.getAttribute("Type"),k=c.getAttribute("Subtype"), g=c.getAttribute("Name"),h=c.getAttribute("Language"),l=a.i(m.a)(h),p=c.getAttribute("Url"),t=r[d],u=[];a.i(e.a)(t,"unrecognized QualityLevel type "+d);var w=0;f=b(c,function(a,b,c){switch(b){case "QualityLevel":b={};for(var e=0;e<t.length;e++){var f=t[e],k=f[0],g=f[2];b[f[1]]="function"==typeof g?g(c.getAttribute(k)):g[c.getAttribute(k)]}"audio"==d&&(c=c.getAttribute("FourCC")||"",e=b.codecPrivateData,c="AACH"==c?5:e?(parseInt(e.substr(0,2),16)&248)>>3:2,b.codecs=c?"mp4a.40."+c:"");if("video"!=d|| b.bitrate>B)b.id=w++,a.representations.push(b);break;case "c":b=a.index;e=a.index.timeline;f=e.length;k=0<f?e[f-1]:{d:0,ts:0,r:0};g=+c.getAttribute("d");var h=c.getAttribute("t");(c=+c.getAttribute("r"))&&c--;0<f&&!k.d&&(k.d=h-k.ts,e[f-1]=k);0<f&&g==k.d&&null==h?k.r+=(c||0)+1:e.push({d:g,ts:null==h?k.ts+k.d*(k.r+1):+h,r:c});b.timeline=e}return a},{representations:[],index:{timeline:[],indexType:"smooth",timescale:f,initialization:{}}});c=f.representations;f=f.index;a.i(e.a)(c.length,"adaptation should have at least one representation"); c.forEach(function(a){return a.codecs=a.codecs||q[d]});c.forEach(function(a){return a.mimeType=a.mimeType||n[d]});if("ADVT"==k)return null;"text"===d&&"DESC"===k&&u.push("hardOfHearing");return{type:d,accessibility:u,index:f,representations:c,name:g,language:h,normalizedLanguage:l,baseURL:p}}function u(a){return w((new DOMParser).parseFromString(a,"application/xml"))}function w(f){f=f.documentElement;e.a.equal(f.nodeName,"SmoothStreamingMedia","document root should be SmoothStreamingMedia");a.i(e.a)(/^[2]-[0-2]$/.test(f.getAttribute("MajorVersion")+ "-"+f.getAttribute("MinorVersion")),"Version should be 2.0, 2.1 or 2.2");var g=+f.getAttribute("Timescale")||1E7,m=[],n=b(f,function(b,f,h){switch(f){case "Protection":h=h.firstElementChild;e.a.equal(h.nodeName,"ProtectionHeader","Protection should have ProtectionHeader child");f=a.i(c.b)(atob(h.textContent));var l=a.i(c.d)(f,8);l=a.i(c.l)(f.subarray(10,10+l));l=(new DOMParser).parseFromString(l,"application/xml").querySelector("KID").textContent;l=a.i(c.m)(atob(l)).toLowerCase();var n=a.i(c.k)(l); h=h.getAttribute("SystemID").toLowerCase().replace(/\{|\}/g,"");f={keyId:l,keySystems:[{systemId:h,privateData:f}].concat(C(n))};b.protection=f;break;case "StreamIndex":if(f=d(h,g)){h=0;do l=f.type+"_"+(f.language?f.language+"_":"")+h++;while(a.i(k.a)(m,l));f.id=l;m.push(l);b.adaptations.push(f)}}return b},{protection:null,adaptations:[]}),q=n.protection;n=n.adaptations;n.forEach(function(a){return a.smoothProtection=q});var r=void 0,p=void 0,t=void 0,u=void 0,w=h(f.getAttribute("IsLive"));if(w){r= y;t=+f.getAttribute("DVRWindowLength")/g;u=z;p=n.filter(function(a){return"video"==a.type})[0];var v=n.filter(function(a){return"audio"==a.type})[0];p=Math.min(l(p),l(v));p=Date.now()/1E3-(p+u)}return{transportType:"smooth",profiles:"",type:w?"dynamic":"static",suggestedPresentationDelay:r,timeShiftBufferDepth:t,presentationLiveGap:p,availabilityStartTime:u,periods:[{duration:(+f.getAttribute("Duration")||Infinity)/g,adaptations:n,laFragCount:+f.getAttribute("LookAheadFragmentCount")}]}}function x(a){return"string"== typeof a?u(a):w(a)}var v=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},y=null==v.suggestedPresentationDelay?f.a.DEFAULT_SUGGESTED_PRESENTATION_DELAY.SMOOTH:v.suggestedPresentationDelay,z=v.referenceDateTime||Date.UTC(1970,0,1,0,0,0,0)/1E3,B=v.minRepresentationBitrate||19E4,C=v.keySystems||g;x.parseFromString=u;x.parseFromDocument=w;return x}},function(b,d,a){function h(b){var c=b.url,e=void 0;(b=b.segment.range)&&(e={Range:a.i(f.f)(b)});return a.i(k.a)({url:c,responseType:"arraybuffer", headers:e})}var l=a(0);a.n(l);var g=a(24);b=a(39);var k=a(67),f=a(68),c=b.a.createVideoInitSegment,e=b.a.createAudioInitSegment;d.a=function n(b){return function(d){var k=d.segment,q=d.representation,r=d.adaptation;d=d.manifest;if(k.isInit){d={};var w=r._smoothProtection||{};switch(r.type){case "video":d=c(k.timescale,q.width,q.height,72,72,4,q._codecPrivateData,w.keyId,w.keySystems);break;case "audio":d=e(k.timescale,q._channels,q._bitsPerSample,q._packetSize,q._samplingRate,q._codecPrivateData, w.keyId,w.keySystems)}return l.Observable.of({type:"data",value:{responseData:d}})}w=a.i(f.e)(a.i(g.b)(q.baseURL),q,k);var x={adaptation:r,representation:q,segment:k,transport:"smooth",url:w,manifest:d};return b?l.Observable.create(function(a){var c=!1,e=!1,f=b(x,{reject:function(){var b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};e||(c=!0,a.error(b))},resolve:function(){var b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};e||(c=!0,a.next({type:"response",value:{responseData:b.data, size:b.size||0,duration:b.duration||0}}),a.complete())},fallback:function(){e=!0;n(x).subscribe(a)}});return function(){c||e||"function"!==typeof f||f()}}):h(x)}}},function(b,d,a){a.d(d,"a",function(){return h});var h=function(){function a(){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.hash={}}a.prototype.add=function(a){this.hash[a]=!0};a.prototype.remove=function(a){delete this.hash[a]};a.prototype.test=function(a){return!0===this.hash[a]};return a}()},function(b, d,a){b=function(){function a(){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.cache={}}a.prototype.add=function(a,b){a=a.segment;a.isInit&&(this.cache[a.id]=b)};a.prototype.get=function(a){a=a.segment;return a.isInit&&(a=this.cache[a.id],null!=a)?a:null};return a}();d.a=b},function(b,d,a){d.a={aa:"aar",ab:"abk",ae:"ave",af:"afr",ak:"aka",am:"amh",an:"arg",ar:"ara",as:"asm",av:"ava",ay:"aym",az:"aze",ba:"bak",be:"bel",bg:"bul",bi:"bis",bm:"bam",bn:"ben",bo:"bod", br:"bre",bs:"bos",ca:"cat",ce:"che",ch:"cha",co:"cos",cr:"cre",cs:"ces",cu:"chu",cv:"chv",cy:"cym",da:"dan",de:"deu",dv:"div",dz:"dzo",ee:"ewe",el:"ell",en:"eng",eo:"epo",es:"spa",et:"est",eu:"eus",fa:"fas",ff:"ful",fi:"fin",fj:"fij",fo:"fao",fr:"fra",fy:"fry",ga:"gle",gd:"gla",gl:"glg",gn:"grn",gu:"guj",gv:"glv",ha:"hau",he:"heb",hi:"hin",ho:"hmo",hr:"hrv",ht:"hat",hu:"hun",hy:"hye",hz:"her",ia:"ina",id:"ind",ie:"ile",ig:"ibo",ii:"iii",ik:"ipk",io:"ido",is:"isl",it:"ita",iu:"iku",ja:"jpn",jv:"jav", ka:"kat",kg:"kon",ki:"kik",kj:"kua",kk:"kaz",kl:"kal",km:"khm",kn:"kan",ko:"kor",kr:"kau",ks:"kas",ku:"kur",kv:"kom",kw:"cor",ky:"kir",la:"lat",lb:"ltz",lg:"lug",li:"lim",ln:"lin",lo:"lao",lt:"lit",lu:"lub",lv:"lav",mg:"mlg",mh:"mah",mi:"mri",mk:"mkd",ml:"mal",mn:"mon",mr:"mar",ms:"msa",mt:"mlt",my:"mya",na:"nau",nb:"nob",nd:"nde",ne:"nep",ng:"ndo",nl:"nld",nn:"nno",no:"nor",nr:"nbl",nv:"nav",ny:"nya",oc:"oci",oj:"oji",om:"orm",or:"ori",os:"oss",pa:"pan",pi:"pli",pl:"pol",ps:"pus",pt:"por",qu:"que", rm:"roh",rn:"run",ro:"ron",ru:"rus",rw:"kin",sa:"san",sc:"srd",sd:"snd",se:"sme",sg:"sag",si:"sin",sk:"slk",sl:"slv",sm:"smo",sn:"sna",so:"som",sq:"sqi",sr:"srp",ss:"ssw",st:"sot",su:"sun",sv:"swe",sw:"swa",ta:"tam",te:"tel",tg:"tgk",th:"tha",ti:"tir",tk:"tuk",tl:"tgl",tn:"tsn",to:"ton",tr:"tur",ts:"tso",tt:"tat",tw:"twi",ty:"tah",ug:"uig",uk:"ukr",ur:"urd",uz:"uzb",ve:"ven",vi:"vie",vo:"vol",wa:"wln",wo:"wol",xh:"xho",yi:"yid",yo:"yor",za:"zha",zh:"zho",zu:"zul"}},function(b,d,a){d.a={alb:"sqi", arm:"hye",baq:"eus",bur:"mya",chi:"zho",cze:"ces",dut:"nld",fre:"fra",geo:"kat",ger:"deu",gre:"ell",ice:"isl",mac:"mkd",mao:"mri",may:"msa",per:"fas",slo:"slk",rum:"ron",tib:"bod",wel:"cym"}},function(b,d,a){d.a=function(a){var b=a.reduce(function(a,b){a[b]=b;return a},{});b.keys=a;return b}},function(b,d,a){d.a=function(b){var d=!1;return function(){if(d)return h.Observable.empty();d=!0;return a.i(l.a)(b.apply(void 0,arguments)).do(null,function(){return d=!1},function(){return d=!1})}};var h=a(0); a.n(h);var l=a(9)},function(b,d,a){d.a=function(){for(var a=0,b=arguments.length;a<b;){if(void 0!==(arguments.length<=a?void 0:arguments[a]))return arguments.length<=a?void 0:arguments[a];a++}}},function(b,d,a){d.a=function(){for(var a=0,b=arguments.length;a<b;){if(null!=(arguments.length<=a?void 0:arguments[a]))return arguments.length<=a?void 0:arguments[a];a++}}},function(b,d,a){function h(a){return!a||"object"!==typeof a||"number"!==typeof a.length||"function"!==typeof a.copy||"function"!==typeof a.slice|| 0<a.length&&"number"!==typeof a[0]?!1:!0}function l(a,b,d){var e;if(null===a||void 0===a||null===b||void 0===b||a.prototype!==b.prototype)return!1;if(f(a)){if(!f(b))return!1;a=g.call(a);b=g.call(b);return c(a,b,d)}if(h(a)){if(!h(b)||a.length!==b.length)return!1;for(e=0;e<a.length;e++)if(a[e]!==b[e])return!1;return!0}try{var l=k(a);var m=k(b)}catch(t){return!1}if(l.length!=m.length)return!1;l.sort();m.sort();for(e=l.length-1;0<=e;e--)if(l[e]!=m[e])return!1;for(e=l.length-1;0<=e;e--)if(m=l[e],!c(a[m], b[m],d))return!1;return typeof a===typeof b}var g=Array.prototype.slice,k=a(171),f=a(170),c=b.exports=function(a,b,c){c||(c={});return a===b?!0:a instanceof Date&&b instanceof Date?a.getTime()===b.getTime():!a||!b||"object"!=typeof a&&"object"!=typeof b?c.strict?a===b:a==b:l(a,b,c)}},function(b,d){function a(a){return"[object Arguments]"==Object.prototype.toString.call(a)}function h(a){return a&&"object"==typeof a&&"number"==typeof a.length&&Object.prototype.hasOwnProperty.call(a,"callee")&&!Object.prototype.propertyIsEnumerable.call(a, "callee")||!1}d="[object Arguments]"==function(){return Object.prototype.toString.call(arguments)}();d=b.exports=d?a:h;d.supported=a;d.unsupported=h},function(b,d){function a(a){var b=[],d;for(d in a)b.push(d);return b}d=b.exports="function"===typeof Object.keys?Object.keys:a;d.shim=a},function(b,d,a){var h=this&&this.__extends||function(a,b){function d(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(d.prototype=b.prototype,new d)};b=function(a){function b(b, f,c){a.call(this);this.parent=b;this.outerValue=f;this.outerIndex=c;this.index=0}h(b,a);b.prototype._next=function(a){this.parent.notifyNext(this.outerValue,a,this.outerIndex,this.index++,this)};b.prototype._error=function(a){this.parent.notifyError(a,this);this.unsubscribe()};b.prototype._complete=function(){this.parent.notifyComplete(this);this.unsubscribe()};return b}(a(3).Subscriber);d.InnerSubscriber=b},function(b,d,a){var h=a(0);b=function(){function a(a,b,f){this.kind=a;this.value=b;this.error= f;this.hasValue="N"===a}a.prototype.observe=function(a){switch(this.kind){case "N":return a.next&&a.next(this.value);case "E":return a.error&&a.error(this.error);case "C":return a.complete&&a.complete()}};a.prototype.do=function(a,b,f){switch(this.kind){case "N":return a&&a(this.value);case "E":return b&&b(this.error);case "C":return f&&f()}};a.prototype.accept=function(a,b,f){return a&&"function"===typeof a.next?this.observe(a):this.do(a,b,f)};a.prototype.toObservable=function(){switch(this.kind){case "N":return h.Observable.of(this.value); case "E":return h.Observable.throw(this.error);case "C":return h.Observable.empty()}throw Error("unexpected notification kind value");};a.createNext=function(b){return"undefined"!==typeof b?new a("N",b):a.undefinedValueNotification};a.createError=function(b){return new a("E",void 0,b)};a.createComplete=function(){return a.completeNotification};a.completeNotification=new a("C");a.undefinedValueNotification=new a("N",void 0);return a}();d.Notification=b},function(b,d,a){var h=this&&this.__extends|| function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(5);var l=a(260),g=a(11),k=a(77),f=a(50),c=a(72);a=function(a){function b(b,c,e){void 0===b&&(b=Number.POSITIVE_INFINITY);void 0===c&&(c=Number.POSITIVE_INFINITY);a.call(this);this.scheduler=e;this._events=[];this._bufferSize=1>b?1:b;this._windowTime=1>c?1:c}h(b,a);b.prototype.next=function(b){var c=this._getNow();this._events.push(new e(c, b));this._trimBufferThenGetEvents();a.prototype.next.call(this,b)};b.prototype._subscribe=function(a){var b=this._trimBufferThenGetEvents(),e=this.scheduler;if(this.closed)throw new f.ObjectUnsubscribedError;if(this.hasError)var d=g.Subscription.EMPTY;else this.isStopped?d=g.Subscription.EMPTY:(this.observers.push(a),d=new c.SubjectSubscription(this,a));e&&a.add(a=new k.ObserveOnSubscriber(a,e));e=b.length;for(var h=0;h<e&&!a.closed;h++)a.next(b[h].value);this.hasError?a.error(this.thrownError):this.isStopped&& a.complete();return d};b.prototype._getNow=function(){return(this.scheduler||l.queue).now()};b.prototype._trimBufferThenGetEvents=function(){for(var a=this._getNow(),b=this._bufferSize,c=this._windowTime,e=this._events,f=e.length,d=0;d<f&&!(a-e[d].time<c);)d++;f>b&&(d=Math.max(d,f-b));0<d&&e.splice(0,d);return e};return b}(b.Subject);d.ReplaySubject=a;var e=function(){return function(a,b){this.time=a;this.value=b}}()},function(b,d,a){b=function(){function a(b,d){void 0===d&&(d=a.now);this.SchedulerAction= b;this.now=d}a.prototype.schedule=function(a,b,d){void 0===b&&(b=0);return(new this.SchedulerAction(this,a)).schedule(d,b)};a.now=Date.now?Date.now:function(){return+new Date};return a}();d.Scheduler=b},function(b,d,a){b=a(0);a=a(223);b.Observable.combineLatest=a.combineLatest},function(b,d,a){b=a(0);a=a(224);b.Observable.defer=a.defer},function(b,d,a){b=a(0);a=a(225);b.Observable.empty=a.empty},function(b,d,a){b=a(0);a=a(226);b.Observable.from=a.from},function(b,d,a){b=a(0);a=a(227);b.Observable.fromEvent= a.fromEvent},function(b,d,a){b=a(0);a=a(228);b.Observable.fromPromise=a.fromPromise},function(b,d,a){b=a(0);a=a(229);b.Observable.interval=a.interval},function(b,d,a){b=a(0);a=a(230);b.Observable.merge=a.merge},function(b,d,a){b=a(0);a=a(231);b.Observable.never=a.never},function(b,d,a){b=a(0);a=a(232);b.Observable.of=a.of},function(b,d,a){b=a(0);a=a(233);b.Observable.throw=a._throw},function(b,d,a){b=a(0);a=a(234);b.Observable.timer=a.timer},function(b,d,a){b=a(0);a=a(235);b.Observable.prototype.catch= a._catch;b.Observable.prototype._catch=a._catch},function(b,d,a){b=a(0);a=a(74);b.Observable.prototype.concat=a.concat},function(b,d,a){b=a(0);a=a(237);b.Observable.prototype.concatAll=a.concatAll},function(b,d,a){b=a(0);a=a(238);b.Observable.prototype.concatMap=a.concatMap},function(b,d,a){b=a(0);a=a(239);b.Observable.prototype.debounceTime=a.debounceTime},function(b,d,a){b=a(0);a=a(240);b.Observable.prototype.distinctUntilChanged=a.distinctUntilChanged},function(b,d,a){b=a(0);a=a(241);b.Observable.prototype.do= a._do;b.Observable.prototype._do=a._do},function(b,d,a){b=a(0);a=a(242);b.Observable.prototype.filter=a.filter},function(b,d,a){b=a(0);a=a(243);b.Observable.prototype.finally=a._finally;b.Observable.prototype._finally=a._finally},function(b,d,a){b=a(0);a=a(244);b.Observable.prototype.ignoreElements=a.ignoreElements},function(b,d,a){b=a(0);a=a(245);b.Observable.prototype.map=a.map},function(b,d,a){b=a(0);a=a(246);b.Observable.prototype.mapTo=a.mapTo},function(b,d,a){b=a(0);a=a(75);b.Observable.prototype.merge= a.merge},function(b,d,a){b=a(0);a=a(76);b.Observable.prototype.mergeMap=a.mergeMap;b.Observable.prototype.flatMap=a.mergeMap},function(b,d,a){b=a(0);a=a(46);b.Observable.prototype.multicast=a.multicast},function(b,d,a){b=a(0);a=a(247);b.Observable.prototype.pairwise=a.pairwise},function(b,d,a){b=a(0);a=a(248);b.Observable.prototype.publish=a.publish},function(b,d,a){b=a(0);a=a(249);b.Observable.prototype.scan=a.scan},function(b,d,a){b=a(0);a=a(250);b.Observable.prototype.share=a.share},function(b, d,a){b=a(0);a=a(251);b.Observable.prototype.skip=a.skip},function(b,d,a){b=a(0);a=a(252);b.Observable.prototype.startWith=a.startWith},function(b,d,a){b=a(0);a=a(253);b.Observable.prototype.switchMap=a.switchMap},function(b,d,a){b=a(0);a=a(254);b.Observable.prototype.take=a.take},function(b,d,a){b=a(0);a=a(255);b.Observable.prototype.takeUntil=a.takeUntil},function(b,d,a){b=a(0);a=a(256);b.Observable.prototype.timeout=a.timeout},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor= a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(0);var l=a(44),g=a(25);a=function(a){function b(b,e){a.call(this);this.arrayLike=b;this.scheduler=e;e||1!==b.length||(this._isScalar=!0,this.value=b[0])}h(b,a);b.create=function(a,e){var c=a.length;return 0===c?new g.EmptyObservable:1===c?new l.ScalarObservable(a[0],e):new b(a,e)};b.dispatch=function(a){var b=a.arrayLike,c=a.index,f=a.subscriber;f.closed||(c>=a.length?f.complete(): (f.next(b[c]),a.index=c+1,this.schedule(a)))};b.prototype._subscribe=function(a){var c=this.arrayLike,f=this.scheduler,d=c.length;if(f)return f.schedule(b.dispatch,0,{arrayLike:c,index:0,length:d,subscriber:a});for(f=0;f<d&&!a.closed;f++)a.next(c[f]);a.complete()};return b}(b.Observable);d.ArrayLikeObservable=a},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype= b.prototype,new c)};b=a(5);var l=a(0),g=a(3),k=a(11);a=function(a){function b(b,c){a.call(this);this.source=b;this.subjectFactory=c;this._refCount=0;this._isComplete=!1}h(b,a);b.prototype._subscribe=function(a){return this.getSubject().subscribe(a)};b.prototype.getSubject=function(){var a=this._subject;if(!a||a.isStopped)this._subject=this.subjectFactory();return this._subject};b.prototype.connect=function(){var a=this._connection;a||(this._isComplete=!1,a=this._connection=new k.Subscription,a.add(this.source.subscribe(new f(this.getSubject(), this))),a.closed?(this._connection=null,a=k.Subscription.EMPTY):this._connection=a);return a};b.prototype.refCount=function(){return this.lift(new c(this))};return b}(l.Observable);d.ConnectableObservable=a;a=a.prototype;d.connectableObservableDescriptor={operator:{value:null},_refCount:{value:0,writable:!0},_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:a._subscribe},_isComplete:{value:a._isComplete,writable:!0},getSubject:{value:a.getSubject},connect:{value:a.connect}, refCount:{value:a.refCount}};var f=function(a){function b(b,c){a.call(this,b);this.connectable=c}h(b,a);b.prototype._error=function(b){this._unsubscribe();a.prototype._error.call(this,b)};b.prototype._complete=function(){this.connectable._isComplete=!0;this._unsubscribe();a.prototype._complete.call(this)};b.prototype._unsubscribe=function(){var a=this.connectable;if(a){this.connectable=null;var b=a._connection;a._refCount=0;a._subject=null;a._connection=null;b&&b.unsubscribe()}};return b}(b.SubjectSubscriber), c=function(){function a(a){this.connectable=a}a.prototype.call=function(a,b){var c=this.connectable;c._refCount++;a=new e(a,c);b=b.subscribe(a);a.closed||(a.connection=c.connect());return b};return a}(),e=function(a){function b(b,c){a.call(this,b);this.connectable=c}h(b,a);b.prototype._unsubscribe=function(){var a=this.connectable;if(a){this.connectable=null;var b=a._refCount;0>=b?this.connection=null:(a._refCount=b-1,1<b?this.connection=null:(b=this.connection,a=a._connection,this.connection=null, !a||b&&a!==b||a.unsubscribe()))}else this.connection=null};return b}(g.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(0);var l=a(16);a=a(14);b=function(a){function b(b){a.call(this);this.observableFactory=b}h(b,a);b.create=function(a){return new b(a)};b.prototype._subscribe=function(a){return new g(a,this.observableFactory)}; return b}(b.Observable);d.DeferObservable=b;var g=function(a){function b(b,e){a.call(this,b);this.factory=e;this.tryDefer()}h(b,a);b.prototype.tryDefer=function(){try{this._callFactory()}catch(c){this._error(c)}};b.prototype._callFactory=function(){var a=this.factory();a&&this.add(l.subscribeToResult(this,a))};return b}(a.OuterSubscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function d(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b? Object.create(b):(d.prototype=b.prototype,new d)};b=function(a){function b(b,f){a.call(this);this.error=b;this.scheduler=f}h(b,a);b.create=function(a,f){return new b(a,f)};b.dispatch=function(a){a.subscriber.error(a.error)};b.prototype._subscribe=function(a){var f=this.error,c=this.scheduler;a.syncErrorThrowable=!0;if(c)return c.schedule(b.dispatch,0,{error:f,subscriber:a});a.error(f)};return b}(a(0).Observable);d.ErrorObservable=b},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor= a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(0);var l=a(52),g=a(51),k=a(33),f=a(11),c=Object.prototype.toString;a=function(a){function b(b,c,e,f){a.call(this);this.sourceObj=b;this.eventName=c;this.selector=e;this.options=f}h(b,a);b.create=function(a,c,e,f){g.isFunction(e)&&(f=e,e=void 0);return new b(a,c,f,e)};b.setupSubscription=function(a,e,d,k,g){if(a&&"[object NodeList]"===c.call(a)||a&&"[object HTMLCollection]"=== c.call(a))for(var h=0,l=a.length;h<l;h++)b.setupSubscription(a[h],e,d,k,g);else if(a&&"function"===typeof a.addEventListener&&"function"===typeof a.removeEventListener){a.addEventListener(e,d,g);var m=function(){return a.removeEventListener(e,d)}}else if(a&&"function"===typeof a.on&&"function"===typeof a.off)a.on(e,d),m=function(){return a.off(e,d)};else if(a&&"function"===typeof a.addListener&&"function"===typeof a.removeListener)a.addListener(e,d),m=function(){return a.removeListener(e,d)};else throw new TypeError("Invalid event target"); k.add(new f.Subscription(m))};b.prototype._subscribe=function(a){var c=this.selector;b.setupSubscription(this.sourceObj,this.eventName,c?function(){for(var b=[],e=0;e<arguments.length;e++)b[e-0]=arguments[e];b=l.tryCatch(c).apply(void 0,b);b===k.errorObject?a.error(k.errorObject.e):a.next(b)}:function(b){return a.next(b)},a,this.options)};return b}(b.Observable);d.FromEventObservable=a},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&& (a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},l=a(26),g=a(81),k=a(85),f=a(73),c=a(220),e=a(15),m=a(213),n=a(47),q=a(0),r=a(77),p=a(48);b=function(a){function b(b,c){a.call(this,null);this.ish=b;this.scheduler=c}h(b,a);b.create=function(a,d){if(null!=a){if("function"===typeof a[p.observable])return a instanceof q.Observable&&!d?a:new b(a,d);if(l.isArray(a))return new e.ArrayObservable(a,d);if(k.isPromise(a))return new f.PromiseObservable(a,d);if("function"===typeof a[n.iterator]|| "string"===typeof a)return new c.IteratorObservable(a,d);if(g.isArrayLike(a))return new m.ArrayLikeObservable(a,d)}throw new TypeError((null!==a&&typeof a||a)+" is not observable");};b.prototype._subscribe=function(a){var b=this.ish,c=this.scheduler;return null==c?b[p.observable]().subscribe(a):b[p.observable]().subscribe(new r.ObserveOnSubscriber(a,c,0))};return b}(q.Observable);d.FromObservable=b},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&& (a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},l=a(83);b=a(0);var g=a(32);a=function(a){function b(b,e){void 0===b&&(b=0);void 0===e&&(e=g.async);a.call(this);this.period=b;this.scheduler=e;if(!l.isNumeric(b)||0>b)this.period=0;e&&"function"===typeof e.schedule||(this.scheduler=g.async)}h(b,a);b.create=function(a,e){void 0===a&&(a=0);void 0===e&&(e=g.async);return new b(a,e)};b.dispatch=function(a){var b=a.subscriber,c=a.period;b.next(a.index);b.closed||(a.index+= 1,this.schedule(a,c))};b.prototype._subscribe=function(a){var c=this.period;a.add(this.scheduler.schedule(b.dispatch,c,{index:0,subscriber:a,period:c}))};return b}(b.Observable);d.IntervalObservable=a},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},l=a(12);b=a(0);var g=a(47);a=function(a){function b(b,c){a.call(this);this.scheduler=c;if(null== b)throw Error("iterator cannot be null.");if((c=b[g.iterator])||"string"!==typeof b)if(c||void 0===b.length){if(!c)throw new TypeError("object is not iterable");b=b[g.iterator]()}else b=new f(b);else b=new k(b);this.iterator=b}h(b,a);b.create=function(a,c){return new b(a,c)};b.dispatch=function(a){var b=a.index,c=a.iterator,e=a.subscriber;if(a.hasError)e.error(a.error);else{var f=c.next();f.done?e.complete():(e.next(f.value),a.index=b+1,e.closed?"function"===typeof c.return&&c.return():this.schedule(a))}}; b.prototype._subscribe=function(a){var c=this.iterator,e=this.scheduler;if(e)return e.schedule(b.dispatch,0,{index:0,iterator:c,subscriber:a});do{e=c.next();if(e.done){a.complete();break}else a.next(e.value);if(a.closed){"function"===typeof c.return&&c.return();break}}while(1)};return b}(b.Observable);d.IteratorObservable=a;var k=function(){function a(a,b,c){void 0===b&&(b=0);void 0===c&&(c=a.length);this.str=a;this.idx=b;this.len=c}a.prototype[g.iterator]=function(){return this};a.prototype.next= function(){return this.idx<this.len?{done:!1,value:this.str.charAt(this.idx++)}:{done:!0,value:void 0}};return a}(),f=function(){function a(a,b,e){void 0===b&&(b=0);if(void 0===e)if(e=+a.length,isNaN(e))e=0;else if(0!==e&&"number"===typeof e&&l.root.isFinite(e)){var f=+e;f=0===f?f:isNaN(f)?f:0>f?-1:1;e=f*Math.floor(Math.abs(e));e=0>=e?0:e>c?c:e}this.arr=a;this.idx=b;this.len=e}a.prototype[g.iterator]=function(){return this};a.prototype.next=function(){return this.idx<this.len?{done:!1,value:this.arr[this.idx++]}: {done:!0,value:void 0}};return a}(),c=Math.pow(2,53)-1},function(b,d,a){var h=this&&this.__extends||function(a,b){function f(){this.constructor=a}for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);a.prototype=null===b?Object.create(b):(f.prototype=b.prototype,new f)};b=a(0);var l=a(86);a=function(a){function b(){a.call(this)}h(b,a);b.create=function(){return new b};b.prototype._subscribe=function(a){l.noop()};return b}(b.Observable);d.NeverObservable=a},function(b,d,a){var h=this&&this.__extends||function(a, b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},l=a(83);b=a(0);var g=a(32),k=a(20),f=a(82);a=function(a){function b(b,c,e){void 0===b&&(b=0);a.call(this);this.period=-1;this.dueTime=0;l.isNumeric(c)?this.period=1>Number(c)&&1||Number(c):k.isScheduler(c)&&(e=c);k.isScheduler(e)||(e=g.async);this.scheduler=e;this.dueTime=f.isDate(b)?+b-this.scheduler.now():b}h(b,a);b.create=function(a,c,e){void 0=== a&&(a=0);return new b(a,c,e)};b.dispatch=function(a){var b=a.index,c=a.period,e=a.subscriber;e.next(b);if(!e.closed){if(-1===c)return e.complete();a.index=b+1;this.schedule(a,c)}};b.prototype._subscribe=function(a){return this.scheduler.schedule(b.dispatch,this.dueTime,{index:0,period:this.period,subscriber:a})};return b}(b.Observable);d.TimerObservable=a},function(b,d,a){var h=a(20),l=a(26),g=a(15),k=a(236);d.combineLatest=function(){for(var a=[],b=0;b<arguments.length;b++)a[b-0]=arguments[b];var e= b=null;h.isScheduler(a[a.length-1])&&(e=a.pop());"function"===typeof a[a.length-1]&&(b=a.pop());1===a.length&&l.isArray(a[0])&&(a=a[0]);return(new g.ArrayObservable(a,e)).lift(new k.CombineLatestOperator(b))}},function(b,d,a){b=a(215);d.defer=b.DeferObservable.create},function(b,d,a){b=a(25);d.empty=b.EmptyObservable.create},function(b,d,a){b=a(218);d.from=b.FromObservable.create},function(b,d,a){b=a(217);d.fromEvent=b.FromEventObservable.create},function(b,d,a){b=a(73);d.fromPromise=b.PromiseObservable.create}, function(b,d,a){b=a(219);d.interval=b.IntervalObservable.create},function(b,d,a){b=a(75);d.merge=b.mergeStatic},function(b,d,a){b=a(221);d.never=b.NeverObservable.create},function(b,d,a){b=a(15);d.of=b.ArrayObservable.of},function(b,d,a){b=a(216);d._throw=b.ErrorObservable.create},function(b,d,a){b=a(222);d.timer=b.TimerObservable.create},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b): (c.prototype=b.prototype,new c)};b=a(14);var l=a(16);d._catch=function(a){a=new g(a);var b=this.lift(a);return a.caught=b};var g=function(){function a(a){this.selector=a}a.prototype.call=function(a,b){return b.subscribe(new k(a,this.selector,this.caught))};return a}(),k=function(a){function b(b,c,d){a.call(this,b);this.selector=c;this.caught=d}h(b,a);b.prototype.error=function(b){if(!this.isStopped){var c=void 0;try{c=this.selector(b,this.caught)}catch(n){a.prototype.error.call(this,n);return}this._unsubscribeAndRecycle(); this.add(l.subscribeToResult(this,c))}};return b}(b.OuterSubscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},l=a(15),g=a(26);b=a(14);var k=a(16),f={};d.combineLatest=function(){for(var a=[],b=0;b<arguments.length;b++)a[b-0]=arguments[b];b=null;"function"===typeof a[a.length-1]&&(b=a.pop());1===a.length&&g.isArray(a[0])&&(a=a[0].slice()); a.unshift(this);return this.lift.call(new l.ArrayObservable(a),new c(b))};var c=function(){function a(a){this.project=a}a.prototype.call=function(a,b){return b.subscribe(new e(a,this.project))};return a}();d.CombineLatestOperator=c;var e=function(a){function b(b,c){a.call(this,b);this.project=c;this.active=0;this.values=[];this.observables=[]}h(b,a);b.prototype._next=function(a){this.values.push(f);this.observables.push(a)};b.prototype._complete=function(){var a=this.observables,b=a.length;if(0=== b)this.destination.complete();else{this.toRespond=this.active=b;for(var c=0;c<b;c++){var e=a[c];this.add(k.subscribeToResult(this,e,e,c))}}};b.prototype.notifyComplete=function(a){0===--this.active&&this.destination.complete()};b.prototype.notifyNext=function(a,b,c,e,d){a=this.values;e=a[c];e=this.toRespond?e===f?--this.toRespond:this.toRespond:0;a[c]=b;0===e&&(this.project?this._tryProject(a):this.destination.next(a.slice()))};b.prototype._tryProject=function(a){try{var b=this.project.apply(this, a)}catch(p){this.destination.error(p);return}this.destination.next(b)};return b}(b.OuterSubscriber);d.CombineLatestSubscriber=e},function(b,d,a){var h=a(45);d.concatAll=function(){return this.lift(new h.MergeAllOperator(1))}},function(b,d,a){var h=a(76);d.concatMap=function(a,b){return this.lift(new h.MergeMapOperator(a,b,1))}},function(b,d,a){function h(a){a.debouncedNext()}var l=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype= null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);var g=a(32);d.debounceTime=function(a,b){void 0===b&&(b=g.async);return this.lift(new k(a,b))};var k=function(){function a(a,b){this.dueTime=a;this.scheduler=b}a.prototype.call=function(a,b){return b.subscribe(new f(a,this.dueTime,this.scheduler))};return a}(),f=function(a){function b(b,c,e){a.call(this,b);this.dueTime=c;this.scheduler=e;this.lastValue=this.debouncedSubscription=null;this.hasValue=!1}l(b,a);b.prototype._next=function(a){this.clearDebounce(); this.lastValue=a;this.hasValue=!0;this.add(this.debouncedSubscription=this.scheduler.schedule(h,this.dueTime,this))};b.prototype._complete=function(){this.debouncedNext();this.destination.complete()};b.prototype.debouncedNext=function(){this.clearDebounce();this.hasValue&&(this.destination.next(this.lastValue),this.lastValue=null,this.hasValue=!1)};b.prototype.clearDebounce=function(){var a=this.debouncedSubscription;null!==a&&(this.remove(a),a.unsubscribe(),this.debouncedSubscription=null)};return b}(b.Subscriber)}, function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);var l=a(52),g=a(33);d.distinctUntilChanged=function(a,b){return this.lift(new k(a,b))};var k=function(){function a(a,b){this.compare=a;this.keySelector=b}a.prototype.call=function(a,b){return b.subscribe(new f(a,this.compare,this.keySelector))};return a}(),f=function(a){function b(b,c, e){a.call(this,b);this.keySelector=e;this.hasKey=!1;"function"===typeof c&&(this.compare=c)}h(b,a);b.prototype.compare=function(a,b){return a===b};b.prototype._next=function(a){var b=a;if(this.keySelector&&(b=l.tryCatch(this.keySelector)(a),b===g.errorObject))return this.destination.error(g.errorObject.e);var c=!1;if(this.hasKey){if(c=l.tryCatch(this.compare)(this.key,b),c===g.errorObject)return this.destination.error(g.errorObject.e)}else this.hasKey=!0;!1===!!c&&(this.key=b,this.destination.next(a))}; return b}(b.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},l=a(3);d._do=function(a,b,e){return this.lift(new g(a,b,e))};var g=function(){function a(a,b,d){this.nextOrObserver=a;this.error=b;this.complete=d}a.prototype.call=function(a,b){return b.subscribe(new k(a,this.nextOrObserver,this.error,this.complete))};return a}(),k= function(a){function b(b,c,d,f){a.call(this,b);b=new l.Subscriber(c,d,f);b.syncErrorThrowable=!0;this.add(b);this.safeSubscriber=b}h(b,a);b.prototype._next=function(a){var b=this.safeSubscriber;b.next(a);b.syncErrorThrown?this.destination.error(b.syncErrorValue):this.destination.next(a)};b.prototype._error=function(a){var b=this.safeSubscriber;b.error(a);b.syncErrorThrown?this.destination.error(b.syncErrorValue):this.destination.error(a)};b.prototype._complete=function(){var a=this.safeSubscriber; a.complete();a.syncErrorThrown?this.destination.error(a.syncErrorValue):this.destination.complete()};return b}(l.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);d.filter=function(a,b){return this.lift(new l(a,b))};var l=function(){function a(a,b){this.predicate=a;this.thisArg=b}a.prototype.call=function(a,b){return b.subscribe(new g(a, this.predicate,this.thisArg))};return a}(),g=function(a){function b(b,e,d){a.call(this,b);this.predicate=e;this.thisArg=d;this.count=0}h(b,a);b.prototype._next=function(a){try{var b=this.predicate.call(this.thisArg,a,this.count++)}catch(m){this.destination.error(m);return}b&&this.destination.next(a)};return b}(b.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b): (c.prototype=b.prototype,new c)};b=a(3);var l=a(11);d._finally=function(a){return this.lift(new g(a))};var g=function(){function a(a){this.callback=a}a.prototype.call=function(a,b){return b.subscribe(new k(a,this.callback))};return a}(),k=function(a){function b(b,c){a.call(this,b);this.add(new l.Subscription(c))}h(b,a);return b}(b.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null=== b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);var l=a(86);d.ignoreElements=function(){return this.lift(new g)};var g=function(){function a(){}a.prototype.call=function(a,b){return b.subscribe(new k(a))};return a}(),k=function(a){function b(){a.apply(this,arguments)}h(b,a);b.prototype._next=function(a){l.noop()};return b}(b.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype= null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);d.map=function(a,b){if("function"!==typeof a)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return this.lift(new l(a,b))};var l=function(){function a(a,b){this.project=a;this.thisArg=b}a.prototype.call=function(a,b){return b.subscribe(new g(a,this.project,this.thisArg))};return a}();d.MapOperator=l;var g=function(a){function b(b,e,d){a.call(this,b);this.project=e;this.count=0;this.thisArg=d||this} h(b,a);b.prototype._next=function(a){try{var b=this.project.call(this.thisArg,a,this.count++)}catch(m){this.destination.error(m);return}this.destination.next(b)};return b}(b.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);d.mapTo=function(a){return this.lift(new l(a))};var l=function(){function a(a){this.value=a}a.prototype.call= function(a,b){return b.subscribe(new g(a,this.value))};return a}(),g=function(a){function b(b,e){a.call(this,b);this.value=e}h(b,a);b.prototype._next=function(a){this.destination.next(this.value)};return b}(b.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);d.pairwise=function(){return this.lift(new l)};var l=function(){function a(){} a.prototype.call=function(a,b){return b.subscribe(new g(a))};return a}(),g=function(a){function b(b){a.call(this,b);this.hasPrev=!1}h(b,a);b.prototype._next=function(a){this.hasPrev?this.destination.next([this.prev,a]):this.hasPrev=!0;this.prev=a};return b}(b.Subscriber)},function(b,d,a){var h=a(5),l=a(46);d.publish=function(a){return a?l.multicast.call(this,function(){return new h.Subject},a):l.multicast.call(this,new h.Subject)}},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor= a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);d.scan=function(a,b){var c=!1;2<=arguments.length&&(c=!0);return this.lift(new l(a,b,c))};var l=function(){function a(a,b,e){void 0===e&&(e=!1);this.accumulator=a;this.seed=b;this.hasSeed=e}a.prototype.call=function(a,b){return b.subscribe(new g(a,this.accumulator,this.seed,this.hasSeed))};return a}(),g=function(a){function b(b,e,d,f){a.call(this,b);this.accumulator=e;this._seed= d;this.hasSeed=f;this.index=0}h(b,a);Object.defineProperty(b.prototype,"seed",{get:function(){return this._seed},set:function(a){this.hasSeed=!0;this._seed=a},enumerable:!0,configurable:!0});b.prototype._next=function(a){if(this.hasSeed)return this._tryNext(a);this.seed=a;this.destination.next(a)};b.prototype._tryNext=function(a){var b=this.index++;try{var c=this.accumulator(this.seed,a,b)}catch(n){this.destination.error(n)}this.seed=c;this.destination.next(c)};return b}(b.Subscriber)},function(b, d,a){function h(){return new g.Subject}var l=a(46),g=a(5);d.share=function(){return l.multicast.call(this,h).refCount()}},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);d.skip=function(a){return this.lift(new l(a))};var l=function(){function a(a){this.total=a}a.prototype.call=function(a,b){return b.subscribe(new g(a,this.total))}; return a}(),g=function(a){function b(b,e){a.call(this,b);this.total=e;this.count=0}h(b,a);b.prototype._next=function(a){++this.count>this.total&&this.destination.next(a)};return b}(b.Subscriber)},function(b,d,a){var h=a(15),l=a(44),g=a(25),k=a(74),f=a(20);d.startWith=function(){for(var a=[],b=0;b<arguments.length;b++)a[b-0]=arguments[b];b=a[a.length-1];f.isScheduler(b)?a.pop():b=null;var d=a.length;return 1===d?k.concatStatic(new l.ScalarObservable(a[0],b),this):1<d?k.concatStatic(new h.ArrayObservable(a, b),this):k.concatStatic(new g.EmptyObservable(b),this)}},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(14);var l=a(16);d.switchMap=function(a,b){return this.lift(new g(a,b))};var g=function(){function a(a,b){this.project=a;this.resultSelector=b}a.prototype.call=function(a,b){return b.subscribe(new k(a,this.project,this.resultSelector))}; return a}(),k=function(a){function b(b,c,d){a.call(this,b);this.project=c;this.resultSelector=d;this.index=0}h(b,a);b.prototype._next=function(a){var b=this.index++;try{var c=this.project(a,b)}catch(q){this.destination.error(q);return}this._innerSub(c,a,b)};b.prototype._innerSub=function(a,b,c){var e=this.innerSubscription;e&&e.unsubscribe();this.add(this.innerSubscription=l.subscribeToResult(this,a,b,c))};b.prototype._complete=function(){var b=this.innerSubscription;b&&!b.closed||a.prototype._complete.call(this)}; b.prototype._unsubscribe=function(){this.innerSubscription=null};b.prototype.notifyComplete=function(b){this.remove(b);this.innerSubscription=null;this.isStopped&&a.prototype._complete.call(this)};b.prototype.notifyNext=function(a,b,c,d,f){this.resultSelector?this._tryNotifyNext(a,b,c,d):this.destination.next(b)};b.prototype._tryNotifyNext=function(a,b,c,d){try{var e=this.resultSelector(a,b,c,d)}catch(p){this.destination.error(p);return}this.destination.next(e)};return b}(b.OuterSubscriber)},function(b, d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);var l=a(261),g=a(25);d.take=function(a){return 0===a?new g.EmptyObservable:this.lift(new k(a))};var k=function(){function a(a){this.total=a;if(0>this.total)throw new l.ArgumentOutOfRangeError;}a.prototype.call=function(a,b){return b.subscribe(new f(a,this.total))};return a}(),f=function(a){function b(b, c){a.call(this,b);this.total=c;this.count=0}h(b,a);b.prototype._next=function(a){var b=this.total,c=++this.count;c<=b&&(this.destination.next(a),c===b&&(this.destination.complete(),this.unsubscribe()))};return b}(b.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(14);var l=a(16);d.takeUntil=function(a){return this.lift(new g(a))}; var g=function(){function a(a){this.notifier=a}a.prototype.call=function(a,b){return b.subscribe(new k(a,this.notifier))};return a}(),k=function(a){function b(b,c){a.call(this,b);this.notifier=c;this.add(l.subscribeToResult(this,c))}h(b,a);b.prototype.notifyNext=function(a,b,c,d,f){this.complete()};b.prototype.notifyComplete=function(){};return b}(b.OuterSubscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]= b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},l=a(32),g=a(82);b=a(3);var k=a(80);d.timeout=function(a,b){void 0===b&&(b=l.async);var c=g.isDate(a);a=c?+a-b.now():Math.abs(a);return this.lift(new f(a,c,b,new k.TimeoutError))};var f=function(){function a(a,b,c,e){this.waitFor=a;this.absoluteTimeout=b;this.scheduler=c;this.errorInstance=e}a.prototype.call=function(a,b){return b.subscribe(new c(a,this.absoluteTimeout,this.waitFor,this.scheduler,this.errorInstance))};return a}(), c=function(a){function b(b,c,d,e,f){a.call(this,b);this.absoluteTimeout=c;this.waitFor=d;this.scheduler=e;this.errorInstance=f;this.action=null;this.scheduleTimeout()}h(b,a);b.dispatchTimeout=function(a){a.error(a.errorInstance)};b.prototype.scheduleTimeout=function(){var a=this.action;a?this.action=a.schedule(this,this.waitFor):this.add(this.action=this.scheduler.schedule(b.dispatchTimeout,this.waitFor,this))};b.prototype._next=function(b){this.absoluteTimeout||this.scheduleTimeout();a.prototype._next.call(this, b)};b.prototype._unsubscribe=function(){this.errorInstance=this.scheduler=this.action=null};return b}(b.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function d(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(d.prototype=b.prototype,new d)};b=function(a){function b(b,d){a.call(this)}h(b,a);b.prototype.schedule=function(a,b){return this};return b}(a(11).Subscription);d.Action=b},function(b,d,a){var h=this&&this.__extends|| function(a,b){function d(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(d.prototype=b.prototype,new d)};b=function(a){function b(b,d){a.call(this,b,d);this.scheduler=b;this.work=d}h(b,a);b.prototype.schedule=function(b,d){void 0===d&&(d=0);if(0<d)return a.prototype.schedule.call(this,b,d);this.delay=d;this.state=b;this.scheduler.flush(this);return this};b.prototype.execute=function(b,d){return 0<d||this.closed?a.prototype.execute.call(this, b,d):this._execute(b,d)};b.prototype.requestAsyncId=function(b,d,c){void 0===c&&(c=0);return null!==c&&0<c||null===c&&0<this.delay?a.prototype.requestAsyncId.call(this,b,d,c):b.flush(this)};return b}(a(78).AsyncAction);d.QueueAction=b},function(b,d,a){var h=this&&this.__extends||function(a,b){function d(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(d.prototype=b.prototype,new d)};b=function(a){function b(){a.apply(this,arguments)}h(b,a); return b}(a(79).AsyncScheduler);d.QueueScheduler=b},function(b,d,a){b=a(258);a=a(259);d.queue=new a.QueueScheduler(b.QueueAction)},function(b,d,a){var h=this&&this.__extends||function(a,b){function d(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(d.prototype=b.prototype,new d)};b=function(a){function b(){var b=a.call(this,"argument out of range");this.name=b.name="ArgumentOutOfRangeError";this.stack=b.stack;this.message=b.message}h(b,a); return b}(Error);d.ArgumentOutOfRangeError=b},function(b,d,a){var h=this&&this.__extends||function(a,b){function d(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(d.prototype=b.prototype,new d)};b=function(a){function b(b){a.call(this);this.errors=b;b=Error.call(this,b?b.length+" errors occurred during unsubscription:\n "+b.map(function(a,b){return b+1+") "+a.toString()}).join("\n "):"");this.name=b.name="UnsubscriptionError";this.stack= b.stack;this.message=b.message}h(b,a);return b}(Error);d.UnsubscriptionError=b},function(b,d,a){var h=a(3),l=a(49),g=a(71);d.toSubscriber=function(a,b,c){if(a){if(a instanceof h.Subscriber)return a;if(a[l.rxSubscriber])return a[l.rxSubscriber]()}return a||b||c?new h.Subscriber(a,b,c):new h.Subscriber(g.empty)}},function(b,d){d=function(){return this}();try{d=d||Function("return this")()||(0,eval)("this")}catch(a){"object"===typeof window&&(d=window)}b.exports=d}])});
extend1994/cdnjs
ajax/libs/rx-player/3.0.0-rc4/rx-player.min.js
JavaScript
mit
223,270