code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
# -*- coding: utf-8 -*- """ Python API for language and translation management. """ from collections import namedtuple from django.conf import settings from django.utils.translation import ugettext as _ from dark_lang.models import DarkLangConfig # Named tuples can be referenced using object-like variable # deferencing, making the use of tuples more readable by # eliminating the need to see the context of the tuple packing. Language = namedtuple('Language', 'code name') def released_languages(): """Retrieve the list of released languages. Constructs a list of Language tuples by intersecting the list of valid language tuples with the list of released language codes. Returns: list of Language: Languages in which full translations are available. Example: >>> print released_languages() [Language(code='en', name=u'English'), Language(code='fr', name=u'Français')] """ released_language_codes = DarkLangConfig.current().released_languages_list default_language_code = settings.LANGUAGE_CODE if default_language_code not in released_language_codes: released_language_codes.append(default_language_code) released_language_codes.sort() # Intersect the list of valid language tuples with the list # of release language codes released_languages = [ Language(tuple[0], tuple[1]) for tuple in settings.LANGUAGES if tuple[0] in released_language_codes ] return released_languages def all_languages(): """Retrieve the list of all languages, translated and sorted. Returns: list of (language code (str), language name (str)): the language names are translated in the current activated language and the results sorted alphabetically. """ languages = [(lang[0], _(lang[1])) for lang in settings.ALL_LANGUAGES] # pylint: disable=translation-of-non-string return sorted(languages, key=lambda lang: lang[1])
louyihua/edx-platform
common/djangoapps/lang_pref/api.py
Python
agpl-3.0
1,986
/* * CommandWithArg.java * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.core.client; public interface CommandWithArg<T> { void execute(T arg); }
maligulzar/Rstudio-instrumented
src/gwt/src/org/rstudio/core/client/CommandWithArg.java
Java
agpl-3.0
682
/** * 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.hadoop.hbase.types; import org.apache.hadoop.hbase.classification.InterfaceAudience; import org.apache.hadoop.hbase.classification.InterfaceStability; import org.apache.hadoop.hbase.util.Order; import org.apache.hadoop.hbase.util.OrderedBytes; import org.apache.hadoop.hbase.util.PositionedByteRange; /** * A {@code float} of 32-bits using a fixed-length encoding. Based on * {@link OrderedBytes#encodeFloat32(PositionedByteRange, float, Order)}. */ @InterfaceAudience.Public @InterfaceStability.Evolving public class OrderedFloat32 extends OrderedBytesBase<Float> { public static final OrderedFloat32 ASCENDING = new OrderedFloat32(Order.ASCENDING); public static final OrderedFloat32 DESCENDING = new OrderedFloat32(Order.DESCENDING); protected OrderedFloat32(Order order) { super(order); } @Override public boolean isNullable() { return false; } @Override public int encodedLength(Float val) { return 5; } @Override public Class<Float> encodedClass() { return Float.class; } @Override public Float decode(PositionedByteRange src) { return OrderedBytes.decodeFloat32(src); } @Override public int encode(PositionedByteRange dst, Float val) { if (null == val) throw new IllegalArgumentException("Null values not supported."); return OrderedBytes.encodeFloat32(dst, val, order); } /** * Read a {@code float} value from the buffer {@code dst}. */ public float decodeFloat(PositionedByteRange dst) { return OrderedBytes.decodeFloat32(dst); } /** * Write instance {@code val} into buffer {@code buff}. */ public int encodeFloat(PositionedByteRange dst, float val) { return OrderedBytes.encodeFloat32(dst, val, order); } }
Guavus/hbase
hbase-common/src/main/java/org/apache/hadoop/hbase/types/OrderedFloat32.java
Java
apache-2.0
2,533
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/run_loop.h" #include "base/bind.h" #if defined(OS_WIN) #include "base/message_loop/message_pump_dispatcher.h" #endif namespace base { RunLoop::RunLoop() : loop_(MessageLoop::current()), previous_run_loop_(NULL), run_depth_(0), run_called_(false), quit_called_(false), running_(false), quit_when_idle_received_(false), weak_factory_(this) { #if defined(OS_WIN) dispatcher_ = NULL; #endif } #if defined(OS_WIN) RunLoop::RunLoop(MessagePumpDispatcher* dispatcher) : loop_(MessageLoop::current()), previous_run_loop_(NULL), dispatcher_(dispatcher), run_depth_(0), run_called_(false), quit_called_(false), running_(false), quit_when_idle_received_(false), weak_factory_(this) { } #endif RunLoop::~RunLoop() { } void RunLoop::Run() { if (!BeforeRun()) return; loop_->RunHandler(); AfterRun(); } void RunLoop::RunUntilIdle() { quit_when_idle_received_ = true; Run(); } void RunLoop::Quit() { quit_called_ = true; if (running_ && loop_->run_loop_ == this) { // This is the inner-most RunLoop, so quit now. loop_->QuitNow(); } } base::Closure RunLoop::QuitClosure() { return base::Bind(&RunLoop::Quit, weak_factory_.GetWeakPtr()); } bool RunLoop::BeforeRun() { DCHECK(!run_called_); run_called_ = true; // Allow Quit to be called before Run. if (quit_called_) return false; // Push RunLoop stack: previous_run_loop_ = loop_->run_loop_; run_depth_ = previous_run_loop_? previous_run_loop_->run_depth_ + 1 : 1; loop_->run_loop_ = this; running_ = true; return true; } void RunLoop::AfterRun() { running_ = false; // Pop RunLoop stack: loop_->run_loop_ = previous_run_loop_; // Execute deferred QuitNow, if any: if (previous_run_loop_ && previous_run_loop_->quit_called_) loop_->QuitNow(); } } // namespace base
wubenqi/zutils
zutils/base/run_loop.cc
C++
apache-2.0
2,073
require 'chef/provisioning/aws_driver/aws_resource' class Chef::Resource::AwsKeyPair < Chef::Provisioning::AWSDriver::AWSResource aws_sdk_type AWS::EC2::KeyPair, id: :name # Private key to use as input (will be generated if it does not exist) attribute :private_key_path, :kind_of => String # Public key to use as input (will be generated if it does not exist) attribute :public_key_path, :kind_of => String # List of parameters to the private_key resource used for generation of the key attribute :private_key_options, :kind_of => Hash # TODO what is the right default for this? attribute :allow_overwrite, :kind_of => [TrueClass, FalseClass], :default => false def aws_object result = driver.ec2.key_pairs[name] result && result.exists? ? result : nil end end
tarak/chef-provisioning-aws
lib/chef/resource/aws_key_pair.rb
Ruby
apache-2.0
796
/* * Copyright 2003,2004 The Apache Software Foundation * * 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 net.sf.cglib.proxy; import java.security.ProtectionDomain; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; /** * <code>Mixin</code> allows * multiple objects to be combined into a single larger object. The * methods in the generated object simply call the original methods in the * underlying "delegate" objects. * @author Chris Nokleberg * @version $Id: Mixin.java,v 1.7 2005/09/27 11:42:27 baliuka Exp $ */ abstract public class Mixin { private static final MixinKey KEY_FACTORY = (MixinKey)KeyFactory.create(MixinKey.class, KeyFactory.CLASS_BY_NAME); private static final Map ROUTE_CACHE = Collections.synchronizedMap(new HashMap()); public static final int STYLE_INTERFACES = 0; public static final int STYLE_BEANS = 1; public static final int STYLE_EVERYTHING = 2; interface MixinKey { public Object newInstance(int style, String[] classes, int[] route); } abstract public Mixin newInstance(Object[] delegates); /** * Helper method to create an interface mixin. For finer control over the * generated instance, use a new instance of <code>Mixin</code> * instead of this static method. * TODO */ public static Mixin create(Object[] delegates) { Generator gen = new Generator(); gen.setDelegates(delegates); return gen.create(); } /** * Helper method to create an interface mixin. For finer control over the * generated instance, use a new instance of <code>Mixin</code> * instead of this static method. * TODO */ public static Mixin create(Class[] interfaces, Object[] delegates) { Generator gen = new Generator(); gen.setClasses(interfaces); gen.setDelegates(delegates); return gen.create(); } public static Mixin createBean(Object[] beans) { return createBean(null, beans); } /** * Helper method to create a bean mixin. For finer control over the * generated instance, use a new instance of <code>Mixin</code> * instead of this static method. * TODO */ public static Mixin createBean(ClassLoader loader,Object[] beans) { Generator gen = new Generator(); gen.setStyle(STYLE_BEANS); gen.setDelegates(beans); gen.setClassLoader(loader); return gen.create(); } public static class Generator extends AbstractClassGenerator { private static final Source SOURCE = new Source(Mixin.class.getName()); private Class[] classes; private Object[] delegates; private int style = STYLE_INTERFACES; private int[] route; public Generator() { super(SOURCE); } protected ClassLoader getDefaultClassLoader() { return classes[0].getClassLoader(); // is this right? } protected ProtectionDomain getProtectionDomain() { return ReflectUtils.getProtectionDomain(classes[0]); } public void setStyle(int style) { switch (style) { case STYLE_INTERFACES: case STYLE_BEANS: case STYLE_EVERYTHING: this.style = style; break; default: throw new IllegalArgumentException("Unknown mixin style: " + style); } } public void setClasses(Class[] classes) { this.classes = classes; } public void setDelegates(Object[] delegates) { this.delegates = delegates; } public Mixin create() { if (classes == null && delegates == null) { throw new IllegalStateException("Either classes or delegates must be set"); } switch (style) { case STYLE_INTERFACES: if (classes == null) { Route r = route(delegates); classes = r.classes; route = r.route; } break; case STYLE_BEANS: // fall-through case STYLE_EVERYTHING: if (classes == null) { classes = ReflectUtils.getClasses(delegates); } else { if (delegates != null) { Class[] temp = ReflectUtils.getClasses(delegates); if (classes.length != temp.length) { throw new IllegalStateException("Specified classes are incompatible with delegates"); } for (int i = 0; i < classes.length; i++) { if (!classes[i].isAssignableFrom(temp[i])) { throw new IllegalStateException("Specified class " + classes[i] + " is incompatible with delegate class " + temp[i] + " (index " + i + ")"); } } } } } setNamePrefix(classes[ReflectUtils.findPackageProtected(classes)].getName()); return (Mixin)super.create(KEY_FACTORY.newInstance(style, ReflectUtils.getNames( classes ), route)); } public void generateClass(ClassVisitor v) { switch (style) { case STYLE_INTERFACES: new MixinEmitter(v, getClassName(), classes, route); break; case STYLE_BEANS: new MixinBeanEmitter(v, getClassName(), classes); break; case STYLE_EVERYTHING: new MixinEverythingEmitter(v, getClassName(), classes); break; } } protected Object firstInstance(Class type) { return ((Mixin)ReflectUtils.newInstance(type)).newInstance(delegates); } protected Object nextInstance(Object instance) { return ((Mixin)instance).newInstance(delegates); } } public static Class[] getClasses(Object[] delegates) { return (Class[])route(delegates).classes.clone(); } // public static int[] getRoute(Object[] delegates) { // return (int[])route(delegates).route.clone(); // } private static Route route(Object[] delegates) { Object key = ClassesKey.create(delegates); Route route = (Route)ROUTE_CACHE.get(key); if (route == null) { ROUTE_CACHE.put(key, route = new Route(delegates)); } return route; } private static class Route { private Class[] classes; private int[] route; Route(Object[] delegates) { Map map = new HashMap(); ArrayList collect = new ArrayList(); for (int i = 0; i < delegates.length; i++) { Class delegate = delegates[i].getClass(); collect.clear(); ReflectUtils.addAllInterfaces(delegate, collect); for (Iterator it = collect.iterator(); it.hasNext();) { Class iface = (Class)it.next(); if (!map.containsKey(iface)) { map.put(iface, new Integer(i)); } } } classes = new Class[map.size()]; route = new int[map.size()]; int index = 0; for (Iterator it = map.keySet().iterator(); it.hasNext();) { Class key = (Class)it.next(); classes[index] = key; route[index] = ((Integer)map.get(key)).intValue(); index++; } } } }
HubSpot/cglib
cglib/src/main/java/net/sf/cglib/proxy/Mixin.java
Java
apache-2.0
8,394
/** * Copyright 2007-2016, Kaazing Corporation. All rights reserved. * * 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.kaazing.gateway.transport.http.bridge.filter; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static org.jboss.netty.util.CharsetUtil.UTF_8; import static org.kaazing.gateway.transport.http.HttpMethod.GET; import static org.kaazing.gateway.transport.http.HttpMethod.POST; import static org.kaazing.gateway.transport.http.HttpStatus.CLIENT_NOT_FOUND; import static org.kaazing.gateway.transport.http.HttpStatus.CLIENT_UNAUTHORIZED; import static org.kaazing.gateway.transport.http.HttpStatus.REDIRECT_FOUND; import static org.kaazing.gateway.transport.http.HttpStatus.REDIRECT_MULTIPLE_CHOICES; import static org.kaazing.gateway.transport.http.HttpStatus.REDIRECT_NOT_MODIFIED; import static org.kaazing.gateway.transport.http.HttpStatus.SUCCESS_OK; import static org.kaazing.gateway.transport.http.HttpVersion.HTTP_1_0; import static org.kaazing.gateway.transport.http.HttpVersion.HTTP_1_1; import static org.kaazing.gateway.transport.http.bridge.HttpContentMessage.EMPTY; import static org.kaazing.gateway.util.Utils.join; import java.net.URI; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import org.apache.mina.core.filterchain.IoFilter.NextFilter; import org.apache.mina.core.filterchain.IoFilterChain; import org.apache.mina.core.write.DefaultWriteRequest; import org.apache.mina.filter.codec.ProtocolCodecException; import org.junit.Test; import org.kaazing.gateway.transport.http.DefaultHttpCookie; import org.kaazing.gateway.transport.http.HttpAcceptSession; import org.kaazing.gateway.transport.http.HttpConnectSession; import org.kaazing.gateway.transport.http.HttpCookie; import org.kaazing.gateway.transport.http.HttpHeaders; import org.kaazing.gateway.transport.http.HttpStatus; import org.kaazing.gateway.transport.http.bridge.HttpContentMessage; import org.kaazing.gateway.transport.http.bridge.HttpRequestMessage; import org.kaazing.gateway.transport.http.bridge.HttpResponseMessage; import org.kaazing.gateway.transport.test.Expectations; import org.kaazing.test.util.Mockery; import org.kaazing.mina.core.buffer.IoBufferEx; import org.kaazing.mina.core.buffer.SimpleBufferAllocator; public class HttpxeProtocolFilterTest { private Mockery context = new Mockery(); private HttpAcceptSession serverSession = context.mock(HttpAcceptSession.class); private HttpConnectSession clientSession = context.mock(HttpConnectSession.class); @SuppressWarnings("unchecked") private Set<HttpCookie> writeCookies = context.mock(Set.class); private IoFilterChain filterChain = context.mock(IoFilterChain.class); private NextFilter nextFilter = context.mock(NextFilter.class); @Test public void shouldWriteResponseWithInsertedStatusNotFound() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(CLIENT_NOT_FOUND); context.checking(new Expectations() { { oneOf(serverSession).setVersion(HTTP_1_1); oneOf(serverSession).setStatus(CLIENT_NOT_FOUND); oneOf(serverSession).setWriteHeader("Content-Type", "text/plain;charset=UTF-8"); oneOf(serverSession).getStatus(); will(returnValue(SUCCESS_OK)); oneOf(serverSession).getWriteHeader(HttpHeaders.HEADER_CACHE_CONTROL); will(returnValue(null)); oneOf(serverSession).setWriteHeader(HttpHeaders.HEADER_CACHE_CONTROL, "no-cache"); oneOf(serverSession).getFilterChain(); will(returnValue(filterChain)); oneOf(filterChain).addFirst(with(equal("http#content-length")), with(aNonNull(HttpContentLengthAdjustmentFilter.class))); oneOf(nextFilter).filterWrite(with(serverSession), with(hasMessage(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(CLIENT_NOT_FOUND); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.filterWrite(nextFilter, serverSession, new DefaultWriteRequest(httpResponse)); context.assertIsSatisfied(); } @Test public void shouldWriteResponseWithoutInsertingStatusClientUnauthorized() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(CLIENT_UNAUTHORIZED); expectedResponse.setHeader("WWW-Authenticate", "Basic realm=\"WallyWorld\""); context.checking(new Expectations() { { oneOf(serverSession).setVersion(HTTP_1_1); oneOf(serverSession).setStatus(SUCCESS_OK); oneOf(serverSession).setWriteHeader("Content-Type", "text/plain;charset=UTF-8"); oneOf(serverSession).getStatus(); will(returnValue(SUCCESS_OK)); oneOf(serverSession).getWriteHeader(HttpHeaders.HEADER_CACHE_CONTROL); will(returnValue(null)); oneOf(serverSession).setWriteHeader(HttpHeaders.HEADER_CACHE_CONTROL, "no-cache"); oneOf(serverSession).getFilterChain(); will(returnValue(filterChain)); oneOf(filterChain).addFirst(with(equal("http#content-length")), with(aNonNull(HttpContentLengthAdjustmentFilter.class))); oneOf(nextFilter).filterWrite(with(serverSession), with(hasMessage(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(CLIENT_UNAUTHORIZED); httpResponse.setHeader("WWW-Authenticate", "Basic realm=\"WallyWorld\""); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.filterWrite(nextFilter, serverSession, new DefaultWriteRequest(httpResponse)); context.assertIsSatisfied(); } @Test public void shouldWriteResponseWithoutInsertingStatusRedirectFound() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(REDIRECT_FOUND); expectedResponse.setHeader("Location", "https://www.w3.org/"); context.checking(new Expectations() { { oneOf(serverSession).setVersion(HTTP_1_1); oneOf(serverSession).setStatus(SUCCESS_OK); oneOf(serverSession).setWriteHeader("Content-Type", "text/plain;charset=UTF-8"); oneOf(serverSession).getStatus(); will(returnValue(SUCCESS_OK)); oneOf(serverSession).getWriteHeader(HttpHeaders.HEADER_CACHE_CONTROL); will(returnValue(null)); oneOf(serverSession).setWriteHeader(HttpHeaders.HEADER_CACHE_CONTROL, "no-cache"); oneOf(serverSession).getFilterChain(); will(returnValue(filterChain)); oneOf(filterChain).addFirst(with(equal("http#content-length")), with(aNonNull(HttpContentLengthAdjustmentFilter.class))); oneOf(nextFilter).filterWrite(with(serverSession), with(hasMessage(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(REDIRECT_FOUND); httpResponse.setHeader("Location", "https://www.w3.org/"); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.filterWrite(nextFilter, serverSession, new DefaultWriteRequest(httpResponse)); context.assertIsSatisfied(); } private static HttpBufferAllocator httpBufferAllocator = new HttpBufferAllocator(SimpleBufferAllocator.BUFFER_ALLOCATOR); private static IoBufferEx wrap(byte[] array) { return httpBufferAllocator.wrap(ByteBuffer.wrap(array)); } @Test public void shouldWriteResponseWithoutInsertingStatusRedirectMultipleChoices() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(REDIRECT_MULTIPLE_CHOICES); expectedResponse.setHeader("Location", "https://www.w3.org/"); String[] alternatives = new String[] { "https://www.w3.org/", "http://www.w3.org/" }; byte[] array = join(alternatives, "\n").getBytes(UTF_8); final HttpContentMessage expectedContent = new HttpContentMessage(wrap(array), true); expectedResponse.setContent(expectedContent); context.checking(new Expectations() { { oneOf(serverSession).setVersion(HTTP_1_1); oneOf(serverSession).setStatus(SUCCESS_OK); oneOf(serverSession).setWriteHeader("Content-Type", "text/plain;charset=UTF-8"); oneOf(serverSession).getStatus(); will(returnValue(SUCCESS_OK)); oneOf(serverSession).getWriteHeader(HttpHeaders.HEADER_CACHE_CONTROL); will(returnValue(null)); oneOf(serverSession).setWriteHeader(HttpHeaders.HEADER_CACHE_CONTROL, "no-cache"); oneOf(serverSession).getFilterChain(); will(returnValue(filterChain)); oneOf(filterChain).addFirst(with(equal("http#content-length")), with(aNonNull(HttpContentLengthAdjustmentFilter.class))); oneOf(nextFilter).filterWrite(with(serverSession), with(hasMessage(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(REDIRECT_MULTIPLE_CHOICES); httpResponse.setHeader("Location", "https://www.w3.org/"); HttpContentMessage httpContent = new HttpContentMessage(wrap(array), true); httpResponse.setContent(httpContent); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.filterWrite(nextFilter, serverSession, new DefaultWriteRequest(httpResponse)); context.assertIsSatisfied(); } @Test public void shouldWriteResponseWithInsertedCookies() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(REDIRECT_FOUND); expectedResponse.setReason("Cross-Origin Redirect"); expectedResponse.setHeader("Location", "https://www.w3.org/"); context.checking(new Expectations() { { oneOf(serverSession).setVersion(HTTP_1_1); oneOf(serverSession).setStatus(SUCCESS_OK); oneOf(serverSession).getStatus(); will(returnValue(SUCCESS_OK)); oneOf(serverSession).getWriteHeader(HttpHeaders.HEADER_CACHE_CONTROL); will(returnValue(null)); oneOf(serverSession).setWriteHeader(HttpHeaders.HEADER_CACHE_CONTROL, "no-cache"); oneOf(serverSession).setWriteHeader("Content-Type", "text/plain;charset=UTF-8"); oneOf(serverSession).setWriteHeaders(with(stringMatching("Set-Cookie")), with(stringListMatching("KSSOID=12345;"))); oneOf(serverSession).getFilterChain(); will(returnValue(filterChain)); oneOf(filterChain).addFirst(with(equal("http#content-length")), with(aNonNull(HttpContentLengthAdjustmentFilter.class))); oneOf(nextFilter).filterWrite(with(serverSession), with(hasMessage(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(REDIRECT_FOUND); httpResponse.setReason("Cross-Origin Redirect"); httpResponse.setHeader("Location", "https://www.w3.org/"); httpResponse.setHeader("Set-Cookie", "KSSOID=12345;"); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.filterWrite(nextFilter, serverSession, new DefaultWriteRequest(httpResponse)); context.assertIsSatisfied(); } @Test public void shouldWriteResponseWithInsertedTextPlainContentType() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(SUCCESS_OK); expectedResponse.setHeader("Content-Type", "text/plain"); context.checking(new Expectations() { { oneOf(serverSession).setVersion(HTTP_1_1); oneOf(serverSession).setStatus(SUCCESS_OK); oneOf(serverSession).setWriteHeader("Content-Type", "text/plain"); oneOf(serverSession).getStatus(); will(returnValue(SUCCESS_OK)); oneOf(serverSession).getFilterChain(); will(returnValue(filterChain)); oneOf(filterChain).addFirst(with(equal("http#content-length")), with(aNonNull(HttpContentLengthAdjustmentFilter.class))); oneOf(nextFilter).filterWrite(with(serverSession), with(hasMessage(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(SUCCESS_OK); httpResponse.setHeader("Content-Type", "text/plain"); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.filterWrite(nextFilter, serverSession, new DefaultWriteRequest(httpResponse)); context.assertIsSatisfied(); } @Test public void shouldWriteResponseWithTextContentTypeInsertedAsTextPlain() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(SUCCESS_OK); expectedResponse.setHeader("Content-Type", "text/xyz;charset=windows-1252"); context.checking(new Expectations() { { oneOf(serverSession).setVersion(HTTP_1_1); oneOf(serverSession).setStatus(SUCCESS_OK); oneOf(serverSession).setWriteHeader("Content-Type", "text/plain;charset=windows-1252"); oneOf(serverSession).getStatus(); will(returnValue(SUCCESS_OK)); oneOf(serverSession).getFilterChain(); will(returnValue(filterChain)); oneOf(filterChain).addFirst(with(equal("http#content-length")), with(aNonNull(HttpContentLengthAdjustmentFilter.class))); oneOf(nextFilter).filterWrite(with(serverSession), with(hasMessage(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(SUCCESS_OK); httpResponse.setHeader("Content-Type", "text/xyz;charset=windows-1252"); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.filterWrite(nextFilter, serverSession, new DefaultWriteRequest(httpResponse)); context.assertIsSatisfied(); } @Test public void shouldWriteResponseWithInsertedAccessControlAllowHeaders() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(SUCCESS_OK); expectedResponse.setHeader("Content-Type", "text/xyz;charset=windows-1252"); context.checking(new Expectations() { { oneOf(serverSession).setVersion(HTTP_1_1); oneOf(serverSession).setStatus(SUCCESS_OK); oneOf(serverSession).setWriteHeader("Content-Type", "text/plain;charset=windows-1252"); oneOf(serverSession).setWriteHeaders(with(stringMatching("Access-Control-Allow-Headers")), with(stringListMatching("x-websocket-extensions"))); oneOf(serverSession).getStatus(); will(returnValue(SUCCESS_OK)); oneOf(serverSession).getFilterChain(); will(returnValue(filterChain)); oneOf(filterChain).addFirst(with(equal("http#content-length")), with(aNonNull(HttpContentLengthAdjustmentFilter.class))); oneOf(nextFilter).filterWrite(with(serverSession), with(hasMessage(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(SUCCESS_OK); httpResponse.setHeader("Content-Type", "text/xyz;charset=windows-1252"); httpResponse.setHeader("Access-Control-Allow-Headers", "x-websocket-extensions"); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.filterWrite(nextFilter, serverSession, new DefaultWriteRequest(httpResponse)); context.assertIsSatisfied(); } @Test public void shouldWriteResponseWithInsertedContentEncoding() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(SUCCESS_OK); expectedResponse.setHeader("Content-Type", "text/xyz;charset=windows-1252"); context.checking(new Expectations() { { oneOf(serverSession).setVersion(HTTP_1_1); oneOf(serverSession).setStatus(SUCCESS_OK); oneOf(serverSession).setWriteHeader("Content-Type", "text/plain;charset=windows-1252"); oneOf(serverSession).setWriteHeaders(with(stringMatching("Content-Encoding")), with(stringListMatching("gzip"))); oneOf(serverSession).getStatus(); will(returnValue(SUCCESS_OK)); oneOf(nextFilter).filterWrite(with(serverSession), with(hasMessage(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(SUCCESS_OK); httpResponse.setHeader("Content-Type", "text/xyz;charset=windows-1252"); httpResponse.setHeader("Content-Encoding", "gzip"); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.filterWrite(nextFilter, serverSession, new DefaultWriteRequest(httpResponse)); context.assertIsSatisfied(); } @Test public void shouldWriteResponseWithInsertedCacheControl() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(REDIRECT_FOUND); expectedResponse.setReason("Cross-Origin Redirect"); expectedResponse.setHeader("Location", "https://www.w3.org/"); context.checking(new Expectations() { { oneOf(serverSession).setVersion(HTTP_1_1); oneOf(serverSession).setStatus(SUCCESS_OK); oneOf(serverSession).setWriteHeader("Content-Type", "text/plain;charset=UTF-8"); oneOf(serverSession).setWriteHeaders(with(stringMatching("Cache-Control")), with(stringListMatching("private"))); oneOf(serverSession).getStatus(); will(returnValue(SUCCESS_OK)); oneOf(serverSession).getWriteHeader(HttpHeaders.HEADER_CACHE_CONTROL); will(returnValue("private")); oneOf(serverSession).getFilterChain(); will(returnValue(filterChain)); oneOf(filterChain).addFirst(with(equal("http#content-length")), with(aNonNull(HttpContentLengthAdjustmentFilter.class))); oneOf(nextFilter).filterWrite(with(serverSession), with(hasMessage(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(HttpStatus.REDIRECT_FOUND); httpResponse.setReason("Cross-Origin Redirect"); httpResponse.setHeader("Cache-Control", "private"); httpResponse.setHeader("Location", "https://www.w3.org/"); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.filterWrite(nextFilter, serverSession, new DefaultWriteRequest(httpResponse)); context.assertIsSatisfied(); } @Test public void shouldWriteResponseWithInsertedContentTypeApplicationOctetStream() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(SUCCESS_OK); expectedResponse.setHeader("Content-Type", "application/octet-stream"); context.checking(new Expectations() { { oneOf(serverSession).setVersion(HTTP_1_1); oneOf(serverSession).setStatus(SUCCESS_OK); oneOf(serverSession).setWriteHeader("Content-Type", "application/octet-stream"); oneOf(serverSession).getStatus(); will(returnValue(SUCCESS_OK)); oneOf(serverSession).getFilterChain(); will(returnValue(filterChain)); oneOf(filterChain).addFirst(with(equal("http#content-length")), with(aNonNull(HttpContentLengthAdjustmentFilter.class))); oneOf(nextFilter).filterWrite(with(serverSession), with(hasMessage(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(SUCCESS_OK); httpResponse.setHeader("Content-Type", "application/octet-stream"); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.filterWrite(nextFilter, serverSession, new DefaultWriteRequest(httpResponse)); context.assertIsSatisfied(); } @Test public void shouldWriteResponseWithIncompleteContent() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(SUCCESS_OK); expectedResponse.setHeader("Content-Type", "text/plain;charset=UTF-8"); byte[] array = "Hello, world".getBytes(UTF_8); HttpContentMessage expectedContent = new HttpContentMessage(wrap(array), false); expectedResponse.setContent(expectedContent); context.checking(new Expectations() { { allowing(serverSession).getWriteHeader("Content-Length"); will(returnValue(null)); allowing(serverSession).setWriteHeader("Content-Length", "0"); oneOf(serverSession).setVersion(HTTP_1_1); oneOf(serverSession).setStatus(SUCCESS_OK); oneOf(serverSession).setWriteHeader("Content-Type", "text/plain;charset=UTF-8"); oneOf(serverSession).getStatus(); will(returnValue(SUCCESS_OK)); oneOf(nextFilter).filterWrite(with(serverSession), with(hasMessage(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(SUCCESS_OK); httpResponse.setHeader("Content-Type", "text/plain;charset=UTF-8"); HttpContentMessage httpContent = new HttpContentMessage(wrap(array), false); httpResponse.setContent(httpContent); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.filterWrite(nextFilter, serverSession, new DefaultWriteRequest(httpResponse)); context.assertIsSatisfied(); } @Test public void shouldWriteResponseWithInsertedTransferEncodingChunked() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(SUCCESS_OK); expectedResponse.setHeader("Content-Type", "text/plain;charset=UTF-8"); byte[] array = "Hello, world".getBytes(UTF_8); HttpContentMessage expectedContent = new HttpContentMessage(wrap(array), false, true, false); expectedResponse.setContent(expectedContent); context.checking(new Expectations() { { allowing(serverSession).getWriteHeader("Content-Length"); will(returnValue(null)); allowing(serverSession).setWriteHeader("Content-Length", "0"); oneOf(serverSession).setVersion(HTTP_1_1); oneOf(serverSession).setStatus(SUCCESS_OK); oneOf(serverSession).setWriteHeaders(with(stringMatching("Transfer-Encoding")), with(stringListMatching("chunked"))); oneOf(serverSession).setWriteHeader("Content-Type", "text/plain;charset=UTF-8"); oneOf(serverSession).getStatus(); will(returnValue(SUCCESS_OK)); oneOf(nextFilter).filterWrite(with(serverSession), with(hasMessage(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(SUCCESS_OK); httpResponse.setHeader("Content-Type", "text/plain;charset=UTF-8"); httpResponse.setHeader("Transfer-Encoding", "chunked"); HttpContentMessage httpContent = new HttpContentMessage(wrap(array), false, true, false); httpResponse.setContent(httpContent); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.filterWrite(nextFilter, serverSession, new DefaultWriteRequest(httpResponse)); context.assertIsSatisfied(); } @Test public void shouldWriteResponseWithCompleteContent() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(SUCCESS_OK); expectedResponse.setHeader("Content-Type", "text/plain;charset=UTF-8"); byte[] array = "Hello, world".getBytes(UTF_8); HttpContentMessage expectedContent = new HttpContentMessage(wrap(array), true); expectedResponse.setContent(expectedContent); context.checking(new Expectations() { { allowing(serverSession).getWriteHeader("Content-Length"); will(returnValue(null)); allowing(serverSession).setWriteHeader("Content-Length", "0"); oneOf(serverSession).setVersion(HTTP_1_1); oneOf(serverSession).setStatus(SUCCESS_OK); oneOf(serverSession).setWriteHeader("Content-Type", "text/plain;charset=UTF-8"); oneOf(serverSession).getStatus(); will(returnValue(SUCCESS_OK)); oneOf(serverSession).getFilterChain(); will(returnValue(filterChain)); oneOf(filterChain).addFirst(with(equal("http#content-length")), with(aNonNull(HttpContentLengthAdjustmentFilter.class))); oneOf(nextFilter).filterWrite(with(serverSession), with(hasMessage(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(SUCCESS_OK); httpResponse.setHeader("Content-Type", "text/plain;charset=UTF-8"); HttpContentMessage httpContent = new HttpContentMessage(wrap(array), true); httpResponse.setContent(httpContent); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.filterWrite(nextFilter, serverSession, new DefaultWriteRequest(httpResponse)); context.assertIsSatisfied(); } @Test public void shouldWriteResponseAfterPrependingContentLengthFilter() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(SUCCESS_OK); expectedResponse.setContent(new HttpContentMessage(wrap(new byte[0]), false)); byte[] array = "Hello, world".getBytes(UTF_8); final HttpContentMessage expectedContent = new HttpContentMessage(wrap(array), true); expectedResponse.setContent(expectedContent); context.checking(new Expectations() { { oneOf(serverSession).setVersion(HTTP_1_1); oneOf(serverSession).setStatus(SUCCESS_OK); oneOf(serverSession).setWriteHeader("Content-Type", "text/plain;charset=UTF-8"); oneOf(serverSession).setWriteHeaders(with(stringMatching("Content-Length")), with(stringListMatching("12"))); allowing(serverSession).getWriteHeader("Content-Length"); will(returnValue("12")); oneOf(serverSession).getStatus(); will(returnValue(SUCCESS_OK)); oneOf(serverSession).getFilterChain(); will(returnValue(filterChain)); oneOf(filterChain).addFirst(with(equal("http#content-length")), with(aNonNull(HttpContentLengthAdjustmentFilter.class))); oneOf(nextFilter).filterWrite(with(serverSession), with(hasMessage(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(SUCCESS_OK); httpResponse.setHeader("Content-Length", "12"); HttpContentMessage httpContent = new HttpContentMessage(wrap(array), true); httpResponse.setContent(httpContent); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.filterWrite(nextFilter, serverSession, new DefaultWriteRequest(httpResponse)); context.assertIsSatisfied(); } @Test public void shouldReceivePostRequestWithExtractedHeadersAndContent() throws Exception { byte[] array = ">|<".getBytes(UTF_8); final HttpRequestMessage expectedRequest = new HttpRequestMessage(); expectedRequest.setVersion(HTTP_1_1); expectedRequest.setMethod(POST); expectedRequest.setRequestURI(URI.create("/kerberos5/;api/get-cookies?.kv=10.05")); expectedRequest.setHeader("Accept", "*/*"); expectedRequest.setHeader("Accept-Language", "en-us"); expectedRequest.addHeader("Accept-Language", "fr-fr"); expectedRequest.setHeader("Content-Length", "3"); expectedRequest.setHeader("Content-Type", "text/plain"); expectedRequest.setHeader("Host", "gateway.kzng.net:8003"); expectedRequest.setHeader("Referer", "http://gateway.kzng.net:8003/?.kr=xsa"); expectedRequest.setHeader("User-Agent", "Shockwave Flash"); expectedRequest.setHeader("X-Origin", "http://gateway.kzng.net:8000"); expectedRequest.setHeader("x-flash-version", "9,0,124,0"); expectedRequest.setContent(new HttpContentMessage(wrap(array), true)); context.checking(new Expectations() { { oneOf(serverSession).getVersion(); will(returnValue(HTTP_1_1)); oneOf(serverSession).getMethod(); will(returnValue(POST)); oneOf(serverSession).getRequestURI(); will(returnValue(URI.create("/kerberos5/;api/get-cookies?.kv=10.05"))); oneOf(serverSession).getReadHeaderNames(); will(returnValue(asList("Accept", "Accept-Language", "Content-Length", "Content-Type", "Host", "X-Origin", "Referer", "User-Agent", "x-flash-version"))); oneOf(serverSession).getReadHeaders(with("Accept")); will(returnValue(Collections.singletonList("*/*"))); oneOf(serverSession).getReadHeaders(with("Accept-Language")); will(returnValue(asList("en-us","fr-fr"))); oneOf(serverSession).getReadHeader(with("Content-Type")); will(returnValue("application/x-message-http")); oneOf(serverSession).getReadHeaders(with("Host")); will(returnValue(Collections.singletonList("gateway.kzng.net:8003"))); oneOf(serverSession).getReadHeaders(with("Referer")); will(returnValue(Collections.singletonList("http://gateway.kzng.net:8003/?.kr=xsa"))); oneOf(serverSession).getReadHeaders(with("User-Agent")); will(returnValue(Collections.singletonList("Shockwave Flash"))); oneOf(serverSession).getReadHeaders(with("X-Origin")); will(returnValue(Collections.singletonList("http://gateway.kzng.net:8000"))); oneOf(serverSession).getReadHeaders(with("x-flash-version")); will(returnValue(Collections.singletonList("9,0,124,0"))); oneOf(serverSession).getReadCookies(); will(returnValue(emptyList())); oneOf(nextFilter).messageReceived(with(serverSession), with(equal(expectedRequest))); } }); HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.setVersion(HTTP_1_1); httpRequest.setMethod(POST); httpRequest.setRequestURI(URI.create("/kerberos5/;api/get-cookies?.kv=10.05")); httpRequest.setHeader("Content-Length", "3"); httpRequest.setHeader("Content-Type", "text/plain"); httpRequest.setContent(new HttpContentMessage(wrap(array), true)); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.messageReceived(nextFilter, serverSession, httpRequest); context.assertIsSatisfied(); } @Test public void shouldReceiveGetRequestWithExtractedHeadersIncludingMultiValuedHeaderAndCookie() throws Exception { final HttpRequestMessage expectedRequest = new HttpRequestMessage(); expectedRequest.setVersion(HTTP_1_1); expectedRequest.setMethod(GET); expectedRequest.setRequestURI(URI.create("/")); expectedRequest.setHeader("Authorization", "restricted-usage"); expectedRequest.setHeader("X-Header", "value1"); expectedRequest.addHeader("X-Header", "value2"); expectedRequest.addCookie(new DefaultHttpCookie("KSSOID", "0123456789abcdef")); expectedRequest.setContent(EMPTY); context.checking(new Expectations() { { oneOf(serverSession).getVersion(); will(returnValue(HTTP_1_1)); oneOf(serverSession).getMethod(); will(returnValue(POST)); oneOf(serverSession).getRequestURI(); will(returnValue(URI.create("/"))); oneOf(serverSession).getReadHeaderNames(); will(returnValue(asList("Content-Length", "Content-Type", "X-Header"))); oneOf(serverSession).getReadHeader(with("Content-Type")); will(returnValue("application/x-message-http")); oneOf(serverSession).getReadHeaders(with("X-Header")); will(returnValue(asList("value1","value2"))); oneOf(serverSession).getReadCookies(); will(returnValue(Collections.singletonList(new DefaultHttpCookie("KSSOID", "0123456789abcdef")))); oneOf(nextFilter).messageReceived(with(serverSession), with(equal(expectedRequest))); } }); HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.setVersion(HTTP_1_1); httpRequest.setMethod(GET); httpRequest.setRequestURI(URI.create("/")); httpRequest.setHeader("Authorization", "restricted-usage"); httpRequest.setContent(EMPTY); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.messageReceived(nextFilter, serverSession, httpRequest); context.assertIsSatisfied(); } @Test (expected = ProtocolCodecException.class) public void shouldRejectReceivedRequestWithInconsistentURI() throws Exception { final HttpRequestMessage expectedRequest = new HttpRequestMessage(); expectedRequest.setVersion(HTTP_1_1); expectedRequest.setMethod(GET); expectedRequest.setRequestURI(URI.create("/")); expectedRequest.setContent(EMPTY); context.checking(new Expectations() { { oneOf(serverSession).getVersion(); will(returnValue(HTTP_1_1)); oneOf(serverSession).getMethod(); will(returnValue(POST)); oneOf(serverSession).getRequestURI(); will(returnValue(URI.create("/"))); oneOf(serverSession).getReadHeaderNames(); will(returnValue(asList("Content-Length", "Content-Type"))); oneOf(serverSession).getReadHeader(with("Content-Length")); will(returnValue("102")); oneOf(serverSession).getReadHeader(with("Content-Type")); will(returnValue("application/x-message-http")); oneOf(serverSession).getStatus(); will(returnValue(SUCCESS_OK)); oneOf(nextFilter).messageReceived(with(serverSession), with(equal(expectedRequest))); } }); HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.setVersion(HTTP_1_1); httpRequest.setMethod(GET); httpRequest.setRequestURI(URI.create("/different/path")); httpRequest.setContent(EMPTY); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.messageReceived(nextFilter, serverSession, httpRequest); context.assertIsSatisfied(); } @Test (expected = ProtocolCodecException.class) public void shouldRejectReceivedRequestWithInconsistentVersion() throws Exception { final HttpRequestMessage expectedRequest = new HttpRequestMessage(); expectedRequest.setVersion(HTTP_1_1); expectedRequest.setMethod(GET); expectedRequest.setRequestURI(URI.create("/")); expectedRequest.setContent(EMPTY); context.checking(new Expectations() { { oneOf(serverSession).getVersion(); will(returnValue(HTTP_1_1)); oneOf(serverSession).getMethod(); will(returnValue(POST)); oneOf(serverSession).getRequestURI(); will(returnValue(URI.create("/"))); oneOf(serverSession).getReadHeaderNames(); will(returnValue(asList("Content-Length", "Content-Type"))); oneOf(serverSession).getReadHeader(with("Content-Length")); will(returnValue("102")); oneOf(serverSession).getReadHeader(with("Content-Type")); will(returnValue("application/x-message-http")); oneOf(serverSession).getStatus(); will(returnValue(SUCCESS_OK)); oneOf(nextFilter).messageReceived(with(serverSession), with(equal(expectedRequest))); } }); HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.setVersion(HTTP_1_0); httpRequest.setMethod(GET); httpRequest.setRequestURI(URI.create("/")); httpRequest.setContent(EMPTY); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.messageReceived(nextFilter, serverSession, httpRequest); context.assertIsSatisfied(); } @Test (expected = ProtocolCodecException.class) public void shouldRejectReceivedRequestWithInvalidHeader() throws Exception { final HttpRequestMessage expectedRequest = new HttpRequestMessage(); expectedRequest.setVersion(HTTP_1_1); expectedRequest.setMethod(GET); expectedRequest.setRequestURI(URI.create("/")); expectedRequest.setContent(EMPTY); context.checking(new Expectations() { { oneOf(serverSession).getVersion(); will(returnValue(HTTP_1_1)); oneOf(serverSession).getMethod(); will(returnValue(POST)); oneOf(serverSession).getRequestURI(); will(returnValue(URI.create("/"))); oneOf(serverSession).getReadHeaderNames(); will(returnValue(asList("Content-Length", "Content-Type"))); oneOf(serverSession).getReadHeader(with("Content-Length")); will(returnValue("102")); oneOf(serverSession).getReadHeader(with("Content-Type")); will(returnValue("application/x-message-http")); oneOf(serverSession).getStatus(); will(returnValue(SUCCESS_OK)); oneOf(nextFilter).messageReceived(with(serverSession), with(equal(expectedRequest))); } }); HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.setVersion(HTTP_1_1); httpRequest.setMethod(GET); httpRequest.setRequestURI(URI.create("/")); httpRequest.setHeader("Accept-Charset", "value"); httpRequest.setContent(EMPTY); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(false); filter.messageReceived(nextFilter, serverSession, httpRequest); context.assertIsSatisfied(); } @Test public void shouldReceiveResponseWithStatusRedirectNotModified() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(REDIRECT_NOT_MODIFIED); context.checking(new Expectations() { { allowing(clientSession).getVersion(); will(returnValue(HTTP_1_1)); allowing(clientSession).getStatus(); will(returnValue(SUCCESS_OK)); allowing(clientSession).getReadHeaderNames(); will(returnValue(emptyList())); allowing(clientSession).getReadCookies(); will(returnValue(emptyList())); oneOf(nextFilter).messageReceived(with(clientSession), with(equal(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(REDIRECT_NOT_MODIFIED); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(true); filter.messageReceived(nextFilter, clientSession, httpResponse); context.assertIsSatisfied(); } @Test public void shouldReceiveResponseWithStatusClientUnauthorized() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(CLIENT_UNAUTHORIZED); expectedResponse.setHeader("WWW-Autheticate", "Basic realm=\"WallyWorld\""); context.checking(new Expectations() { { allowing(clientSession).getVersion(); will(returnValue(HTTP_1_1)); allowing(clientSession).getStatus(); will(returnValue(SUCCESS_OK)); allowing(clientSession).getReadHeaderNames(); will(returnValue(emptyList())); allowing(clientSession).getReadCookies(); will(returnValue(emptyList())); oneOf(nextFilter).messageReceived(with(clientSession), with(equal(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(CLIENT_UNAUTHORIZED); httpResponse.setHeader("WWW-Autheticate", "Basic realm=\"WallyWorld\""); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(true); filter.messageReceived(nextFilter, clientSession, httpResponse); context.assertIsSatisfied(); } @Test public void shouldReceiveResponseWithExtractedCookies() throws Exception { final List<HttpCookie> expectedCookies = Collections.singletonList(new DefaultHttpCookie("KSSOID", "12345")); final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(REDIRECT_FOUND); expectedResponse.setReason("Cross-Origin Redirect"); expectedResponse.setHeader("Location", "https://www.w3.org/"); expectedResponse.setCookies(expectedCookies); context.checking(new Expectations() { { allowing(clientSession).getVersion(); will(returnValue(HTTP_1_1)); allowing(clientSession).getStatus(); will(returnValue(SUCCESS_OK)); allowing(clientSession).getReadHeaderNames(); will(returnValue(Collections.<String>emptySet())); oneOf(clientSession).getReadCookies(); will(returnValue(expectedCookies)); oneOf(nextFilter).messageReceived(with(clientSession), with(equal(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(REDIRECT_FOUND); httpResponse.setReason("Cross-Origin Redirect"); httpResponse.setHeader("Location", "https://www.w3.org/"); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(true); filter.messageReceived(nextFilter, clientSession, httpResponse); context.assertIsSatisfied(); } @Test public void shouldReceiveResponseWithContentTypeTextPlain() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(SUCCESS_OK); expectedResponse.setHeader("Content-Type", "text/plain"); context.checking(new Expectations() { { allowing(clientSession).getVersion(); will(returnValue(HTTP_1_1)); allowing(clientSession).getStatus(); will(returnValue(SUCCESS_OK)); allowing(clientSession).getReadCookies(); will(returnValue(emptyList())); oneOf(clientSession).getReadHeaderNames(); will(returnValue(Collections.singletonList("Content-Type"))); oneOf(clientSession).getReadHeader("Content-Type"); will(returnValue("text/plain")); oneOf(nextFilter).messageReceived(with(clientSession), with(equal(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(SUCCESS_OK); httpResponse.setHeader("Content-Type", "text/plain"); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(true); filter.messageReceived(nextFilter, clientSession, httpResponse); context.assertIsSatisfied(); } @Test public void shouldReceiveResponseWithTextContentTypeInsertedAsTextPlain() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(SUCCESS_OK); expectedResponse.setHeader("Content-Type", "text/xyz;charset=windows-1252"); context.checking(new Expectations() { { allowing(clientSession).getVersion(); will(returnValue(HTTP_1_1)); allowing(clientSession).getStatus(); will(returnValue(SUCCESS_OK)); allowing(clientSession).getReadCookies(); will(returnValue(emptyList())); oneOf(clientSession).getReadHeaderNames(); will(returnValue(Collections.singletonList("Content-Type"))); oneOf(clientSession).getReadHeader("Content-Type"); will(returnValue("text/plain;charset=windows-1252")); oneOf(nextFilter).messageReceived(with(clientSession), with(equal(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(SUCCESS_OK); httpResponse.setHeader("Content-Type", "text/xyz;charset=windows-1252"); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(true); filter.messageReceived(nextFilter, clientSession, httpResponse); context.assertIsSatisfied(); } @Test (expected = ProtocolCodecException.class) public void shouldRejectReceivedResponseWithIncompatibleTextContentType() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(SUCCESS_OK); expectedResponse.setHeader("Content-Type", "text/xyz;charset=windows-1252"); context.checking(new Expectations() { { allowing(clientSession).getVersion(); will(returnValue(HTTP_1_1)); allowing(clientSession).getStatus(); will(returnValue(SUCCESS_OK)); allowing(clientSession).getReadCookies(); will(returnValue(emptyList())); oneOf(clientSession).getReadHeaderNames(); will(returnValue(Collections.singletonList("Content-Type"))); oneOf(clientSession).getReadHeader("Content-Type"); will(returnValue("text/pdf")); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(SUCCESS_OK); httpResponse.setHeader("Content-Type", "text/xyz;charset=windows-1252"); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(true); filter.messageReceived(nextFilter, clientSession, httpResponse); context.assertIsSatisfied(); } @Test public void shouldReceiveResponseWithExtractedAccessControlAllowHeaders() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(SUCCESS_OK); expectedResponse.setHeader("Content-Type", "text/xyz;charset=windows-1252"); expectedResponse.setHeader("Access-Control-Allow-Headers", "x-websocket-extensions"); context.checking(new Expectations() { { allowing(clientSession).getVersion(); will(returnValue(HTTP_1_1)); allowing(clientSession).getStatus(); will(returnValue(SUCCESS_OK)); allowing(clientSession).getReadCookies(); will(returnValue(emptyList())); oneOf(clientSession).getReadHeaderNames(); will(returnValue(asList("Content-Type", "Access-Control-Allow-Headers"))); oneOf(clientSession).getReadHeader("Content-Type"); will(returnValue("text/plain;charset=windows-1252")); oneOf(clientSession).getReadHeader("Access-Control-Allow-Headers"); will(returnValue("x-websocket-extensions")); oneOf(nextFilter).messageReceived(with(clientSession), with(equal(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(SUCCESS_OK); httpResponse.setHeader("Content-Type", "text/xyz;charset=windows-1252"); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(true); filter.messageReceived(nextFilter, clientSession, httpResponse); context.assertIsSatisfied(); } @Test public void shouldReceiveResponseWithExtractedContentEncoding() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(SUCCESS_OK); expectedResponse.setHeader("Content-Type", "text/xyz;charset=windows-1252"); expectedResponse.setHeader("Content-Encoding", "gzip"); context.checking(new Expectations() { { allowing(clientSession).getVersion(); will(returnValue(HTTP_1_1)); allowing(clientSession).getStatus(); will(returnValue(SUCCESS_OK)); allowing(clientSession).getReadCookies(); will(returnValue(emptyList())); oneOf(clientSession).getReadHeaderNames(); will(returnValue(asList("Content-Type", "Content-Encoding"))); oneOf(clientSession).getReadHeader("Content-Type"); will(returnValue("text/plain;charset=windows-1252")); oneOf(clientSession).getReadHeader("Content-Encoding"); will(returnValue("gzip")); oneOf(nextFilter).messageReceived(with(clientSession), with(equal(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(SUCCESS_OK); httpResponse.setHeader("Content-Type", "text/xyz;charset=windows-1252"); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(true); filter.messageReceived(nextFilter, clientSession, httpResponse); context.assertIsSatisfied(); } @Test public void shouldReceiveResponseWithExtractedCacheControl() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(REDIRECT_FOUND); expectedResponse.setHeader("Location", "https://www.w3.org/"); expectedResponse.setHeader("Cache-Control", "private"); context.checking(new Expectations() { { allowing(clientSession).getVersion(); will(returnValue(HTTP_1_1)); allowing(clientSession).getStatus(); will(returnValue(SUCCESS_OK)); allowing(clientSession).getReadCookies(); will(returnValue(emptyList())); oneOf(clientSession).getReadHeaderNames(); will(returnValue(asList("Content-Type", "Cache-Control"))); oneOf(clientSession).getReadHeader("Content-Type"); will(returnValue("text/plain;charset=windows-1252")); oneOf(clientSession).getReadHeader("Cache-Control"); will(returnValue("private")); oneOf(nextFilter).messageReceived(with(clientSession), with(equal(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(REDIRECT_FOUND); httpResponse.setHeader("Location", "https://www.w3.org/"); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(true); filter.messageReceived(nextFilter, clientSession, httpResponse); context.assertIsSatisfied(); } @Test public void shouldReceiveResponseWithExtractedContentTypeApplicationOctetStream() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(SUCCESS_OK); expectedResponse.setHeader("Content-Type", "application/octet-stream"); expectedResponse.setHeader("Content-Length", "0"); context.checking(new Expectations() { { allowing(clientSession).getVersion(); will(returnValue(HTTP_1_1)); allowing(clientSession).getStatus(); will(returnValue(SUCCESS_OK)); allowing(clientSession).getReadCookies(); will(returnValue(emptyList())); oneOf(clientSession).getReadHeaderNames(); will(returnValue(asList("Content-Type", "Content-Length"))); oneOf(clientSession).getReadHeader("Content-Type"); will(returnValue("application/octet-stream")); oneOf(nextFilter).messageReceived(with(clientSession), with(equal(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(SUCCESS_OK); httpResponse.setHeader("Content-Type", "application/octet-stream"); httpResponse.setHeader("Content-Length", "0"); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(true); filter.messageReceived(nextFilter, clientSession, httpResponse); context.assertIsSatisfied(); } @Test public void shouldReceiveResponseWithIncompleteContent() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(SUCCESS_OK); byte[] array = "Hello, world".getBytes(UTF_8); HttpContentMessage expectedContent = new HttpContentMessage(wrap(array), false); expectedResponse.setContent(expectedContent); context.checking(new Expectations() { { allowing(clientSession).getVersion(); will(returnValue(HTTP_1_1)); allowing(clientSession).getStatus(); will(returnValue(SUCCESS_OK)); allowing(clientSession).getReadCookies(); will(returnValue(emptyList())); oneOf(clientSession).getReadHeaderNames(); will(returnValue(emptyList())); oneOf(nextFilter).messageReceived(with(clientSession), with(equal(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(SUCCESS_OK); HttpContentMessage httpContent = new HttpContentMessage(wrap(array), false); httpResponse.setContent(httpContent); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(true); filter.messageReceived(nextFilter, clientSession, httpResponse); context.assertIsSatisfied(); } @Test public void shouldReceiveResponseWithExtractedTransferEncodingChunked() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(SUCCESS_OK); expectedResponse.setHeader("Content-Type", "text/plain;charset=UTF-8"); expectedResponse.setHeader("Transfer-Encoding", "chunked"); byte[] array = "Hello, world".getBytes(UTF_8); HttpContentMessage expectedContent = new HttpContentMessage(wrap(array), false, true, false); expectedResponse.setContent(expectedContent); context.checking(new Expectations() { { allowing(clientSession).getVersion(); will(returnValue(HTTP_1_1)); allowing(clientSession).getStatus(); will(returnValue(SUCCESS_OK)); allowing(clientSession).getReadCookies(); will(returnValue(emptyList())); oneOf(clientSession).getReadHeaderNames(); will(returnValue(asList("Transfer-Encoding", "Content-Type"))); oneOf(clientSession).getReadHeader("Transfer-Encoding"); will(returnValue("chunked")); oneOf(clientSession).getReadHeader("Content-Type"); will(returnValue("text/plain;charset=UTF-8")); oneOf(nextFilter).messageReceived(with(clientSession), with(equal(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(SUCCESS_OK); httpResponse.setHeader("Content-Type", "text/plain;charset=UTF-8"); HttpContentMessage httpContent = new HttpContentMessage(wrap(array), false, true, false); httpResponse.setContent(httpContent); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(true); filter.messageReceived(nextFilter, clientSession, httpResponse); context.assertIsSatisfied(); } @Test public void shouldReceiveResponseWithCompleteContent() throws Exception { final HttpResponseMessage expectedResponse = new HttpResponseMessage(); expectedResponse.setVersion(HTTP_1_1); expectedResponse.setStatus(SUCCESS_OK); expectedResponse.setHeader("Content-Type", "text/plain;charset=UTF-8"); byte[] array = "Hello, world".getBytes(UTF_8); HttpContentMessage expectedContent = new HttpContentMessage(wrap(array), true); expectedResponse.setContent(expectedContent); context.checking(new Expectations() { { allowing(clientSession).getVersion(); will(returnValue(HTTP_1_1)); allowing(clientSession).getStatus(); will(returnValue(SUCCESS_OK)); allowing(clientSession).getReadCookies(); will(returnValue(emptyList())); oneOf(clientSession).getReadHeaderNames(); will(returnValue(Collections.singletonList("Content-Type"))); oneOf(clientSession).getReadHeader("Content-Type"); will(returnValue("text/plain;charset=UTF-8")); oneOf(nextFilter).messageReceived(with(clientSession), with(equal(expectedResponse))); } }); HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.setVersion(HTTP_1_1); httpResponse.setStatus(SUCCESS_OK); httpResponse.setHeader("Content-Type", "text/plain;charset=UTF-8"); HttpContentMessage httpContent = new HttpContentMessage(wrap(array), true); httpResponse.setContent(httpContent); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(true); filter.messageReceived(nextFilter, clientSession, httpResponse); context.assertIsSatisfied(); } @Test public void shouldWriteRequestAfterPrependingContentLengthFilter() throws Exception { final HttpRequestMessage expectedRequest = new HttpRequestMessage(); expectedRequest.setVersion(HTTP_1_1); expectedRequest.setMethod(POST); expectedRequest.setRequestURI(URI.create("/")); expectedRequest.setContent(new HttpContentMessage(wrap(new byte[0]), false)); byte[] array = "Hello, world".getBytes(UTF_8); final HttpContentMessage expectedContent = new HttpContentMessage(wrap(array), true); expectedRequest.setContent(expectedContent); context.checking(new Expectations() { { oneOf(clientSession).setVersion(HTTP_1_1); oneOf(clientSession).setMethod(POST); oneOf(clientSession).setRequestURI(URI.create("/")); oneOf(clientSession).setWriteHeader("Content-Type", "text/plain;charset=UTF-8"); oneOf(clientSession).setWriteHeader("Content-Length", "12"); oneOf(clientSession).getFilterChain(); will(returnValue(filterChain)); oneOf(filterChain).addFirst(with("http#content-length"), with(any(HttpContentLengthAdjustmentFilter.class))); oneOf(nextFilter).filterWrite(with(clientSession), with(hasMessage(expectedRequest))); } }); HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.setVersion(HTTP_1_1); httpRequest.setMethod(POST); httpRequest.setRequestURI(URI.create("/")); httpRequest.setHeader("Content-Length", "12"); HttpContentMessage httpContent = new HttpContentMessage(wrap(array), true); httpRequest.setContent(httpContent); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(true); filter.filterWrite(nextFilter, clientSession, new DefaultWriteRequest(httpRequest)); context.assertIsSatisfied(); } @Test public void shouldWritePostRequestWithInsertedHeadersAndContent() throws Exception { byte[] array = ">|<".getBytes(UTF_8); final HttpRequestMessage expectedRequest = new HttpRequestMessage(); expectedRequest.setVersion(HTTP_1_1); expectedRequest.setMethod(POST); expectedRequest.setRequestURI(URI.create("/kerberos5/;api/get-cookies?.kv=10.05")); expectedRequest.setHeader("Content-Type", "text/plain"); expectedRequest.setContent(new HttpContentMessage(wrap(array), true)); context.checking(new Expectations() { { oneOf(clientSession).setVersion(HTTP_1_1); oneOf(clientSession).setMethod(POST); oneOf(clientSession).setRequestURI(URI.create("/kerberos5/;api/get-cookies?.kv=10.05")); oneOf(clientSession).setWriteHeader("Accept", "*/*"); oneOf(clientSession).setWriteHeader("Accept-Language", "en-us"); oneOf(clientSession).setWriteHeader("Content-Length", "3"); oneOf(clientSession).setWriteHeader("Content-Type", "text/plain"); oneOf(clientSession).setWriteHeader("Host", "gateway.kzng.net:8003"); oneOf(clientSession).setWriteHeader("Referer", "http://gateway.kzng.net:8003/?.kr=xsa"); oneOf(clientSession).setWriteHeader("User-Agent", "Shockwave Flash"); oneOf(clientSession).setWriteHeader("X-Origin", "http://gateway.kzng.net:8000"); oneOf(clientSession).setWriteHeader("x-flash-version", "9,0,124,0"); oneOf(clientSession).getFilterChain(); will(returnValue(filterChain)); oneOf(filterChain).addFirst(with("http#content-length"), with(any(HttpContentLengthAdjustmentFilter.class))); oneOf(nextFilter).filterWrite(with(clientSession), with(hasMessage(expectedRequest))); } }); HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.setVersion(HTTP_1_1); httpRequest.setMethod(POST); httpRequest.setRequestURI(URI.create("/kerberos5/;api/get-cookies?.kv=10.05")); httpRequest.setHeader("Accept", "*/*"); httpRequest.setHeader("Accept-Language", "en-us"); httpRequest.setHeader("Content-Length", "3"); httpRequest.setHeader("Content-Type", "text/plain"); httpRequest.setHeader("Host", "gateway.kzng.net:8003"); httpRequest.setHeader("Referer", "http://gateway.kzng.net:8003/?.kr=xsa"); httpRequest.setHeader("User-Agent", "Shockwave Flash"); httpRequest.setHeader("X-Origin", "http://gateway.kzng.net:8000"); httpRequest.setHeader("x-flash-version", "9,0,124,0"); httpRequest.setContent(new HttpContentMessage(wrap(array), true)); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(true); filter.filterWrite(nextFilter, clientSession, new DefaultWriteRequest(httpRequest)); context.assertIsSatisfied(); } @Test public void shouldWriteGetRequestWithInsertedHeadersAndCookies() throws Exception { final HttpRequestMessage expectedRequest = new HttpRequestMessage(); expectedRequest.setVersion(HTTP_1_1); expectedRequest.setMethod(GET); expectedRequest.setRequestURI(URI.create("/")); expectedRequest.setHeader("Authorization", "restricted-usage"); expectedRequest.setContent(EMPTY); context.checking(new Expectations() { { oneOf(clientSession).setVersion(HTTP_1_1); oneOf(clientSession).setMethod(POST); oneOf(clientSession).setRequestURI(URI.create("/")); oneOf(clientSession).setWriteHeader("Content-Type", "text/plain;charset=UTF-8"); oneOf(clientSession).setWriteHeader("X-Header", "value"); oneOf(nextFilter).filterWrite(with(clientSession), with(hasMessage(expectedRequest))); } }); HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.setVersion(HTTP_1_1); httpRequest.setMethod(GET); httpRequest.setRequestURI(URI.create("/")); httpRequest.setHeader("Authorization", "restricted-usage"); httpRequest.setHeader("X-Header", "value"); httpRequest.setContent(EMPTY); HttpxeProtocolFilter filter = new HttpxeProtocolFilter(true); filter.filterWrite(nextFilter, clientSession, new DefaultWriteRequest(httpRequest)); context.assertIsSatisfied(); } }
cmebarrow/gateway
transport/http/src/test/java/org/kaazing/gateway/transport/http/bridge/filter/HttpxeProtocolFilterTest.java
Java
apache-2.0
66,272
/* * 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.drill.exec.schema; public class BackedRecord implements Record { DiffSchema schema; DataRecord record; public BackedRecord(DiffSchema schema, DataRecord record) { this.schema = schema; this.record = record; } public void setBackend(DiffSchema schema, DataRecord record) { this.record = record; this.schema = schema; } @Override public DiffSchema getSchemaChanges() { return schema; } @Override public Object getField(int fieldId) { return record.getData(fieldId); } }
pwong-mapr/incubator-drill
exec/java-exec/src/main/java/org/apache/drill/exec/schema/BackedRecord.java
Java
apache-2.0
1,390
/* * Copyright 2012-2017 the original author or authors. * * 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.springframework.boot.test.mock.mockito; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.internal.util.MockUtil; import org.springframework.boot.test.mock.mockito.example.SimpleExampleStringGenericService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; /** * Test {@link SpyBean} on a test class field can be used to inject a spy instance when * there are multiple candidates and one is chosen using the name attribute. * * @author Phillip Webb * @author Andy Wilkinson */ @RunWith(SpringRunner.class) public class SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests { @SpyBean(name = "two") private SimpleExampleStringGenericService spy; @Test public void testSpying() throws Exception { assertThat(MockUtil.isSpy(this.spy)).isTrue(); assertThat(MockUtil.getMockName(this.spy).toString()).isEqualTo("two"); } @Configuration static class Config { @Bean public SimpleExampleStringGenericService one() { return new SimpleExampleStringGenericService("one"); } @Bean public SimpleExampleStringGenericService two() { return new SimpleExampleStringGenericService("two"); } } }
jbovet/spring-boot
spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests.java
Java
apache-2.0
1,967
/* Copyright 2014 The Kubernetes Authors. 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 cmd import ( "bytes" "fmt" "io/ioutil" "os" "reflect" "strings" "testing" "github.com/spf13/cobra" "k8s.io/cli-runtime/pkg/genericclioptions" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" ) func TestNormalizationFuncGlobalExistence(t *testing.T) { // This test can be safely deleted when we will not support multiple flag formats root := NewKubectlCommand(os.Stdin, os.Stdout, os.Stderr) if root.Parent() != nil { t.Fatal("We expect the root command to be returned") } if root.GlobalNormalizationFunc() == nil { t.Fatal("We expect that root command has a global normalization function") } if reflect.ValueOf(root.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(root.Flags().GetNormalizeFunc()).Pointer() { t.Fatal("root command seems to have a wrong normalization function") } sub := root for sub.HasSubCommands() { sub = sub.Commands()[0] } // In case of failure of this test check this PR: spf13/cobra#110 if reflect.ValueOf(sub.Flags().GetNormalizeFunc()).Pointer() != reflect.ValueOf(root.Flags().GetNormalizeFunc()).Pointer() { t.Fatal("child and root commands should have the same normalization functions") } } func Test_deprecatedAlias(t *testing.T) { var correctCommandCalled bool makeCobraCommand := func() *cobra.Command { cobraCmd := new(cobra.Command) cobraCmd.Use = "print five lines" cobraCmd.Run = func(*cobra.Command, []string) { correctCommandCalled = true } return cobraCmd } original := makeCobraCommand() alias := deprecatedAlias("echo", makeCobraCommand()) if len(alias.Deprecated) == 0 { t.Error("deprecatedAlias should always have a non-empty .Deprecated") } if !strings.Contains(alias.Deprecated, "print") { t.Error("deprecatedAlias should give the name of the new function in its .Deprecated field") } if !alias.Hidden { t.Error("deprecatedAlias should never have .Hidden == false (deprecated aliases should be hidden)") } if alias.Name() != "echo" { t.Errorf("deprecatedAlias has name %q, expected %q", alias.Name(), "echo") } if original.Name() != "print" { t.Errorf("original command has name %q, expected %q", original.Name(), "print") } buffer := new(bytes.Buffer) alias.SetOutput(buffer) alias.Execute() str := buffer.String() if !strings.Contains(str, "deprecated") || !strings.Contains(str, "print") { t.Errorf("deprecation warning %q does not include enough information", str) } // It would be nice to test to see that original.Run == alias.Run // Unfortunately Golang does not allow comparing functions. I could do // this with reflect, but that's technically invoking undefined // behavior. Best we can do is make sure that the function is called. if !correctCommandCalled { t.Errorf("original function doesn't appear to have been called by alias") } } func TestKubectlCommandHandlesPlugins(t *testing.T) { tests := []struct { name string args []string expectPlugin string expectPluginArgs []string expectError string }{ { name: "test that normal commands are able to be executed, when no plugin overshadows them", args: []string{"kubectl", "get", "foo"}, expectPlugin: "", expectPluginArgs: []string{}, }, { name: "test that a plugin executable is found based on command args", args: []string{"kubectl", "foo", "--bar"}, expectPlugin: "plugin/testdata/kubectl-foo", expectPluginArgs: []string{"foo", "--bar"}, }, { name: "test that a plugin does not execute over an existing command by the same name", args: []string{"kubectl", "version"}, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { pluginsHandler := &testPluginHandler{ pluginsDirectory: "plugin/testdata", } _, in, out, errOut := genericclioptions.NewTestIOStreams() cmdutil.BehaviorOnFatal(func(str string, code int) { errOut.Write([]byte(str)) }) root := NewDefaultKubectlCommandWithArgs(pluginsHandler, test.args, in, out, errOut) if err := root.Execute(); err != nil { t.Fatalf("unexpected error: %v", err) } if pluginsHandler.err != nil && pluginsHandler.err.Error() != test.expectError { t.Fatalf("unexpected error: expected %q to occur, but got %q", test.expectError, pluginsHandler.err) } if pluginsHandler.executedPlugin != test.expectPlugin { t.Fatalf("unexpected plugin execution: expedcted %q, got %q", test.expectPlugin, pluginsHandler.executedPlugin) } if len(pluginsHandler.withArgs) != len(test.expectPluginArgs) { t.Fatalf("unexpected plugin execution args: expedcted %q, got %q", test.expectPluginArgs, pluginsHandler.withArgs) } }) } } type testPluginHandler struct { pluginsDirectory string // execution results executedPlugin string withArgs []string withEnv []string err error } func (h *testPluginHandler) Lookup(filename string) (string, bool) { // append supported plugin prefix to the filename filename = fmt.Sprintf("%s-%s", "kubectl", filename) dir, err := os.Stat(h.pluginsDirectory) if err != nil { h.err = err return "", false } if !dir.IsDir() { h.err = fmt.Errorf("expected %q to be a directory", h.pluginsDirectory) return "", false } plugins, err := ioutil.ReadDir(h.pluginsDirectory) if err != nil { h.err = err return "", false } for _, p := range plugins { if p.Name() == filename { return fmt.Sprintf("%s/%s", h.pluginsDirectory, p.Name()), true } } h.err = fmt.Errorf("unable to find a plugin executable %q", filename) return "", false } func (h *testPluginHandler) Execute(executablePath string, cmdArgs, env []string) error { h.executedPlugin = executablePath h.withArgs = cmdArgs h.withEnv = env return nil }
Stackdriver/heapster
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/cmd_test.go
GO
apache-2.0
6,357
<?php /** * * * Created on July 7, 2007 * * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com" * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @file */ /** * @ingroup API */ class ApiQueryExtLinksUsage extends ApiQueryGeneratorBase { public function __construct( $query, $moduleName ) { parent::__construct( $query, $moduleName, 'eu' ); } public function execute() { $this->run(); } public function getCacheMode( $params ) { return 'public'; } public function executeGenerator( $resultPageSet ) { $this->run( $resultPageSet ); } /** * @param $resultPageSet ApiPageSet * @return void */ private function run( $resultPageSet = null ) { $params = $this->extractRequestParams(); $query = $params['query']; $protocol = self::getProtocolPrefix( $params['protocol'] ); $this->addTables( array( 'page', 'externallinks' ) ); // must be in this order for 'USE INDEX' $this->addOption( 'USE INDEX', 'el_index' ); $this->addWhere( 'page_id=el_from' ); global $wgMiserMode; $miser_ns = array(); if ( $wgMiserMode ) { $miser_ns = $params['namespace']; } else { $this->addWhereFld( 'page_namespace', $params['namespace'] ); } $whereQuery = $this->prepareUrlQuerySearchString( $query, $protocol ); if ( $whereQuery !== null ) { $this->addWhere( $whereQuery ); } $prop = array_flip( $params['prop'] ); $fld_ids = isset( $prop['ids'] ); $fld_title = isset( $prop['title'] ); $fld_url = isset( $prop['url'] ); if ( is_null( $resultPageSet ) ) { $this->addFields( array( 'page_id', 'page_namespace', 'page_title' ) ); $this->addFieldsIf( 'el_to', $fld_url ); } else { $this->addFields( $resultPageSet->getPageTableFields() ); } $limit = $params['limit']; $offset = $params['offset']; $this->addOption( 'LIMIT', $limit + 1 ); if ( isset( $offset ) ) { $this->addOption( 'OFFSET', $offset ); } $res = $this->select( __METHOD__ ); $result = $this->getResult(); $count = 0; foreach ( $res as $row ) { if ( ++ $count > $limit ) { // We've reached the one extra which shows that there are additional pages to be had. Stop here... $this->setContinueEnumParameter( 'offset', $offset + $limit ); break; } if ( count( $miser_ns ) && !in_array( $row->page_namespace, $miser_ns ) ) { continue; } if ( is_null( $resultPageSet ) ) { $vals = array(); if ( $fld_ids ) { $vals['pageid'] = intval( $row->page_id ); } if ( $fld_title ) { $title = Title::makeTitle( $row->page_namespace, $row->page_title ); ApiQueryBase::addTitleInfo( $vals, $title ); } if ( $fld_url ) { $to = $row->el_to; // expand protocol-relative urls if ( $params['expandurl'] ) { $to = wfExpandUrl( $to, PROTO_CANONICAL ); } $vals['url'] = $to; } $fit = $result->addValue( array( 'query', $this->getModuleName() ), null, $vals ); if ( !$fit ) { $this->setContinueEnumParameter( 'offset', $offset + $count - 1 ); break; } } else { $resultPageSet->processDbRow( $row ); } } if ( is_null( $resultPageSet ) ) { $result->setIndexedTagName_internal( array( 'query', $this->getModuleName() ), $this->getModulePrefix() ); } } public function getAllowedParams() { return array( 'prop' => array( ApiBase::PARAM_ISMULTI => true, ApiBase::PARAM_DFLT => 'ids|title|url', ApiBase::PARAM_TYPE => array( 'ids', 'title', 'url' ) ), 'offset' => array( ApiBase::PARAM_TYPE => 'integer' ), 'protocol' => array( ApiBase::PARAM_TYPE => self::prepareProtocols(), ApiBase::PARAM_DFLT => '', ), 'query' => null, 'namespace' => array( ApiBase::PARAM_ISMULTI => true, ApiBase::PARAM_TYPE => 'namespace' ), 'limit' => array( ApiBase::PARAM_DFLT => 10, ApiBase::PARAM_TYPE => 'limit', ApiBase::PARAM_MIN => 1, ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1, ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2 ), 'expandurl' => false, ); } public static function prepareProtocols() { global $wgUrlProtocols; $protocols = array( '' ); foreach ( $wgUrlProtocols as $p ) { if ( $p !== '//' ) { $protocols[] = substr( $p, 0, strpos( $p, ':' ) ); } } return $protocols; } public static function getProtocolPrefix( $protocol ) { // Find the right prefix global $wgUrlProtocols; if ( $protocol && !in_array( $protocol, $wgUrlProtocols ) ) { foreach ( $wgUrlProtocols as $p ) { if ( substr( $p, 0, strlen( $protocol ) ) === $protocol ) { $protocol = $p; break; } } return $protocol; } else { return null; } } public function getParamDescription() { global $wgMiserMode; $p = $this->getModulePrefix(); $desc = array( 'prop' => array( 'What pieces of information to include', ' ids - Adds the ID of page', ' title - Adds the title and namespace ID of the page', ' url - Adds the URL used in the page', ), 'offset' => 'Used for paging. Use the value returned for "continue"', 'protocol' => array( "Protocol of the URL. If empty and {$p}query set, the protocol is http.", "Leave both this and {$p}query empty to list all external links" ), 'query' => 'Search string without protocol. See [[Special:LinkSearch]]. Leave empty to list all external links', 'namespace' => 'The page namespace(s) to enumerate.', 'limit' => 'How many pages to return.', 'expandurl' => 'Expand protocol-relative URLs with the canonical protocol', ); if ( $wgMiserMode ) { $desc['namespace'] = array( $desc['namespace'], "NOTE: Due to \$wgMiserMode, using this may result in fewer than \"{$p}limit\" results", 'returned before continuing; in extreme cases, zero results may be returned', ); } return $desc; } public function getResultProperties() { return array( 'ids' => array( 'pageid' => 'integer' ), 'title' => array( 'ns' => 'namespace', 'title' => 'string' ), 'url' => array( 'url' => 'string' ) ); } public function getDescription() { return 'Enumerate pages that contain a given URL'; } public function getPossibleErrors() { return array_merge( parent::getPossibleErrors(), array( array( 'code' => 'bad_query', 'info' => 'Invalid query' ), ) ); } public function getExamples() { return array( 'api.php?action=query&list=exturlusage&euquery=www.mediawiki.org' ); } public function getHelpUrls() { return 'https://www.mediawiki.org/wiki/API:Exturlusage'; } }
BRL-CAD/web
wiki/includes/api/ApiQueryExtLinksUsage.php
PHP
bsd-2-clause
7,300
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.2/15.2.3/15.2.3.7/15.2.3.7-6-a-93-1.js * @description Object.defineProperties will update [[Value]] attribute of named data property 'P' successfully when [[Configurable]] attribute is true and [[Writable]] attribute is false but not when both are false (8.12.9 - step Note & 10.a.ii.1) */ function testcase() { var obj = {}; Object.defineProperty(obj, "property", { value: 1001, writable: false, configurable: true }); Object.defineProperty(obj, "property1", { value: 1003, writable: false, configurable: false }); try { Object.defineProperties(obj, { property: { value: 1002 }, property1: { value: 1004 } }); return false; } catch (e) { return e instanceof TypeError && dataPropertyAttributesAreCorrect(obj, "property", 1002, false, false, true) && dataPropertyAttributesAreCorrect(obj, "property1", 1003, false, false, false); } } runTestCase(testcase);
Oceanswave/NiL.JS
Tests/tests/sputnik/ch15/15.2/15.2.3/15.2.3.7/15.2.3.7-6-a-93-1.js
JavaScript
bsd-3-clause
1,285
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-7-c-ii-10.js * @description Array.prototype.some - callbackfn is called with 1 formal parameter */ function testcase() { function callbackfn(val) { return val > 10; } return [11, 12].some(callbackfn); } runTestCase(testcase);
Oceanswave/NiL.JS
Tests/tests/sputnik/ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-7-c-ii-10.js
JavaScript
bsd-3-clause
388
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch10/10.4/10.4.3/10.4.3-1-49gs.js * @description Strict - checking 'this' from a global scope (FunctionExpression with a strict directive prologue defined within a FunctionExpression) * @noStrict */ var f1 = function () { var f = function () { "use strict"; return typeof this; } return (f()==="undefined") && (this===fnGlobalObject()); } if (! f1()) { throw "'this' had incorrect value!"; }
Oceanswave/NiL.JS
Tests/tests/sputnik/ch10/10.4/10.4.3/10.4.3-1-49gs.js
JavaScript
bsd-3-clause
506
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-8-b-16.js * @description Array.prototype.map - decreasing length of array does not delete non-configurable properties */ function testcase() { function callbackfn(val, idx, obj) { if (idx === 2 && val === "unconfigurable") { return false; } else { return true; } } var arr = [0, 1, 2]; Object.defineProperty(arr, "2", { get: function () { return "unconfigurable"; }, configurable: false }); Object.defineProperty(arr, "1", { get: function () { arr.length = 2; return 1; }, configurable: true }); var testResult = arr.map(callbackfn); return testResult.length === 3 && testResult[2] === false; } runTestCase(testcase);
Oceanswave/NiL.JS
Tests/tests/sputnik/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-8-b-16.js
JavaScript
bsd-3-clause
1,006
// Type definitions for riot v2.6.0 // Project: https://github.com/riot/riot // Definitions by: Boriss Nazarovs <https://github.com/Stubb0rn> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace riot { /** * Current version number as string */ const version: string; /** * Riot settings */ interface Settings { /** * Setting used to customize the start and end tokens of the expression */ brackets: string; } const settings: Settings; interface TemplateError extends Error { riotData: { tagName: string; } } interface Util { tmpl: { errorHandler(error: TemplateError): void; } } const util: Util; /** * Internal riot tags cache */ const vdom: Tag[]; interface Observable { /** * Register callback for specified events. * Callback is executed each time event is triggered * @param events Space separated list of events or wildcard '*' that matches all events * @param callback Callback function */ on?(events: string, callback: Function): Observable; /** * Register callback for specified events. * Callback is executed at most once. * @param events Space separated list of events. * @param callback Callback function */ one?(events: string, callback: Function): Observable; /** * Remove all registered callbacks for specified events * @param events Space separated list of events or wildcard '*' that matches all events */ off?(events: string): Observable; /** * Remove specified callback for specified events * @param events Space separated list of events or wildcard '*' that matches all events * @param callback Callback function to remove */ off?(events: string, callback: Function): Observable; /** * Execute all callback functions registered for specified list of events * @param events Space separated list of events * @param args Arguments provided to callbacks */ trigger?(events: string, ...args: any[]): Observable; } /** * Riot Router */ interface Route { /** * Register callback that is executed when the URL changes * @param callback Callback function */ (callback: (...args: any[]) => void): void; /** * Register callback that is executed when the URL changes and new URL matches specified filter * @param filter URL filter * @param callback Callback function */ (filter: string, callback: (...any: string[]) => void): void; /** * Change the browser URL and notify all the listeners registered with `Route(callback)` * @param to New URL * @param title Document title for new URL * @param shouldReplace Should new url replace the current history */ (to: string, title?: string, shouldReplace?: boolean): void; /** * Return a new routing context */ create(): Route; /** * Start listening for url changes * @param autoExec Should router exec routing on the current url */ start(autoExec?: boolean): void; /** * Stop all the routings. * Removes the listeners and clears the callbacks. */ stop(): void; /** * Study the current browser path “in place” and emit routing without waiting for it to change. */ exec(): void; /** * @deprecated */ exec(callback: Function): void; /** * Extract query from the url */ query(): { [key: string]: string }; /** * Change the base path * @param base Base path */ base(base: string): void; /** * Change the default parsers to the custom ones. * @param parser Replacement parser for default parser * @param secondParser Replacement parser for handling url filters */ parser(parser: (path: string) => any[], secondParser?: (path: string, filter: string) => any[]): void; } /** * Adds Observer support for the given object or * if the argument is empty a new observable instance is created and returned. * @param el Object to become observable */ function observable(el?: any): Observable; const route: Route; /** * Mount custom tags with specified tag name. Returns an array of mounted tag instances. * @param selector Tag selector. * It can be tag name, css selector or special '*' selector that matches all tags on the page. * @param opts Optional object passed for the tags to consume. */ function mount(selector: string, opts?: any): Tag[]; /** * Mount a custom tag on DOM nodes matching provided selector. Returns an array of mounted tag instances. * @param selector CSS selector * @param tagName Custom tag name * @param opts Optional object passed for the tag to consume. */ function mount(selector: string, tagName: string, opts?: any): Tag[]; /** * Mount a custom tag on a given DOM node. Returns an array of mounted tag instances. * @param domNode DOM node * @param tagName Tag name * @param opts Optional object passed for the tag to consume. */ function mount(domNode: Node, tagName: string, opts?: any): Tag[]; /** * Render a tag to html. This method is only available on server-side. * @param tagName Custom tag name * @param opts Optional object passed for the tag to consume. */ function render(tagName: string, opts?: any): string; /** * Update all the mounted tags and their expressions on the page. * Returns an array of tag instances that are mounted on the page. */ function update(): Tag[]; /** * Register a global mixin and automatically add it to all tag instances. * @param mixinObject Mixin object */ function mixin(mixinObject: TagMixin): void; /** * Register a shared mixin, globally available to be used in any tag using `TagInstance.mixin(mixinName)` * @param mixinName Name of the mixin * @param mixinObject Mixin object * @param isGlobal Is global mixin? */ function mixin(mixinName: string, mixinObject: TagMixin, isGlobal?: boolean): void; /** * Create a new custom tag “manually” without the compiler. Returns name of the tag. * @param tagName The tag name * @param html The layout with expressions * @param css The style of the tag * @param attrs String of attributes for the tag * @param constructor The initialization function being called before * the tag expressions are calculated and before the tag is mounted */ function tag(tagName: string, html: string, css?: string, attrs?: string, constructor?: (opts: any) => void): string; interface TagImplementation { /** * Tag template */ tmpl: string; /** * The callback function called on the mount event * @param opts Tag options object */ fn?(opts: any): void; /** * Root tag html attributes as object (key => value) */ attrs?: { [key: string]: any; } } interface TagConfiguration { /** * DOM node where you will mount the tag template */ root: Node; /** * Tag options */ opts?: any; /** * Is it used in as loop tag */ isLoop?: boolean; /** * Is already registered using `riot.tag` */ hasImpl?: boolean; /** * Loop item in the loop assigned to this instance */ item?: any; } interface TagInterface extends Observable { /** * options object */ opts?: any; /** * the parent tag if any */ parent?: Tag; /** * root DOM node */ root?: Node; /** * nested custom tags */ tags?: { [key: string]: Tag | Tag[]; }; /** * Updates all the expressions on the current tag instance as well as on all the children. * @param data Context data */ update?(data?: any): void; /** * Extend tag with functionality available on shared mixin registered with `riot.mixin(mixinName, mixinObject)` * @param mixinName Name of shared mixin */ mixin?(mixinName: string): void; /** * Extend tag functionality with functionality available on provided mixin object. * @param mixinObject Mixin object */ mixin?(mixinObject: TagMixin): void; /** * Mount the tag */ mount?(): void; /** * Detach the tag and its children from the page. * @param keepTheParent If `true` unmounting tag doesn't remove the parent tag */ unmount?(keepTheParent?: boolean): void; } class Tag implements TagInterface { /** * Tag constructor * @param impl Tag implementation * @param conf Tag configuration * @param innerHTML HTML that can be used replacing a nested `yield` tag in its template */ constructor(impl: TagImplementation, conf: TagConfiguration, innerHTML?: string); /** * options object */ opts: any; /** * the parent tag if any */ parent: Tag; /** * root DOM node */ root: Node; /** * nested custom tags */ tags: { [key: string]: Tag | Tag[]; }; /** * Updates all the expressions on the current tag instance as well as on all the children. * @param data Context data */ update(data?: any): void; /** * Extend tag with functionality available on shared mixin registered with `riot.mixin(mixinName, mixinObject)` * @param mixinName Name of shared mixin */ mixin(mixinName: string): void; /** * Extend tag functionality with functionality available on provided mixin object. * @param mixinObject Mixin object */ mixin(mixinObject: TagMixin): void; /** * Mount the tag */ mount(): void; /** * Detach the tag and its children from the page. * @param keepTheParent If `true` unmounting tag doesn't remove the parent tag */ unmount(keepTheParent?: boolean): void; // Observable methods on(events: string, callback: Function): this; one(events: string, callback: Function): this; off(events: string): this; off(events: string, callback: Function): this; trigger(events: string, ...args: any[]): this; } /** * Mixin object for extending tag functionality. * When it gets mixed in it has access to all tag properties. * It should not override any built in tag properties */ interface TagMixin extends TagInterface { /** * Special method which can initialize * the mixin when it's loaded to the tag and is not * accessible from the tag its mixed in */ init?(): void; } /** * Compile all tags defined with <script type="riot/tag"> to JavaScript. * @param callback Function that is called after all scripts are compiled */ function compile(callback: Function): void; /** * Compiles and executes the given tag. * @param tag Tag definition * @return {string} Compiled JavaScript as string */ function compile(tag: string): string; /** * Compiles the given tag but doesn't execute it, if `skipExecution` parameter is `true` * @param tag Tag definition * @param skipExecution If `true` tag is not executed after compilation * @return {string} Compiled JavaScript as string */ function compile(tag: string, skipExecution: boolean): string; /** * Loads the given URL and compiles all tags after which the callback is called * @param url URL to load * @param callback Function that is called after all tags are compiled */ function compile(url: string, callback: Function): void; } declare module 'riot' { export = riot; }
smrq/DefinitelyTyped
types/riot/index.d.ts
TypeScript
mit
12,881
<?php namespace Concrete\Core\StyleCustomizer\Style; use Core; use \Concrete\Core\StyleCustomizer\Style\Value\ColorValue; use Less_Tree_Color; use Less_Tree_Call; use Less_Tree_Dimension; use View; use Request; use \Concrete\Core\Http\Service\Json; class ColorStyle extends Style { public function render($value = false) { $color = ''; if ($value) { $color = $value->toStyleString(); } $inputName = $this->getVariable(); $r = Request::getInstance(); if ($r->request->has($inputName)) { $color = h($r->request->get($inputName)); } $view = View::getInstance(); $view->requireAsset('core/colorpicker'); $json = new Json(); print "<input type=\"text\" name=\"{$inputName}[color]\" value=\"{$color}\" id=\"ccm-colorpicker-{$inputName}\" />"; print "<script type=\"text/javascript\">"; print "$(function() { $('#ccm-colorpicker-{$inputName}').spectrum({ showInput: true, showInitial: true, preferredFormat: 'rgb', allowEmpty: true, className: 'ccm-widget-colorpicker', showAlpha: true, value: " . $json->encode($color) . ", cancelText: " . $json->encode(t('Cancel')) . ", chooseText: " . $json->encode(t('Choose')) . ", clearText: " . $json->encode(t('Clear Color Selection')) . ", change: function() {ConcreteEvent.publish('StyleCustomizerControlUpdate');} });});"; print "</script>"; } public static function parse($value, $variable = false) { if ($value instanceof Less_Tree_Color) { if ($value->isTransparentKeyword) { return false; } $cv = new ColorValue($variable); $cv->setRed($value->rgb[0]); $cv->setGreen($value->rgb[1]); $cv->setBlue($value->rgb[2]); } else if ($value instanceof Less_Tree_Call) { // might be rgb() or rgba() $cv = new ColorValue($variable); $cv->setRed($value->args[0]->value[0]->value); $cv->setGreen($value->args[1]->value[0]->value); $cv->setBlue($value->args[2]->value[0]->value); if ($value->name == 'rgba') { $cv->setAlpha($value->args[3]->value[0]->value); } } return $cv; } public function getValueFromRequest(\Symfony\Component\HttpFoundation\ParameterBag $request) { $color = $request->get($this->getVariable()); if (!$color['color']) { // transparent return false; } $cv = new \Primal\Color\Parser($color['color']); $result = $cv->getResult(); $alpha = false; if ($result->alpha && $result->alpha < 1) { $alpha = $result->alpha; } $cv = new ColorValue($this->getVariable()); $cv->setRed($result->red); $cv->setGreen($result->green); $cv->setBlue($result->blue); $cv->setAlpha($alpha); return $cv; } public function getValuesFromVariables($rules = array()) { $values = array(); foreach($rules as $rule) { if (preg_match('/@(.+)\-color/i', $rule->name, $matches)) { $value = $rule->value->value[0]->value[0]; $cv = static::parse($value, $matches[1]); if (is_object($cv)) { $values[] = $cv; } } } return $values; } }
LinkedOpenData/challenge2015
docs/concrete5/updates/concrete5.7.5.1_remote_updater/concrete/src/StyleCustomizer/Style/ColorStyle.php
PHP
mit
3,566
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ import java.util.concurrent.atomic.AtomicBoolean; import junit.framework.Test; import junit.framework.TestSuite; public class AtomicBoolean9Test extends JSR166TestCase { public static void main(String[] args) { main(suite(), args); } public static Test suite() { return new TestSuite(AtomicBoolean9Test.class); } /** * getPlain returns the last value set */ public void testGetPlainSet() { AtomicBoolean ai = new AtomicBoolean(true); assertEquals(true, ai.getPlain()); ai.set(false); assertEquals(false, ai.getPlain()); ai.set(true); assertEquals(true, ai.getPlain()); } /** * getOpaque returns the last value set */ public void testGetOpaqueSet() { AtomicBoolean ai = new AtomicBoolean(true); assertEquals(true, ai.getOpaque()); ai.set(false); assertEquals(false, ai.getOpaque()); ai.set(true); assertEquals(true, ai.getOpaque()); } /** * getAcquire returns the last value set */ public void testGetAcquireSet() { AtomicBoolean ai = new AtomicBoolean(true); assertEquals(true, ai.getAcquire()); ai.set(false); assertEquals(false, ai.getAcquire()); ai.set(true); assertEquals(true, ai.getAcquire()); } /** * get returns the last value setPlain */ public void testGetSetPlain() { AtomicBoolean ai = new AtomicBoolean(true); assertEquals(true, ai.get()); ai.setPlain(false); assertEquals(false, ai.get()); ai.setPlain(true); assertEquals(true, ai.get()); } /** * get returns the last value setOpaque */ public void testGetSetOpaque() { AtomicBoolean ai = new AtomicBoolean(true); assertEquals(true, ai.get()); ai.setOpaque(false); assertEquals(false, ai.get()); ai.setOpaque(true); assertEquals(true, ai.get()); } /** * get returns the last value setRelease */ public void testGetSetRelease() { AtomicBoolean ai = new AtomicBoolean(true); assertEquals(true, ai.get()); ai.setRelease(false); assertEquals(false, ai.get()); ai.setRelease(true); assertEquals(true, ai.get()); } /** * compareAndExchange succeeds in changing value if equal to * expected else fails */ public void testCompareAndExchange() { AtomicBoolean ai = new AtomicBoolean(true); assertEquals(true, ai.compareAndExchange(true, false)); assertEquals(false, ai.compareAndExchange(false, false)); assertEquals(false, ai.get()); assertEquals(false, ai.compareAndExchange(true, true)); assertEquals(false, ai.get()); assertEquals(false, ai.compareAndExchange(false, true)); assertEquals(true, ai.get()); } /** * compareAndExchangeAcquire succeeds in changing value if equal to * expected else fails */ public void testCompareAndExchangeAcquire() { AtomicBoolean ai = new AtomicBoolean(true); assertEquals(true, ai.compareAndExchangeAcquire(true, false)); assertEquals(false, ai.compareAndExchangeAcquire(false, false)); assertEquals(false, ai.get()); assertEquals(false, ai.compareAndExchangeAcquire(true, true)); assertEquals(false, ai.get()); assertEquals(false, ai.compareAndExchangeAcquire(false, true)); assertEquals(true, ai.get()); } /** * compareAndExchangeRelease succeeds in changing value if equal to * expected else fails */ public void testCompareAndExchangeRelease() { AtomicBoolean ai = new AtomicBoolean(true); assertEquals(true, ai.compareAndExchangeRelease(true, false)); assertEquals(false, ai.compareAndExchangeRelease(false, false)); assertEquals(false, ai.get()); assertEquals(false, ai.compareAndExchangeRelease(true, true)); assertEquals(false, ai.get()); assertEquals(false, ai.compareAndExchangeRelease(false, true)); assertEquals(true, ai.get()); } /** * repeated weakCompareAndSetPlain succeeds in changing value when equal * to expected */ public void testWeakCompareAndSetPlain() { AtomicBoolean ai = new AtomicBoolean(true); do {} while (!ai.weakCompareAndSetPlain(true, false)); do {} while (!ai.weakCompareAndSetPlain(false, false)); assertFalse(ai.get()); do {} while (!ai.weakCompareAndSetPlain(false, true)); assertTrue(ai.get()); } /** * repeated weakCompareAndSetVolatile succeeds in changing value when equal * to expected */ public void testWeakCompareAndSetVolatile() { AtomicBoolean ai = new AtomicBoolean(true); do {} while (!ai.weakCompareAndSetVolatile(true, false)); do {} while (!ai.weakCompareAndSetVolatile(false, false)); assertEquals(false, ai.get()); do {} while (!ai.weakCompareAndSetVolatile(false, true)); assertEquals(true, ai.get()); } /** * repeated weakCompareAndSetAcquire succeeds in changing value when equal * to expected */ public void testWeakCompareAndSetAcquire() { AtomicBoolean ai = new AtomicBoolean(true); do {} while (!ai.weakCompareAndSetAcquire(true, false)); do {} while (!ai.weakCompareAndSetAcquire(false, false)); assertEquals(false, ai.get()); do {} while (!ai.weakCompareAndSetAcquire(false, true)); assertEquals(true, ai.get()); } /** * repeated weakCompareAndSetRelease succeeds in changing value when equal * to expected */ public void testWeakCompareAndSetRelease() { AtomicBoolean ai = new AtomicBoolean(true); do {} while (!ai.weakCompareAndSetRelease(true, false)); do {} while (!ai.weakCompareAndSetRelease(false, false)); assertEquals(false, ai.get()); do {} while (!ai.weakCompareAndSetRelease(false, true)); assertEquals(true, ai.get()); } }
md-5/jdk10
test/jdk/java/util/concurrent/tck/AtomicBoolean9Test.java
Java
gpl-2.0
7,537
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "$Id$" /*====== This file is part of PerconaFT. Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved. PerconaFT is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. PerconaFT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PerconaFT. If not, see <http://www.gnu.org/licenses/>. ---------------------------------------- PerconaFT is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. PerconaFT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with PerconaFT. If not, see <http://www.gnu.org/licenses/>. ======= */ #ident "Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved." #include "test.h" #include "toku_pthread.h" #include <portability/toku_atomic.h> static int my_compare (DB *db, const DBT *a, const DBT *b) { assert(db); assert(db->cmp_descriptor); assert(db->cmp_descriptor->dbt.size >= 3); char *CAST_FROM_VOIDP(data, db->cmp_descriptor->dbt.data); assert(data[0]=='f'); assert(data[1]=='o'); assert(data[2]=='o'); if (verbose) printf("compare descriptor=%s\n", data); sched_yield(); return uint_dbt_cmp(db, a, b); } DB_ENV *env; DB *db; const char *env_dir = TOKU_TEST_FILENAME; volatile int done = 0; static void *startA (void *ignore __attribute__((__unused__))) { for (int i=0;i<999; i++) { DBT k,v; int a = (random()<<16) + i; dbt_init(&k, &a, sizeof(a)); dbt_init(&v, &a, sizeof(a)); DB_TXN *txn; again: { int chk_r = env->txn_begin(env, NULL, &txn, DB_TXN_NOSYNC); CKERR(chk_r); } { int r = db->put(db, txn, &k, &v, 0); if (r==DB_LOCK_NOTGRANTED) { if (verbose) printf("lock not granted on %d\n", i); { int chk_r = txn->abort(txn); CKERR(chk_r); } goto again; } assert(r==0); } { int chk_r = txn->commit(txn, 0); CKERR(chk_r); } } int r __attribute__((__unused__)) = toku_sync_fetch_and_add(&done, 1); return NULL; } static void change_descriptor (DB_TXN *txn, int i) { DBT desc; char foo[100]; snprintf(foo, 99, "foo%d", i); dbt_init(&desc, foo, 1+strlen(foo)); int r; if (verbose) printf("trying to change to %s\n", foo); while ((r=db->change_descriptor(db, txn, &desc, 0))) { if (verbose) printf("Change failed r=%d, try again\n", r); } if (verbose) printf("ok\n"); } static void startB (void) { for (int i=0; !done; i++) { IN_TXN_COMMIT(env, NULL, txn, 0, change_descriptor(txn, i)); sched_yield(); } } static void my_parse_args (int argc, char * const argv[]) { const char *argv0=argv[0]; while (argc>1) { int resultcode=0; if (strcmp(argv[1], "-v")==0) { verbose++; } else if (strcmp(argv[1],"-q")==0) { verbose--; if (verbose<0) verbose=0; } else if (strcmp(argv[1],"--envdir")==0) { assert(argc>2); env_dir = argv[2]; argc--; argv++; } else if (strcmp(argv[1], "-h")==0) { do_usage: fprintf(stderr, "Usage:\n%s [-v|-q] [-h] [--envdir <envdir>]\n", argv0); exit(resultcode); } else { resultcode=1; goto do_usage; } argc--; argv++; } } int test_main(int argc, char * const argv[]) { my_parse_args(argc, argv); db_env_set_num_bucket_mutexes(32); { int chk_r = db_env_create(&env, 0); CKERR(chk_r); } { int chk_r = env->set_redzone(env, 0); CKERR(chk_r); } { int chk_r = env->set_default_bt_compare(env, my_compare); CKERR(chk_r); } { const int size = 10+strlen(env_dir); char cmd[size]; snprintf(cmd, size, "rm -rf %s", env_dir); int r = system(cmd); CKERR(r); } { int chk_r = toku_os_mkdir(env_dir, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(chk_r); } const int envflags = DB_INIT_MPOOL|DB_CREATE|DB_THREAD |DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_TXN|DB_PRIVATE; { int chk_r = env->open(env, env_dir, envflags, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(chk_r); } { int chk_r = db_create(&db, env, 0); CKERR(chk_r); } { int chk_r = db->set_pagesize(db, 1024); CKERR(chk_r); } { int chk_r = db->open(db, NULL, "db", NULL, DB_BTREE, DB_CREATE, 0666); CKERR(chk_r); } DBT desc; dbt_init(&desc, "foo", sizeof("foo")); IN_TXN_COMMIT(env, NULL, txn, 0, { int chk_r = db->change_descriptor(db, txn, &desc, DB_UPDATE_CMP_DESCRIPTOR); CKERR(chk_r); }); pthread_t thd; { int chk_r = toku_pthread_create(&thd, NULL, startA, NULL); CKERR(chk_r); } startB(); void *retval; { int chk_r = toku_pthread_join(thd, &retval); CKERR(chk_r); } assert(retval==NULL); { int chk_r = db->close(db, 0); CKERR(chk_r); } { int chk_r = env->close(env, 0); CKERR(chk_r); } return 0; }
ChengXiaoZ/MariaDBserver
storage/tokudb/PerconaFT/src/tests/test_4015.cc
C++
gpl-2.0
5,525
<p>Auf dieser Seite k&ouml;nnen Sie eine Nachricht vorbereiten, die erst zu einem sp&auml;teren Zeitpunkt verschickt werden soll. Sie k&ouml;nnen alle erforderlichen Angaben erfassen - ausser an welche Liste(n) die Nachricht versendet werden soll. Dies geschieht erst in dem Moment, wo Sie eine vorbereitete Nachricht tats&auml;chlich versenden.</p> <p>Eine vorbereitete Nachricht verschwindet nicht, wenn sie einmal verschickt wurde, sondern bleibt als Vorlage erhalten und kann mehrfach f&uuml;r einen Nachrichtenversand benutzt werden. Bitte seien Sie vorsichtig mit dieser Funktion, denn es k&ouml;nnte leicht passieren, dass Sie versehentlich dieselbe Nachricht mehrfach an dieselben Emfp&auml;nger senden.</p> <p>Die M&ouml;glichkeit, Nachrichten vorzubereiten und als Vorlagen zu benutzen, wurde insbesondere im Hinblick auf Systeme mit mehrere Administratoren entwickelt. Wenn der Haupt-Administrator eine Nachricht vorbereitet, kann sie anschliessend von Sub-Administratoren an deren jeweiligen Listen versendet werden. In diesem Fall k&ouml;nnen Sie zus&auml;tzliche Platzhalter in Ihre Nachricht einf&uuml;gen: die Administratoren-Attribute.</p> <p>Wenn Sie beispielsweise ein Administratoren-Attribut <b>Name</b> definiert haben, dann k&ouml;nnen Sie [LISTOWNER.NAME] als Platzhalter verwenden. In diesem Fall wird der Platzhalter durch den Namen des Besitzers derjenigen Liste ersetzt, an welche die Nachricht verschickt wird. Dies gilt unabh&auml;ngig davon, wer die Nachricht effektiv verschickt: Wenn also der Haupt-Administrator eine Nachricht an eine Liste verschickt, deren Besitzer ein anderer Administrator ist, so werden die [LISTOWNER]-Platzhalter trotzdem mit den Daten des jeweiligen Besitzers ersetzt (und nicht mit den Daten des Haupt-Administrators). </p> <p>Das Format f&uuml;r [LISTOWNER]-Platzhalter ist <b>[LISTOWNER.ATTRIBUT]</b></p> <p>Zur Zeit sind folgende Administratoren-Attribute im System definiert: <table border=1 cellspacing=0 cellpadding=2> <tr> <td><b>Attribut</b></td> <td><b>Platzhalter</b></td> </tr> <?php $req = Sql_query("select name from {$tables["adminattribute"]} order by listorder"); if (!Sql_Affected_Rows()) print '<tr><td colspan=2>-</td></tr>'; while ($row = Sql_Fetch_Row($req)) if (strlen($row[0]) < 20) printf ('<tr><td>%s</td><td>[LISTOWNER.%s]</td></tr>',$row[0],strtoupper($row[0])); ?> </table>
washingtonstateuniversity/WSU-Lists
www/admin/help/de/preparemessage.php
PHP
gpl-2.0
2,382
using System.Web.Mvc; using System.Web.Routing; using SmartStore.Web.Framework.Mvc.Routes; namespace SmartStore.Clickatell { public partial class RouteProvider : IRouteProvider { public void RegisterRoutes(RouteCollection routes) { routes.MapRoute("SmartStore.Clickatell", "Plugins/SmartStore.Clickatell/{action}", new { controller = "SmsClickatell", action = "Configure" }, new[] { "SmartStore.Clickatell.Controllers" } ) .DataTokens["area"] = "SmartStore.Clickatell"; } public int Priority { get { return 0; } } } }
Li-Yanzhi/SmartStoreNET
src/Plugins/SmartStore.Clickatell/RouteProvider.cs
C#
gpl-3.0
700
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/. import os from wptrunner.update.base import Step, StepRunner from wptrunner.update.update import LoadConfig, SyncFromUpstream, UpdateMetadata from wptrunner.update.tree import NoVCSTree from .tree import GitTree, HgTree, GeckoCommit from .upstream import SyncToUpstream class LoadTrees(Step): """Load gecko tree and sync tree containing web-platform-tests""" provides = ["local_tree", "sync_tree"] def create(self, state): if os.path.exists(state.sync["path"]): sync_tree = GitTree(root=state.sync["path"]) else: sync_tree = None if GitTree.is_type(): local_tree = GitTree(commit_cls=GeckoCommit) elif HgTree.is_type(): local_tree = HgTree(commit_cls=GeckoCommit) else: local_tree = NoVCSTree() state.update({"local_tree": local_tree, "sync_tree": sync_tree}) class UpdateRunner(StepRunner): """Overall runner for updating web-platform-tests in Gecko.""" steps = [LoadConfig, LoadTrees, SyncToUpstream, SyncFromUpstream, UpdateMetadata]
UK992/servo
tests/wpt/update/update.py
Python
mpl-2.0
1,349
define([ 'css!theme/liveblog', 'tmpl!theme/container', 'tmpl!theme/item/base', 'plugins/wrappup-toggle', 'plugins/scroll-pagination', 'plugins/permanent-link', 'plugins/user-comments' ], function(){ });
vladnicoara/SDLive-Blog
plugins/livedesk-embed/gui-themes/themes/tageswoche.min.js
JavaScript
agpl-3.0
209
// Copyright 2016 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package logfwd import ( "fmt" "github.com/juju/errors" "github.com/juju/version" "gopkg.in/juju/names.v2" ) // canonicalPEN is the IANA-registered Private Enterprise Number // assigned to Canonical. Among other things, this is used in RFC 5424 // structured data. // // See https://www.iana.org/assignments/enterprise-numbers/enterprise-numbers. const canonicalPEN = 28978 // These are the recognized origin types. const ( OriginTypeUnknown OriginType = 0 OriginTypeUser = iota OriginTypeMachine OriginTypeUnit ) var originTypes = map[OriginType]string{ OriginTypeUnknown: "unknown", OriginTypeUser: names.UserTagKind, OriginTypeMachine: names.MachineTagKind, OriginTypeUnit: names.UnitTagKind, } // OriginType is the "enum" type for the different kinds of log record // origin. type OriginType int // ParseOriginType converts a string to an OriginType or fails if // not able. It round-trips with String(). func ParseOriginType(value string) (OriginType, error) { for ot, str := range originTypes { if value == str { return ot, nil } } const originTypeInvalid OriginType = -1 return originTypeInvalid, errors.Errorf("unrecognized origin type %q", value) } // String returns a string representation of the origin type. func (ot OriginType) String() string { return originTypes[ot] } // Validate ensures that the origin type is correct. func (ot OriginType) Validate() error { // As noted above, typedef'ing int means that the use of int // literals or explicit type conversion could result in unsupported // "enum" values. Otherwise OriginType would not need this method. if _, ok := originTypes[ot]; !ok { return errors.NewNotValid(nil, "unsupported origin type") } return nil } // ValidateName ensures that the given origin name is valid within the // context of the origin type. func (ot OriginType) ValidateName(name string) error { switch ot { case OriginTypeUnknown: if name != "" { return errors.NewNotValid(nil, "origin name must not be set if type is unknown") } case OriginTypeUser: if !names.IsValidUser(name) { return errors.NewNotValid(nil, "bad user name") } case OriginTypeMachine: if !names.IsValidMachine(name) { return errors.NewNotValid(nil, "bad machine name") } case OriginTypeUnit: if !names.IsValidUnit(name) { return errors.NewNotValid(nil, "bad unit name") } } return nil } // Origin describes what created the record. type Origin struct { // ControllerUUID is the ID of the Juju controller under which the // record originated. ControllerUUID string // ModelUUID is the ID of the Juju model under which the record // originated. ModelUUID string // Hostname identifies the host where the record originated. Hostname string // Type identifies the kind of thing that generated the record. Type OriginType // Name identifies the thing that generated the record. Name string // Software identifies the running software that created the record. Software Software } // OriginForMachineAgent populates a new origin for the agent. func OriginForMachineAgent(tag names.MachineTag, controller, model string, ver version.Number) Origin { return originForAgent(OriginTypeMachine, tag, controller, model, ver) } // OriginForUnitAgent populates a new origin for the agent. func OriginForUnitAgent(tag names.UnitTag, controller, model string, ver version.Number) Origin { return originForAgent(OriginTypeUnit, tag, controller, model, ver) } func originForAgent(oType OriginType, tag names.Tag, controller, model string, ver version.Number) Origin { origin := originForJuju(oType, tag.Id(), controller, model, ver) origin.Hostname = fmt.Sprintf("%s.%s", tag, model) origin.Software.Name = fmt.Sprintf("jujud-%s-agent", tag.Kind()) return origin } // OriginForJuju populates a new origin for the juju client. func OriginForJuju(tag names.Tag, controller, model string, ver version.Number) (Origin, error) { oType, err := ParseOriginType(tag.Kind()) if err != nil { return Origin{}, errors.Annotate(err, "invalid tag") } return originForJuju(oType, tag.Id(), controller, model, ver), nil } func originForJuju(oType OriginType, name, controller, model string, ver version.Number) Origin { return Origin{ ControllerUUID: controller, ModelUUID: model, Type: oType, Name: name, Software: Software{ PrivateEnterpriseNumber: canonicalPEN, Name: "juju", Version: ver, }, } } // Validate ensures that the origin is correct. func (o Origin) Validate() error { if o.ControllerUUID == "" { return errors.NewNotValid(nil, "empty ControllerUUID") } if !names.IsValidModel(o.ControllerUUID) { return errors.NewNotValid(nil, fmt.Sprintf("ControllerUUID %q not a valid UUID", o.ControllerUUID)) } if o.ModelUUID == "" { return errors.NewNotValid(nil, "empty ModelUUID") } if !names.IsValidModel(o.ModelUUID) { return errors.NewNotValid(nil, fmt.Sprintf("ModelUUID %q not a valid UUID", o.ModelUUID)) } if err := o.Type.Validate(); err != nil { return errors.Annotate(err, "invalid Type") } if o.Name == "" && o.Type != OriginTypeUnknown { return errors.NewNotValid(nil, "empty Name") } if err := o.Type.ValidateName(o.Name); err != nil { return errors.Annotatef(err, "invalid Name %q", o.Name) } if !o.Software.isZero() { if err := o.Software.Validate(); err != nil { return errors.Annotate(err, "invalid Software") } } return nil } // Software describes a running application. type Software struct { // PrivateEnterpriseNumber is the IANA-registered "SMI Network // Management Private Enterprise Code" for the software's vendor. // // See https://tools.ietf.org/html/rfc5424#section-7.2.2. PrivateEnterpriseNumber int // Name identifies the software (relative to the vendor). Name string // Version is the software's version. Version version.Number } func (sw Software) isZero() bool { if sw.PrivateEnterpriseNumber > 0 { return false } if sw.Name != "" { return false } if sw.Version != version.Zero { return false } return true } // Validate ensures that the software info is correct. func (sw Software) Validate() error { if sw.PrivateEnterpriseNumber <= 0 { return errors.NewNotValid(nil, "missing PrivateEnterpriseNumber") } if sw.Name == "" { return errors.NewNotValid(nil, "empty Name") } if sw.Version == version.Zero { return errors.NewNotValid(nil, "empty Version") } return nil }
ericsnowcurrently/juju
logfwd/origin.go
GO
agpl-3.0
6,547
/* * 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.sling.testing.paxexam; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import static org.apache.sling.testing.paxexam.SlingOptions.eventadmin; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class SlingOptionsEventadminIT extends SlingOptionsTestSupport { @Configuration public Option[] configuration() { return new Option[]{ baseConfiguration(), eventadmin() }; } @Test public void test() { } }
ist-dresden/sling
testing/org.apache.sling.testing.paxexam/src/test/java/org/apache/sling/testing/paxexam/SlingOptionsEventadminIT.java
Java
apache-2.0
1,546
import { PlatformRef } from '@angular/core'; export * from './private_export_testing'; /** * @experimental API related to bootstrapping are still under review. */ export declare const platformBrowserDynamicTesting: (extraProviders?: any[]) => PlatformRef; /** * NgModule for testing. * * @stable */ export declare class BrowserDynamicTestingModule { } /** * @deprecated Use initTestEnvironment with platformBrowserDynamicTesting instead. */ export declare const TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS: Array<any>; /** * @deprecated Use initTestEnvironment with BrowserDynamicTestingModule instead. */ export declare const TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS: Array<any>;
oleksandr-minakov/northshore
ui/node_modules/@angular/platform-browser-dynamic/testing.d.ts
TypeScript
apache-2.0
689
/** * 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.hadoop.yarn.server.nodemanager.amrmproxy; import java.io.IOException; import java.util.Map; import com.google.common.base.Preconditions; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterRequest; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.server.api.protocolrecords.DistributedSchedulingAllocateRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.DistributedSchedulingAllocateResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterDistributedSchedulingAMResponse; import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService; /** * Implements the RequestInterceptor interface and provides common functionality * which can can be used and/or extended by other concrete intercepter classes. * */ public abstract class AbstractRequestInterceptor implements RequestInterceptor { private Configuration conf; private AMRMProxyApplicationContext appContext; private RequestInterceptor nextInterceptor; /** * Sets the {@link RequestInterceptor} in the chain. */ @Override public void setNextInterceptor(RequestInterceptor nextInterceptor) { this.nextInterceptor = nextInterceptor; } /** * Sets the {@link Configuration}. */ @Override public void setConf(Configuration conf) { this.conf = conf; if (this.nextInterceptor != null) { this.nextInterceptor.setConf(conf); } } /** * Gets the {@link Configuration}. */ @Override public Configuration getConf() { return this.conf; } /** * Initializes the {@link RequestInterceptor}. */ @Override public void init(AMRMProxyApplicationContext appContext) { Preconditions.checkState(this.appContext == null, "init is called multiple times on this interceptor: " + this.getClass().getName()); this.appContext = appContext; if (this.nextInterceptor != null) { this.nextInterceptor.init(appContext); } } /** * Recover {@link RequestInterceptor} state from store. */ @Override public void recover(Map<String, byte[]> recoveredDataMap) { if (this.nextInterceptor != null) { this.nextInterceptor.recover(recoveredDataMap); } } /** * Disposes the {@link RequestInterceptor}. */ @Override public void shutdown() { if (this.nextInterceptor != null) { this.nextInterceptor.shutdown(); } } /** * Gets the next {@link RequestInterceptor} in the chain. */ @Override public RequestInterceptor getNextInterceptor() { return this.nextInterceptor; } /** * Gets the {@link AMRMProxyApplicationContext}. */ public AMRMProxyApplicationContext getApplicationContext() { return this.appContext; } /** * Default implementation that invokes the distributed scheduling version * of the register method. * * @param request ApplicationMaster allocate request * @return Distribtued Scheduler Allocate Response * @throws YarnException if fails * @throws IOException if fails */ @Override public DistributedSchedulingAllocateResponse allocateForDistributedScheduling( DistributedSchedulingAllocateRequest request) throws YarnException, IOException { return (this.nextInterceptor != null) ? this.nextInterceptor.allocateForDistributedScheduling(request) : null; } /** * Default implementation that invokes the distributed scheduling version * of the allocate method. * * @param request ApplicationMaster registration request * @return Distributed Scheduler Register Response * @throws YarnException if fails * @throws IOException if fails */ @Override public RegisterDistributedSchedulingAMResponse registerApplicationMasterForDistributedScheduling( RegisterApplicationMasterRequest request) throws YarnException, IOException { return (this.nextInterceptor != null) ? this.nextInterceptor .registerApplicationMasterForDistributedScheduling(request) : null; } /** * A helper method for getting NM state store. * * @return the NMSS instance */ public NMStateStoreService getNMStateStore() { if (this.appContext == null || this.appContext.getNMCotext() == null) { return null; } return this.appContext.getNMCotext().getNMStateStore(); } }
dennishuo/hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/AbstractRequestInterceptor.java
Java
apache-2.0
5,223
// "Replace with Optional.ofNullable() chain" "GENERIC_ERROR_OR_WARNING" import java.util.Optional; class Test { interface V {} interface Type { V getValue(); } // IDEA-179273 public Optional<V> foo(Type arg) { return Optional.ofNullable(arg).map(Type::getValue); } }
siosio/intellij-community
java/java-tests/testData/inspection/conditionalCanBeOptional/afterOptionalReturn.java
Java
apache-2.0
291
/* Copyright 2018 The Kubernetes Authors. 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 polymorphichelpers import ( "fmt" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" extensionsv1beta1 "k8s.io/api/extensions/v1beta1" "k8s.io/apimachinery/pkg/runtime/schema" ) func canBeAutoscaled(kind schema.GroupKind) error { switch kind { case corev1.SchemeGroupVersion.WithKind("ReplicationController").GroupKind(), appsv1.SchemeGroupVersion.WithKind("Deployment").GroupKind(), appsv1.SchemeGroupVersion.WithKind("ReplicaSet").GroupKind(), extensionsv1beta1.SchemeGroupVersion.WithKind("Deployment").GroupKind(), extensionsv1beta1.SchemeGroupVersion.WithKind("ReplicaSet").GroupKind(): // nothing to do here default: return fmt.Errorf("cannot autoscale a %v", kind) } return nil }
liyinan926/kubernetes
pkg/kubectl/polymorphichelpers/canbeautoscaled.go
GO
apache-2.0
1,298
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.hadoop.integration.rest.ssl; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.ssl.SslContext; import java.io.File; import java.nio.file.Paths; import org.elasticsearch.hadoop.util.StringUtils; import static io.netty.handler.codec.http.HttpHeaders.Names.*; import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpVersion.*; public class BasicSSLServer { private static class BasicSSLServerInitializer extends ChannelInitializer<SocketChannel> { private final SslContext sslCtx; public BasicSSLServerInitializer(SslContext sslCtx) { this.sslCtx = sslCtx; } @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(sslCtx.newHandler(ch.alloc())); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new EchoServerHandler()); } } @Sharable public static class EchoServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(req.getUri().getBytes(StringUtils.UTF_8))); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); ctx.write(response).addListener(ChannelFutureListener.CLOSE); } } @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // Close the connection when an exception is raised. cause.printStackTrace(); ctx.close(); } } private EventLoopGroup bossGroup, workerGroup; private ServerBootstrap server; private final int port; public File certificate; public File privateKey; public BasicSSLServer(int port) throws Exception { this.port = port; } public void start() throws Exception { File cert = Paths.get(getClass().getResource("/ssl/server.pem").toURI()).toFile(); File keyStore = Paths.get(getClass().getResource("/ssl/server.key").toURI()).toFile(); SslContext sslCtx = SslContext.newServerContext(cert, keyStore); bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); server = new ServerBootstrap(); server.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new BasicSSLServerInitializer(sslCtx)); server.bind(port).sync().channel().closeFuture(); } public void stop() throws Exception { if (bossGroup != null) { bossGroup.shutdownGracefully(); } if (workerGroup != null) { workerGroup.shutdownGracefully(); } } }
jasontedor/elasticsearch-hadoop
mr/src/itest/java/org/elasticsearch/hadoop/integration/rest/ssl/BasicSSLServer.java
Java
apache-2.0
5,006
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.integration; import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequestBuilder; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.test.SecuritySettingsSourceField; import org.elasticsearch.xpack.core.XPackSettings; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken.BASIC_AUTH_HEADER; import static org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue; import static org.hamcrest.Matchers.equalTo; public class DocumentLevelSecurityRandomTests extends SecurityIntegTestCase { protected static final SecureString USERS_PASSWD = SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING; // can't add a second test method, because each test run creates a new instance of this class and that will will result // in a new random value: private final int numberOfRoles = scaledRandomIntBetween(3, 99); @Override protected String configUsers() { final String usersPasswdHashed = new String(getFastStoredHashAlgoForTests().hash(USERS_PASSWD)); StringBuilder builder = new StringBuilder(super.configUsers()); for (int i = 1; i <= numberOfRoles; i++) { builder.append("user").append(i).append(':').append(usersPasswdHashed).append('\n'); } return builder.toString(); } @Override protected String configUsersRoles() { StringBuilder builder = new StringBuilder(super.configUsersRoles()); builder.append("role0:"); for (int i = 1; i <= numberOfRoles; i++) { builder.append("user").append(i); if (i != numberOfRoles) { builder.append(","); } } builder.append("\n"); for (int i = 1; i <= numberOfRoles; i++) { builder.append("role").append(i).append(":user").append(i).append('\n'); } return builder.toString(); } @Override protected String configRoles() { StringBuilder builder = new StringBuilder(super.configRoles()); builder.append("\nrole0:\n"); builder.append(" cluster: [ none ]\n"); builder.append(" indices:\n"); builder.append(" - names: '*'\n"); builder.append(" privileges: [ none ]\n"); for (int i = 1; i <= numberOfRoles; i++) { builder.append("role").append(i).append(":\n"); builder.append(" cluster: [ all ]\n"); builder.append(" indices:\n"); builder.append(" - names: '*'\n"); builder.append(" privileges:\n"); builder.append(" - all\n"); builder.append(" query: \n"); builder.append(" term: \n"); builder.append(" field1: value").append(i).append('\n'); } return builder.toString(); } @Override public Settings nodeSettings(int nodeOrdinal, Settings otherSettings) { return Settings.builder() .put(super.nodeSettings(nodeOrdinal, otherSettings)) .put(XPackSettings.DLS_FLS_ENABLED.getKey(), true) .build(); } public void testDuelWithAliasFilters() throws Exception { assertAcked(client().admin().indices().prepareCreate("test").setMapping("field1", "type=text", "field2", "type=text")); List<IndexRequestBuilder> requests = new ArrayList<>(numberOfRoles); IndicesAliasesRequestBuilder builder = client().admin().indices().prepareAliases(); for (int i = 1; i <= numberOfRoles; i++) { String value = "value" + i; requests.add(client().prepareIndex("test").setId(value).setSource("field1", value)); builder.addAlias("test", "alias" + i, QueryBuilders.termQuery("field1", value)); } indexRandom(true, requests); builder.get(); for (int roleI = 1; roleI <= numberOfRoles; roleI++) { SearchResponse searchResponse1 = client().filterWithHeader( Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue("user" + roleI, USERS_PASSWD)) ).prepareSearch("test").get(); SearchResponse searchResponse2 = client().prepareSearch("alias" + roleI).get(); assertThat(searchResponse1.getHits().getTotalHits().value, equalTo(searchResponse2.getHits().getTotalHits().value)); for (int hitI = 0; hitI < searchResponse1.getHits().getHits().length; hitI++) { assertThat(searchResponse1.getHits().getAt(hitI).getId(), equalTo(searchResponse2.getHits().getAt(hitI).getId())); } } } }
GlenRSmith/elasticsearch
x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/integration/DocumentLevelSecurityRandomTests.java
Java
apache-2.0
5,357
const url_base = "/permissions-policy/experimental-features/resources/"; window.messageResponseCallback = null; function setFeatureState(iframe, feature, origins) { iframe.setAttribute("allow", `${feature} ${origins};`); } // Returns a promise which is resolved when the <iframe> is navigated to |url| // and "load" handler has been called. function loadUrlInIframe(iframe, url) { return new Promise((resolve) => { iframe.addEventListener("load", resolve); iframe.src = url; }); } // Posts |message| to |target| and resolves the promise with the response coming // back from |target|. function sendMessageAndGetResponse(target, message) { return new Promise((resolve) => { window.messageResponseCallback = resolve; target.postMessage(message, "*"); }); } function onMessage(e) { if (window.messageResponseCallback) { window.messageResponseCallback(e.data); window.messageResponseCallback = null; } } window.addEventListener("message", onMessage); // Waits for |load_timeout| before resolving the promise. It will resolve the // promise sooner if a message event with |e.data.id| of |id| is received. // In such a case the response is the contents of the message |e.data.contents|. // Otherwise, returns false (when timeout occurs). function waitForMessageOrTimeout(t, id, load_timeout) { return new Promise((resolve) => { window.addEventListener( "message", (e) => { if (!e.data || e.data.id !== id) return; resolve(e.data.contents); } ); t.step_timeout(() => { resolve(false); }, load_timeout); }); } function createIframe(container, attributes) { var new_iframe = document.createElement("iframe"); for (attr_name in attributes) new_iframe.setAttribute(attr_name, attributes[attr_name]); container.appendChild(new_iframe); return new_iframe; } // Returns a promise which is resolved when |load| event is dispatched for |e|. function wait_for_load(e) { return new Promise((resolve) => { e.addEventListener("load", resolve); }); } setup(() => { window.reporting_observer_instance = new ReportingObserver((reports, observer) => { if (window.reporting_observer_callback) { reports.forEach(window.reporting_observer_callback); } }, {types: ["permissions-policy-violation"]}); window.reporting_observer_instance.observe(); window.reporting_observer_callback = null; }); // Waits for a violation in |feature| and source file containing |file_name|. function wait_for_violation_in_file(feature, file_name) { return new Promise( (resolve) => { assert_equals(null, window.reporting_observer_callback); window.reporting_observer_callback = (report) => { var feature_match = (feature === report.body.featureId); var file_name_match = !file_name || (report.body.sourceFile.indexOf(file_name) !== -1); if (feature_match && file_name_match) { window.reporting_observer_callback = null; resolve(report); } }; }); }
chromium/chromium
third_party/blink/web_tests/external/wpt/permissions-policy/experimental-features/resources/common.js
JavaScript
bsd-3-clause
3,063
/** Added to editors of custom graph types */ [System.AttributeUsage(System.AttributeTargets.All, Inherited = false, AllowMultiple = true)] public class CustomGraphEditorAttribute : System.Attribute { /** Graph type which this is an editor for */ public System.Type graphType; /** Name displayed in the inpector */ public string displayName; /** Type of the editor for the graph */ public System.Type editorType; public CustomGraphEditorAttribute (System.Type t, string displayName) { graphType = t; this.displayName = displayName; } }
NBurrichter/Brainzzz
UnityGame/Brainz/Assets/AstarPathfindingProject/Editor/CustomGraphEditorAttribute.cs
C#
mit
551
# -*- coding: utf-8 -*- import os.path import shutil import uuid import re from django.test import TestCase from django.contrib.auth.models import User from mock import patch, Mock, PropertyMock from docker.errors import APIError as DockerAPIError, DockerException from readthedocs.projects.models import Project from readthedocs.builds.models import Version from readthedocs.doc_builder.environments import (DockerEnvironment, DockerBuildCommand, LocalEnvironment, BuildCommand) from readthedocs.doc_builder.exceptions import BuildEnvironmentError from readthedocs.rtd_tests.utils import make_test_git from readthedocs.rtd_tests.base import RTDTestCase from readthedocs.rtd_tests.mocks.environment import EnvironmentMockGroup class TestLocalEnvironment(TestCase): '''Test execution and exception handling in environment''' fixtures = ['test_data'] def setUp(self): self.project = Project.objects.get(slug='pip') self.version = Version(slug='foo', verbose_name='foobar') self.project.versions.add(self.version) self.mocks = EnvironmentMockGroup() self.mocks.start() def tearDown(self): self.mocks.stop() def test_normal_execution(self): '''Normal build in passing state''' self.mocks.configure_mock('process', { 'communicate.return_value': ('This is okay', '')}) type(self.mocks.process).returncode = PropertyMock(return_value=0) build_env = LocalEnvironment(version=self.version, project=self.project, build={}) with build_env: build_env.run('echo', 'test') self.assertTrue(self.mocks.process.communicate.called) self.assertTrue(build_env.done) self.assertTrue(build_env.successful) self.assertEqual(len(build_env.commands), 1) self.assertEqual(build_env.commands[0].output, u'This is okay') def test_failing_execution(self): '''Build in failing state''' self.mocks.configure_mock('process', { 'communicate.return_value': ('This is not okay', '')}) type(self.mocks.process).returncode = PropertyMock(return_value=1) build_env = LocalEnvironment(version=self.version, project=self.project, build={}) with build_env: build_env.run('echo', 'test') self.fail('This should be unreachable') self.assertTrue(self.mocks.process.communicate.called) self.assertTrue(build_env.done) self.assertTrue(build_env.failed) self.assertEqual(len(build_env.commands), 1) self.assertEqual(build_env.commands[0].output, u'This is not okay') def test_failing_execution_with_caught_exception(self): '''Build in failing state with BuildEnvironmentError exception''' build_env = LocalEnvironment(version=self.version, project=self.project, build={}) with build_env: raise BuildEnvironmentError('Foobar') self.assertFalse(self.mocks.process.communicate.called) self.assertEqual(len(build_env.commands), 0) self.assertTrue(build_env.done) self.assertTrue(build_env.failed) def test_failing_execution_with_uncaught_exception(self): '''Build in failing state with exception from code''' build_env = LocalEnvironment(version=self.version, project=self.project, build={}) def _inner(): with build_env: raise Exception() self.assertRaises(Exception, _inner) self.assertFalse(self.mocks.process.communicate.called) self.assertTrue(build_env.done) self.assertTrue(build_env.failed) class TestDockerEnvironment(TestCase): '''Test docker build environment''' fixtures = ['test_data'] def setUp(self): self.project = Project.objects.get(slug='pip') self.version = Version(slug='foo', verbose_name='foobar') self.project.versions.add(self.version) self.mocks = EnvironmentMockGroup() self.mocks.start() def tearDown(self): self.mocks.stop() def test_container_id(self): '''Test docker build command''' docker = DockerEnvironment(version=self.version, project=self.project, build={}) self.assertEqual(docker.container_id, 'version-foobar-of-pip-20') def test_connection_failure(self): '''Connection failure on to docker socket should raise exception''' self.mocks.configure_mock('docker', { 'side_effect': DockerException }) build_env = DockerEnvironment(version=self.version, project=self.project, build={}) def _inner(): with build_env: self.fail('Should not hit this') self.assertRaises(BuildEnvironmentError, _inner) def test_api_failure(self): '''Failing API error response from docker should raise exception''' response = Mock(status_code=500, reason='Because') self.mocks.configure_mock('docker_client', { 'create_container.side_effect': DockerAPIError( 'Failure creating container', response, 'Failure creating container' ) }) build_env = DockerEnvironment(version=self.version, project=self.project, build={}) def _inner(): with build_env: self.fail('Should not hit this') self.assertRaises(BuildEnvironmentError, _inner) def test_command_execution(self): '''Command execution through Docker''' self.mocks.configure_mock('docker_client', { 'exec_create.return_value': {'Id': 'container-foobar'}, 'exec_start.return_value': 'This is the return', 'exec_inspect.return_value': {'ExitCode': 1}, }) build_env = DockerEnvironment(version=self.version, project=self.project, build={}) with build_env: build_env.run('echo test', cwd='/tmp') self.mocks.docker_client.exec_create.assert_called_with( container='version-foobar-of-pip-20', cmd="/bin/sh -c 'cd /tmp && echo\\ test'", stderr=True, stdout=True ) self.assertEqual(build_env.commands[0].exit_code, 1) self.assertEqual(build_env.commands[0].output, 'This is the return') self.assertEqual(build_env.commands[0].error, None) self.assertTrue(build_env.failed) def test_command_execution_cleanup_exception(self): '''Command execution through Docker, catch exception during cleanup''' response = Mock(status_code=500, reason='Because') self.mocks.configure_mock('docker_client', { 'exec_create.return_value': {'Id': 'container-foobar'}, 'exec_start.return_value': 'This is the return', 'exec_inspect.return_value': {'ExitCode': 0}, 'kill.side_effect': DockerAPIError( 'Failure killing container', response, 'Failure killing container' ) }) build_env = DockerEnvironment(version=self.version, project=self.project, build={}) with build_env: build_env.run('echo', 'test', cwd='/tmp') self.mocks.docker_client.kill.assert_called_with( 'version-foobar-of-pip-20') self.assertTrue(build_env.successful) def test_container_already_exists(self): '''Docker container already exists''' self.mocks.configure_mock('docker_client', { 'inspect_container.return_value': {'State': {'Running': True}}, 'exec_create.return_value': {'Id': 'container-foobar'}, 'exec_start.return_value': 'This is the return', 'exec_inspect.return_value': {'ExitCode': 0}, }) build_env = DockerEnvironment(version=self.version, project=self.project, build={}) def _inner(): with build_env: build_env.run('echo', 'test', cwd='/tmp') self.assertRaises(BuildEnvironmentError, _inner) self.assertEqual( str(build_env.failure), 'A build environment is currently running for this version') self.assertEqual(self.mocks.docker_client.exec_create.call_count, 0) self.assertTrue(build_env.failed) def test_container_timeout(self): '''Docker container timeout and command failure''' response = Mock(status_code=404, reason='Container not found') self.mocks.configure_mock('docker_client', { 'inspect_container.side_effect': [ DockerAPIError( 'No container found', response, 'No container found', ), {'State': {'Running': False, 'ExitCode': 42}}, ], 'exec_create.return_value': {'Id': 'container-foobar'}, 'exec_start.return_value': 'This is the return', 'exec_inspect.return_value': {'ExitCode': 0}, }) build_env = DockerEnvironment(version=self.version, project=self.project, build={}) with build_env: build_env.run('echo', 'test', cwd='/tmp') self.assertEqual( str(build_env.failure), 'Build exited due to time out') self.assertEqual(self.mocks.docker_client.exec_create.call_count, 1) self.assertTrue(build_env.failed) class TestBuildCommand(TestCase): '''Test build command creation''' def test_command_env(self): '''Test build command env vars''' env = {'FOOBAR': 'foobar', 'PATH': 'foobar'} cmd = BuildCommand('echo', environment=env) for key in env.keys(): self.assertEqual(cmd.environment[key], env[key]) def test_result(self): '''Test result of output using unix true/false commands''' cmd = BuildCommand('true') cmd.run() self.assertTrue(cmd.successful) cmd = BuildCommand('false') cmd.run() self.assertTrue(cmd.failed) def test_missing_command(self): '''Test missing command''' path = os.path.join('non-existant', str(uuid.uuid4())) self.assertFalse(os.path.exists(path)) cmd = BuildCommand(path) cmd.run() missing_re = re.compile(r'(?:No such file or directory|not found)') self.assertRegexpMatches(cmd.error, missing_re) def test_input(self): '''Test input to command''' cmd = BuildCommand('/bin/cat', input_data='FOOBAR') cmd.run() self.assertEqual(cmd.output, 'FOOBAR') def test_output(self): '''Test output command''' cmd = BuildCommand(['/bin/bash', '-c', 'echo -n FOOBAR']) cmd.run() self.assertEqual(cmd.output, "FOOBAR") def test_error_output(self): '''Test error output from command''' # Test default combined output/error streams cmd = BuildCommand(['/bin/bash', '-c', 'echo -n FOOBAR 1>&2']) cmd.run() self.assertEqual(cmd.output, 'FOOBAR') self.assertIsNone(cmd.error) # Test non-combined streams cmd = BuildCommand(['/bin/bash', '-c', 'echo -n FOOBAR 1>&2'], combine_output=False) cmd.run() self.assertEqual(cmd.output, '') self.assertEqual(cmd.error, 'FOOBAR') @patch('subprocess.Popen') def test_unicode_output(self, mock_subprocess): '''Unicode output from command''' mock_process = Mock(**{ 'communicate.return_value': (b'HérÉ îß sömê ünïçó∂é', ''), }) mock_subprocess.return_value = mock_process cmd = BuildCommand(['echo', 'test'], cwd='/tmp/foobar') cmd.run() self.assertEqual( cmd.output, u'H\xe9r\xc9 \xee\xdf s\xf6m\xea \xfcn\xef\xe7\xf3\u2202\xe9') class TestDockerBuildCommand(TestCase): '''Test docker build commands''' def setUp(self): self.mocks = EnvironmentMockGroup() self.mocks.start() def tearDown(self): self.mocks.stop() def test_wrapped_command(self): '''Test shell wrapping for Docker chdir''' cmd = DockerBuildCommand(['pip', 'install', 'requests'], cwd='/tmp/foobar') self.assertEqual( cmd.get_wrapped_command(), ("/bin/sh -c " "'cd /tmp/foobar && " "pip install requests'")) cmd = DockerBuildCommand(['python', '/tmp/foo/pip', 'install', 'Django>1.7'], cwd='/tmp/foobar', bin_path='/tmp/foo') self.assertEqual( cmd.get_wrapped_command(), ("/bin/sh -c " "'cd /tmp/foobar && PATH=/tmp/foo:$PATH " "python /tmp/foo/pip install Django\>1.7'")) def test_unicode_output(self): '''Unicode output from command''' self.mocks.configure_mock('docker_client', { 'exec_create.return_value': {'Id': 'container-foobar'}, 'exec_start.return_value': b'HérÉ îß sömê ünïçó∂é', 'exec_inspect.return_value': {'ExitCode': 0}, }) cmd = DockerBuildCommand(['echo', 'test'], cwd='/tmp/foobar') cmd.build_env = Mock() cmd.build_env.get_client.return_value = self.mocks.docker_client type(cmd.build_env).container_id = PropertyMock(return_value='foo') cmd.run() self.assertEqual( cmd.output, u'H\xe9r\xc9 \xee\xdf s\xf6m\xea \xfcn\xef\xe7\xf3\u2202\xe9') self.assertEqual(self.mocks.docker_client.exec_start.call_count, 1) self.assertEqual(self.mocks.docker_client.exec_create.call_count, 1) self.assertEqual(self.mocks.docker_client.exec_inspect.call_count, 1) def test_command_oom_kill(self): '''Command is OOM killed''' self.mocks.configure_mock('docker_client', { 'exec_create.return_value': {'Id': 'container-foobar'}, 'exec_start.return_value': b'Killed\n', 'exec_inspect.return_value': {'ExitCode': 137}, }) cmd = DockerBuildCommand(['echo', 'test'], cwd='/tmp/foobar') cmd.build_env = Mock() cmd.build_env.get_client.return_value = self.mocks.docker_client type(cmd.build_env).container_id = PropertyMock(return_value='foo') cmd.run() self.assertEqual( str(cmd.output), u'Command killed due to excessive memory consumption\n')
stevepiercy/readthedocs.org
readthedocs/rtd_tests/tests/test_doc_building.py
Python
mit
15,211
/* * File: urlstream.cpp * ------------------- * This file contains the implementation of the iurlstream class. * Please see urlstream.h for information about how to use these classes. * * @author Marty Stepp * @version 2015/07/05 * - removed static global Platform variable, replaced by getPlatform as needed * @version 2014/10/14 * - fixed .c_str() Mac bug on ifstream::open() call * @since 2014/10/08 */ #include "urlstream.h" #include <sstream> #include <string> #include "error.h" #include "filelib.h" #include "strlib.h" #include "private/platform.h" iurlstream::iurlstream() : m_url(""), m_tempFilePath(""), m_lastError(0) { // empty } iurlstream::iurlstream(std::string url) : m_url(url), m_tempFilePath(""), m_lastError(0) { open(url); } void iurlstream::close() { std::ifstream::close(); if (!m_tempFilePath.empty() && fileExists(m_tempFilePath)) { deleteFile(m_tempFilePath); } m_tempFilePath = ""; m_lastError = 0; } int iurlstream::getErrorCode() const { return m_lastError; } void iurlstream::open(std::string url) { if (url.empty()) { url = m_url; } // download the entire URL to a temp file, put into stringbuf for reading std::string tempDir = getTempDirectory(); std::string filename = getUrlFilename(url); m_tempFilePath = tempDir + getDirectoryPathSeparator() + filename; m_lastError = stanfordcpplib::getPlatform()->url_download(url, filename); if (m_lastError == ERR_MALFORMED_URL) { error("iurlstream::open: malformed URL when downloading " + url + " to " + m_tempFilePath); } else if (m_lastError == ERR_IO_EXCEPTION) { error("iurlstream::open: network I/O error when downloading " + url + " to " + m_tempFilePath); } if (m_lastError == 200) { std::ifstream::open(m_tempFilePath.c_str()); } else { setstate(std::ios::failbit); } } std::string iurlstream::getUrlFilename(std::string url) const { std::string filename = url; // strip query string, anchor from URL int questionmark = stringIndexOf(url, "?"); if (questionmark >= 0) { filename = filename.substr(0, questionmark); } int hash = stringIndexOf(url, "#"); if (hash >= 0) { filename = filename.substr(0, hash); } filename = getTail(filename); if (filename.empty()) { filename = "index.tmp"; // for / urls like http://google.com/ } return filename; }
shawlu95/SuperWordLadder
lib/StanfordCPPLib/io/urlstream.cpp
C++
mit
2,486
<?php /* * The RandomLib library for securely generating random numbers and strings in PHP * * @author Anthony Ferrara <ircmaxell@ircmaxell.com> * @copyright 2011 The Authors * @license http://www.opensource.org/licenses/mit-license.html MIT License * @version Build @@version@@ */ namespace RandomLib\Mixer; use SecurityLib\Strength; class HashTest extends \PHPUnit_Framework_TestCase { public static function provideMix() { $data = array( array(array(), ''), array(array('1', '1'), '0d'), array(array('a'), '61'), // This expects 'b' because of how the mock hmac function works array(array('a', 'b'), '9a'), array(array('aa', 'ba'), '6e84'), array(array('ab', 'bb'), 'b0cb'), array(array('aa', 'bb'), 'ae8d'), array(array('aa', 'bb', 'cc'), 'a14c'), array(array('aabbcc', 'bbccdd', 'ccddee'), 'a8aff3939934'), ); return $data; } public function testConstructWithoutArgument() { $hash = new Hash(); $this->assertTrue($hash instanceof \RandomLib\Mixer); } public function testGetStrength() { $strength = new Strength(Strength::MEDIUM); $actual = Hash::getStrength(); $this->assertEquals($actual, $strength); } public function testTest() { $actual = Hash::test(); $this->assertTrue($actual); } /** * @dataProvider provideMix */ public function testMix($parts, $result) { $mixer = new Hash('md5'); $actual = $mixer->mix($parts); $this->assertEquals($result, bin2hex($actual)); } }
masmike/accu
vendor/ircmaxell/random-lib/test/Unit/RandomLib/Mixer/HashTest.php
PHP
mit
1,704
# coding=utf-8 # (c) 2018, NetApp Inc. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from ansible.modules.storage.netapp.netapp_e_mgmt_interface import MgmtInterface from units.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase, set_module_args __metaclass__ = type import mock from units.compat.mock import PropertyMock class MgmtInterfaceTest(ModuleTestCase): REQUIRED_PARAMS = { 'api_username': 'rw', 'api_password': 'password', 'api_url': 'http://localhost', 'ssid': '1', } TEST_DATA = [ { "controllerRef": "070000000000000000000001", "controllerSlot": 1, "interfaceName": "wan0", "interfaceRef": "2800070000000000000000000001000000000000", "channel": 1, "alias": "creG1g-AP-a", "ipv4Enabled": True, "ipv4Address": "10.1.1.10", "linkStatus": "up", "ipv4SubnetMask": "255.255.255.0", "ipv4AddressConfigMethod": "configStatic", "ipv4GatewayAddress": "10.1.1.1", "ipv6Enabled": False, "physicalLocation": { "slot": 0, }, "dnsProperties": { "acquisitionProperties": { "dnsAcquisitionType": "stat", "dnsServers": [ { "addressType": "ipv4", "ipv4Address": "10.1.0.250", }, { "addressType": "ipv4", "ipv4Address": "10.10.0.20", } ] }, "dhcpAcquiredDnsServers": [] }, "ntpProperties": { "acquisitionProperties": { "ntpAcquisitionType": "disabled", "ntpServers": None }, "dhcpAcquiredNtpServers": [] }, }, { "controllerRef": "070000000000000000000001", "controllerSlot": 1, "interfaceName": "wan1", "interfaceRef": "2800070000000000000000000001000000000000", "channel": 2, "alias": "creG1g-AP-a", "ipv4Enabled": True, "ipv4Address": "0.0.0.0", "ipv4SubnetMask": "0.0.0.0", "ipv4AddressConfigMethod": "configDhcp", "ipv4GatewayAddress": "10.1.1.1", "ipv6Enabled": False, "physicalLocation": { "slot": 1, }, "dnsProperties": { "acquisitionProperties": { "dnsAcquisitionType": "stat", "dnsServers": [ { "addressType": "ipv4", "ipv4Address": "10.1.0.250", "ipv6Address": None }, { "addressType": "ipv4", "ipv4Address": "10.10.0.20", "ipv6Address": None } ] }, "dhcpAcquiredDnsServers": [] }, "ntpProperties": { "acquisitionProperties": { "ntpAcquisitionType": "disabled", "ntpServers": None }, "dhcpAcquiredNtpServers": [] }, }, { "controllerRef": "070000000000000000000002", "controllerSlot": 2, "interfaceName": "wan0", "interfaceRef": "2800070000000000000000000001000000000000", "channel": 1, "alias": "creG1g-AP-b", "ipv4Enabled": True, "ipv4Address": "0.0.0.0", "ipv4SubnetMask": "0.0.0.0", "ipv4AddressConfigMethod": "configDhcp", "ipv4GatewayAddress": "10.1.1.1", "ipv6Enabled": False, "physicalLocation": { "slot": 0, }, "dnsProperties": { "acquisitionProperties": { "dnsAcquisitionType": "stat", "dnsServers": [ { "addressType": "ipv4", "ipv4Address": "10.1.0.250", "ipv6Address": None } ] }, "dhcpAcquiredDnsServers": [] }, "ntpProperties": { "acquisitionProperties": { "ntpAcquisitionType": "stat", "ntpServers": [ { "addrType": "ipvx", "domainName": None, "ipvxAddress": { "addressType": "ipv4", "ipv4Address": "10.13.1.5", "ipv6Address": None } }, { "addrType": "ipvx", "domainName": None, "ipvxAddress": { "addressType": "ipv4", "ipv4Address": "10.15.1.8", "ipv6Address": None } } ] }, "dhcpAcquiredNtpServers": [] }, }, { "controllerRef": "070000000000000000000002", "controllerSlot": 2, "interfaceName": "wan1", "interfaceRef": "2801070000000000000000000001000000000000", "channel": 2, "alias": "creG1g-AP-b", "ipv4Enabled": True, "ipv4Address": "0.0.0.0", "ipv4SubnetMask": "0.0.0.0", "ipv4AddressConfigMethod": "configDhcp", "ipv4GatewayAddress": "10.1.1.1", "ipv6Enabled": False, "physicalLocation": { "slot": 1, }, "dnsProperties": { "acquisitionProperties": { "dnsAcquisitionType": "stat", "dnsServers": [ { "addressType": "ipv4", "ipv4Address": "10.19.1.2", "ipv6Address": None } ] }, "dhcpAcquiredDnsServers": [] }, "ntpProperties": { "acquisitionProperties": { "ntpAcquisitionType": "stat", "ntpServers": [ { "addrType": "ipvx", "domainName": None, "ipvxAddress": { "addressType": "ipv4", "ipv4Address": "10.13.1.5", "ipv6Address": None } }, { "addrType": "ipvx", "domainName": None, "ipvxAddress": { "addressType": "ipv4", "ipv4Address": "10.15.1.18", "ipv6Address": None } } ] }, "dhcpAcquiredNtpServers": [] }, }, ] REQ_FUNC = 'ansible.modules.storage.netapp.netapp_e_mgmt_interface.request' def _set_args(self, args=None): module_args = self.REQUIRED_PARAMS.copy() if args is not None: module_args.update(args) set_module_args(module_args) def test_controller_property_pass(self): """Verify dictionary return from controller property.""" initial = { "state": "enable", "controller": "A", "channel": "1", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static"} controller_request = [ {"physicalLocation": {"slot": 2}, "controllerRef": "070000000000000000000002", "networkSettings": {"remoteAccessEnabled": True}}, {"physicalLocation": {"slot": 1}, "controllerRef": "070000000000000000000001", "networkSettings": {"remoteAccessEnabled": False}}] expected = { 'A': {'controllerRef': '070000000000000000000001', 'controllerSlot': 1, 'ssh': False}, 'B': {'controllerRef': '070000000000000000000002', 'controllerSlot': 2, 'ssh': True}} self._set_args(initial) mgmt_interface = MgmtInterface() with mock.patch(self.REQ_FUNC, return_value=(200, controller_request)): response = mgmt_interface.controllers self.assertTrue(response == expected) def test_controller_property_fail(self): """Verify controllers endpoint request failure causes AnsibleFailJson exception.""" initial = { "state": "enable", "controller": "A", "channel": "1", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static"} controller_request = [ {"physicalLocation": {"slot": 2}, "controllerRef": "070000000000000000000002", "networkSettings": {"remoteAccessEnabled": True}}, {"physicalLocation": {"slot": 1}, "controllerRef": "070000000000000000000001", "networkSettings": {"remoteAccessEnabled": False}}] expected = { 'A': {'controllerRef': '070000000000000000000001', 'controllerSlot': 1, 'ssh': False}, 'B': {'controllerRef': '070000000000000000000002', 'controllerSlot': 2, 'ssh': True}} self._set_args(initial) mgmt_interface = MgmtInterface() with self.assertRaisesRegexp(AnsibleFailJson, r"Failed to retrieve the controller settings."): with mock.patch(self.REQ_FUNC, return_value=Exception): response = mgmt_interface.controllers def test_interface_property_match_pass(self): """Verify return value from interface property.""" initial = { "state": "enable", "controller": "A", "channel": "1", "address": "192.168.1.1", "subnet_mask": "255.255.255.0", "config_method": "static"} controller_request = [ {"physicalLocation": {"slot": 2}, "controllerRef": "070000000000000000000002", "networkSettings": {"remoteAccessEnabled": True}}, {"physicalLocation": {"slot": 1}, "controllerRef": "070000000000000000000001", "networkSettings": {"remoteAccessEnabled": False}}] expected = { "dns_servers": [{"ipv4Address": "10.1.0.250", "addressType": "ipv4"}, {"ipv4Address": "10.10.0.20", "addressType": "ipv4"}], "subnet_mask": "255.255.255.0", "link_status": "up", "ntp_servers": None, "ntp_config_method": "disabled", "controllerRef": "070000000000000000000001", "config_method": "configStatic", "enabled": True, "gateway": "10.1.1.1", "alias": "creG1g-AP-a", "controllerSlot": 1, "dns_config_method": "stat", "id": "2800070000000000000000000001000000000000", "address": "10.1.1.10", "ipv6Enabled": False, "channel": 1} self._set_args(initial) mgmt_interface = MgmtInterface() with mock.patch(self.REQ_FUNC, side_effect=[(200, self.TEST_DATA), (200, controller_request)]): iface = mgmt_interface.interface self.assertTrue(iface == expected) def test_interface_property_request_exception_fail(self): """Verify ethernet-interfaces endpoint request failure results in AnsibleFailJson exception.""" initial = { "state": "enable", "controller": "A", "channel": "1", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static"} controller_request = [ {"physicalLocation": {"slot": 2}, "controllerRef": "070000000000000000000002", "networkSettings": {"remoteAccessEnabled": True}}, {"physicalLocation": {"slot": 1}, "controllerRef": "070000000000000000000001", "networkSettings": {"remoteAccessEnabled": False}}] self._set_args(initial) mgmt_interface = MgmtInterface() with self.assertRaisesRegexp(AnsibleFailJson, r"Failed to retrieve defined management interfaces."): with mock.patch(self.REQ_FUNC, side_effect=[Exception, (200, controller_request)]): iface = mgmt_interface.interface def test_interface_property_no_match_fail(self): """Verify return value from interface property.""" initial = { "state": "enable", "controller": "A", "name": "wrong_name", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static"} controller_request = [ {"physicalLocation": {"slot": 2}, "controllerRef": "070000000000000000000002", "networkSettings": {"remoteAccessEnabled": True}}, {"physicalLocation": {"slot": 1}, "controllerRef": "070000000000000000000001", "networkSettings": {"remoteAccessEnabled": False}}] expected = { "dns_servers": [{"ipv4Address": "10.1.0.20", "addressType": "ipv4"}, {"ipv4Address": "10.1.0.50", "addressType": "ipv4"}], "subnet_mask": "255.255.255.0", "ntp_servers": None, "ntp_config_method": "disabled", "controllerRef": "070000000000000000000001", "config_method": "configStatic", "enabled": True, "gateway": "10.1.1.1", "alias": "creG1g-AP-a", "controllerSlot": 1, "dns_config_method": "stat", "id": "2800070000000000000000000001000000000000", "address": "10.1.1.111", "ipv6Enabled": False, "channel": 1} self._set_args(initial) mgmt_interface = MgmtInterface() with self.assertRaisesRegexp(AnsibleFailJson, r"We could not find an interface matching"): with mock.patch(self.REQ_FUNC, side_effect=[(200, self.TEST_DATA), (200, controller_request)]): iface = mgmt_interface.interface def test_get_enable_interface_settings_enabled_pass(self): """Validate get_enable_interface_settings updates properly.""" initial = { "state": "enable", "controller": "A", "name": "wrong_name", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static"} iface = {"enabled": False} expected_iface = {} self._set_args(initial) mgmt_interface = MgmtInterface() update, expected_iface, body = mgmt_interface.get_enable_interface_settings(iface, expected_iface, False, {}) self.assertTrue(update and expected_iface["enabled"] and body["ipv4Enabled"]) def test_get_enable_interface_settings_disabled_pass(self): """Validate get_enable_interface_settings updates properly.""" initial = { "state": "disable", "controller": "A", "name": "wan0", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static"} iface = {"enabled": True} expected_iface = {} self._set_args(initial) mgmt_interface = MgmtInterface() update, expected_iface, body = mgmt_interface.get_enable_interface_settings(iface, expected_iface, False, {}) self.assertTrue(update and not expected_iface["enabled"] and not body["ipv4Enabled"]) def test_update_array_interface_ssh_pass(self): """Verify get_interface_settings gives the right static configuration response.""" initial = { "state": "enable", "controller": "A", "name": "wan0", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static", "ssh": True} iface = {"dns_servers": [{"ipv4Address": "10.1.0.20", "addressType": "ipv4"}, {"ipv4Address": "10.1.0.50", "addressType": "ipv4"}], "subnet_mask": "255.255.255.0", "link_status": "up", "ntp_servers": None, "ntp_config_method": "disabled", "controllerRef": "070000000000000000000001", "config_method": "configStatic", "enabled": True, "gateway": "10.1.1.1", "alias": "creG1g-AP-a", "controllerSlot": 1, "dns_config_method": "stat", "id": "2800070000000000000000000001000000000000", "address": "10.1.1.111", "ipv6Enabled": False, "channel": 1} settings = {"controllerRef": "070000000000000000000001", "ssh": False} self._set_args(initial) mgmt_interface = MgmtInterface() with mock.patch(self.REQ_FUNC, return_value=(200, None)): update = mgmt_interface.update_array(settings, iface) self.assertTrue(update) def test_update_array_dns_static_ntp_disable_pass(self): """Verify get_interface_settings gives the right static configuration response.""" initial = { "controller": "A", "name": "wan0", "dns_config_method": "static", "dns_address": "192.168.1.1", "dns_address_backup": "192.168.1.100", "ntp_config_method": "disable"} iface = {"dns_servers": [{"ipv4Address": "10.1.0.20", "addressType": "ipv4"}, {"ipv4Address": "10.1.0.50", "addressType": "ipv4"}], "subnet_mask": "255.255.255.0", "link_status": "up", "ntp_servers": None, "ntp_config_method": "disabled", "controllerRef": "070000000000000000000001", "config_method": "configStatic", "enabled": True, "gateway": "10.1.1.1", "alias": "creG1g-AP-a", "controllerSlot": 1, "dns_config_method": "configDhcp", "id": "2800070000000000000000000001000000000000", "address": "10.1.1.111", "ipv6Enabled": False, "channel": 1} settings = {"controllerRef": "070000000000000000000001", "ssh": False} self._set_args(initial) mgmt_interface = MgmtInterface() with mock.patch(self.REQ_FUNC, return_value=(200, None)): update = mgmt_interface.update_array(settings, iface) self.assertTrue(update) def test_update_array_dns_dhcp_ntp_static_pass(self): """Verify get_interface_settings gives the right static configuration response.""" initial = { "controller": "A", "name": "wan0", "ntp_config_method": "static", "ntp_address": "192.168.1.1", "ntp_address_backup": "192.168.1.100", "dns_config_method": "dhcp"} iface = {"dns_servers": [{"ipv4Address": "10.1.0.20", "addressType": "ipv4"}, {"ipv4Address": "10.1.0.50", "addressType": "ipv4"}], "subnet_mask": "255.255.255.0", "link_status": "up", "ntp_servers": None, "ntp_config_method": "disabled", "controllerRef": "070000000000000000000001", "config_method": "configStatic", "enabled": True, "gateway": "10.1.1.1", "alias": "creG1g-AP-a", "controllerSlot": 1, "dns_config_method": "configStatic", "id": "2800070000000000000000000001000000000000", "address": "10.1.1.111", "ipv6Enabled": False, "channel": 1} settings = {"controllerRef": "070000000000000000000001", "ssh": False} self._set_args(initial) mgmt_interface = MgmtInterface() with mock.patch(self.REQ_FUNC, return_value=(200, None)): update = mgmt_interface.update_array(settings, iface) self.assertTrue(update) def test_update_array_dns_dhcp_ntp_static_no_change_pass(self): """Verify get_interface_settings gives the right static configuration response.""" initial = { "controller": "A", "name": "wan0", "ntp_config_method": "dhcp", "dns_config_method": "dhcp"} iface = {"dns_servers": [{"ipv4Address": "10.1.0.20", "addressType": "ipv4"}, {"ipv4Address": "10.1.0.50", "addressType": "ipv4"}], "subnet_mask": "255.255.255.0", "ntp_servers": None, "ntp_config_method": "dhcp", "controllerRef": "070000000000000000000001", "config_method": "static", "enabled": True, "gateway": "10.1.1.1", "alias": "creG1g-AP-a", "controllerSlot": 1, "dns_config_method": "dhcp", "id": "2800070000000000000000000001000000000000", "address": "10.1.1.11", "ipv6Enabled": False, "channel": 1} settings = {"controllerRef": "070000000000000000000001", "ssh": False} self._set_args(initial) mgmt_interface = MgmtInterface() with mock.patch(self.REQ_FUNC, return_value=(200, None)): update = mgmt_interface.update_array(settings, iface) self.assertFalse(update) def test_update_array_ipv4_ipv6_disabled_fail(self): """Verify exception is thrown when both ipv4 and ipv6 would be disabled at the same time.""" initial = { "state": "disable", "controller": "A", "name": "wan0", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static", "ssh": True} iface = {"dns_servers": [{"ipv4Address": "10.1.0.20", "addressType": "ipv4"}, {"ipv4Address": "10.1.0.50", "addressType": "ipv4"}], "subnet_mask": "255.255.255.0", "ntp_servers": None, "ntp_config_method": "disabled", "controllerRef": "070000000000000000000001", "config_method": "configStatic", "enabled": True, "gateway": "10.1.1.1", "alias": "creG1g-AP-a", "controllerSlot": 1, "dns_config_method": "stat", "id": "2800070000000000000000000001000000000000", "address": "10.1.1.11", "ipv6Enabled": False, "channel": 1} settings = {"controllerRef": "070000000000000000000001", "ssh": False} self._set_args(initial) mgmt_interface = MgmtInterface() with self.assertRaisesRegexp(AnsibleFailJson, r"This storage-system already has IPv6 connectivity disabled."): with mock.patch(self.REQ_FUNC, return_value=(422, dict(ipv4Enabled=False, retcode="4", errorMessage=""))): mgmt_interface.update_array(settings, iface) def test_update_array_request_error_fail(self): """Verify exception is thrown when request results in an error.""" initial = { "state": "disable", "controller": "A", "name": "wan0", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static", "ssh": True} iface = {"dns_servers": [{"ipv4Address": "10.1.0.20", "addressType": "ipv4"}, {"ipv4Address": "10.1.0.50", "addressType": "ipv4"}], "subnet_mask": "255.255.255.0", "ntp_servers": None, "ntp_config_method": "disabled", "controllerRef": "070000000000000000000001", "config_method": "configStatic", "enabled": True, "gateway": "10.1.1.1", "alias": "creG1g-AP-a", "controllerSlot": 1, "dns_config_method": "stat", "id": "2800070000000000000000000001000000000000", "address": "10.1.1.111", "ipv6Enabled": False, "channel": 1} settings = {"controllerRef": "070000000000000000000001", "ssh": False} self._set_args(initial) mgmt_interface = MgmtInterface() with self.assertRaisesRegexp(AnsibleFailJson, r"We failed to configure the management interface."): with mock.patch(self.REQ_FUNC, return_value=(300, dict(ipv4Enabled=False, retcode="4", errorMessage=""))): mgmt_interface.update_array(settings, iface) def test_update_pass(self): """Validate update method completes.""" initial = { "state": "enable", "controller": "A", "channel": "1", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static", "ssh": "yes"} controller_request = [ {"physicalLocation": {"slot": 2}, "controllerRef": "070000000000000000000002", "networkSettings": {"remoteAccessEnabled": True}}, {"physicalLocation": {"slot": 1}, "controllerRef": "070000000000000000000001", "networkSettings": {"remoteAccessEnabled": False}}] expected = { "dns_servers": [{"ipv4Address": "10.1.0.20", "addressType": "ipv4"}, {"ipv4Address": "10.1.0.50", "addressType": "ipv4"}], "subnet_mask": "255.255.255.0", "ntp_servers": None, "ntp_config_method": "disabled", "controllerRef": "070000000000000000000001", "config_method": "configStatic", "enabled": True, "gateway": "10.1.1.1", "alias": "creG1g-AP-a", "controllerSlot": 1, "dns_config_method": "stat", "id": "2800070000000000000000000001000000000000", "address": "10.1.1.111", "ipv6Enabled": False, "channel": 1} self._set_args(initial) mgmt_interface = MgmtInterface() with self.assertRaisesRegexp(AnsibleExitJson, r"The interface settings have been updated."): with mock.patch(self.REQ_FUNC, side_effect=[(200, None), (200, controller_request), (200, self.TEST_DATA), (200, controller_request), (200, self.TEST_DATA)]): mgmt_interface.update()
thaim/ansible
test/units/modules/storage/netapp/test_netapp_e_mgmt_interface.py
Python
mit
28,142
/********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // "liveMedia" // Copyright (c) 1996-2013 Live Networks, Inc. All rights reserved. // Qualcomm "PureVoice" (aka. "QCELP") Audio RTP Sources // Implementation #include "QCELPAudioRTPSource.hh" #include "MultiFramedRTPSource.hh" #include "FramedFilter.hh" #include <string.h> #include <stdlib.h> // This source is implemented internally by two separate sources: // (i) a RTP source for the raw (interleaved) QCELP frames, and // (ii) a deinterleaving filter that reads from this. // Define these two new classes here: class RawQCELPRTPSource: public MultiFramedRTPSource { public: static RawQCELPRTPSource* createNew(UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat, unsigned rtpTimestampFrequency); unsigned char interleaveL() const { return fInterleaveL; } unsigned char interleaveN() const { return fInterleaveN; } unsigned char& frameIndex() { return fFrameIndex; } // index within pkt private: RawQCELPRTPSource(UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat, unsigned rtpTimestampFrequency); // called only by createNew() virtual ~RawQCELPRTPSource(); private: // redefined virtual functions: virtual Boolean processSpecialHeader(BufferedPacket* packet, unsigned& resultSpecialHeaderSize); virtual char const* MIMEtype() const; virtual Boolean hasBeenSynchronizedUsingRTCP(); private: unsigned char fInterleaveL, fInterleaveN, fFrameIndex; unsigned fNumSuccessiveSyncedPackets; }; class QCELPDeinterleaver: public FramedFilter { public: static QCELPDeinterleaver* createNew(UsageEnvironment& env, RawQCELPRTPSource* inputSource); private: QCELPDeinterleaver(UsageEnvironment& env, RawQCELPRTPSource* inputSource); // called only by "createNew()" virtual ~QCELPDeinterleaver(); static void afterGettingFrame(void* clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds); void afterGettingFrame1(unsigned frameSize, struct timeval presentationTime); private: // Redefined virtual functions: void doGetNextFrame(); virtual void doStopGettingFrames(); private: class QCELPDeinterleavingBuffer* fDeinterleavingBuffer; Boolean fNeedAFrame; }; ////////// QCELPAudioRTPSource implementation ////////// FramedSource* QCELPAudioRTPSource::createNew(UsageEnvironment& env, Groupsock* RTPgs, RTPSource*& resultRTPSource, unsigned char rtpPayloadFormat, unsigned rtpTimestampFrequency) { RawQCELPRTPSource* rawRTPSource; resultRTPSource = rawRTPSource = RawQCELPRTPSource::createNew(env, RTPgs, rtpPayloadFormat, rtpTimestampFrequency); if (resultRTPSource == NULL) return NULL; QCELPDeinterleaver* deinterleaver = QCELPDeinterleaver::createNew(env, rawRTPSource); if (deinterleaver == NULL) { Medium::close(resultRTPSource); resultRTPSource = NULL; } return deinterleaver; } ////////// QCELPBufferedPacket and QCELPBufferedPacketFactory ////////// // A subclass of BufferedPacket, used to separate out QCELP frames. class QCELPBufferedPacket: public BufferedPacket { public: QCELPBufferedPacket(RawQCELPRTPSource& ourSource); virtual ~QCELPBufferedPacket(); private: // redefined virtual functions virtual unsigned nextEnclosedFrameSize(unsigned char*& framePtr, unsigned dataSize); private: RawQCELPRTPSource& fOurSource; }; class QCELPBufferedPacketFactory: public BufferedPacketFactory { private: // redefined virtual functions virtual BufferedPacket* createNewPacket(MultiFramedRTPSource* ourSource); }; ///////// RawQCELPRTPSource implementation //////// RawQCELPRTPSource* RawQCELPRTPSource::createNew(UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat, unsigned rtpTimestampFrequency) { return new RawQCELPRTPSource(env, RTPgs, rtpPayloadFormat, rtpTimestampFrequency); } RawQCELPRTPSource::RawQCELPRTPSource(UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat, unsigned rtpTimestampFrequency) : MultiFramedRTPSource(env, RTPgs, rtpPayloadFormat, rtpTimestampFrequency, new QCELPBufferedPacketFactory), fInterleaveL(0), fInterleaveN(0), fFrameIndex(0), fNumSuccessiveSyncedPackets(0) { } RawQCELPRTPSource::~RawQCELPRTPSource() { } Boolean RawQCELPRTPSource ::processSpecialHeader(BufferedPacket* packet, unsigned& resultSpecialHeaderSize) { unsigned char* headerStart = packet->data(); unsigned packetSize = packet->dataSize(); // First, check whether this packet's RTP timestamp is synchronized: if (RTPSource::hasBeenSynchronizedUsingRTCP()) { ++fNumSuccessiveSyncedPackets; } else { fNumSuccessiveSyncedPackets = 0; } // There's a 1-byte header indicating the interleave parameters if (packetSize < 1) return False; // Get the interleaving parameters from the 1-byte header, // and check them for validity: unsigned char const firstByte = headerStart[0]; unsigned char const interleaveL = (firstByte&0x38)>>3; unsigned char const interleaveN = firstByte&0x07; #ifdef DEBUG fprintf(stderr, "packetSize: %d, interleaveL: %d, interleaveN: %d\n", packetSize, interleaveL, interleaveN); #endif if (interleaveL > 5 || interleaveN > interleaveL) return False; //invalid fInterleaveL = interleaveL; fInterleaveN = interleaveN; fFrameIndex = 0; // initially resultSpecialHeaderSize = 1; return True; } char const* RawQCELPRTPSource::MIMEtype() const { return "audio/QCELP"; } Boolean RawQCELPRTPSource::hasBeenSynchronizedUsingRTCP() { // Don't report ourselves as being synchronized until we've received // at least a complete interleave cycle of synchronized packets. // This ensures that the receiver is currently getting a frame from // a packet that was synchronized. if (fNumSuccessiveSyncedPackets > (unsigned)(fInterleaveL+1)) { fNumSuccessiveSyncedPackets = fInterleaveL+2; // prevents overflow return True; } return False; } ///// QCELPBufferedPacket and QCELPBufferedPacketFactory implementation QCELPBufferedPacket::QCELPBufferedPacket(RawQCELPRTPSource& ourSource) : fOurSource(ourSource) { } QCELPBufferedPacket::~QCELPBufferedPacket() { } unsigned QCELPBufferedPacket:: nextEnclosedFrameSize(unsigned char*& framePtr, unsigned dataSize) { // The size of the QCELP frame is determined by the first byte: if (dataSize == 0) return 0; // sanity check unsigned char const firstByte = framePtr[0]; unsigned frameSize; switch (firstByte) { case 0: { frameSize = 1; break; } case 1: { frameSize = 4; break; } case 2: { frameSize = 8; break; } case 3: { frameSize = 17; break; } case 4: { frameSize = 35; break; } default: { frameSize = 0; break; } } #ifdef DEBUG fprintf(stderr, "QCELPBufferedPacket::nextEnclosedFrameSize(): frameSize: %d, dataSize: %d\n", frameSize, dataSize); #endif if (dataSize < frameSize) return 0; ++fOurSource.frameIndex(); return frameSize; } BufferedPacket* QCELPBufferedPacketFactory ::createNewPacket(MultiFramedRTPSource* ourSource) { return new QCELPBufferedPacket((RawQCELPRTPSource&)(*ourSource)); } ///////// QCELPDeinterleavingBuffer ///////// // (used to implement QCELPDeinterleaver) #define QCELP_MAX_FRAME_SIZE 35 #define QCELP_MAX_INTERLEAVE_L 5 #define QCELP_MAX_FRAMES_PER_PACKET 10 #define QCELP_MAX_INTERLEAVE_GROUP_SIZE \ ((QCELP_MAX_INTERLEAVE_L+1)*QCELP_MAX_FRAMES_PER_PACKET) class QCELPDeinterleavingBuffer { public: QCELPDeinterleavingBuffer(); virtual ~QCELPDeinterleavingBuffer(); void deliverIncomingFrame(unsigned frameSize, unsigned char interleaveL, unsigned char interleaveN, unsigned char frameIndex, unsigned short packetSeqNum, struct timeval presentationTime); Boolean retrieveFrame(unsigned char* to, unsigned maxSize, unsigned& resultFrameSize, unsigned& resultNumTruncatedBytes, struct timeval& resultPresentationTime); unsigned char* inputBuffer() { return fInputBuffer; } unsigned inputBufferSize() const { return QCELP_MAX_FRAME_SIZE; } private: class FrameDescriptor { public: FrameDescriptor(); virtual ~FrameDescriptor(); unsigned frameSize; unsigned char* frameData; struct timeval presentationTime; }; // Use two banks of descriptors - one for incoming, one for outgoing FrameDescriptor fFrames[QCELP_MAX_INTERLEAVE_GROUP_SIZE][2]; unsigned char fIncomingBankId; // toggles between 0 and 1 unsigned char fIncomingBinMax; // in the incoming bank unsigned char fOutgoingBinMax; // in the outgoing bank unsigned char fNextOutgoingBin; Boolean fHaveSeenPackets; u_int16_t fLastPacketSeqNumForGroup; unsigned char* fInputBuffer; struct timeval fLastRetrievedPresentationTime; }; ////////// QCELPDeinterleaver implementation ///////// QCELPDeinterleaver* QCELPDeinterleaver::createNew(UsageEnvironment& env, RawQCELPRTPSource* inputSource) { return new QCELPDeinterleaver(env, inputSource); } QCELPDeinterleaver::QCELPDeinterleaver(UsageEnvironment& env, RawQCELPRTPSource* inputSource) : FramedFilter(env, inputSource), fNeedAFrame(False) { fDeinterleavingBuffer = new QCELPDeinterleavingBuffer(); } QCELPDeinterleaver::~QCELPDeinterleaver() { delete fDeinterleavingBuffer; } static unsigned const uSecsPerFrame = 20000; // 20 ms void QCELPDeinterleaver::doGetNextFrame() { // First, try getting a frame from the deinterleaving buffer: if (fDeinterleavingBuffer->retrieveFrame(fTo, fMaxSize, fFrameSize, fNumTruncatedBytes, fPresentationTime)) { // Success! fNeedAFrame = False; fDurationInMicroseconds = uSecsPerFrame; // Call our own 'after getting' function. Because we're not a 'leaf' // source, we can call this directly, without risking // infinite recursion afterGetting(this); return; } // No luck, so ask our source for help: fNeedAFrame = True; if (!fInputSource->isCurrentlyAwaitingData()) { fInputSource->getNextFrame(fDeinterleavingBuffer->inputBuffer(), fDeinterleavingBuffer->inputBufferSize(), afterGettingFrame, this, FramedSource::handleClosure, this); } } void QCELPDeinterleaver::doStopGettingFrames() { fNeedAFrame = False; fInputSource->stopGettingFrames(); } void QCELPDeinterleaver ::afterGettingFrame(void* clientData, unsigned frameSize, unsigned /*numTruncatedBytes*/, struct timeval presentationTime, unsigned /*durationInMicroseconds*/) { QCELPDeinterleaver* deinterleaver = (QCELPDeinterleaver*)clientData; deinterleaver->afterGettingFrame1(frameSize, presentationTime); } void QCELPDeinterleaver ::afterGettingFrame1(unsigned frameSize, struct timeval presentationTime) { RawQCELPRTPSource* source = (RawQCELPRTPSource*)fInputSource; // First, put the frame into our deinterleaving buffer: fDeinterleavingBuffer ->deliverIncomingFrame(frameSize, source->interleaveL(), source->interleaveN(), source->frameIndex(), source->curPacketRTPSeqNum(), presentationTime); // Then, try delivering a frame to the client (if he wants one): if (fNeedAFrame) doGetNextFrame(); } ////////// QCELPDeinterleavingBuffer implementation ///////// QCELPDeinterleavingBuffer::QCELPDeinterleavingBuffer() : fIncomingBankId(0), fIncomingBinMax(0), fOutgoingBinMax(0), fNextOutgoingBin(0), fHaveSeenPackets(False) { fInputBuffer = new unsigned char[QCELP_MAX_FRAME_SIZE]; } QCELPDeinterleavingBuffer::~QCELPDeinterleavingBuffer() { delete[] fInputBuffer; } void QCELPDeinterleavingBuffer ::deliverIncomingFrame(unsigned frameSize, unsigned char interleaveL, unsigned char interleaveN, unsigned char frameIndex, unsigned short packetSeqNum, struct timeval presentationTime) { // First perform a sanity check on the parameters: // (This is overkill, as the source should have already done this.) if (frameSize > QCELP_MAX_FRAME_SIZE || interleaveL > QCELP_MAX_INTERLEAVE_L || interleaveN > interleaveL || frameIndex == 0 || frameIndex > QCELP_MAX_FRAMES_PER_PACKET) { #ifdef DEBUG fprintf(stderr, "QCELPDeinterleavingBuffer::deliverIncomingFrame() param sanity check failed (%d,%d,%d,%d)\n", frameSize, interleaveL, interleaveN, frameIndex); #endif return; } // The input "presentationTime" was that of the first frame in this // packet. Update it for the current frame: unsigned uSecIncrement = (frameIndex-1)*(interleaveL+1)*uSecsPerFrame; presentationTime.tv_usec += uSecIncrement; presentationTime.tv_sec += presentationTime.tv_usec/1000000; presentationTime.tv_usec = presentationTime.tv_usec%1000000; // Next, check whether this packet is part of a new interleave group if (!fHaveSeenPackets || seqNumLT(fLastPacketSeqNumForGroup, packetSeqNum)) { // We've moved to a new interleave group fHaveSeenPackets = True; fLastPacketSeqNumForGroup = packetSeqNum + interleaveL - interleaveN; // Switch the incoming and outgoing banks: fIncomingBankId ^= 1; unsigned char tmp = fIncomingBinMax; fIncomingBinMax = fOutgoingBinMax; fOutgoingBinMax = tmp; fNextOutgoingBin = 0; } // Now move the incoming frame into the appropriate bin: unsigned const binNumber = interleaveN + (frameIndex-1)*(interleaveL+1); FrameDescriptor& inBin = fFrames[binNumber][fIncomingBankId]; unsigned char* curBuffer = inBin.frameData; inBin.frameData = fInputBuffer; inBin.frameSize = frameSize; inBin.presentationTime = presentationTime; if (curBuffer == NULL) curBuffer = new unsigned char[QCELP_MAX_FRAME_SIZE]; fInputBuffer = curBuffer; if (binNumber >= fIncomingBinMax) { fIncomingBinMax = binNumber + 1; } } Boolean QCELPDeinterleavingBuffer ::retrieveFrame(unsigned char* to, unsigned maxSize, unsigned& resultFrameSize, unsigned& resultNumTruncatedBytes, struct timeval& resultPresentationTime) { if (fNextOutgoingBin >= fOutgoingBinMax) return False; // none left FrameDescriptor& outBin = fFrames[fNextOutgoingBin][fIncomingBankId^1]; unsigned char* fromPtr; unsigned char fromSize = outBin.frameSize; outBin.frameSize = 0; // for the next time this bin is used // Check whether this frame is missing; if so, return an 'erasure' frame: unsigned char erasure = 14; if (fromSize == 0) { fromPtr = &erasure; fromSize = 1; // Compute this erasure frame's presentation time via extrapolation: resultPresentationTime = fLastRetrievedPresentationTime; resultPresentationTime.tv_usec += uSecsPerFrame; if (resultPresentationTime.tv_usec >= 1000000) { ++resultPresentationTime.tv_sec; resultPresentationTime.tv_usec -= 1000000; } } else { // Normal case - a frame exists: fromPtr = outBin.frameData; resultPresentationTime = outBin.presentationTime; } fLastRetrievedPresentationTime = resultPresentationTime; if (fromSize > maxSize) { resultNumTruncatedBytes = fromSize - maxSize; resultFrameSize = maxSize; } else { resultNumTruncatedBytes = 0; resultFrameSize = fromSize; } memmove(to, fromPtr, resultFrameSize); ++fNextOutgoingBin; return True; } QCELPDeinterleavingBuffer::FrameDescriptor::FrameDescriptor() : frameSize(0), frameData(NULL) { } QCELPDeinterleavingBuffer::FrameDescriptor::~FrameDescriptor() { delete[] frameData; }
DDTChen/CookieVLC
vlc/contrib/android/live555/liveMedia/QCELPAudioRTPSource.cpp
C++
gpl-2.0
16,387
<?php /** * Shopware 5 * Copyright (c) shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. */ // Check the minimum required php version if (version_compare(PHP_VERSION, '5.4.0', '<')) { header('Content-type: text/html; charset=utf-8', true, 503); echo '<h2>Error</h2>'; echo 'Your server is running PHP version ' . PHP_VERSION . ' but Shopware 5 requires at least PHP 5.4.0'; echo '<h2>Fehler</h2>'; echo 'Auf Ihrem Server läuft PHP version ' . PHP_VERSION . ', Shopware 5 benötigt mindestens PHP 5.4.0'; return; } // Check for active auto update or manual update if (is_file('files/update/update.json') || is_dir('update-assets')) { header('Content-type: text/html; charset=utf-8', true, 503); header('Status: 503 Service Temporarily Unavailable'); header('Retry-After: 1200'); echo file_get_contents(__DIR__ . '/recovery/update/maintenance.html'); return; } // Check for installation if (is_dir('recovery/install') && !is_file('recovery/install/data/install.lock')) { if (PHP_SAPI == 'cli') { echo 'Shopware 5 must be configured before use. Please run the Shopware installer by executing \'php recovery/install/index.php\'.'.PHP_EOL; } else { $basePath = 'recovery/install'; $baseURL = str_replace(basename(__FILE__), '', $_SERVER['SCRIPT_NAME']); $baseURL = rtrim($baseURL, '/'); $installerURL = $baseURL.'/'.$basePath; if (strpos($_SERVER['REQUEST_URI'], $basePath) === false) { header('Location: '.$installerURL); exit; } header('Content-type: text/html; charset=utf-8', true, 503); echo '<h2>Error</h2>'; echo 'Shopware 5 must be configured before use. Please run the <a href="recovery/install/?language=en">installer</a>.'; echo '<h2>Fehler</h2>'; echo 'Shopware 5 muss zunächst konfiguriert werden. Bitte führen Sie den <a href="recovery/install/?language=de">Installer</a> aus.'; } exit; } // check for composer autoloader if (!file_exists('vendor/autoload.php')) { header('Content-type: text/html; charset=utf-8', true, 503); echo '<h2>Error</h2>'; echo 'Please execute "composer install" from the command line to install the required dependencies for Shopware 5'; echo '<h2>Fehler</h2>'; echo 'Bitte führen Sie zuerst "composer install" aus.'; return; } require __DIR__ . '/autoload.php'; use Shopware\Kernel; use Shopware\Components\HttpCache\AppCache; use Symfony\Component\HttpFoundation\Request; $environment = getenv('SHOPWARE_ENV') ?: getenv('REDIRECT_SHOPWARE_ENV') ?: 'production'; $kernel = new Kernel($environment, $environment !== 'production'); if ($kernel->isHttpCacheEnabled()) { $kernel = new AppCache($kernel, $kernel->getHttpCacheConfig()); } $request = Request::createFromGlobals(); $kernel->handle($request) ->send();
ShopwareHackathon/shopware_search_optimization
shopware.php
PHP
agpl-3.0
3,731
// ---------------------------------------------------------------------------------- // // Copyright 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. // ---------------------------------------------------------------------------------- using System.Collections.Generic; using System.Management.Automation; using Microsoft.WindowsAzure.Commands.Common; using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.WindowsAzure.Commands.Common.Test.Mocks; using Microsoft.WindowsAzure.Commands.Profile; using Microsoft.WindowsAzure.Commands.Profile.Models; using Microsoft.WindowsAzure.Commands.Test.Utilities.Common; using Microsoft.WindowsAzure.Commands.Utilities.Common; using Moq; using Microsoft.WindowsAzure.Commands.ScenarioTest; using Xunit; using Microsoft.Azure.Commands.Common.Authentication; namespace Microsoft.WindowsAzure.Commands.Test.Environment { public class GetAzureEnvironmentTests : SMTestBase { private MemoryDataStore dataStore; public GetAzureEnvironmentTests() { dataStore = new MemoryDataStore(); AzureSession.DataStore = dataStore; } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void GetsAzureEnvironments() { List<PSAzureEnvironment> environments = null; Mock<ICommandRuntime> commandRuntimeMock = new Mock<ICommandRuntime>(); commandRuntimeMock.Setup(c => c.WriteObject(It.IsAny<object>(), It.IsAny<bool>())) .Callback<object, bool>((e, _) => environments = (List<PSAzureEnvironment>)e); GetAzureEnvironmentCommand cmdlet = new GetAzureEnvironmentCommand() { CommandRuntime = commandRuntimeMock.Object }; AzureSMCmdlet.CurrentProfile = new AzureSMProfile(); cmdlet.InvokeBeginProcessing(); cmdlet.ExecuteCmdlet(); cmdlet.InvokeEndProcessing(); Assert.Equal(4, environments.Count); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void GetsAzureEnvironment() { List<PSAzureEnvironment> environments = null; Mock<ICommandRuntime> commandRuntimeMock = new Mock<ICommandRuntime>(); commandRuntimeMock.Setup(c => c.WriteObject(It.IsAny<object>(), It.IsAny<bool>())) .Callback<object, bool>((e, _) => environments = (List<PSAzureEnvironment>)e); GetAzureEnvironmentCommand cmdlet = new GetAzureEnvironmentCommand() { CommandRuntime = commandRuntimeMock.Object, Name = EnvironmentName.AzureChinaCloud }; AzureSMCmdlet.CurrentProfile = new AzureSMProfile(); cmdlet.InvokeBeginProcessing(); cmdlet.ExecuteCmdlet(); cmdlet.InvokeEndProcessing(); Assert.Equal(1, environments.Count); } } }
zhencui/azure-powershell
src/ServiceManagement/Services/Commands.Test/Environment/GetAzureEnvironmentTests.cs
C#
apache-2.0
3,485
/* * 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.ignite.console.demo; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.log4j.Logger; import org.h2.tools.RunScript; import org.h2.tools.Server; import static org.apache.ignite.console.agent.AgentUtils.resolvePath; /** * Demo for metadata load from database. * * H2 database will be started and several tables will be created. */ public class AgentMetadataDemo { /** */ private static final Logger log = Logger.getLogger(AgentMetadataDemo.class.getName()); /** */ private static final AtomicBoolean initLatch = new AtomicBoolean(); /** * @param jdbcUrl Connection url. * @return true if url is used for test-drive. */ public static boolean isTestDriveUrl(String jdbcUrl) { return "jdbc:h2:mem:demo-db".equals(jdbcUrl); } /** * Start H2 database and populate it with several tables. */ public static Connection testDrive() throws SQLException { if (initLatch.compareAndSet(false, true)) { log.info("DEMO: Prepare in-memory H2 database..."); try { Class.forName("org.h2.Driver"); Connection conn = DriverManager.getConnection("jdbc:h2:mem:demo-db;DB_CLOSE_DELAY=-1", "sa", ""); File sqlScript = resolvePath("demo/db-init.sql"); //noinspection ConstantConditions RunScript.execute(conn, new FileReader(sqlScript)); log.info("DEMO: Sample tables created."); conn.close(); Server.createTcpServer("-tcpDaemon").start(); log.info("DEMO: TcpServer stared."); log.info("DEMO: JDBC URL for test drive metadata load: jdbc:h2:mem:demo-db"); } catch (ClassNotFoundException e) { log.error("DEMO: Failed to load H2 driver!", e); throw new SQLException("Failed to load H2 driver", e); } catch (SQLException e) { log.error("DEMO: Failed to start test drive for metadata!", e); throw e; } catch (FileNotFoundException | NullPointerException e) { log.error("DEMO: Failed to find demo database init script file: demo/db-init.sql"); throw new SQLException("Failed to start demo for metadata", e); } } return DriverManager.getConnection("jdbc:h2:mem:demo-db;DB_CLOSE_DELAY=-1", "sa", ""); } }
irudyak/ignite
modules/web-console/web-agent/src/main/java/org/apache/ignite/console/demo/AgentMetadataDemo.java
Java
apache-2.0
3,471
package org.apache.lucene.search.similarities; /* * 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. */ import java.util.Locale; import org.apache.lucene.search.Explanation; /** * Bayesian smoothing using Dirichlet priors. From Chengxiang Zhai and John * Lafferty. 2001. A study of smoothing methods for language models applied to * Ad Hoc information retrieval. In Proceedings of the 24th annual international * ACM SIGIR conference on Research and development in information retrieval * (SIGIR '01). ACM, New York, NY, USA, 334-342. * <p> * The formula as defined the paper assigns a negative score to documents that * contain the term, but with fewer occurrences than predicted by the collection * language model. The Lucene implementation returns {@code 0} for such * documents. * </p> * * @lucene.experimental */ public class LMDirichletSimilarity extends LMSimilarity { /** The &mu; parameter. */ private final float mu; /** Instantiates the similarity with the provided &mu; parameter. */ public LMDirichletSimilarity(CollectionModel collectionModel, float mu) { super(collectionModel); this.mu = mu; } /** Instantiates the similarity with the provided &mu; parameter. */ public LMDirichletSimilarity(float mu) { this.mu = mu; } /** Instantiates the similarity with the default &mu; value of 2000. */ public LMDirichletSimilarity(CollectionModel collectionModel) { this(collectionModel, 2000); } /** Instantiates the similarity with the default &mu; value of 2000. */ public LMDirichletSimilarity() { this(2000); } @Override protected float score(BasicStats stats, float freq, float docLen) { float score = stats.getTotalBoost() * (float)(Math.log(1 + freq / (mu * ((LMStats)stats).getCollectionProbability())) + Math.log(mu / (docLen + mu))); return score > 0.0f ? score : 0.0f; } @Override protected void explain(Explanation expl, BasicStats stats, int doc, float freq, float docLen) { if (stats.getTotalBoost() != 1.0f) { expl.addDetail(new Explanation(stats.getTotalBoost(), "boost")); } expl.addDetail(new Explanation(mu, "mu")); Explanation weightExpl = new Explanation(); weightExpl.setValue((float)Math.log(1 + freq / (mu * ((LMStats)stats).getCollectionProbability()))); weightExpl.setDescription("term weight"); expl.addDetail(weightExpl); expl.addDetail(new Explanation( (float)Math.log(mu / (docLen + mu)), "document norm")); super.explain(expl, stats, doc, freq, docLen); } /** Returns the &mu; parameter. */ public float getMu() { return mu; } @Override public String getName() { return String.format(Locale.ROOT, "Dirichlet(%f)", getMu()); } }
smartan/lucene
src/main/java/org/apache/lucene/search/similarities/LMDirichletSimilarity.java
Java
apache-2.0
3,519
import { ThisSideUp32 } from "../../"; export = ThisSideUp32;
markogresak/DefinitelyTyped
types/carbon__icons-react/lib/this-side-up/32.d.ts
TypeScript
mit
63
// Type definitions for the Facebook Javascript SDK // Project: https://developers.facebook.com/docs/javascript // Definitions by: Amrit Kahlon <https://github.com/amritk/> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import fb = facebook; declare var FB: fb.FacebookStatic; declare namespace facebook { interface FacebookStatic { api: any; AppEvents: any; Canvas: any; Event: any; /** * The method FB.getAuthResponse() is a synchronous accessor for the current authResponse. * The synchronous nature of this method is what sets it apart from the other login methods. * * @param callback function to handle the response. */ getAuthResponse(callback: (response: AuthResponse) => void): void; /** * FB.getLoginStatus() allows you to determine if a user is * logged in to Facebook and has authenticated your app. * * @param callback function to handle the response. */ getLoginStatus(callback: (response: AuthResponse) => void, roundtrip?: boolean ): void; /** * The method FB.init() is used to initialize and setup the SDK. * * @param params params for the initialization. */ init(params: InitParams): void; /** * Use this function to log the user in * * Calling FB.login() results in the JS SDK attempting to open a popup window. * As such, this method should only be called after a user click event, otherwise * the popup window will be blocked by most browsers. * * @param callback function to handle the response. * @param options optional ILoginOption to add params such as scope. */ login(callback: (response: AuthResponse) => void, options?: LoginOptions): void; /** * The method FB.logout() logs the user out of your site and, in some cases, Facebook. * * @param callback function to handle the response */ logout(callback: (response: AuthResponse) => void): void; ui: any; XFBML: any; } interface InitParams { appId: string; version?: string; cookie?: boolean; status?: boolean; xfbml?: boolean; frictionlessRequests?: boolean; hideFlashCallback?: boolean; } interface LoginOptions { auth_type?: string; scope?: string; return_scopes?: boolean; enable_profile_selector?: boolean; profile_selector_ids?: string; } //////////////////////// // // RESPONSES // //////////////////////// interface AuthResponse { status: string; authResponse: { accessToken: string; expiresIn: number; signedRequest: string; userID: string; } } }
subash-a/DefinitelyTyped
facebook-js-sdk/index.d.ts
TypeScript
mit
2,970
var assert = require('assert'); var R = require('..'); describe('add', function() { it('adds together two numbers', function() { assert.strictEqual(R.add(3, 7), 10); }); it('is curried', function() { var incr = R.add(1); assert.strictEqual(incr(42), 43); }); });
kairyan/ramda
test/add.js
JavaScript
mit
287
import { SendToBack32 } from "../../"; export = SendToBack32;
markogresak/DefinitelyTyped
types/carbon__icons-react/lib/send-to-back/32.d.ts
TypeScript
mit
63
<?php namespace CommerceGuys\Intl\Language; use CommerceGuys\Intl\LocaleResolverTrait; use CommerceGuys\Intl\Exception\UnknownLanguageException; /** * Manages languages based on JSON definitions. */ class LanguageRepository implements LanguageRepositoryInterface { use LocaleResolverTrait; /** * Per-locale language definitions. * * @var array */ protected $definitions = array(); /** * Creates a LanguageRepository instance. * * @param string $definitionPath The path to the currency definitions. * Defaults to 'resources/language'. */ public function __construct($definitionPath = null) { $this->definitionPath = $definitionPath ? $definitionPath : __DIR__ . '/../../resources/language/'; } /** * {@inheritdoc} */ public function get($languageCode, $locale = null, $fallbackLocale = null) { $locale = $this->resolveLocale($locale, $fallbackLocale); $definitions = $this->loadDefinitions($locale); if (!isset($definitions[$languageCode])) { throw new UnknownLanguageException($languageCode); } return $this->createLanguageFromDefinition($definitions[$languageCode], $locale); } /** * {@inheritdoc} */ public function getAll($locale = null, $fallbackLocale = null) { $locale = $this->resolveLocale($locale, $fallbackLocale); $definitions = $this->loadDefinitions($locale); $languages = array(); foreach ($definitions as $languageCode => $definition) { $languages[$languageCode] = $this->createLanguageFromDefinition($definition, $locale); } return $languages; } /** * Loads the language definitions for the provided locale. * * @param string $locale The desired locale. * * @return array */ protected function loadDefinitions($locale) { if (!isset($this->definitions[$locale])) { $filename = $this->definitionPath . $locale . '.json'; $this->definitions[$locale] = json_decode(file_get_contents($filename), true); } return $this->definitions[$locale]; } /** * Creates a language object from the provided definition. * * @param array $definition The language definition. * @param string $locale The locale of the language definition. * * @return Language */ protected function createLanguageFromDefinition(array $definition, $locale) { $language = new Language(); $language->setLanguageCode($definition['code']); $language->setName($definition['name']); $language->setLocale($locale); return $language; } }
bashrc/hubzilla-debian
src/library/intl/src/Language/LanguageRepository.php
PHP
mit
2,786
import { WindGusts24 } from "../../"; export = WindGusts24;
markogresak/DefinitelyTyped
types/carbon__icons-react/lib/wind-gusts/24.d.ts
TypeScript
mit
61
/** * Copyright (c) 2010-2016, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.homematic.internal.model.adapter; import javax.xml.bind.annotation.adapters.XmlAdapter; import org.apache.commons.lang.StringUtils; /** * JAXB Adapter to trim a string value to null. * * @author Gerhard Riegler * @since 1.5.0 */ public class TrimToNullStringAdapter extends XmlAdapter<String, Object> { /** * {@inheritDoc} */ @Override public Object unmarshal(String value) throws Exception { return StringUtils.trimToNull(value); } /** * {@inheritDoc} */ @Override public String marshal(Object value) throws Exception { if (value == null) { return null; } return value.toString(); } }
evansj/openhab
bundles/binding/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/model/adapter/TrimToNullStringAdapter.java
Java
epl-1.0
1,031
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2015 - ROLI Ltd. Permission is granted to use this software under the terms of either: a) the GPL v2 (or any later version) b) the Affero GPL v3 Details of these licenses can be found at: www.gnu.org/licenses JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ namespace ComponentBuilderHelpers { static String getStateId (const ValueTree& state) { return state [ComponentBuilder::idProperty].toString(); } static Component* removeComponentWithID (OwnedArray<Component>& components, const String& compId) { jassert (compId.isNotEmpty()); for (int i = components.size(); --i >= 0;) { Component* const c = components.getUnchecked (i); if (c->getComponentID() == compId) return components.removeAndReturn (i); } return nullptr; } static Component* findComponentWithID (Component& c, const String& compId) { jassert (compId.isNotEmpty()); if (c.getComponentID() == compId) return &c; for (int i = c.getNumChildComponents(); --i >= 0;) if (Component* const child = findComponentWithID (*c.getChildComponent (i), compId)) return child; return nullptr; } static Component* createNewComponent (ComponentBuilder::TypeHandler& type, const ValueTree& state, Component* parent) { Component* const c = type.addNewComponentFromState (state, parent); jassert (c != nullptr && c->getParentComponent() == parent); c->setComponentID (getStateId (state)); return c; } static void updateComponent (ComponentBuilder& builder, const ValueTree& state) { if (Component* topLevelComp = builder.getManagedComponent()) { ComponentBuilder::TypeHandler* const type = builder.getHandlerForState (state); const String uid (getStateId (state)); if (type == nullptr || uid.isEmpty()) { // ..handle the case where a child of the actual state node has changed. if (state.getParent().isValid()) updateComponent (builder, state.getParent()); } else { if (Component* const changedComp = findComponentWithID (*topLevelComp, uid)) type->updateComponentFromState (changedComp, state); } } } } //============================================================================== const Identifier ComponentBuilder::idProperty ("id"); ComponentBuilder::ComponentBuilder() : imageProvider (nullptr) { } ComponentBuilder::ComponentBuilder (const ValueTree& state_) : state (state_), imageProvider (nullptr) { state.addListener (this); } ComponentBuilder::~ComponentBuilder() { state.removeListener (this); #if JUCE_DEBUG // Don't delete the managed component!! The builder owns that component, and will delete // it automatically when it gets deleted. jassert (componentRef.get() == static_cast<Component*> (component)); #endif } Component* ComponentBuilder::getManagedComponent() { if (component == nullptr) { component = createComponent(); #if JUCE_DEBUG componentRef = component; #endif } return component; } Component* ComponentBuilder::createComponent() { jassert (types.size() > 0); // You need to register all the necessary types before you can load a component! if (TypeHandler* const type = getHandlerForState (state)) return ComponentBuilderHelpers::createNewComponent (*type, state, nullptr); jassertfalse; // trying to create a component from an unknown type of ValueTree return nullptr; } void ComponentBuilder::registerTypeHandler (ComponentBuilder::TypeHandler* const type) { jassert (type != nullptr); // Don't try to move your types around! Once a type has been added to a builder, the // builder owns it, and you should leave it alone! jassert (type->builder == nullptr); types.add (type); type->builder = this; } ComponentBuilder::TypeHandler* ComponentBuilder::getHandlerForState (const ValueTree& s) const { const Identifier targetType (s.getType()); for (int i = 0; i < types.size(); ++i) { TypeHandler* const t = types.getUnchecked(i); if (t->type == targetType) return t; } return nullptr; } int ComponentBuilder::getNumHandlers() const noexcept { return types.size(); } ComponentBuilder::TypeHandler* ComponentBuilder::getHandler (const int index) const noexcept { return types [index]; } void ComponentBuilder::registerStandardComponentTypes() { Drawable::registerDrawableTypeHandlers (*this); } void ComponentBuilder::setImageProvider (ImageProvider* newImageProvider) noexcept { imageProvider = newImageProvider; } ComponentBuilder::ImageProvider* ComponentBuilder::getImageProvider() const noexcept { return imageProvider; } void ComponentBuilder::valueTreePropertyChanged (ValueTree& tree, const Identifier&) { ComponentBuilderHelpers::updateComponent (*this, tree); } void ComponentBuilder::valueTreeChildAdded (ValueTree& tree, ValueTree&) { ComponentBuilderHelpers::updateComponent (*this, tree); } void ComponentBuilder::valueTreeChildRemoved (ValueTree& tree, ValueTree&, int) { ComponentBuilderHelpers::updateComponent (*this, tree); } void ComponentBuilder::valueTreeChildOrderChanged (ValueTree& tree, int, int) { ComponentBuilderHelpers::updateComponent (*this, tree); } void ComponentBuilder::valueTreeParentChanged (ValueTree& tree) { ComponentBuilderHelpers::updateComponent (*this, tree); } //============================================================================== ComponentBuilder::TypeHandler::TypeHandler (const Identifier& valueTreeType) : type (valueTreeType), builder (nullptr) { } ComponentBuilder::TypeHandler::~TypeHandler() { } ComponentBuilder* ComponentBuilder::TypeHandler::getBuilder() const noexcept { // A type handler needs to be registered with a ComponentBuilder before using it! jassert (builder != nullptr); return builder; } void ComponentBuilder::updateChildComponents (Component& parent, const ValueTree& children) { using namespace ComponentBuilderHelpers; const int numExistingChildComps = parent.getNumChildComponents(); Array<Component*> componentsInOrder; componentsInOrder.ensureStorageAllocated (numExistingChildComps); { OwnedArray<Component> existingComponents; existingComponents.ensureStorageAllocated (numExistingChildComps); for (int i = 0; i < numExistingChildComps; ++i) existingComponents.add (parent.getChildComponent (i)); const int newNumChildren = children.getNumChildren(); for (int i = 0; i < newNumChildren; ++i) { const ValueTree childState (children.getChild (i)); Component* c = removeComponentWithID (existingComponents, getStateId (childState)); if (c == nullptr) { if (TypeHandler* const type = getHandlerForState (childState)) c = ComponentBuilderHelpers::createNewComponent (*type, childState, &parent); else jassertfalse; } if (c != nullptr) componentsInOrder.add (c); } // (remaining unused items in existingComponents get deleted here as it goes out of scope) } // Make sure the z-order is correct.. if (componentsInOrder.size() > 0) { componentsInOrder.getLast()->toFront (false); for (int i = componentsInOrder.size() - 1; --i >= 0;) componentsInOrder.getUnchecked(i)->toBehind (componentsInOrder.getUnchecked (i + 1)); } }
reuk/waveguide
wayverb/JuceLibraryCode/modules/juce_gui_basics/layout/juce_ComponentBuilder.cpp
C++
gpl-2.0
8,800
var URL = require("../url2"); var tests = [ { source: "", target: "", relative: "" }, { source: "foo/bar/", target: "foo/bar/", relative: "" }, { source: "foo/bar/baz", target: "foo/bar/", relative: "./" }, { source: "foo/bar/", target: "/foo/bar/", relative: "/foo/bar/" }, { source: "/foo/bar/baz", target: "/foo/bar/quux", relative: "quux" }, { source: "/foo/bar/baz", target: "/foo/bar/quux/asdf", relative: "quux/asdf" }, { source: "/foo/bar/baz", target: "/foo/bar/quux/baz", relative: "quux/baz" }, { source: "/foo/bar/baz", target: "/foo/quux/baz", relative: "../quux/baz" }, { source: "/foo/bar/baz", target: "/foo/quux/baz?a=10", relative: "../quux/baz?a=10" }, { source: "/foo/bar/baz?a=10", target: "/foo/quux/baz?a=10", relative: "../quux/baz?a=10" }, { source: "/foo/bar/baz?b=20", target: "/foo/quux/baz?a=10", relative: "../quux/baz?a=10" }, { source: "http://example.com", target: "/foo/bar", relative: "/foo/bar" }, { source: "", target: "http://example.com/foo/bar", relative: "http://example.com/foo/bar" }, { source: "", target: "#foo", relative: "#foo" }, { source: "", target: "?a=10", relative: "?a=10" }, { source: "?a=10", target: "#foo", relative: "?a=10#foo" }, { source: "file:///test.js", target: "file:///test.js", relative: "test.js" }, { source: "file:///test.js", target: "file:///test/test.js", relative: "test/test.js" } ]; describe("relative", function () { tests.forEach(function (test) { (test.focus ? iit : it)( test.label || ( "from " + JSON.stringify(test.source) + " " + "to " + JSON.stringify(test.target) ), function () { expect(URL.relative(test.source, test.target)) .toBe(test.relative) } ) }); it("should format a url with a path property", function () { expect(URL.format({path: "a/b"})).toEqual("a/b"); expect(URL.format({path: "a/b?c=d"})).toEqual("a/b?c=d"); }); });
AlexanderDolgan/sputnik
wp-content/themes/node_modules/gulp.spritesmith/node_modules/url2/test/url2-spec.js
JavaScript
gpl-2.0
2,582
# barber patches to re-route raw compilation via ember compat handlebars class Barber::Precompiler def sources [File.open("#{Rails.root}/vendor/assets/javascripts/handlebars.js"), precompiler] end def precompiler if !@precompiler source = File.read("#{Rails.root}/app/assets/javascripts/discourse-common/lib/raw-handlebars.js.es6") template = Tilt::ES6ModuleTranspilerTemplate.new {} transpiled = template.babel_transpile(source) # very hacky but lets us use ES6. I'm ashamed of this code -RW transpiled.gsub!(/^export .*$/, '') @precompiler = StringIO.new <<END var __RawHandlebars; (function() { #{transpiled}; __RawHandlebars = RawHandlebars; })(); Barber = { precompile: function(string) { return __RawHandlebars.precompile(string, false).toString(); } }; END end @precompiler end end module Discourse module Ember module Handlebars module Helper def precompile_handlebars(string) "require('discourse-common/lib/raw-handlebars').template(#{Barber::Precompiler.compile(string)});" end def compile_handlebars(string) "require('discourse-common/lib/raw-handlebars').compile(#{indent(string).inspect});" end end end end end class Ember::Handlebars::Template include Discourse::Ember::Handlebars::Helper def precompile_handlebars(string, input=nil) "require('discourse-common/lib/raw-handlebars').template(#{Barber::Precompiler.compile(string)});" end def compile_handlebars(string, input=nil) "require('discourse-common/lib/raw-handlebars').compile(#{indent(string).inspect});" end def global_template_target(namespace, module_name, config) "#{namespace}[#{template_path(module_name, config).inspect}]" end # FIXME: Previously, ember-handlebars-templates uses the logical path which incorrectly # returned paths with the `.raw` extension and our code is depending on the `.raw` # to find the right template to use. def actual_name(input) actual_name = input[:name] input[:filename].include?('.raw') ? "#{actual_name}.raw" : actual_name end end
gsambrotta/discourse
lib/freedom_patches/raw_handlebars.rb
Ruby
gpl-2.0
2,215
<?php /** * @package Joomla.UnitTest * @subpackage Linkedin * * @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ /** * Test class for JLinkedinCommunications. * * @package Joomla.UnitTest * @subpackage Linkedin * * @since 13.1 */ class JLinkedinCommunicationsTest extends TestCase { /** * @var JRegistry Options for the Linkedin object. * @since 13.1 */ protected $options; /** * @var JHttp Mock http object. * @since 13.1 */ protected $client; /** * @var JInput The input object to use in retrieving GET/POST data. * @since 13.1 */ protected $input; /** * @var JLinkedinCommunications Object under test. * @since 13.1 */ protected $object; /** * @var JLinkedinOAuth Authentication object for the Twitter object. * @since 13.1 */ protected $oauth; /** * @var string Sample JSON string. * @since 13.1 */ protected $sampleString = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; /** * @var string Sample JSON error message. * @since 13.1 */ protected $errorString = '{"errorCode":401, "message": "Generic error"}'; /** * Backup of the SERVER superglobal * * @var array * @since 3.6 */ protected $backupServer; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. * * @return void */ protected function setUp() { parent::setUp(); $this->backupServer = $_SERVER; $_SERVER['HTTP_HOST'] = 'example.com'; $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0'; $_SERVER['REQUEST_URI'] = '/index.php'; $_SERVER['SCRIPT_NAME'] = '/index.php'; $key = "app_key"; $secret = "app_secret"; $my_url = "http://127.0.0.1/gsoc/joomla-platform/linkedin_test.php"; $this->options = new JRegistry; $this->input = new JInput; $this->client = $this->getMockBuilder('JHttp')->setMethods(array('get', 'post', 'delete', 'put'))->getMock(); $this->oauth = new JLinkedinOauth($this->options, $this->client, $this->input); $this->oauth->setToken(array('key' => $key, 'secret' => $secret)); $this->object = new JLinkedinCommunications($this->options, $this->client, $this->oauth); $this->options->set('consumer_key', $key); $this->options->set('consumer_secret', $secret); $this->options->set('callback', $my_url); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. * * @return void * * @see \PHPUnit\Framework\TestCase::tearDown() * @since 3.6 */ protected function tearDown() { $_SERVER = $this->backupServer; unset($this->backupServer, $this->options, $this->input, $this->client, $this->oauth, $this->object); parent::tearDown(); } /** * Tests the inviteByEmail method * * @return void * * @since 13.1 */ public function testInviteByEmail() { $email = 'example@domain.com'; $first_name = 'Frist'; $last_name = 'Last'; $subject = 'Subject'; $body = 'body'; $connection = 'friend'; $path = '/v1/people/~/mailbox'; // Build the xml. $xml = '<mailbox-item> <recipients> <recipient> <person path="/people/email=' . $email . '"> <first-name>' . $first_name . '</first-name> <last-name>' . $last_name . '</last-name> </person> </recipient> </recipients> <subject>' . $subject . '</subject> <body>' . $body . '</body> <item-content> <invitation-request> <connect-type>' . $connection . '</connect-type> </invitation-request> </item-content> </mailbox-item>'; $header['Content-Type'] = 'text/xml'; $returnData = new stdClass; $returnData->code = 201; $returnData->body = $this->sampleString; $this->client->expects($this->once()) ->method('post', $xml, $header) ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->inviteByEmail($email, $first_name, $last_name, $subject, $body, $connection), $this->equalTo($returnData) ); } /** * Tests the inviteByEmail method - failure * * @return void * * @expectedException DomainException * @since 13.1 */ public function testInviteByEmailFailure() { $email = 'example@domain.com'; $first_name = 'Frist'; $last_name = 'Last'; $subject = 'Subject'; $body = 'body'; $connection = 'friend'; $path = '/v1/people/~/mailbox'; // Build the xml. $xml = '<mailbox-item> <recipients> <recipient> <person path="/people/email=' . $email . '"> <first-name>' . $first_name . '</first-name> <last-name>' . $last_name . '</last-name> </person> </recipient> </recipients> <subject>' . $subject . '</subject> <body>' . $body . '</body> <item-content> <invitation-request> <connect-type>' . $connection . '</connect-type> </invitation-request> </item-content> </mailbox-item>'; $header['Content-Type'] = 'text/xml'; $returnData = new stdClass; $returnData->code = 401; $returnData->body = $this->errorString; $this->client->expects($this->once()) ->method('post', $xml, $header) ->with($path) ->will($this->returnValue($returnData)); $this->object->inviteByEmail($email, $first_name, $last_name, $subject, $body, $connection); } /** * Tests the inviteById method * * @return void * * @since 13.1 */ public function testInviteById() { $id = 'lcnIwDU0S6'; $first_name = 'Frist'; $last_name = 'Last'; $subject = 'Subject'; $body = 'body'; $connection = 'friend'; $name = 'NAME_SEARCH'; $value = 'mwjY'; $path = '/v1/people-search:(people:(api-standard-profile-request))'; $returnData = new stdClass; $returnData->code = 200; $returnData->body = '{"apiStandardProfileRequest": {"headers": {"_total": 1,"values": [{"name": "x-li-auth-token","value": "' . $name . ':' . $value . '"}]}}}'; $data['format'] = 'json'; $data['first-name'] = $first_name; $data['last-name'] = $last_name; $path = $this->oauth->toUrl($path, $data); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $path = '/v1/people/~/mailbox'; // Build the xml. $xml = '<mailbox-item> <recipients> <recipient> <person path="/people/id=' . $id . '"> </person> </recipient> </recipients> <subject>' . $subject . '</subject> <body>' . $body . '</body> <item-content> <invitation-request> <connect-type>' . $connection . '</connect-type> <authorization> <name>' . $name . '</name> <value>' . $value . '</value> </authorization> </invitation-request> </item-content> </mailbox-item>'; $header['Content-Type'] = 'text/xml'; $returnData = new stdClass; $returnData->code = 201; $returnData->body = $this->sampleString; $this->client->expects($this->at(1)) ->method('post', $xml, $header) ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->inviteById($id, $first_name, $last_name, $subject, $body, $connection), $this->equalTo($returnData) ); } /** * Tests the inviteById method - failure * * @return void * * @expectedException RuntimeException * @since 13.1 */ public function testInviteByIdFailure() { $id = 'lcnIwDU0S6'; $first_name = 'Frist'; $last_name = 'Last'; $subject = 'Subject'; $body = 'body'; $connection = 'friend'; $path = '/v1/people-search:(people:(api-standard-profile-request))'; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; $data['format'] = 'json'; $data['first-name'] = $first_name; $data['last-name'] = $last_name; $path = $this->oauth->toUrl($path, $data); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->inviteById($id, $first_name, $last_name, $subject, $body, $connection); } /** * Tests the sendMessage method * * @return void * * @since 13.1 */ public function testSendMessage() { $recipient = array('~', 'lcnIwDU0S6'); $subject = 'Subject'; $body = 'body'; $path = '/v1/people/~/mailbox'; // Build the xml. $xml = '<mailbox-item> <recipients> <recipient> <person path="/people/~"/> </recipient> <recipient> <person path="/people/lcnIwDU0S6"/> </recipient> </recipients> <subject>' . $subject . '</subject> <body>' . $body . '</body> </mailbox-item>'; $header['Content-Type'] = 'text/xml'; $returnData = new stdClass; $returnData->code = 201; $returnData->body = $this->sampleString; $this->client->expects($this->once()) ->method('post', $xml, $header) ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->sendMessage($recipient, $subject, $body), $this->equalTo($returnData) ); } /** * Tests the sendMessage method - failure * * @return void * * @expectedException DomainException * @since 13.1 */ public function testSendMessageFailure() { $recipient = array('~', 'lcnIwDU0S6'); $subject = 'Subject'; $body = 'body'; $path = '/v1/people/~/mailbox'; // Build the xml. $xml = '<mailbox-item> <recipients> <recipient> <person path="/people/~"/> </recipient> <recipient> <person path="/people/lcnIwDU0S6"/> </recipient> </recipients> <subject>' . $subject . '</subject> <body>' . $body . '</body> </mailbox-item>'; $header['Content-Type'] = 'text/xml'; $returnData = new stdClass; $returnData->code = 401; $returnData->body = $this->errorString; $this->client->expects($this->once()) ->method('post', $xml, $header) ->with($path) ->will($this->returnValue($returnData)); $this->object->sendMessage($recipient, $subject, $body); } }
philip-sorokin/joomla-cms
tests/unit/suites/libraries/joomla/linkedin/JLinkedinCommunicationsTest.php
PHP
gpl-2.0
10,137
<?php function _wpsc_get_exchange_rate( $from, $to ) { if ( $from == $to ) { return 1; } $key = "wpsc_exchange_{$from}_{$to}"; if ( $rate = get_transient( $key ) ) { return (float) $rate; } $url = add_query_arg( array( 'a' => '1', 'from' => $from, 'to' => $to ), 'http://www.google.com/finance/converter' ); $url = apply_filters( '_wpsc_get_exchange_rate_service_endpoint', $url, $from, $to ); $response = wp_remote_retrieve_body( wp_remote_get( $url, array( 'timeout' => 10 ) ) ); if ( has_filter( '_wpsc_get_exchange_rate' ) ) { return (float) apply_filters( '_wpsc_get_exchange_rate', $response, $from, $to ); } if ( empty( $response ) ) { return $response; } else { $rate = explode( 'bld>', $response ); $rate = explode( $to, $rate[1] ); $rate = trim( $rate[0] ); set_transient( $key, $rate, DAY_IN_SECONDS ); return (float) $rate; } } function wpsc_convert_currency( $amt, $from, $to ) { if ( empty( $from ) || empty( $to ) ) { return $amt; } $rate = _wpsc_get_exchange_rate( $from, $to ); if ( is_wp_error( $rate ) ) { return $rate; } return $rate * $amt; } function wpsc_string_to_float( $string ) { global $wp_locale; $decimal_separator = get_option( 'wpsc_decimal_separator', $wp_locale->number_format['decimal_point'] ); $string = preg_replace( '/[^0-9\\' . $decimal_separator . ']/', '', $string ); $string = str_replace( $decimal_separator, '.', $string ); return (float) $string; } function wpsc_format_number( $number, $decimals = 2 ) { global $wp_locale; $decimal_separator = get_option( 'wpsc_decimal_separator', $wp_locale->number_format['decimal_point'] ); $thousands_separator = get_option( 'wpsc_thousands_separator', $wp_locale->number_format['thousands_sep'] ); $formatted = number_format( (float) $number, $decimals, $decimal_separator, $thousands_separator ); return $formatted; }
ericbarns/WP-e-Commerce
wpsc-includes/currency.helpers.php
PHP
gpl-2.0
1,953
import { Mongo } from "meteor/mongo"; /** * Client side collections */ export const Countries = new Mongo.Collection(null);
deetail/kimchi4u
client/collections/countries.js
JavaScript
gpl-3.0
128
from inspect import ismethod, isfunction import os import time import traceback from CodernityDB.database import RecordDeleted, RecordNotFound from couchpotato import md5, get_db from couchpotato.api import addApiView from couchpotato.core.event import fireEvent, addEvent from couchpotato.core.helpers.encoding import toUnicode, sp from couchpotato.core.helpers.variable import getTitle, tryInt from couchpotato.core.logger import CPLog from couchpotato.core.plugins.base import Plugin from .index import ReleaseIndex, ReleaseStatusIndex, ReleaseIDIndex, ReleaseDownloadIndex from couchpotato.environment import Env log = CPLog(__name__) class Release(Plugin): _database = { 'release': ReleaseIndex, 'release_status': ReleaseStatusIndex, 'release_identifier': ReleaseIDIndex, 'release_download': ReleaseDownloadIndex } def __init__(self): addApiView('release.manual_download', self.manualDownload, docs = { 'desc': 'Send a release manually to the downloaders', 'params': { 'id': {'type': 'id', 'desc': 'ID of the release object in release-table'} } }) addApiView('release.delete', self.deleteView, docs = { 'desc': 'Delete releases', 'params': { 'id': {'type': 'id', 'desc': 'ID of the release object in release-table'} } }) addApiView('release.ignore', self.ignore, docs = { 'desc': 'Toggle ignore, for bad or wrong releases', 'params': { 'id': {'type': 'id', 'desc': 'ID of the release object in release-table'} } }) addEvent('release.add', self.add) addEvent('release.download', self.download) addEvent('release.try_download_result', self.tryDownloadResult) addEvent('release.create_from_search', self.createFromSearch) addEvent('release.delete', self.delete) addEvent('release.clean', self.clean) addEvent('release.update_status', self.updateStatus) addEvent('release.with_status', self.withStatus) addEvent('release.for_media', self.forMedia) # Clean releases that didn't have activity in the last week addEvent('app.load', self.cleanDone, priority = 1000) fireEvent('schedule.interval', 'movie.clean_releases', self.cleanDone, hours = 12) def cleanDone(self): log.debug('Removing releases from dashboard') now = time.time() week = 604800 db = get_db() # Get (and remove) parentless releases releases = db.all('release', with_doc = False) media_exist = [] reindex = 0 for release in releases: if release.get('key') in media_exist: continue try: try: doc = db.get('id', release.get('_id')) except RecordDeleted: reindex += 1 continue db.get('id', release.get('key')) media_exist.append(release.get('key')) try: if doc.get('status') == 'ignore': doc['status'] = 'ignored' db.update(doc) except: log.error('Failed fixing mis-status tag: %s', traceback.format_exc()) except ValueError: fireEvent('database.delete_corrupted', release.get('key'), traceback_error = traceback.format_exc(0)) reindex += 1 except RecordDeleted: db.delete(doc) log.debug('Deleted orphaned release: %s', doc) reindex += 1 except: log.debug('Failed cleaning up orphaned releases: %s', traceback.format_exc()) if reindex > 0: db.reindex() del media_exist # get movies last_edit more than a week ago medias = fireEvent('media.with_status', ['done', 'active'], single = True) for media in medias: if media.get('last_edit', 0) > (now - week): continue for rel in self.forMedia(media['_id']): # Remove all available releases if rel['status'] in ['available']: self.delete(rel['_id']) # Set all snatched and downloaded releases to ignored to make sure they are ignored when re-adding the media elif rel['status'] in ['snatched', 'downloaded']: self.updateStatus(rel['_id'], status = 'ignored') if 'recent' in media.get('tags', []): fireEvent('media.untag', media.get('_id'), 'recent', single = True) def add(self, group, update_info = True, update_id = None): try: db = get_db() release_identifier = '%s.%s.%s' % (group['identifier'], group['meta_data'].get('audio', 'unknown'), group['meta_data']['quality']['identifier']) # Add movie if it doesn't exist try: media = db.get('media', 'imdb-%s' % group['identifier'], with_doc = True)['doc'] except: media = fireEvent('movie.add', params = { 'identifier': group['identifier'], 'profile_id': None, }, search_after = False, update_after = update_info, notify_after = False, status = 'done', single = True) release = None if update_id: try: release = db.get('id', update_id) release.update({ 'identifier': release_identifier, 'last_edit': int(time.time()), 'status': 'done', }) except: log.error('Failed updating existing release: %s', traceback.format_exc()) else: # Add Release if not release: release = { '_t': 'release', 'media_id': media['_id'], 'identifier': release_identifier, 'quality': group['meta_data']['quality'].get('identifier'), 'is_3d': group['meta_data']['quality'].get('is_3d', 0), 'last_edit': int(time.time()), 'status': 'done' } try: r = db.get('release_identifier', release_identifier, with_doc = True)['doc'] r['media_id'] = media['_id'] except: log.debug('Failed updating release by identifier "%s". Inserting new.', release_identifier) r = db.insert(release) # Update with ref and _id release.update({ '_id': r['_id'], '_rev': r['_rev'], }) # Empty out empty file groups release['files'] = dict((k, [toUnicode(x) for x in v]) for k, v in group['files'].items() if v) db.update(release) fireEvent('media.restatus', media['_id'], allowed_restatus = ['done'], single = True) return True except: log.error('Failed: %s', traceback.format_exc()) return False def deleteView(self, id = None, **kwargs): return { 'success': self.delete(id) } def delete(self, release_id): try: db = get_db() rel = db.get('id', release_id) db.delete(rel) return True except RecordDeleted: log.debug('Already deleted: %s', release_id) return True except: log.error('Failed: %s', traceback.format_exc()) return False def clean(self, release_id): try: db = get_db() rel = db.get('id', release_id) raw_files = rel.get('files') if len(raw_files) == 0: self.delete(rel['_id']) else: files = {} for file_type in raw_files: for release_file in raw_files.get(file_type, []): if os.path.isfile(sp(release_file)): if file_type not in files: files[file_type] = [] files[file_type].append(release_file) rel['files'] = files db.update(rel) return True except: log.error('Failed: %s', traceback.format_exc()) return False def ignore(self, id = None, **kwargs): db = get_db() try: if id: rel = db.get('id', id, with_doc = True) self.updateStatus(id, 'available' if rel['status'] in ['ignored', 'failed'] else 'ignored') return { 'success': True } except: log.error('Failed: %s', traceback.format_exc()) return { 'success': False } def manualDownload(self, id = None, **kwargs): db = get_db() try: release = db.get('id', id) item = release['info'] movie = db.get('id', release['media_id']) fireEvent('notify.frontend', type = 'release.manual_download', data = True, message = 'Snatching "%s"' % item['name']) # Get matching provider provider = fireEvent('provider.belongs_to', item['url'], provider = item.get('provider'), single = True) if item.get('protocol') != 'torrent_magnet': item['download'] = provider.loginDownload if provider.urls.get('login') else provider.download success = self.download(data = item, media = movie, manual = True) if success: fireEvent('notify.frontend', type = 'release.manual_download', data = True, message = 'Successfully snatched "%s"' % item['name']) return { 'success': success == True } except: log.error('Couldn\'t find release with id: %s: %s', (id, traceback.format_exc())) return { 'success': False } def download(self, data, media, manual = False): # Test to see if any downloaders are enabled for this type downloader_enabled = fireEvent('download.enabled', manual, data, single = True) if not downloader_enabled: log.info('Tried to download, but none of the "%s" downloaders are enabled or gave an error', data.get('protocol')) return False # Download NZB or torrent file filedata = None if data.get('download') and (ismethod(data.get('download')) or isfunction(data.get('download'))): try: filedata = data.get('download')(url = data.get('url'), nzb_id = data.get('id')) except: log.error('Tried to download, but the "%s" provider gave an error: %s', (data.get('protocol'), traceback.format_exc())) return False if filedata == 'try_next': return filedata elif not filedata: return False # Send NZB or torrent file to downloader download_result = fireEvent('download', data = data, media = media, manual = manual, filedata = filedata, single = True) if not download_result: log.info('Tried to download, but the "%s" downloader gave an error', data.get('protocol')) return False log.debug('Downloader result: %s', download_result) try: db = get_db() try: rls = db.get('release_identifier', md5(data['url']), with_doc = True)['doc'] except: log.error('No release found to store download information in') return False renamer_enabled = Env.setting('enabled', 'renamer') # Save download-id info if returned if isinstance(download_result, dict): rls['download_info'] = download_result db.update(rls) log_movie = '%s (%s) in %s' % (getTitle(media), media['info'].get('year'), rls['quality']) snatch_message = 'Snatched "%s": %s from %s' % (data.get('name'), log_movie, (data.get('provider', '') + data.get('provider_extra', ''))) log.info(snatch_message) fireEvent('%s.snatched' % data['type'], message = snatch_message, data = media) # Mark release as snatched if renamer_enabled: self.updateStatus(rls['_id'], status = 'snatched') # If renamer isn't used, mark media done if finished or release downloaded else: if media['status'] == 'active': profile = db.get('id', media['profile_id']) if fireEvent('quality.isfinish', {'identifier': rls['quality'], 'is_3d': rls.get('is_3d', False)}, profile, single = True): log.info('Renamer disabled, marking media as finished: %s', log_movie) # Mark release done self.updateStatus(rls['_id'], status = 'done') # Mark media done fireEvent('media.restatus', media['_id'], single = True) return True # Assume release downloaded self.updateStatus(rls['_id'], status = 'downloaded') except: log.error('Failed storing download status: %s', traceback.format_exc()) return False return True def tryDownloadResult(self, results, media, quality_custom): wait_for = False let_through = False filtered_results = [] minimum_seeders = tryInt(Env.setting('minimum_seeders', section = 'torrent', default = 1)) # Filter out ignored and other releases we don't want for rel in results: if rel['status'] in ['ignored', 'failed']: log.info('Ignored: %s', rel['name']) continue if rel['score'] < quality_custom.get('minimum_score'): log.info('Ignored, score "%s" to low, need at least "%s": %s', (rel['score'], quality_custom.get('minimum_score'), rel['name'])) continue if rel['size'] <= 50: log.info('Ignored, size "%sMB" to low: %s', (rel['size'], rel['name'])) continue if 'seeders' in rel and rel.get('seeders') < minimum_seeders: log.info('Ignored, not enough seeders, has %s needs %s: %s', (rel.get('seeders'), minimum_seeders, rel['name'])) continue # If a single release comes through the "wait for", let through all rel['wait_for'] = False if quality_custom.get('index') != 0 and quality_custom.get('wait_for', 0) > 0 and rel.get('age') <= quality_custom.get('wait_for', 0): rel['wait_for'] = True else: let_through = True filtered_results.append(rel) # Loop through filtered results for rel in filtered_results: # Only wait if not a single release is old enough if rel.get('wait_for') and not let_through: log.info('Ignored, waiting %s days: %s', (quality_custom.get('wait_for') - rel.get('age'), rel['name'])) wait_for = True continue downloaded = fireEvent('release.download', data = rel, media = media, single = True) if downloaded is True: return True elif downloaded != 'try_next': break return wait_for def createFromSearch(self, search_results, media, quality): try: db = get_db() found_releases = [] is_3d = False try: is_3d = quality['custom']['3d'] except: pass for rel in search_results: rel_identifier = md5(rel['url']) release = { '_t': 'release', 'identifier': rel_identifier, 'media_id': media.get('_id'), 'quality': quality.get('identifier'), 'is_3d': is_3d, 'status': rel.get('status', 'available'), 'last_edit': int(time.time()), 'info': {} } # Add downloader info if provided try: release['download_info'] = rel['download_info'] del rel['download_info'] except: pass try: rls = db.get('release_identifier', rel_identifier, with_doc = True)['doc'] except: rls = db.insert(release) rls.update(release) # Update info, but filter out functions for info in rel: try: if not isinstance(rel[info], (str, unicode, int, long, float)): continue rls['info'][info] = toUnicode(rel[info]) if isinstance(rel[info], (str, unicode)) else rel[info] except: log.debug('Couldn\'t add %s to ReleaseInfo: %s', (info, traceback.format_exc())) db.update(rls) # Update release in search_results rel['status'] = rls.get('status') if rel['status'] == 'available': found_releases.append(rel_identifier) return found_releases except: log.error('Failed: %s', traceback.format_exc()) return [] def updateStatus(self, release_id, status = None): if not status: return False try: db = get_db() rel = db.get('id', release_id) if rel and rel.get('status') != status: release_name = None if rel.get('files'): for file_type in rel.get('files', {}): if file_type == 'movie': for release_file in rel['files'][file_type]: release_name = os.path.basename(release_file) break if not release_name and rel.get('info'): release_name = rel['info'].get('name') #update status in Db log.debug('Marking release %s as %s', (release_name, status)) rel['status'] = status rel['last_edit'] = int(time.time()) db.update(rel) #Update all movie info as there is no release update function fireEvent('notify.frontend', type = 'release.update_status', data = rel) return True except: log.error('Failed: %s', traceback.format_exc()) return False def withStatus(self, status, with_doc = True): db = get_db() status = list(status if isinstance(status, (list, tuple)) else [status]) for s in status: for ms in db.get_many('release_status', s): if with_doc: try: doc = db.get('id', ms['_id']) yield doc except RecordNotFound: log.debug('Record not found, skipping: %s', ms['_id']) else: yield ms def forMedia(self, media_id): db = get_db() raw_releases = db.get_many('release', media_id) releases = [] for r in raw_releases: try: doc = db.get('id', r.get('_id')) releases.append(doc) except RecordDeleted: pass except (ValueError, EOFError): fireEvent('database.delete_corrupted', r.get('_id'), traceback_error = traceback.format_exc(0)) releases = sorted(releases, key = lambda k: k.get('info', {}).get('score', 0), reverse = True) # Sort based on preferred search method download_preference = self.conf('preferred_method', section = 'searcher') if download_preference != 'both': releases = sorted(releases, key = lambda k: k.get('info', {}).get('protocol', '')[:3], reverse = (download_preference == 'torrent')) return releases or []
coderb0t/CouchPotatoServer
couchpotato/core/plugins/release/main.py
Python
gpl-3.0
20,734
package aws import ( "fmt" "log" "math" "regexp" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" events "github.com/aws/aws-sdk-go/service/cloudwatchevents" "github.com/hashicorp/terraform/helper/validation" ) func resourceAwsCloudWatchEventTarget() *schema.Resource { return &schema.Resource{ Create: resourceAwsCloudWatchEventTargetCreate, Read: resourceAwsCloudWatchEventTargetRead, Update: resourceAwsCloudWatchEventTargetUpdate, Delete: resourceAwsCloudWatchEventTargetDelete, Schema: map[string]*schema.Schema{ "rule": { Type: schema.TypeString, Required: true, ForceNew: true, ValidateFunc: validateCloudWatchEventRuleName, }, "target_id": { Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, ValidateFunc: validateCloudWatchEventTargetId, }, "arn": { Type: schema.TypeString, Required: true, }, "input": { Type: schema.TypeString, Optional: true, ConflictsWith: []string{"input_path"}, // We could be normalizing the JSON here, // but for built-in targets input may not be JSON }, "input_path": { Type: schema.TypeString, Optional: true, ConflictsWith: []string{"input"}, }, "role_arn": { Type: schema.TypeString, Optional: true, }, "run_command_targets": { Type: schema.TypeList, Optional: true, MaxItems: 5, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "key": { Type: schema.TypeString, Required: true, ValidateFunc: validation.StringLenBetween(1, 128), }, "values": { Type: schema.TypeList, Required: true, Elem: &schema.Schema{Type: schema.TypeString}, }, }, }, }, "ecs_target": { Type: schema.TypeList, Optional: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "task_count": { Type: schema.TypeInt, Optional: true, ValidateFunc: validation.IntBetween(1, math.MaxInt32), }, "task_definition_arn": { Type: schema.TypeString, Required: true, ValidateFunc: validation.StringLenBetween(1, 1600), }, }, }, }, "input_transformer": { Type: schema.TypeList, Optional: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "input_paths": { Type: schema.TypeMap, Optional: true, }, "input_template": { Type: schema.TypeString, Required: true, ValidateFunc: validation.StringLenBetween(1, 8192), }, }, }, }, }, } } func resourceAwsCloudWatchEventTargetCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).cloudwatcheventsconn rule := d.Get("rule").(string) var targetId string if v, ok := d.GetOk("target_id"); ok { targetId = v.(string) } else { targetId = resource.UniqueId() d.Set("target_id", targetId) } input := buildPutTargetInputStruct(d) log.Printf("[DEBUG] Creating CloudWatch Event Target: %s", input) out, err := conn.PutTargets(input) if err != nil { return fmt.Errorf("Creating CloudWatch Event Target failed: %s", err) } if len(out.FailedEntries) > 0 { return fmt.Errorf("Creating CloudWatch Event Target failed: %s", out.FailedEntries) } id := rule + "-" + targetId d.SetId(id) log.Printf("[INFO] CloudWatch Event Target %q created", d.Id()) return resourceAwsCloudWatchEventTargetRead(d, meta) } func resourceAwsCloudWatchEventTargetRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).cloudwatcheventsconn t, err := findEventTargetById( d.Get("target_id").(string), d.Get("rule").(string), nil, conn) if err != nil { if regexp.MustCompile(" not found$").MatchString(err.Error()) { log.Printf("[WARN] Removing CloudWatch Event Target %q because it's gone.", d.Id()) d.SetId("") return nil } if awsErr, ok := err.(awserr.Error); ok { // This should never happen, but it's useful // for recovering from https://github.com/hashicorp/terraform/issues/5389 if awsErr.Code() == "ValidationException" { log.Printf("[WARN] Removing CloudWatch Event Target %q because it never existed.", d.Id()) d.SetId("") return nil } if awsErr.Code() == "ResourceNotFoundException" { log.Printf("[WARN] CloudWatch Event Target (%q) not found. Removing it from state.", d.Id()) d.SetId("") return nil } } return err } log.Printf("[DEBUG] Found Event Target: %s", t) d.Set("arn", t.Arn) d.Set("target_id", t.Id) d.Set("input", t.Input) d.Set("input_path", t.InputPath) d.Set("role_arn", t.RoleArn) if t.RunCommandParameters != nil { if err := d.Set("run_command_targets", flattenAwsCloudWatchEventTargetRunParameters(t.RunCommandParameters)); err != nil { return fmt.Errorf("[DEBUG] Error setting run_command_targets error: %#v", err) } } if t.EcsParameters != nil { if err := d.Set("ecs_target", flattenAwsCloudWatchEventTargetEcsParameters(t.EcsParameters)); err != nil { return fmt.Errorf("[DEBUG] Error setting ecs_target error: %#v", err) } } if t.InputTransformer != nil { if err := d.Set("input_transformer", flattenAwsCloudWatchInputTransformer(t.InputTransformer)); err != nil { return fmt.Errorf("[DEBUG] Error setting input_transformer error: %#v", err) } } return nil } func findEventTargetById(id, rule string, nextToken *string, conn *events.CloudWatchEvents) (*events.Target, error) { input := events.ListTargetsByRuleInput{ Rule: aws.String(rule), NextToken: nextToken, Limit: aws.Int64(100), // Set limit to allowed maximum to prevent API throttling } log.Printf("[DEBUG] Reading CloudWatch Event Target: %s", input) out, err := conn.ListTargetsByRule(&input) if err != nil { return nil, err } for _, t := range out.Targets { if *t.Id == id { return t, nil } } if out.NextToken != nil { return findEventTargetById(id, rule, nextToken, conn) } return nil, fmt.Errorf("CloudWatch Event Target %q (%q) not found", id, rule) } func resourceAwsCloudWatchEventTargetUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).cloudwatcheventsconn input := buildPutTargetInputStruct(d) log.Printf("[DEBUG] Updating CloudWatch Event Target: %s", input) _, err := conn.PutTargets(input) if err != nil { return fmt.Errorf("Updating CloudWatch Event Target failed: %s", err) } return resourceAwsCloudWatchEventTargetRead(d, meta) } func resourceAwsCloudWatchEventTargetDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).cloudwatcheventsconn input := events.RemoveTargetsInput{ Ids: []*string{aws.String(d.Get("target_id").(string))}, Rule: aws.String(d.Get("rule").(string)), } log.Printf("[INFO] Deleting CloudWatch Event Target: %s", input) _, err := conn.RemoveTargets(&input) if err != nil { return fmt.Errorf("Error deleting CloudWatch Event Target: %s", err) } log.Println("[INFO] CloudWatch Event Target deleted") d.SetId("") return nil } func buildPutTargetInputStruct(d *schema.ResourceData) *events.PutTargetsInput { e := &events.Target{ Arn: aws.String(d.Get("arn").(string)), Id: aws.String(d.Get("target_id").(string)), } if v, ok := d.GetOk("input"); ok { e.Input = aws.String(v.(string)) } if v, ok := d.GetOk("input_path"); ok { e.InputPath = aws.String(v.(string)) } if v, ok := d.GetOk("role_arn"); ok { e.RoleArn = aws.String(v.(string)) } if v, ok := d.GetOk("run_command_targets"); ok { e.RunCommandParameters = expandAwsCloudWatchEventTargetRunParameters(v.([]interface{})) } if v, ok := d.GetOk("ecs_target"); ok { e.EcsParameters = expandAwsCloudWatchEventTargetEcsParameters(v.([]interface{})) } if v, ok := d.GetOk("input_transformer"); ok { e.InputTransformer = expandAwsCloudWatchEventTransformerParameters(v.([]interface{})) } input := events.PutTargetsInput{ Rule: aws.String(d.Get("rule").(string)), Targets: []*events.Target{e}, } return &input } func expandAwsCloudWatchEventTargetRunParameters(config []interface{}) *events.RunCommandParameters { commands := make([]*events.RunCommandTarget, 0) for _, c := range config { param := c.(map[string]interface{}) command := &events.RunCommandTarget{ Key: aws.String(param["key"].(string)), Values: expandStringList(param["values"].([]interface{})), } commands = append(commands, command) } command := &events.RunCommandParameters{ RunCommandTargets: commands, } return command } func expandAwsCloudWatchEventTargetEcsParameters(config []interface{}) *events.EcsParameters { ecsParameters := &events.EcsParameters{} for _, c := range config { param := c.(map[string]interface{}) ecsParameters.TaskCount = aws.Int64(int64(param["task_count"].(int))) ecsParameters.TaskDefinitionArn = aws.String(param["task_definition_arn"].(string)) } return ecsParameters } func expandAwsCloudWatchEventTransformerParameters(config []interface{}) *events.InputTransformer { transformerParameters := &events.InputTransformer{} inputPathsMaps := map[string]*string{} for _, c := range config { param := c.(map[string]interface{}) inputPaths := param["input_paths"].(map[string]interface{}) for k, v := range inputPaths { inputPathsMaps[k] = aws.String(v.(string)) } transformerParameters.InputTemplate = aws.String(param["input_template"].(string)) } transformerParameters.InputPathsMap = inputPathsMaps return transformerParameters } func flattenAwsCloudWatchEventTargetRunParameters(runCommand *events.RunCommandParameters) []map[string]interface{} { result := make([]map[string]interface{}, 0) for _, x := range runCommand.RunCommandTargets { config := make(map[string]interface{}) config["key"] = *x.Key config["values"] = flattenStringList(x.Values) result = append(result, config) } return result } func flattenAwsCloudWatchEventTargetEcsParameters(ecsParameters *events.EcsParameters) []map[string]interface{} { config := make(map[string]interface{}) config["task_count"] = *ecsParameters.TaskCount config["task_definition_arn"] = *ecsParameters.TaskDefinitionArn result := []map[string]interface{}{config} return result } func flattenAwsCloudWatchInputTransformer(inputTransformer *events.InputTransformer) []map[string]interface{} { config := make(map[string]interface{}) inputPathsMap := make(map[string]string) for k, v := range inputTransformer.InputPathsMap { inputPathsMap[k] = *v } config["input_template"] = *inputTransformer.InputTemplate config["input_paths"] = inputPathsMap result := []map[string]interface{}{config} return result }
hartzell/terraform
vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_cloudwatch_event_target.go
GO
mpl-2.0
11,014
from edxmako.shortcuts import render_to_string from pipeline.conf import settings from pipeline.packager import Packager from pipeline.utils import guess_type from static_replace import try_staticfiles_lookup def compressed_css(package_name): package = settings.PIPELINE_CSS.get(package_name, {}) if package: package = {package_name: package} packager = Packager(css_packages=package, js_packages={}) package = packager.package_for('css', package_name) if settings.PIPELINE: return render_css(package, package.output_filename) else: paths = packager.compile(package.paths) return render_individual_css(package, paths) def render_css(package, path): template_name = package.template_name or "mako/css.html" context = package.extra_context url = try_staticfiles_lookup(path) context.update({ 'type': guess_type(path, 'text/css'), 'url': url, }) return render_to_string(template_name, context) def render_individual_css(package, paths): tags = [render_css(package, path) for path in paths] return '\n'.join(tags) def compressed_js(package_name): package = settings.PIPELINE_JS.get(package_name, {}) if package: package = {package_name: package} packager = Packager(css_packages={}, js_packages=package) package = packager.package_for('js', package_name) if settings.PIPELINE: return render_js(package, package.output_filename) else: paths = packager.compile(package.paths) templates = packager.pack_templates(package) return render_individual_js(package, paths, templates) def render_js(package, path): template_name = package.template_name or "mako/js.html" context = package.extra_context context.update({ 'type': guess_type(path, 'text/javascript'), 'url': try_staticfiles_lookup(path) }) return render_to_string(template_name, context) def render_inline_js(package, js): context = package.extra_context context.update({ 'source': js }) return render_to_string("mako/inline_js.html", context) def render_individual_js(package, paths, templates=None): tags = [render_js(package, js) for js in paths] if templates: tags.append(render_inline_js(package, templates)) return '\n'.join(tags)
liuqr/edx-xiaodun
common/djangoapps/pipeline_mako/__init__.py
Python
agpl-3.0
2,354
/* * 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.nifi.hbase; /** * Encapsulates the information for a delete operation. */ public class DeleteRequest { private byte[] rowId; private byte[] columnFamily; private byte[] columnQualifier; private String visibilityLabel; public DeleteRequest(byte[] rowId, byte[] columnFamily, byte[] columnQualifier, String visibilityLabel) { this.rowId = rowId; this.columnFamily = columnFamily; this.columnQualifier = columnQualifier; this.visibilityLabel = visibilityLabel; } public byte[] getRowId() { return rowId; } public byte[] getColumnFamily() { return columnFamily; } public byte[] getColumnQualifier() { return columnQualifier; } public String getVisibilityLabel() { return visibilityLabel; } @Override public String toString() { return new StringBuilder() .append(String.format("Row ID: %s\n", new String(rowId))) .append(String.format("Column Family: %s\n", new String(columnFamily))) .append(String.format("Column Qualifier: %s\n", new String(columnQualifier))) .append(visibilityLabel != null ? String.format("Visibility Label: %s", visibilityLabel) : "") .toString(); } }
ijokarumawak/nifi
nifi-nar-bundles/nifi-standard-services/nifi-hbase-client-service-api/src/main/java/org/apache/nifi/hbase/DeleteRequest.java
Java
apache-2.0
2,100
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Differencing { /// <summary> /// Represents an edit operation on a sequence of values. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct SequenceEdit : IEquatable<SequenceEdit> { private readonly int _oldIndex; private readonly int _newIndex; internal SequenceEdit(int oldIndex, int newIndex) { Debug.Assert(oldIndex >= -1); Debug.Assert(newIndex >= -1); Debug.Assert(newIndex != -1 || oldIndex != -1); _oldIndex = oldIndex; _newIndex = newIndex; } /// <summary> /// The kind of edit: <see cref="EditKind.Delete"/>, <see cref="EditKind.Insert"/>, or <see cref="EditKind.Update"/>. /// </summary> public EditKind Kind { get { if (_oldIndex == -1) { return EditKind.Insert; } if (_newIndex == -1) { return EditKind.Delete; } return EditKind.Update; } } /// <summary> /// Index in the old sequence, or -1 if the edit is insert. /// </summary> public int OldIndex => _oldIndex; /// <summary> /// Index in the new sequence, or -1 if the edit is delete. /// </summary> public int NewIndex => _newIndex; public bool Equals(SequenceEdit other) { return _oldIndex == other._oldIndex && _newIndex == other._newIndex; } public override bool Equals(object obj) => obj is SequenceEdit && Equals((SequenceEdit)obj); public override int GetHashCode() => Hash.Combine(_oldIndex, _newIndex); private string GetDebuggerDisplay() { var result = Kind.ToString(); switch (Kind) { case EditKind.Delete: return result + " (" + _oldIndex + ")"; case EditKind.Insert: return result + " (" + _newIndex + ")"; case EditKind.Update: return result + " (" + _oldIndex + " -> " + _newIndex + ")"; } return result; } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly SequenceEdit _sequenceEdit; public TestAccessor(SequenceEdit sequenceEdit) => _sequenceEdit = sequenceEdit; internal string GetDebuggerDisplay() => _sequenceEdit.GetDebuggerDisplay(); } } }
physhi/roslyn
src/Workspaces/Core/Portable/Differencing/SequenceEdit.cs
C#
apache-2.0
3,081
// Copyright 2015 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. package icmp import ( "fmt" "net" "reflect" "testing" "golang.org/x/net/internal/iana" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" ) func TestMarshalAndParseExtension(t *testing.T) { fn := func(t *testing.T, proto int, typ Type, hdr, obj []byte, te Extension) error { b, err := te.Marshal(proto) if err != nil { return err } if !reflect.DeepEqual(b, obj) { return fmt.Errorf("got %#v; want %#v", b, obj) } switch typ { case ipv4.ICMPTypeExtendedEchoRequest, ipv6.ICMPTypeExtendedEchoRequest: exts, l, err := parseExtensions(typ, append(hdr, obj...), 0) if err != nil { return err } if l != 0 { return fmt.Errorf("got %d; want 0", l) } if !reflect.DeepEqual(exts, []Extension{te}) { return fmt.Errorf("got %#v; want %#v", exts[0], te) } default: for i, wire := range []struct { data []byte // original datagram inlattr int // length of padded original datagram, a hint outlattr int // length of padded original datagram, a want err error }{ {nil, 0, -1, errNoExtension}, {make([]byte, 127), 128, -1, errNoExtension}, {make([]byte, 128), 127, -1, errNoExtension}, {make([]byte, 128), 128, -1, errNoExtension}, {make([]byte, 128), 129, -1, errNoExtension}, {append(make([]byte, 128), append(hdr, obj...)...), 127, 128, nil}, {append(make([]byte, 128), append(hdr, obj...)...), 128, 128, nil}, {append(make([]byte, 128), append(hdr, obj...)...), 129, 128, nil}, {append(make([]byte, 512), append(hdr, obj...)...), 511, -1, errNoExtension}, {append(make([]byte, 512), append(hdr, obj...)...), 512, 512, nil}, {append(make([]byte, 512), append(hdr, obj...)...), 513, -1, errNoExtension}, } { exts, l, err := parseExtensions(typ, wire.data, wire.inlattr) if err != wire.err { return fmt.Errorf("#%d: got %v; want %v", i, err, wire.err) } if wire.err != nil { continue } if l != wire.outlattr { return fmt.Errorf("#%d: got %d; want %d", i, l, wire.outlattr) } if !reflect.DeepEqual(exts, []Extension{te}) { return fmt.Errorf("#%d: got %#v; want %#v", i, exts[0], te) } } } return nil } t.Run("MPLSLabelStack", func(t *testing.T) { for _, et := range []struct { proto int typ Type hdr []byte obj []byte ext Extension }{ // MPLS label stack with no label { proto: iana.ProtocolICMP, typ: ipv4.ICMPTypeDestinationUnreachable, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x04, 0x01, 0x01, }, ext: &MPLSLabelStack{ Class: classMPLSLabelStack, Type: typeIncomingMPLSLabelStack, }, }, // MPLS label stack with a single label { proto: iana.ProtocolIPv6ICMP, typ: ipv6.ICMPTypeDestinationUnreachable, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x08, 0x01, 0x01, 0x03, 0xe8, 0xe9, 0xff, }, ext: &MPLSLabelStack{ Class: classMPLSLabelStack, Type: typeIncomingMPLSLabelStack, Labels: []MPLSLabel{ { Label: 16014, TC: 0x4, S: true, TTL: 255, }, }, }, }, // MPLS label stack with multiple labels { proto: iana.ProtocolICMP, typ: ipv4.ICMPTypeDestinationUnreachable, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x0c, 0x01, 0x01, 0x03, 0xe8, 0xde, 0xfe, 0x03, 0xe8, 0xe1, 0xff, }, ext: &MPLSLabelStack{ Class: classMPLSLabelStack, Type: typeIncomingMPLSLabelStack, Labels: []MPLSLabel{ { Label: 16013, TC: 0x7, S: false, TTL: 254, }, { Label: 16014, TC: 0, S: true, TTL: 255, }, }, }, }, } { if err := fn(t, et.proto, et.typ, et.hdr, et.obj, et.ext); err != nil { t.Error(err) } } }) t.Run("InterfaceInfo", func(t *testing.T) { for _, et := range []struct { proto int typ Type hdr []byte obj []byte ext Extension }{ // Interface information with no attribute { proto: iana.ProtocolICMP, typ: ipv4.ICMPTypeDestinationUnreachable, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x04, 0x02, 0x00, }, ext: &InterfaceInfo{ Class: classInterfaceInfo, }, }, // Interface information with ifIndex and name { proto: iana.ProtocolICMP, typ: ipv4.ICMPTypeDestinationUnreachable, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x10, 0x02, 0x0a, 0x00, 0x00, 0x00, 0x10, 0x08, byte('e'), byte('n'), byte('1'), byte('0'), byte('1'), 0x00, 0x00, }, ext: &InterfaceInfo{ Class: classInterfaceInfo, Type: 0x0a, Interface: &net.Interface{ Index: 16, Name: "en101", }, }, }, // Interface information with ifIndex, IPAddr, name and MTU { proto: iana.ProtocolIPv6ICMP, typ: ipv6.ICMPTypeDestinationUnreachable, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x28, 0x02, 0x0f, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x02, 0x00, 0x00, 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x08, byte('e'), byte('n'), byte('1'), byte('0'), byte('1'), 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, }, ext: &InterfaceInfo{ Class: classInterfaceInfo, Type: 0x0f, Interface: &net.Interface{ Index: 15, Name: "en101", MTU: 8192, }, Addr: &net.IPAddr{ IP: net.ParseIP("fe80::1"), Zone: "en101", }, }, }, } { if err := fn(t, et.proto, et.typ, et.hdr, et.obj, et.ext); err != nil { t.Error(err) } } }) t.Run("InterfaceIdent", func(t *testing.T) { for _, et := range []struct { proto int typ Type hdr []byte obj []byte ext Extension }{ // Interface identification by name { proto: iana.ProtocolICMP, typ: ipv4.ICMPTypeExtendedEchoRequest, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x0c, 0x03, 0x01, byte('e'), byte('n'), byte('1'), byte('0'), byte('1'), 0x00, 0x00, 0x00, }, ext: &InterfaceIdent{ Class: classInterfaceIdent, Type: typeInterfaceByName, Name: "en101", }, }, // Interface identification by index { proto: iana.ProtocolIPv6ICMP, typ: ipv6.ICMPTypeExtendedEchoRequest, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x08, 0x03, 0x02, 0x00, 0x00, 0x03, 0x8f, }, ext: &InterfaceIdent{ Class: classInterfaceIdent, Type: typeInterfaceByIndex, Index: 911, }, }, // Interface identification by address { proto: iana.ProtocolICMP, typ: ipv4.ICMPTypeExtendedEchoRequest, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x10, 0x03, 0x03, byte(iana.AddrFamily48bitMAC >> 8), byte(iana.AddrFamily48bitMAC & 0x0f), 0x06, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0x00, 0x00, }, ext: &InterfaceIdent{ Class: classInterfaceIdent, Type: typeInterfaceByAddress, AFI: iana.AddrFamily48bitMAC, Addr: []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}, }, }, } { if err := fn(t, et.proto, et.typ, et.hdr, et.obj, et.ext); err != nil { t.Error(err) } } }) } func TestParseInterfaceName(t *testing.T) { ifi := InterfaceInfo{Interface: &net.Interface{}} for i, tt := range []struct { b []byte error }{ {[]byte{0, 'e', 'n', '0'}, errInvalidExtension}, {[]byte{4, 'e', 'n', '0'}, nil}, {[]byte{7, 'e', 'n', '0', 0xff, 0xff, 0xff, 0xff}, errInvalidExtension}, {[]byte{8, 'e', 'n', '0', 0xff, 0xff, 0xff}, errMessageTooShort}, } { if _, err := ifi.parseName(tt.b); err != tt.error { t.Errorf("#%d: got %v; want %v", i, err, tt.error) } } }
muzining/net
x/net/icmp/extension_test.go
GO
bsd-3-clause
8,186
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <iomanip> // quoted #include <iomanip> #include <sstream> #include <string> #include <cassert> #if _LIBCPP_STD_VER > 11 bool is_skipws ( const std::istream *is ) { return ( is->flags() & std::ios_base::skipws ) != 0; } bool is_skipws ( const std::wistream *is ) { return ( is->flags() & std::ios_base::skipws ) != 0; } void both_ways ( const char *p ) { std::string str(p); auto q = std::quoted(str); std::stringstream ss; bool skippingws = is_skipws ( &ss ); ss << q; ss >> q; } void round_trip ( const char *p ) { std::stringstream ss; bool skippingws = is_skipws ( &ss ); ss << std::quoted(p); std::string s; ss >> std::quoted(s); assert ( s == p ); assert ( skippingws == is_skipws ( &ss )); } void round_trip_ws ( const char *p ) { std::stringstream ss; std::noskipws ( ss ); bool skippingws = is_skipws ( &ss ); ss << std::quoted(p); std::string s; ss >> std::quoted(s); assert ( s == p ); assert ( skippingws == is_skipws ( &ss )); } void round_trip_d ( const char *p, char delim ) { std::stringstream ss; ss << std::quoted(p, delim); std::string s; ss >> std::quoted(s, delim); assert ( s == p ); } void round_trip_e ( const char *p, char escape ) { std::stringstream ss; ss << std::quoted(p, '"', escape ); std::string s; ss >> std::quoted(s, '"', escape ); assert ( s == p ); } std::string quote ( const char *p, char delim='"', char escape='\\' ) { std::stringstream ss; ss << std::quoted(p, delim, escape); std::string s; ss >> s; // no quote return s; } std::string unquote ( const char *p, char delim='"', char escape='\\' ) { std::stringstream ss; ss << p; std::string s; ss >> std::quoted(s, delim, escape); return s; } void test_padding () { { std::stringstream ss; ss << std::left << std::setw(10) << std::setfill('!') << std::quoted("abc", '`'); assert ( ss.str() == "`abc`!!!!!" ); } { std::stringstream ss; ss << std::right << std::setw(10) << std::setfill('!') << std::quoted("abc", '`'); assert ( ss.str() == "!!!!!`abc`" ); } } void round_trip ( const wchar_t *p ) { std::wstringstream ss; bool skippingws = is_skipws ( &ss ); ss << std::quoted(p); std::wstring s; ss >> std::quoted(s); assert ( s == p ); assert ( skippingws == is_skipws ( &ss )); } void round_trip_ws ( const wchar_t *p ) { std::wstringstream ss; std::noskipws ( ss ); bool skippingws = is_skipws ( &ss ); ss << std::quoted(p); std::wstring s; ss >> std::quoted(s); assert ( s == p ); assert ( skippingws == is_skipws ( &ss )); } void round_trip_d ( const wchar_t *p, wchar_t delim ) { std::wstringstream ss; ss << std::quoted(p, delim); std::wstring s; ss >> std::quoted(s, delim); assert ( s == p ); } void round_trip_e ( const wchar_t *p, wchar_t escape ) { std::wstringstream ss; ss << std::quoted(p, wchar_t('"'), escape ); std::wstring s; ss >> std::quoted(s, wchar_t('"'), escape ); assert ( s == p ); } std::wstring quote ( const wchar_t *p, wchar_t delim='"', wchar_t escape='\\' ) { std::wstringstream ss; ss << std::quoted(p, delim, escape); std::wstring s; ss >> s; // no quote return s; } std::wstring unquote ( const wchar_t *p, wchar_t delim='"', wchar_t escape='\\' ) { std::wstringstream ss; ss << p; std::wstring s; ss >> std::quoted(s, delim, escape); return s; } int main() { both_ways ( "" ); // This is a compilation check round_trip ( "" ); round_trip_ws ( "" ); round_trip_d ( "", 'q' ); round_trip_e ( "", 'q' ); round_trip ( L"" ); round_trip_ws ( L"" ); round_trip_d ( L"", 'q' ); round_trip_e ( L"", 'q' ); round_trip ( "Hi" ); round_trip_ws ( "Hi" ); round_trip_d ( "Hi", '!' ); round_trip_e ( "Hi", '!' ); assert ( quote ( "Hi", '!' ) == "!Hi!" ); assert ( quote ( "Hi!", '!' ) == R"(!Hi\!!)" ); round_trip ( L"Hi" ); round_trip_ws ( L"Hi" ); round_trip_d ( L"Hi", '!' ); round_trip_e ( L"Hi", '!' ); assert ( quote ( L"Hi", '!' ) == L"!Hi!" ); assert ( quote ( L"Hi!", '!' ) == LR"(!Hi\!!)" ); round_trip ( "Hi Mom" ); round_trip_ws ( "Hi Mom" ); round_trip ( L"Hi Mom" ); round_trip_ws ( L"Hi Mom" ); assert ( quote ( "" ) == "\"\"" ); assert ( quote ( L"" ) == L"\"\"" ); assert ( quote ( "a" ) == "\"a\"" ); assert ( quote ( L"a" ) == L"\"a\"" ); // missing end quote - must not hang assert ( unquote ( "\"abc" ) == "abc" ); assert ( unquote ( L"\"abc" ) == L"abc" ); assert ( unquote ( "abc" ) == "abc" ); // no delimiter assert ( unquote ( L"abc" ) == L"abc" ); // no delimiter assert ( unquote ( "abc def" ) == "abc" ); // no delimiter assert ( unquote ( L"abc def" ) == L"abc" ); // no delimiter assert ( unquote ( "" ) == "" ); // nothing there assert ( unquote ( L"" ) == L"" ); // nothing there test_padding (); } #else int main() {} #endif
mxOBS/deb-pkg_trusty_chromium-browser
third_party/libc++/trunk/test/input.output/iostream.format/quoted.manip/quoted.pass.cpp
C++
bsd-3-clause
5,616
/* * Planck.js v0.1.34 * * Copyright (c) 2016-2017 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.play() : 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.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; }); viewer.scale(1, -1); 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) { 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) { if (mouseJoint) { mouseJoint.setTarget(point); } mouseMove.x = point.x; mouseMove.y = point.y; }).on(Stage.Mouse.END, function(point) { 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) { 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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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; } 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.wAdd(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.wAdd(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 node = this.m_fixtureList; var found = false; while (node != null) { if (node == fixture) { node = 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.mul(this.m_xf, localPoint); }; Body.prototype.getWorldVector = function(localVector) { return Rot.mul(this.m_xf.q, localVector); }; Body.prototype.getLocalPoint = function(worldPoint) { return Transform.mulT(this.m_xf, worldPoint); }; Body.prototype.getLocalVector = function(worldVector) { return Rot.mulT(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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var DEBUG_SOLVER = false; var common = require("./util/common"); 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; this.next; this.other; } function Contact(fA, indexA, fB, indexB, evaluateFcn) { this.m_nodeA = new ContactEdge(this); this.m_nodeB = new ContactEdge(this); this.m_fixtureA = fA; this.m_fixtureB = fB; this.m_indexA = indexA; this.m_indexB = indexB; this.m_evaluateFcn = evaluateFcn; this.m_manifold = new Manifold(); 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 = []; this.v_normal = Vec2.zero(); this.v_normalMass = new Mat22(); this.v_K = new Mat22(); this.v_pointCount; this.v_tangentSpeed; this.v_friction; this.v_restitution; this.v_invMassA; this.v_invMassB; this.v_invIA; this.v_invIB; this.p_localPoints = []; this.p_localNormal = Vec2.zero(); this.p_localPoint = Vec2.zero(); this.p_localCenterA = Vec2.zero(); this.p_localCenterB = Vec2.zero(); this.p_type; this.p_radiusA; this.p_radiusB; this.p_pointCount; this.p_invMassA; this.p_invMassB; this.p_invIA; this.p_invIB; } 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.getManifold(); 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; DEBUG && common.debug("pc", 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 = Vec2.clone(bodyA.m_sweep.localCenter); this.p_localCenterB = Vec2.clone(bodyB.m_sweep.localCenter); this.p_radiusA = shapeA.m_radius; this.p_radiusB = shapeB.m_radius; this.p_type = manifold.type; this.p_localNormal = Vec2.clone(manifold.localNormal); this.p_localPoint = Vec2.clone(manifold.localPoint); this.p_pointCount = pointCount; for (var j = 0; j < pointCount; ++j) { var cp = manifold.points[j]; var vcp = this.v_points[j] = new VelocityConstraintPoint(); 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] = Vec2.clone(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(); return this.m_manifold.getWorldManifold(worldManifold, bodyA.getTransform(), shapeA.m_radius, bodyB.getTransform(), shapeB.m_radius); }; 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); }; 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 = new Manifold(); 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 == false && touching == true && listener) { listener.beginContact(this); } if (wasTouching == true && touching == false && listener) { listener.endContact(this); } if (sensor == false && 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); }; 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 = Vec2.clone(this.p_localCenterA); var localCenterB = Vec2.clone(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 = Vec2.clone(positionA.c); var aA = positionA.a; var cB = Vec2.clone(positionB.c); var aB = positionB.a; var minSeparation = 0; for (var j = 0; j < this.p_pointCount; ++j) { var xfA = Transform.identity(); var xfB = Transform.identity(); xfA.q.set(aA); xfB.q.set(aB); xfA.p = Vec2.sub(cA, Rot.mul(xfA.q, localCenterA)); xfB.p = Vec2.sub(cB, Rot.mul(xfB.q, localCenterB)); var normal, point, separation; switch (this.p_type) { case Manifold.e_circles: var pointA = Transform.mul(xfA, this.p_localPoint); var pointB = Transform.mul(xfB, this.p_localPoints[0]); normal = Vec2.sub(pointB, pointA); normal.normalize(); point = Vec2.wAdd(.5, pointA, .5, pointB); separation = Vec2.dot(Vec2.sub(pointB, pointA), normal) - this.p_radiusA - this.p_radiusB; break; case Manifold.e_faceA: normal = Rot.mul(xfA.q, this.p_localNormal); var planePoint = Transform.mul(xfA, this.p_localPoint); var clipPoint = Transform.mul(xfB, this.p_localPoints[j]); separation = Vec2.dot(Vec2.sub(clipPoint, planePoint), normal) - this.p_radiusA - this.p_radiusB; point = clipPoint; break; case Manifold.e_faceB: normal = Rot.mul(xfB.q, this.p_localNormal); var planePoint = Transform.mul(xfB, this.p_localPoint); var clipPoint = Transform.mul(xfA, this.p_localPoints[j]); separation = Vec2.dot(Vec2.sub(clipPoint, planePoint), normal) - this.p_radiusA - this.p_radiusB; point = clipPoint; normal.mul(-1); break; } var rA = Vec2.sub(point, cA); var rB = Vec2.sub(point, cB); 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.cross(rA, normal); var rnB = Vec2.cross(rB, normal); var K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; var impulse = K > 0 ? -C / K : 0; var P = Vec2.mul(impulse, normal); cA.wSub(mA, P); aA -= iA * Vec2.cross(rA, P); cB.wAdd(mB, P); aB += iB * Vec2.cross(rB, P); } positionA.c.set(cA); positionA.a = aA; positionB.c.set(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; } 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.getManifold(); var mA = this.v_invMassA; var mB = this.v_invMassB; var iA = this.v_invIA; var iB = this.v_invIB; var localCenterA = Vec2.clone(this.p_localCenterA); var localCenterB = Vec2.clone(this.p_localCenterB); var cA = Vec2.clone(positionA.c); var aA = positionA.a; var vA = Vec2.clone(velocityA.v); var wA = velocityA.w; var cB = Vec2.clone(positionB.c); var aB = positionB.a; var vB = Vec2.clone(velocityB.v); var wB = velocityB.w; ASSERT && common.assert(manifold.pointCount > 0); var xfA = Transform.identity(); var xfB = Transform.identity(); xfA.q.set(aA); xfB.q.set(aB); xfA.p.wSet(1, cA, -1, Rot.mul(xfA.q, localCenterA)); xfB.p.wSet(1, cB, -1, Rot.mul(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.set(Vec2.sub(worldManifold.points[j], cA)); vcp.rB.set(Vec2.sub(worldManifold.points[j], cB)); DEBUG && common.debug("vcp.rA", worldManifold.points[j].x, worldManifold.points[j].y, cA.x, cA.y, vcp.rA.x, vcp.rA.y); var rnA = Vec2.cross(vcp.rA, this.v_normal); var rnB = Vec2.cross(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.cross(this.v_normal, 1); var rtA = Vec2.cross(vcp.rA, tangent); var rtB = Vec2.cross(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.cross(wB, vcp.rB)) - Vec2.dot(this.v_normal, vA) - Vec2.dot(this.v_normal, Vec2.cross(wA, vcp.rA)); 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.cross(vcp1.rA, this.v_normal); var rn1B = Vec2.cross(vcp1.rB, this.v_normal); var rn2A = Vec2.cross(vcp2.rA, this.v_normal); var rn2B = Vec2.cross(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; DEBUG && common.debug("k1x2: ", k11, k22, k12, mA, mB, iA, rn1A, rn2A, iB, rn1B, rn2B); 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; }; 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 = Vec2.clone(velocityA.v); var wA = velocityA.w; var vB = Vec2.clone(velocityB.v); var wB = velocityB.w; var normal = this.v_normal; var tangent = Vec2.cross(normal, 1); for (var j = 0; j < this.v_pointCount; ++j) { var vcp = this.v_points[j]; var P = Vec2.wAdd(vcp.normalImpulse, normal, vcp.tangentImpulse, tangent); DEBUG && common.debug(iA, iB, vcp.rA.x, vcp.rA.y, vcp.rB.x, vcp.rB.y, P.x, P.y); wA -= iA * Vec2.cross(vcp.rA, P); vA.wSub(mA, P); wB += iB * Vec2.cross(vcp.rB, P); vB.wAdd(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; } }; 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 = Vec2.clone(velocityA.v); var wA = velocityA.w; var vB = Vec2.clone(velocityB.v); var wB = velocityB.w; var normal = this.v_normal; var tangent = Vec2.cross(normal, 1); 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 = Vec2.zero(); dv.wAdd(1, vB, 1, Vec2.cross(wB, vcp.rB)); dv.wSub(1, vA, 1, Vec2.cross(wA, vcp.rA)); 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.mul(lambda, tangent); vA.wSub(mA, P); wA -= iA * Vec2.cross(vcp.rA, P); vB.wAdd(mB, P); wB += iB * Vec2.cross(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 = Vec2.zero(); dv.wAdd(1, vB, 1, Vec2.cross(wB, vcp.rB)); dv.wSub(1, vA, 1, Vec2.cross(wA, vcp.rA)); 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.mul(lambda, normal); vA.wSub(mA, P); wA -= iA * Vec2.cross(vcp.rA, P); vB.wAdd(mB, P); wB += iB * Vec2.cross(vcp.rB, P); } } else { var vcp1 = this.v_points[0]; var vcp2 = this.v_points[1]; var a = Vec2.neo(vcp1.normalImpulse, vcp2.normalImpulse); ASSERT && common.assert(a.x >= 0 && a.y >= 0); var dv1 = Vec2.zero().add(vB).add(Vec2.cross(wB, vcp1.rB)).sub(vA).sub(Vec2.cross(wA, vcp1.rA)); var dv2 = Vec2.zero().add(vB).add(Vec2.cross(wB, vcp2.rB)).sub(vA).sub(Vec2.cross(wA, vcp2.rA)); var vn1 = Vec2.dot(dv1, normal); var vn2 = Vec2.dot(dv2, normal); var b = Vec2.neo(vn1 - vcp1.velocityBias, vn2 - vcp2.velocityBias); b.sub(Mat22.mul(this.v_K, a)); var k_errorTol = .001; for (;;) { var x = Vec2.neg(Mat22.mul(this.v_normalMass, b)); if (x.x >= 0 && x.y >= 0) { var d = Vec2.sub(x, a); var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.wSub(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.wAdd(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(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 = Dot(dv1, normal); vn2 = Dot(dv2, normal); ASSERT && common.assert(Abs(vn1 - vcp1.velocityBias) < k_errorTol); ASSERT && common.assert(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); var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.wSub(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.wAdd(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(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); var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.wSub(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.wAdd(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(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); var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.wSub(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.wAdd(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(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 = []; 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 = new Contact(fixtureA, indexA, fixtureB, indexB, evaluateFcn); } else if (evaluateFcn = s_registers[typeB] && s_registers[typeB][typeA]) { contact = new Contact(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() == false && fixtureB.isSensor() == false) { 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() == false && fixtureB.isSensor() == false) { 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); } }; },{"./Manifold":6,"./Settings":7,"./collision/Distance":13,"./common/Mat22":16,"./common/Math":18,"./common/Rot":20,"./common/Transform":22,"./common/Vec2":23,"./util/common":51}],4:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Fixture; var common = require("./util/common"); var options = require("./util/options"); 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/Vec2":23,"./util/common":51,"./util/options":53}],5:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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 JointDef = { 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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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; this.localNormal = Vec2.zero(); this.localPoint = Vec2.zero(); this.points = [ new ManifoldPoint(), new ManifoldPoint() ]; this.pointCount = 0; } function ManifoldPoint() { this.localPoint = Vec2.zero(); this.normalImpulse = 0; this.tangentImpulse = 0; this.id = new ContactID(); } function ContactID() { this.cf = new ContactFeature(); this.key; } ContactID.prototype.set = function(o) { this.key = o.key; this.cf.set(o.cf); }; function ContactFeature() { this.indexA; this.indexB; this.typeA; this.typeB; } 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.mul(xfA, this.localPoint); var pointB = Transform.mul(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.mul(xfA.q, this.localNormal); var planePoint = Transform.mul(xfA, this.localPoint); DEBUG && common.debug("faceA", this.localPoint.x, this.localPoint.y, this.localNormal.x, this.localNormal.y, normal.x, normal.y); for (var i = 0; i < this.pointCount; ++i) { var clipPoint = Transform.mul(xfB, this.points[i].localPoint); var cA = Vec2.clone(clipPoint).wAdd(radiusA - Vec2.dot(Vec2.sub(clipPoint, planePoint), normal), normal); var cB = Vec2.clone(clipPoint).wSub(radiusB, normal); points[i] = Vec2.mid(cA, cB); separations[i] = Vec2.dot(Vec2.sub(cB, cA), normal); DEBUG && common.debug(i, this.points[i].localPoint.x, this.points[i].localPoint.y, planePoint.x, planePoint.y, xfA.p.x, xfA.p.y, xfA.q.c, xfA.q.s, xfB.p.x, xfB.p.y, xfB.q.c, xfB.q.s, radiusA, radiusB, clipPoint.x, clipPoint.y, cA.x, cA.y, cB.x, cB.y, separations[i], points[i].x, points[i].y); } points.length = this.pointCount; separations.length = this.pointCount; break; case Manifold.e_faceB: normal = Rot.mul(xfB.q, this.localNormal); var planePoint = Transform.mul(xfB, this.localPoint); for (var i = 0; i < this.pointCount; ++i) { var clipPoint = Transform.mul(xfA, this.points[i].localPoint); var cB = Vec2.zero().wSet(1, clipPoint, radiusB - Vec2.dot(Vec2.sub(clipPoint, planePoint), normal), normal); var cA = Vec2.zero().wSet(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); }; 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.wSet(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 = ContactFeature.e_vertex; vOut[numOut].id.cf.typeB = ContactFeature.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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Solver; module.exports.TimeStep = TimeStep; var Settings = require("./Settings"); var common = require("./util/common"); var Timer = require("./util/Timer"); 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 Profile() { this.solveInit; this.solveVelocity; this.solvePosition; } 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_profile = new Profile(); 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; var profile = this.m_profile; profile.solveInit = 0; profile.solveVelocity = 0; profile.solvePosition = 0; 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 profile = this.m_profile; var gravity = world.m_gravity; var allowSleep = world.m_allowSleep; var timer = Timer.now(); 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; DEBUG && common.debug("P: ", a, c.x, c.y, w, v.x, v.y); if (body.isDynamic()) { v.wAdd(h * body.m_gravityScale, gravity); v.wAdd(h * body.m_invMass, body.m_force); w += h * body.m_invI * body.m_torque; DEBUG && common.debug("N: " + h, body.m_gravityScale, gravity.x, gravity.y, body.m_invMass, body.m_force.x, body.m_force.y); v.mul(1 / (1 + h * body.m_linearDamping)); w *= 1 / (1 + h * body.m_angularDamping); } common.debug("A: ", a, c.x, c.y, w, v.x, v.y); body.c_position.c = c; body.c_position.a = a; body.c_velocity.v = v; body.c_velocity.w = w; } timer = Timer.now(); 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: "); profile.solveInit = Timer.diff(timer); timer = Timer.now(); for (var i = 0; i < step.velocityIterations; ++i) { DEBUG && common.debug("--", 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); } profile.solveVelocity = Timer.diff(timer); 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.wAdd(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: "); timer = Timer.now(); 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(); } profile.solvePosition = Timer.diff(timer); 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) { DEBUG && common.debug("TOI++++++World"); var world = this.m_world; var profile = this.m_profile; DEBUG && common.debug("Z:", world.m_stepComplete); if (world.m_stepComplete) { for (var b = world.m_bodyList; b; b = b.m_next) { b.m_islandFlag = false; b.m_sweep.alpha0 = 0; DEBUG && common.debug("b.alpha0:", b.m_sweep.alpha0); } 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; } } if (DEBUG) for (var c = world.m_contactList; c; c = c.m_next) { DEBUG && common.debug("X:", c.m_toiFlag); } for (;;) { DEBUG && common.debug(";;"); var minContact = null; var minAlpha = 1; for (var c = world.m_contactList; c; c = c.m_next) { DEBUG && common.debug("alpha0::", c.getFixtureA().getBody().m_sweep.alpha0, c.getFixtureB().getBody().m_sweep.alpha0); if (c.isEnabled() == false) { continue; } DEBUG && common.debug("toiCount:", c.m_toiCount, Settings.maxSubSteps); if (c.m_toiCount > Settings.maxSubSteps) { continue; } DEBUG && common.debug("toiFlag:", c.m_toiFlag); var alpha = 1; if (c.m_toiFlag) { alpha = c.m_toi; } else { var fA = c.getFixtureA(); var fB = c.getFixtureB(); DEBUG && common.debug("sensor:", fA.isSensor(), fB.isSensor()); 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(); DEBUG && common.debug("awakestatic:", bA.isAwake(), bA.isStatic()); DEBUG && common.debug("awakestatic:", bB.isAwake(), bB.isStatic()); DEBUG && common.debug("active:", activeA, activeB); if (activeA == false && activeB == false) { continue; } DEBUG && common.debug("alpha:", alpha, bA.m_sweep.alpha0, bB.m_sweep.alpha0); var collideA = bA.isBullet() || !bA.isDynamic(); var collideB = bB.isBullet() || !bB.isDynamic(); DEBUG && common.debug("collide:", collideA, collideB); 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); } DEBUG && common.debug("alpha0:", alpha0, bA.m_sweep.alpha0, bB.m_sweep.alpha0); ASSERT && common.assert(alpha0 < 1); var indexA = c.getChildIndexA(); var indexB = c.getChildIndexB(); var sweepA = bA.m_sweep; var sweepB = bB.m_sweep; DEBUG && common.debug("sweepA", sweepA.localCenter.x, sweepA.localCenter.y, sweepA.c.x, sweepA.c.y, sweepA.a, sweepA.alpha0, sweepA.c0.x, sweepA.c0.y, sweepA.a0); DEBUG && common.debug("sweepB", sweepB.localCenter.x, sweepB.localCenter.y, sweepB.c.x, sweepB.c.y, sweepB.a, sweepB.alpha0, sweepB.c0.x, sweepB.c0.y, sweepB.a0); 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; DEBUG && common.debug("state:", output.state, TOIOutput.e_touching); 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; } DEBUG && common.debug("minAlpha:", minAlpha, alpha); if (alpha < minAlpha) { minContact = c; minAlpha = alpha; } } DEBUG && common.debug("minContact:", minContact == null, 1 - 10 * Math.EPSILON < minAlpha, minAlpha); 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; DEBUG && common.debug("== ", a, c.x, c.y, w, v.x, v.y); } }; Solver.prototype.solveIslandTOI = function(subStep, toiA, toiB) { DEBUG && common.debug("TOI++++++Island"); var world = this.m_world; var profile = this.m_profile; 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.wAdd(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(); DEBUG && common.debug("TOI------Island"); }; 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/Timer":50,"./util/common":51}],10:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = World; var options = require("./util/options"); var common = require("./util/common"); var Timer = require("./util/Timer"); 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; 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/Timer":50,"./util/common":51,"./util/options":53}],11:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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.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) { b = b || this; this.lowerBound.set(Math.min(a.lowerBound.x, b.lowerBound.x), Math.min(a.lowerBound.y, b.lowerBound.y)); this.upperBound.set(Math.max(a.upperBound.x, b.upperBound.x), Math.max(a.upperBound.y, b.upperBound.y)); }; 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 hB = b.upperBound.y - b.lowerBound.y; 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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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 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"); 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; DEBUG && common.debug("cahce:", cache.metric, cache.count); DEBUG && common.debug("proxyA:", proxyA.m_count); DEBUG && common.debug("proxyB:", proxyB.m_count); DEBUG && common.debug("xfA:", xfA.p.x, xfA.p.y, xfA.q.c, xfA.q.s); DEBUG && common.debug("xfB:", xfB.p.x, xfB.p.y, xfB.q.c, xfB.q.s); var simplex = new Simplex(); simplex.readCache(cache, proxyA, xfA, proxyB, xfB); DEBUG && common.debug("cache", simplex.print()); 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.mulT(xfA.q, Vec2.neg(d))); vertex.wA = Transform.mul(xfA, proxyA.getVertex(vertex.indexA)); vertex.indexB = proxyB.getSupport(Rot.mulT(xfB.q, d)); vertex.wB = Transform.mul(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; DEBUG && common.debug("Distance:", output.distance, output.pointA.x, output.pointA.y, output.pointB.x, output.pointB.y); 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.wAdd(rA, normal); output.pointB.wSub(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.mul(transformA, wALocal); v.wB = Transform.mul(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.mul(transformA, wALocal); v.wB = Transform.mul(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.wAdd(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: DEBUG && common.debug("case1", this.print()); pA.set(this.m_v1.wA); pB.set(this.m_v1.wB); break; case 2: DEBUG && common.debug("case2", this.print()); pA.wSet(this.m_v1.a, this.m_v1.wA, this.m_v2.a, this.m_v2.wA); pB.wSet(this.m_v1.a, this.m_v1.wB, this.m_v2.a, this.m_v2.wB); break; case 3: DEBUG && common.debug("case3", this.print()); pA.wSet(this.m_v1.a, this.m_v1.wA, this.m_v2.a, this.m_v2.wA); pA.wAdd(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/Timer":50,"../util/common":51}],14:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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; 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; this.m_pool = new Pool({ create: function() { return new TreeNode(); } }); } 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 = this.m_pool.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) { this.m_pool.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); AABB.extend(node.aabb, 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 = new AABB(); combinedAABB.combine(index.aabb, leafAABB); var combinedArea = combinedAABB.getPerimeter(); var cost = 2 * combinedArea; var inheritanceCost = 2 * (combinedArea - area); var cost1; if (child1.isLeaf()) { var aabb = new AABB(); aabb.combine(leafAABB, child1.aabb); cost1 = aabb.getPerimeter() + inheritanceCost; } else { var aabb = new AABB(); aabb.combine(leafAABB, child1.aabb); var oldArea = child1.aabb.getPerimeter(); var newArea = aabb.getPerimeter(); cost1 = newArea - oldArea + inheritanceCost; } var cost2; if (child2.isLeaf()) { var aabb = new AABB(); aabb.combine(leafAABB, child2.aabb); cost2 = aabb.getPerimeter() + inheritanceCost; } else { var aabb = new AABB(); aabb.combine(leafAABB, child2.aabb); var oldArea = child2.aabb.getPerimeter(); var newArea = aabb.getPerimeter(); cost2 = newArea - oldArea + inheritanceCost; } 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); var aabb = new AABB(); aabb.combine(child1.aabb, child2.aabb); ASSERT && common.assert(AABB.areEqual(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 = new AABB(); b.combine(aabbi, aabbj); var cost = b.getPerimeter(); if (cost < minCost) { iMin = i; jMin = j; minCost = cost; } } } 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.lowerBound.x -= newOrigin.x; aabb.lowerBound.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.wAdd(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.wAdd(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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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; DEBUG && common.debug("sweepA", sweepA.localCenter.x, sweepA.localCenter.y, sweepA.c.x, sweepA.c.y, sweepA.a, sweepA.alpha0, sweepA.c0.x, sweepA.c0.y, sweepA.a0); DEBUG && common.debug("sweepB", sweepB.localCenter.x, sweepB.localCenter.y, sweepB.c.x, sweepB.c.y, sweepB.a, sweepB.alpha0, sweepB.c0.x, sweepB.c0.y, sweepB.a0); 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); DEBUG && common.debug("xfA:", xfA.p.x, xfA.p.y, xfA.q.c, xfA.q.s); DEBUG && common.debug("xfB:", xfB.p.x, xfB.p.y, xfB.q.c, xfB.q.s); distanceInput.transformA = xfA; distanceInput.transformB = xfB; var distanceOutput = new DistanceOutput(); Distance(distanceOutput, cache, distanceInput); DEBUG && common.debug("distance:", distanceOutput.distance); 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; DEBUG && common.debug("s1:", s1, target, tolerance, t1); 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.mul(xfA, localPointA); var pointB = Transform.mul(xfB, localPointB); this.m_axis.wSet(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.mul(xfB.q, this.m_axis); this.m_localPoint = Vec2.mid(localPointB1, localPointB2); var pointB = Transform.mul(xfB, this.m_localPoint); var localPointA = proxyA.getVertex(cache.indexA[0]); var pointA = Transform.mul(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.mul(xfA.q, this.m_axis); this.m_localPoint = Vec2.mid(localPointA1, localPointA2); var pointA = Transform.mul(xfA, this.m_localPoint); var localPointB = this.m_proxyB.getVertex(cache.indexB[0]); var pointB = Transform.mul(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.mulT(xfA.q, this.m_axis); var axisB = Rot.mulT(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.mul(xfA, localPointA); var pointB = Transform.mul(xfB, localPointB); var sep = Vec2.dot(pointB, this.m_axis) - Vec2.dot(pointA, this.m_axis); return sep; } case e_faceA: { var normal = Rot.mul(xfA.q, this.m_axis); var pointA = Transform.mul(xfA, this.m_localPoint); if (find) { var axisB = Rot.mulT(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.mul(xfB, localPointB); var sep = Vec2.dot(pointB, normal) - Vec2.dot(pointA, normal); return sep; } case e_faceB: { var normal = Rot.mul(xfB.q, this.m_axis); var pointB = Transform.mul(xfB, this.m_localPoint); if (find) { var axisA = Rot.mulT(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.mul(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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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.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.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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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.add = function(a, b) { ASSERT && Mat33.assert(a); ASSERT && Mat33.assert(b); return new Vec3(a.x + b.x, a.y + b.y, a.z + b.z); }; },{"../util/common":51,"./Math":18,"./Vec2":23,"./Vec3":24}],18:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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.mul(xf.q, p))); return xf; }; },{"./Rot":20,"./Vec2":23}],20:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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); ojb.s = rot.s; ojb.c = rot.c; return ojb; }; Rot.identity = function(rot) { ASSERT && Rot.assert(rot); 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; }; 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.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); } }; },{"../util/common":51,"./Math":18,"./Vec2":23}],21:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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.mul(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.mul(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.wSet(1 - beta, this.c0, beta, this.c); xf.p.sub(Rot.mul(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.wSet(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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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(); }; Transform.prototype.set = function(a, b) { if (Transform.isValid(a)) { 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.mul(a.q, b.q); xf.p = Vec2.add(Rot.mul(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.mulT(a.q, b.q)); xf.p.set(Rot.mulT(a.q, Vec2.sub(b.p, a.p))); return xf; } }; },{"../util/common":51,"./Rot":20,"./Vec2":23}],23:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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, depricated) { ASSERT && Vec2.assert(v); ASSERT && common.assert(!depricated); 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(depricated) { return Vec2.clone(this, depricated); }; 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.wSet = function(a, v, b, w) { ASSERT && Math.assert(a); ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; if (typeof b !== "undefined" || typeof w !== "undefined") { ASSERT && Math.assert(b); ASSERT && Vec2.assert(w); x += b * w.x; y += b * w.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) { ASSERT && Math.assert(a); ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; if (typeof b !== "undefined" || typeof w !== "undefined") { ASSERT && Math.assert(b); ASSERT && Vec2.assert(w); x += b * w.x; y += b * w.y; } this.x += x; this.y += y; return this; }; Vec2.prototype.wSub = function(a, v, b, w) { ASSERT && Math.assert(a); ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; if (typeof b !== "undefined" || typeof w !== "undefined") { ASSERT && Math.assert(b); ASSERT && Vec2.assert(w); x += b * w.x; y += b * w.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.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) { var r = Vec2.zero(); r.wAdd(a, v, b, w); return r; }; 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.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.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.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; }; },{"../util/common":51,"./Math":18}],24:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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.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) { return v == w || 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(m) { 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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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.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/Math":18,"./common/Rot":20,"./common/Sweep":21,"./common/Transform":22,"./common/Vec2":23,"./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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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 DistanceJointDef = { frequencyHz: 0, dampingRatio: 0 }; function DistanceJoint(def, bodyA, anchorA, bodyB, anchorB) { if (!(this instanceof DistanceJoint)) { return new DistanceJoint(def, bodyA, anchorA, bodyB, anchorB); } def = options(def, DistanceJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = DistanceJoint.TYPE; this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchorA); this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchorB); this.m_length = Vec2.distance(anchorB, anchorA); 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) { var F = Vec2.mul(inv_dt * this.m_impulse, this.m_u); return F; }; 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.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(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.wSub(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.wAdd(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.wSub(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.wAdd(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.wSub(this.m_invMassA, P); aA -= this.m_invIA * Vec2.cross(rA, P); cB.wAdd(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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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 FrictionJointDef = { maxForce: 0, maxTorque: 0 }; function FrictionJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof FrictionJoint)) { return new FrictionJoint(def, bodyA, bodyB, anchor); } def = options(def, FrictionJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = FrictionJoint.TYPE; if (anchor) { this.m_localAnchorA = bodyA.getLocalPoint(anchor); this.m_localAnchorB = bodyB.getLocalPoint(anchor); } else { this.m_localAnchorA = Vec2.zero(); this.m_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(IsValid(force) && force >= 0); this.m_maxForce = force; }; FrictionJoint.prototype.getMaxForce = function() { return this.m_maxForce; }; FrictionJoint.prototype.setMaxTorque = function(torque) { ASSERT && common.assert(IsValid(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 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.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(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.wSub(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_angularImpulse); vB.wAdd(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.mul(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.wSub(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.wAdd(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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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 GearJointDef = { 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, GearJointDef); Joint.call(this, def, bodyA, 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; this.m_joint2 = joint2; 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 = 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 = 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.mulT(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 = 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 = 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.mulT(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_ratio = ratio || def.ratio; 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(IsValid(ratio)); this.m_ratio = ratio; }; GearJoint.prototype.setRatio = 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) { var P = this.m_impulse * this.m_JvAC; return inv_dt * P; }; 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.mul(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.mul(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.wAdd(this.m_mA * this.m_impulse, this.m_JvAC); wA += this.m_iA * this.m_impulse * this.m_JwA; vB.wAdd(this.m_mB * this.m_impulse, this.m_JvBD); wB += this.m_iB * this.m_impulse * this.m_JwB; vC.wSub(this.m_mC * this.m_impulse, this.m_JvAC); wC -= this.m_iC * this.m_impulse * this.m_JwC; vD.wSub(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.wAdd(this.m_mA * impulse, this.m_JvAC); wA += this.m_iA * impulse * this.m_JwA; vB.wAdd(this.m_mB * impulse, this.m_JvBD); wB += this.m_iB * impulse * this.m_JwB; vC.wSub(this.m_mC * impulse, this.m_JvAC); wC -= this.m_iC * impulse * this.m_JwC; vD.wSub(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.mul(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 = this.m_localAnchorC - this.m_lcC; var pA = Rot.mulT(qC, Vec2.add(rA, Vec2.sub(cA, cC))); coordinateA = Dot(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.mul(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.mulT(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.wAdd(this.m_mA * impulse, JvAC); aA += this.m_iA * impulse * JwA; cB.wAdd(this.m_mB * impulse, JvBD); aB += this.m_iB * impulse * JwB; cC.wAdd(this.m_mC * impulse, JvAC); aC -= this.m_iC * impulse * JwC; cD.wAdd(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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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 MotorJointDef = { maxForce: 1, maxTorque: 1, correctionFactor: .3 }; function MotorJoint(def, bodyA, bodyB) { if (!(this instanceof MotorJoint)) { return new MotorJoint(def, bodyA, bodyB); } def = options(def, MotorJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = MotorJoint.TYPE; var xB = bodyB.getPosition(); this.m_linearOffset = bodyA.getLocalPoint(xB); 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(IsValid(force) && force >= 0); this.m_maxForce = force; }; MotorJoint.prototype.getMaxForce = function() { return this.m_maxForce; }; MotorJoint.prototype.setMaxTorque = function(torque) { ASSERT && common.assert(IsValid(torque) && torque >= 0); this.m_maxTorque = torque; }; MotorJoint.prototype.getMaxTorque = function() { return this.m_maxTorque; }; MotorJoint.prototype.setCorrectionFactor = function(factor) { ASSERT && common.assert(IsValid(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 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.mul(qA, Vec2.neg(this.m_localCenterA)); this.m_rB = Rot.mul(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.wAdd(1, cB, 1, this.m_rB); this.m_linearError.wSub(1, cA, 1, this.m_rA); this.m_linearError.sub(Rot.mul(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.wSub(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_angularImpulse); vB.wAdd(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.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot.wSub(1, vA, 1, Vec2.cross(wA, this.m_rA)); Cdot.wAdd(inv_h * this.m_correctionFactor, this.m_linearError); var impulse = Vec2.neg(Mat22.mul(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.wSub(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.wAdd(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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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 MouseJointDef = { 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, MouseJointDef); Joint.call(this, def, bodyA, 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 = Vec2.clone(target); this.m_localAnchorB = Transform.mulT(this.m_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.mul(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.wAdd(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.wAdd(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.wAdd(1, this.m_C, this.m_gamma, this.m_impulse); Cdot.neg(); var impulse = Mat22.mul(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.wAdd(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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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 PrismaticJointDef = { 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, PrismaticJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = PrismaticJoint.TYPE; this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchor); this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchor); this.m_localXAxisA = def.localAxisA || bodyA.getLocalVector(axis); this.m_localXAxisA.normalize(); this.m_localYAxisA = Vec2.cross(1, this.m_localXAxisA); this.m_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 = Mul(bA.m_xf.q, this.m_localAnchorA - bA.m_sweep.localCenter); var rB = Mul(bB.m_xf.q, this.m_localAnchorB - bB.m_sweep.localCenter); var p1 = bA.m_sweep.c + rA; var p2 = bB.m_sweep.c + rB; var d = p2 - p1; var axis = Mul(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 = Dot(d, Cross(wA, axis)) + Dot(axis, vB + Cross(wB, rB) - vA - Cross(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 inv_dt * (this.m_impulse.x * this.m_perp + (this.m_motorImpulse + this.m_impulse.z) * this.m_axis); }; 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.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.wAdd(1, cB, 1, rB); d.wSub(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.mul(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.mul(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.wAdd(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.wSub(mA, P); wA -= iA * LA; vB.wAdd(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.zero().wSet(impulse, this.m_axis); var LA = impulse * this.m_a1; var LB = impulse * this.m_a2; vA.wSub(mA, P); wA -= iA * LA; vB.wAdd(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.wAdd(-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.wAdd(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.wSub(mA, P); wA -= iA * LA; vB.wAdd(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.zero().wAdd(df.x, this.m_perp); var LA = df.x * this.m_s1 + df.y; var LB = df.x * this.m_s2 + df.y; vA.wSub(mA, P); wA -= iA * LA; vB.wAdd(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.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.sub(Vec2.add(cB, rB), Vec2.add(cA, rA)); var axis = Rot.mul(qA, this.m_localXAxisA); var a1 = Vec2.cross(Vec2.add(d, rA), axis); var a2 = Vec2.cross(rB, axis); var perp = Rot.mul(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.wAdd(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.wSub(mA, P); aA -= iA * LA; cB.wAdd(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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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); this.m_type = PulleyJoint.TYPE; this.m_groundAnchorA = groundA; this.m_groundAnchorB = groundB; this.m_localAnchorA = bodyA.getLocalPoint(anchorA); this.m_localAnchorB = bodyB.getLocalPoint(anchorB); this.m_lengthA = Vec2.distance(anchorA, groundA); this.m_lengthB = Vec2.distance(anchorB, groundB); this.m_ratio = def.ratio || 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.setRatio = 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 -= newOrigin; this.m_groundAnchorB -= 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 Vec3.mul(inv_dt * this.m_impulse, this.m_uB); }; 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.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(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.wAdd(this.m_invMassA, PA); wA += this.m_invIA * Vec2.cross(this.m_rA, PA); vB.wAdd(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.zero().wSet(-impulse, this.m_uA); var PB = Vec2.zero().wSet(-this.m_ratio * impulse, this.m_uB); vA.wAdd(this.m_invMassA, PA); wA += this.m_invIA * Vec2.cross(this.m_rA, PA); vB.wAdd(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.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(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.zero().wSet(-impulse, uA); var PB = Vec2.zero().wSet(-this.m_ratio * impulse, uB); cA.wAdd(this.m_invMassA, PA); aA += this.m_invIA * Vec2.cross(rA, PA); cB.wAdd(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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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 RevoluteJointDef = { 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, RevoluteJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = RevoluteJoint.TYPE; this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchor); this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchor); this.m_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) { var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); return inv_dt * P; }; 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.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(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.wSub(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_motorImpulse + this.m_impulse.z); vB.wAdd(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.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.wSub(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.wAdd(-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.wAdd(-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.wSub(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + impulse.z); vB.wAdd(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + impulse.z); } else { var Cdot = Vec2.zero(); Cdot.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot.wSub(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.wSub(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.wAdd(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.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var C = Vec2.zero(); C.wAdd(1, cB, 1, rB); C.wSub(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.wSub(mA, impulse); aA -= iA * Vec2.cross(rA, impulse); cB.wAdd(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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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 RopeJointDef = { maxLength: 0 }; function RopeJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof RopeJoint)) { return new RopeJoint(def, bodyA, bodyB, anchor); } def = options(def, RopeJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = RopeJoint.TYPE; this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchor); this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchor); 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) { var F = inv_dt * this.m_impulse * this.m_u; return F; }; 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.wAdd(1, cB, 1, this.m_rB); this.m_u.wSub(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.wSub(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.wAdd(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.wSub(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.wAdd(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.wAdd(1, cB, 1, rB); u.wSub(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.wSub(this.m_invMassA, P); aA -= this.m_invIA * Vec2.cross(rA, P); cB.wAdd(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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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 WeldJointDef = { frequencyHz: 0, dampingRatio: 0 }; function WeldJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof WeldJoint)) { return new WeldJoint(def, bodyA, bodyB, anchor); } def = options(def, WeldJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = WeldJoint.TYPE; this.m_localAnchorA = bodyA.getLocalPoint(anchor); this.m_localAnchorB = bodyB.getLocalPoint(anchor); this.m_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) { var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); return inv_dt * P; }; 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.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(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.wSub(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_impulse.z); vB.wAdd(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.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.wSub(1, vA, 1, Vec2.cross(wA, this.m_rA)); var impulse1 = Vec2.neg(Mat33.mul(this.m_mass, Cdot1)); this.m_impulse.x += impulse1.x; this.m_impulse.y += impulse1.y; var P = Vec2.clone(impulse1); vA.wSub(mA, P); wA -= iA * Vec2.cross(this.m_rA, P); vB.wAdd(mB, P); wB += iB * Vec2.cross(this.m_rB, P); } else { var Cdot1 = Vec2.zero(); Cdot1.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.wSub(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.mul(this.m_mass, Cdot)); this.m_impulse.add(impulse); var P = Vec2.neo(impulse.x, impulse.y); vA.wSub(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + impulse.z); vB.wAdd(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.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(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.wAdd(1, cB, 1, rB); C1.wSub(1, cA, 1, rA); positionError = C1.length(); angularError = 0; var P = Vec2.neg(K.solve22(C1)); cA.wSub(mA, P); aA -= iA * Vec2.cross(rA, P); cB.wAdd(mB, P); aB += iB * Vec2.cross(rB, P); } else { var C1 = Vec2.zero(); C1.wAdd(1, cB, 1, rB); C1.wSub(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.wSub(mA, P); aA -= iA * (Vec2.cross(rA, P) + impulse.z); cB.wAdd(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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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 WheelJointDef = { 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, WheelJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = WheelJoint.TYPE; this.m_localAnchorA = bodyA.getLocalPoint(anchor); this.m_localAnchorB = bodyB.getLocalPoint(anchor); this.m_localXAxisA = bodyA.getLocalVector(axis || Vec2.neo(1, 0)); 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 = pB - pA; var axis = bA.getWorldVector(this.m_localXAxisA); var translation = 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 inv_dt * (this.m_impulse * this.m_ay + this.m_springImpulse * this.m_ax); }; 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.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.wAdd(1, cB, 1, rB); d.wSub(1, cA, 1, rA); { this.m_ay = Rot.mul(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.mul(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.wAdd(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.wSub(this.m_invMassA, P); wA -= this.m_invIA * LA; vB.wAdd(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.zero().wSet(impulse, this.m_ax); var LA = impulse * this.m_sAx; var LB = impulse * this.m_sBx; vA.wSub(mA, P); wA -= iA * LA; vB.wAdd(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.zero().wSet(impulse, this.m_ay); var LA = impulse * this.m_sAy; var LB = impulse * this.m_sBy; vA.wSub(mA, P); wA -= iA * LA; vB.wAdd(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.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.wAdd(1, cB, 1, rB); d.wSub(1, cA, 1, rA); var ay = Rot.mul(qA, this.m_localYAxisA); var sAy = Vec2.cross(Vec2.sub(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.zero().wSet(impulse, ay); var LA = impulse * sAy; var LB = impulse * sBy; cA.wSub(this.m_invMassA, P); aA -= this.m_invIA * LA; cB.wAdd(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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = BoxShape; 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 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.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 (center && "x" in center && "y" in 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.mul(xf, this.m_vertices[i]); this.m_normals[i] = Rot.mul(xf.q, this.m_normals[i]); } } } },{"../Settings":7,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53,"./PolygonShape":48}],40:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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.mul(xf, this.getVertex(childIndex)); var v2 = Transform.mul(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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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.getSupportVertex = function(d) { 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.mul(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.mul(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.mul(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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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.mul(xfA, circleA.m_p); var pB = Transform.mul(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.key = 0; } 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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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.mul(xfB, circleB.m_p); var cLocal = Transform.mulT(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.wSet(.5, v1, .5, v2); manifold.points[0].localPoint = circleB.m_p; manifold.points[0].id.key = 0; 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.wSet(1, cLocal, -1, v1); manifold.localNormal.normalize(); manifold.localPoint = v1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; } else if (u2 <= 0) { if (Vec2.distanceSquared(cLocal, v2) > radius * radius) { return; } manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.wSet(1, cLocal, -1, v2); manifold.localNormal.normalize(); manifold.localPoint.set(v2); manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; } 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.key = 0; } } },{"../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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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.mulT(xfA, Transform.mul(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.key = 0; 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.key = 0; 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.wAdd(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 = n; manifold.localPoint.set(A); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; 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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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) { DEBUG && common.debug("CollideEdgePolygon"); var m_type1, m_type2; var xf = Transform.mulT(xfA, xfB); var centroidB = Transform.mul(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.wSet(-1, normal1); lowerLimit.wSet(-1, normal1); upperLimit.wSet(-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.wSet(-1, normal1); lowerLimit.wSet(-1, normal2); upperLimit.wSet(-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.wSet(-1, normal1); lowerLimit.wSet(-1, normal1); upperLimit.wSet(-1, normal0); } } else { front = offset0 >= 0 && offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.set(normal1); } else { normal.wSet(-1, normal1); lowerLimit.wSet(-1, normal2); upperLimit.wSet(-1, normal0); } } } else if (hasVertex0) { if (convex1) { front = offset0 >= 0 || offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.wSet(-1, normal1); } else { normal.wSet(-1, normal1); lowerLimit.set(normal1); upperLimit.wSet(-1, normal1); } } else { front = offset0 >= 0 && offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.wSet(-1, normal1); } else { normal.wSet(-1, normal1); lowerLimit.set(normal1); upperLimit.wSet(-1, normal0); } } } else if (hasVertex3) { if (convex2) { front = offset1 >= 0 || offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.wSet(-1, normal1); upperLimit.set(normal2); } else { normal.wSet(-1, normal1); lowerLimit.wSet(-1, normal1); upperLimit.set(normal1); } } else { front = offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.wSet(-1, normal1); upperLimit.set(normal1); } else { normal.wSet(-1, normal1); lowerLimit.wSet(-1, normal2); upperLimit.set(normal1); } } } else { front = offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.wSet(-1, normal1); upperLimit.wSet(-1, normal1); } else { normal.wSet(-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.mul(xf, polygonB.m_vertices[i]); polygonBA.normals[i] = Rot.mul(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.wSet(-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.wSet(-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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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); } 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.mulT(xf2, xf1); var bestIndex = 0; var maxSeparation = -Infinity; for (var i = 0; i < count1; ++i) { var n = Rot.mul(xf.q, n1s[i]); var v1 = Transform.mul(xf, v1s[i]); 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; } } FindMaxSeparation._maxSeparation = maxSeparation; FindMaxSeparation._bestIndex = bestIndex; } 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.mulT(xf2.q, Rot.mul(xf1.q, normals1[edge1])); 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.mul(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.mul(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; } 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 = FindMaxSeparation._bestIndex; var separationA = FindMaxSeparation._maxSeparation; if (separationA > totalRadius) return; FindMaxSeparation(polyB, xfB, polyA, xfA); var edgeB = FindMaxSeparation._bestIndex; var separationB = FindMaxSeparation._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 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; 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 = vertices1[iv1]; var v12 = vertices1[iv2]; var localTangent = Vec2.sub(v12, v11); localTangent.normalize(); var localNormal = Vec2.cross(localTangent, 1); var planePoint = Vec2.wAdd(.5, v11, .5, v12); var tangent = Rot.mul(xf1.q, localTangent); var normal = Vec2.cross(tangent, 1); v11 = Transform.mul(xf1, v11); v12 = Transform.mul(xf1, v12); var frontOffset = Vec2.dot(normal, v11); var sideOffset1 = -Vec2.dot(tangent, v11) + totalRadius; var sideOffset2 = Vec2.dot(tangent, v12) + totalRadius; var clipPoints1 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var clipPoints2 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var np; np = Manifold.clipSegmentToLine(clipPoints1, incidentEdge, Vec2.neg(tangent), sideOffset1, iv1); if (np < 2) { return; } np = Manifold.clipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2); if (np < 2) { return; } manifold.localNormal = localNormal; manifold.localPoint = planePoint; var pointCount = 0; for (var i = 0; i < clipPoints2.length; ++i) { var separation = Vec2.dot(normal, clipPoints2[i].v) - frontOffset; if (separation <= totalRadius) { var cp = manifold.points[pointCount]; cp.localPoint.set(Transform.mulT(xf2, clipPoints2[i].v)); 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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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.mulT(xf.q, Vec2.sub(input.p1, xf.p)); var p2 = Rot.mulT(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.mul(xf.q, normal).neg(); } else { output.normal = Rot.mul(xf.q, normal); } return true; }; EdgeShape.prototype.computeAABB = function(aabb, xf, childIndex) { var v1 = Transform.mul(xf, this.m_vertex1); var v2 = Transform.mul(xf, this.m_vertex2); aabb.combinePoints(v1, v2); aabb.extend(this.m_radius); }; EdgeShape.prototype.computeMass = function(massData, density) { massData.mass = 0; massData.center.wSet(.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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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.wAdd(triangleArea * inv3, p1); c.wAdd(triangleArea * inv3, p2); c.wAdd(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) { 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); 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); 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.testPoint = function(xf, p) { var pLocal = Rot.mulT(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.mulT(xf.q, Vec2.sub(input.p1, xf.p)); var p2 = Rot.mulT(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.mul(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.mul(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.wAdd(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.wSet(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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Pool; function Pool(opts) { var _list = []; var _max = opts.max || Infinity; var _createFn = opts.create; var _outFn = opts.allocate; var _inFn = opts.release; var _discardFn = opts.discard; 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 _list.length; }; this.allocate = function() { var item; if (_list.length > 0) { item = _list.shift(); } else { _createCount++; if (typeof _createFn === "function") { item = _createFn(); } else { item = {}; } } _outCount++; if (typeof _outFn === "function") { _outFn(item); } return item; }; this.release = function(item) { if (_list.length < _max) { _inCount++; if (typeof _inFn === "function") { _inFn(item); } _list.push(item); } else { _discardCount++; if (typeof _discardFn === "function") { item = _discardFn(item); } } }; this.toString = function() { return " +" + _createCount + " >" + _outCount + " <" + _inCount + " -" + _discardCount + " =" + _list.length + "/" + _max; }; } },{}],50:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; 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 next = this._tweens[0].tick(this, elapsed, now, last); if (next) { this._tweens.shift(); } 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; } p = typeof this._easing == 'function' ? this._easing(p) : 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) { try { this._done && this._done.call(this._owner); } catch (e) { console.log(e); } return this._next || 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 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'); 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, n = this._tickBefore.length; i < n; i++) { stats.tick++; ticked = this._tickBefore[i].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, n = this._tickAfter.length; i < n; i++) { stats.tick++; ticked = this._tickAfter[i].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.tick(function timer(t) { if ((time -= t) < 0) { this.untick(timer); fn.call(this); } else { return true; } }); }; },{"./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/'); require('../lib/canvas'); 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) });
PeterDaveHello/jsdelivr
files/planck/0.1.34/planck-with-testbed.js
JavaScript
mit
464,606
module.exports = function isString (value) { return Object.prototype.toString.call(value) === '[object String]' }
chrisdavidmills/express-local-library
node_modules/helmet-csp/lib/is-string.js
JavaScript
mit
116
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockitousage.verification; import static org.mockito.Mockito.*; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.verification.NoInteractionsWanted; import org.mockitoutil.TestBase; @SuppressWarnings("unchecked") public class NoMoreInteractionsVerificationTest extends TestBase { private LinkedList mock; @Before public void setup() { mock = mock(LinkedList.class); } @Test public void shouldStubbingNotRegisterRedundantInteractions() throws Exception { when(mock.add("one")).thenReturn(true); when(mock.add("two")).thenReturn(true); mock.add("one"); verify(mock).add("one"); verifyNoMoreInteractions(mock); } @Test public void shouldVerifyWhenWantedNumberOfInvocationsUsed() throws Exception { mock.add("one"); mock.add("one"); mock.add("one"); verify(mock, times(3)).add("one"); verifyNoMoreInteractions(mock); } @Test public void shouldVerifyNoInteractionsAsManyTimesAsYouWant() throws Exception { verifyNoMoreInteractions(mock); verifyNoMoreInteractions(mock); verifyZeroInteractions(mock); verifyZeroInteractions(mock); } @Test public void shouldFailZeroInteractionsVerification() throws Exception { mock.clear(); try { verifyZeroInteractions(mock); fail(); } catch (NoInteractionsWanted e) {} } @Test public void shouldFailNoMoreInteractionsVerification() throws Exception { mock.clear(); try { verifyNoMoreInteractions(mock); fail(); } catch (NoInteractionsWanted e) {} } @Test public void shouldPrintAllInvocationsWhenVerifyingNoMoreInvocations() throws Exception { mock.add(1); mock.add(2); mock.clear(); verify(mock).add(2); try { verifyNoMoreInteractions(mock); fail(); } catch (NoInteractionsWanted e) { assertContains("list of all invocations", e.getMessage()); } } @Test public void shouldNotContainAllInvocationsWhenSingleUnwantedFound() throws Exception { mock.add(1); try { verifyNoMoreInteractions(mock); fail(); } catch (NoInteractionsWanted e) { assertNotContains("list of all invocations", e.getMessage()); } } @Test public void shouldVerifyOneMockButFailOnOther() throws Exception { List list = mock(List.class); Map map = mock(Map.class); list.add("one"); list.add("one"); map.put("one", 1); verify(list, times(2)).add("one"); verifyNoMoreInteractions(list); try { verifyZeroInteractions(map); fail(); } catch (NoInteractionsWanted e) {} } @SuppressWarnings("all") @Test(expected=MockitoException.class) public void verifyNoMoreInteractionsShouldScreamWhenNullPassed() throws Exception { verifyNoMoreInteractions((Object[])null); } }
GeeChao/mockito
test/org/mockitousage/verification/NoMoreInteractionsVerificationTest.java
Java
mit
3,508
/* * The MIT License * Copyright (c) 2012 Microsoft 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. */ package microsoft.exchange.webservices.data.core.request; import microsoft.exchange.webservices.data.core.EwsServiceXmlWriter; import microsoft.exchange.webservices.data.core.EwsUtilities; import microsoft.exchange.webservices.data.core.ExchangeService; import microsoft.exchange.webservices.data.core.XmlElementNames; import microsoft.exchange.webservices.data.core.enumeration.service.error.ServiceErrorHandling; import microsoft.exchange.webservices.data.core.response.ServiceResponse; import microsoft.exchange.webservices.data.core.service.item.Item; import microsoft.exchange.webservices.data.core.enumeration.misc.XmlNamespace; import microsoft.exchange.webservices.data.misc.ItemIdWrapperList; /** * Represents an abstract Move/Copy Item request. * * @param <TResponse> The type of the response. */ public abstract class MoveCopyItemRequest<TResponse extends ServiceResponse> extends MoveCopyRequest<Item, TResponse> { private ItemIdWrapperList itemIds = new ItemIdWrapperList(); private Boolean newItemIds; /** * Validates request. * * @throws Exception the exception */ @Override public void validate() throws Exception { super.validate(); EwsUtilities.validateParam(this.getItemIds(), "ItemIds"); } /** * Initializes a new instance of the class. * * @param service the service * @param errorHandlingMode the error handling mode * @throws Exception on error */ protected MoveCopyItemRequest(ExchangeService service, ServiceErrorHandling errorHandlingMode) throws Exception { super(service, errorHandlingMode); } /** * Writes the ids as XML. * * @param writer the writer * @throws Exception the exception */ @Override protected void writeIdsToXml(EwsServiceXmlWriter writer) throws Exception { this.getItemIds().writeToXml(writer, XmlNamespace.Messages, XmlElementNames.ItemIds); if (this.getReturnNewItemIds() != null) { writer.writeElementValue( XmlNamespace.Messages, XmlElementNames.ReturnNewItemIds, this.getReturnNewItemIds()); } } /** * Gets the expected response message count. * * @return Number of expected response messages. */ @Override protected int getExpectedResponseMessageCount() { return this.getItemIds().getCount(); } /** * Gets the item ids. * * @return the item ids */ public ItemIdWrapperList getItemIds() { return this.itemIds; } protected Boolean getReturnNewItemIds() { return this.newItemIds; } public void setReturnNewItemIds(Boolean value) { this.newItemIds = value; } }
KatharineYe/ews-java-api
src/main/java/microsoft/exchange/webservices/data/core/request/MoveCopyItemRequest.java
Java
mit
3,795
import { Teammates } from "../../"; export = Teammates;
georgemarshall/DefinitelyTyped
types/carbon__pictograms-react/lib/teammates/index.d.ts
TypeScript
mit
57
self.description = "Install a package from a sync db with fnmatch'ed NoExtract" sp = pmpkg("dummy") sp.files = ["bin/dummy", "usr/share/man/man8", "usr/share/man/man1/dummy.1"] self.addpkg2db("sync", sp) self.option["NoExtract"] = ["usr/share/man/*"] self.args = "-S %s" % sp.name self.addrule("PACMAN_RETCODE=0") self.addrule("PKG_EXIST=dummy") self.addrule("FILE_EXIST=bin/dummy") self.addrule("!FILE_EXIST=usr/share/man/man8") self.addrule("!FILE_EXIST=usr/share/man/man1/dummy.1")
kylon/pacman-fakeroot
test/pacman/tests/sync502.py
Python
gpl-2.0
513
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/media/audio_sync_reader.h" #include <algorithm> #include "base/command_line.h" #include "base/memory/shared_memory.h" #include "base/metrics/histogram.h" #include "content/public/common/content_switches.h" #include "media/audio/audio_buffers_state.h" #include "media/audio/audio_parameters.h" using media::AudioBus; namespace content { AudioSyncReader::AudioSyncReader(base::SharedMemory* shared_memory, const media::AudioParameters& params, int input_channels) : shared_memory_(shared_memory), input_channels_(input_channels), mute_audio_(CommandLine::ForCurrentProcess()->HasSwitch( switches::kMuteAudio)), packet_size_(shared_memory_->requested_size()), renderer_callback_count_(0), renderer_missed_callback_count_(0), #if defined(OS_MACOSX) maximum_wait_time_(params.GetBufferDuration() / 2), #else // TODO(dalecurtis): Investigate if we can reduce this on all platforms. maximum_wait_time_(base::TimeDelta::FromMilliseconds(20)), #endif buffer_index_(0) { int input_memory_size = 0; int output_memory_size = AudioBus::CalculateMemorySize(params); if (input_channels_ > 0) { // The input storage is after the output storage. int frames = params.frames_per_buffer(); input_memory_size = AudioBus::CalculateMemorySize(input_channels_, frames); char* input_data = static_cast<char*>(shared_memory_->memory()) + output_memory_size; input_bus_ = AudioBus::WrapMemory(input_channels_, frames, input_data); input_bus_->Zero(); } DCHECK_EQ(packet_size_, output_memory_size + input_memory_size); output_bus_ = AudioBus::WrapMemory(params, shared_memory->memory()); output_bus_->Zero(); } AudioSyncReader::~AudioSyncReader() { if (!renderer_callback_count_) return; // Recording the percentage of deadline misses gives us a rough overview of // how many users might be running into audio glitches. int percentage_missed = 100.0 * renderer_missed_callback_count_ / renderer_callback_count_; UMA_HISTOGRAM_PERCENTAGE( "Media.AudioRendererMissedDeadline", percentage_missed); } // media::AudioOutputController::SyncReader implementations. void AudioSyncReader::UpdatePendingBytes(uint32 bytes) { // Zero out the entire output buffer to avoid stuttering/repeating-buffers // in the anomalous case if the renderer is unable to keep up with real-time. output_bus_->Zero(); socket_->Send(&bytes, sizeof(bytes)); ++buffer_index_; } void AudioSyncReader::Read(const AudioBus* source, AudioBus* dest) { ++renderer_callback_count_; if (!WaitUntilDataIsReady()) { ++renderer_missed_callback_count_; dest->Zero(); return; } // Copy optional synchronized live audio input for consumption by renderer // process. if (input_bus_) { if (source) source->CopyTo(input_bus_.get()); else input_bus_->Zero(); } if (mute_audio_) dest->Zero(); else output_bus_->CopyTo(dest); } void AudioSyncReader::Close() { socket_->Close(); } bool AudioSyncReader::Init() { socket_.reset(new base::CancelableSyncSocket()); foreign_socket_.reset(new base::CancelableSyncSocket()); return base::CancelableSyncSocket::CreatePair(socket_.get(), foreign_socket_.get()); } #if defined(OS_WIN) bool AudioSyncReader::PrepareForeignSocketHandle( base::ProcessHandle process_handle, base::SyncSocket::Handle* foreign_handle) { ::DuplicateHandle(GetCurrentProcess(), foreign_socket_->handle(), process_handle, foreign_handle, 0, FALSE, DUPLICATE_SAME_ACCESS); return (*foreign_handle != 0); } #else bool AudioSyncReader::PrepareForeignSocketHandle( base::ProcessHandle process_handle, base::FileDescriptor* foreign_handle) { foreign_handle->fd = foreign_socket_->handle(); foreign_handle->auto_close = false; return (foreign_handle->fd != -1); } #endif bool AudioSyncReader::WaitUntilDataIsReady() { base::TimeDelta timeout = maximum_wait_time_; const base::TimeTicks start_time = base::TimeTicks::Now(); const base::TimeTicks finish_time = start_time + timeout; // Check if data is ready and if not, wait a reasonable amount of time for it. // // Data readiness is achieved via parallel counters, one on the renderer side // and one here. Every time a buffer is requested via UpdatePendingBytes(), // |buffer_index_| is incremented. Subsequently every time the renderer has a // buffer ready it increments its counter and sends the counter value over the // SyncSocket. Data is ready when |buffer_index_| matches the counter value // received from the renderer. // // The counter values may temporarily become out of sync if the renderer is // unable to deliver audio fast enough. It's assumed that the renderer will // catch up at some point, which means discarding counter values read from the // SyncSocket which don't match our current buffer index. size_t bytes_received = 0; uint32 renderer_buffer_index = 0; while (timeout.InMicroseconds() > 0) { bytes_received = socket_->ReceiveWithTimeout( &renderer_buffer_index, sizeof(renderer_buffer_index), timeout); if (!bytes_received) break; DCHECK_EQ(bytes_received, sizeof(renderer_buffer_index)); if (renderer_buffer_index == buffer_index_) break; // Reduce the timeout value as receives succeed, but aren't the right index. timeout = finish_time - base::TimeTicks::Now(); } // Receive timed out or another error occurred. Receive can timeout if the // renderer is unable to deliver audio data within the allotted time. if (!bytes_received || renderer_buffer_index != buffer_index_) { DVLOG(2) << "AudioSyncReader::WaitUntilDataIsReady() timed out."; base::TimeDelta time_since_start = base::TimeTicks::Now() - start_time; UMA_HISTOGRAM_CUSTOM_TIMES("Media.AudioOutputControllerDataNotReady", time_since_start, base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMilliseconds(1000), 50); return false; } return true; } } // namespace content
qtekfun/htcDesire820Kernel
external/chromium_org/content/browser/renderer_host/media/audio_sync_reader.cc
C++
gpl-2.0
6,518
<?php /** * Discussion * * @package ThematicCoreLibrary * @subpackage Discussion */ /** * Custom callback function to list comments in the Thematic style. * * If you want to use your own comments callback for wp_list_comments, filter list_comments_arg * * @param object $comment * @param array $args * @param int $depth */ function thematic_comments($comment, $args, $depth) { $GLOBALS['comment'] = $comment; $GLOBALS['comment_depth'] = $depth; ?> <li id="comment-<?php comment_ID() ?>" <?php comment_class() ?>> <?php // action hook for inserting content above #comment thematic_abovecomment(); ?> <div class="comment-author vcard"><?php thematic_commenter_link() ?></div> <?php thematic_commentmeta(TRUE); ?> <?php if ( $comment->comment_approved == '0' ) { echo "\t\t\t\t\t" . '<span class="unapproved">'; _e( 'Your comment is awaiting moderation', 'thematic' ); echo ".</span>\n"; } ?> <div class="comment-content"> <?php comment_text() ?> </div> <?php // echo the comment reply link with help from Justin Tadlock http://justintadlock.com/ and Will Norris http://willnorris.com/ if( $args['type'] == 'all' || get_comment_type() == 'comment' ) : comment_reply_link( array_merge( $args, array( 'reply_text' => __( 'Reply','thematic' ), 'login_text' => __( 'Log in to reply.','thematic' ), 'depth' => $depth, 'before' => '<div class="comment-reply-link">', 'after' => '</div>' ))); endif; ?> <?php // action hook for inserting content above #comment thematic_belowcomment() ?> <?php } /** * Custom callback to list pings in the Thematic style * * @param object $comment * @param array $args * @param int $depth */ function thematic_pings($comment, $args, $depth) { $GLOBALS['comment'] = $comment; ?> <li id="comment-<?php comment_ID() ?>" <?php comment_class() ?>> <div class="comment-author"><?php printf(_x('By %1$s on %2$s at %3$s', 'By {$authorlink} on {$date} at {$time}', 'thematic'), get_comment_author_link(), get_comment_date(), get_comment_time() ); edit_comment_link(__('Edit', 'thematic'), ' <span class="meta-sep">|</span>' . "\n\n\t\t\t\t\t\t" . '<span class="edit-link">', '</span>'); ?> </div> <?php if ($comment->comment_approved == '0') { echo "\t\t\t\t\t" . '<span class="unapproved">'; _e( 'Your trackback is awaiting moderation', 'thematic' ); echo ".</span>\n"; } ?> <div class="comment-content"> <?php comment_text() ?> </div> <?php }
bourroush/blog-17aout
wp-content/themes/thematic/library/extensions/discussion.php
PHP
gpl-2.0
2,891
// Generated by CoffeeScript 1.4.0 (function() { var RoomIO; RoomIO = require('./room').RoomIO; exports.RequestIO = (function() { function RequestIO(socket, request, io) { this.socket = socket; this.request = request; this.manager = io; } RequestIO.prototype.broadcast = function(event, message) { return this.socket.broadcast.emit(event, message); }; RequestIO.prototype.emit = function(event, message) { return this.socket.emit(event, message); }; RequestIO.prototype.room = function(room) { return new RoomIO(room, this.socket); }; RequestIO.prototype.join = function(room) { return this.socket.join(room); }; RequestIO.prototype.route = function(route) { return this.manager.route(route, this.request, { trigger: true }); }; RequestIO.prototype.leave = function(room) { return this.socket.leave(room); }; RequestIO.prototype.on = function() { var args; args = Array.prototype.slice.call(arguments, 0); return this.sockets.on.apply(this.socket, args); }; RequestIO.prototype.disconnect = function(callback) { return this.socket.disconnect(callback); }; return RequestIO; })(); }).call(this);
mekinney/transparica
webapp/node_modules/express.io/compiled/request.js
JavaScript
gpl-2.0
1,285
/* * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* @test @bug 4116781 @summary Tests that long (more than 64K) MimeType can be serialized and deserialized. @author gas@sparc.spb.su area=datatransfer @modules java.datatransfer @run main MimeTypeSerializationTest */ import java.awt.datatransfer.DataFlavor; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; public class MimeTypeSerializationTest { public static void main(String[] args) throws Exception { boolean failed = false; try { int len = 70000; char[] longValue = new char[len]; Arrays.fill(longValue, 'v'); DataFlavor longdf = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + "; class=java.lang.String; longParameter=" + new String(longValue)); DataFlavor shortdf = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + "; class=java.lang.String"); ByteArrayOutputStream baos = new ByteArrayOutputStream(100000); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(longdf); oos.writeObject(shortdf); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); DataFlavor longdf2 = (DataFlavor) ois.readObject(); DataFlavor shortdf2 = (DataFlavor) ois.readObject(); ois.close(); failed = !( longdf.getMimeType().equals(longdf2.getMimeType()) && shortdf.getMimeType().equals(shortdf2.getMimeType()) ); if (failed) { System.err.println("deserialized MIME type does not match original one"); } } catch (IOException e) { failed = true; e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } if (failed) { throw new RuntimeException("test failed: serialization attempt failed"); } else { System.err.println("test passed"); } } }
md-5/jdk10
test/jdk/java/awt/datatransfer/DataFlavor/MimeTypeSerializationTest.java
Java
gpl-2.0
3,301
// Copyright 2016 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package interact import ( "testing" gc "gopkg.in/check.v1" ) func TestPackage(t *testing.T) { gc.TestingT(t) }
mjs/juju
cmd/juju/interact/package_test.go
GO
agpl-3.0
211
# -*- coding: utf-8 -*- from . import project_sla from . import analytic_account from . import project_sla_control from . import project_issue from . import project_task from . import report
sergiocorato/project-service
project_sla/__init__.py
Python
agpl-3.0
191
from nose.tools import * from framework.mongo import database as db from scripts.remove_wiki_title_forward_slashes import main from tests.base import OsfTestCase from tests.factories import NodeWikiFactory, ProjectFactory class TestRemoveWikiTitleForwardSlashes(OsfTestCase): def test_forward_slash_is_removed_from_wiki_title(self): project = ProjectFactory() wiki = NodeWikiFactory(node=project) invalid_name = 'invalid/name' db.nodewikipage.update({'_id': wiki._id}, {'$set': {'page_name': invalid_name}}) project.wiki_pages_current['invalid/name'] = project.wiki_pages_current[wiki.page_name] project.wiki_pages_versions['invalid/name'] = project.wiki_pages_versions[wiki.page_name] project.save() main() wiki.reload() assert_equal(wiki.page_name, 'invalidname') assert_in('invalidname', project.wiki_pages_current) assert_in('invalidname', project.wiki_pages_versions) def test_valid_wiki_title(self): project = ProjectFactory() wiki = NodeWikiFactory(node=project) page_name = wiki.page_name main() wiki.reload() assert_equal(page_name, wiki.page_name) assert_in(page_name, project.wiki_pages_current) assert_in(page_name, project.wiki_pages_versions)
rdhyee/osf.io
scripts/tests/test_remove_wiki_title_forward_slashes.py
Python
apache-2.0
1,335
name "runit_test" maintainer "Opscode, Inc." maintainer_email "cookbooks@opscode.com" license "Apache 2.0" description "This cookbook is used with test-kitchen to test the parent, runit cookbok" version "1.0.0"
dialoghq/runit
test/kitchen/cookbooks/runit_test/metadata.rb
Ruby
apache-2.0
258
package hclog import ( "bufio" "bytes" "encoding" "encoding/json" "fmt" "log" "os" "reflect" "runtime" "sort" "strconv" "strings" "sync" "sync/atomic" "time" ) var ( _levelToBracket = map[Level]string{ Debug: "[DEBUG]", Trace: "[TRACE]", Info: "[INFO] ", Warn: "[WARN] ", Error: "[ERROR]", } ) // Given the options (nil for defaults), create a new Logger func New(opts *LoggerOptions) Logger { if opts == nil { opts = &LoggerOptions{} } output := opts.Output if output == nil { output = os.Stderr } level := opts.Level if level == NoLevel { level = DefaultLevel } mtx := opts.Mutex if mtx == nil { mtx = new(sync.Mutex) } ret := &intLogger{ m: mtx, json: opts.JSONFormat, caller: opts.IncludeLocation, name: opts.Name, timeFormat: TimeFormat, w: bufio.NewWriter(output), level: new(int32), } if opts.TimeFormat != "" { ret.timeFormat = opts.TimeFormat } atomic.StoreInt32(ret.level, int32(level)) return ret } // The internal logger implementation. Internal in that it is defined entirely // by this package. type intLogger struct { json bool caller bool name string timeFormat string // this is a pointer so that it's shared by any derived loggers, since // those derived loggers share the bufio.Writer as well. m *sync.Mutex w *bufio.Writer level *int32 implied []interface{} } // Make sure that intLogger is a Logger var _ Logger = &intLogger{} // The time format to use for logging. This is a version of RFC3339 that // contains millisecond precision const TimeFormat = "2006-01-02T15:04:05.000Z0700" // Log a message and a set of key/value pairs if the given level is at // or more severe that the threshold configured in the Logger. func (z *intLogger) Log(level Level, msg string, args ...interface{}) { if level < Level(atomic.LoadInt32(z.level)) { return } t := time.Now() z.m.Lock() defer z.m.Unlock() if z.json { z.logJson(t, level, msg, args...) } else { z.log(t, level, msg, args...) } z.w.Flush() } // Cleanup a path by returning the last 2 segments of the path only. func trimCallerPath(path string) string { // lovely borrowed from zap // nb. To make sure we trim the path correctly on Windows too, we // counter-intuitively need to use '/' and *not* os.PathSeparator here, // because the path given originates from Go stdlib, specifically // runtime.Caller() which (as of Mar/17) returns forward slashes even on // Windows. // // See https://github.com/golang/go/issues/3335 // and https://github.com/golang/go/issues/18151 // // for discussion on the issue on Go side. // // Find the last separator. // idx := strings.LastIndexByte(path, '/') if idx == -1 { return path } // Find the penultimate separator. idx = strings.LastIndexByte(path[:idx], '/') if idx == -1 { return path } return path[idx+1:] } // Non-JSON logging format function func (z *intLogger) log(t time.Time, level Level, msg string, args ...interface{}) { z.w.WriteString(t.Format(z.timeFormat)) z.w.WriteByte(' ') s, ok := _levelToBracket[level] if ok { z.w.WriteString(s) } else { z.w.WriteString("[?????]") } if z.caller { if _, file, line, ok := runtime.Caller(3); ok { z.w.WriteByte(' ') z.w.WriteString(trimCallerPath(file)) z.w.WriteByte(':') z.w.WriteString(strconv.Itoa(line)) z.w.WriteByte(':') } } z.w.WriteByte(' ') if z.name != "" { z.w.WriteString(z.name) z.w.WriteString(": ") } z.w.WriteString(msg) args = append(z.implied, args...) var stacktrace CapturedStacktrace if args != nil && len(args) > 0 { if len(args)%2 != 0 { cs, ok := args[len(args)-1].(CapturedStacktrace) if ok { args = args[:len(args)-1] stacktrace = cs } else { args = append(args, "<unknown>") } } z.w.WriteByte(':') FOR: for i := 0; i < len(args); i = i + 2 { var ( val string raw bool ) switch st := args[i+1].(type) { case string: val = st case int: val = strconv.FormatInt(int64(st), 10) case int64: val = strconv.FormatInt(int64(st), 10) case int32: val = strconv.FormatInt(int64(st), 10) case int16: val = strconv.FormatInt(int64(st), 10) case int8: val = strconv.FormatInt(int64(st), 10) case uint: val = strconv.FormatUint(uint64(st), 10) case uint64: val = strconv.FormatUint(uint64(st), 10) case uint32: val = strconv.FormatUint(uint64(st), 10) case uint16: val = strconv.FormatUint(uint64(st), 10) case uint8: val = strconv.FormatUint(uint64(st), 10) case CapturedStacktrace: stacktrace = st continue FOR case Format: val = fmt.Sprintf(st[0].(string), st[1:]...) default: v := reflect.ValueOf(st) if v.Kind() == reflect.Slice { val = z.renderSlice(v) raw = true } else { val = fmt.Sprintf("%v", st) } } z.w.WriteByte(' ') z.w.WriteString(args[i].(string)) z.w.WriteByte('=') if !raw && strings.ContainsAny(val, " \t\n\r") { z.w.WriteByte('"') z.w.WriteString(val) z.w.WriteByte('"') } else { z.w.WriteString(val) } } } z.w.WriteString("\n") if stacktrace != "" { z.w.WriteString(string(stacktrace)) } } func (z *intLogger) renderSlice(v reflect.Value) string { var buf bytes.Buffer buf.WriteRune('[') for i := 0; i < v.Len(); i++ { if i > 0 { buf.WriteString(", ") } sv := v.Index(i) var val string switch sv.Kind() { case reflect.String: val = sv.String() case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64: val = strconv.FormatInt(sv.Int(), 10) case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: val = strconv.FormatUint(sv.Uint(), 10) default: val = fmt.Sprintf("%v", sv.Interface()) } if strings.ContainsAny(val, " \t\n\r") { buf.WriteByte('"') buf.WriteString(val) buf.WriteByte('"') } else { buf.WriteString(val) } } buf.WriteRune(']') return buf.String() } // JSON logging function func (z *intLogger) logJson(t time.Time, level Level, msg string, args ...interface{}) { vals := map[string]interface{}{ "@message": msg, "@timestamp": t.Format("2006-01-02T15:04:05.000000Z07:00"), } var levelStr string switch level { case Error: levelStr = "error" case Warn: levelStr = "warn" case Info: levelStr = "info" case Debug: levelStr = "debug" case Trace: levelStr = "trace" default: levelStr = "all" } vals["@level"] = levelStr if z.name != "" { vals["@module"] = z.name } if z.caller { if _, file, line, ok := runtime.Caller(3); ok { vals["@caller"] = fmt.Sprintf("%s:%d", file, line) } } args = append(z.implied, args...) if args != nil && len(args) > 0 { if len(args)%2 != 0 { cs, ok := args[len(args)-1].(CapturedStacktrace) if ok { args = args[:len(args)-1] vals["stacktrace"] = cs } else { args = append(args, "<unknown>") } } for i := 0; i < len(args); i = i + 2 { if _, ok := args[i].(string); !ok { // As this is the logging function not much we can do here // without injecting into logs... continue } val := args[i+1] switch sv := val.(type) { case error: // Check if val is of type error. If error type doesn't // implement json.Marshaler or encoding.TextMarshaler // then set val to err.Error() so that it gets marshaled switch sv.(type) { case json.Marshaler, encoding.TextMarshaler: default: val = sv.Error() } case Format: val = fmt.Sprintf(sv[0].(string), sv[1:]...) } vals[args[i].(string)] = val } } err := json.NewEncoder(z.w).Encode(vals) if err != nil { panic(err) } } // Emit the message and args at DEBUG level func (z *intLogger) Debug(msg string, args ...interface{}) { z.Log(Debug, msg, args...) } // Emit the message and args at TRACE level func (z *intLogger) Trace(msg string, args ...interface{}) { z.Log(Trace, msg, args...) } // Emit the message and args at INFO level func (z *intLogger) Info(msg string, args ...interface{}) { z.Log(Info, msg, args...) } // Emit the message and args at WARN level func (z *intLogger) Warn(msg string, args ...interface{}) { z.Log(Warn, msg, args...) } // Emit the message and args at ERROR level func (z *intLogger) Error(msg string, args ...interface{}) { z.Log(Error, msg, args...) } // Indicate that the logger would emit TRACE level logs func (z *intLogger) IsTrace() bool { return Level(atomic.LoadInt32(z.level)) == Trace } // Indicate that the logger would emit DEBUG level logs func (z *intLogger) IsDebug() bool { return Level(atomic.LoadInt32(z.level)) <= Debug } // Indicate that the logger would emit INFO level logs func (z *intLogger) IsInfo() bool { return Level(atomic.LoadInt32(z.level)) <= Info } // Indicate that the logger would emit WARN level logs func (z *intLogger) IsWarn() bool { return Level(atomic.LoadInt32(z.level)) <= Warn } // Indicate that the logger would emit ERROR level logs func (z *intLogger) IsError() bool { return Level(atomic.LoadInt32(z.level)) <= Error } // Return a sub-Logger for which every emitted log message will contain // the given key/value pairs. This is used to create a context specific // Logger. func (z *intLogger) With(args ...interface{}) Logger { if len(args)%2 != 0 { panic("With() call requires paired arguments") } var nz intLogger = *z result := make(map[string]interface{}, len(z.implied)+len(args)) keys := make([]string, 0, len(z.implied)+len(args)) // Read existing args, store map and key for consistent sorting for i := 0; i < len(z.implied); i += 2 { key := z.implied[i].(string) keys = append(keys, key) result[key] = z.implied[i+1] } // Read new args, store map and key for consistent sorting for i := 0; i < len(args); i += 2 { key := args[i].(string) _, exists := result[key] if !exists { keys = append(keys, key) } result[key] = args[i+1] } // Sort keys to be consistent sort.Strings(keys) nz.implied = make([]interface{}, 0, len(z.implied)+len(args)) for _, k := range keys { nz.implied = append(nz.implied, k) nz.implied = append(nz.implied, result[k]) } return &nz } // Create a new sub-Logger that a name decending from the current name. // This is used to create a subsystem specific Logger. func (z *intLogger) Named(name string) Logger { var nz intLogger = *z if nz.name != "" { nz.name = nz.name + "." + name } else { nz.name = name } return &nz } // Create a new sub-Logger with an explicit name. This ignores the current // name. This is used to create a standalone logger that doesn't fall // within the normal hierarchy. func (z *intLogger) ResetNamed(name string) Logger { var nz intLogger = *z nz.name = name return &nz } // Update the logging level on-the-fly. This will affect all subloggers as // well. func (z *intLogger) SetLevel(level Level) { atomic.StoreInt32(z.level, int32(level)) } // Create a *log.Logger that will send it's data through this Logger. This // allows packages that expect to be using the standard library log to actually // use this logger. func (z *intLogger) StandardLogger(opts *StandardLoggerOptions) *log.Logger { if opts == nil { opts = &StandardLoggerOptions{} } return log.New(&stdlogAdapter{z, opts.InferLevels}, "", 0) }
xanzy/terraform-provider-cosmic
vendor/github.com/hashicorp/go-hclog/int.go
GO
apache-2.0
11,348
/* Copyright 2015 The Kubernetes Authors. 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 podautoscaler import ( "fmt" "math" "time" "github.com/golang/glog" autoscalingv1 "k8s.io/api/autoscaling/v1" autoscalingv2 "k8s.io/api/autoscaling/v2beta1" "k8s.io/api/core/v1" apiequality "k8s.io/apimachinery/pkg/api/equality" "k8s.io/apimachinery/pkg/api/errors" apimeta "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/wait" autoscalinginformers "k8s.io/client-go/informers/autoscaling/v1" "k8s.io/client-go/kubernetes/scheme" autoscalingclient "k8s.io/client-go/kubernetes/typed/autoscaling/v1" v1core "k8s.io/client-go/kubernetes/typed/core/v1" autoscalinglisters "k8s.io/client-go/listers/autoscaling/v1" scaleclient "k8s.io/client-go/scale" "k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/record" "k8s.io/client-go/util/workqueue" "k8s.io/kubernetes/pkg/api/legacyscheme" "k8s.io/kubernetes/pkg/controller" ) var ( scaleUpLimitFactor = 2.0 scaleUpLimitMinimum = 4.0 ) // HorizontalController is responsible for the synchronizing HPA objects stored // in the system with the actual deployments/replication controllers they // control. type HorizontalController struct { scaleNamespacer scaleclient.ScalesGetter hpaNamespacer autoscalingclient.HorizontalPodAutoscalersGetter mapper apimeta.RESTMapper replicaCalc *ReplicaCalculator eventRecorder record.EventRecorder upscaleForbiddenWindow time.Duration downscaleForbiddenWindow time.Duration // hpaLister is able to list/get HPAs from the shared cache from the informer passed in to // NewHorizontalController. hpaLister autoscalinglisters.HorizontalPodAutoscalerLister hpaListerSynced cache.InformerSynced // Controllers that need to be synced queue workqueue.RateLimitingInterface } // NewHorizontalController creates a new HorizontalController. func NewHorizontalController( evtNamespacer v1core.EventsGetter, scaleNamespacer scaleclient.ScalesGetter, hpaNamespacer autoscalingclient.HorizontalPodAutoscalersGetter, mapper apimeta.RESTMapper, replicaCalc *ReplicaCalculator, hpaInformer autoscalinginformers.HorizontalPodAutoscalerInformer, resyncPeriod time.Duration, upscaleForbiddenWindow time.Duration, downscaleForbiddenWindow time.Duration, ) *HorizontalController { broadcaster := record.NewBroadcaster() broadcaster.StartLogging(glog.Infof) broadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: evtNamespacer.Events("")}) recorder := broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: "horizontal-pod-autoscaler"}) hpaController := &HorizontalController{ replicaCalc: replicaCalc, eventRecorder: recorder, scaleNamespacer: scaleNamespacer, hpaNamespacer: hpaNamespacer, upscaleForbiddenWindow: upscaleForbiddenWindow, downscaleForbiddenWindow: downscaleForbiddenWindow, queue: workqueue.NewNamedRateLimitingQueue(NewDefaultHPARateLimiter(resyncPeriod), "horizontalpodautoscaler"), mapper: mapper, } hpaInformer.Informer().AddEventHandlerWithResyncPeriod( cache.ResourceEventHandlerFuncs{ AddFunc: hpaController.enqueueHPA, UpdateFunc: hpaController.updateHPA, DeleteFunc: hpaController.deleteHPA, }, resyncPeriod, ) hpaController.hpaLister = hpaInformer.Lister() hpaController.hpaListerSynced = hpaInformer.Informer().HasSynced return hpaController } // Run begins watching and syncing. func (a *HorizontalController) Run(stopCh <-chan struct{}) { defer utilruntime.HandleCrash() defer a.queue.ShutDown() glog.Infof("Starting HPA controller") defer glog.Infof("Shutting down HPA controller") if !controller.WaitForCacheSync("HPA", stopCh, a.hpaListerSynced) { return } // start a single worker (we may wish to start more in the future) go wait.Until(a.worker, time.Second, stopCh) <-stopCh } // obj could be an *v1.HorizontalPodAutoscaler, or a DeletionFinalStateUnknown marker item. func (a *HorizontalController) updateHPA(old, cur interface{}) { a.enqueueHPA(cur) } // obj could be an *v1.HorizontalPodAutoscaler, or a DeletionFinalStateUnknown marker item. func (a *HorizontalController) enqueueHPA(obj interface{}) { key, err := controller.KeyFunc(obj) if err != nil { utilruntime.HandleError(fmt.Errorf("couldn't get key for object %+v: %v", obj, err)) return } // always add rate-limitted so we don't fetch metrics more that once per resync interval a.queue.AddRateLimited(key) } func (a *HorizontalController) deleteHPA(obj interface{}) { key, err := controller.KeyFunc(obj) if err != nil { utilruntime.HandleError(fmt.Errorf("couldn't get key for object %+v: %v", obj, err)) return } // TODO: could we leak if we fail to get the key? a.queue.Forget(key) } func (a *HorizontalController) worker() { for a.processNextWorkItem() { } glog.Infof("horizontal pod autoscaler controller worker shutting down") } func (a *HorizontalController) processNextWorkItem() bool { key, quit := a.queue.Get() if quit { return false } defer a.queue.Done(key) err := a.reconcileKey(key.(string)) if err == nil { // don't "forget" here because we want to only process a given HPA once per resync interval return true } a.queue.AddRateLimited(key) utilruntime.HandleError(err) return true } // Computes the desired number of replicas for the metric specifications listed in the HPA, returning the maximum // of the computed replica counts, a description of the associated metric, and the statuses of all metrics // computed. func (a *HorizontalController) computeReplicasForMetrics(hpa *autoscalingv2.HorizontalPodAutoscaler, scale *autoscalingv1.Scale, metricSpecs []autoscalingv2.MetricSpec) (replicas int32, metric string, statuses []autoscalingv2.MetricStatus, timestamp time.Time, err error) { currentReplicas := scale.Status.Replicas statuses = make([]autoscalingv2.MetricStatus, len(metricSpecs)) for i, metricSpec := range metricSpecs { if scale.Status.Selector == "" { errMsg := "selector is required" a.eventRecorder.Event(hpa, v1.EventTypeWarning, "SelectorRequired", errMsg) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "InvalidSelector", "the HPA target's scale is missing a selector") return 0, "", nil, time.Time{}, fmt.Errorf(errMsg) } selector, err := labels.Parse(scale.Status.Selector) if err != nil { errMsg := fmt.Sprintf("couldn't convert selector into a corresponding internal selector object: %v", err) a.eventRecorder.Event(hpa, v1.EventTypeWarning, "InvalidSelector", errMsg) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "InvalidSelector", errMsg) return 0, "", nil, time.Time{}, fmt.Errorf(errMsg) } var replicaCountProposal int32 var utilizationProposal int64 var timestampProposal time.Time var metricNameProposal string switch metricSpec.Type { case autoscalingv2.ObjectMetricSourceType: replicaCountProposal, utilizationProposal, timestampProposal, err = a.replicaCalc.GetObjectMetricReplicas(currentReplicas, metricSpec.Object.TargetValue.MilliValue(), metricSpec.Object.MetricName, hpa.Namespace, &metricSpec.Object.Target, selector) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetObjectMetric", err.Error()) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetObjectMetric", "the HPA was unable to compute the replica count: %v", err) return 0, "", nil, time.Time{}, fmt.Errorf("failed to get object metric value: %v", err) } metricNameProposal = fmt.Sprintf("%s metric %s", metricSpec.Object.Target.Kind, metricSpec.Object.MetricName) statuses[i] = autoscalingv2.MetricStatus{ Type: autoscalingv2.ObjectMetricSourceType, Object: &autoscalingv2.ObjectMetricStatus{ Target: metricSpec.Object.Target, MetricName: metricSpec.Object.MetricName, CurrentValue: *resource.NewMilliQuantity(utilizationProposal, resource.DecimalSI), }, } case autoscalingv2.PodsMetricSourceType: replicaCountProposal, utilizationProposal, timestampProposal, err = a.replicaCalc.GetMetricReplicas(currentReplicas, metricSpec.Pods.TargetAverageValue.MilliValue(), metricSpec.Pods.MetricName, hpa.Namespace, selector) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetPodsMetric", err.Error()) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetPodsMetric", "the HPA was unable to compute the replica count: %v", err) return 0, "", nil, time.Time{}, fmt.Errorf("failed to get pods metric value: %v", err) } metricNameProposal = fmt.Sprintf("pods metric %s", metricSpec.Pods.MetricName) statuses[i] = autoscalingv2.MetricStatus{ Type: autoscalingv2.PodsMetricSourceType, Pods: &autoscalingv2.PodsMetricStatus{ MetricName: metricSpec.Pods.MetricName, CurrentAverageValue: *resource.NewMilliQuantity(utilizationProposal, resource.DecimalSI), }, } case autoscalingv2.ResourceMetricSourceType: if metricSpec.Resource.TargetAverageValue != nil { var rawProposal int64 replicaCountProposal, rawProposal, timestampProposal, err = a.replicaCalc.GetRawResourceReplicas(currentReplicas, metricSpec.Resource.TargetAverageValue.MilliValue(), metricSpec.Resource.Name, hpa.Namespace, selector) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetResourceMetric", err.Error()) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetResourceMetric", "the HPA was unable to compute the replica count: %v", err) return 0, "", nil, time.Time{}, fmt.Errorf("failed to get %s utilization: %v", metricSpec.Resource.Name, err) } metricNameProposal = fmt.Sprintf("%s resource", metricSpec.Resource.Name) statuses[i] = autoscalingv2.MetricStatus{ Type: autoscalingv2.ResourceMetricSourceType, Resource: &autoscalingv2.ResourceMetricStatus{ Name: metricSpec.Resource.Name, CurrentAverageValue: *resource.NewMilliQuantity(rawProposal, resource.DecimalSI), }, } } else { // set a default utilization percentage if none is set if metricSpec.Resource.TargetAverageUtilization == nil { errMsg := "invalid resource metric source: neither a utilization target nor a value target was set" a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetResourceMetric", errMsg) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetResourceMetric", "the HPA was unable to compute the replica count: %s", errMsg) return 0, "", nil, time.Time{}, fmt.Errorf(errMsg) } targetUtilization := *metricSpec.Resource.TargetAverageUtilization var percentageProposal int32 var rawProposal int64 replicaCountProposal, percentageProposal, rawProposal, timestampProposal, err = a.replicaCalc.GetResourceReplicas(currentReplicas, targetUtilization, metricSpec.Resource.Name, hpa.Namespace, selector) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetResourceMetric", err.Error()) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetResourceMetric", "the HPA was unable to compute the replica count: %v", err) return 0, "", nil, time.Time{}, fmt.Errorf("failed to get %s utilization: %v", metricSpec.Resource.Name, err) } metricNameProposal = fmt.Sprintf("%s resource utilization (percentage of request)", metricSpec.Resource.Name) statuses[i] = autoscalingv2.MetricStatus{ Type: autoscalingv2.ResourceMetricSourceType, Resource: &autoscalingv2.ResourceMetricStatus{ Name: metricSpec.Resource.Name, CurrentAverageUtilization: &percentageProposal, CurrentAverageValue: *resource.NewMilliQuantity(rawProposal, resource.DecimalSI), }, } } case autoscalingv2.ExternalMetricSourceType: if metricSpec.External.TargetAverageValue != nil { replicaCountProposal, utilizationProposal, timestampProposal, err = a.replicaCalc.GetExternalPerPodMetricReplicas(currentReplicas, metricSpec.External.TargetAverageValue.MilliValue(), metricSpec.External.MetricName, hpa.Namespace, metricSpec.External.MetricSelector) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetExternalMetric", err.Error()) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetExternalMetric", "the HPA was unable to compute the replica count: %v", err) return 0, "", nil, time.Time{}, fmt.Errorf("failed to get %s external metric: %v", metricSpec.External.MetricName, err) } metricNameProposal = fmt.Sprintf("external metric %s(%+v)", metricSpec.External.MetricName, metricSpec.External.MetricSelector) statuses[i] = autoscalingv2.MetricStatus{ Type: autoscalingv2.ExternalMetricSourceType, External: &autoscalingv2.ExternalMetricStatus{ MetricSelector: metricSpec.External.MetricSelector, MetricName: metricSpec.External.MetricName, CurrentAverageValue: resource.NewMilliQuantity(utilizationProposal, resource.DecimalSI), }, } } else if metricSpec.External.TargetValue != nil { replicaCountProposal, utilizationProposal, timestampProposal, err = a.replicaCalc.GetExternalMetricReplicas(currentReplicas, metricSpec.External.TargetValue.MilliValue(), metricSpec.External.MetricName, hpa.Namespace, metricSpec.External.MetricSelector, selector) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetExternalMetric", err.Error()) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetExternalMetric", "the HPA was unable to compute the replica count: %v", err) return 0, "", nil, time.Time{}, fmt.Errorf("failed to get external metric %s: %v", metricSpec.External.MetricName, err) } metricNameProposal = fmt.Sprintf("external metric %s(%+v)", metricSpec.External.MetricName, metricSpec.External.MetricSelector) statuses[i] = autoscalingv2.MetricStatus{ Type: autoscalingv2.ExternalMetricSourceType, External: &autoscalingv2.ExternalMetricStatus{ MetricSelector: metricSpec.External.MetricSelector, MetricName: metricSpec.External.MetricName, CurrentValue: *resource.NewMilliQuantity(utilizationProposal, resource.DecimalSI), }, } } else { errMsg := "invalid external metric source: neither a value target nor an average value target was set" a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetExternalMetric", errMsg) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetExternalMetric", "the HPA was unable to compute the replica count: %v", err) return 0, "", nil, time.Time{}, fmt.Errorf(errMsg) } default: errMsg := fmt.Sprintf("unknown metric source type %q", string(metricSpec.Type)) a.eventRecorder.Event(hpa, v1.EventTypeWarning, "InvalidMetricSourceType", errMsg) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "InvalidMetricSourceType", "the HPA was unable to compute the replica count: %s", errMsg) return 0, "", nil, time.Time{}, fmt.Errorf(errMsg) } if replicas == 0 || replicaCountProposal > replicas { timestamp = timestampProposal replicas = replicaCountProposal metric = metricNameProposal } } setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionTrue, "ValidMetricFound", "the HPA was able to successfully calculate a replica count from %s", metric) return replicas, metric, statuses, timestamp, nil } func (a *HorizontalController) reconcileKey(key string) error { namespace, name, err := cache.SplitMetaNamespaceKey(key) if err != nil { return err } hpa, err := a.hpaLister.HorizontalPodAutoscalers(namespace).Get(name) if errors.IsNotFound(err) { glog.Infof("Horizontal Pod Autoscaler has been deleted %v", key) return nil } return a.reconcileAutoscaler(hpa) } func (a *HorizontalController) reconcileAutoscaler(hpav1Shared *autoscalingv1.HorizontalPodAutoscaler) error { // make a copy so that we never mutate the shared informer cache (conversion can mutate the object) hpav1 := hpav1Shared.DeepCopy() // then, convert to autoscaling/v2, which makes our lives easier when calculating metrics hpaRaw, err := unsafeConvertToVersionVia(hpav1, autoscalingv2.SchemeGroupVersion) if err != nil { a.eventRecorder.Event(hpav1, v1.EventTypeWarning, "FailedConvertHPA", err.Error()) return fmt.Errorf("failed to convert the given HPA to %s: %v", autoscalingv2.SchemeGroupVersion.String(), err) } hpa := hpaRaw.(*autoscalingv2.HorizontalPodAutoscaler) hpaStatusOriginal := hpa.Status.DeepCopy() reference := fmt.Sprintf("%s/%s/%s", hpa.Spec.ScaleTargetRef.Kind, hpa.Namespace, hpa.Spec.ScaleTargetRef.Name) targetGV, err := schema.ParseGroupVersion(hpa.Spec.ScaleTargetRef.APIVersion) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetScale", err.Error()) setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "FailedGetScale", "the HPA controller was unable to get the target's current scale: %v", err) a.updateStatusIfNeeded(hpaStatusOriginal, hpa) return fmt.Errorf("invalid API version in scale target reference: %v", err) } targetGK := schema.GroupKind{ Group: targetGV.Group, Kind: hpa.Spec.ScaleTargetRef.Kind, } mappings, err := a.mapper.RESTMappings(targetGK) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetScale", err.Error()) setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "FailedGetScale", "the HPA controller was unable to get the target's current scale: %v", err) a.updateStatusIfNeeded(hpaStatusOriginal, hpa) return fmt.Errorf("unable to determine resource for scale target reference: %v", err) } scale, targetGR, err := a.scaleForResourceMappings(hpa.Namespace, hpa.Spec.ScaleTargetRef.Name, mappings) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetScale", err.Error()) setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "FailedGetScale", "the HPA controller was unable to get the target's current scale: %v", err) a.updateStatusIfNeeded(hpaStatusOriginal, hpa) return fmt.Errorf("failed to query scale subresource for %s: %v", reference, err) } setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionTrue, "SucceededGetScale", "the HPA controller was able to get the target's current scale") currentReplicas := scale.Status.Replicas var metricStatuses []autoscalingv2.MetricStatus metricDesiredReplicas := int32(0) metricName := "" metricTimestamp := time.Time{} desiredReplicas := int32(0) rescaleReason := "" timestamp := time.Now() rescale := true if scale.Spec.Replicas == 0 { // Autoscaling is disabled for this resource desiredReplicas = 0 rescale = false setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "ScalingDisabled", "scaling is disabled since the replica count of the target is zero") } else if currentReplicas > hpa.Spec.MaxReplicas { rescaleReason = "Current number of replicas above Spec.MaxReplicas" desiredReplicas = hpa.Spec.MaxReplicas } else if hpa.Spec.MinReplicas != nil && currentReplicas < *hpa.Spec.MinReplicas { rescaleReason = "Current number of replicas below Spec.MinReplicas" desiredReplicas = *hpa.Spec.MinReplicas } else if currentReplicas == 0 { rescaleReason = "Current number of replicas must be greater than 0" desiredReplicas = 1 } else { metricDesiredReplicas, metricName, metricStatuses, metricTimestamp, err = a.computeReplicasForMetrics(hpa, scale, hpa.Spec.Metrics) if err != nil { a.setCurrentReplicasInStatus(hpa, currentReplicas) if err := a.updateStatusIfNeeded(hpaStatusOriginal, hpa); err != nil { utilruntime.HandleError(err) } a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedComputeMetricsReplicas", err.Error()) return fmt.Errorf("failed to compute desired number of replicas based on listed metrics for %s: %v", reference, err) } glog.V(4).Infof("proposing %v desired replicas (based on %s from %s) for %s", metricDesiredReplicas, metricName, timestamp, reference) rescaleMetric := "" if metricDesiredReplicas > desiredReplicas { desiredReplicas = metricDesiredReplicas timestamp = metricTimestamp rescaleMetric = metricName } if desiredReplicas > currentReplicas { rescaleReason = fmt.Sprintf("%s above target", rescaleMetric) } if desiredReplicas < currentReplicas { rescaleReason = "All metrics below target" } desiredReplicas = a.normalizeDesiredReplicas(hpa, currentReplicas, desiredReplicas) rescale = a.shouldScale(hpa, currentReplicas, desiredReplicas, timestamp) backoffDown := false backoffUp := false if hpa.Status.LastScaleTime != nil { if !hpa.Status.LastScaleTime.Add(a.downscaleForbiddenWindow).Before(timestamp) { setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "BackoffDownscale", "the time since the previous scale is still within the downscale forbidden window") backoffDown = true } if !hpa.Status.LastScaleTime.Add(a.upscaleForbiddenWindow).Before(timestamp) { backoffUp = true if backoffDown { setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "BackoffBoth", "the time since the previous scale is still within both the downscale and upscale forbidden windows") } else { setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "BackoffUpscale", "the time since the previous scale is still within the upscale forbidden window") } } } if !backoffDown && !backoffUp { // mark that we're not backing off setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionTrue, "ReadyForNewScale", "the last scale time was sufficiently old as to warrant a new scale") } } if rescale { scale.Spec.Replicas = desiredReplicas _, err = a.scaleNamespacer.Scales(hpa.Namespace).Update(targetGR, scale) if err != nil { a.eventRecorder.Eventf(hpa, v1.EventTypeWarning, "FailedRescale", "New size: %d; reason: %s; error: %v", desiredReplicas, rescaleReason, err.Error()) setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "FailedUpdateScale", "the HPA controller was unable to update the target scale: %v", err) a.setCurrentReplicasInStatus(hpa, currentReplicas) if err := a.updateStatusIfNeeded(hpaStatusOriginal, hpa); err != nil { utilruntime.HandleError(err) } return fmt.Errorf("failed to rescale %s: %v", reference, err) } setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionTrue, "SucceededRescale", "the HPA controller was able to update the target scale to %d", desiredReplicas) a.eventRecorder.Eventf(hpa, v1.EventTypeNormal, "SuccessfulRescale", "New size: %d; reason: %s", desiredReplicas, rescaleReason) glog.Infof("Successful rescale of %s, old size: %d, new size: %d, reason: %s", hpa.Name, currentReplicas, desiredReplicas, rescaleReason) } else { glog.V(4).Infof("decided not to scale %s to %v (last scale time was %s)", reference, desiredReplicas, hpa.Status.LastScaleTime) desiredReplicas = currentReplicas } a.setStatus(hpa, currentReplicas, desiredReplicas, metricStatuses, rescale) return a.updateStatusIfNeeded(hpaStatusOriginal, hpa) } // normalizeDesiredReplicas takes the metrics desired replicas value and normalizes it based on the appropriate conditions (i.e. < maxReplicas, > // minReplicas, etc...) func (a *HorizontalController) normalizeDesiredReplicas(hpa *autoscalingv2.HorizontalPodAutoscaler, currentReplicas int32, prenormalizedDesiredReplicas int32) int32 { var minReplicas int32 if hpa.Spec.MinReplicas != nil { minReplicas = *hpa.Spec.MinReplicas } else { minReplicas = 0 } desiredReplicas, condition, reason := convertDesiredReplicasWithRules(currentReplicas, prenormalizedDesiredReplicas, minReplicas, hpa.Spec.MaxReplicas) if desiredReplicas == prenormalizedDesiredReplicas { setCondition(hpa, autoscalingv2.ScalingLimited, v1.ConditionFalse, condition, reason) } else { setCondition(hpa, autoscalingv2.ScalingLimited, v1.ConditionTrue, condition, reason) } return desiredReplicas } // convertDesiredReplicas performs the actual normalization, without depending on `HorizontalController` or `HorizontalPodAutoscaler` func convertDesiredReplicasWithRules(currentReplicas, desiredReplicas, hpaMinReplicas, hpaMaxReplicas int32) (int32, string, string) { var minimumAllowedReplicas int32 var maximumAllowedReplicas int32 var possibleLimitingCondition string var possibleLimitingReason string if hpaMinReplicas == 0 { minimumAllowedReplicas = 1 possibleLimitingReason = "the desired replica count is zero" } else { minimumAllowedReplicas = hpaMinReplicas possibleLimitingReason = "the desired replica count is less than the minimum replica count" } // Do not upscale too much to prevent incorrect rapid increase of the number of master replicas caused by // bogus CPU usage report from heapster/kubelet (like in issue #32304). scaleUpLimit := calculateScaleUpLimit(currentReplicas) if hpaMaxReplicas > scaleUpLimit { maximumAllowedReplicas = scaleUpLimit possibleLimitingCondition = "ScaleUpLimit" possibleLimitingReason = "the desired replica count is increasing faster than the maximum scale rate" } else { maximumAllowedReplicas = hpaMaxReplicas possibleLimitingCondition = "TooManyReplicas" possibleLimitingReason = "the desired replica count is more than the maximum replica count" } if desiredReplicas < minimumAllowedReplicas { possibleLimitingCondition = "TooFewReplicas" return minimumAllowedReplicas, possibleLimitingCondition, possibleLimitingReason } else if desiredReplicas > maximumAllowedReplicas { return maximumAllowedReplicas, possibleLimitingCondition, possibleLimitingReason } return desiredReplicas, "DesiredWithinRange", "the desired count is within the acceptable range" } func calculateScaleUpLimit(currentReplicas int32) int32 { return int32(math.Max(scaleUpLimitFactor*float64(currentReplicas), scaleUpLimitMinimum)) } func (a *HorizontalController) shouldScale(hpa *autoscalingv2.HorizontalPodAutoscaler, currentReplicas, desiredReplicas int32, timestamp time.Time) bool { if desiredReplicas == currentReplicas { return false } if hpa.Status.LastScaleTime == nil { return true } // Going down only if the usageRatio dropped significantly below the target // and there was no rescaling in the last downscaleForbiddenWindow. if desiredReplicas < currentReplicas && hpa.Status.LastScaleTime.Add(a.downscaleForbiddenWindow).Before(timestamp) { return true } // Going up only if the usage ratio increased significantly above the target // and there was no rescaling in the last upscaleForbiddenWindow. if desiredReplicas > currentReplicas && hpa.Status.LastScaleTime.Add(a.upscaleForbiddenWindow).Before(timestamp) { return true } return false } // scaleForResourceMappings attempts to fetch the scale for the // resource with the given name and namespace, trying each RESTMapping // in turn until a working one is found. If none work, the first error // is returned. It returns both the scale, as well as the group-resource from // the working mapping. func (a *HorizontalController) scaleForResourceMappings(namespace, name string, mappings []*apimeta.RESTMapping) (*autoscalingv1.Scale, schema.GroupResource, error) { var firstErr error for i, mapping := range mappings { targetGR := mapping.Resource.GroupResource() scale, err := a.scaleNamespacer.Scales(namespace).Get(targetGR, name) if err == nil { return scale, targetGR, nil } // if this is the first error, remember it, // then go on and try other mappings until we find a good one if i == 0 { firstErr = err } } // make sure we handle an empty set of mappings if firstErr == nil { firstErr = fmt.Errorf("unrecognized resource") } return nil, schema.GroupResource{}, firstErr } // setCurrentReplicasInStatus sets the current replica count in the status of the HPA. func (a *HorizontalController) setCurrentReplicasInStatus(hpa *autoscalingv2.HorizontalPodAutoscaler, currentReplicas int32) { a.setStatus(hpa, currentReplicas, hpa.Status.DesiredReplicas, hpa.Status.CurrentMetrics, false) } // setStatus recreates the status of the given HPA, updating the current and // desired replicas, as well as the metric statuses func (a *HorizontalController) setStatus(hpa *autoscalingv2.HorizontalPodAutoscaler, currentReplicas, desiredReplicas int32, metricStatuses []autoscalingv2.MetricStatus, rescale bool) { hpa.Status = autoscalingv2.HorizontalPodAutoscalerStatus{ CurrentReplicas: currentReplicas, DesiredReplicas: desiredReplicas, LastScaleTime: hpa.Status.LastScaleTime, CurrentMetrics: metricStatuses, Conditions: hpa.Status.Conditions, } if rescale { now := metav1.NewTime(time.Now()) hpa.Status.LastScaleTime = &now } } // updateStatusIfNeeded calls updateStatus only if the status of the new HPA is not the same as the old status func (a *HorizontalController) updateStatusIfNeeded(oldStatus *autoscalingv2.HorizontalPodAutoscalerStatus, newHPA *autoscalingv2.HorizontalPodAutoscaler) error { // skip a write if we wouldn't need to update if apiequality.Semantic.DeepEqual(oldStatus, &newHPA.Status) { return nil } return a.updateStatus(newHPA) } // updateStatus actually does the update request for the status of the given HPA func (a *HorizontalController) updateStatus(hpa *autoscalingv2.HorizontalPodAutoscaler) error { // convert back to autoscalingv1 hpaRaw, err := unsafeConvertToVersionVia(hpa, autoscalingv1.SchemeGroupVersion) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedConvertHPA", err.Error()) return fmt.Errorf("failed to convert the given HPA to %s: %v", autoscalingv2.SchemeGroupVersion.String(), err) } hpav1 := hpaRaw.(*autoscalingv1.HorizontalPodAutoscaler) _, err = a.hpaNamespacer.HorizontalPodAutoscalers(hpav1.Namespace).UpdateStatus(hpav1) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedUpdateStatus", err.Error()) return fmt.Errorf("failed to update status for %s: %v", hpa.Name, err) } glog.V(2).Infof("Successfully updated status for %s", hpa.Name) return nil } // unsafeConvertToVersionVia is like Scheme.UnsafeConvertToVersion, but it does so via an internal version first. // We use it since working with v2alpha1 is convenient here, but we want to use the v1 client (and // can't just use the internal version). Note that conversion mutates the object, so you need to deepcopy // *before* you call this if the input object came out of a shared cache. func unsafeConvertToVersionVia(obj runtime.Object, externalVersion schema.GroupVersion) (runtime.Object, error) { objInt, err := legacyscheme.Scheme.UnsafeConvertToVersion(obj, schema.GroupVersion{Group: externalVersion.Group, Version: runtime.APIVersionInternal}) if err != nil { return nil, fmt.Errorf("failed to convert the given object to the internal version: %v", err) } objExt, err := legacyscheme.Scheme.UnsafeConvertToVersion(objInt, externalVersion) if err != nil { return nil, fmt.Errorf("failed to convert the given object back to the external version: %v", err) } return objExt, err } // setCondition sets the specific condition type on the given HPA to the specified value with the given reason // and message. The message and args are treated like a format string. The condition will be added if it is // not present. func setCondition(hpa *autoscalingv2.HorizontalPodAutoscaler, conditionType autoscalingv2.HorizontalPodAutoscalerConditionType, status v1.ConditionStatus, reason, message string, args ...interface{}) { hpa.Status.Conditions = setConditionInList(hpa.Status.Conditions, conditionType, status, reason, message, args...) } // setConditionInList sets the specific condition type on the given HPA to the specified value with the given // reason and message. The message and args are treated like a format string. The condition will be added if // it is not present. The new list will be returned. func setConditionInList(inputList []autoscalingv2.HorizontalPodAutoscalerCondition, conditionType autoscalingv2.HorizontalPodAutoscalerConditionType, status v1.ConditionStatus, reason, message string, args ...interface{}) []autoscalingv2.HorizontalPodAutoscalerCondition { resList := inputList var existingCond *autoscalingv2.HorizontalPodAutoscalerCondition for i, condition := range resList { if condition.Type == conditionType { // can't take a pointer to an iteration variable existingCond = &resList[i] break } } if existingCond == nil { resList = append(resList, autoscalingv2.HorizontalPodAutoscalerCondition{ Type: conditionType, }) existingCond = &resList[len(resList)-1] } if existingCond.Status != status { existingCond.LastTransitionTime = metav1.Now() } existingCond.Status = status existingCond.Reason = reason existingCond.Message = fmt.Sprintf(message, args...) return resList }
victorgp/kubernetes
pkg/controller/podautoscaler/horizontal.go
GO
apache-2.0
33,818
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/global_error/global_error_service.h" #include <algorithm> #include "base/stl_util.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/global_error/global_error.h" #include "chrome/browser/ui/global_error/global_error_bubble_view_base.h" #include "content/public/browser/notification_service.h" GlobalErrorService::GlobalErrorService(Profile* profile) : profile_(profile) { } GlobalErrorService::~GlobalErrorService() { STLDeleteElements(&errors_); } void GlobalErrorService::AddGlobalError(GlobalError* error) { errors_.push_back(error); NotifyErrorsChanged(error); } void GlobalErrorService::RemoveGlobalError(GlobalError* error) { errors_.erase(std::find(errors_.begin(), errors_.end(), error)); GlobalErrorBubbleViewBase* bubble = error->GetBubbleView(); if (bubble) bubble->CloseBubbleView(); NotifyErrorsChanged(error); } GlobalError* GlobalErrorService::GetGlobalErrorByMenuItemCommandID( int command_id) const { for (GlobalErrorList::const_iterator it = errors_.begin(); it != errors_.end(); ++it) { GlobalError* error = *it; if (error->HasMenuItem() && command_id == error->MenuItemCommandID()) return error; } return NULL; } GlobalError* GlobalErrorService::GetHighestSeverityGlobalErrorWithWrenchMenuItem() const { GlobalError::Severity highest_severity = GlobalError::SEVERITY_LOW; GlobalError* highest_severity_error = NULL; for (GlobalErrorList::const_iterator it = errors_.begin(); it != errors_.end(); ++it) { GlobalError* error = *it; if (error->HasMenuItem()) { if (!highest_severity_error || error->GetSeverity() > highest_severity) { highest_severity = error->GetSeverity(); highest_severity_error = error; } } } return highest_severity_error; } GlobalError* GlobalErrorService::GetFirstGlobalErrorWithBubbleView() const { for (GlobalErrorList::const_iterator it = errors_.begin(); it != errors_.end(); ++it) { GlobalError* error = *it; if (error->HasBubbleView() && !error->HasShownBubbleView()) return error; } return NULL; } void GlobalErrorService::NotifyErrorsChanged(GlobalError* error) { // GlobalErrorService is bound only to original profile so we need to send // notifications to both it and its off-the-record profile to update // incognito windows as well. std::vector<Profile*> profiles_to_notify; if (profile_ != NULL) { profiles_to_notify.push_back(profile_); if (profile_->IsOffTheRecord()) profiles_to_notify.push_back(profile_->GetOriginalProfile()); else if (profile_->HasOffTheRecordProfile()) profiles_to_notify.push_back(profile_->GetOffTheRecordProfile()); for (size_t i = 0; i < profiles_to_notify.size(); ++i) { content::NotificationService::current()->Notify( chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED, content::Source<Profile>(profiles_to_notify[i]), content::Details<GlobalError>(error)); } } }
aospx-kitkat/platform_external_chromium_org
chrome/browser/ui/global_error/global_error_service.cc
C++
bsd-3-clause
3,238
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "google_apis/gaia/gaia_oauth_client.h" #include "base/json/json_reader.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/strings/string_util.h" #include "base/values.h" #include "google_apis/gaia/gaia_urls.h" #include "net/base/escape.h" #include "net/base/load_flags.h" #include "net/http/http_status_code.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_delegate.h" #include "net/url_request/url_request_context_getter.h" #include "url/gurl.h" namespace { const char kAccessTokenValue[] = "access_token"; const char kRefreshTokenValue[] = "refresh_token"; const char kExpiresInValue[] = "expires_in"; } namespace gaia { // Use a non-zero number, so unit tests can differentiate the URLFetcher used by // this class from other fetchers (most other code just hardcodes the ID to 0). const int GaiaOAuthClient::kUrlFetcherId = 17109006; class GaiaOAuthClient::Core : public base::RefCountedThreadSafe<GaiaOAuthClient::Core>, public net::URLFetcherDelegate { public: Core(net::URLRequestContextGetter* request_context_getter) : num_retries_(0), request_context_getter_(request_context_getter), delegate_(NULL), request_type_(NO_PENDING_REQUEST) { } void GetTokensFromAuthCode(const OAuthClientInfo& oauth_client_info, const std::string& auth_code, int max_retries, GaiaOAuthClient::Delegate* delegate); void RefreshToken(const OAuthClientInfo& oauth_client_info, const std::string& refresh_token, const std::vector<std::string>& scopes, int max_retries, GaiaOAuthClient::Delegate* delegate); void GetUserEmail(const std::string& oauth_access_token, int max_retries, Delegate* delegate); void GetUserId(const std::string& oauth_access_token, int max_retries, Delegate* delegate); void GetTokenInfo(const std::string& oauth_access_token, int max_retries, Delegate* delegate); // net::URLFetcherDelegate implementation. virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE; private: friend class base::RefCountedThreadSafe<Core>; enum RequestType { NO_PENDING_REQUEST, TOKENS_FROM_AUTH_CODE, REFRESH_TOKEN, TOKEN_INFO, USER_EMAIL, USER_ID, }; virtual ~Core() {} void GetUserInfo(const std::string& oauth_access_token, int max_retries, Delegate* delegate); void MakeGaiaRequest(const GURL& url, const std::string& post_body, int max_retries, GaiaOAuthClient::Delegate* delegate); void HandleResponse(const net::URLFetcher* source, bool* should_retry_request); int num_retries_; scoped_refptr<net::URLRequestContextGetter> request_context_getter_; GaiaOAuthClient::Delegate* delegate_; scoped_ptr<net::URLFetcher> request_; RequestType request_type_; }; void GaiaOAuthClient::Core::GetTokensFromAuthCode( const OAuthClientInfo& oauth_client_info, const std::string& auth_code, int max_retries, GaiaOAuthClient::Delegate* delegate) { DCHECK_EQ(request_type_, NO_PENDING_REQUEST); request_type_ = TOKENS_FROM_AUTH_CODE; std::string post_body = "code=" + net::EscapeUrlEncodedData(auth_code, true) + "&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id, true) + "&client_secret=" + net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) + "&redirect_uri=" + net::EscapeUrlEncodedData(oauth_client_info.redirect_uri, true) + "&grant_type=authorization_code"; MakeGaiaRequest(GURL(GaiaUrls::GetInstance()->oauth2_token_url()), post_body, max_retries, delegate); } void GaiaOAuthClient::Core::RefreshToken( const OAuthClientInfo& oauth_client_info, const std::string& refresh_token, const std::vector<std::string>& scopes, int max_retries, GaiaOAuthClient::Delegate* delegate) { DCHECK_EQ(request_type_, NO_PENDING_REQUEST); request_type_ = REFRESH_TOKEN; std::string post_body = "refresh_token=" + net::EscapeUrlEncodedData(refresh_token, true) + "&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id, true) + "&client_secret=" + net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) + "&grant_type=refresh_token"; if (!scopes.empty()) { std::string scopes_string = JoinString(scopes, ' '); post_body += "&scope=" + net::EscapeUrlEncodedData(scopes_string, true); } MakeGaiaRequest(GURL(GaiaUrls::GetInstance()->oauth2_token_url()), post_body, max_retries, delegate); } void GaiaOAuthClient::Core::GetUserEmail(const std::string& oauth_access_token, int max_retries, Delegate* delegate) { DCHECK_EQ(request_type_, NO_PENDING_REQUEST); DCHECK(!request_.get()); request_type_ = USER_EMAIL; GetUserInfo(oauth_access_token, max_retries, delegate); } void GaiaOAuthClient::Core::GetUserId(const std::string& oauth_access_token, int max_retries, Delegate* delegate) { DCHECK_EQ(request_type_, NO_PENDING_REQUEST); DCHECK(!request_.get()); request_type_ = USER_ID; GetUserInfo(oauth_access_token, max_retries, delegate); } void GaiaOAuthClient::Core::GetUserInfo(const std::string& oauth_access_token, int max_retries, Delegate* delegate) { delegate_ = delegate; num_retries_ = 0; request_.reset(net::URLFetcher::Create( kUrlFetcherId, GURL(GaiaUrls::GetInstance()->oauth_user_info_url()), net::URLFetcher::GET, this)); request_->SetRequestContext(request_context_getter_.get()); request_->AddExtraRequestHeader("Authorization: OAuth " + oauth_access_token); request_->SetMaxRetriesOn5xx(max_retries); request_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES); // Fetchers are sometimes cancelled because a network change was detected, // especially at startup and after sign-in on ChromeOS. Retrying once should // be enough in those cases; let the fetcher retry up to 3 times just in case. // http://crbug.com/163710 request_->SetAutomaticallyRetryOnNetworkChanges(3); request_->Start(); } void GaiaOAuthClient::Core::GetTokenInfo(const std::string& oauth_access_token, int max_retries, Delegate* delegate) { DCHECK_EQ(request_type_, NO_PENDING_REQUEST); DCHECK(!request_.get()); request_type_ = TOKEN_INFO; std::string post_body = "access_token=" + net::EscapeUrlEncodedData(oauth_access_token, true); MakeGaiaRequest(GURL(GaiaUrls::GetInstance()->oauth2_token_info_url()), post_body, max_retries, delegate); } void GaiaOAuthClient::Core::MakeGaiaRequest( const GURL& url, const std::string& post_body, int max_retries, GaiaOAuthClient::Delegate* delegate) { DCHECK(!request_.get()) << "Tried to fetch two things at once!"; delegate_ = delegate; num_retries_ = 0; request_.reset(net::URLFetcher::Create( kUrlFetcherId, url, net::URLFetcher::POST, this)); request_->SetRequestContext(request_context_getter_.get()); request_->SetUploadData("application/x-www-form-urlencoded", post_body); request_->SetMaxRetriesOn5xx(max_retries); request_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES); // See comment on SetAutomaticallyRetryOnNetworkChanges() above. request_->SetAutomaticallyRetryOnNetworkChanges(3); request_->Start(); } // URLFetcher::Delegate implementation. void GaiaOAuthClient::Core::OnURLFetchComplete( const net::URLFetcher* source) { bool should_retry = false; HandleResponse(source, &should_retry); if (should_retry) { // Explicitly call ReceivedContentWasMalformed() to ensure the current // request gets counted as a failure for calculation of the back-off // period. If it was already a failure by status code, this call will // be ignored. request_->ReceivedContentWasMalformed(); num_retries_++; // We must set our request_context_getter_ again because // URLFetcher::Core::RetryOrCompleteUrlFetch resets it to NULL... request_->SetRequestContext(request_context_getter_.get()); request_->Start(); } } void GaiaOAuthClient::Core::HandleResponse( const net::URLFetcher* source, bool* should_retry_request) { // Move ownership of the request fetcher into a local scoped_ptr which // will be nuked when we're done handling the request, unless we need // to retry, in which case ownership will be returned to request_. scoped_ptr<net::URLFetcher> old_request = request_.Pass(); DCHECK_EQ(source, old_request.get()); // RC_BAD_REQUEST means the arguments are invalid. No point retrying. We are // done here. if (source->GetResponseCode() == net::HTTP_BAD_REQUEST) { delegate_->OnOAuthError(); return; } scoped_ptr<base::DictionaryValue> response_dict; if (source->GetResponseCode() == net::HTTP_OK) { std::string data; source->GetResponseAsString(&data); scoped_ptr<base::Value> message_value(base::JSONReader::Read(data)); if (message_value.get() && message_value->IsType(base::Value::TYPE_DICTIONARY)) { response_dict.reset( static_cast<base::DictionaryValue*>(message_value.release())); } } if (!response_dict.get()) { // If we don't have an access token yet and the the error was not // RC_BAD_REQUEST, we may need to retry. if ((source->GetMaxRetriesOn5xx() != -1) && (num_retries_ >= source->GetMaxRetriesOn5xx())) { // Retry limit reached. Give up. delegate_->OnNetworkError(source->GetResponseCode()); } else { request_ = old_request.Pass(); *should_retry_request = true; } return; } RequestType type = request_type_; request_type_ = NO_PENDING_REQUEST; switch (type) { case USER_EMAIL: { std::string email; response_dict->GetString("email", &email); delegate_->OnGetUserEmailResponse(email); break; } case USER_ID: { std::string id; response_dict->GetString("id", &id); delegate_->OnGetUserIdResponse(id); break; } case TOKEN_INFO: { delegate_->OnGetTokenInfoResponse(response_dict.Pass()); break; } case TOKENS_FROM_AUTH_CODE: case REFRESH_TOKEN: { std::string access_token; std::string refresh_token; int expires_in_seconds = 0; response_dict->GetString(kAccessTokenValue, &access_token); response_dict->GetString(kRefreshTokenValue, &refresh_token); response_dict->GetInteger(kExpiresInValue, &expires_in_seconds); if (access_token.empty()) { delegate_->OnOAuthError(); return; } if (type == REFRESH_TOKEN) { delegate_->OnRefreshTokenResponse(access_token, expires_in_seconds); } else { delegate_->OnGetTokensResponse(refresh_token, access_token, expires_in_seconds); } break; } default: NOTREACHED(); } } GaiaOAuthClient::GaiaOAuthClient(net::URLRequestContextGetter* context_getter) { core_ = new Core(context_getter); } GaiaOAuthClient::~GaiaOAuthClient() { } void GaiaOAuthClient::GetTokensFromAuthCode( const OAuthClientInfo& oauth_client_info, const std::string& auth_code, int max_retries, Delegate* delegate) { return core_->GetTokensFromAuthCode(oauth_client_info, auth_code, max_retries, delegate); } void GaiaOAuthClient::RefreshToken( const OAuthClientInfo& oauth_client_info, const std::string& refresh_token, const std::vector<std::string>& scopes, int max_retries, Delegate* delegate) { return core_->RefreshToken(oauth_client_info, refresh_token, scopes, max_retries, delegate); } void GaiaOAuthClient::GetUserEmail(const std::string& access_token, int max_retries, Delegate* delegate) { return core_->GetUserEmail(access_token, max_retries, delegate); } void GaiaOAuthClient::GetUserId(const std::string& access_token, int max_retries, Delegate* delegate) { return core_->GetUserId(access_token, max_retries, delegate); } void GaiaOAuthClient::GetTokenInfo(const std::string& access_token, int max_retries, Delegate* delegate) { return core_->GetTokenInfo(access_token, max_retries, delegate); } } // namespace gaia
Gateworks/platform-external-chromium_org
google_apis/gaia/gaia_oauth_client.cc
C++
bsd-3-clause
13,657
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/usb/usb_chooser_context_factory.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/usb/usb_chooser_context.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" UsbChooserContextFactory::UsbChooserContextFactory() : BrowserContextKeyedServiceFactory( "UsbChooserContext", BrowserContextDependencyManager::GetInstance()) { DependsOn(HostContentSettingsMapFactory::GetInstance()); } UsbChooserContextFactory::~UsbChooserContextFactory() {} KeyedService* UsbChooserContextFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { return new UsbChooserContext(Profile::FromBrowserContext(context)); } // static UsbChooserContextFactory* UsbChooserContextFactory::GetInstance() { return base::Singleton<UsbChooserContextFactory>::get(); } // static UsbChooserContext* UsbChooserContextFactory::GetForProfile(Profile* profile) { return static_cast<UsbChooserContext*>( GetInstance()->GetServiceForBrowserContext(profile, true)); } content::BrowserContext* UsbChooserContextFactory::GetBrowserContextToUse( content::BrowserContext* context) const { return chrome::GetBrowserContextOwnInstanceInIncognito(context); }
endlessm/chromium-browser
chrome/browser/usb/usb_chooser_context_factory.cc
C++
bsd-3-clause
1,559
// Code generated by protoc-gen-gogo. // source: combos/both/one.proto // DO NOT EDIT! /* Package one is a generated protocol buffer package. It is generated from these files: combos/both/one.proto It has these top-level messages: Subby SampleOneOf */ package one import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/gogo/protobuf/gogoproto" import github_com_gogo_protobuf_protoc_gen_gogo_descriptor "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto" import compress_gzip "compress/gzip" import bytes "bytes" import io_ioutil "io/ioutil" import strings "strings" import reflect "reflect" import io "io" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package type Subby struct { Sub string `protobuf:"bytes,1,opt,name=sub,proto3" json:"sub,omitempty"` } func (m *Subby) Reset() { *m = Subby{} } func (*Subby) ProtoMessage() {} func (*Subby) Descriptor() ([]byte, []int) { return fileDescriptorOne, []int{0} } type SampleOneOf struct { // Types that are valid to be assigned to TestOneof: // *SampleOneOf_Field1 // *SampleOneOf_Field2 // *SampleOneOf_Field3 // *SampleOneOf_Field4 // *SampleOneOf_Field5 // *SampleOneOf_Field6 // *SampleOneOf_Field7 // *SampleOneOf_Field8 // *SampleOneOf_Field9 // *SampleOneOf_Field10 // *SampleOneOf_Field11 // *SampleOneOf_Field12 // *SampleOneOf_Field13 // *SampleOneOf_Field14 // *SampleOneOf_Field15 // *SampleOneOf_SubMessage TestOneof isSampleOneOf_TestOneof `protobuf_oneof:"test_oneof"` } func (m *SampleOneOf) Reset() { *m = SampleOneOf{} } func (*SampleOneOf) ProtoMessage() {} func (*SampleOneOf) Descriptor() ([]byte, []int) { return fileDescriptorOne, []int{1} } type isSampleOneOf_TestOneof interface { isSampleOneOf_TestOneof() Equal(interface{}) bool VerboseEqual(interface{}) error MarshalTo([]byte) (int, error) Size() int } type SampleOneOf_Field1 struct { Field1 float64 `protobuf:"fixed64,1,opt,name=Field1,proto3,oneof"` } type SampleOneOf_Field2 struct { Field2 float32 `protobuf:"fixed32,2,opt,name=Field2,proto3,oneof"` } type SampleOneOf_Field3 struct { Field3 int32 `protobuf:"varint,3,opt,name=Field3,proto3,oneof"` } type SampleOneOf_Field4 struct { Field4 int64 `protobuf:"varint,4,opt,name=Field4,proto3,oneof"` } type SampleOneOf_Field5 struct { Field5 uint32 `protobuf:"varint,5,opt,name=Field5,proto3,oneof"` } type SampleOneOf_Field6 struct { Field6 uint64 `protobuf:"varint,6,opt,name=Field6,proto3,oneof"` } type SampleOneOf_Field7 struct { Field7 int32 `protobuf:"zigzag32,7,opt,name=Field7,proto3,oneof"` } type SampleOneOf_Field8 struct { Field8 int64 `protobuf:"zigzag64,8,opt,name=Field8,proto3,oneof"` } type SampleOneOf_Field9 struct { Field9 uint32 `protobuf:"fixed32,9,opt,name=Field9,proto3,oneof"` } type SampleOneOf_Field10 struct { Field10 int32 `protobuf:"fixed32,10,opt,name=Field10,proto3,oneof"` } type SampleOneOf_Field11 struct { Field11 uint64 `protobuf:"fixed64,11,opt,name=Field11,proto3,oneof"` } type SampleOneOf_Field12 struct { Field12 int64 `protobuf:"fixed64,12,opt,name=Field12,proto3,oneof"` } type SampleOneOf_Field13 struct { Field13 bool `protobuf:"varint,13,opt,name=Field13,proto3,oneof"` } type SampleOneOf_Field14 struct { Field14 string `protobuf:"bytes,14,opt,name=Field14,proto3,oneof"` } type SampleOneOf_Field15 struct { Field15 []byte `protobuf:"bytes,15,opt,name=Field15,proto3,oneof"` } type SampleOneOf_SubMessage struct { SubMessage *Subby `protobuf:"bytes,16,opt,name=sub_message,json=subMessage,oneof"` } func (*SampleOneOf_Field1) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field2) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field3) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field4) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field5) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field6) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field7) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field8) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field9) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field10) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field11) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field12) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field13) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field14) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field15) isSampleOneOf_TestOneof() {} func (*SampleOneOf_SubMessage) isSampleOneOf_TestOneof() {} func (m *SampleOneOf) GetTestOneof() isSampleOneOf_TestOneof { if m != nil { return m.TestOneof } return nil } func (m *SampleOneOf) GetField1() float64 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field1); ok { return x.Field1 } return 0 } func (m *SampleOneOf) GetField2() float32 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field2); ok { return x.Field2 } return 0 } func (m *SampleOneOf) GetField3() int32 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field3); ok { return x.Field3 } return 0 } func (m *SampleOneOf) GetField4() int64 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field4); ok { return x.Field4 } return 0 } func (m *SampleOneOf) GetField5() uint32 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field5); ok { return x.Field5 } return 0 } func (m *SampleOneOf) GetField6() uint64 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field6); ok { return x.Field6 } return 0 } func (m *SampleOneOf) GetField7() int32 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field7); ok { return x.Field7 } return 0 } func (m *SampleOneOf) GetField8() int64 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field8); ok { return x.Field8 } return 0 } func (m *SampleOneOf) GetField9() uint32 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field9); ok { return x.Field9 } return 0 } func (m *SampleOneOf) GetField10() int32 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field10); ok { return x.Field10 } return 0 } func (m *SampleOneOf) GetField11() uint64 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field11); ok { return x.Field11 } return 0 } func (m *SampleOneOf) GetField12() int64 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field12); ok { return x.Field12 } return 0 } func (m *SampleOneOf) GetField13() bool { if x, ok := m.GetTestOneof().(*SampleOneOf_Field13); ok { return x.Field13 } return false } func (m *SampleOneOf) GetField14() string { if x, ok := m.GetTestOneof().(*SampleOneOf_Field14); ok { return x.Field14 } return "" } func (m *SampleOneOf) GetField15() []byte { if x, ok := m.GetTestOneof().(*SampleOneOf_Field15); ok { return x.Field15 } return nil } func (m *SampleOneOf) GetSubMessage() *Subby { if x, ok := m.GetTestOneof().(*SampleOneOf_SubMessage); ok { return x.SubMessage } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*SampleOneOf) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _SampleOneOf_OneofMarshaler, _SampleOneOf_OneofUnmarshaler, _SampleOneOf_OneofSizer, []interface{}{ (*SampleOneOf_Field1)(nil), (*SampleOneOf_Field2)(nil), (*SampleOneOf_Field3)(nil), (*SampleOneOf_Field4)(nil), (*SampleOneOf_Field5)(nil), (*SampleOneOf_Field6)(nil), (*SampleOneOf_Field7)(nil), (*SampleOneOf_Field8)(nil), (*SampleOneOf_Field9)(nil), (*SampleOneOf_Field10)(nil), (*SampleOneOf_Field11)(nil), (*SampleOneOf_Field12)(nil), (*SampleOneOf_Field13)(nil), (*SampleOneOf_Field14)(nil), (*SampleOneOf_Field15)(nil), (*SampleOneOf_SubMessage)(nil), } } func _SampleOneOf_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*SampleOneOf) // test_oneof switch x := m.TestOneof.(type) { case *SampleOneOf_Field1: _ = b.EncodeVarint(1<<3 | proto.WireFixed64) _ = b.EncodeFixed64(math.Float64bits(x.Field1)) case *SampleOneOf_Field2: _ = b.EncodeVarint(2<<3 | proto.WireFixed32) _ = b.EncodeFixed32(uint64(math.Float32bits(x.Field2))) case *SampleOneOf_Field3: _ = b.EncodeVarint(3<<3 | proto.WireVarint) _ = b.EncodeVarint(uint64(x.Field3)) case *SampleOneOf_Field4: _ = b.EncodeVarint(4<<3 | proto.WireVarint) _ = b.EncodeVarint(uint64(x.Field4)) case *SampleOneOf_Field5: _ = b.EncodeVarint(5<<3 | proto.WireVarint) _ = b.EncodeVarint(uint64(x.Field5)) case *SampleOneOf_Field6: _ = b.EncodeVarint(6<<3 | proto.WireVarint) _ = b.EncodeVarint(uint64(x.Field6)) case *SampleOneOf_Field7: _ = b.EncodeVarint(7<<3 | proto.WireVarint) _ = b.EncodeZigzag32(uint64(x.Field7)) case *SampleOneOf_Field8: _ = b.EncodeVarint(8<<3 | proto.WireVarint) _ = b.EncodeZigzag64(uint64(x.Field8)) case *SampleOneOf_Field9: _ = b.EncodeVarint(9<<3 | proto.WireFixed32) _ = b.EncodeFixed32(uint64(x.Field9)) case *SampleOneOf_Field10: _ = b.EncodeVarint(10<<3 | proto.WireFixed32) _ = b.EncodeFixed32(uint64(x.Field10)) case *SampleOneOf_Field11: _ = b.EncodeVarint(11<<3 | proto.WireFixed64) _ = b.EncodeFixed64(uint64(x.Field11)) case *SampleOneOf_Field12: _ = b.EncodeVarint(12<<3 | proto.WireFixed64) _ = b.EncodeFixed64(uint64(x.Field12)) case *SampleOneOf_Field13: t := uint64(0) if x.Field13 { t = 1 } _ = b.EncodeVarint(13<<3 | proto.WireVarint) _ = b.EncodeVarint(t) case *SampleOneOf_Field14: _ = b.EncodeVarint(14<<3 | proto.WireBytes) _ = b.EncodeStringBytes(x.Field14) case *SampleOneOf_Field15: _ = b.EncodeVarint(15<<3 | proto.WireBytes) _ = b.EncodeRawBytes(x.Field15) case *SampleOneOf_SubMessage: _ = b.EncodeVarint(16<<3 | proto.WireBytes) if err := b.EncodeMessage(x.SubMessage); err != nil { return err } case nil: default: return fmt.Errorf("SampleOneOf.TestOneof has unexpected type %T", x) } return nil } func _SampleOneOf_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*SampleOneOf) switch tag { case 1: // test_oneof.Field1 if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.TestOneof = &SampleOneOf_Field1{math.Float64frombits(x)} return true, err case 2: // test_oneof.Field2 if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.TestOneof = &SampleOneOf_Field2{math.Float32frombits(uint32(x))} return true, err case 3: // test_oneof.Field3 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.TestOneof = &SampleOneOf_Field3{int32(x)} return true, err case 4: // test_oneof.Field4 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.TestOneof = &SampleOneOf_Field4{int64(x)} return true, err case 5: // test_oneof.Field5 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.TestOneof = &SampleOneOf_Field5{uint32(x)} return true, err case 6: // test_oneof.Field6 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.TestOneof = &SampleOneOf_Field6{x} return true, err case 7: // test_oneof.Field7 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeZigzag32() m.TestOneof = &SampleOneOf_Field7{int32(x)} return true, err case 8: // test_oneof.Field8 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeZigzag64() m.TestOneof = &SampleOneOf_Field8{int64(x)} return true, err case 9: // test_oneof.Field9 if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.TestOneof = &SampleOneOf_Field9{uint32(x)} return true, err case 10: // test_oneof.Field10 if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.TestOneof = &SampleOneOf_Field10{int32(x)} return true, err case 11: // test_oneof.Field11 if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.TestOneof = &SampleOneOf_Field11{x} return true, err case 12: // test_oneof.Field12 if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.TestOneof = &SampleOneOf_Field12{int64(x)} return true, err case 13: // test_oneof.Field13 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.TestOneof = &SampleOneOf_Field13{x != 0} return true, err case 14: // test_oneof.Field14 if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.TestOneof = &SampleOneOf_Field14{x} return true, err case 15: // test_oneof.Field15 if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.TestOneof = &SampleOneOf_Field15{x} return true, err case 16: // test_oneof.sub_message if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(Subby) err := b.DecodeMessage(msg) m.TestOneof = &SampleOneOf_SubMessage{msg} return true, err default: return false, nil } } func _SampleOneOf_OneofSizer(msg proto.Message) (n int) { m := msg.(*SampleOneOf) // test_oneof switch x := m.TestOneof.(type) { case *SampleOneOf_Field1: n += proto.SizeVarint(1<<3 | proto.WireFixed64) n += 8 case *SampleOneOf_Field2: n += proto.SizeVarint(2<<3 | proto.WireFixed32) n += 4 case *SampleOneOf_Field3: n += proto.SizeVarint(3<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Field3)) case *SampleOneOf_Field4: n += proto.SizeVarint(4<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Field4)) case *SampleOneOf_Field5: n += proto.SizeVarint(5<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Field5)) case *SampleOneOf_Field6: n += proto.SizeVarint(6<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Field6)) case *SampleOneOf_Field7: n += proto.SizeVarint(7<<3 | proto.WireVarint) n += proto.SizeVarint(uint64((uint32(x.Field7) << 1) ^ uint32((int32(x.Field7) >> 31)))) case *SampleOneOf_Field8: n += proto.SizeVarint(8<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(uint64(x.Field8<<1) ^ uint64((int64(x.Field8) >> 63)))) case *SampleOneOf_Field9: n += proto.SizeVarint(9<<3 | proto.WireFixed32) n += 4 case *SampleOneOf_Field10: n += proto.SizeVarint(10<<3 | proto.WireFixed32) n += 4 case *SampleOneOf_Field11: n += proto.SizeVarint(11<<3 | proto.WireFixed64) n += 8 case *SampleOneOf_Field12: n += proto.SizeVarint(12<<3 | proto.WireFixed64) n += 8 case *SampleOneOf_Field13: n += proto.SizeVarint(13<<3 | proto.WireVarint) n += 1 case *SampleOneOf_Field14: n += proto.SizeVarint(14<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Field14))) n += len(x.Field14) case *SampleOneOf_Field15: n += proto.SizeVarint(15<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Field15))) n += len(x.Field15) case *SampleOneOf_SubMessage: s := proto.Size(x.SubMessage) n += proto.SizeVarint(16<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } func init() { proto.RegisterType((*Subby)(nil), "one.Subby") proto.RegisterType((*SampleOneOf)(nil), "one.SampleOneOf") } func (this *Subby) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) { return OneDescription() } func (this *SampleOneOf) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) { return OneDescription() } func OneDescription() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) { d := &github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet{} var gzipped = []byte{ // 3749 bytes of a gzipped FileDescriptorSet 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x5a, 0x5b, 0x6c, 0xe4, 0xe6, 0x75, 0x16, 0xe7, 0xa6, 0x99, 0x33, 0xa3, 0x11, 0xf5, 0x4b, 0x5e, 0x73, 0xe5, 0x78, 0x56, 0xab, 0xd8, 0xb1, 0x6c, 0xd7, 0x5a, 0x5b, 0x97, 0xbd, 0xcc, 0x36, 0x31, 0x46, 0xd2, 0x58, 0xab, 0x85, 0x6e, 0xe1, 0x48, 0x89, 0x9d, 0x3c, 0x10, 0x1c, 0xce, 0x3f, 0x23, 0xee, 0x72, 0xc8, 0x29, 0xc9, 0x59, 0x5b, 0x7e, 0xda, 0xc0, 0xbd, 0x20, 0x08, 0x7a, 0x4d, 0x81, 0x26, 0x8e, 0xe3, 0xa6, 0x01, 0x5a, 0xa7, 0xe9, 0x2d, 0xe9, 0x25, 0x0d, 0xfa, 0xd4, 0x97, 0xb4, 0x7e, 0x2a, 0x92, 0xb7, 0x3e, 0xe4, 0x21, 0xab, 0x1a, 0x68, 0xda, 0xba, 0xad, 0xdb, 0x18, 0x68, 0x80, 0x7d, 0x29, 0xfe, 0x1b, 0xc9, 0xb9, 0x68, 0x39, 0x0a, 0x90, 0x38, 0x4f, 0x12, 0xcf, 0x39, 0xdf, 0xc7, 0xc3, 0xf3, 0x9f, 0xff, 0x9c, 0xc3, 0x7f, 0x08, 0x9f, 0x59, 0x81, 0xb9, 0x96, 0xe3, 0xb4, 0x2c, 0x7c, 0xa9, 0xe3, 0x3a, 0xbe, 0x53, 0xef, 0x36, 0x2f, 0x35, 0xb0, 0x67, 0xb8, 0x66, 0xc7, 0x77, 0xdc, 0x45, 0x2a, 0x43, 0x93, 0xcc, 0x62, 0x51, 0x58, 0xcc, 0xef, 0xc0, 0xd4, 0x0b, 0xa6, 0x85, 0x37, 0x02, 0xc3, 0x1a, 0xf6, 0xd1, 0x55, 0x48, 0x35, 0x4d, 0x0b, 0x2b, 0xd2, 0x5c, 0x72, 0x21, 0xbf, 0xf4, 0xd8, 0x62, 0x1f, 0x68, 0xb1, 0x17, 0xb1, 0x4f, 0xc4, 0x2a, 0x45, 0xcc, 0xbf, 0x93, 0x82, 0xe9, 0x21, 0x5a, 0x84, 0x20, 0x65, 0xeb, 0x6d, 0xc2, 0x28, 0x2d, 0xe4, 0x54, 0xfa, 0x3f, 0x52, 0x60, 0xbc, 0xa3, 0x1b, 0xb7, 0xf5, 0x16, 0x56, 0x12, 0x54, 0x2c, 0x2e, 0x51, 0x09, 0xa0, 0x81, 0x3b, 0xd8, 0x6e, 0x60, 0xdb, 0x38, 0x56, 0x92, 0x73, 0xc9, 0x85, 0x9c, 0x1a, 0x91, 0xa0, 0xa7, 0x61, 0xaa, 0xd3, 0xad, 0x5b, 0xa6, 0xa1, 0x45, 0xcc, 0x60, 0x2e, 0xb9, 0x90, 0x56, 0x65, 0xa6, 0xd8, 0x08, 0x8d, 0x9f, 0x80, 0xc9, 0x97, 0xb1, 0x7e, 0x3b, 0x6a, 0x9a, 0xa7, 0xa6, 0x45, 0x22, 0x8e, 0x18, 0xae, 0x43, 0xa1, 0x8d, 0x3d, 0x4f, 0x6f, 0x61, 0xcd, 0x3f, 0xee, 0x60, 0x25, 0x45, 0x9f, 0x7e, 0x6e, 0xe0, 0xe9, 0xfb, 0x9f, 0x3c, 0xcf, 0x51, 0x07, 0xc7, 0x1d, 0x8c, 0x2a, 0x90, 0xc3, 0x76, 0xb7, 0xcd, 0x18, 0xd2, 0xa7, 0xc4, 0xaf, 0x6a, 0x77, 0xdb, 0xfd, 0x2c, 0x59, 0x02, 0xe3, 0x14, 0xe3, 0x1e, 0x76, 0xef, 0x98, 0x06, 0x56, 0x32, 0x94, 0xe0, 0x89, 0x01, 0x82, 0x1a, 0xd3, 0xf7, 0x73, 0x08, 0x1c, 0x5a, 0x87, 0x1c, 0x7e, 0xc5, 0xc7, 0xb6, 0x67, 0x3a, 0xb6, 0x32, 0x4e, 0x49, 0x1e, 0x1f, 0xb2, 0x8a, 0xd8, 0x6a, 0xf4, 0x53, 0x84, 0x38, 0x74, 0x19, 0xc6, 0x9d, 0x8e, 0x6f, 0x3a, 0xb6, 0xa7, 0x64, 0xe7, 0xa4, 0x85, 0xfc, 0xd2, 0x87, 0x86, 0x26, 0xc2, 0x1e, 0xb3, 0x51, 0x85, 0x31, 0xda, 0x02, 0xd9, 0x73, 0xba, 0xae, 0x81, 0x35, 0xc3, 0x69, 0x60, 0xcd, 0xb4, 0x9b, 0x8e, 0x92, 0xa3, 0x04, 0x17, 0x06, 0x1f, 0x84, 0x1a, 0xae, 0x3b, 0x0d, 0xbc, 0x65, 0x37, 0x1d, 0xb5, 0xe8, 0xf5, 0x5c, 0xa3, 0x73, 0x90, 0xf1, 0x8e, 0x6d, 0x5f, 0x7f, 0x45, 0x29, 0xd0, 0x0c, 0xe1, 0x57, 0xf3, 0xff, 0x97, 0x86, 0xc9, 0x51, 0x52, 0xec, 0x3a, 0xa4, 0x9b, 0xe4, 0x29, 0x95, 0xc4, 0x59, 0x62, 0xc0, 0x30, 0xbd, 0x41, 0xcc, 0xfc, 0x84, 0x41, 0xac, 0x40, 0xde, 0xc6, 0x9e, 0x8f, 0x1b, 0x2c, 0x23, 0x92, 0x23, 0xe6, 0x14, 0x30, 0xd0, 0x60, 0x4a, 0xa5, 0x7e, 0xa2, 0x94, 0x7a, 0x11, 0x26, 0x03, 0x97, 0x34, 0x57, 0xb7, 0x5b, 0x22, 0x37, 0x2f, 0xc5, 0x79, 0xb2, 0x58, 0x15, 0x38, 0x95, 0xc0, 0xd4, 0x22, 0xee, 0xb9, 0x46, 0x1b, 0x00, 0x8e, 0x8d, 0x9d, 0xa6, 0xd6, 0xc0, 0x86, 0xa5, 0x64, 0x4f, 0x89, 0xd2, 0x1e, 0x31, 0x19, 0x88, 0x92, 0xc3, 0xa4, 0x86, 0x85, 0xae, 0x85, 0xa9, 0x36, 0x7e, 0x4a, 0xa6, 0xec, 0xb0, 0x4d, 0x36, 0x90, 0x6d, 0x87, 0x50, 0x74, 0x31, 0xc9, 0x7b, 0xdc, 0xe0, 0x4f, 0x96, 0xa3, 0x4e, 0x2c, 0xc6, 0x3e, 0x99, 0xca, 0x61, 0xec, 0xc1, 0x26, 0xdc, 0xe8, 0x25, 0xfa, 0x30, 0x04, 0x02, 0x8d, 0xa6, 0x15, 0xd0, 0x2a, 0x54, 0x10, 0xc2, 0x5d, 0xbd, 0x8d, 0x67, 0xaf, 0x42, 0xb1, 0x37, 0x3c, 0x68, 0x06, 0xd2, 0x9e, 0xaf, 0xbb, 0x3e, 0xcd, 0xc2, 0xb4, 0xca, 0x2e, 0x90, 0x0c, 0x49, 0x6c, 0x37, 0x68, 0x95, 0x4b, 0xab, 0xe4, 0xdf, 0xd9, 0x2b, 0x30, 0xd1, 0x73, 0xfb, 0x51, 0x81, 0xf3, 0x5f, 0xc8, 0xc0, 0xcc, 0xb0, 0x9c, 0x1b, 0x9a, 0xfe, 0xe7, 0x20, 0x63, 0x77, 0xdb, 0x75, 0xec, 0x2a, 0x49, 0xca, 0xc0, 0xaf, 0x50, 0x05, 0xd2, 0x96, 0x5e, 0xc7, 0x96, 0x92, 0x9a, 0x93, 0x16, 0x8a, 0x4b, 0x4f, 0x8f, 0x94, 0xd5, 0x8b, 0xdb, 0x04, 0xa2, 0x32, 0x24, 0xfa, 0x18, 0xa4, 0x78, 0x89, 0x23, 0x0c, 0x4f, 0x8d, 0xc6, 0x40, 0x72, 0x51, 0xa5, 0x38, 0xf4, 0x08, 0xe4, 0xc8, 0x5f, 0x16, 0xdb, 0x0c, 0xf5, 0x39, 0x4b, 0x04, 0x24, 0xae, 0x68, 0x16, 0xb2, 0x34, 0xcd, 0x1a, 0x58, 0xb4, 0x86, 0xe0, 0x9a, 0x2c, 0x4c, 0x03, 0x37, 0xf5, 0xae, 0xe5, 0x6b, 0x77, 0x74, 0xab, 0x8b, 0x69, 0xc2, 0xe4, 0xd4, 0x02, 0x17, 0x7e, 0x82, 0xc8, 0xd0, 0x05, 0xc8, 0xb3, 0xac, 0x34, 0xed, 0x06, 0x7e, 0x85, 0x56, 0x9f, 0xb4, 0xca, 0x12, 0x75, 0x8b, 0x48, 0xc8, 0xed, 0x6f, 0x79, 0x8e, 0x2d, 0x96, 0x96, 0xde, 0x82, 0x08, 0xe8, 0xed, 0xaf, 0xf4, 0x17, 0xbe, 0x47, 0x87, 0x3f, 0x5e, 0x7f, 0x2e, 0xce, 0x7f, 0x2b, 0x01, 0x29, 0xba, 0xdf, 0x26, 0x21, 0x7f, 0xf0, 0xd2, 0x7e, 0x55, 0xdb, 0xd8, 0x3b, 0x5c, 0xdb, 0xae, 0xca, 0x12, 0x2a, 0x02, 0x50, 0xc1, 0x0b, 0xdb, 0x7b, 0x95, 0x03, 0x39, 0x11, 0x5c, 0x6f, 0xed, 0x1e, 0x5c, 0x5e, 0x91, 0x93, 0x01, 0xe0, 0x90, 0x09, 0x52, 0x51, 0x83, 0xe5, 0x25, 0x39, 0x8d, 0x64, 0x28, 0x30, 0x82, 0xad, 0x17, 0xab, 0x1b, 0x97, 0x57, 0xe4, 0x4c, 0xaf, 0x64, 0x79, 0x49, 0x1e, 0x47, 0x13, 0x90, 0xa3, 0x92, 0xb5, 0xbd, 0xbd, 0x6d, 0x39, 0x1b, 0x70, 0xd6, 0x0e, 0xd4, 0xad, 0xdd, 0x4d, 0x39, 0x17, 0x70, 0x6e, 0xaa, 0x7b, 0x87, 0xfb, 0x32, 0x04, 0x0c, 0x3b, 0xd5, 0x5a, 0xad, 0xb2, 0x59, 0x95, 0xf3, 0x81, 0xc5, 0xda, 0x4b, 0x07, 0xd5, 0x9a, 0x5c, 0xe8, 0x71, 0x6b, 0x79, 0x49, 0x9e, 0x08, 0x6e, 0x51, 0xdd, 0x3d, 0xdc, 0x91, 0x8b, 0x68, 0x0a, 0x26, 0xd8, 0x2d, 0x84, 0x13, 0x93, 0x7d, 0xa2, 0xcb, 0x2b, 0xb2, 0x1c, 0x3a, 0xc2, 0x58, 0xa6, 0x7a, 0x04, 0x97, 0x57, 0x64, 0x34, 0xbf, 0x0e, 0x69, 0x9a, 0x5d, 0x08, 0x41, 0x71, 0xbb, 0xb2, 0x56, 0xdd, 0xd6, 0xf6, 0xf6, 0x0f, 0xb6, 0xf6, 0x76, 0x2b, 0xdb, 0xb2, 0x14, 0xca, 0xd4, 0xea, 0xc7, 0x0f, 0xb7, 0xd4, 0xea, 0x86, 0x9c, 0x88, 0xca, 0xf6, 0xab, 0x95, 0x83, 0xea, 0x86, 0x9c, 0x9c, 0x37, 0x60, 0x66, 0x58, 0x9d, 0x19, 0xba, 0x33, 0x22, 0x4b, 0x9c, 0x38, 0x65, 0x89, 0x29, 0xd7, 0xc0, 0x12, 0x7f, 0x55, 0x82, 0xe9, 0x21, 0xb5, 0x76, 0xe8, 0x4d, 0x9e, 0x87, 0x34, 0x4b, 0x51, 0xd6, 0x7d, 0x9e, 0x1c, 0x5a, 0xb4, 0x69, 0xc2, 0x0e, 0x74, 0x20, 0x8a, 0x8b, 0x76, 0xe0, 0xe4, 0x29, 0x1d, 0x98, 0x50, 0x0c, 0x38, 0xf9, 0x9a, 0x04, 0xca, 0x69, 0xdc, 0x31, 0x85, 0x22, 0xd1, 0x53, 0x28, 0xae, 0xf7, 0x3b, 0x70, 0xf1, 0xf4, 0x67, 0x18, 0xf0, 0xe2, 0x2d, 0x09, 0xce, 0x0d, 0x1f, 0x54, 0x86, 0xfa, 0xf0, 0x31, 0xc8, 0xb4, 0xb1, 0x7f, 0xe4, 0x88, 0x66, 0xfd, 0x91, 0x21, 0x2d, 0x80, 0xa8, 0xfb, 0x63, 0xc5, 0x51, 0xd1, 0x1e, 0x92, 0x3c, 0x6d, 0xda, 0x60, 0xde, 0x0c, 0x78, 0xfa, 0xd9, 0x04, 0x3c, 0x34, 0x94, 0x7c, 0xa8, 0xa3, 0x8f, 0x02, 0x98, 0x76, 0xa7, 0xeb, 0xb3, 0x86, 0xcc, 0xea, 0x53, 0x8e, 0x4a, 0xe8, 0xde, 0x27, 0xb5, 0xa7, 0xeb, 0x07, 0xfa, 0x24, 0xd5, 0x03, 0x13, 0x51, 0x83, 0xab, 0xa1, 0xa3, 0x29, 0xea, 0x68, 0xe9, 0x94, 0x27, 0x1d, 0xe8, 0x75, 0xcf, 0x82, 0x6c, 0x58, 0x26, 0xb6, 0x7d, 0xcd, 0xf3, 0x5d, 0xac, 0xb7, 0x4d, 0xbb, 0x45, 0x0b, 0x70, 0xb6, 0x9c, 0x6e, 0xea, 0x96, 0x87, 0xd5, 0x49, 0xa6, 0xae, 0x09, 0x2d, 0x41, 0xd0, 0x2e, 0xe3, 0x46, 0x10, 0x99, 0x1e, 0x04, 0x53, 0x07, 0x88, 0xf9, 0xcf, 0x8d, 0x43, 0x3e, 0x32, 0xd6, 0xa1, 0x8b, 0x50, 0xb8, 0xa5, 0xdf, 0xd1, 0x35, 0x31, 0xaa, 0xb3, 0x48, 0xe4, 0x89, 0x6c, 0x9f, 0x8f, 0xeb, 0xcf, 0xc2, 0x0c, 0x35, 0x71, 0xba, 0x3e, 0x76, 0x35, 0xc3, 0xd2, 0x3d, 0x8f, 0x06, 0x2d, 0x4b, 0x4d, 0x11, 0xd1, 0xed, 0x11, 0xd5, 0xba, 0xd0, 0xa0, 0x55, 0x98, 0xa6, 0x88, 0x76, 0xd7, 0xf2, 0xcd, 0x8e, 0x85, 0x35, 0xf2, 0xf2, 0xe0, 0xd1, 0x42, 0x1c, 0x78, 0x36, 0x45, 0x2c, 0x76, 0xb8, 0x01, 0xf1, 0xc8, 0x43, 0x9b, 0xf0, 0x28, 0x85, 0xb5, 0xb0, 0x8d, 0x5d, 0xdd, 0xc7, 0x1a, 0xfe, 0xa5, 0xae, 0x6e, 0x79, 0x9a, 0x6e, 0x37, 0xb4, 0x23, 0xdd, 0x3b, 0x52, 0x66, 0xa2, 0x04, 0xe7, 0x89, 0xed, 0x26, 0x37, 0xad, 0x52, 0xcb, 0x8a, 0xdd, 0xb8, 0xa1, 0x7b, 0x47, 0xa8, 0x0c, 0xe7, 0x28, 0x91, 0xe7, 0xbb, 0xa6, 0xdd, 0xd2, 0x8c, 0x23, 0x6c, 0xdc, 0xd6, 0xba, 0x7e, 0xf3, 0xaa, 0xf2, 0x48, 0x94, 0x81, 0x3a, 0x59, 0xa3, 0x36, 0xeb, 0xc4, 0xe4, 0xd0, 0x6f, 0x5e, 0x45, 0x35, 0x28, 0x90, 0xf5, 0x68, 0x9b, 0xaf, 0x62, 0xad, 0xe9, 0xb8, 0xb4, 0xb9, 0x14, 0x87, 0x6c, 0xee, 0x48, 0x10, 0x17, 0xf7, 0x38, 0x60, 0xc7, 0x69, 0xe0, 0x72, 0xba, 0xb6, 0x5f, 0xad, 0x6e, 0xa8, 0x79, 0xc1, 0xf2, 0x82, 0xe3, 0x92, 0x9c, 0x6a, 0x39, 0x41, 0x8c, 0xf3, 0x2c, 0xa7, 0x5a, 0x8e, 0x88, 0xf0, 0x2a, 0x4c, 0x1b, 0x06, 0x7b, 0x6c, 0xd3, 0xd0, 0xf8, 0x94, 0xef, 0x29, 0x72, 0x4f, 0xbc, 0x0c, 0x63, 0x93, 0x19, 0xf0, 0x34, 0xf7, 0xd0, 0x35, 0x78, 0x28, 0x8c, 0x57, 0x14, 0x38, 0x35, 0xf0, 0x94, 0xfd, 0xd0, 0x55, 0x98, 0xee, 0x1c, 0x0f, 0x02, 0x51, 0xcf, 0x1d, 0x3b, 0xc7, 0xfd, 0xb0, 0xc7, 0xe9, 0x9b, 0x9b, 0x8b, 0x0d, 0xdd, 0xc7, 0x0d, 0xe5, 0xe1, 0xa8, 0x75, 0x44, 0x81, 0x2e, 0x81, 0x6c, 0x18, 0x1a, 0xb6, 0xf5, 0xba, 0x85, 0x35, 0xdd, 0xc5, 0xb6, 0xee, 0x29, 0x17, 0xa2, 0xc6, 0x45, 0xc3, 0xa8, 0x52, 0x6d, 0x85, 0x2a, 0xd1, 0x53, 0x30, 0xe5, 0xd4, 0x6f, 0x19, 0x2c, 0xb9, 0xb4, 0x8e, 0x8b, 0x9b, 0xe6, 0x2b, 0xca, 0x63, 0x34, 0x4c, 0x93, 0x44, 0x41, 0x53, 0x6b, 0x9f, 0x8a, 0xd1, 0x93, 0x20, 0x1b, 0xde, 0x91, 0xee, 0x76, 0x68, 0x77, 0xf7, 0x3a, 0xba, 0x81, 0x95, 0xc7, 0x99, 0x29, 0x93, 0xef, 0x0a, 0x31, 0x7a, 0x11, 0x66, 0xba, 0xb6, 0x69, 0xfb, 0xd8, 0xed, 0xb8, 0x98, 0x0c, 0xe9, 0x6c, 0xa7, 0x29, 0xff, 0x3a, 0x7e, 0xca, 0x98, 0x7d, 0x18, 0xb5, 0x66, 0xab, 0xab, 0x4e, 0x77, 0x07, 0x85, 0xf3, 0x65, 0x28, 0x44, 0x17, 0x1d, 0xe5, 0x80, 0x2d, 0xbb, 0x2c, 0x91, 0x1e, 0xba, 0xbe, 0xb7, 0x41, 0xba, 0xdf, 0xa7, 0xaa, 0x72, 0x82, 0x74, 0xe1, 0xed, 0xad, 0x83, 0xaa, 0xa6, 0x1e, 0xee, 0x1e, 0x6c, 0xed, 0x54, 0xe5, 0xe4, 0x53, 0xb9, 0xec, 0x0f, 0xc7, 0xe5, 0xbb, 0x77, 0xef, 0xde, 0x4d, 0xcc, 0x7f, 0x27, 0x01, 0xc5, 0xde, 0xc9, 0x17, 0xfd, 0x22, 0x3c, 0x2c, 0x5e, 0x53, 0x3d, 0xec, 0x6b, 0x2f, 0x9b, 0x2e, 0xcd, 0xc3, 0xb6, 0xce, 0x66, 0xc7, 0x20, 0x84, 0x33, 0xdc, 0xaa, 0x86, 0xfd, 0x4f, 0x9a, 0x2e, 0xc9, 0xb2, 0xb6, 0xee, 0xa3, 0x6d, 0xb8, 0x60, 0x3b, 0x9a, 0xe7, 0xeb, 0x76, 0x43, 0x77, 0x1b, 0x5a, 0x78, 0x40, 0xa0, 0xe9, 0x86, 0x81, 0x3d, 0xcf, 0x61, 0x2d, 0x20, 0x60, 0xf9, 0x90, 0xed, 0xd4, 0xb8, 0x71, 0x58, 0x1b, 0x2b, 0xdc, 0xb4, 0x6f, 0xb9, 0x93, 0xa7, 0x2d, 0xf7, 0x23, 0x90, 0x6b, 0xeb, 0x1d, 0x0d, 0xdb, 0xbe, 0x7b, 0x4c, 0xe7, 0xb5, 0xac, 0x9a, 0x6d, 0xeb, 0x9d, 0x2a, 0xb9, 0xfe, 0xe9, 0xad, 0x41, 0x34, 0x8e, 0xdf, 0x4f, 0x42, 0x21, 0x3a, 0xb3, 0x91, 0x11, 0xd8, 0xa0, 0xf5, 0x59, 0xa2, 0xdb, 0xf7, 0xc3, 0x0f, 0x9c, 0xf0, 0x16, 0xd7, 0x49, 0xe1, 0x2e, 0x67, 0xd8, 0x24, 0xa5, 0x32, 0x24, 0x69, 0x9a, 0x64, 0xc3, 0x62, 0x36, 0x9f, 0x67, 0x55, 0x7e, 0x85, 0x36, 0x21, 0x73, 0xcb, 0xa3, 0xdc, 0x19, 0xca, 0xfd, 0xd8, 0x83, 0xb9, 0x6f, 0xd6, 0x28, 0x79, 0xee, 0x66, 0x4d, 0xdb, 0xdd, 0x53, 0x77, 0x2a, 0xdb, 0x2a, 0x87, 0xa3, 0xf3, 0x90, 0xb2, 0xf4, 0x57, 0x8f, 0x7b, 0x4b, 0x3c, 0x15, 0x8d, 0x1a, 0xf8, 0xf3, 0x90, 0x7a, 0x19, 0xeb, 0xb7, 0x7b, 0x0b, 0x2b, 0x15, 0xfd, 0x14, 0x53, 0xff, 0x12, 0xa4, 0x69, 0xbc, 0x10, 0x00, 0x8f, 0x98, 0x3c, 0x86, 0xb2, 0x90, 0x5a, 0xdf, 0x53, 0x49, 0xfa, 0xcb, 0x50, 0x60, 0x52, 0x6d, 0x7f, 0xab, 0xba, 0x5e, 0x95, 0x13, 0xf3, 0xab, 0x90, 0x61, 0x41, 0x20, 0x5b, 0x23, 0x08, 0x83, 0x3c, 0xc6, 0x2f, 0x39, 0x87, 0x24, 0xb4, 0x87, 0x3b, 0x6b, 0x55, 0x55, 0x4e, 0x44, 0x97, 0xd7, 0x83, 0x42, 0x74, 0x5c, 0xfb, 0xd9, 0xe4, 0xd4, 0xdf, 0x49, 0x90, 0x8f, 0x8c, 0x5f, 0xa4, 0xf1, 0xeb, 0x96, 0xe5, 0xbc, 0xac, 0xe9, 0x96, 0xa9, 0x7b, 0x3c, 0x29, 0x80, 0x8a, 0x2a, 0x44, 0x32, 0xea, 0xa2, 0xfd, 0x4c, 0x9c, 0x7f, 0x53, 0x02, 0xb9, 0x7f, 0x74, 0xeb, 0x73, 0x50, 0xfa, 0x40, 0x1d, 0x7c, 0x43, 0x82, 0x62, 0xef, 0xbc, 0xd6, 0xe7, 0xde, 0xc5, 0x0f, 0xd4, 0xbd, 0x2f, 0x49, 0x30, 0xd1, 0x33, 0xa5, 0xfd, 0x5c, 0x79, 0xf7, 0x7a, 0x12, 0xa6, 0x87, 0xe0, 0x50, 0x85, 0x8f, 0xb3, 0x6c, 0xc2, 0x7e, 0x66, 0x94, 0x7b, 0x2d, 0x92, 0x6e, 0xb9, 0xaf, 0xbb, 0x3e, 0x9f, 0x7e, 0x9f, 0x04, 0xd9, 0x6c, 0x60, 0xdb, 0x37, 0x9b, 0x26, 0x76, 0xf9, 0x2b, 0x38, 0x9b, 0x71, 0x27, 0x43, 0x39, 0x7b, 0x0b, 0xff, 0x05, 0x40, 0x1d, 0xc7, 0x33, 0x7d, 0xf3, 0x0e, 0xd6, 0x4c, 0x5b, 0xbc, 0xaf, 0x93, 0x99, 0x37, 0xa5, 0xca, 0x42, 0xb3, 0x65, 0xfb, 0x81, 0xb5, 0x8d, 0x5b, 0x7a, 0x9f, 0x35, 0xa9, 0x7d, 0x49, 0x55, 0x16, 0x9a, 0xc0, 0xfa, 0x22, 0x14, 0x1a, 0x4e, 0x97, 0x8c, 0x0f, 0xcc, 0x8e, 0x94, 0x5a, 0x49, 0xcd, 0x33, 0x59, 0x60, 0xc2, 0xe7, 0xbb, 0xf0, 0xa0, 0xa0, 0xa0, 0xe6, 0x99, 0x8c, 0x99, 0x3c, 0x01, 0x93, 0x7a, 0xab, 0xe5, 0x12, 0x72, 0x41, 0xc4, 0x86, 0xd6, 0x62, 0x20, 0xa6, 0x86, 0xb3, 0x37, 0x21, 0x2b, 0xe2, 0x40, 0xba, 0x19, 0x89, 0x84, 0xd6, 0x61, 0xc7, 0x35, 0x89, 0x85, 0x9c, 0x9a, 0xb5, 0x85, 0xf2, 0x22, 0x14, 0x4c, 0x4f, 0x0b, 0xcf, 0x0d, 0x13, 0x73, 0x89, 0x85, 0xac, 0x9a, 0x37, 0xbd, 0xe0, 0xa0, 0x68, 0xfe, 0xad, 0x04, 0x14, 0x7b, 0xcf, 0x3d, 0xd1, 0x06, 0x64, 0x2d, 0xc7, 0xd0, 0x69, 0x22, 0xb0, 0x43, 0xf7, 0x85, 0x98, 0xa3, 0xd2, 0xc5, 0x6d, 0x6e, 0xaf, 0x06, 0xc8, 0xd9, 0x7f, 0x92, 0x20, 0x2b, 0xc4, 0xe8, 0x1c, 0xa4, 0x3a, 0xba, 0x7f, 0x44, 0xe9, 0xd2, 0x6b, 0x09, 0x59, 0x52, 0xe9, 0x35, 0x91, 0x7b, 0x1d, 0xdd, 0xa6, 0x29, 0xc0, 0xe5, 0xe4, 0x9a, 0xac, 0xab, 0x85, 0xf5, 0x06, 0x1d, 0x87, 0x9d, 0x76, 0x1b, 0xdb, 0xbe, 0x27, 0xd6, 0x95, 0xcb, 0xd7, 0xb9, 0x18, 0x3d, 0x0d, 0x53, 0xbe, 0xab, 0x9b, 0x56, 0x8f, 0x6d, 0x8a, 0xda, 0xca, 0x42, 0x11, 0x18, 0x97, 0xe1, 0xbc, 0xe0, 0x6d, 0x60, 0x5f, 0x37, 0x8e, 0x70, 0x23, 0x04, 0x65, 0xe8, 0xa1, 0xda, 0xc3, 0xdc, 0x60, 0x83, 0xeb, 0x05, 0x76, 0xfe, 0x7b, 0x12, 0x4c, 0x89, 0x01, 0xbe, 0x11, 0x04, 0x6b, 0x07, 0x40, 0xb7, 0x6d, 0xc7, 0x8f, 0x86, 0x6b, 0x30, 0x95, 0x07, 0x70, 0x8b, 0x95, 0x00, 0xa4, 0x46, 0x08, 0x66, 0xdb, 0x00, 0xa1, 0xe6, 0xd4, 0xb0, 0x5d, 0x80, 0x3c, 0x3f, 0xd4, 0xa6, 0xbf, 0x8c, 0xb0, 0xb7, 0x3e, 0x60, 0x22, 0x32, 0xe9, 0xa3, 0x19, 0x48, 0xd7, 0x71, 0xcb, 0xb4, 0xf9, 0x51, 0x1b, 0xbb, 0x10, 0x07, 0x78, 0xa9, 0xe0, 0x00, 0x6f, 0xed, 0xd3, 0x30, 0x6d, 0x38, 0xed, 0x7e, 0x77, 0xd7, 0xe4, 0xbe, 0x37, 0x4f, 0xef, 0x86, 0xf4, 0x29, 0x08, 0xa7, 0xb3, 0xaf, 0x48, 0xd2, 0x57, 0x13, 0xc9, 0xcd, 0xfd, 0xb5, 0xaf, 0x27, 0x66, 0x37, 0x19, 0x74, 0x5f, 0x3c, 0xa9, 0x8a, 0x9b, 0x16, 0x36, 0x88, 0xf7, 0xf0, 0xa3, 0x8f, 0xc0, 0x33, 0x2d, 0xd3, 0x3f, 0xea, 0xd6, 0x17, 0x0d, 0xa7, 0x7d, 0xa9, 0xe5, 0xb4, 0x9c, 0xf0, 0xc7, 0x20, 0x72, 0x45, 0x2f, 0xe8, 0x7f, 0xfc, 0x07, 0xa1, 0x5c, 0x20, 0x9d, 0x8d, 0xfd, 0xf5, 0xa8, 0xbc, 0x0b, 0xd3, 0xdc, 0x58, 0xa3, 0x27, 0xd2, 0x6c, 0x0e, 0x47, 0x0f, 0x3c, 0x95, 0x50, 0xbe, 0xf9, 0x0e, 0xed, 0x74, 0xea, 0x14, 0x87, 0x12, 0x1d, 0x9b, 0xd4, 0xcb, 0x2a, 0x3c, 0xd4, 0xc3, 0xc7, 0xb6, 0x26, 0x76, 0x63, 0x18, 0xbf, 0xc3, 0x19, 0xa7, 0x23, 0x8c, 0x35, 0x0e, 0x2d, 0xaf, 0xc3, 0xc4, 0x59, 0xb8, 0xfe, 0x81, 0x73, 0x15, 0x70, 0x94, 0x64, 0x13, 0x26, 0x29, 0x89, 0xd1, 0xf5, 0x7c, 0xa7, 0x4d, 0xeb, 0xde, 0x83, 0x69, 0xfe, 0xf1, 0x1d, 0xb6, 0x57, 0x8a, 0x04, 0xb6, 0x1e, 0xa0, 0xca, 0x65, 0xa0, 0x87, 0xf0, 0x0d, 0x6c, 0x58, 0x31, 0x0c, 0x6f, 0x73, 0x47, 0x02, 0xfb, 0xf2, 0x27, 0x60, 0x86, 0xfc, 0x4f, 0xcb, 0x52, 0xd4, 0x93, 0xf8, 0x33, 0x18, 0xe5, 0x7b, 0xaf, 0xb1, 0xed, 0x38, 0x1d, 0x10, 0x44, 0x7c, 0x8a, 0xac, 0x62, 0x0b, 0xfb, 0x3e, 0x76, 0x3d, 0x4d, 0xb7, 0x86, 0xb9, 0x17, 0x79, 0x83, 0x55, 0xbe, 0xf8, 0x6e, 0xef, 0x2a, 0x6e, 0x32, 0x64, 0xc5, 0xb2, 0xca, 0x87, 0xf0, 0xf0, 0x90, 0xac, 0x18, 0x81, 0xf3, 0x75, 0xce, 0x39, 0x33, 0x90, 0x19, 0x84, 0x76, 0x1f, 0x84, 0x3c, 0x58, 0xcb, 0x11, 0x38, 0xbf, 0xc4, 0x39, 0x11, 0xc7, 0x8a, 0x25, 0x25, 0x8c, 0x37, 0x61, 0xea, 0x0e, 0x76, 0xeb, 0x8e, 0xc7, 0x0f, 0x0e, 0x46, 0xa0, 0x7b, 0x83, 0xd3, 0x4d, 0x72, 0x20, 0x3d, 0x46, 0x20, 0x5c, 0xd7, 0x20, 0xdb, 0xd4, 0x0d, 0x3c, 0x02, 0xc5, 0x97, 0x39, 0xc5, 0x38, 0xb1, 0x27, 0xd0, 0x0a, 0x14, 0x5a, 0x0e, 0xef, 0x4c, 0xf1, 0xf0, 0x37, 0x39, 0x3c, 0x2f, 0x30, 0x9c, 0xa2, 0xe3, 0x74, 0xba, 0x16, 0x69, 0x5b, 0xf1, 0x14, 0xbf, 0x2f, 0x28, 0x04, 0x86, 0x53, 0x9c, 0x21, 0xac, 0x5f, 0x11, 0x14, 0x5e, 0x24, 0x9e, 0xcf, 0x43, 0xde, 0xb1, 0xad, 0x63, 0xc7, 0x1e, 0xc5, 0x89, 0x3f, 0xe0, 0x0c, 0xc0, 0x21, 0x84, 0xe0, 0x3a, 0xe4, 0x46, 0x5d, 0x88, 0x3f, 0x7c, 0x57, 0x6c, 0x0f, 0xb1, 0x02, 0x9b, 0x30, 0x29, 0x0a, 0x94, 0xe9, 0xd8, 0x23, 0x50, 0xfc, 0x11, 0xa7, 0x28, 0x46, 0x60, 0xfc, 0x31, 0x7c, 0xec, 0xf9, 0x2d, 0x3c, 0x0a, 0xc9, 0x5b, 0xe2, 0x31, 0x38, 0x84, 0x87, 0xb2, 0x8e, 0x6d, 0xe3, 0x68, 0x34, 0x86, 0xaf, 0x89, 0x50, 0x0a, 0x0c, 0xa1, 0x58, 0x87, 0x89, 0xb6, 0xee, 0x7a, 0x47, 0xba, 0x35, 0xd2, 0x72, 0xfc, 0x31, 0xe7, 0x28, 0x04, 0x20, 0x1e, 0x91, 0xae, 0x7d, 0x16, 0x9a, 0xaf, 0x8b, 0x88, 0x44, 0x60, 0x7c, 0xeb, 0x79, 0x3e, 0x3d, 0x9b, 0x39, 0x0b, 0xdb, 0x9f, 0x88, 0xad, 0xc7, 0xb0, 0x3b, 0x51, 0xc6, 0xeb, 0x90, 0xf3, 0xcc, 0x57, 0x47, 0xa2, 0xf9, 0x53, 0xb1, 0xd2, 0x14, 0x40, 0xc0, 0x2f, 0xc1, 0xf9, 0xa1, 0x6d, 0x62, 0x04, 0xb2, 0x3f, 0xe3, 0x64, 0xe7, 0x86, 0xb4, 0x0a, 0x5e, 0x12, 0xce, 0x4a, 0xf9, 0xe7, 0xa2, 0x24, 0xe0, 0x3e, 0xae, 0x7d, 0x32, 0xd9, 0x7b, 0x7a, 0xf3, 0x6c, 0x51, 0xfb, 0x0b, 0x11, 0x35, 0x86, 0xed, 0x89, 0xda, 0x01, 0x9c, 0xe3, 0x8c, 0x67, 0x5b, 0xd7, 0x6f, 0x88, 0xc2, 0xca, 0xd0, 0x87, 0xbd, 0xab, 0xfb, 0x69, 0x98, 0x0d, 0xc2, 0x29, 0x86, 0x52, 0x4f, 0x6b, 0xeb, 0x9d, 0x11, 0x98, 0xbf, 0xc9, 0x99, 0x45, 0xc5, 0x0f, 0xa6, 0x5a, 0x6f, 0x47, 0xef, 0x10, 0xf2, 0x17, 0x41, 0x11, 0xe4, 0x5d, 0xdb, 0xc5, 0x86, 0xd3, 0xb2, 0xcd, 0x57, 0x71, 0x63, 0x04, 0xea, 0xbf, 0xec, 0x5b, 0xaa, 0xc3, 0x08, 0x9c, 0x30, 0x6f, 0x81, 0x1c, 0xcc, 0x2a, 0x9a, 0xd9, 0xee, 0x38, 0xae, 0x1f, 0xc3, 0xf8, 0x57, 0x62, 0xa5, 0x02, 0xdc, 0x16, 0x85, 0x95, 0xab, 0x50, 0xa4, 0x97, 0xa3, 0xa6, 0xe4, 0x5f, 0x73, 0xa2, 0x89, 0x10, 0xc5, 0x0b, 0x87, 0xe1, 0xb4, 0x3b, 0xba, 0x3b, 0x4a, 0xfd, 0xfb, 0x1b, 0x51, 0x38, 0x38, 0x84, 0x17, 0x0e, 0xff, 0xb8, 0x83, 0x49, 0xb7, 0x1f, 0x81, 0xe1, 0x5b, 0xa2, 0x70, 0x08, 0x0c, 0xa7, 0x10, 0x03, 0xc3, 0x08, 0x14, 0x7f, 0x2b, 0x28, 0x04, 0x86, 0x50, 0x7c, 0x3c, 0x6c, 0xb4, 0x2e, 0x6e, 0x99, 0x9e, 0xef, 0xb2, 0x51, 0xf8, 0xc1, 0x54, 0xdf, 0x7e, 0xb7, 0x77, 0x08, 0x53, 0x23, 0xd0, 0xf2, 0x4d, 0x98, 0xec, 0x1b, 0x31, 0x50, 0xdc, 0x2f, 0xfa, 0xca, 0x67, 0xde, 0xe7, 0xc5, 0xa8, 0x77, 0xc2, 0x28, 0x6f, 0x93, 0x75, 0xef, 0x9d, 0x03, 0xe2, 0xc9, 0x5e, 0x7b, 0x3f, 0x58, 0xfa, 0x9e, 0x31, 0xa0, 0xfc, 0x02, 0x4c, 0xf4, 0xcc, 0x00, 0xf1, 0x54, 0xbf, 0xcc, 0xa9, 0x0a, 0xd1, 0x11, 0xa0, 0xbc, 0x0a, 0x29, 0xd2, 0xcf, 0xe3, 0xe1, 0xbf, 0xc2, 0xe1, 0xd4, 0xbc, 0xfc, 0x51, 0xc8, 0x8a, 0x3e, 0x1e, 0x0f, 0xfd, 0x55, 0x0e, 0x0d, 0x20, 0x04, 0x2e, 0x7a, 0x78, 0x3c, 0xfc, 0xd7, 0x04, 0x5c, 0x40, 0x08, 0x7c, 0xf4, 0x10, 0xfe, 0xfd, 0xe7, 0x52, 0xbc, 0x0e, 0x8b, 0xd8, 0x5d, 0x87, 0x71, 0xde, 0xbc, 0xe3, 0xd1, 0x9f, 0xe5, 0x37, 0x17, 0x88, 0xf2, 0x15, 0x48, 0x8f, 0x18, 0xf0, 0x5f, 0xe7, 0x50, 0x66, 0x5f, 0x5e, 0x87, 0x7c, 0xa4, 0x61, 0xc7, 0xc3, 0x7f, 0x83, 0xc3, 0xa3, 0x28, 0xe2, 0x3a, 0x6f, 0xd8, 0xf1, 0x04, 0xbf, 0x29, 0x5c, 0xe7, 0x08, 0x12, 0x36, 0xd1, 0xab, 0xe3, 0xd1, 0xbf, 0x25, 0xa2, 0x2e, 0x20, 0xe5, 0xe7, 0x21, 0x17, 0xd4, 0xdf, 0x78, 0xfc, 0x6f, 0x73, 0x7c, 0x88, 0x21, 0x11, 0x88, 0xd4, 0xff, 0x78, 0x8a, 0xdf, 0x11, 0x11, 0x88, 0xa0, 0xc8, 0x36, 0xea, 0xef, 0xe9, 0xf1, 0x4c, 0x9f, 0x17, 0xdb, 0xa8, 0xaf, 0xa5, 0x93, 0xd5, 0xa4, 0x65, 0x30, 0x9e, 0xe2, 0x77, 0xc5, 0x6a, 0x52, 0x7b, 0xe2, 0x46, 0x7f, 0x93, 0x8c, 0xe7, 0xf8, 0x3d, 0xe1, 0x46, 0x5f, 0x8f, 0x2c, 0xef, 0x03, 0x1a, 0x6c, 0x90, 0xf1, 0x7c, 0x5f, 0xe0, 0x7c, 0x53, 0x03, 0xfd, 0xb1, 0xfc, 0x49, 0x38, 0x37, 0xbc, 0x39, 0xc6, 0xb3, 0x7e, 0xf1, 0xfd, 0xbe, 0xd7, 0x99, 0x68, 0x6f, 0x2c, 0x1f, 0x84, 0x55, 0x36, 0xda, 0x18, 0xe3, 0x69, 0x5f, 0x7f, 0xbf, 0xb7, 0xd0, 0x46, 0xfb, 0x62, 0xb9, 0x02, 0x10, 0xf6, 0xa4, 0x78, 0xae, 0x37, 0x38, 0x57, 0x04, 0x44, 0xb6, 0x06, 0x6f, 0x49, 0xf1, 0xf8, 0x2f, 0x8b, 0xad, 0xc1, 0x11, 0x64, 0x6b, 0x88, 0x6e, 0x14, 0x8f, 0x7e, 0x53, 0x6c, 0x0d, 0x01, 0x29, 0x5f, 0x87, 0xac, 0xdd, 0xb5, 0x2c, 0x92, 0x5b, 0xe8, 0xc1, 0x1f, 0xd9, 0x28, 0xff, 0x76, 0x9f, 0x83, 0x05, 0xa0, 0xbc, 0x0a, 0x69, 0xdc, 0xae, 0xe3, 0x46, 0x1c, 0xf2, 0xdf, 0xef, 0x8b, 0x7a, 0x42, 0xac, 0xcb, 0xcf, 0x03, 0xb0, 0x97, 0x69, 0xfa, 0x1b, 0x4b, 0x0c, 0xf6, 0x3f, 0xee, 0xf3, 0xdf, 0xef, 0x43, 0x48, 0x48, 0xc0, 0xbe, 0x06, 0x78, 0x30, 0xc1, 0xbb, 0xbd, 0x04, 0xf4, 0x05, 0xfc, 0x1a, 0x8c, 0xdf, 0xf2, 0x1c, 0xdb, 0xd7, 0x5b, 0x71, 0xe8, 0xff, 0xe4, 0x68, 0x61, 0x4f, 0x02, 0xd6, 0x76, 0x5c, 0xec, 0xeb, 0x2d, 0x2f, 0x0e, 0xfb, 0x5f, 0x1c, 0x1b, 0x00, 0x08, 0xd8, 0xd0, 0x3d, 0x7f, 0x94, 0xe7, 0xfe, 0x6f, 0x01, 0x16, 0x00, 0xe2, 0x34, 0xf9, 0xff, 0x36, 0x3e, 0x8e, 0xc3, 0xbe, 0x27, 0x9c, 0xe6, 0xf6, 0xe5, 0x8f, 0x42, 0x8e, 0xfc, 0xcb, 0xbe, 0x69, 0x89, 0x01, 0xff, 0x0f, 0x07, 0x87, 0x08, 0x72, 0x67, 0xcf, 0x6f, 0xf8, 0x66, 0x7c, 0xb0, 0xff, 0x97, 0xaf, 0xb4, 0xb0, 0x2f, 0x57, 0x20, 0xef, 0xf9, 0x8d, 0x46, 0x97, 0x4f, 0x34, 0x31, 0xf0, 0x1f, 0xdd, 0x0f, 0x5e, 0x72, 0x03, 0xcc, 0xda, 0xc5, 0xe1, 0xe7, 0x75, 0xb0, 0xe9, 0x6c, 0x3a, 0xec, 0xa4, 0x0e, 0x3e, 0x9f, 0x86, 0x87, 0x0c, 0xa7, 0x5d, 0x77, 0xbc, 0x4b, 0x75, 0xc7, 0x3f, 0xba, 0xe4, 0xd8, 0xdc, 0x10, 0x25, 0x1d, 0x1b, 0xcf, 0x9e, 0xed, 0x44, 0x6e, 0xfe, 0x3c, 0xa4, 0x6b, 0xdd, 0x7a, 0xfd, 0x18, 0xc9, 0x90, 0xf4, 0xba, 0x75, 0xfe, 0xc1, 0x05, 0xf9, 0x77, 0xfe, 0xfb, 0x49, 0xc8, 0xd7, 0xf4, 0x76, 0xc7, 0xc2, 0x7b, 0x36, 0xde, 0x6b, 0x22, 0x05, 0x32, 0xf4, 0x01, 0x9e, 0xa3, 0x46, 0xd2, 0x8d, 0x31, 0x95, 0x5f, 0x07, 0x9a, 0x25, 0x7a, 0x52, 0x99, 0x08, 0x34, 0x4b, 0x81, 0x66, 0x99, 0x1d, 0x54, 0x06, 0x9a, 0xe5, 0x40, 0xb3, 0x42, 0x8f, 0x2b, 0x93, 0x81, 0x66, 0x25, 0xd0, 0xac, 0xd2, 0xe3, 0xf8, 0x89, 0x40, 0xb3, 0x1a, 0x68, 0x2e, 0xd3, 0x03, 0xf8, 0x54, 0xa0, 0xb9, 0x1c, 0x68, 0xae, 0xd0, 0x73, 0xf7, 0xa9, 0x40, 0x73, 0x25, 0xd0, 0x5c, 0xa5, 0x67, 0xed, 0x28, 0xd0, 0x5c, 0x0d, 0x34, 0xd7, 0xe8, 0x47, 0x15, 0xe3, 0x81, 0xe6, 0x1a, 0x9a, 0x85, 0x71, 0xf6, 0x64, 0xcf, 0xd2, 0xdf, 0x32, 0x27, 0x6f, 0x8c, 0xa9, 0x42, 0x10, 0xea, 0x9e, 0xa3, 0x1f, 0x4e, 0x64, 0x42, 0xdd, 0x73, 0xa1, 0x6e, 0x89, 0x7e, 0x41, 0x2c, 0x87, 0xba, 0xa5, 0x50, 0xb7, 0xac, 0x4c, 0x90, 0x75, 0x0f, 0x75, 0xcb, 0xa1, 0x6e, 0x45, 0x29, 0x92, 0xf8, 0x87, 0xba, 0x95, 0x50, 0xb7, 0xaa, 0x4c, 0xce, 0x49, 0x0b, 0x85, 0x50, 0xb7, 0x8a, 0x9e, 0x81, 0xbc, 0xd7, 0xad, 0x6b, 0xfc, 0xa7, 0x77, 0xfa, 0x81, 0x46, 0x7e, 0x09, 0x16, 0x49, 0x46, 0xd0, 0x45, 0xbd, 0x31, 0xa6, 0x82, 0xd7, 0xad, 0xf3, 0xc2, 0xb8, 0x56, 0x00, 0x7a, 0x8e, 0xa0, 0xd1, 0x2f, 0x13, 0xd7, 0x36, 0xde, 0xbe, 0x57, 0x1a, 0xfb, 0xee, 0xbd, 0xd2, 0xd8, 0x3f, 0xdf, 0x2b, 0x8d, 0xfd, 0xe0, 0x5e, 0x49, 0x7a, 0xef, 0x5e, 0x49, 0xfa, 0xf1, 0xbd, 0x92, 0x74, 0xf7, 0xa4, 0x24, 0x7d, 0xed, 0xa4, 0x24, 0x7d, 0xe3, 0xa4, 0x24, 0x7d, 0xfb, 0xa4, 0x24, 0xbd, 0x7d, 0x52, 0x92, 0xbe, 0x7b, 0x52, 0x92, 0x7e, 0x70, 0x52, 0x92, 0x7e, 0x78, 0x52, 0x1a, 0x7b, 0xef, 0xa4, 0x24, 0xfd, 0xf8, 0xa4, 0x34, 0x76, 0xf7, 0x5f, 0x4a, 0x63, 0xf5, 0x0c, 0x4d, 0xa3, 0xe5, 0xff, 0x0f, 0x00, 0x00, 0xff, 0xff, 0x34, 0x19, 0xac, 0x3a, 0x10, 0x30, 0x00, 0x00, } r := bytes.NewReader(gzipped) gzipr, err := compress_gzip.NewReader(r) if err != nil { panic(err) } ungzipped, err := io_ioutil.ReadAll(gzipr) if err != nil { panic(err) } if err := github_com_gogo_protobuf_proto.Unmarshal(ungzipped, d); err != nil { panic(err) } return d } func (this *Subby) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*Subby) if !ok { that2, ok := that.(Subby) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *Subby") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *Subby but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *Subby but is not nil && this == nil") } if this.Sub != that1.Sub { return fmt.Errorf("Sub this(%v) Not Equal that(%v)", this.Sub, that1.Sub) } return nil } func (this *Subby) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*Subby) if !ok { that2, ok := that.(Subby) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Sub != that1.Sub { return false } return true } func (this *SampleOneOf) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf) if !ok { that2, ok := that.(SampleOneOf) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf but is not nil && this == nil") } if that1.TestOneof == nil { if this.TestOneof != nil { return fmt.Errorf("this.TestOneof != nil && that1.TestOneof == nil") } } else if this.TestOneof == nil { return fmt.Errorf("this.TestOneof == nil && that1.TestOneof != nil") } else if err := this.TestOneof.VerboseEqual(that1.TestOneof); err != nil { return err } return nil } func (this *SampleOneOf_Field1) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field1) if !ok { that2, ok := that.(SampleOneOf_Field1) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field1") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field1 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field1 but is not nil && this == nil") } if this.Field1 != that1.Field1 { return fmt.Errorf("Field1 this(%v) Not Equal that(%v)", this.Field1, that1.Field1) } return nil } func (this *SampleOneOf_Field2) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field2) if !ok { that2, ok := that.(SampleOneOf_Field2) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field2") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field2 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field2 but is not nil && this == nil") } if this.Field2 != that1.Field2 { return fmt.Errorf("Field2 this(%v) Not Equal that(%v)", this.Field2, that1.Field2) } return nil } func (this *SampleOneOf_Field3) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field3) if !ok { that2, ok := that.(SampleOneOf_Field3) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field3") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field3 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field3 but is not nil && this == nil") } if this.Field3 != that1.Field3 { return fmt.Errorf("Field3 this(%v) Not Equal that(%v)", this.Field3, that1.Field3) } return nil } func (this *SampleOneOf_Field4) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field4) if !ok { that2, ok := that.(SampleOneOf_Field4) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field4") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field4 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field4 but is not nil && this == nil") } if this.Field4 != that1.Field4 { return fmt.Errorf("Field4 this(%v) Not Equal that(%v)", this.Field4, that1.Field4) } return nil } func (this *SampleOneOf_Field5) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field5) if !ok { that2, ok := that.(SampleOneOf_Field5) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field5") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field5 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field5 but is not nil && this == nil") } if this.Field5 != that1.Field5 { return fmt.Errorf("Field5 this(%v) Not Equal that(%v)", this.Field5, that1.Field5) } return nil } func (this *SampleOneOf_Field6) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field6) if !ok { that2, ok := that.(SampleOneOf_Field6) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field6") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field6 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field6 but is not nil && this == nil") } if this.Field6 != that1.Field6 { return fmt.Errorf("Field6 this(%v) Not Equal that(%v)", this.Field6, that1.Field6) } return nil } func (this *SampleOneOf_Field7) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field7) if !ok { that2, ok := that.(SampleOneOf_Field7) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field7") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field7 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field7 but is not nil && this == nil") } if this.Field7 != that1.Field7 { return fmt.Errorf("Field7 this(%v) Not Equal that(%v)", this.Field7, that1.Field7) } return nil } func (this *SampleOneOf_Field8) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field8) if !ok { that2, ok := that.(SampleOneOf_Field8) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field8") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field8 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field8 but is not nil && this == nil") } if this.Field8 != that1.Field8 { return fmt.Errorf("Field8 this(%v) Not Equal that(%v)", this.Field8, that1.Field8) } return nil } func (this *SampleOneOf_Field9) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field9) if !ok { that2, ok := that.(SampleOneOf_Field9) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field9") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field9 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field9 but is not nil && this == nil") } if this.Field9 != that1.Field9 { return fmt.Errorf("Field9 this(%v) Not Equal that(%v)", this.Field9, that1.Field9) } return nil } func (this *SampleOneOf_Field10) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field10) if !ok { that2, ok := that.(SampleOneOf_Field10) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field10") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field10 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field10 but is not nil && this == nil") } if this.Field10 != that1.Field10 { return fmt.Errorf("Field10 this(%v) Not Equal that(%v)", this.Field10, that1.Field10) } return nil } func (this *SampleOneOf_Field11) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field11) if !ok { that2, ok := that.(SampleOneOf_Field11) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field11") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field11 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field11 but is not nil && this == nil") } if this.Field11 != that1.Field11 { return fmt.Errorf("Field11 this(%v) Not Equal that(%v)", this.Field11, that1.Field11) } return nil } func (this *SampleOneOf_Field12) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field12) if !ok { that2, ok := that.(SampleOneOf_Field12) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field12") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field12 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field12 but is not nil && this == nil") } if this.Field12 != that1.Field12 { return fmt.Errorf("Field12 this(%v) Not Equal that(%v)", this.Field12, that1.Field12) } return nil } func (this *SampleOneOf_Field13) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field13) if !ok { that2, ok := that.(SampleOneOf_Field13) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field13") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field13 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field13 but is not nil && this == nil") } if this.Field13 != that1.Field13 { return fmt.Errorf("Field13 this(%v) Not Equal that(%v)", this.Field13, that1.Field13) } return nil } func (this *SampleOneOf_Field14) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field14) if !ok { that2, ok := that.(SampleOneOf_Field14) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field14") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field14 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field14 but is not nil && this == nil") } if this.Field14 != that1.Field14 { return fmt.Errorf("Field14 this(%v) Not Equal that(%v)", this.Field14, that1.Field14) } return nil } func (this *SampleOneOf_Field15) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field15) if !ok { that2, ok := that.(SampleOneOf_Field15) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field15") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field15 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field15 but is not nil && this == nil") } if !bytes.Equal(this.Field15, that1.Field15) { return fmt.Errorf("Field15 this(%v) Not Equal that(%v)", this.Field15, that1.Field15) } return nil } func (this *SampleOneOf_SubMessage) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_SubMessage) if !ok { that2, ok := that.(SampleOneOf_SubMessage) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_SubMessage") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_SubMessage but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_SubMessage but is not nil && this == nil") } if !this.SubMessage.Equal(that1.SubMessage) { return fmt.Errorf("SubMessage this(%v) Not Equal that(%v)", this.SubMessage, that1.SubMessage) } return nil } func (this *SampleOneOf) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf) if !ok { that2, ok := that.(SampleOneOf) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if that1.TestOneof == nil { if this.TestOneof != nil { return false } } else if this.TestOneof == nil { return false } else if !this.TestOneof.Equal(that1.TestOneof) { return false } return true } func (this *SampleOneOf_Field1) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field1) if !ok { that2, ok := that.(SampleOneOf_Field1) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field1 != that1.Field1 { return false } return true } func (this *SampleOneOf_Field2) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field2) if !ok { that2, ok := that.(SampleOneOf_Field2) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field2 != that1.Field2 { return false } return true } func (this *SampleOneOf_Field3) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field3) if !ok { that2, ok := that.(SampleOneOf_Field3) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field3 != that1.Field3 { return false } return true } func (this *SampleOneOf_Field4) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field4) if !ok { that2, ok := that.(SampleOneOf_Field4) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field4 != that1.Field4 { return false } return true } func (this *SampleOneOf_Field5) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field5) if !ok { that2, ok := that.(SampleOneOf_Field5) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field5 != that1.Field5 { return false } return true } func (this *SampleOneOf_Field6) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field6) if !ok { that2, ok := that.(SampleOneOf_Field6) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field6 != that1.Field6 { return false } return true } func (this *SampleOneOf_Field7) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field7) if !ok { that2, ok := that.(SampleOneOf_Field7) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field7 != that1.Field7 { return false } return true } func (this *SampleOneOf_Field8) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field8) if !ok { that2, ok := that.(SampleOneOf_Field8) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field8 != that1.Field8 { return false } return true } func (this *SampleOneOf_Field9) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field9) if !ok { that2, ok := that.(SampleOneOf_Field9) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field9 != that1.Field9 { return false } return true } func (this *SampleOneOf_Field10) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field10) if !ok { that2, ok := that.(SampleOneOf_Field10) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field10 != that1.Field10 { return false } return true } func (this *SampleOneOf_Field11) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field11) if !ok { that2, ok := that.(SampleOneOf_Field11) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field11 != that1.Field11 { return false } return true } func (this *SampleOneOf_Field12) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field12) if !ok { that2, ok := that.(SampleOneOf_Field12) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field12 != that1.Field12 { return false } return true } func (this *SampleOneOf_Field13) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field13) if !ok { that2, ok := that.(SampleOneOf_Field13) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field13 != that1.Field13 { return false } return true } func (this *SampleOneOf_Field14) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field14) if !ok { that2, ok := that.(SampleOneOf_Field14) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field14 != that1.Field14 { return false } return true } func (this *SampleOneOf_Field15) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field15) if !ok { that2, ok := that.(SampleOneOf_Field15) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if !bytes.Equal(this.Field15, that1.Field15) { return false } return true } func (this *SampleOneOf_SubMessage) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_SubMessage) if !ok { that2, ok := that.(SampleOneOf_SubMessage) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if !this.SubMessage.Equal(that1.SubMessage) { return false } return true } func (this *Subby) GoString() string { if this == nil { return "nil" } s := make([]string, 0, 5) s = append(s, "&one.Subby{") s = append(s, "Sub: "+fmt.Sprintf("%#v", this.Sub)+",\n") s = append(s, "}") return strings.Join(s, "") } func (this *SampleOneOf) GoString() string { if this == nil { return "nil" } s := make([]string, 0, 20) s = append(s, "&one.SampleOneOf{") if this.TestOneof != nil { s = append(s, "TestOneof: "+fmt.Sprintf("%#v", this.TestOneof)+",\n") } s = append(s, "}") return strings.Join(s, "") } func (this *SampleOneOf_Field1) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field1{` + `Field1:` + fmt.Sprintf("%#v", this.Field1) + `}`}, ", ") return s } func (this *SampleOneOf_Field2) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field2{` + `Field2:` + fmt.Sprintf("%#v", this.Field2) + `}`}, ", ") return s } func (this *SampleOneOf_Field3) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field3{` + `Field3:` + fmt.Sprintf("%#v", this.Field3) + `}`}, ", ") return s } func (this *SampleOneOf_Field4) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field4{` + `Field4:` + fmt.Sprintf("%#v", this.Field4) + `}`}, ", ") return s } func (this *SampleOneOf_Field5) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field5{` + `Field5:` + fmt.Sprintf("%#v", this.Field5) + `}`}, ", ") return s } func (this *SampleOneOf_Field6) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field6{` + `Field6:` + fmt.Sprintf("%#v", this.Field6) + `}`}, ", ") return s } func (this *SampleOneOf_Field7) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field7{` + `Field7:` + fmt.Sprintf("%#v", this.Field7) + `}`}, ", ") return s } func (this *SampleOneOf_Field8) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field8{` + `Field8:` + fmt.Sprintf("%#v", this.Field8) + `}`}, ", ") return s } func (this *SampleOneOf_Field9) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field9{` + `Field9:` + fmt.Sprintf("%#v", this.Field9) + `}`}, ", ") return s } func (this *SampleOneOf_Field10) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field10{` + `Field10:` + fmt.Sprintf("%#v", this.Field10) + `}`}, ", ") return s } func (this *SampleOneOf_Field11) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field11{` + `Field11:` + fmt.Sprintf("%#v", this.Field11) + `}`}, ", ") return s } func (this *SampleOneOf_Field12) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field12{` + `Field12:` + fmt.Sprintf("%#v", this.Field12) + `}`}, ", ") return s } func (this *SampleOneOf_Field13) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field13{` + `Field13:` + fmt.Sprintf("%#v", this.Field13) + `}`}, ", ") return s } func (this *SampleOneOf_Field14) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field14{` + `Field14:` + fmt.Sprintf("%#v", this.Field14) + `}`}, ", ") return s } func (this *SampleOneOf_Field15) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field15{` + `Field15:` + fmt.Sprintf("%#v", this.Field15) + `}`}, ", ") return s } func (this *SampleOneOf_SubMessage) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_SubMessage{` + `SubMessage:` + fmt.Sprintf("%#v", this.SubMessage) + `}`}, ", ") return s } func valueToGoStringOne(v interface{}, typ string) string { rv := reflect.ValueOf(v) if rv.IsNil() { return "nil" } pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) } func (m *Subby) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *Subby) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l if len(m.Sub) > 0 { dAtA[i] = 0xa i++ i = encodeVarintOne(dAtA, i, uint64(len(m.Sub))) i += copy(dAtA[i:], m.Sub) } return i, nil } func (m *SampleOneOf) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *SampleOneOf) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l if m.TestOneof != nil { nn1, err := m.TestOneof.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += nn1 } return i, nil } func (m *SampleOneOf_Field1) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x9 i++ i = encodeFixed64One(dAtA, i, uint64(math.Float64bits(float64(m.Field1)))) return i, nil } func (m *SampleOneOf_Field2) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x15 i++ i = encodeFixed32One(dAtA, i, uint32(math.Float32bits(float32(m.Field2)))) return i, nil } func (m *SampleOneOf_Field3) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x18 i++ i = encodeVarintOne(dAtA, i, uint64(m.Field3)) return i, nil } func (m *SampleOneOf_Field4) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x20 i++ i = encodeVarintOne(dAtA, i, uint64(m.Field4)) return i, nil } func (m *SampleOneOf_Field5) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x28 i++ i = encodeVarintOne(dAtA, i, uint64(m.Field5)) return i, nil } func (m *SampleOneOf_Field6) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x30 i++ i = encodeVarintOne(dAtA, i, uint64(m.Field6)) return i, nil } func (m *SampleOneOf_Field7) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x38 i++ i = encodeVarintOne(dAtA, i, uint64((uint32(m.Field7)<<1)^uint32((m.Field7>>31)))) return i, nil } func (m *SampleOneOf_Field8) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x40 i++ i = encodeVarintOne(dAtA, i, uint64((uint64(m.Field8)<<1)^uint64((m.Field8>>63)))) return i, nil } func (m *SampleOneOf_Field9) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x4d i++ i = encodeFixed32One(dAtA, i, uint32(m.Field9)) return i, nil } func (m *SampleOneOf_Field10) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x55 i++ i = encodeFixed32One(dAtA, i, uint32(m.Field10)) return i, nil } func (m *SampleOneOf_Field11) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x59 i++ i = encodeFixed64One(dAtA, i, uint64(m.Field11)) return i, nil } func (m *SampleOneOf_Field12) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x61 i++ i = encodeFixed64One(dAtA, i, uint64(m.Field12)) return i, nil } func (m *SampleOneOf_Field13) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x68 i++ if m.Field13 { dAtA[i] = 1 } else { dAtA[i] = 0 } i++ return i, nil } func (m *SampleOneOf_Field14) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x72 i++ i = encodeVarintOne(dAtA, i, uint64(len(m.Field14))) i += copy(dAtA[i:], m.Field14) return i, nil } func (m *SampleOneOf_Field15) MarshalTo(dAtA []byte) (int, error) { i := 0 if m.Field15 != nil { dAtA[i] = 0x7a i++ i = encodeVarintOne(dAtA, i, uint64(len(m.Field15))) i += copy(dAtA[i:], m.Field15) } return i, nil } func (m *SampleOneOf_SubMessage) MarshalTo(dAtA []byte) (int, error) { i := 0 if m.SubMessage != nil { dAtA[i] = 0x82 i++ dAtA[i] = 0x1 i++ i = encodeVarintOne(dAtA, i, uint64(m.SubMessage.Size())) n2, err := m.SubMessage.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n2 } return i, nil } func encodeFixed64One(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) dAtA[offset+1] = uint8(v >> 8) dAtA[offset+2] = uint8(v >> 16) dAtA[offset+3] = uint8(v >> 24) dAtA[offset+4] = uint8(v >> 32) dAtA[offset+5] = uint8(v >> 40) dAtA[offset+6] = uint8(v >> 48) dAtA[offset+7] = uint8(v >> 56) return offset + 8 } func encodeFixed32One(dAtA []byte, offset int, v uint32) int { dAtA[offset] = uint8(v) dAtA[offset+1] = uint8(v >> 8) dAtA[offset+2] = uint8(v >> 16) dAtA[offset+3] = uint8(v >> 24) return offset + 4 } func encodeVarintOne(dAtA []byte, offset int, v uint64) int { for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return offset + 1 } func NewPopulatedSubby(r randyOne, easy bool) *Subby { this := &Subby{} this.Sub = string(randStringOne(r)) if !easy && r.Intn(10) != 0 { } return this } func NewPopulatedSampleOneOf(r randyOne, easy bool) *SampleOneOf { this := &SampleOneOf{} oneofNumber_TestOneof := []int32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}[r.Intn(16)] switch oneofNumber_TestOneof { case 1: this.TestOneof = NewPopulatedSampleOneOf_Field1(r, easy) case 2: this.TestOneof = NewPopulatedSampleOneOf_Field2(r, easy) case 3: this.TestOneof = NewPopulatedSampleOneOf_Field3(r, easy) case 4: this.TestOneof = NewPopulatedSampleOneOf_Field4(r, easy) case 5: this.TestOneof = NewPopulatedSampleOneOf_Field5(r, easy) case 6: this.TestOneof = NewPopulatedSampleOneOf_Field6(r, easy) case 7: this.TestOneof = NewPopulatedSampleOneOf_Field7(r, easy) case 8: this.TestOneof = NewPopulatedSampleOneOf_Field8(r, easy) case 9: this.TestOneof = NewPopulatedSampleOneOf_Field9(r, easy) case 10: this.TestOneof = NewPopulatedSampleOneOf_Field10(r, easy) case 11: this.TestOneof = NewPopulatedSampleOneOf_Field11(r, easy) case 12: this.TestOneof = NewPopulatedSampleOneOf_Field12(r, easy) case 13: this.TestOneof = NewPopulatedSampleOneOf_Field13(r, easy) case 14: this.TestOneof = NewPopulatedSampleOneOf_Field14(r, easy) case 15: this.TestOneof = NewPopulatedSampleOneOf_Field15(r, easy) case 16: this.TestOneof = NewPopulatedSampleOneOf_SubMessage(r, easy) } if !easy && r.Intn(10) != 0 { } return this } func NewPopulatedSampleOneOf_Field1(r randyOne, easy bool) *SampleOneOf_Field1 { this := &SampleOneOf_Field1{} this.Field1 = float64(r.Float64()) if r.Intn(2) == 0 { this.Field1 *= -1 } return this } func NewPopulatedSampleOneOf_Field2(r randyOne, easy bool) *SampleOneOf_Field2 { this := &SampleOneOf_Field2{} this.Field2 = float32(r.Float32()) if r.Intn(2) == 0 { this.Field2 *= -1 } return this } func NewPopulatedSampleOneOf_Field3(r randyOne, easy bool) *SampleOneOf_Field3 { this := &SampleOneOf_Field3{} this.Field3 = int32(r.Int31()) if r.Intn(2) == 0 { this.Field3 *= -1 } return this } func NewPopulatedSampleOneOf_Field4(r randyOne, easy bool) *SampleOneOf_Field4 { this := &SampleOneOf_Field4{} this.Field4 = int64(r.Int63()) if r.Intn(2) == 0 { this.Field4 *= -1 } return this } func NewPopulatedSampleOneOf_Field5(r randyOne, easy bool) *SampleOneOf_Field5 { this := &SampleOneOf_Field5{} this.Field5 = uint32(r.Uint32()) return this } func NewPopulatedSampleOneOf_Field6(r randyOne, easy bool) *SampleOneOf_Field6 { this := &SampleOneOf_Field6{} this.Field6 = uint64(uint64(r.Uint32())) return this } func NewPopulatedSampleOneOf_Field7(r randyOne, easy bool) *SampleOneOf_Field7 { this := &SampleOneOf_Field7{} this.Field7 = int32(r.Int31()) if r.Intn(2) == 0 { this.Field7 *= -1 } return this } func NewPopulatedSampleOneOf_Field8(r randyOne, easy bool) *SampleOneOf_Field8 { this := &SampleOneOf_Field8{} this.Field8 = int64(r.Int63()) if r.Intn(2) == 0 { this.Field8 *= -1 } return this } func NewPopulatedSampleOneOf_Field9(r randyOne, easy bool) *SampleOneOf_Field9 { this := &SampleOneOf_Field9{} this.Field9 = uint32(r.Uint32()) return this } func NewPopulatedSampleOneOf_Field10(r randyOne, easy bool) *SampleOneOf_Field10 { this := &SampleOneOf_Field10{} this.Field10 = int32(r.Int31()) if r.Intn(2) == 0 { this.Field10 *= -1 } return this } func NewPopulatedSampleOneOf_Field11(r randyOne, easy bool) *SampleOneOf_Field11 { this := &SampleOneOf_Field11{} this.Field11 = uint64(uint64(r.Uint32())) return this } func NewPopulatedSampleOneOf_Field12(r randyOne, easy bool) *SampleOneOf_Field12 { this := &SampleOneOf_Field12{} this.Field12 = int64(r.Int63()) if r.Intn(2) == 0 { this.Field12 *= -1 } return this } func NewPopulatedSampleOneOf_Field13(r randyOne, easy bool) *SampleOneOf_Field13 { this := &SampleOneOf_Field13{} this.Field13 = bool(bool(r.Intn(2) == 0)) return this } func NewPopulatedSampleOneOf_Field14(r randyOne, easy bool) *SampleOneOf_Field14 { this := &SampleOneOf_Field14{} this.Field14 = string(randStringOne(r)) return this } func NewPopulatedSampleOneOf_Field15(r randyOne, easy bool) *SampleOneOf_Field15 { this := &SampleOneOf_Field15{} v1 := r.Intn(100) this.Field15 = make([]byte, v1) for i := 0; i < v1; i++ { this.Field15[i] = byte(r.Intn(256)) } return this } func NewPopulatedSampleOneOf_SubMessage(r randyOne, easy bool) *SampleOneOf_SubMessage { this := &SampleOneOf_SubMessage{} this.SubMessage = NewPopulatedSubby(r, easy) return this } type randyOne interface { Float32() float32 Float64() float64 Int63() int64 Int31() int32 Uint32() uint32 Intn(n int) int } func randUTF8RuneOne(r randyOne) rune { ru := r.Intn(62) if ru < 10 { return rune(ru + 48) } else if ru < 36 { return rune(ru + 55) } return rune(ru + 61) } func randStringOne(r randyOne) string { v2 := r.Intn(100) tmps := make([]rune, v2) for i := 0; i < v2; i++ { tmps[i] = randUTF8RuneOne(r) } return string(tmps) } func randUnrecognizedOne(r randyOne, maxFieldNumber int) (dAtA []byte) { l := r.Intn(5) for i := 0; i < l; i++ { wire := r.Intn(4) if wire == 3 { wire = 5 } fieldNumber := maxFieldNumber + r.Intn(100) dAtA = randFieldOne(dAtA, r, fieldNumber, wire) } return dAtA } func randFieldOne(dAtA []byte, r randyOne, fieldNumber int, wire int) []byte { key := uint32(fieldNumber)<<3 | uint32(wire) switch wire { case 0: dAtA = encodeVarintPopulateOne(dAtA, uint64(key)) v3 := r.Int63() if r.Intn(2) == 0 { v3 *= -1 } dAtA = encodeVarintPopulateOne(dAtA, uint64(v3)) case 1: dAtA = encodeVarintPopulateOne(dAtA, uint64(key)) dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) case 2: dAtA = encodeVarintPopulateOne(dAtA, uint64(key)) ll := r.Intn(100) dAtA = encodeVarintPopulateOne(dAtA, uint64(ll)) for j := 0; j < ll; j++ { dAtA = append(dAtA, byte(r.Intn(256))) } default: dAtA = encodeVarintPopulateOne(dAtA, uint64(key)) dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) } return dAtA } func encodeVarintPopulateOne(dAtA []byte, v uint64) []byte { for v >= 1<<7 { dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80)) v >>= 7 } dAtA = append(dAtA, uint8(v)) return dAtA } func (m *Subby) Size() (n int) { var l int _ = l l = len(m.Sub) if l > 0 { n += 1 + l + sovOne(uint64(l)) } return n } func (m *SampleOneOf) Size() (n int) { var l int _ = l if m.TestOneof != nil { n += m.TestOneof.Size() } return n } func (m *SampleOneOf_Field1) Size() (n int) { var l int _ = l n += 9 return n } func (m *SampleOneOf_Field2) Size() (n int) { var l int _ = l n += 5 return n } func (m *SampleOneOf_Field3) Size() (n int) { var l int _ = l n += 1 + sovOne(uint64(m.Field3)) return n } func (m *SampleOneOf_Field4) Size() (n int) { var l int _ = l n += 1 + sovOne(uint64(m.Field4)) return n } func (m *SampleOneOf_Field5) Size() (n int) { var l int _ = l n += 1 + sovOne(uint64(m.Field5)) return n } func (m *SampleOneOf_Field6) Size() (n int) { var l int _ = l n += 1 + sovOne(uint64(m.Field6)) return n } func (m *SampleOneOf_Field7) Size() (n int) { var l int _ = l n += 1 + sozOne(uint64(m.Field7)) return n } func (m *SampleOneOf_Field8) Size() (n int) { var l int _ = l n += 1 + sozOne(uint64(m.Field8)) return n } func (m *SampleOneOf_Field9) Size() (n int) { var l int _ = l n += 5 return n } func (m *SampleOneOf_Field10) Size() (n int) { var l int _ = l n += 5 return n } func (m *SampleOneOf_Field11) Size() (n int) { var l int _ = l n += 9 return n } func (m *SampleOneOf_Field12) Size() (n int) { var l int _ = l n += 9 return n } func (m *SampleOneOf_Field13) Size() (n int) { var l int _ = l n += 2 return n } func (m *SampleOneOf_Field14) Size() (n int) { var l int _ = l l = len(m.Field14) n += 1 + l + sovOne(uint64(l)) return n } func (m *SampleOneOf_Field15) Size() (n int) { var l int _ = l if m.Field15 != nil { l = len(m.Field15) n += 1 + l + sovOne(uint64(l)) } return n } func (m *SampleOneOf_SubMessage) Size() (n int) { var l int _ = l if m.SubMessage != nil { l = m.SubMessage.Size() n += 2 + l + sovOne(uint64(l)) } return n } func sovOne(x uint64) (n int) { for { n++ x >>= 7 if x == 0 { break } } return n } func sozOne(x uint64) (n int) { return sovOne(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (this *Subby) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&Subby{`, `Sub:` + fmt.Sprintf("%v", this.Sub) + `,`, `}`, }, "") return s } func (this *SampleOneOf) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf{`, `TestOneof:` + fmt.Sprintf("%v", this.TestOneof) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field1) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field1{`, `Field1:` + fmt.Sprintf("%v", this.Field1) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field2) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field2{`, `Field2:` + fmt.Sprintf("%v", this.Field2) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field3) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field3{`, `Field3:` + fmt.Sprintf("%v", this.Field3) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field4) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field4{`, `Field4:` + fmt.Sprintf("%v", this.Field4) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field5) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field5{`, `Field5:` + fmt.Sprintf("%v", this.Field5) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field6) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field6{`, `Field6:` + fmt.Sprintf("%v", this.Field6) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field7) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field7{`, `Field7:` + fmt.Sprintf("%v", this.Field7) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field8) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field8{`, `Field8:` + fmt.Sprintf("%v", this.Field8) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field9) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field9{`, `Field9:` + fmt.Sprintf("%v", this.Field9) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field10) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field10{`, `Field10:` + fmt.Sprintf("%v", this.Field10) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field11) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field11{`, `Field11:` + fmt.Sprintf("%v", this.Field11) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field12) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field12{`, `Field12:` + fmt.Sprintf("%v", this.Field12) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field13) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field13{`, `Field13:` + fmt.Sprintf("%v", this.Field13) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field14) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field14{`, `Field14:` + fmt.Sprintf("%v", this.Field14) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field15) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field15{`, `Field15:` + fmt.Sprintf("%v", this.Field15) + `,`, `}`, }, "") return s } func (this *SampleOneOf_SubMessage) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_SubMessage{`, `SubMessage:` + strings.Replace(fmt.Sprintf("%v", this.SubMessage), "Subby", "Subby", 1) + `,`, `}`, }, "") return s } func valueToStringOne(v interface{}) string { rv := reflect.ValueOf(v) if rv.IsNil() { return "nil" } pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("*%v", pv) } func (m *Subby) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Subby: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Subby: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Sub", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthOne } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Sub = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipOne(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthOne } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *SampleOneOf) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: SampleOneOf: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: SampleOneOf: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 1 { return fmt.Errorf("proto: wrong wireType = %d for field Field1", wireType) } var v uint64 if (iNdEx + 8) > l { return io.ErrUnexpectedEOF } iNdEx += 8 v = uint64(dAtA[iNdEx-8]) v |= uint64(dAtA[iNdEx-7]) << 8 v |= uint64(dAtA[iNdEx-6]) << 16 v |= uint64(dAtA[iNdEx-5]) << 24 v |= uint64(dAtA[iNdEx-4]) << 32 v |= uint64(dAtA[iNdEx-3]) << 40 v |= uint64(dAtA[iNdEx-2]) << 48 v |= uint64(dAtA[iNdEx-1]) << 56 m.TestOneof = &SampleOneOf_Field1{float64(math.Float64frombits(v))} case 2: if wireType != 5 { return fmt.Errorf("proto: wrong wireType = %d for field Field2", wireType) } var v uint32 if (iNdEx + 4) > l { return io.ErrUnexpectedEOF } iNdEx += 4 v = uint32(dAtA[iNdEx-4]) v |= uint32(dAtA[iNdEx-3]) << 8 v |= uint32(dAtA[iNdEx-2]) << 16 v |= uint32(dAtA[iNdEx-1]) << 24 m.TestOneof = &SampleOneOf_Field2{float32(math.Float32frombits(v))} case 3: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field3", wireType) } var v int32 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (int32(b) & 0x7F) << shift if b < 0x80 { break } } m.TestOneof = &SampleOneOf_Field3{v} case 4: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field4", wireType) } var v int64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (int64(b) & 0x7F) << shift if b < 0x80 { break } } m.TestOneof = &SampleOneOf_Field4{v} case 5: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field5", wireType) } var v uint32 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (uint32(b) & 0x7F) << shift if b < 0x80 { break } } m.TestOneof = &SampleOneOf_Field5{v} case 6: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field6", wireType) } var v uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } m.TestOneof = &SampleOneOf_Field6{v} case 7: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field7", wireType) } var v int32 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (int32(b) & 0x7F) << shift if b < 0x80 { break } } v = int32((uint32(v) >> 1) ^ uint32(((v&1)<<31)>>31)) m.TestOneof = &SampleOneOf_Field7{v} case 8: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field8", wireType) } var v uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } v = (v >> 1) ^ uint64((int64(v&1)<<63)>>63) m.TestOneof = &SampleOneOf_Field8{int64(v)} case 9: if wireType != 5 { return fmt.Errorf("proto: wrong wireType = %d for field Field9", wireType) } var v uint32 if (iNdEx + 4) > l { return io.ErrUnexpectedEOF } iNdEx += 4 v = uint32(dAtA[iNdEx-4]) v |= uint32(dAtA[iNdEx-3]) << 8 v |= uint32(dAtA[iNdEx-2]) << 16 v |= uint32(dAtA[iNdEx-1]) << 24 m.TestOneof = &SampleOneOf_Field9{v} case 10: if wireType != 5 { return fmt.Errorf("proto: wrong wireType = %d for field Field10", wireType) } var v int32 if (iNdEx + 4) > l { return io.ErrUnexpectedEOF } iNdEx += 4 v = int32(dAtA[iNdEx-4]) v |= int32(dAtA[iNdEx-3]) << 8 v |= int32(dAtA[iNdEx-2]) << 16 v |= int32(dAtA[iNdEx-1]) << 24 m.TestOneof = &SampleOneOf_Field10{v} case 11: if wireType != 1 { return fmt.Errorf("proto: wrong wireType = %d for field Field11", wireType) } var v uint64 if (iNdEx + 8) > l { return io.ErrUnexpectedEOF } iNdEx += 8 v = uint64(dAtA[iNdEx-8]) v |= uint64(dAtA[iNdEx-7]) << 8 v |= uint64(dAtA[iNdEx-6]) << 16 v |= uint64(dAtA[iNdEx-5]) << 24 v |= uint64(dAtA[iNdEx-4]) << 32 v |= uint64(dAtA[iNdEx-3]) << 40 v |= uint64(dAtA[iNdEx-2]) << 48 v |= uint64(dAtA[iNdEx-1]) << 56 m.TestOneof = &SampleOneOf_Field11{v} case 12: if wireType != 1 { return fmt.Errorf("proto: wrong wireType = %d for field Field12", wireType) } var v int64 if (iNdEx + 8) > l { return io.ErrUnexpectedEOF } iNdEx += 8 v = int64(dAtA[iNdEx-8]) v |= int64(dAtA[iNdEx-7]) << 8 v |= int64(dAtA[iNdEx-6]) << 16 v |= int64(dAtA[iNdEx-5]) << 24 v |= int64(dAtA[iNdEx-4]) << 32 v |= int64(dAtA[iNdEx-3]) << 40 v |= int64(dAtA[iNdEx-2]) << 48 v |= int64(dAtA[iNdEx-1]) << 56 m.TestOneof = &SampleOneOf_Field12{v} case 13: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field13", wireType) } var v int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (int(b) & 0x7F) << shift if b < 0x80 { break } } b := bool(v != 0) m.TestOneof = &SampleOneOf_Field13{b} case 14: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Field14", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthOne } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.TestOneof = &SampleOneOf_Field14{string(dAtA[iNdEx:postIndex])} iNdEx = postIndex case 15: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Field15", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthOne } postIndex := iNdEx + byteLen if postIndex > l { return io.ErrUnexpectedEOF } v := make([]byte, postIndex-iNdEx) copy(v, dAtA[iNdEx:postIndex]) m.TestOneof = &SampleOneOf_Field15{v} iNdEx = postIndex case 16: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SubMessage", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthOne } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } v := &Subby{} if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } m.TestOneof = &SampleOneOf_SubMessage{v} iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipOne(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthOne } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipOne(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowOne } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowOne } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } return iNdEx, nil case 1: iNdEx += 8 return iNdEx, nil case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowOne } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } iNdEx += length if length < 0 { return 0, ErrInvalidLengthOne } return iNdEx, nil case 3: for { var innerWire uint64 var start int = iNdEx for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowOne } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ innerWire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } innerWireType := int(innerWire & 0x7) if innerWireType == 4 { break } next, err := skipOne(dAtA[start:]) if err != nil { return 0, err } iNdEx = start + next } return iNdEx, nil case 4: return iNdEx, nil case 5: iNdEx += 4 return iNdEx, nil default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } } panic("unreachable") } var ( ErrInvalidLengthOne = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowOne = fmt.Errorf("proto: integer overflow") ) func init() { proto.RegisterFile("combos/both/one.proto", fileDescriptorOne) } var fileDescriptorOne = []byte{ // 404 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x44, 0xd2, 0xbf, 0x4f, 0x1b, 0x31, 0x14, 0x07, 0x70, 0x3f, 0x8e, 0x24, 0xe0, 0x84, 0x92, 0x9e, 0x54, 0xe9, 0x95, 0xe1, 0xc9, 0x62, 0xf2, 0x42, 0xd2, 0xdc, 0x25, 0xfc, 0x58, 0x51, 0x55, 0x65, 0xa9, 0x90, 0xc2, 0x1f, 0x80, 0x30, 0x75, 0x0e, 0x24, 0xee, 0x8c, 0x7a, 0x77, 0x43, 0x37, 0xfe, 0x9c, 0x8e, 0x1d, 0xfb, 0x27, 0x30, 0x32, 0x76, 0xe8, 0xc0, 0xb9, 0x4b, 0x47, 0x46, 0xc6, 0x2a, 0x97, 0xf2, 0xbc, 0xbd, 0xaf, 0x3f, 0xf6, 0x60, 0xfb, 0x2b, 0xdf, 0x5d, 0xb9, 0xdc, 0xb8, 0x72, 0x6c, 0x5c, 0x75, 0x3d, 0x76, 0x85, 0x1d, 0xdd, 0x7d, 0x75, 0x95, 0x8b, 0x23, 0x57, 0xd8, 0xbd, 0x83, 0xec, 0xa6, 0xba, 0xae, 0xcd, 0xe8, 0xca, 0xe5, 0xe3, 0xcc, 0x65, 0x6e, 0xdc, 0x9a, 0xa9, 0x97, 0x6d, 0x6a, 0x43, 0x3b, 0xad, 0xcf, 0xec, 0xbf, 0x97, 0x9d, 0xf3, 0xda, 0x98, 0x6f, 0xf1, 0x50, 0x46, 0x65, 0x6d, 0x10, 0x14, 0xe8, 0xed, 0xc5, 0x6a, 0xdc, 0xff, 0x1d, 0xc9, 0xfe, 0xf9, 0x65, 0x7e, 0x77, 0x6b, 0xcf, 0x0a, 0x7b, 0xb6, 0x8c, 0x51, 0x76, 0x3f, 0xdd, 0xd8, 0xdb, 0x2f, 0x93, 0x76, 0x13, 0xcc, 0xc5, 0xe2, 0x7f, 0x66, 0x49, 0x70, 0x43, 0x81, 0xde, 0x60, 0x49, 0x58, 0x52, 0x8c, 0x14, 0xe8, 0x0e, 0x4b, 0xca, 0x32, 0xc5, 0x4d, 0x05, 0x3a, 0x62, 0x99, 0xb2, 0xcc, 0xb0, 0xa3, 0x40, 0xef, 0xb0, 0xcc, 0x58, 0x0e, 0xb1, 0xab, 0x40, 0x6f, 0xb2, 0x1c, 0xb2, 0x1c, 0x61, 0x4f, 0x81, 0x7e, 0xcb, 0x72, 0xc4, 0x72, 0x8c, 0x5b, 0x0a, 0x74, 0xcc, 0x72, 0xcc, 0x72, 0x82, 0xdb, 0x0a, 0x74, 0x8f, 0xe5, 0x24, 0xde, 0x93, 0xbd, 0xf5, 0xcd, 0x3e, 0xa0, 0x54, 0xa0, 0x77, 0xe7, 0x62, 0xf1, 0xba, 0x10, 0x6c, 0x82, 0x7d, 0x05, 0xba, 0x1b, 0x6c, 0x12, 0x2c, 0xc1, 0x81, 0x02, 0x3d, 0x0c, 0x96, 0x04, 0x4b, 0x71, 0x47, 0x81, 0xde, 0x0a, 0x96, 0x06, 0x9b, 0xe2, 0x9b, 0xd5, 0xfb, 0x07, 0x9b, 0x06, 0x9b, 0xe1, 0xae, 0x02, 0x3d, 0x08, 0x36, 0x8b, 0x0f, 0x64, 0xbf, 0xac, 0xcd, 0x45, 0x6e, 0xcb, 0xf2, 0x32, 0xb3, 0x38, 0x54, 0xa0, 0xfb, 0x89, 0x1c, 0xad, 0x1a, 0xd1, 0x7e, 0xea, 0x5c, 0x2c, 0x64, 0x59, 0x9b, 0xcf, 0x6b, 0x3f, 0x1d, 0x48, 0x59, 0xd9, 0xb2, 0xba, 0x70, 0x85, 0x75, 0xcb, 0xd3, 0x8f, 0x0f, 0x0d, 0x89, 0xc7, 0x86, 0xc4, 0xaf, 0x86, 0xc4, 0x53, 0x43, 0xf0, 0xdc, 0x10, 0xbc, 0x34, 0x04, 0xf7, 0x9e, 0xe0, 0xbb, 0x27, 0xf8, 0xe1, 0x09, 0x7e, 0x7a, 0x82, 0x07, 0x4f, 0xf0, 0xe8, 0x09, 0x9e, 0x3c, 0xc1, 0x5f, 0x4f, 0xe2, 0xd9, 0x13, 0xbc, 0x78, 0x12, 0xf7, 0x7f, 0x48, 0x98, 0x6e, 0x5b, 0xa3, 0xf4, 0x5f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x1e, 0x42, 0xd6, 0x88, 0x93, 0x02, 0x00, 0x00, }
ae6rt/decap
web/vendor/github.com/gogo/protobuf/test/oneof3/combos/both/one.pb.go
GO
mit
99,707
<?php /** * @package Joomla.UnitTest * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ JLoader::register('JFolder', JPATH_PLATFORM . '/joomla/filesystem/folder.php'); /** * Test class for JFolder. * Generated by PHPUnit on 2011-10-26 at 19:32:37. * * @package Joomla.UnitTest * @subpackage Event * @since 11.1 */ class JFolderTest extends TestCase { /** * Test... * * @todo Implement testCopy(). * * @return void */ public function testCopy() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Test... * * @todo Implement testCreate(). * * @return void */ public function testCreate() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Test... * * @todo Implement testDelete(). * * @return void */ public function testDelete() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Tests the JFolder::delete method with an array as an input * * @return void * * @expectedException UnexpectedValueException * @since 11.3 */ public function testDeleteArrayPath() { JFolder::delete(array('/path/to/folder') ); } /** * Test... * * @todo Implement testMove(). * * @return void */ public function testMove() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Test... * * @return void */ public function testExists() { $this->assertTrue( JFolder::exists(__DIR__) ); } /** * Tests the JFolder::files method. * * @return void * * @since 12.1 */ public function testFiles() { // Make sure previous test files are cleaned up $this->_cleanupTestFiles(); // Make some test files and folders mkdir(JPath::clean(JPATH_TESTS . '/tmp/test'), 0777, true); file_put_contents(JPath::clean(JPATH_TESTS . '/tmp/test/index.html'), 'test'); file_put_contents(JPath::clean(JPATH_TESTS . '/tmp/test/index.txt'), 'test'); mkdir(JPath::clean(JPATH_TESTS . '/tmp/test/test'), 0777, true); file_put_contents(JPath::clean(JPATH_TESTS . '/tmp/test/test/index.html'), 'test'); file_put_contents(JPath::clean(JPATH_TESTS . '/tmp/test/test/index.txt'), 'test'); // Use of realpath to ensure test works for on all platforms $result = JFolder::files(JPath::clean(JPATH_TESTS . '/tmp/test'), 'index.*', true, true, array('index.html')); $result[0] = realpath($result[0]); $result[1] = realpath($result[1]); $this->assertEquals( array( JPath::clean(JPATH_TESTS . '/tmp/test/index.txt'), JPath::clean(JPATH_TESTS . '/tmp/test/test/index.txt') ), $result, 'Line: ' . __LINE__ . ' Should exclude index.html files' ); // Use of realpath to ensure test works for on all platforms $result = JFolder::files(JPath::clean(JPATH_TESTS . '/tmp/test'), 'index.html', true, true); $result[0] = realpath($result[0]); $result[1] = realpath($result[1]); $this->assertEquals( array( JPath::clean(JPATH_TESTS . '/tmp/test/index.html'), JPath::clean(JPATH_TESTS . '/tmp/test/test/index.html') ), $result, 'Line: ' . __LINE__ . ' Should include full path of both index.html files' ); $this->assertEquals( array( JPath::clean('index.html'), JPath::clean('index.html') ), JFolder::files(JPath::clean(JPATH_TESTS . '/tmp/test'), 'index.html', true, false), 'Line: ' . __LINE__ . ' Should include only file names of both index.html files' ); // Use of realpath to ensure test works for on all platforms $result = JFolder::files(JPath::clean(JPATH_TESTS . '/tmp/test'), 'index.html', false, true); $result[0] = realpath($result[0]); $this->assertEquals( array( JPath::clean(JPATH_TESTS . '/tmp/test/index.html') ), $result, 'Line: ' . __LINE__ . ' Non-recursive should only return top folder file full path' ); $this->assertEquals( array( JPath::clean('index.html') ), JFolder::files(JPath::clean(JPATH_TESTS . '/tmp/test'), 'index.html', false, false), 'Line: ' . __LINE__ . ' non-recursive should return only file name of top folder file' ); $this->assertFalse( JFolder::files('/this/is/not/a/path'), 'Line: ' . __LINE__ . ' Non-existent path should return false' ); $this->assertEquals( array(), JFolder::files(JPath::clean(JPATH_TESTS . '/tmp/test'), 'nothing.here', true, true, array(), array()), 'Line: ' . __LINE__ . ' When nothing matches the filter, should return empty array' ); // Clean up our files $this->_cleanupTestFiles(); } /** * Tests the JFolder::folders method. * * @return void * * @since 12.1 */ public function testFolders() { // Make sure previous test files are cleaned up $this->_cleanupTestFiles(); // Create the test folders mkdir(JPath::clean(JPATH_TESTS . '/tmp/test'), 0777, true); mkdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo1'), 0777, true); mkdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo1/bar1'), 0777, true); mkdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo1/bar2'), 0777, true); mkdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo2'), 0777, true); mkdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar1'), 0777, true); mkdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar2'), 0777, true); $this->assertEquals( array(), JFolder::folders(JPath::clean(JPATH_TESTS . '/tmp/test'), 'bar1', true, true, array('foo1', 'foo2')) ); // Use of realpath to ensure test works for on all platforms $result = JFolder::folders(JPath::clean(JPATH_TESTS . '/tmp/test'), 'bar1', true, true, array('foo1')); $result[0] = realpath($result[0]); $this->assertEquals( array(JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar1')), $result ); // Use of realpath to ensure test works for on all platforms $result = JFolder::folders(JPath::clean(JPATH_TESTS . '/tmp/test'), 'bar1', true, true); $result[0] = realpath($result[0]); $result[1] = realpath($result[1]); $this->assertEquals( array( JPath::clean(JPATH_TESTS . '/tmp/test/foo1/bar1'), JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar1'), ), $result ); // Use of realpath to ensure test works for on all platforms $result = JFolder::folders(JPath::clean(JPATH_TESTS . '/tmp/test'), 'bar', true, true); $result[0] = realpath($result[0]); $result[1] = realpath($result[1]); $result[2] = realpath($result[2]); $result[3] = realpath($result[3]); $this->assertEquals( array( JPath::clean(JPATH_TESTS . '/tmp/test/foo1/bar1'), JPath::clean(JPATH_TESTS . '/tmp/test/foo1/bar2'), JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar1'), JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar2'), ), $result ); // Use of realpath to ensure test works for on all platforms $result = JFolder::folders(JPath::clean(JPATH_TESTS . '/tmp/test'), '.', true, true); $result[0] = realpath($result[0]); $result[1] = realpath($result[1]); $result[2] = realpath($result[2]); $result[3] = realpath($result[3]); $result[4] = realpath($result[4]); $result[5] = realpath($result[5]); $this->assertEquals( array( JPath::clean(JPATH_TESTS . '/tmp/test/foo1'), JPath::clean(JPATH_TESTS . '/tmp/test/foo1/bar1'), JPath::clean(JPATH_TESTS . '/tmp/test/foo1/bar2'), JPath::clean(JPATH_TESTS . '/tmp/test/foo2'), JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar1'), JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar2'), ), $result ); $this->assertEquals( array( JPath::clean('bar1'), JPath::clean('bar1'), JPath::clean('bar2'), JPath::clean('bar2'), JPath::clean('foo1'), JPath::clean('foo2'), ), JFolder::folders(JPath::clean(JPATH_TESTS . '/tmp/test'), '.', true, false) ); // Use of realpath to ensure test works for on all platforms $result = JFolder::folders(JPath::clean(JPATH_TESTS . '/tmp/test'), '.', false, true); $result[0] = realpath($result[0]); $result[1] = realpath($result[1]); $this->assertEquals( array( JPath::clean(JPATH_TESTS . '/tmp/test/foo1'), JPath::clean(JPATH_TESTS . '/tmp/test/foo2'), ), $result ); $this->assertEquals( array( JPath::clean('foo1'), JPath::clean('foo2'), ), JFolder::folders(JPath::clean(JPATH_TESTS . '/tmp/test'), '.', false, false, array(), array()) ); $this->assertFalse( JFolder::folders('this/is/not/a/path'), 'Line: ' . __LINE__ . ' Non-existent path should return false' ); // Clean up the folders rmdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar2')); rmdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar1')); rmdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo2')); rmdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo1/bar2')); rmdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo1/bar1')); rmdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo1')); rmdir(JPath::clean(JPATH_TESTS . '/tmp/test')); } /** * Test... * * @todo Implement testListFolderTree(). * * @return void */ public function testListFolderTree() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Tests the JFolder::makeSafe method. * * @return void * * @since 12.1 */ public function testMakeSafe() { $actual = JFolder::makeSafe('test1/testdirectory'); $this->assertEquals('test1/testdirectory', $actual); } /** * Convenience method to cleanup before and after testFiles * * @return void * * @since 12.1 */ private function _cleanupTestFiles() { $this->_cleanupFile(JPath::clean(JPATH_TESTS . '/tmp/test/test/index.html')); $this->_cleanupFile(JPath::clean(JPATH_TESTS . '/tmp/test/test/index.txt')); $this->_cleanupFile(JPath::clean(JPATH_TESTS . '/tmp/test/test')); $this->_cleanupFile(JPath::clean(JPATH_TESTS . '/tmp/test/index.html')); $this->_cleanupFile(JPath::clean(JPATH_TESTS . '/tmp/test/index.txt')); $this->_cleanupFile(JPath::clean(JPATH_TESTS . '/tmp/test')); } /** * Convenience method to clean up for files test * * @param string $path The path to clean * * @return void * * @since 12.1 */ private function _cleanupFile($path) { if (file_exists($path)) { if (is_file($path)) { unlink($path); } elseif (is_dir($path)) { rmdir($path); } } } }
yiendos/pomander
tests/unit/suites/libraries/joomla/filesystem/JFolderTest.php
PHP
gpl-2.0
10,715
/* * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 6350057 7025809 * @summary Test that parameters on implicit enum methods have the right kind * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler * @build JavacTestingAbstractProcessor T6350057 * @compile -processor T6350057 -proc:only TestEnum.java */ import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.element.*; import javax.lang.model.util.*; import static javax.tools.Diagnostic.Kind.*; public class T6350057 extends JavacTestingAbstractProcessor { static class LocalVarAllergy extends ElementKindVisitor<Boolean, Void> { @Override public Boolean visitTypeAsEnum(TypeElement e, Void v) { System.out.println("visitTypeAsEnum: " + e.getSimpleName().toString()); for(Element el: e.getEnclosedElements() ) this.visit(el); return true; } @Override public Boolean visitVariableAsLocalVariable(VariableElement e, Void v){ throw new IllegalStateException("Should not see any local variables!"); } @Override public Boolean visitVariableAsParameter(VariableElement e, Void v){ String senclm=e.getEnclosingElement().getEnclosingElement().getSimpleName().toString(); String sEncl = senclm+"."+e.getEnclosingElement().getSimpleName().toString(); String stype = e.asType().toString(); String name = e.getSimpleName().toString(); System.out.println("visitVariableAsParameter: " +sEncl+"." + stype + " " + name); return true; } @Override public Boolean visitExecutableAsMethod(ExecutableElement e, Void v){ String name=e.getEnclosingElement().getSimpleName().toString(); name = name + "."+e.getSimpleName().toString(); System.out.println("visitExecutableAsMethod: " + name); for (VariableElement ve: e.getParameters()) this.visit(ve); return true; } } public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnvironment) { if (!roundEnvironment.processingOver()) for(Element element : roundEnvironment.getRootElements()) element.accept(new LocalVarAllergy(), null); return true; } }
FauxFaux/jdk9-langtools
test/tools/javac/enum/6350057/T6350057.java
Java
gpl-2.0
3,605
<?php /** * @package Joomla.UnitTest * @subpackage Linkedin * * @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ /** * Test class for JLinkedinPeople. * * @package Joomla.UnitTest * @subpackage Linkedin * @since 3.2.0 */ class JLinkedinPeopleTest extends TestCase { /** * @var JRegistry Options for the Linkedin object. * @since 3.2.0 */ protected $options; /** * @var JHttp Mock http object. * @since 3.2.0 */ protected $client; /** * @var JInput The input object to use in retrieving GET/POST data. * @since 3.2.0 */ protected $input; /** * @var JLinkedinPeople Object under test. * @since 3.2.0 */ protected $object; /** * @var JLinkedinOAuth Authentication object for the Twitter object. * @since 3.2.0 */ protected $oauth; /** * @var string Sample JSON string. * @since 3.2.0 */ protected $sampleString = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; /** * @var string Sample JSON string used to access out of network profiles. * @since 3.2.0 */ protected $outString = '{"headers": { "_total": 1, "values": [{ "name": "x-li-auth-token", "value": "NAME_SEARCH:-Ogn" }] }, "url": "/v1/people/oAFz-3CZyv"}'; /** * @var string Sample JSON error message. * @since 3.2.0 */ protected $errorString = '{"errorCode":401, "message": "Generic error"}'; /** * Backup of the SERVER superglobal * * @var array * @since 3.6 */ protected $backupServer; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. * * @return void */ protected function setUp() { parent::setUp(); $this->backupServer = $_SERVER; $_SERVER['HTTP_HOST'] = 'example.com'; $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0'; $_SERVER['REQUEST_URI'] = '/index.php'; $_SERVER['SCRIPT_NAME'] = '/index.php'; $key = "app_key"; $secret = "app_secret"; $my_url = "http://127.0.0.1/gsoc/joomla-platform/linkedin_test.php"; $this->options = new JRegistry; $this->input = new JInput; $this->client = $this->getMockBuilder('JHttp')->setMethods(array('get', 'post', 'delete', 'put'))->getMock(); $this->oauth = new JLinkedinOauth($this->options, $this->client, $this->input); $this->oauth->setToken(array('key' => $key, 'secret' => $secret)); $this->object = new JLinkedinPeople($this->options, $this->client, $this->oauth); $this->options->set('consumer_key', $key); $this->options->set('consumer_secret', $secret); $this->options->set('callback', $my_url); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. * * @return void * * @see \PHPUnit\Framework\TestCase::tearDown() * @since 3.6 */ protected function tearDown() { $_SERVER = $this->backupServer; unset($this->backupServer, $this->options, $this->input, $this->client, $this->oauth, $this->object); parent::tearDown(); } /** * Provides test data for request format detection. * * @return array * * @since 3.2.0 */ public function seedIdUrl() { // Member ID or url return array( array('lcnIwDU0S6', null), array(null, 'http://www.linkedin.com/in/dianaprajescu'), array(null, null) ); } /** * Tests the getProfile method * * @param string $id Member id of the profile you want. * @param string $url The public profile URL. * * @return void * * @dataProvider seedIdUrl * @since 3.2.0 */ public function testGetProfile($id, $url) { $fields = '(id,first-name,last-name)'; $language = 'en-US'; // Set request parameters. $data['format'] = 'json'; $path = '/v1/people/'; if ($url) { $path .= 'url=' . $this->oauth->safeEncode($url) . ':public'; $type = 'public'; } else { $type = 'standard'; } if ($id) { $path .= 'id=' . $id; } elseif (!$url) { $path .= '~'; } $path .= ':' . $fields; $header = array('Accept-Language' => $language); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; $path = $this->oauth->toUrl($path, $data); $this->client->expects($this->once()) ->method('get', $header) ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->getProfile($id, $url, $fields, $type, $language), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the getProfile method - failure * * @param string $id Member id of the profile you want. * @param string $url The public profile URL. * * @return void * * @dataProvider seedIdUrl * @since 3.2.0 * @expectedException DomainException */ public function testGetProfileFailure($id, $url) { $fields = '(id,first-name,last-name)'; $language = 'en-US'; // Set request parameters. $data['format'] = 'json'; $path = '/v1/people/'; if ($url) { $path .= 'url=' . $this->oauth->safeEncode($url) . ':public'; $type = 'public'; } else { $type = 'standard'; } if ($id) { $path .= 'id=' . $id; } elseif (!$url) { $path .= '~'; } $path .= ':' . $fields; $header = array('Accept-Language' => $language); $returnData = new stdClass; $returnData->code = 401; $returnData->body = $this->errorString; $path = $this->oauth->toUrl($path, $data); $this->client->expects($this->once()) ->method('get', $header) ->with($path) ->will($this->returnValue($returnData)); $this->object->getProfile($id, $url, $fields, $type, $language); } /** * Tests the getConnections method * * @return void * * @since 3.2.0 */ public function testGetConnections() { $fields = '(id,first-name,last-name)'; $start = 1; $count = 50; $modified = 'new'; $modified_since = '1267401600000'; // Set request parameters. $data['format'] = 'json'; $data['start'] = $start; $data['count'] = $count; $data['modified'] = $modified; $data['modified-since'] = $modified_since; $path = '/v1/people/~/connections'; $path .= ':' . $fields; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; $path = $this->oauth->toUrl($path, $data); $this->client->expects($this->once()) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->getConnections($fields, $start, $count, $modified, $modified_since), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the getConnections method - failure * * @return void * * @since 3.2.0 * @expectedException DomainException */ public function testGetConnectionsFailure() { $fields = '(id,first-name,last-name)'; $start = 1; $count = 50; $modified = 'new'; $modified_since = '1267401600000'; // Set request parameters. $data['format'] = 'json'; $data['start'] = $start; $data['count'] = $count; $data['modified'] = $modified; $data['modified-since'] = $modified_since; $path = '/v1/people/~/connections'; $path .= ':' . $fields; $returnData = new stdClass; $returnData->code = 401; $returnData->body = $this->errorString; $path = $this->oauth->toUrl($path, $data); $this->client->expects($this->once()) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->getConnections($fields, $start, $count, $modified, $modified_since); } /** * Provides test data for request format detection. * * @return array * * @since 3.2.0 */ public function seedFields() { // Fields return array( array('(people:(id,first-name,last-name,api-standard-profile-request))'), array('(people:(id,first-name,last-name))') ); } /** * Tests the search method * * @param string $fields Request fields beyond the default ones. provide 'api-standard-profile-request' field for out of network profiles. * * @return void * * @dataProvider seedFields * @since 3.2.0 */ public function testSearch($fields) { $keywords = 'Princess'; $first_name = 'Clair'; $last_name = 'Standish'; $company_name = 'Smth'; $current_company = true; $title = 'developer'; $current_title = true; $school_name = 'Shermer High School'; $current_school = true; $country_code = 'us'; $postal_code = 12345; $distance = 500; $facets = 'location,industry,network,language,current-company,past-company,school'; $facet = array('us-84', 47, 'F', 'en', 1006, 1028, 2345); $start = 1; $count = 50; $sort = 'distance'; // Set request parameters. $data['format'] = 'json'; $data['keywords'] = $keywords; $data['first-name'] = $first_name; $data['last-name'] = $last_name; $data['company-name'] = $company_name; $data['current-company'] = $current_company; $data['title'] = $title; $data['current-title'] = $current_title; $data['school-name'] = $school_name; $data['current-school'] = $current_school; $data['country-code'] = $country_code; $data['postal-code'] = $postal_code; $data['distance'] = $distance; $data['facets'] = $facets; $data['facet'] = array(); $data['facet'][] = 'location,' . $facet[0]; $data['facet'][] = 'industry,' . $facet[1]; $data['facet'][] = 'network,' . $facet[2]; $data['facet'][] = 'language,' . $facet[3]; $data['facet'][] = 'current-company,' . $facet[4]; $data['facet'][] = 'past-company,' . $facet[5]; $data['facet'][] = 'school,' . $facet[6]; $data['start'] = $start; $data['count'] = $count; $data['sort'] = $sort; $path = '/v1/people-search'; $path .= ':' . $fields; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; $path = $this->oauth->toUrl($path, $data); if (strpos($fields, 'api-standard-profile-request') === false) { $this->client->expects($this->once()) ->method('get') ->with($path) ->will($this->returnValue($returnData)); } else { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->outString; $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; $path = '/v1/people/oAFz-3CZyv'; $path = $this->oauth->toUrl($path, $data); $name = 'x-li-auth-token'; $value = 'NAME_SEARCH:-Ogn'; $header[$name] = $value; $this->client->expects($this->at(1)) ->method('get', $header) ->with($path) ->will($this->returnValue($returnData)); } $this->assertThat( $this->object->search( $fields, $keywords, $first_name, $last_name, $company_name, $current_company, $title, $current_title, $school_name, $current_school, $country_code, $postal_code, $distance, $facets, $facet, $start, $count, $sort ), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the search method - failure * * @return void * * @since 3.2.0 * @expectedException DomainException */ public function testSearchFailure() { $fields = '(id,first-name,last-name)'; $keywords = 'Princess'; $first_name = 'Clair'; $last_name = 'Standish'; $company_name = 'Smth'; $current_company = true; $title = 'developer'; $current_title = true; $school_name = 'Shermer High School'; $current_school = true; $country_code = 'us'; $postal_code = 12345; $distance = 500; $facets = 'location,industry,network,language,current-company,past-company,school'; $facet = array('us-84', 47, 'F', 'en', 1006, 1028, 2345); $start = 1; $count = 50; $sort = 'distance'; // Set request parameters. $data['format'] = 'json'; $data['keywords'] = $keywords; $data['first-name'] = $first_name; $data['last-name'] = $last_name; $data['company-name'] = $company_name; $data['current-company'] = $current_company; $data['title'] = $title; $data['current-title'] = $current_title; $data['school-name'] = $school_name; $data['current-school'] = $current_school; $data['country-code'] = $country_code; $data['postal-code'] = $postal_code; $data['distance'] = $distance; $data['facets'] = $facets; $data['facet'] = array(); $data['facet'][] = 'location,' . $facet[0]; $data['facet'][] = 'industry,' . $facet[1]; $data['facet'][] = 'network,' . $facet[2]; $data['facet'][] = 'language,' . $facet[3]; $data['facet'][] = 'current-company,' . $facet[4]; $data['facet'][] = 'past-company,' . $facet[5]; $data['facet'][] = 'school,' . $facet[6]; $data['start'] = $start; $data['count'] = $count; $data['sort'] = $sort; $path = '/v1/people-search'; $path .= ':' . $fields; $returnData = new stdClass; $returnData->code = 401; $returnData->body = $this->errorString; $path = $this->oauth->toUrl($path, $data); $this->client->expects($this->once()) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->search( $fields, $keywords, $first_name, $last_name, $company_name, $current_company, $title, $current_title, $school_name, $current_school, $country_code, $postal_code, $distance, $facets, $facet, $start, $count, $sort ); } }
810/joomla-cms
tests/unit/suites/libraries/joomla/linkedin/JLinkedinPeopleTest.php
PHP
gpl-2.0
13,369
<?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_Gdata_Gbase * @subpackage UnitTests * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id $ */ require_once 'Zend/Gdata/Gbase.php'; require_once 'Zend/Gdata/Gbase/Query.php'; require_once 'Zend/Http/Client.php'; /** * @category Zend * @package Zend_Gdata_Gbase * @subpackage UnitTests * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Gdata * @group Zend_Gdata_Gbase */ class Zend_Gdata_Gbase_QueryTest extends PHPUnit_Framework_TestCase { public function setUp() { $this->query = new Zend_Gdata_Gbase_Query(); } public function testKey() { $this->query->setKey('xyz'); $this->assertEquals($this->query->getKey(), 'xyz'); } }
akellehe/Restructuring-the-Edifice
wp-includes/ZendGdata-1.11.11/tests/Zend/Gdata/Gbase/QueryTest.php
PHP
gpl-2.0
1,464
<?php /* Copyright (C) 2014 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2015 Frederic France <frederic.france@free.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * or see http://www.gnu.org/ */ /** * \file htdocs/core/actions_fetchobject.inc.php * \brief Code for actions on fetching object page */ // $action must be defined // $object must be defined (object is loaded in this file with fetch) // $cancel must be defined // $id or $ref must be defined (object is loaded in this file with fetch) if (($id > 0 || (! empty($ref) && ! in_array($action, array('create','createtask')))) && empty($cancel)) { $ret = $object->fetch($id,$ref); if ($ret > 0) { $object->fetch_thirdparty(); $id = $object->id; } else { setEventMessages($object->error, $object->errors, 'errors'); $action=''; } }
atm-robin/dolibarr
htdocs/core/actions_fetchobject.inc.php
PHP
gpl-3.0
1,522
// Inspired from https://github.com/tsi/inlineDisqussions (function () { 'use strict'; var website = openerp.website, qweb = openerp.qweb; website.blog_discussion = openerp.Class.extend({ init: function(options) { var self = this ; self.discus_identifier; var defaults = { position: 'right', post_id: $('#blog_post_name').attr('data-blog-id'), content : false, public_user: false, }; self.settings = $.extend({}, defaults, options); // TODO: bundlify qweb templates website.add_template_file('/website_blog/static/src/xml/website_blog.inline.discussion.xml').then(function () { self.do_render(self); }); }, do_render: function(data) { var self = this; if ($('#discussions_wrapper').length === 0 && self.settings.content.length > 0) { $('<div id="discussions_wrapper"></div>').insertAfter($('#blog_content')); } // Attach a discussion to each paragraph. self.discussions_handler(self.settings.content); // Hide the discussion. $('html').click(function(event) { if($(event.target).parents('#discussions_wrapper, .main-discussion-link-wrp').length === 0) { self.hide_discussion(); } if(!$(event.target).hasClass('discussion-link') && !$(event.target).parents('.popover').length){ if($('.move_discuss').length){ $('[enable_chatter_discuss=True]').removeClass('move_discuss'); $('[enable_chatter_discuss=True]').animate({ 'marginLeft': "+=40%" }); $('#discussions_wrapper').animate({ 'marginLeft': "+=250px" }); } } }); }, prepare_data : function(identifier, comment_count) { var self = this; return openerp.jsonRpc("/blogpost/get_discussion/", 'call', { 'post_id': self.settings.post_id, 'path': identifier, 'count': comment_count, //if true only get length of total comment, display on discussion thread. }) }, prepare_multi_data : function(identifiers, comment_count) { var self = this; return openerp.jsonRpc("/blogpost/get_discussions/", 'call', { 'post_id': self.settings.post_id, 'paths': identifiers, 'count': comment_count, //if true only get length of total comment, display on discussion thread. }) }, discussions_handler: function() { var self = this; var node_by_id = {}; $(self.settings.content).each(function(i) { var node = $(this); var identifier = node.attr('data-chatter-id'); if (identifier) { node_by_id[identifier] = node; } }); self.prepare_multi_data(_.keys(node_by_id), true).then( function (multi_data) { _.forEach(multi_data, function(data) { self.prepare_discuss_link(data.val, data.path, node_by_id[data.path]); }); }); }, prepare_discuss_link : function(data, identifier, node) { var self = this; var cls = data > 0 ? 'discussion-link has-comments' : 'discussion-link'; var a = $('<a class="'+ cls +' css_editable_mode_hidden" />') .attr('data-discus-identifier', identifier) .attr('data-discus-position', self.settings.position) .text(data > 0 ? data : '+') .attr('data-contentwrapper', '.mycontent') .wrap('<div class="discussion" />') .parent() .appendTo('#discussions_wrapper'); a.css({ 'top': node.offset().top, 'left': self.settings.position == 'right' ? node.outerWidth() + node.offset().left: node.offset().left - a.outerWidth() }); // node.attr('data-discus-identifier', identifier) node.mouseover(function() { a.addClass("hovered"); }).mouseout(function() { a.removeClass("hovered"); }); a.delegate('a.discussion-link', "click", function(e) { e.preventDefault(); if(!$('.move_discuss').length){ $('[enable_chatter_discuss=True]').addClass('move_discuss'); $('[enable_chatter_discuss=True]').animate({ 'marginLeft': "-=40%" }); $('#discussions_wrapper').animate({ 'marginLeft': "-=250px" }); } if ($(this).is('.active')) { e.stopPropagation(); self.hide_discussion(); } else { self.get_discussion($(this), function(source) {}); } }); }, get_discussion : function(source, callback) { var self = this; var identifier = source.attr('data-discus-identifier'); self.hide_discussion(); self.discus_identifier = identifier; var elt = $('a[data-discus-identifier="'+identifier+'"]'); elt.append(qweb.render("website.blog_discussion.popover", {'identifier': identifier , 'options': self.settings})); var comment = ''; self.prepare_data(identifier,false).then(function(data){ _.each(data, function(res){ comment += qweb.render("website.blog_discussion.comment", {'res': res}); }); $('.discussion_history').html('<ul class="media-list">'+comment+'</ul>'); self.create_popover(elt, identifier); // Add 'active' class. $('a.discussion-link, a.main-discussion-link').removeClass('active').filter(source).addClass('active'); elt.popover('hide').filter(source).popover('show'); callback(source); }); }, create_popover : function(elt, identifier) { var self = this; elt.popover({ placement:'right', trigger:'manual', html:true, content:function(){ return $($(this).data('contentwrapper')).html(); } }).parent().delegate(self).on('click','button#comment_post',function(e) { e.stopImmediatePropagation(); self.post_discussion(identifier); }); }, validate : function(public_user){ var comment = $(".popover textarea#inline_comment").val(); if (public_user){ var author_name = $('.popover input#author_name').val(); var author_email = $('.popover input#author_email').val(); if(!comment || !author_name || !author_email){ if (!author_name) $('div#author_name').addClass('has-error'); else $('div#author_name').removeClass('has-error'); if (!author_email) $('div#author_email').addClass('has-error'); else $('div#author_email').removeClass('has-error'); if(!comment) $('div#inline_comment').addClass('has-error'); else $('div#inline_comment').removeClass('has-error'); return false } } else if(!comment) { $('div#inline_comment').addClass('has-error'); return false } $("div#inline_comment").removeClass('has-error'); $('div#author_name').removeClass('has-error'); $('div#author_email').removeClass('has-error'); $(".popover textarea#inline_comment").val(''); $('.popover input#author_name').val(''); $('.popover input#author_email').val(''); return [comment, author_name, author_email] }, post_discussion : function(identifier) { var self = this; var val = self.validate(self.settings.public_user) if(!val) return openerp.jsonRpc("/blogpost/post_discussion", 'call', { 'blog_post_id': self.settings.post_id, 'path': self.discus_identifier, 'comment': val[0], 'name' : val[1], 'email': val[2], }).then(function(res){ $(".popover ul.media-list").prepend(qweb.render("website.blog_discussion.comment", {'res': res[0]})) var ele = $('a[data-discus-identifier="'+ self.discus_identifier +'"]'); ele.text(_.isNaN(parseInt(ele.text())) ? 1 : parseInt(ele.text())+1) ele.addClass('has-comments'); }); }, hide_discussion : function() { var self = this; $('a[data-discus-identifier="'+ self.discus_identifier+'"]').popover('destroy'); $('a.discussion-link').removeClass('active'); } }); })();
jjscarafia/odoo
addons/website_blog/static/src/js/website_blog.inline.discussion.js
JavaScript
agpl-3.0
9,713
/* * Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.event.ws.internal.builders.exceptions; public class InvalidExpirationTimeException extends Exception { public InvalidExpirationTimeException(String message) { super(message); } public InvalidExpirationTimeException(String message, Throwable cause) { super(message, cause); } }
madhawa-gunasekara/carbon-commons
components/event/org.wso2.carbon.event.ws/src/main/java/org/wso2/carbon/event/ws/internal/builders/exceptions/InvalidExpirationTimeException.java
Java
apache-2.0
1,026
require "cmd/missing" require "formula" require "keg" require "language/python" require "version" class Volumes def initialize @volumes = get_mounts end def which path vols = get_mounts path # no volume found if vols.empty? return -1 end vol_index = @volumes.index(vols[0]) # volume not found in volume list if vol_index.nil? return -1 end return vol_index end def get_mounts path=nil vols = [] # get the volume of path, if path is nil returns all volumes args = %w[/bin/df -P] args << path if path Utils.popen_read(*args) do |io| io.each_line do |line| case line.chomp # regex matches: /dev/disk0s2 489562928 440803616 48247312 91% / when /^.+\s+[0-9]+\s+[0-9]+\s+[0-9]+\s+[0-9]{1,3}%\s+(.+)/ vols << $1 end end end return vols end end class Checks ############# HELPERS # Finds files in HOMEBREW_PREFIX *and* /usr/local. # Specify paths relative to a prefix eg. "include/foo.h". # Sets @found for your convenience. def find_relative_paths *relative_paths @found = %W[#{HOMEBREW_PREFIX} /usr/local].uniq.inject([]) do |found, prefix| found + relative_paths.map{|f| File.join(prefix, f) }.select{|f| File.exist? f } end end def inject_file_list(list, str) list.inject(str) { |s, f| s << " #{f}\n" } end # Git will always be on PATH because of the wrapper script in # Library/ENV/scm, so we check if there is a *real* # git here to avoid multiple warnings. def git? return @git if instance_variable_defined?(:@git) @git = system "git --version >/dev/null 2>&1" end ############# END HELPERS # Sorry for the lack of an indent here, the diff would have been unreadable. # See https://github.com/Homebrew/homebrew/pull/9986 def check_path_for_trailing_slashes bad_paths = ENV['PATH'].split(File::PATH_SEPARATOR).select { |p| p[-1..-1] == '/' } return if bad_paths.empty? s = <<-EOS.undent Some directories in your path end in a slash. Directories in your path should not end in a slash. This can break other doctor checks. The following directories should be edited: EOS bad_paths.each{|p| s << " #{p}"} s end # Installing MacGPG2 interferes with Homebrew in a big way # https://github.com/GPGTools/MacGPG2 def check_for_macgpg2 return if File.exist? '/usr/local/MacGPG2/share/gnupg/VERSION' suspects = %w{ /Applications/start-gpg-agent.app /Library/Receipts/libiconv1.pkg /usr/local/MacGPG2 } if suspects.any? { |f| File.exist? f } then <<-EOS.undent You may have installed MacGPG2 via the package installer. Several other checks in this script will turn up problems, such as stray dylibs in /usr/local and permissions issues with share and man in /usr/local/. EOS end end def __check_stray_files(dir, pattern, white_list, message) return unless File.directory?(dir) files = Dir.chdir(dir) { Dir[pattern].select { |f| File.file?(f) && !File.symlink?(f) } - Dir.glob(white_list) }.map { |file| File.join(dir, file) } inject_file_list(files, message) unless files.empty? end def check_for_stray_dylibs # Dylibs which are generally OK should be added to this list, # with a short description of the software they come with. white_list = [ "libfuse.2.dylib", # MacFuse "libfuse_ino64.2.dylib", # MacFuse "libmacfuse_i32.2.dylib", # OSXFuse MacFuse compatibility layer "libmacfuse_i64.2.dylib", # OSXFuse MacFuse compatibility layer "libosxfuse_i32.2.dylib", # OSXFuse "libosxfuse_i64.2.dylib", # OSXFuse "libTrAPI.dylib", # TrAPI / Endpoint Security VPN "libntfs-3g.*.dylib", # NTFS-3G "libntfs.*.dylib", # NTFS-3G "libublio.*.dylib", # NTFS-3G ] __check_stray_files "/usr/local/lib", "*.dylib", white_list, <<-EOS.undent Unbrewed dylibs were found in /usr/local/lib. If you didn't put them there on purpose they could cause problems when building Homebrew formulae, and may need to be deleted. Unexpected dylibs: EOS end def check_for_stray_static_libs # Static libs which are generally OK should be added to this list, # with a short description of the software they come with. white_list = [ "libsecurity_agent_client.a", # OS X 10.8.2 Supplemental Update "libsecurity_agent_server.a", # OS X 10.8.2 Supplemental Update "libntfs-3g.a", # NTFS-3G "libntfs.a", # NTFS-3G "libublio.a", # NTFS-3G ] __check_stray_files "/usr/local/lib", "*.a", white_list, <<-EOS.undent Unbrewed static libraries were found in /usr/local/lib. If you didn't put them there on purpose they could cause problems when building Homebrew formulae, and may need to be deleted. Unexpected static libraries: EOS end def check_for_stray_pcs # Package-config files which are generally OK should be added to this list, # with a short description of the software they come with. white_list = [ "fuse.pc", # OSXFuse/MacFuse "macfuse.pc", # OSXFuse MacFuse compatibility layer "osxfuse.pc", # OSXFuse "libntfs-3g.pc", # NTFS-3G "libublio.pc",# NTFS-3G ] __check_stray_files "/usr/local/lib/pkgconfig", "*.pc", white_list, <<-EOS.undent Unbrewed .pc files were found in /usr/local/lib/pkgconfig. If you didn't put them there on purpose they could cause problems when building Homebrew formulae, and may need to be deleted. Unexpected .pc files: EOS end def check_for_stray_las white_list = [ "libfuse.la", # MacFuse "libfuse_ino64.la", # MacFuse "libosxfuse_i32.la", # OSXFuse "libosxfuse_i64.la", # OSXFuse "libntfs-3g.la", # NTFS-3G "libntfs.la", # NTFS-3G "libublio.la", # NTFS-3G ] __check_stray_files "/usr/local/lib", "*.la", white_list, <<-EOS.undent Unbrewed .la files were found in /usr/local/lib. If you didn't put them there on purpose they could cause problems when building Homebrew formulae, and may need to be deleted. Unexpected .la files: EOS end def check_for_stray_headers white_list = [ "fuse.h", # MacFuse "fuse/**/*.h", # MacFuse "macfuse/**/*.h", # OSXFuse MacFuse compatibility layer "osxfuse/**/*.h", # OSXFuse "ntfs/**/*.h", # NTFS-3G "ntfs-3g/**/*.h", # NTFS-3G ] __check_stray_files "/usr/local/include", "**/*.h", white_list, <<-EOS.undent Unbrewed header files were found in /usr/local/include. If you didn't put them there on purpose they could cause problems when building Homebrew formulae, and may need to be deleted. Unexpected header files: EOS end def check_for_other_package_managers ponk = MacOS.macports_or_fink unless ponk.empty? <<-EOS.undent You have MacPorts or Fink installed: #{ponk.join(", ")} This can cause trouble. You don't have to uninstall them, but you may want to temporarily move them out of the way, e.g. sudo mv /opt/local ~/macports EOS end end def check_for_broken_symlinks broken_symlinks = [] Keg::PRUNEABLE_DIRECTORIES.select(&:directory?).each do |d| d.find do |path| if path.symlink? && !path.resolved_path_exists? broken_symlinks << path end end end unless broken_symlinks.empty? then <<-EOS.undent Broken symlinks were found. Remove them with `brew prune`: #{broken_symlinks * "\n "} EOS end end def check_for_unsupported_osx if MacOS.version >= "10.11" then <<-EOS.undent You are using OS X #{MacOS.version}. We do not provide support for this pre-release version. You may encounter build failures or other breakage. EOS end end if MacOS.version >= "10.9" def check_for_installed_developer_tools unless MacOS::Xcode.installed? || MacOS::CLT.installed? then <<-EOS.undent No developer tools installed. Install the Command Line Tools: xcode-select --install EOS end end def check_xcode_up_to_date if MacOS::Xcode.installed? && MacOS::Xcode.outdated? <<-EOS.undent Your Xcode (#{MacOS::Xcode.version}) is outdated Please update to Xcode #{MacOS::Xcode.latest_version}. Xcode can be updated from the App Store. EOS end end def check_clt_up_to_date if MacOS::CLT.installed? && MacOS::CLT.outdated? then <<-EOS.undent A newer Command Line Tools release is available. Update them from Software Update in the App Store. EOS end end elsif MacOS.version == "10.8" || MacOS.version == "10.7" def check_for_installed_developer_tools unless MacOS::Xcode.installed? || MacOS::CLT.installed? then <<-EOS.undent No developer tools installed. You should install the Command Line Tools. The standalone package can be obtained from https://developer.apple.com/downloads or it can be installed via Xcode's preferences. EOS end end def check_xcode_up_to_date if MacOS::Xcode.installed? && MacOS::Xcode.outdated? then <<-EOS.undent Your Xcode (#{MacOS::Xcode.version}) is outdated Please update to Xcode #{MacOS::Xcode.latest_version}. Xcode can be updated from https://developer.apple.com/downloads EOS end end def check_clt_up_to_date if MacOS::CLT.installed? && MacOS::CLT.outdated? then <<-EOS.undent A newer Command Line Tools release is available. The standalone package can be obtained from https://developer.apple.com/downloads or it can be installed via Xcode's preferences. EOS end end else def check_for_installed_developer_tools unless MacOS::Xcode.installed? then <<-EOS.undent Xcode is not installed. Most formulae need Xcode to build. It can be installed from https://developer.apple.com/downloads EOS end end def check_xcode_up_to_date if MacOS::Xcode.installed? && MacOS::Xcode.outdated? then <<-EOS.undent Your Xcode (#{MacOS::Xcode.version}) is outdated Please update to Xcode #{MacOS::Xcode.latest_version}. Xcode can be updated from https://developer.apple.com/downloads EOS end end end def check_for_osx_gcc_installer if (MacOS.version < "10.7" || MacOS::Xcode.version > "4.1") && \ MacOS.clang_version == "2.1" message = <<-EOS.undent You seem to have osx-gcc-installer installed. Homebrew doesn't support osx-gcc-installer. It causes many builds to fail and is an unlicensed distribution of really old Xcode files. EOS if MacOS.version >= :mavericks message += <<-EOS.undent Please run `xcode-select --install` to install the CLT. EOS elsif MacOS.version >= :lion message += <<-EOS.undent Please install the CLT or Xcode #{MacOS::Xcode.latest_version}. EOS else message += <<-EOS.undent Please install Xcode #{MacOS::Xcode.latest_version}. EOS end end end def check_for_stray_developer_directory # if the uninstaller script isn't there, it's a good guess neither are # any troublesome leftover Xcode files uninstaller = Pathname.new("/Developer/Library/uninstall-developer-folder") if MacOS::Xcode.version >= "4.3" && uninstaller.exist? then <<-EOS.undent You have leftover files from an older version of Xcode. You should delete them using: #{uninstaller} EOS end end def check_for_bad_install_name_tool return if MacOS.version < "10.9" libs = Pathname.new("/usr/bin/install_name_tool").dynamically_linked_libraries # otool may not work, for example if the Xcode license hasn't been accepted yet return if libs.empty? unless libs.include? "/usr/lib/libxcselect.dylib" then <<-EOS.undent You have an outdated version of /usr/bin/install_name_tool installed. This will cause binary package installations to fail. This can happen if you install osx-gcc-installer or RailsInstaller. To restore it, you must reinstall OS X or restore the binary from the OS packages. EOS end end def __check_subdir_access base target = HOMEBREW_PREFIX+base return unless target.exist? cant_read = [] target.find do |d| next unless d.directory? cant_read << d unless d.writable_real? end cant_read.sort! if cant_read.length > 0 then s = <<-EOS.undent Some directories in #{target} aren't writable. This can happen if you "sudo make install" software that isn't managed by Homebrew. If a brew tries to add locale information to one of these directories, then the install will fail during the link step. You should probably `chown` them: EOS cant_read.each{ |f| s << " #{f}\n" } s end end def check_access_share_locale __check_subdir_access 'share/locale' end def check_access_share_man __check_subdir_access 'share/man' end def check_access_usr_local return unless HOMEBREW_PREFIX.to_s == '/usr/local' unless File.writable_real?("/usr/local") then <<-EOS.undent The /usr/local directory is not writable. Even if this directory was writable when you installed Homebrew, other software may change permissions on this directory. Some versions of the "InstantOn" component of Airfoil are known to do this. You should probably change the ownership and permissions of /usr/local back to your user account. EOS end end def check_tmpdir_sticky_bit world_writable = HOMEBREW_TEMP.stat.mode & 0777 == 0777 if world_writable && !HOMEBREW_TEMP.sticky? then <<-EOS.undent #{HOMEBREW_TEMP} is world-writable but does not have the sticky bit set. Please run "Repair Disk Permissions" in Disk Utility. EOS end end (Keg::TOP_LEVEL_DIRECTORIES + ["lib/pkgconfig"]).each do |d| define_method("check_access_#{d.sub("/", "_")}") do dir = HOMEBREW_PREFIX.join(d) if dir.exist? && !dir.writable_real? then <<-EOS.undent #{dir} isn't writable. This can happen if you "sudo make install" software that isn't managed by by Homebrew. If a formula tries to write a file to this directory, the install will fail during the link step. You should probably `chown` #{dir} EOS end end end def check_access_site_packages if Language::Python.homebrew_site_packages.exist? && !Language::Python.homebrew_site_packages.writable_real? <<-EOS.undent #{Language::Python.homebrew_site_packages} isn't writable. This can happen if you "sudo pip install" software that isn't managed by Homebrew. If you install a formula with Python modules, the install will fail during the link step. You should probably `chown` #{Language::Python.homebrew_site_packages} EOS end end def check_access_logs if HOMEBREW_LOGS.exist? and not HOMEBREW_LOGS.writable_real? <<-EOS.undent #{HOMEBREW_LOGS} isn't writable. Homebrew writes debugging logs to this location. You should probably `chown` #{HOMEBREW_LOGS} EOS end end def check_access_cache if HOMEBREW_CACHE.exist? && !HOMEBREW_CACHE.writable_real? <<-EOS.undent #{HOMEBREW_CACHE} isn't writable. This can happen if you run `brew install` or `brew fetch` as another user. Homebrew caches downloaded files to this location. You should probably `chown` #{HOMEBREW_CACHE} EOS end end def check_access_cellar if HOMEBREW_CELLAR.exist? && !HOMEBREW_CELLAR.writable_real? <<-EOS.undent #{HOMEBREW_CELLAR} isn't writable. You should `chown` #{HOMEBREW_CELLAR} EOS end end def check_access_prefix_opt opt = HOMEBREW_PREFIX.join("opt") if opt.exist? && !opt.writable_real? <<-EOS.undent #{opt} isn't writable. You should `chown` #{opt} EOS end end def check_ruby_version ruby_version = MacOS.version >= "10.9" ? "2.0" : "1.8" if RUBY_VERSION[/\d\.\d/] != ruby_version then <<-EOS.undent Ruby version #{RUBY_VERSION} is unsupported on #{MacOS.version}. Homebrew is developed and tested on Ruby #{ruby_version}, and may not work correctly on other Rubies. Patches are accepted as long as they don't cause breakage on supported Rubies. EOS end end def check_homebrew_prefix unless HOMEBREW_PREFIX.to_s == '/usr/local' <<-EOS.undent Your Homebrew is not installed to /usr/local You can install Homebrew anywhere you want, but some brews may only build correctly if you install in /usr/local. Sorry! EOS end end def check_xcode_prefix prefix = MacOS::Xcode.prefix return if prefix.nil? if prefix.to_s.match(' ') <<-EOS.undent Xcode is installed to a directory with a space in the name. This will cause some formulae to fail to build. EOS end end def check_xcode_prefix_exists prefix = MacOS::Xcode.prefix return if prefix.nil? unless prefix.exist? <<-EOS.undent The directory Xcode is reportedly installed to doesn't exist: #{prefix} You may need to `xcode-select` the proper path if you have moved Xcode. EOS end end def check_xcode_select_path if not MacOS::CLT.installed? and not File.file? "#{MacOS.active_developer_dir}/usr/bin/xcodebuild" path = MacOS::Xcode.bundle_path path = '/Developer' if path.nil? or not path.directory? <<-EOS.undent Your Xcode is configured with an invalid path. You should change it to the correct path: sudo xcode-select -switch #{path} EOS end end def check_user_path_1 $seen_prefix_bin = false $seen_prefix_sbin = false out = nil paths.each do |p| case p when '/usr/bin' unless $seen_prefix_bin # only show the doctor message if there are any conflicts # rationale: a default install should not trigger any brew doctor messages conflicts = Dir["#{HOMEBREW_PREFIX}/bin/*"]. map{ |fn| File.basename fn }. select{ |bn| File.exist? "/usr/bin/#{bn}" } if conflicts.size > 0 out = <<-EOS.undent /usr/bin occurs before #{HOMEBREW_PREFIX}/bin This means that system-provided programs will be used instead of those provided by Homebrew. The following tools exist at both paths: #{conflicts * "\n "} Consider setting your PATH so that #{HOMEBREW_PREFIX}/bin occurs before /usr/bin. Here is a one-liner: echo 'export PATH="#{HOMEBREW_PREFIX}/bin:$PATH"' >> #{shell_profile} EOS end end when "#{HOMEBREW_PREFIX}/bin" $seen_prefix_bin = true when "#{HOMEBREW_PREFIX}/sbin" $seen_prefix_sbin = true end end out end def check_user_path_2 unless $seen_prefix_bin <<-EOS.undent Homebrew's bin was not found in your PATH. Consider setting the PATH for example like so echo 'export PATH="#{HOMEBREW_PREFIX}/bin:$PATH"' >> #{shell_profile} EOS end end def check_user_path_3 # Don't complain about sbin not being in the path if it doesn't exist sbin = (HOMEBREW_PREFIX+'sbin') if sbin.directory? and sbin.children.length > 0 unless $seen_prefix_sbin <<-EOS.undent Homebrew's sbin was not found in your PATH but you have installed formulae that put executables in #{HOMEBREW_PREFIX}/sbin. Consider setting the PATH for example like so echo 'export PATH="#{HOMEBREW_PREFIX}/sbin:$PATH"' >> #{shell_profile} EOS end end end def check_user_curlrc if %w[CURL_HOME HOME].any?{|key| ENV[key] and File.exist? "#{ENV[key]}/.curlrc" } then <<-EOS.undent You have a curlrc file If you have trouble downloading packages with Homebrew, then maybe this is the problem? If the following command doesn't work, then try removing your curlrc: curl http://github.com EOS end end def check_which_pkg_config binary = which 'pkg-config' return if binary.nil? mono_config = Pathname.new("/usr/bin/pkg-config") if mono_config.exist? && mono_config.realpath.to_s.include?("Mono.framework") then <<-EOS.undent You have a non-Homebrew 'pkg-config' in your PATH: /usr/bin/pkg-config => #{mono_config.realpath} This was most likely created by the Mono installer. `./configure` may have problems finding brew-installed packages using this other pkg-config. Mono no longer installs this file as of 3.0.4. You should `sudo rm /usr/bin/pkg-config` and upgrade to the latest version of Mono. EOS elsif binary.to_s != "#{HOMEBREW_PREFIX}/bin/pkg-config" then <<-EOS.undent You have a non-Homebrew 'pkg-config' in your PATH: #{binary} `./configure` may have problems finding brew-installed packages using this other pkg-config. EOS end end def check_for_gettext find_relative_paths("lib/libgettextlib.dylib", "lib/libintl.dylib", "include/libintl.h") return if @found.empty? # Our gettext formula will be caught by check_linked_keg_only_brews f = Formulary.factory("gettext") rescue nil return if f and f.linked_keg.directory? and @found.all? do |path| Pathname.new(path).realpath.to_s.start_with? "#{HOMEBREW_CELLAR}/gettext" end s = <<-EOS.undent_________________________________________________________72 gettext files detected at a system prefix These files can cause compilation and link failures, especially if they are compiled with improper architectures. Consider removing these files: EOS inject_file_list(@found, s) end def check_for_iconv unless find_relative_paths("lib/libiconv.dylib", "include/iconv.h").empty? if (f = Formulary.factory("libiconv") rescue nil) and f.linked_keg.directory? if not f.keg_only? then <<-EOS.undent A libiconv formula is installed and linked This will break stuff. For serious. Unlink it. EOS else # NOOP because: check_for_linked_keg_only_brews end else s = <<-EOS.undent_________________________________________________________72 libiconv files detected at a system prefix other than /usr Homebrew doesn't provide a libiconv formula, and expects to link against the system version in /usr. libiconv in other prefixes can cause compile or link failure, especially if compiled with improper architectures. OS X itself never installs anything to /usr/local so it was either installed by a user or some other third party software. tl;dr: delete these files: EOS inject_file_list(@found, s) end end end def check_for_config_scripts return unless HOMEBREW_CELLAR.exist? real_cellar = HOMEBREW_CELLAR.realpath scripts = [] whitelist = %W[ /usr/bin /usr/sbin /usr/X11/bin /usr/X11R6/bin /opt/X11/bin #{HOMEBREW_PREFIX}/bin #{HOMEBREW_PREFIX}/sbin /Applications/Server.app/Contents/ServerRoot/usr/bin /Applications/Server.app/Contents/ServerRoot/usr/sbin ].map(&:downcase) paths.each do |p| next if whitelist.include?(p.downcase) || !File.directory?(p) realpath = Pathname.new(p).realpath.to_s next if realpath.start_with?(real_cellar.to_s, HOMEBREW_CELLAR.to_s) scripts += Dir.chdir(p) { Dir["*-config"] }.map { |c| File.join(p, c) } end unless scripts.empty? s = <<-EOS.undent "config" scripts exist outside your system or Homebrew directories. `./configure` scripts often look for *-config scripts to determine if software packages are installed, and what additional flags to use when compiling and linking. Having additional scripts in your path can confuse software installed via Homebrew if the config script overrides a system or Homebrew provided script of the same name. We found the following "config" scripts: EOS s << scripts.map { |f| " #{f}" }.join("\n") end end def check_DYLD_vars found = ENV.keys.grep(/^DYLD_/) unless found.empty? s = <<-EOS.undent Setting DYLD_* vars can break dynamic linking. Set variables: EOS s << found.map { |e| " #{e}: #{ENV.fetch(e)}\n" }.join if found.include? 'DYLD_INSERT_LIBRARIES' s += <<-EOS.undent Setting DYLD_INSERT_LIBRARIES can cause Go builds to fail. Having this set is common if you use this software: http://asepsis.binaryage.com/ EOS end s end end def check_for_symlinked_cellar return unless HOMEBREW_CELLAR.exist? if HOMEBREW_CELLAR.symlink? <<-EOS.undent Symlinked Cellars can cause problems. Your Homebrew Cellar is a symlink: #{HOMEBREW_CELLAR} which resolves to: #{HOMEBREW_CELLAR.realpath} The recommended Homebrew installations are either: (A) Have Cellar be a real directory inside of your HOMEBREW_PREFIX (B) Symlink "bin/brew" into your prefix, but don't symlink "Cellar". Older installations of Homebrew may have created a symlinked Cellar, but this can cause problems when two formula install to locations that are mapped on top of each other during the linking step. EOS end end def check_for_multiple_volumes return unless HOMEBREW_CELLAR.exist? volumes = Volumes.new # Find the volumes for the TMP folder & HOMEBREW_CELLAR real_cellar = HOMEBREW_CELLAR.realpath tmp = Pathname.new(Dir.mktmpdir("doctor", HOMEBREW_TEMP)) real_temp = tmp.realpath.parent where_cellar = volumes.which real_cellar where_temp = volumes.which real_temp Dir.delete tmp unless where_cellar == where_temp then <<-EOS.undent Your Cellar and TEMP directories are on different volumes. OS X won't move relative symlinks across volumes unless the target file already exists. Brews known to be affected by this are Git and Narwhal. You should set the "HOMEBREW_TEMP" environmental variable to a suitable directory on the same volume as your Cellar. EOS end end def check_filesystem_case_sensitive volumes = Volumes.new case_sensitive_vols = [HOMEBREW_PREFIX, HOMEBREW_REPOSITORY, HOMEBREW_CELLAR, HOMEBREW_TEMP].select do |dir| # We select the dir as being case-sensitive if either the UPCASED or the # downcased variant is missing. # Of course, on a case-insensitive fs, both exist because the os reports so. # In the rare situation when the user has indeed a downcased and an upcased # dir (e.g. /TMP and /tmp) this check falsely thinks it is case-insensitive # but we don't care beacuse: 1. there is more than one dir checked, 2. the # check is not vital and 3. we would have to touch files otherwise. upcased = Pathname.new(dir.to_s.upcase) downcased = Pathname.new(dir.to_s.downcase) dir.exist? && !(upcased.exist? && downcased.exist?) end.map { |case_sensitive_dir| volumes.get_mounts(case_sensitive_dir) }.uniq return if case_sensitive_vols.empty? <<-EOS.undent The filesystem on #{case_sensitive_vols.join(",")} appears to be case-sensitive. The default OS X filesystem is case-insensitive. Please report any apparent problems. EOS end def __check_git_version # https://help.github.com/articles/https-cloning-errors `git --version`.chomp =~ /git version ((?:\d+\.?)+)/ if $1 and Version.new($1) < Version.new("1.7.10") then <<-EOS.undent An outdated version of Git was detected in your PATH. Git 1.7.10 or newer is required to perform checkouts over HTTPS from GitHub. Please upgrade: brew upgrade git EOS end end def check_for_git if git? __check_git_version else <<-EOS.undent Git could not be found in your PATH. Homebrew uses Git for several internal functions, and some formulae use Git checkouts instead of stable tarballs. You may want to install Git: brew install git EOS end end def check_git_newline_settings return unless git? autocrlf = `git config --get core.autocrlf`.chomp if autocrlf == 'true' then <<-EOS.undent Suspicious Git newline settings found. The detected Git newline settings will cause checkout problems: core.autocrlf = #{autocrlf} If you are not routinely dealing with Windows-based projects, consider removing these by running: `git config --global core.autocrlf input` EOS end end def check_git_origin return unless git? && (HOMEBREW_REPOSITORY/'.git').exist? HOMEBREW_REPOSITORY.cd do origin = `git config --get remote.origin.url`.strip if origin.empty? then <<-EOS.undent Missing git origin remote. Without a correctly configured origin, Homebrew won't update properly. You can solve this by adding the Homebrew remote: cd #{HOMEBREW_REPOSITORY} git remote add origin https://github.com/Homebrew/homebrew.git EOS elsif origin !~ /(mxcl|Homebrew)\/homebrew(\.git)?$/ then <<-EOS.undent Suspicious git origin remote found. With a non-standard origin, Homebrew won't pull updates from the main repository. The current git origin is: #{origin} Unless you have compelling reasons, consider setting the origin remote to point at the main repository, located at: https://github.com/Homebrew/homebrew.git EOS end end end def check_for_autoconf return unless MacOS::Xcode.provides_autotools? autoconf = which('autoconf') safe_autoconfs = %w[/usr/bin/autoconf /Developer/usr/bin/autoconf] unless autoconf.nil? or safe_autoconfs.include? autoconf.to_s then <<-EOS.undent An "autoconf" in your path blocks the Xcode-provided version at: #{autoconf} This custom autoconf may cause some Homebrew formulae to fail to compile. EOS end end def __check_linked_brew f f.rack.subdirs.each do |prefix| prefix.find do |src| next if src == prefix dst = HOMEBREW_PREFIX + src.relative_path_from(prefix) return true if dst.symlink? && src == dst.resolved_path end end false end def check_for_linked_keg_only_brews return unless HOMEBREW_CELLAR.exist? linked = Formula.installed.select { |f| f.keg_only? && __check_linked_brew(f) } unless linked.empty? s = <<-EOS.undent Some keg-only formula are linked into the Cellar. Linking a keg-only formula, such as gettext, into the cellar with `brew link <formula>` will cause other formulae to detect them during the `./configure` step. This may cause problems when compiling those other formulae. Binaries provided by keg-only formulae may override system binaries with other strange results. You may wish to `brew unlink` these brews: EOS linked.each { |f| s << " #{f.full_name}\n" } s end end def check_for_other_frameworks # Other frameworks that are known to cause problems when present %w{expat.framework libexpat.framework libcurl.framework}. map{ |frmwrk| "/Library/Frameworks/#{frmwrk}" }. select{ |frmwrk| File.exist? frmwrk }. map do |frmwrk| <<-EOS.undent #{frmwrk} detected This can be picked up by CMake's build system and likely cause the build to fail. You may need to move this file out of the way to compile CMake. EOS end.join end def check_tmpdir tmpdir = ENV['TMPDIR'] "TMPDIR #{tmpdir.inspect} doesn't exist." unless tmpdir.nil? or File.directory? tmpdir end def check_missing_deps return unless HOMEBREW_CELLAR.exist? missing = Set.new Homebrew.missing_deps(Formula.installed).each_value do |deps| missing.merge(deps) end if missing.any? then <<-EOS.undent Some installed formula are missing dependencies. You should `brew install` the missing dependencies: brew install #{missing.sort_by(&:full_name) * " "} Run `brew missing` for more details. EOS end end def check_git_status return unless git? HOMEBREW_REPOSITORY.cd do unless `git status --untracked-files=all --porcelain -- Library/Homebrew/ 2>/dev/null`.chomp.empty? <<-EOS.undent_________________________________________________________72 You have uncommitted modifications to Homebrew If this a surprise to you, then you should stash these modifications. Stashing returns Homebrew to a pristine state but can be undone should you later need to do so for some reason. cd #{HOMEBREW_LIBRARY} && git stash && git clean -d -f EOS end end end def check_for_enthought_python if which "enpkg" then <<-EOS.undent Enthought Python was found in your PATH. This can cause build problems, as this software installs its own copies of iconv and libxml2 into directories that are picked up by other build systems. EOS end end def check_for_library_python if File.exist?("/Library/Frameworks/Python.framework") then <<-EOS.undent Python is installed at /Library/Frameworks/Python.framework Homebrew only supports building against the System-provided Python or a brewed Python. In particular, Pythons installed to /Library can interfere with other software installs. EOS end end def check_for_old_homebrew_share_python_in_path s = '' ['', '3'].map do |suffix| if paths.include?((HOMEBREW_PREFIX/"share/python#{suffix}").to_s) s += "#{HOMEBREW_PREFIX}/share/python#{suffix} is not needed in PATH.\n" end end unless s.empty? s += <<-EOS.undent Formerly homebrew put Python scripts you installed via `pip` or `pip3` (or `easy_install`) into that directory above but now it can be removed from your PATH variable. Python scripts will now install into #{HOMEBREW_PREFIX}/bin. You can delete anything, except 'Extras', from the #{HOMEBREW_PREFIX}/share/python (and #{HOMEBREW_PREFIX}/share/python3) dir and install affected Python packages anew with `pip install --upgrade`. EOS end end def check_for_bad_python_symlink return unless which "python" `python -V 2>&1` =~ /Python (\d+)\./ # This won't be the right warning if we matched nothing at all return if $1.nil? unless $1 == "2" then <<-EOS.undent python is symlinked to python#$1 This will confuse build scripts and in general lead to subtle breakage. EOS end end def check_for_non_prefixed_coreutils gnubin = "#{Formulary.factory('coreutils').prefix}/libexec/gnubin" if paths.include? gnubin then <<-EOS.undent Putting non-prefixed coreutils in your path can cause gmp builds to fail. EOS end end def check_for_non_prefixed_findutils default_names = Tab.for_name('findutils').with? "default-names" if default_names then <<-EOS.undent Putting non-prefixed findutils in your path can cause python builds to fail. EOS end end def check_for_pydistutils_cfg_in_home if File.exist? "#{ENV['HOME']}/.pydistutils.cfg" then <<-EOS.undent A .pydistutils.cfg file was found in $HOME, which may cause Python builds to fail. See: https://bugs.python.org/issue6138 https://bugs.python.org/issue4655 EOS end end def check_for_outdated_homebrew return unless git? HOMEBREW_REPOSITORY.cd do if File.directory? ".git" local = `git rev-parse -q --verify refs/remotes/origin/master`.chomp remote = /^([a-f0-9]{40})/.match(`git ls-remote origin refs/heads/master 2>/dev/null`) if remote.nil? || local == remote[0] return end end timestamp = if File.directory? ".git" `git log -1 --format="%ct" HEAD`.to_i else HOMEBREW_LIBRARY.mtime.to_i end if Time.now.to_i - timestamp > 60 * 60 * 24 then <<-EOS.undent Your Homebrew is outdated. You haven't updated for at least 24 hours. This is a long time in brewland! To update Homebrew, run `brew update`. EOS end end end def check_for_unlinked_but_not_keg_only return unless HOMEBREW_CELLAR.exist? unlinked = HOMEBREW_CELLAR.children.reject do |rack| if not rack.directory? true elsif not (HOMEBREW_REPOSITORY/"Library/LinkedKegs"/rack.basename).directory? begin Formulary.from_rack(rack).keg_only? rescue FormulaUnavailableError, TapFormulaAmbiguityError false end else true end end.map{ |pn| pn.basename } if not unlinked.empty? then <<-EOS.undent You have unlinked kegs in your Cellar Leaving kegs unlinked can lead to build-trouble and cause brews that depend on those kegs to fail to run properly once built. Run `brew link` on these: #{unlinked * "\n "} EOS end end def check_xcode_license_approved # If the user installs Xcode-only, they have to approve the # license or no "xc*" tool will work. if `/usr/bin/xcrun clang 2>&1` =~ /license/ and not $?.success? then <<-EOS.undent You have not agreed to the Xcode license. Builds will fail! Agree to the license by opening Xcode.app or running: sudo xcodebuild -license EOS end end def check_for_latest_xquartz return unless MacOS::XQuartz.version return if MacOS::XQuartz.provided_by_apple? installed_version = Version.new(MacOS::XQuartz.version) latest_version = Version.new(MacOS::XQuartz.latest_version) return if installed_version >= latest_version <<-EOS.undent Your XQuartz (#{installed_version}) is outdated Please install XQuartz #{latest_version}: https://xquartz.macosforge.org EOS end def check_for_old_env_vars if ENV["HOMEBREW_KEEP_INFO"] <<-EOS.undent `HOMEBREW_KEEP_INFO` is no longer used info files are no longer deleted by default; you may remove this environment variable. EOS end end def check_for_pth_support homebrew_site_packages = Language::Python.homebrew_site_packages return unless homebrew_site_packages.directory? return if Language::Python.reads_brewed_pth_files?("python") != false return unless Language::Python.in_sys_path?("python", homebrew_site_packages) user_site_packages = Language::Python.user_site_packages "python" <<-EOS.undent Your default Python does not recognize the Homebrew site-packages directory as a special site-packages directory, which means that .pth files will not be followed. This means you will not be able to import some modules after installing them with Homebrew, like wxpython. To fix this for the current user, you can run: mkdir -p #{user_site_packages} echo 'import site; site.addsitedir("#{homebrew_site_packages}")' >> #{user_site_packages}/homebrew.pth EOS end def check_for_external_cmd_name_conflict cmds = paths.map { |p| Dir["#{p}/brew-*"] }.flatten.uniq cmds = cmds.select { |cmd| File.file?(cmd) && File.executable?(cmd) } cmd_map = {} cmds.each do |cmd| cmd_name = File.basename(cmd, ".rb") cmd_map[cmd_name] ||= [] cmd_map[cmd_name] << cmd end cmd_map.reject! { |cmd_name, cmd_paths| cmd_paths.size == 1 } return if cmd_map.empty? s = "You have external commands with conflicting names." cmd_map.each do |cmd_name, cmd_paths| s += "\n\nFound command `#{cmd_name}` in following places:\n" s += cmd_paths.map { |f| " #{f}" }.join("\n") end s end def all methods.map(&:to_s).grep(/^check_/) end end # end class Checks module Homebrew def doctor checks = Checks.new if ARGV.include? '--list-checks' puts checks.all.sort exit end inject_dump_stats(checks) if ARGV.switch? 'D' if ARGV.named.empty? methods = checks.all.sort methods << "check_for_linked_keg_only_brews" << "check_for_outdated_homebrew" methods = methods.reverse.uniq.reverse else methods = ARGV.named end first_warning = true methods.each do |method| begin out = checks.send(method) rescue NoMethodError Homebrew.failed = true puts "No check available by the name: #{method}" next end unless out.nil? or out.empty? if first_warning puts <<-EOS.undent #{Tty.white}Please note that these warnings are just used to help the Homebrew maintainers with debugging if you file an issue. If everything you use Homebrew for is working fine: please don't worry and just ignore them. Thanks!#{Tty.reset} EOS end puts opoo out Homebrew.failed = true first_warning = false end end puts "Your system is ready to brew." unless Homebrew.failed? end def inject_dump_stats checks checks.extend Module.new { def send(method, *) time = Time.now super ensure $times[method] = Time.now - time end } $times = {} at_exit { puts $times.sort_by{|k, v| v }.map{|k, v| "#{k}: #{v}"} } end end
wolfd/homebrew
Library/Homebrew/cmd/doctor.rb
Ruby
bsd-2-clause
40,730
require 'formula' class Sratom < Formula homepage 'http://drobilla.net/software/sratom/' url 'http://download.drobilla.net/sratom-0.4.6.tar.bz2' sha1 '5f7d18e4917e5a2fee6eedc6ae06aa72d47fa52a' bottle do cellar :any sha256 "9023b8427d0e4068c7ca9e9a66a18545c51af3e30fcf9566db74aacceff18d2b" => :yosemite sha256 "9720a29b9fc95760edc5d96a36d89fee9a44403e0ce1cbe76fbf4a805c8c9571" => :mavericks sha256 "4b2acde2a46119ac0d6ae10a0d161b5f644e507296f44defc036ab311d93cf27" => :mountain_lion end depends_on 'pkg-config' => :build depends_on 'lv2' depends_on 'serd' depends_on 'sord' def install system "./waf", "configure", "--prefix=#{prefix}" system "./waf" system "./waf", "install" end end
robrix/homebrew
Library/Formula/sratom.rb
Ruby
bsd-2-clause
738
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/corewm/window_animations.h" #include <math.h> #include <algorithm> #include <vector> #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/message_loop/message_loop.h" #include "base/stl_util.h" #include "base/time/time.h" #include "ui/aura/client/animation_host.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/aura/window_delegate.h" #include "ui/aura/window_observer.h" #include "ui/aura/window_property.h" #include "ui/compositor/compositor_observer.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_animation_observer.h" #include "ui/compositor/layer_animation_sequence.h" #include "ui/compositor/layer_animator.h" #include "ui/compositor/scoped_layer_animation_settings.h" #include "ui/gfx/interpolated_transform.h" #include "ui/gfx/rect_conversions.h" #include "ui/gfx/screen.h" #include "ui/gfx/vector2d.h" #include "ui/gfx/vector3d_f.h" #include "ui/views/corewm/corewm_switches.h" #include "ui/views/corewm/window_util.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" DECLARE_WINDOW_PROPERTY_TYPE(int) DECLARE_WINDOW_PROPERTY_TYPE(views::corewm::WindowVisibilityAnimationType) DECLARE_WINDOW_PROPERTY_TYPE(views::corewm::WindowVisibilityAnimationTransition) DECLARE_WINDOW_PROPERTY_TYPE(float) DECLARE_EXPORTED_WINDOW_PROPERTY_TYPE(VIEWS_EXPORT, bool) using aura::Window; using base::TimeDelta; using ui::Layer; namespace views { namespace corewm { namespace { const float kWindowAnimation_Vertical_TranslateY = 15.f; } // namespace DEFINE_WINDOW_PROPERTY_KEY(int, kWindowVisibilityAnimationTypeKey, WINDOW_VISIBILITY_ANIMATION_TYPE_DEFAULT); DEFINE_WINDOW_PROPERTY_KEY(int, kWindowVisibilityAnimationDurationKey, 0); DEFINE_WINDOW_PROPERTY_KEY(WindowVisibilityAnimationTransition, kWindowVisibilityAnimationTransitionKey, ANIMATE_BOTH); DEFINE_WINDOW_PROPERTY_KEY(float, kWindowVisibilityAnimationVerticalPositionKey, kWindowAnimation_Vertical_TranslateY); namespace { const int kDefaultAnimationDurationForMenuMS = 150; const float kWindowAnimation_HideOpacity = 0.f; const float kWindowAnimation_ShowOpacity = 1.f; const float kWindowAnimation_TranslateFactor = 0.5f; const float kWindowAnimation_ScaleFactor = .95f; const int kWindowAnimation_Rotate_DurationMS = 180; const int kWindowAnimation_Rotate_OpacityDurationPercent = 90; const float kWindowAnimation_Rotate_TranslateY = -20.f; const float kWindowAnimation_Rotate_PerspectiveDepth = 500.f; const float kWindowAnimation_Rotate_DegreesX = 5.f; const float kWindowAnimation_Rotate_ScaleFactor = .99f; const float kWindowAnimation_Bounce_Scale = 1.02f; const int kWindowAnimation_Bounce_DurationMS = 180; const int kWindowAnimation_Bounce_GrowShrinkDurationPercent = 40; base::TimeDelta GetWindowVisibilityAnimationDuration(aura::Window* window) { int duration = window->GetProperty(kWindowVisibilityAnimationDurationKey); if (duration == 0 && window->type() == aura::client::WINDOW_TYPE_MENU) { return base::TimeDelta::FromMilliseconds( kDefaultAnimationDurationForMenuMS); } return TimeDelta::FromInternalValue(duration); } // Gets/sets the WindowVisibilityAnimationType associated with a window. // TODO(beng): redundant/fold into method on public api? int GetWindowVisibilityAnimationType(aura::Window* window) { int type = window->GetProperty(kWindowVisibilityAnimationTypeKey); if (type == WINDOW_VISIBILITY_ANIMATION_TYPE_DEFAULT) { return (window->type() == aura::client::WINDOW_TYPE_MENU || window->type() == aura::client::WINDOW_TYPE_TOOLTIP) ? WINDOW_VISIBILITY_ANIMATION_TYPE_FADE : WINDOW_VISIBILITY_ANIMATION_TYPE_DROP; } return type; } // Observes a hide animation. // A window can be hidden for a variety of reasons. Sometimes, Hide() will be // called and life is simple. Sometimes, the window is actually bound to a // views::Widget and that Widget is closed, and life is a little more // complicated. When a Widget is closed the aura::Window* is actually not // destroyed immediately - it is actually just immediately hidden and then // destroyed when the stack unwinds. To handle this case, we start the hide // animation immediately when the window is hidden, then when the window is // subsequently destroyed this object acquires ownership of the window's layer, // so that it can continue animating it until the animation completes. // Regardless of whether or not the window is destroyed, this object deletes // itself when the animation completes. class HidingWindowAnimationObserver : public ui::ImplicitAnimationObserver, public aura::WindowObserver { public: explicit HidingWindowAnimationObserver(aura::Window* window) : window_(window) { window_->AddObserver(this); } virtual ~HidingWindowAnimationObserver() { STLDeleteElements(&layers_); } private: // Overridden from ui::ImplicitAnimationObserver: virtual void OnImplicitAnimationsCompleted() OVERRIDE { // Window may have been destroyed by this point. if (window_) { aura::client::AnimationHost* animation_host = aura::client::GetAnimationHost(window_); if (animation_host) animation_host->OnWindowHidingAnimationCompleted(); window_->RemoveObserver(this); } delete this; } // Overridden from aura::WindowObserver: virtual void OnWindowDestroying(aura::Window* window) OVERRIDE { DCHECK_EQ(window, window_); DCHECK(layers_.empty()); AcquireAllLayers(window_); // If the Widget has views with layers, then it is necessary to take // ownership of those layers too. views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window_); const views::Widget* const_widget = widget; if (widget && const_widget->GetRootView() && widget->GetContentsView()) AcquireAllViewLayers(widget->GetContentsView()); window_->RemoveObserver(this); window_ = NULL; } void AcquireAllLayers(aura::Window* window) { ui::Layer* layer = window->AcquireLayer(); DCHECK(layer); layers_.push_back(layer); for (aura::Window::Windows::const_iterator it = window->children().begin(); it != window->children().end(); ++it) AcquireAllLayers(*it); } void AcquireAllViewLayers(views::View* view) { for (int i = 0; i < view->child_count(); ++i) AcquireAllViewLayers(view->child_at(i)); if (view->layer()) { ui::Layer* layer = view->RecreateLayer(); if (layer) { layer->SuppressPaint(); layers_.push_back(layer); } } } aura::Window* window_; std::vector<ui::Layer*> layers_; DISALLOW_COPY_AND_ASSIGN(HidingWindowAnimationObserver); }; void GetTransformRelativeToRoot(ui::Layer* layer, gfx::Transform* transform) { const Layer* root = layer; while (root->parent()) root = root->parent(); layer->GetTargetTransformRelativeTo(root, transform); } gfx::Rect GetLayerWorldBoundsAfterTransform(ui::Layer* layer, const gfx::Transform& transform) { gfx::Transform in_world = transform; GetTransformRelativeToRoot(layer, &in_world); gfx::RectF transformed = layer->bounds(); in_world.TransformRect(&transformed); return gfx::ToEnclosingRect(transformed); } // Augment the host window so that the enclosing bounds of the full // animation will fit inside of it. void AugmentWindowSize(aura::Window* window, const gfx::Transform& end_transform) { aura::client::AnimationHost* animation_host = aura::client::GetAnimationHost(window); if (!animation_host) return; const gfx::Rect& world_at_start = window->bounds(); gfx::Rect world_at_end = GetLayerWorldBoundsAfterTransform(window->layer(), end_transform); gfx::Rect union_in_window_space = gfx::UnionRects(world_at_start, world_at_end); // Calculate the top left and bottom right deltas to be added to the window // bounds. gfx::Vector2d top_left_delta(world_at_start.x() - union_in_window_space.x(), world_at_start.y() - union_in_window_space.y()); gfx::Vector2d bottom_right_delta( union_in_window_space.x() + union_in_window_space.width() - (world_at_start.x() + world_at_start.width()), union_in_window_space.y() + union_in_window_space.height() - (world_at_start.y() + world_at_start.height())); DCHECK(top_left_delta.x() >= 0 && top_left_delta.y() >= 0 && bottom_right_delta.x() >= 0 && bottom_right_delta.y() >= 0); animation_host->SetHostTransitionOffsets(top_left_delta, bottom_right_delta); } // Shows a window using an animation, animating its opacity from 0.f to 1.f, // its visibility to true, and its transform from |start_transform| to // |end_transform|. void AnimateShowWindowCommon(aura::Window* window, const gfx::Transform& start_transform, const gfx::Transform& end_transform) { window->layer()->set_delegate(window); AugmentWindowSize(window, end_transform); window->layer()->SetOpacity(kWindowAnimation_HideOpacity); window->layer()->SetTransform(start_transform); window->layer()->SetVisible(true); { // Property sets within this scope will be implicitly animated. ui::ScopedLayerAnimationSettings settings(window->layer()->GetAnimator()); base::TimeDelta duration = GetWindowVisibilityAnimationDuration(window); if (duration.ToInternalValue() > 0) settings.SetTransitionDuration(duration); window->layer()->SetTransform(end_transform); window->layer()->SetOpacity(kWindowAnimation_ShowOpacity); } } // Hides a window using an animation, animating its opacity from 1.f to 0.f, // its visibility to false, and its transform to |end_transform|. void AnimateHideWindowCommon(aura::Window* window, const gfx::Transform& end_transform) { AugmentWindowSize(window, end_transform); window->layer()->set_delegate(NULL); // Property sets within this scope will be implicitly animated. ui::ScopedLayerAnimationSettings settings(window->layer()->GetAnimator()); settings.AddObserver(new HidingWindowAnimationObserver(window)); base::TimeDelta duration = GetWindowVisibilityAnimationDuration(window); if (duration.ToInternalValue() > 0) settings.SetTransitionDuration(duration); window->layer()->SetOpacity(kWindowAnimation_HideOpacity); window->layer()->SetTransform(end_transform); window->layer()->SetVisible(false); } static gfx::Transform GetScaleForWindow(aura::Window* window) { gfx::Rect bounds = window->bounds(); gfx::Transform scale = gfx::GetScaleTransform( gfx::Point(kWindowAnimation_TranslateFactor * bounds.width(), kWindowAnimation_TranslateFactor * bounds.height()), kWindowAnimation_ScaleFactor); return scale; } // Show/Hide windows using a shrink animation. void AnimateShowWindow_Drop(aura::Window* window) { AnimateShowWindowCommon(window, GetScaleForWindow(window), gfx::Transform()); } void AnimateHideWindow_Drop(aura::Window* window) { AnimateHideWindowCommon(window, GetScaleForWindow(window)); } // Show/Hide windows using a vertical Glenimation. void AnimateShowWindow_Vertical(aura::Window* window) { gfx::Transform transform; transform.Translate(0, window->GetProperty( kWindowVisibilityAnimationVerticalPositionKey)); AnimateShowWindowCommon(window, transform, gfx::Transform()); } void AnimateHideWindow_Vertical(aura::Window* window) { gfx::Transform transform; transform.Translate(0, window->GetProperty( kWindowVisibilityAnimationVerticalPositionKey)); AnimateHideWindowCommon(window, transform); } // Show/Hide windows using a fade. void AnimateShowWindow_Fade(aura::Window* window) { AnimateShowWindowCommon(window, gfx::Transform(), gfx::Transform()); } void AnimateHideWindow_Fade(aura::Window* window) { AnimateHideWindowCommon(window, gfx::Transform()); } ui::LayerAnimationElement* CreateGrowShrinkElement( aura::Window* window, bool grow) { scoped_ptr<ui::InterpolatedTransform> scale(new ui::InterpolatedScale( gfx::Point3F(kWindowAnimation_Bounce_Scale, kWindowAnimation_Bounce_Scale, 1), gfx::Point3F(1, 1, 1))); scoped_ptr<ui::InterpolatedTransform> scale_about_pivot( new ui::InterpolatedTransformAboutPivot( gfx::Point(window->bounds().width() * 0.5, window->bounds().height() * 0.5), scale.release())); scale_about_pivot->SetReversed(grow); scoped_ptr<ui::LayerAnimationElement> transition( ui::LayerAnimationElement::CreateInterpolatedTransformElement( scale_about_pivot.release(), base::TimeDelta::FromMilliseconds( kWindowAnimation_Bounce_DurationMS * kWindowAnimation_Bounce_GrowShrinkDurationPercent / 100))); transition->set_tween_type(grow ? gfx::Tween::EASE_OUT : gfx::Tween::EASE_IN); return transition.release(); } void AnimateBounce(aura::Window* window) { ui::ScopedLayerAnimationSettings scoped_settings( window->layer()->GetAnimator()); scoped_settings.SetPreemptionStrategy( ui::LayerAnimator::REPLACE_QUEUED_ANIMATIONS); window->layer()->set_delegate(window); scoped_ptr<ui::LayerAnimationSequence> sequence( new ui::LayerAnimationSequence); sequence->AddElement(CreateGrowShrinkElement(window, true)); ui::LayerAnimationElement::AnimatableProperties paused_properties; paused_properties.insert(ui::LayerAnimationElement::BOUNDS); sequence->AddElement(ui::LayerAnimationElement::CreatePauseElement( paused_properties, base::TimeDelta::FromMilliseconds( kWindowAnimation_Bounce_DurationMS * (100 - 2 * kWindowAnimation_Bounce_GrowShrinkDurationPercent) / 100))); sequence->AddElement(CreateGrowShrinkElement(window, false)); window->layer()->GetAnimator()->StartAnimation(sequence.release()); } void AddLayerAnimationsForRotate(aura::Window* window, bool show) { window->layer()->set_delegate(window); if (show) window->layer()->SetOpacity(kWindowAnimation_HideOpacity); base::TimeDelta duration = base::TimeDelta::FromMilliseconds( kWindowAnimation_Rotate_DurationMS); if (!show) { new HidingWindowAnimationObserver(window); window->layer()->GetAnimator()->SchedulePauseForProperties( duration * (100 - kWindowAnimation_Rotate_OpacityDurationPercent) / 100, ui::LayerAnimationElement::OPACITY, -1); } scoped_ptr<ui::LayerAnimationElement> opacity( ui::LayerAnimationElement::CreateOpacityElement( show ? kWindowAnimation_ShowOpacity : kWindowAnimation_HideOpacity, duration * kWindowAnimation_Rotate_OpacityDurationPercent / 100)); opacity->set_tween_type(gfx::Tween::EASE_IN_OUT); window->layer()->GetAnimator()->ScheduleAnimation( new ui::LayerAnimationSequence(opacity.release())); float xcenter = window->bounds().width() * 0.5; gfx::Transform transform; transform.Translate(xcenter, 0); transform.ApplyPerspectiveDepth(kWindowAnimation_Rotate_PerspectiveDepth); transform.Translate(-xcenter, 0); scoped_ptr<ui::InterpolatedTransform> perspective( new ui::InterpolatedConstantTransform(transform)); scoped_ptr<ui::InterpolatedTransform> scale( new ui::InterpolatedScale(1, kWindowAnimation_Rotate_ScaleFactor)); scoped_ptr<ui::InterpolatedTransform> scale_about_pivot( new ui::InterpolatedTransformAboutPivot( gfx::Point(xcenter, kWindowAnimation_Rotate_TranslateY), scale.release())); scoped_ptr<ui::InterpolatedTransform> translation( new ui::InterpolatedTranslation(gfx::Point(), gfx::Point( 0, kWindowAnimation_Rotate_TranslateY))); scoped_ptr<ui::InterpolatedTransform> rotation( new ui::InterpolatedAxisAngleRotation( gfx::Vector3dF(1, 0, 0), 0, kWindowAnimation_Rotate_DegreesX)); scale_about_pivot->SetChild(perspective.release()); translation->SetChild(scale_about_pivot.release()); rotation->SetChild(translation.release()); rotation->SetReversed(show); scoped_ptr<ui::LayerAnimationElement> transition( ui::LayerAnimationElement::CreateInterpolatedTransformElement( rotation.release(), duration)); window->layer()->GetAnimator()->ScheduleAnimation( new ui::LayerAnimationSequence(transition.release())); } void AnimateShowWindow_Rotate(aura::Window* window) { AddLayerAnimationsForRotate(window, true); } void AnimateHideWindow_Rotate(aura::Window* window) { AddLayerAnimationsForRotate(window, false); } bool AnimateShowWindow(aura::Window* window) { if (!HasWindowVisibilityAnimationTransition(window, ANIMATE_SHOW)) { if (HasWindowVisibilityAnimationTransition(window, ANIMATE_HIDE)) { // Since hide animation may have changed opacity and transform, // reset them to show the window. window->layer()->set_delegate(window); window->layer()->SetOpacity(kWindowAnimation_ShowOpacity); window->layer()->SetTransform(gfx::Transform()); } return false; } switch (GetWindowVisibilityAnimationType(window)) { case WINDOW_VISIBILITY_ANIMATION_TYPE_DROP: AnimateShowWindow_Drop(window); return true; case WINDOW_VISIBILITY_ANIMATION_TYPE_VERTICAL: AnimateShowWindow_Vertical(window); return true; case WINDOW_VISIBILITY_ANIMATION_TYPE_FADE: AnimateShowWindow_Fade(window); return true; case WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE: AnimateShowWindow_Rotate(window); return true; default: return false; } } bool AnimateHideWindow(aura::Window* window) { if (!HasWindowVisibilityAnimationTransition(window, ANIMATE_HIDE)) { if (HasWindowVisibilityAnimationTransition(window, ANIMATE_SHOW)) { // Since show animation may have changed opacity and transform, // reset them, though the change should be hidden. window->layer()->set_delegate(NULL); window->layer()->SetOpacity(kWindowAnimation_HideOpacity); window->layer()->SetTransform(gfx::Transform()); } return false; } switch (GetWindowVisibilityAnimationType(window)) { case WINDOW_VISIBILITY_ANIMATION_TYPE_DROP: AnimateHideWindow_Drop(window); return true; case WINDOW_VISIBILITY_ANIMATION_TYPE_VERTICAL: AnimateHideWindow_Vertical(window); return true; case WINDOW_VISIBILITY_ANIMATION_TYPE_FADE: AnimateHideWindow_Fade(window); return true; case WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE: AnimateHideWindow_Rotate(window); return true; default: return false; } } } // namespace //////////////////////////////////////////////////////////////////////////////// // External interface void SetWindowVisibilityAnimationType(aura::Window* window, int type) { window->SetProperty(kWindowVisibilityAnimationTypeKey, type); } int GetWindowVisibilityAnimationType(aura::Window* window) { return window->GetProperty(kWindowVisibilityAnimationTypeKey); } void SetWindowVisibilityAnimationTransition( aura::Window* window, WindowVisibilityAnimationTransition transition) { window->SetProperty(kWindowVisibilityAnimationTransitionKey, transition); } bool HasWindowVisibilityAnimationTransition( aura::Window* window, WindowVisibilityAnimationTransition transition) { WindowVisibilityAnimationTransition prop = window->GetProperty( kWindowVisibilityAnimationTransitionKey); return (prop & transition) != 0; } void SetWindowVisibilityAnimationDuration(aura::Window* window, const TimeDelta& duration) { window->SetProperty(kWindowVisibilityAnimationDurationKey, static_cast<int>(duration.ToInternalValue())); } void SetWindowVisibilityAnimationVerticalPosition(aura::Window* window, float position) { window->SetProperty(kWindowVisibilityAnimationVerticalPositionKey, position); } ui::ImplicitAnimationObserver* CreateHidingWindowAnimationObserver( aura::Window* window) { return new HidingWindowAnimationObserver(window); } bool AnimateOnChildWindowVisibilityChanged(aura::Window* window, bool visible) { if (WindowAnimationsDisabled(window)) return false; if (visible) return AnimateShowWindow(window); // Don't start hiding the window again if it's already being hidden. return window->layer()->GetTargetOpacity() != 0.0f && AnimateHideWindow(window); } bool AnimateWindow(aura::Window* window, WindowAnimationType type) { switch (type) { case WINDOW_ANIMATION_TYPE_BOUNCE: AnimateBounce(window); return true; default: NOTREACHED(); return false; } } bool WindowAnimationsDisabled(aura::Window* window) { return (window && window->GetProperty(aura::client::kAnimationsDisabledKey)) || CommandLine::ForCurrentProcess()->HasSwitch( switches::kWindowAnimationsDisabled); } } // namespace corewm } // namespace views
DirtyUnicorns/android_external_chromium-org
ui/views/corewm/window_animations.cc
C++
bsd-3-clause
21,476
/* @flow */ function a(x: {[key: string]: ?string}, y: string): string { if (x[y]) { return x[y]; } return ""; } function b(x: {y: {[key: string]: ?string}}, z: string): string { if (x.y[z]) { return x.y[z]; } return ""; } function c(x: {[key: string]: ?string}, y: {z: string}): string { if (x[y.z]) { return x[y.z]; } return ""; } function d(x: {y: {[key: string]: ?string}}, a: {b: string}): string { if (x.y[a.b]) { return x.y[a.b]; } return ""; } function a_array(x: Array<?string>, y: number): string { if (x[y]) { return x[y]; } return ""; } function b_array(x: {y: Array<?string>}, z: number): string { if (x.y[z]) { return x.y[z]; } return ""; } function c_array(x: Array<?string>, y: {z: number}): string { if (x[y.z]) { return x[y.z]; } return ""; } function d_array(x: {y: Array<?string>}, a: {b: number}): string { if (x.y[a.b]) { return x.y[a.b]; } return ""; } // --- name-sensitive havoc --- function c2(x: {[key: string]: ?string}, y: {z: string}): string { if (x[y.z]) { y.z = "HEY"; return x[y.z]; // error } return ""; } function c3(x: {[key: string]: ?string}, y: {z: string, a: string}): string { if (x[y.z]) { y.a = "HEY"; return x[y.z]; // ok } return ""; }
JohnyDays/flow
tests/refinements/property.js
JavaScript
bsd-3-clause
1,303
// Copyright 2012-2015 Oliver Eilhard. All rights reserved. // Use of this source code is governed by a MIT-license. // See http://olivere.mit-license.org/license.txt for details. package elastic import ( "encoding/json" "fmt" "log" "net/url" "strings" "github.com/olivere/elastic/uritemplates" ) var ( _ = fmt.Print _ = log.Print _ = strings.Index _ = uritemplates.Expand _ = url.Parse ) // PutMappingService allows to register specific mapping definition // for a specific type. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-put-mapping.html. type PutMappingService struct { client *Client pretty bool typ string index []string masterTimeout string ignoreUnavailable *bool allowNoIndices *bool expandWildcards string ignoreConflicts *bool timeout string bodyJson map[string]interface{} bodyString string } // NewPutMappingService creates a new PutMappingService. func NewPutMappingService(client *Client) *PutMappingService { return &PutMappingService{ client: client, index: make([]string, 0), } } // Index is a list of index names the mapping should be added to // (supports wildcards); use `_all` or omit to add the mapping on all indices. func (s *PutMappingService) Index(index ...string) *PutMappingService { s.index = append(s.index, index...) return s } // Type is the name of the document type. func (s *PutMappingService) Type(typ string) *PutMappingService { s.typ = typ return s } // Timeout is an explicit operation timeout. func (s *PutMappingService) Timeout(timeout string) *PutMappingService { s.timeout = timeout return s } // MasterTimeout specifies the timeout for connection to master. func (s *PutMappingService) MasterTimeout(masterTimeout string) *PutMappingService { s.masterTimeout = masterTimeout return s } // IgnoreUnavailable indicates whether specified concrete indices should be // ignored when unavailable (missing or closed). func (s *PutMappingService) IgnoreUnavailable(ignoreUnavailable bool) *PutMappingService { s.ignoreUnavailable = &ignoreUnavailable return s } // AllowNoIndices indicates whether to ignore if a wildcard indices // expression resolves into no concrete indices. // This includes `_all` string or when no indices have been specified. func (s *PutMappingService) AllowNoIndices(allowNoIndices bool) *PutMappingService { s.allowNoIndices = &allowNoIndices return s } // ExpandWildcards indicates whether to expand wildcard expression to // concrete indices that are open, closed or both. func (s *PutMappingService) ExpandWildcards(expandWildcards string) *PutMappingService { s.expandWildcards = expandWildcards return s } // IgnoreConflicts specifies whether to ignore conflicts while updating // the mapping (default: false). func (s *PutMappingService) IgnoreConflicts(ignoreConflicts bool) *PutMappingService { s.ignoreConflicts = &ignoreConflicts return s } // Pretty indicates that the JSON response be indented and human readable. func (s *PutMappingService) Pretty(pretty bool) *PutMappingService { s.pretty = pretty return s } // BodyJson contains the mapping definition. func (s *PutMappingService) BodyJson(mapping map[string]interface{}) *PutMappingService { s.bodyJson = mapping return s } // BodyString is the mapping definition serialized as a string. func (s *PutMappingService) BodyString(mapping string) *PutMappingService { s.bodyString = mapping return s } // buildURL builds the URL for the operation. func (s *PutMappingService) buildURL() (string, url.Values, error) { var err error var path string // Build URL: Typ MUST be specified and is verified in Validate. if len(s.index) > 0 { path, err = uritemplates.Expand("/{index}/_mapping/{type}", map[string]string{ "index": strings.Join(s.index, ","), "type": s.typ, }) } else { path, err = uritemplates.Expand("/_mapping/{type}", map[string]string{ "type": s.typ, }) } if err != nil { return "", url.Values{}, err } // Add query string parameters params := url.Values{} if s.pretty { params.Set("pretty", "1") } if s.ignoreUnavailable != nil { params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable)) } if s.allowNoIndices != nil { params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices)) } if s.expandWildcards != "" { params.Set("expand_wildcards", s.expandWildcards) } if s.ignoreConflicts != nil { params.Set("ignore_conflicts", fmt.Sprintf("%v", *s.ignoreConflicts)) } if s.timeout != "" { params.Set("timeout", s.timeout) } if s.masterTimeout != "" { params.Set("master_timeout", s.masterTimeout) } return path, params, nil } // Validate checks if the operation is valid. func (s *PutMappingService) Validate() error { var invalid []string if s.typ == "" { invalid = append(invalid, "Type") } if s.bodyString == "" && s.bodyJson == nil { invalid = append(invalid, "BodyJson") } if len(invalid) > 0 { return fmt.Errorf("missing required fields: %v", invalid) } return nil } // Do executes the operation. func (s *PutMappingService) Do() (*PutMappingResponse, error) { // Check pre-conditions if err := s.Validate(); err != nil { return nil, err } // Get URL for request path, params, err := s.buildURL() if err != nil { return nil, err } // Setup HTTP request body var body interface{} if s.bodyJson != nil { body = s.bodyJson } else { body = s.bodyString } // Get HTTP response res, err := s.client.PerformRequest("PUT", path, params, body) if err != nil { return nil, err } // Return operation response ret := new(PutMappingResponse) if err := json.Unmarshal(res.Body, ret); err != nil { return nil, err } return ret, nil } // PutMappingResponse is the response of PutMappingService.Do. type PutMappingResponse struct { Acknowledged bool `json:"acknowledged"` }
seekingalpha/bosun
vendor/github.com/olivere/elastic/put_mapping.go
GO
mit
5,940
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using UICore; namespace SlimTuneUI.CoreVis { [DisplayName("Hotspots")] public partial class HotSpots : UserControl, IVisualizer { ProfilerWindowBase m_mainWindow; Connection m_connection; Snapshot m_snapshot; //drawing stuff Font m_functionFont = new Font(SystemFonts.DefaultFont.FontFamily, 12, FontStyle.Bold); Font m_objectFont = new Font(SystemFonts.DefaultFont.FontFamily, 9, FontStyle.Regular); class ListTag { public ListBox Right; public double TotalTime; } public event EventHandler Refreshed; public string DisplayName { get { return "Hotspots"; } } public UserControl Control { get { return this; } } public Snapshot Snapshot { get { return m_snapshot; } } public bool SupportsRefresh { get { return true; } } public HotSpots() { InitializeComponent(); HotspotsList.Tag = new ListTag(); } public bool Initialize(ProfilerWindowBase mainWindow, Connection connection, Snapshot snapshot) { if(mainWindow == null) throw new ArgumentNullException("mainWindow"); if(connection == null) throw new ArgumentNullException("connection"); m_mainWindow = mainWindow; m_connection = connection; m_snapshot = snapshot; UpdateHotspots(); return true; } public void OnClose() { } public void RefreshView() { var rightTag = HotspotsList.Tag as ListTag; if(rightTag != null) RemoveList(rightTag.Right); UpdateHotspots(); Utilities.FireEvent(this, Refreshed); } private void UpdateHotspots() { HotspotsList.Items.Clear(); using(var session = m_connection.DataEngine.OpenSession(m_snapshot.Id)) using(var tx = session.BeginTransaction()) { //find the total time consumed var totalQuery = session.CreateQuery("select sum(call.Time) from Call call where call.ChildId = 0"); var totalTimeFuture = totalQuery.FutureValue<double>(); //find the functions that consumed the most time-exclusive. These are hotspots. var query = session.CreateQuery("from Call c inner join fetch c.Parent where c.ChildId = 0 order by c.Time desc"); query.SetMaxResults(20); var hotspots = query.Future<Call>(); var totalTime = totalTimeFuture.Value; (HotspotsList.Tag as ListTag).TotalTime = totalTime; foreach(var call in hotspots) { if(call.Time / totalTime < 0.01f) { //less than 1% is not a hotspot, and since we're ordered by Time we can exit break; } HotspotsList.Items.Add(call); } tx.Commit(); } } private bool UpdateParents(Call child, ListBox box) { using(var session = m_connection.DataEngine.OpenSession(m_snapshot.Id)) using(var tx = session.BeginTransaction()) { var query = session.CreateQuery("from Call c inner join fetch c.Parent where c.ChildId = :funcId order by c.Time desc") .SetInt32("funcId", child.Parent.Id); var parents = query.List<Call>(); double totalTime = 0; foreach(var call in parents) { if(call.ParentId == 0) return false; totalTime += call.Time; box.Items.Add(call); } (box.Tag as ListTag).TotalTime = totalTime; tx.Commit(); } return true; } private void RefreshTimer_Tick(object sender, EventArgs e) { //UpdateHotspots(); } private void RemoveList(ListBox list) { if(list == null) return; RemoveList((list.Tag as ListTag).Right); ScrollPanel.Controls.Remove(list); } private void CallList_SelectedIndexChanged(object sender, EventArgs e) { ListBox list = sender as ListBox; RemoveList((list.Tag as ListTag).Right); //create a new listbox to the right ListBox lb = new ListBox(); lb.Size = list.Size; lb.Location = new Point(list.Right + 4, 4); lb.IntegralHeight = false; lb.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left; lb.FormattingEnabled = true; lb.DrawMode = DrawMode.OwnerDrawFixed; lb.ItemHeight = HotspotsList.ItemHeight; lb.Tag = new ListTag(); lb.Format += new ListControlConvertEventHandler(CallList_Format); lb.SelectedIndexChanged += new EventHandler(CallList_SelectedIndexChanged); lb.DrawItem += new DrawItemEventHandler(CallList_DrawItem); if(UpdateParents(list.SelectedItem as Call, lb)) { ScrollPanel.Controls.Add(lb); ScrollPanel.ScrollControlIntoView(lb); (list.Tag as ListTag).Right = lb; } } private void CallList_Format(object sender, ListControlConvertEventArgs e) { Call call = e.ListItem as Call; e.Value = call.Parent.Name; } private void CallList_DrawItem(object sender, DrawItemEventArgs e) { ListBox list = sender as ListBox; Call item = list.Items[e.Index] as Call; int splitIndex = item.Parent.Name.LastIndexOf('.'); string functionName = item.Parent.Name.Substring(splitIndex + 1); string objectName = "- " + item.Parent.Name.Substring(0, splitIndex); double percent = 100 * item.Time / (list.Tag as ListTag).TotalTime; string functionString = string.Format("{0:0.##}%: {1}", percent, functionName); Brush brush = Brushes.Black; if((e.State & DrawItemState.Selected) == DrawItemState.Selected) brush = Brushes.White; e.DrawBackground(); e.Graphics.DrawString(functionString, m_functionFont, brush, new PointF(e.Bounds.X, e.Bounds.Y)); e.Graphics.DrawString(objectName, m_objectFont, brush, new PointF(e.Bounds.X + 4, e.Bounds.Y + 18)); e.DrawFocusRectangle(); } } }
mohdmasd/slimtune
CoreVis/HotSpots.cs
C#
mit
5,633
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace spec\Sylius\Bundle\UserBundle\Reloader; use Doctrine\Common\Persistence\ObjectManager; use Sylius\Component\User\Model\UserInterface; use PhpSpec\ObjectBehavior; /** * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com> */ class UserReloaderSpec extends ObjectBehavior { function let(ObjectManager $objectManager) { $this->beConstructedWith($objectManager); } function it_is_initializable() { $this->shouldHaveType('Sylius\Bundle\UserBundle\Reloader\UserReloader'); } function it_implements_user_reloader_interface() { $this->shouldImplement('Sylius\Bundle\UserBundle\Reloader\UserReloaderInterface'); } function it_reloads_user($objectManager, UserInterface $user) { $objectManager->refresh($user)->shouldBeCalled(); $this->reloadUser($user); } }
wwojcik/Sylius
src/Sylius/Bundle/UserBundle/spec/Reloader/UserReloaderSpec.php
PHP
mit
1,079
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * 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. */ /// <reference path="../_references.ts"/> module powerbi.visuals.sampleDataViews { import DataViewTransform = powerbi.data.DataViewTransform; export class SalesByCountryData extends SampleDataViews implements ISampleDataViewsMethods { public name: string = "SalesByCountryData"; public displayName: string = "Sales By Country"; public visuals: string[] = ['default']; private sampleData = [ [742731.43, 162066.43, 283085.78, 300263.49, 376074.57, 814724.34], [123455.43, 40566.43, 200457.78, 5000.49, 320000.57, 450000.34] ]; private sampleMin: number = 30000; private sampleMax: number = 1000000; private sampleSingleData: number = 55943.67; public getDataViews(): DataView[] { var fieldExpr = powerbi.data.SQExprBuilder.fieldDef({ schema: 's', entity: "table1", column: "country" }); var categoryValues = ["Australia", "Canada", "France", "Germany", "United Kingdom", "United States"]; var categoryIdentities = categoryValues.map(function (value) { var expr = powerbi.data.SQExprBuilder.equal(fieldExpr, powerbi.data.SQExprBuilder.text(value)); return powerbi.data.createDataViewScopeIdentity(expr); }); // Metadata, describes the data columns, and provides the visual with hints // so it can decide how to best represent the data var dataViewMetadata: powerbi.DataViewMetadata = { columns: [ { displayName: 'Country', queryName: 'Country', type: powerbi.ValueType.fromDescriptor({ text: true }) }, { displayName: 'Sales Amount (2014)', isMeasure: true, format: "$0,000.00", queryName: 'sales1', type: powerbi.ValueType.fromDescriptor({ numeric: true }), objects: { dataPoint: { fill: { solid: { color: 'purple' } } } }, }, { displayName: 'Sales Amount (2015)', isMeasure: true, format: "$0,000.00", queryName: 'sales2', type: powerbi.ValueType.fromDescriptor({ numeric: true }) } ] }; var columns = [ { source: dataViewMetadata.columns[1], // Sales Amount for 2014 values: this.sampleData[0], }, { source: dataViewMetadata.columns[2], // Sales Amount for 2015 values: this.sampleData[1], } ]; var dataValues: DataViewValueColumns = DataViewTransform.createValueColumns(columns); var tableDataValues = categoryValues.map(function (countryName, idx) { return [countryName, columns[0].values[idx], columns[1].values[idx]]; }); return [{ metadata: dataViewMetadata, categorical: { categories: [{ source: dataViewMetadata.columns[0], values: categoryValues, identity: categoryIdentities, }], values: dataValues }, table: { rows: tableDataValues, columns: dataViewMetadata.columns, }, single: { value: this.sampleSingleData } }]; } public randomize(): void { this.sampleData = this.sampleData.map((item) => { return item.map(() => this.getRandomValue(this.sampleMin, this.sampleMax)); }); this.sampleSingleData = this.getRandomValue(this.sampleMin, this.sampleMax); } } }
yduit/PowerBI-visuals
src/Clients/PowerBIVisualsPlayground/sampleDataViews/SalesByCountryData.ts
TypeScript
mit
5,374
<?php /** * @package Joomla.Site * @subpackage mod_custom * * @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; if ($params->def('prepare_content', 1)) { JPluginHelper::importPlugin('content'); $module->content = JHtml::_('content.prepare', $module->content, '', 'mod_custom.content'); } $moduleclass_sfx = htmlspecialchars($params->get('moduleclass_sfx'), ENT_COMPAT, 'UTF-8'); require JModuleHelper::getLayoutPath('mod_custom', $params->get('layout', 'default'));
810/joomla-cms
modules/mod_custom/mod_custom.php
PHP
gpl-2.0
626
// license:BSD-3-Clause // copyright-holders:Ryan Holtz //============================================================ // // clearreader.cpp - BGFX clear state JSON reader // //============================================================ #include <bgfx/bgfx.h> #include "clearreader.h" #include "clear.h" clear_state* clear_reader::read_from_value(const Value& value, std::string prefix) { if (!validate_parameters(value, prefix)) { return nullptr; } uint64_t clear_flags = 0; uint32_t clear_color = 0; float clear_depth = 1.0f; uint8_t clear_stencil = 0; if (value.HasMember("clearcolor")) { const Value& colors = value["clearcolor"]; for (int i = 0; i < colors.Size(); i++) { if (!READER_CHECK(colors[i].IsNumber(), (prefix + "clearcolor[" + std::to_string(i) + "] must be a numeric value\n").c_str())) return nullptr; auto val = int32_t(float(colors[i].GetDouble()) * 255.0f); if (val > 255) val = 255; if (val < 0) val = 0; clear_color |= val << (24 - (i * 3)); } clear_flags |= BGFX_CLEAR_COLOR; } if (value.HasMember("cleardepth")) { get_float(value, "cleardepth", &clear_depth, &clear_depth); clear_flags |= BGFX_CLEAR_DEPTH; } if (value.HasMember("clearstencil")) { clear_stencil = uint8_t(get_int(value, "clearstencil", clear_stencil)); clear_flags |= BGFX_CLEAR_STENCIL; } return new clear_state(clear_flags, clear_color, clear_depth, clear_stencil); } bool clear_reader::validate_parameters(const Value& value, std::string prefix) { if (!READER_CHECK(!value.HasMember("clearcolor") || (value["clearcolor"].IsArray() && value["clearcolor"].GetArray().Size() == 4), (prefix + "'clearcolor' must be an array of four numeric RGBA values representing the color to which to clear the color buffer\n").c_str())) return false; if (!READER_CHECK(!value.HasMember("cleardepth") || value["cleardepth"].IsNumber(), (prefix + "'cleardepth' must be a numeric value representing the depth to which to clear the depth buffer\n").c_str())) return false; if (!READER_CHECK(!value.HasMember("clearstencil") || value["clearstencil"].IsNumber(), (prefix + "'clearstencil' must be a numeric value representing the stencil value to which to clear the stencil buffer\n").c_str())) return false; return true; }
johnparker007/mame
src/osd/modules/render/bgfx/clearreader.cpp
C++
gpl-2.0
2,264
/* Copyright 2017 The Kubernetes Authors. 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. */ // This file was automatically generated by informer-gen package v1alpha1 import ( internalinterfaces "k8s.io/sample-apiserver/pkg/client/informers/externalversions/internalinterfaces" ) // Interface provides access to all the informers in this group version. type Interface interface { // Fischers returns a FischerInformer. Fischers() FischerInformer // Flunders returns a FlunderInformer. Flunders() FlunderInformer } type version struct { internalinterfaces.SharedInformerFactory } // New returns a new Interface. func New(f internalinterfaces.SharedInformerFactory) Interface { return &version{f} } // Fischers returns a FischerInformer. func (v *version) Fischers() FischerInformer { return &fischerInformer{factory: v.SharedInformerFactory} } // Flunders returns a FlunderInformer. func (v *version) Flunders() FlunderInformer { return &flunderInformer{factory: v.SharedInformerFactory} }
shakamunyi/kubernetes
vendor/k8s.io/sample-apiserver/pkg/client/informers/externalversions/wardle/v1alpha1/interface.go
GO
apache-2.0
1,483